PackageManagerService.java revision d957f80ced65b4151c4fe1fcd9815cc2dcc00c99
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.server.pm.InstructionSets.getAppDexInstructionSets; 58import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 59import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 60import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 61 62import android.util.ArrayMap; 63 64import com.android.internal.R; 65import com.android.internal.app.IMediaContainerService; 66import com.android.internal.app.ResolverActivity; 67import com.android.internal.content.NativeLibraryHelper; 68import com.android.internal.content.PackageHelper; 69import com.android.internal.os.IParcelFileDescriptorFactory; 70import com.android.internal.util.ArrayUtils; 71import com.android.internal.util.FastPrintWriter; 72import com.android.internal.util.FastXmlSerializer; 73import com.android.internal.util.IndentingPrintWriter; 74import com.android.server.EventLogTags; 75import com.android.server.IntentResolver; 76import com.android.server.LocalServices; 77import com.android.server.ServiceThread; 78import com.android.server.SystemConfig; 79import com.android.server.Watchdog; 80import com.android.server.pm.Settings.DatabaseVersion; 81import com.android.server.storage.DeviceStorageMonitorInternal; 82 83import org.xmlpull.v1.XmlSerializer; 84 85import android.app.ActivityManager; 86import android.app.ActivityManagerNative; 87import android.app.AppGlobals; 88import android.app.IActivityManager; 89import android.app.admin.IDevicePolicyManager; 90import android.app.backup.IBackupManager; 91import android.app.usage.UsageStats; 92import android.app.usage.UsageStatsManager; 93import android.content.BroadcastReceiver; 94import android.content.ComponentName; 95import android.content.Context; 96import android.content.IIntentReceiver; 97import android.content.Intent; 98import android.content.IntentFilter; 99import android.content.IntentSender; 100import android.content.IntentSender.SendIntentException; 101import android.content.ServiceConnection; 102import android.content.pm.ActivityInfo; 103import android.content.pm.ApplicationInfo; 104import android.content.pm.FeatureInfo; 105import android.content.pm.IPackageDataObserver; 106import android.content.pm.IPackageDeleteObserver; 107import android.content.pm.IPackageDeleteObserver2; 108import android.content.pm.IPackageInstallObserver2; 109import android.content.pm.IPackageInstaller; 110import android.content.pm.IPackageManager; 111import android.content.pm.IPackageMoveObserver; 112import android.content.pm.IPackageStatsObserver; 113import android.content.pm.InstrumentationInfo; 114import android.content.pm.KeySet; 115import android.content.pm.ManifestDigest; 116import android.content.pm.PackageCleanItem; 117import android.content.pm.PackageInfo; 118import android.content.pm.PackageInfoLite; 119import android.content.pm.PackageInstaller; 120import android.content.pm.PackageManager; 121import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 122import android.content.pm.PackageParser.ActivityIntentInfo; 123import android.content.pm.PackageParser.PackageLite; 124import android.content.pm.PackageParser.PackageParserException; 125import android.content.pm.PackageParser; 126import android.content.pm.PackageStats; 127import android.content.pm.PackageUserState; 128import android.content.pm.ParceledListSlice; 129import android.content.pm.PermissionGroupInfo; 130import android.content.pm.PermissionInfo; 131import android.content.pm.ProviderInfo; 132import android.content.pm.ResolveInfo; 133import android.content.pm.ServiceInfo; 134import android.content.pm.Signature; 135import android.content.pm.UserInfo; 136import android.content.pm.VerificationParams; 137import android.content.pm.VerifierDeviceIdentity; 138import android.content.pm.VerifierInfo; 139import android.content.res.Resources; 140import android.hardware.display.DisplayManager; 141import android.net.Uri; 142import android.os.Binder; 143import android.os.Build; 144import android.os.Bundle; 145import android.os.Environment; 146import android.os.Environment.UserEnvironment; 147import android.os.storage.IMountService; 148import android.os.storage.StorageManager; 149import android.os.Debug; 150import android.os.FileUtils; 151import android.os.Handler; 152import android.os.IBinder; 153import android.os.Looper; 154import android.os.Message; 155import android.os.Parcel; 156import android.os.ParcelFileDescriptor; 157import android.os.Process; 158import android.os.RemoteException; 159import android.os.SELinux; 160import android.os.ServiceManager; 161import android.os.SystemClock; 162import android.os.SystemProperties; 163import android.os.UserHandle; 164import android.os.UserManager; 165import android.security.KeyStore; 166import android.security.SystemKeyStore; 167import android.system.ErrnoException; 168import android.system.Os; 169import android.system.StructStat; 170import android.text.TextUtils; 171import android.text.format.DateUtils; 172import android.util.ArraySet; 173import android.util.AtomicFile; 174import android.util.DisplayMetrics; 175import android.util.EventLog; 176import android.util.ExceptionUtils; 177import android.util.Log; 178import android.util.LogPrinter; 179import android.util.PrintStreamPrinter; 180import android.util.Slog; 181import android.util.SparseArray; 182import android.util.SparseBooleanArray; 183import android.view.Display; 184 185import java.io.BufferedInputStream; 186import java.io.BufferedOutputStream; 187import java.io.BufferedReader; 188import java.io.File; 189import java.io.FileDescriptor; 190import java.io.FileNotFoundException; 191import java.io.FileOutputStream; 192import java.io.FileReader; 193import java.io.FilenameFilter; 194import java.io.IOException; 195import java.io.InputStream; 196import java.io.PrintWriter; 197import java.nio.charset.StandardCharsets; 198import java.security.NoSuchAlgorithmException; 199import java.security.PublicKey; 200import java.security.cert.CertificateEncodingException; 201import java.security.cert.CertificateException; 202import java.text.SimpleDateFormat; 203import java.util.ArrayList; 204import java.util.Arrays; 205import java.util.Collection; 206import java.util.Collections; 207import java.util.Comparator; 208import java.util.Date; 209import java.util.Iterator; 210import java.util.List; 211import java.util.Map; 212import java.util.Objects; 213import java.util.Set; 214import java.util.concurrent.atomic.AtomicBoolean; 215import java.util.concurrent.atomic.AtomicLong; 216 217import dalvik.system.DexFile; 218import dalvik.system.VMRuntime; 219 220import libcore.io.IoUtils; 221import libcore.util.EmptyArray; 222 223/** 224 * Keep track of all those .apks everywhere. 225 * 226 * This is very central to the platform's security; please run the unit 227 * tests whenever making modifications here: 228 * 229mmm frameworks/base/tests/AndroidTests 230adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 231adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 232 * 233 * {@hide} 234 */ 235public class PackageManagerService extends IPackageManager.Stub { 236 static final String TAG = "PackageManager"; 237 static final boolean DEBUG_SETTINGS = false; 238 static final boolean DEBUG_PREFERRED = false; 239 static final boolean DEBUG_UPGRADE = false; 240 private static final boolean DEBUG_INSTALL = false; 241 private static final boolean DEBUG_REMOVE = false; 242 private static final boolean DEBUG_BROADCASTS = false; 243 private static final boolean DEBUG_SHOW_INFO = false; 244 private static final boolean DEBUG_PACKAGE_INFO = false; 245 private static final boolean DEBUG_INTENT_MATCHING = false; 246 private static final boolean DEBUG_PACKAGE_SCANNING = false; 247 private static final boolean DEBUG_VERIFY = false; 248 private static final boolean DEBUG_DEXOPT = false; 249 private static final boolean DEBUG_ABI_SELECTION = false; 250 251 private static final boolean RUNTIME_PERMISSIONS_ENABLED = 252 SystemProperties.getInt("ro.runtime.premissions.enabled", 0) == 1; 253 254 private static final int RADIO_UID = Process.PHONE_UID; 255 private static final int LOG_UID = Process.LOG_UID; 256 private static final int NFC_UID = Process.NFC_UID; 257 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 258 private static final int SHELL_UID = Process.SHELL_UID; 259 260 // Cap the size of permission trees that 3rd party apps can define 261 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 262 263 // Suffix used during package installation when copying/moving 264 // package apks to install directory. 265 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 266 267 static final int SCAN_NO_DEX = 1<<1; 268 static final int SCAN_FORCE_DEX = 1<<2; 269 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 270 static final int SCAN_NEW_INSTALL = 1<<4; 271 static final int SCAN_NO_PATHS = 1<<5; 272 static final int SCAN_UPDATE_TIME = 1<<6; 273 static final int SCAN_DEFER_DEX = 1<<7; 274 static final int SCAN_BOOTING = 1<<8; 275 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 276 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 277 static final int SCAN_REPLACING = 1<<11; 278 279 static final int REMOVE_CHATTY = 1<<16; 280 281 /** 282 * Timeout (in milliseconds) after which the watchdog should declare that 283 * our handler thread is wedged. The usual default for such things is one 284 * minute but we sometimes do very lengthy I/O operations on this thread, 285 * such as installing multi-gigabyte applications, so ours needs to be longer. 286 */ 287 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 288 289 /** 290 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 291 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 292 * settings entry if available, otherwise we use the hardcoded default. If it's been 293 * more than this long since the last fstrim, we force one during the boot sequence. 294 * 295 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 296 * one gets run at the next available charging+idle time. This final mandatory 297 * no-fstrim check kicks in only of the other scheduling criteria is never met. 298 */ 299 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 300 301 /** 302 * Whether verification is enabled by default. 303 */ 304 private static final boolean DEFAULT_VERIFY_ENABLE = true; 305 306 /** 307 * The default maximum time to wait for the verification agent to return in 308 * milliseconds. 309 */ 310 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 311 312 /** 313 * The default response for package verification timeout. 314 * 315 * This can be either PackageManager.VERIFICATION_ALLOW or 316 * PackageManager.VERIFICATION_REJECT. 317 */ 318 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 319 320 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 321 322 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 323 DEFAULT_CONTAINER_PACKAGE, 324 "com.android.defcontainer.DefaultContainerService"); 325 326 private static final String KILL_APP_REASON_GIDS_CHANGED = 327 "permission grant or revoke changed gids"; 328 329 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 330 "permissions revoked"; 331 332 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 333 334 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 335 336 /** Permission grant: not grant the permission. */ 337 private static final int GRANT_DENIED = 1; 338 339 /** Permission grant: grant the permission as an install permission. */ 340 private static final int GRANT_INSTALL = 2; 341 342 /** Permission grant: grant the permission as a runtime permission. */ 343 private static final int GRANT_RUNTIME = 3; 344 345 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 346 private static final int GRANT_UPGRADE = 4; 347 348 final ServiceThread mHandlerThread; 349 350 final PackageHandler mHandler; 351 352 /** 353 * Messages for {@link #mHandler} that need to wait for system ready before 354 * being dispatched. 355 */ 356 private ArrayList<Message> mPostSystemReadyMessages; 357 358 final int mSdkVersion = Build.VERSION.SDK_INT; 359 360 final Context mContext; 361 final boolean mFactoryTest; 362 final boolean mOnlyCore; 363 final boolean mLazyDexOpt; 364 final long mDexOptLRUThresholdInMills; 365 final DisplayMetrics mMetrics; 366 final int mDefParseFlags; 367 final String[] mSeparateProcesses; 368 final boolean mIsUpgrade; 369 370 // This is where all application persistent data goes. 371 final File mAppDataDir; 372 373 // This is where all application persistent data goes for secondary users. 374 final File mUserAppDataDir; 375 376 /** The location for ASEC container files on internal storage. */ 377 final String mAsecInternalPath; 378 379 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 380 // LOCK HELD. Can be called with mInstallLock held. 381 final Installer mInstaller; 382 383 /** Directory where installed third-party apps stored */ 384 final File mAppInstallDir; 385 386 /** 387 * Directory to which applications installed internally have their 388 * 32 bit native libraries copied. 389 */ 390 private File mAppLib32InstallDir; 391 392 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 393 // apps. 394 final File mDrmAppPrivateInstallDir; 395 396 // ---------------------------------------------------------------- 397 398 // Lock for state used when installing and doing other long running 399 // operations. Methods that must be called with this lock held have 400 // the suffix "LI". 401 final Object mInstallLock = new Object(); 402 403 // ---------------------------------------------------------------- 404 405 // Keys are String (package name), values are Package. This also serves 406 // as the lock for the global state. Methods that must be called with 407 // this lock held have the prefix "LP". 408 final ArrayMap<String, PackageParser.Package> mPackages = 409 new ArrayMap<String, PackageParser.Package>(); 410 411 // Tracks available target package names -> overlay package paths. 412 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 413 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 414 415 final Settings mSettings; 416 boolean mRestoredSettings; 417 418 // System configuration read by SystemConfig. 419 final int[] mGlobalGids; 420 final SparseArray<ArraySet<String>> mSystemPermissions; 421 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 422 423 // If mac_permissions.xml was found for seinfo labeling. 424 boolean mFoundPolicyFile; 425 426 // If a recursive restorecon of /data/data/<pkg> is needed. 427 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 428 429 public static final class SharedLibraryEntry { 430 public final String path; 431 public final String apk; 432 433 SharedLibraryEntry(String _path, String _apk) { 434 path = _path; 435 apk = _apk; 436 } 437 } 438 439 // Currently known shared libraries. 440 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 441 new ArrayMap<String, SharedLibraryEntry>(); 442 443 // All available activities, for your resolving pleasure. 444 final ActivityIntentResolver mActivities = 445 new ActivityIntentResolver(); 446 447 // All available receivers, for your resolving pleasure. 448 final ActivityIntentResolver mReceivers = 449 new ActivityIntentResolver(); 450 451 // All available services, for your resolving pleasure. 452 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 453 454 // All available providers, for your resolving pleasure. 455 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 456 457 // Mapping from provider base names (first directory in content URI codePath) 458 // to the provider information. 459 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 460 new ArrayMap<String, PackageParser.Provider>(); 461 462 // Mapping from instrumentation class names to info about them. 463 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 464 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 465 466 // Mapping from permission names to info about them. 467 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 468 new ArrayMap<String, PackageParser.PermissionGroup>(); 469 470 // Packages whose data we have transfered into another package, thus 471 // should no longer exist. 472 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 473 474 // Broadcast actions that are only available to the system. 475 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 476 477 /** List of packages waiting for verification. */ 478 final SparseArray<PackageVerificationState> mPendingVerification 479 = new SparseArray<PackageVerificationState>(); 480 481 /** Set of packages associated with each app op permission. */ 482 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 483 484 final PackageInstallerService mInstallerService; 485 486 private final PackageDexOptimizer mPackageDexOptimizer; 487 // Cache of users who need badging. 488 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 489 490 /** Token for keys in mPendingVerification. */ 491 private int mPendingVerificationToken = 0; 492 493 volatile boolean mSystemReady; 494 volatile boolean mSafeMode; 495 volatile boolean mHasSystemUidErrors; 496 497 ApplicationInfo mAndroidApplication; 498 final ActivityInfo mResolveActivity = new ActivityInfo(); 499 final ResolveInfo mResolveInfo = new ResolveInfo(); 500 ComponentName mResolveComponentName; 501 PackageParser.Package mPlatformPackage; 502 ComponentName mCustomResolverComponentName; 503 504 boolean mResolverReplaced = false; 505 506 // Set of pending broadcasts for aggregating enable/disable of components. 507 static class PendingPackageBroadcasts { 508 // for each user id, a map of <package name -> components within that package> 509 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 510 511 public PendingPackageBroadcasts() { 512 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 513 } 514 515 public ArrayList<String> get(int userId, String packageName) { 516 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 517 return packages.get(packageName); 518 } 519 520 public void put(int userId, String packageName, ArrayList<String> components) { 521 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 522 packages.put(packageName, components); 523 } 524 525 public void remove(int userId, String packageName) { 526 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 527 if (packages != null) { 528 packages.remove(packageName); 529 } 530 } 531 532 public void remove(int userId) { 533 mUidMap.remove(userId); 534 } 535 536 public int userIdCount() { 537 return mUidMap.size(); 538 } 539 540 public int userIdAt(int n) { 541 return mUidMap.keyAt(n); 542 } 543 544 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 545 return mUidMap.get(userId); 546 } 547 548 public int size() { 549 // total number of pending broadcast entries across all userIds 550 int num = 0; 551 for (int i = 0; i< mUidMap.size(); i++) { 552 num += mUidMap.valueAt(i).size(); 553 } 554 return num; 555 } 556 557 public void clear() { 558 mUidMap.clear(); 559 } 560 561 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 562 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 563 if (map == null) { 564 map = new ArrayMap<String, ArrayList<String>>(); 565 mUidMap.put(userId, map); 566 } 567 return map; 568 } 569 } 570 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 571 572 // Service Connection to remote media container service to copy 573 // package uri's from external media onto secure containers 574 // or internal storage. 575 private IMediaContainerService mContainerService = null; 576 577 static final int SEND_PENDING_BROADCAST = 1; 578 static final int MCS_BOUND = 3; 579 static final int END_COPY = 4; 580 static final int INIT_COPY = 5; 581 static final int MCS_UNBIND = 6; 582 static final int START_CLEANING_PACKAGE = 7; 583 static final int FIND_INSTALL_LOC = 8; 584 static final int POST_INSTALL = 9; 585 static final int MCS_RECONNECT = 10; 586 static final int MCS_GIVE_UP = 11; 587 static final int UPDATED_MEDIA_STATUS = 12; 588 static final int WRITE_SETTINGS = 13; 589 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 590 static final int PACKAGE_VERIFIED = 15; 591 static final int CHECK_PENDING_VERIFICATION = 16; 592 593 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 594 595 // Delay time in millisecs 596 static final int BROADCAST_DELAY = 10 * 1000; 597 598 static UserManagerService sUserManager; 599 600 // Stores a list of users whose package restrictions file needs to be updated 601 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 602 603 final private DefaultContainerConnection mDefContainerConn = 604 new DefaultContainerConnection(); 605 class DefaultContainerConnection implements ServiceConnection { 606 public void onServiceConnected(ComponentName name, IBinder service) { 607 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 608 IMediaContainerService imcs = 609 IMediaContainerService.Stub.asInterface(service); 610 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 611 } 612 613 public void onServiceDisconnected(ComponentName name) { 614 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 615 } 616 }; 617 618 // Recordkeeping of restore-after-install operations that are currently in flight 619 // between the Package Manager and the Backup Manager 620 class PostInstallData { 621 public InstallArgs args; 622 public PackageInstalledInfo res; 623 624 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 625 args = _a; 626 res = _r; 627 } 628 }; 629 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 630 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 631 632 private final String mRequiredVerifierPackage; 633 634 private final PackageUsage mPackageUsage = new PackageUsage(); 635 636 private class PackageUsage { 637 private static final int WRITE_INTERVAL 638 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 639 640 private final Object mFileLock = new Object(); 641 private final AtomicLong mLastWritten = new AtomicLong(0); 642 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 643 644 private boolean mIsHistoricalPackageUsageAvailable = true; 645 646 boolean isHistoricalPackageUsageAvailable() { 647 return mIsHistoricalPackageUsageAvailable; 648 } 649 650 void write(boolean force) { 651 if (force) { 652 writeInternal(); 653 return; 654 } 655 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 656 && !DEBUG_DEXOPT) { 657 return; 658 } 659 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 660 new Thread("PackageUsage_DiskWriter") { 661 @Override 662 public void run() { 663 try { 664 writeInternal(); 665 } finally { 666 mBackgroundWriteRunning.set(false); 667 } 668 } 669 }.start(); 670 } 671 } 672 673 private void writeInternal() { 674 synchronized (mPackages) { 675 synchronized (mFileLock) { 676 AtomicFile file = getFile(); 677 FileOutputStream f = null; 678 try { 679 f = file.startWrite(); 680 BufferedOutputStream out = new BufferedOutputStream(f); 681 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 682 StringBuilder sb = new StringBuilder(); 683 for (PackageParser.Package pkg : mPackages.values()) { 684 if (pkg.mLastPackageUsageTimeInMills == 0) { 685 continue; 686 } 687 sb.setLength(0); 688 sb.append(pkg.packageName); 689 sb.append(' '); 690 sb.append((long)pkg.mLastPackageUsageTimeInMills); 691 sb.append('\n'); 692 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 693 } 694 out.flush(); 695 file.finishWrite(f); 696 } catch (IOException e) { 697 if (f != null) { 698 file.failWrite(f); 699 } 700 Log.e(TAG, "Failed to write package usage times", e); 701 } 702 } 703 } 704 mLastWritten.set(SystemClock.elapsedRealtime()); 705 } 706 707 void readLP() { 708 synchronized (mFileLock) { 709 AtomicFile file = getFile(); 710 BufferedInputStream in = null; 711 try { 712 in = new BufferedInputStream(file.openRead()); 713 StringBuffer sb = new StringBuffer(); 714 while (true) { 715 String packageName = readToken(in, sb, ' '); 716 if (packageName == null) { 717 break; 718 } 719 String timeInMillisString = readToken(in, sb, '\n'); 720 if (timeInMillisString == null) { 721 throw new IOException("Failed to find last usage time for package " 722 + packageName); 723 } 724 PackageParser.Package pkg = mPackages.get(packageName); 725 if (pkg == null) { 726 continue; 727 } 728 long timeInMillis; 729 try { 730 timeInMillis = Long.parseLong(timeInMillisString.toString()); 731 } catch (NumberFormatException e) { 732 throw new IOException("Failed to parse " + timeInMillisString 733 + " as a long.", e); 734 } 735 pkg.mLastPackageUsageTimeInMills = timeInMillis; 736 } 737 } catch (FileNotFoundException expected) { 738 mIsHistoricalPackageUsageAvailable = false; 739 } catch (IOException e) { 740 Log.w(TAG, "Failed to read package usage times", e); 741 } finally { 742 IoUtils.closeQuietly(in); 743 } 744 } 745 mLastWritten.set(SystemClock.elapsedRealtime()); 746 } 747 748 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 749 throws IOException { 750 sb.setLength(0); 751 while (true) { 752 int ch = in.read(); 753 if (ch == -1) { 754 if (sb.length() == 0) { 755 return null; 756 } 757 throw new IOException("Unexpected EOF"); 758 } 759 if (ch == endOfToken) { 760 return sb.toString(); 761 } 762 sb.append((char)ch); 763 } 764 } 765 766 private AtomicFile getFile() { 767 File dataDir = Environment.getDataDirectory(); 768 File systemDir = new File(dataDir, "system"); 769 File fname = new File(systemDir, "package-usage.list"); 770 return new AtomicFile(fname); 771 } 772 } 773 774 class PackageHandler extends Handler { 775 private boolean mBound = false; 776 final ArrayList<HandlerParams> mPendingInstalls = 777 new ArrayList<HandlerParams>(); 778 779 private boolean connectToService() { 780 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 781 " DefaultContainerService"); 782 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 783 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 784 if (mContext.bindServiceAsUser(service, mDefContainerConn, 785 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 786 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 787 mBound = true; 788 return true; 789 } 790 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 791 return false; 792 } 793 794 private void disconnectService() { 795 mContainerService = null; 796 mBound = false; 797 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 798 mContext.unbindService(mDefContainerConn); 799 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 800 } 801 802 PackageHandler(Looper looper) { 803 super(looper); 804 } 805 806 public void handleMessage(Message msg) { 807 try { 808 doHandleMessage(msg); 809 } finally { 810 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 811 } 812 } 813 814 void doHandleMessage(Message msg) { 815 switch (msg.what) { 816 case INIT_COPY: { 817 HandlerParams params = (HandlerParams) msg.obj; 818 int idx = mPendingInstalls.size(); 819 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 820 // If a bind was already initiated we dont really 821 // need to do anything. The pending install 822 // will be processed later on. 823 if (!mBound) { 824 // If this is the only one pending we might 825 // have to bind to the service again. 826 if (!connectToService()) { 827 Slog.e(TAG, "Failed to bind to media container service"); 828 params.serviceError(); 829 return; 830 } else { 831 // Once we bind to the service, the first 832 // pending request will be processed. 833 mPendingInstalls.add(idx, params); 834 } 835 } else { 836 mPendingInstalls.add(idx, params); 837 // Already bound to the service. Just make 838 // sure we trigger off processing the first request. 839 if (idx == 0) { 840 mHandler.sendEmptyMessage(MCS_BOUND); 841 } 842 } 843 break; 844 } 845 case MCS_BOUND: { 846 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 847 if (msg.obj != null) { 848 mContainerService = (IMediaContainerService) msg.obj; 849 } 850 if (mContainerService == null) { 851 // Something seriously wrong. Bail out 852 Slog.e(TAG, "Cannot bind to media container service"); 853 for (HandlerParams params : mPendingInstalls) { 854 // Indicate service bind error 855 params.serviceError(); 856 } 857 mPendingInstalls.clear(); 858 } else if (mPendingInstalls.size() > 0) { 859 HandlerParams params = mPendingInstalls.get(0); 860 if (params != null) { 861 if (params.startCopy()) { 862 // We are done... look for more work or to 863 // go idle. 864 if (DEBUG_SD_INSTALL) Log.i(TAG, 865 "Checking for more work or unbind..."); 866 // Delete pending install 867 if (mPendingInstalls.size() > 0) { 868 mPendingInstalls.remove(0); 869 } 870 if (mPendingInstalls.size() == 0) { 871 if (mBound) { 872 if (DEBUG_SD_INSTALL) Log.i(TAG, 873 "Posting delayed MCS_UNBIND"); 874 removeMessages(MCS_UNBIND); 875 Message ubmsg = obtainMessage(MCS_UNBIND); 876 // Unbind after a little delay, to avoid 877 // continual thrashing. 878 sendMessageDelayed(ubmsg, 10000); 879 } 880 } else { 881 // There are more pending requests in queue. 882 // Just post MCS_BOUND message to trigger processing 883 // of next pending install. 884 if (DEBUG_SD_INSTALL) Log.i(TAG, 885 "Posting MCS_BOUND for next work"); 886 mHandler.sendEmptyMessage(MCS_BOUND); 887 } 888 } 889 } 890 } else { 891 // Should never happen ideally. 892 Slog.w(TAG, "Empty queue"); 893 } 894 break; 895 } 896 case MCS_RECONNECT: { 897 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 898 if (mPendingInstalls.size() > 0) { 899 if (mBound) { 900 disconnectService(); 901 } 902 if (!connectToService()) { 903 Slog.e(TAG, "Failed to bind to media container service"); 904 for (HandlerParams params : mPendingInstalls) { 905 // Indicate service bind error 906 params.serviceError(); 907 } 908 mPendingInstalls.clear(); 909 } 910 } 911 break; 912 } 913 case MCS_UNBIND: { 914 // If there is no actual work left, then time to unbind. 915 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 916 917 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 918 if (mBound) { 919 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 920 921 disconnectService(); 922 } 923 } else if (mPendingInstalls.size() > 0) { 924 // There are more pending requests in queue. 925 // Just post MCS_BOUND message to trigger processing 926 // of next pending install. 927 mHandler.sendEmptyMessage(MCS_BOUND); 928 } 929 930 break; 931 } 932 case MCS_GIVE_UP: { 933 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 934 mPendingInstalls.remove(0); 935 break; 936 } 937 case SEND_PENDING_BROADCAST: { 938 String packages[]; 939 ArrayList<String> components[]; 940 int size = 0; 941 int uids[]; 942 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 943 synchronized (mPackages) { 944 if (mPendingBroadcasts == null) { 945 return; 946 } 947 size = mPendingBroadcasts.size(); 948 if (size <= 0) { 949 // Nothing to be done. Just return 950 return; 951 } 952 packages = new String[size]; 953 components = new ArrayList[size]; 954 uids = new int[size]; 955 int i = 0; // filling out the above arrays 956 957 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 958 int packageUserId = mPendingBroadcasts.userIdAt(n); 959 Iterator<Map.Entry<String, ArrayList<String>>> it 960 = mPendingBroadcasts.packagesForUserId(packageUserId) 961 .entrySet().iterator(); 962 while (it.hasNext() && i < size) { 963 Map.Entry<String, ArrayList<String>> ent = it.next(); 964 packages[i] = ent.getKey(); 965 components[i] = ent.getValue(); 966 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 967 uids[i] = (ps != null) 968 ? UserHandle.getUid(packageUserId, ps.appId) 969 : -1; 970 i++; 971 } 972 } 973 size = i; 974 mPendingBroadcasts.clear(); 975 } 976 // Send broadcasts 977 for (int i = 0; i < size; i++) { 978 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 979 } 980 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 981 break; 982 } 983 case START_CLEANING_PACKAGE: { 984 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 985 final String packageName = (String)msg.obj; 986 final int userId = msg.arg1; 987 final boolean andCode = msg.arg2 != 0; 988 synchronized (mPackages) { 989 if (userId == UserHandle.USER_ALL) { 990 int[] users = sUserManager.getUserIds(); 991 for (int user : users) { 992 mSettings.addPackageToCleanLPw( 993 new PackageCleanItem(user, packageName, andCode)); 994 } 995 } else { 996 mSettings.addPackageToCleanLPw( 997 new PackageCleanItem(userId, packageName, andCode)); 998 } 999 } 1000 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1001 startCleaningPackages(); 1002 } break; 1003 case POST_INSTALL: { 1004 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1005 PostInstallData data = mRunningInstalls.get(msg.arg1); 1006 mRunningInstalls.delete(msg.arg1); 1007 boolean deleteOld = false; 1008 1009 if (data != null) { 1010 InstallArgs args = data.args; 1011 PackageInstalledInfo res = data.res; 1012 1013 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1014 res.removedInfo.sendBroadcast(false, true, false); 1015 Bundle extras = new Bundle(1); 1016 extras.putInt(Intent.EXTRA_UID, res.uid); 1017 1018 // Now that we successfully installed the package, grant runtime 1019 // permissions if requested before broadcasting the install. 1020 if ((args.installFlags 1021 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1022 grantRequestedRuntimePermissions(res.pkg, 1023 args.user.getIdentifier()); 1024 } 1025 1026 // Determine the set of users who are adding this 1027 // package for the first time vs. those who are seeing 1028 // an update. 1029 int[] firstUsers; 1030 int[] updateUsers = new int[0]; 1031 if (res.origUsers == null || res.origUsers.length == 0) { 1032 firstUsers = res.newUsers; 1033 } else { 1034 firstUsers = new int[0]; 1035 for (int i=0; i<res.newUsers.length; i++) { 1036 int user = res.newUsers[i]; 1037 boolean isNew = true; 1038 for (int j=0; j<res.origUsers.length; j++) { 1039 if (res.origUsers[j] == user) { 1040 isNew = false; 1041 break; 1042 } 1043 } 1044 if (isNew) { 1045 int[] newFirst = new int[firstUsers.length+1]; 1046 System.arraycopy(firstUsers, 0, newFirst, 0, 1047 firstUsers.length); 1048 newFirst[firstUsers.length] = user; 1049 firstUsers = newFirst; 1050 } else { 1051 int[] newUpdate = new int[updateUsers.length+1]; 1052 System.arraycopy(updateUsers, 0, newUpdate, 0, 1053 updateUsers.length); 1054 newUpdate[updateUsers.length] = user; 1055 updateUsers = newUpdate; 1056 } 1057 } 1058 } 1059 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1060 res.pkg.applicationInfo.packageName, 1061 extras, null, null, firstUsers); 1062 final boolean update = res.removedInfo.removedPackage != null; 1063 if (update) { 1064 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1065 } 1066 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1067 res.pkg.applicationInfo.packageName, 1068 extras, null, null, updateUsers); 1069 if (update) { 1070 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1071 res.pkg.applicationInfo.packageName, 1072 extras, null, null, updateUsers); 1073 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1074 null, null, 1075 res.pkg.applicationInfo.packageName, null, updateUsers); 1076 1077 // treat asec-hosted packages like removable media on upgrade 1078 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1079 if (DEBUG_INSTALL) { 1080 Slog.i(TAG, "upgrading pkg " + res.pkg 1081 + " is ASEC-hosted -> AVAILABLE"); 1082 } 1083 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1084 ArrayList<String> pkgList = new ArrayList<String>(1); 1085 pkgList.add(res.pkg.applicationInfo.packageName); 1086 sendResourcesChangedBroadcast(true, true, 1087 pkgList,uidArray, null); 1088 } 1089 } 1090 if (res.removedInfo.args != null) { 1091 // Remove the replaced package's older resources safely now 1092 deleteOld = true; 1093 } 1094 1095 // Log current value of "unknown sources" setting 1096 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1097 getUnknownSourcesSettings()); 1098 } 1099 // Force a gc to clear up things 1100 Runtime.getRuntime().gc(); 1101 // We delete after a gc for applications on sdcard. 1102 if (deleteOld) { 1103 synchronized (mInstallLock) { 1104 res.removedInfo.args.doPostDeleteLI(true); 1105 } 1106 } 1107 if (args.observer != null) { 1108 try { 1109 Bundle extras = extrasForInstallResult(res); 1110 args.observer.onPackageInstalled(res.name, res.returnCode, 1111 res.returnMsg, extras); 1112 } catch (RemoteException e) { 1113 Slog.i(TAG, "Observer no longer exists."); 1114 } 1115 } 1116 } else { 1117 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1118 } 1119 } break; 1120 case UPDATED_MEDIA_STATUS: { 1121 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1122 boolean reportStatus = msg.arg1 == 1; 1123 boolean doGc = msg.arg2 == 1; 1124 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1125 if (doGc) { 1126 // Force a gc to clear up stale containers. 1127 Runtime.getRuntime().gc(); 1128 } 1129 if (msg.obj != null) { 1130 @SuppressWarnings("unchecked") 1131 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1132 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1133 // Unload containers 1134 unloadAllContainers(args); 1135 } 1136 if (reportStatus) { 1137 try { 1138 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1139 PackageHelper.getMountService().finishMediaUpdate(); 1140 } catch (RemoteException e) { 1141 Log.e(TAG, "MountService not running?"); 1142 } 1143 } 1144 } break; 1145 case WRITE_SETTINGS: { 1146 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1147 synchronized (mPackages) { 1148 removeMessages(WRITE_SETTINGS); 1149 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1150 mSettings.writeLPr(); 1151 mDirtyUsers.clear(); 1152 } 1153 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1154 } break; 1155 case WRITE_PACKAGE_RESTRICTIONS: { 1156 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1157 synchronized (mPackages) { 1158 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1159 for (int userId : mDirtyUsers) { 1160 mSettings.writePackageRestrictionsLPr(userId); 1161 } 1162 mDirtyUsers.clear(); 1163 } 1164 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1165 } break; 1166 case CHECK_PENDING_VERIFICATION: { 1167 final int verificationId = msg.arg1; 1168 final PackageVerificationState state = mPendingVerification.get(verificationId); 1169 1170 if ((state != null) && !state.timeoutExtended()) { 1171 final InstallArgs args = state.getInstallArgs(); 1172 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1173 1174 Slog.i(TAG, "Verification timed out for " + originUri); 1175 mPendingVerification.remove(verificationId); 1176 1177 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1178 1179 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1180 Slog.i(TAG, "Continuing with installation of " + originUri); 1181 state.setVerifierResponse(Binder.getCallingUid(), 1182 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1183 broadcastPackageVerified(verificationId, originUri, 1184 PackageManager.VERIFICATION_ALLOW, 1185 state.getInstallArgs().getUser()); 1186 try { 1187 ret = args.copyApk(mContainerService, true); 1188 } catch (RemoteException e) { 1189 Slog.e(TAG, "Could not contact the ContainerService"); 1190 } 1191 } else { 1192 broadcastPackageVerified(verificationId, originUri, 1193 PackageManager.VERIFICATION_REJECT, 1194 state.getInstallArgs().getUser()); 1195 } 1196 1197 processPendingInstall(args, ret); 1198 mHandler.sendEmptyMessage(MCS_UNBIND); 1199 } 1200 break; 1201 } 1202 case PACKAGE_VERIFIED: { 1203 final int verificationId = msg.arg1; 1204 1205 final PackageVerificationState state = mPendingVerification.get(verificationId); 1206 if (state == null) { 1207 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1208 break; 1209 } 1210 1211 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1212 1213 state.setVerifierResponse(response.callerUid, response.code); 1214 1215 if (state.isVerificationComplete()) { 1216 mPendingVerification.remove(verificationId); 1217 1218 final InstallArgs args = state.getInstallArgs(); 1219 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1220 1221 int ret; 1222 if (state.isInstallAllowed()) { 1223 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1224 broadcastPackageVerified(verificationId, originUri, 1225 response.code, state.getInstallArgs().getUser()); 1226 try { 1227 ret = args.copyApk(mContainerService, true); 1228 } catch (RemoteException e) { 1229 Slog.e(TAG, "Could not contact the ContainerService"); 1230 } 1231 } else { 1232 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1233 } 1234 1235 processPendingInstall(args, ret); 1236 1237 mHandler.sendEmptyMessage(MCS_UNBIND); 1238 } 1239 1240 break; 1241 } 1242 } 1243 } 1244 } 1245 1246 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1247 if (userId >= UserHandle.USER_OWNER) { 1248 grantRequestedRuntimePermissionsForUser(pkg, userId); 1249 } else if (userId == UserHandle.USER_ALL) { 1250 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1251 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1252 } 1253 } 1254 } 1255 1256 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1257 SettingBase sb = (SettingBase) pkg.mExtras; 1258 if (sb == null) { 1259 return; 1260 } 1261 1262 PermissionsState permissionsState = sb.getPermissionsState(); 1263 1264 for (String permission : pkg.requestedPermissions) { 1265 BasePermission bp = mSettings.mPermissions.get(permission); 1266 if (bp != null && bp.isRuntime()) { 1267 permissionsState.grantRuntimePermission(bp, userId); 1268 } 1269 } 1270 } 1271 1272 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1273 Bundle extras = null; 1274 switch (res.returnCode) { 1275 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1276 extras = new Bundle(); 1277 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1278 res.origPermission); 1279 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1280 res.origPackage); 1281 break; 1282 } 1283 } 1284 return extras; 1285 } 1286 1287 void scheduleWriteSettingsLocked() { 1288 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1289 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1290 } 1291 } 1292 1293 void scheduleWritePackageRestrictionsLocked(int userId) { 1294 if (!sUserManager.exists(userId)) return; 1295 mDirtyUsers.add(userId); 1296 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1297 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1298 } 1299 } 1300 1301 public static PackageManagerService main(Context context, Installer installer, 1302 boolean factoryTest, boolean onlyCore) { 1303 PackageManagerService m = new PackageManagerService(context, installer, 1304 factoryTest, onlyCore); 1305 ServiceManager.addService("package", m); 1306 return m; 1307 } 1308 1309 static String[] splitString(String str, char sep) { 1310 int count = 1; 1311 int i = 0; 1312 while ((i=str.indexOf(sep, i)) >= 0) { 1313 count++; 1314 i++; 1315 } 1316 1317 String[] res = new String[count]; 1318 i=0; 1319 count = 0; 1320 int lastI=0; 1321 while ((i=str.indexOf(sep, i)) >= 0) { 1322 res[count] = str.substring(lastI, i); 1323 count++; 1324 i++; 1325 lastI = i; 1326 } 1327 res[count] = str.substring(lastI, str.length()); 1328 return res; 1329 } 1330 1331 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1332 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1333 Context.DISPLAY_SERVICE); 1334 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1335 } 1336 1337 public PackageManagerService(Context context, Installer installer, 1338 boolean factoryTest, boolean onlyCore) { 1339 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1340 SystemClock.uptimeMillis()); 1341 1342 if (mSdkVersion <= 0) { 1343 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1344 } 1345 1346 mContext = context; 1347 mFactoryTest = factoryTest; 1348 mOnlyCore = onlyCore; 1349 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1350 mMetrics = new DisplayMetrics(); 1351 mSettings = new Settings(mContext, mPackages); 1352 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1353 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1354 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1355 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1356 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1357 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1358 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1359 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1360 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1361 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1362 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1363 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1364 1365 // TODO: add a property to control this? 1366 long dexOptLRUThresholdInMinutes; 1367 if (mLazyDexOpt) { 1368 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1369 } else { 1370 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1371 } 1372 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1373 1374 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1375 if (separateProcesses != null && separateProcesses.length() > 0) { 1376 if ("*".equals(separateProcesses)) { 1377 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1378 mSeparateProcesses = null; 1379 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1380 } else { 1381 mDefParseFlags = 0; 1382 mSeparateProcesses = separateProcesses.split(","); 1383 Slog.w(TAG, "Running with debug.separate_processes: " 1384 + separateProcesses); 1385 } 1386 } else { 1387 mDefParseFlags = 0; 1388 mSeparateProcesses = null; 1389 } 1390 1391 mInstaller = installer; 1392 mPackageDexOptimizer = new PackageDexOptimizer(this); 1393 1394 getDefaultDisplayMetrics(context, mMetrics); 1395 1396 SystemConfig systemConfig = SystemConfig.getInstance(); 1397 mGlobalGids = systemConfig.getGlobalGids(); 1398 mSystemPermissions = systemConfig.getSystemPermissions(); 1399 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1400 1401 synchronized (mInstallLock) { 1402 // writer 1403 synchronized (mPackages) { 1404 mHandlerThread = new ServiceThread(TAG, 1405 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1406 mHandlerThread.start(); 1407 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1408 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1409 1410 File dataDir = Environment.getDataDirectory(); 1411 mAppDataDir = new File(dataDir, "data"); 1412 mAppInstallDir = new File(dataDir, "app"); 1413 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1414 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1415 mUserAppDataDir = new File(dataDir, "user"); 1416 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1417 1418 sUserManager = new UserManagerService(context, this, 1419 mInstallLock, mPackages); 1420 1421 // Propagate permission configuration in to package manager. 1422 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1423 = systemConfig.getPermissions(); 1424 for (int i=0; i<permConfig.size(); i++) { 1425 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1426 BasePermission bp = mSettings.mPermissions.get(perm.name); 1427 if (bp == null) { 1428 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1429 mSettings.mPermissions.put(perm.name, bp); 1430 } 1431 if (perm.gids != null) { 1432 bp.setGids(perm.gids, perm.perUser); 1433 } 1434 } 1435 1436 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1437 for (int i=0; i<libConfig.size(); i++) { 1438 mSharedLibraries.put(libConfig.keyAt(i), 1439 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1440 } 1441 1442 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1443 1444 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1445 mSdkVersion, mOnlyCore); 1446 1447 String customResolverActivity = Resources.getSystem().getString( 1448 R.string.config_customResolverActivity); 1449 if (TextUtils.isEmpty(customResolverActivity)) { 1450 customResolverActivity = null; 1451 } else { 1452 mCustomResolverComponentName = ComponentName.unflattenFromString( 1453 customResolverActivity); 1454 } 1455 1456 long startTime = SystemClock.uptimeMillis(); 1457 1458 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1459 startTime); 1460 1461 // Set flag to monitor and not change apk file paths when 1462 // scanning install directories. 1463 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1464 1465 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1466 1467 /** 1468 * Add everything in the in the boot class path to the 1469 * list of process files because dexopt will have been run 1470 * if necessary during zygote startup. 1471 */ 1472 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1473 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1474 1475 if (bootClassPath != null) { 1476 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1477 for (String element : bootClassPathElements) { 1478 alreadyDexOpted.add(element); 1479 } 1480 } else { 1481 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1482 } 1483 1484 if (systemServerClassPath != null) { 1485 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1486 for (String element : systemServerClassPathElements) { 1487 alreadyDexOpted.add(element); 1488 } 1489 } else { 1490 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1491 } 1492 1493 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1494 final String[] dexCodeInstructionSets = 1495 getDexCodeInstructionSets( 1496 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1497 1498 /** 1499 * Ensure all external libraries have had dexopt run on them. 1500 */ 1501 if (mSharedLibraries.size() > 0) { 1502 // NOTE: For now, we're compiling these system "shared libraries" 1503 // (and framework jars) into all available architectures. It's possible 1504 // to compile them only when we come across an app that uses them (there's 1505 // already logic for that in scanPackageLI) but that adds some complexity. 1506 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1507 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1508 final String lib = libEntry.path; 1509 if (lib == null) { 1510 continue; 1511 } 1512 1513 try { 1514 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1515 dexCodeInstructionSet, 1516 false); 1517 if (dexoptRequired != DexFile.UP_TO_DATE) { 1518 alreadyDexOpted.add(lib); 1519 1520 // The list of "shared libraries" we have at this point is 1521 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1522 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1523 } else { 1524 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1525 } 1526 } 1527 } catch (FileNotFoundException e) { 1528 Slog.w(TAG, "Library not found: " + lib); 1529 } catch (IOException e) { 1530 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1531 + e.getMessage()); 1532 } 1533 } 1534 } 1535 } 1536 1537 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1538 1539 // Gross hack for now: we know this file doesn't contain any 1540 // code, so don't dexopt it to avoid the resulting log spew. 1541 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1542 1543 // Gross hack for now: we know this file is only part of 1544 // the boot class path for art, so don't dexopt it to 1545 // avoid the resulting log spew. 1546 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1547 1548 /** 1549 * And there are a number of commands implemented in Java, which 1550 * we currently need to do the dexopt on so that they can be 1551 * run from a non-root shell. 1552 */ 1553 String[] frameworkFiles = frameworkDir.list(); 1554 if (frameworkFiles != null) { 1555 // TODO: We could compile these only for the most preferred ABI. We should 1556 // first double check that the dex files for these commands are not referenced 1557 // by other system apps. 1558 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1559 for (int i=0; i<frameworkFiles.length; i++) { 1560 File libPath = new File(frameworkDir, frameworkFiles[i]); 1561 String path = libPath.getPath(); 1562 // Skip the file if we already did it. 1563 if (alreadyDexOpted.contains(path)) { 1564 continue; 1565 } 1566 // Skip the file if it is not a type we want to dexopt. 1567 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1568 continue; 1569 } 1570 try { 1571 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1572 dexCodeInstructionSet, 1573 false); 1574 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1575 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1576 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1577 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1578 } 1579 } catch (FileNotFoundException e) { 1580 Slog.w(TAG, "Jar not found: " + path); 1581 } catch (IOException e) { 1582 Slog.w(TAG, "Exception reading jar: " + path, e); 1583 } 1584 } 1585 } 1586 } 1587 1588 // Collect vendor overlay packages. 1589 // (Do this before scanning any apps.) 1590 // For security and version matching reason, only consider 1591 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1592 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1593 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1594 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1595 1596 // Find base frameworks (resource packages without code). 1597 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1598 | PackageParser.PARSE_IS_SYSTEM_DIR 1599 | PackageParser.PARSE_IS_PRIVILEGED, 1600 scanFlags | SCAN_NO_DEX, 0); 1601 1602 // Collected privileged system packages. 1603 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1604 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1605 | PackageParser.PARSE_IS_SYSTEM_DIR 1606 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1607 1608 // Collect ordinary system packages. 1609 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1610 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1611 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1612 1613 // Collect all vendor packages. 1614 File vendorAppDir = new File("/vendor/app"); 1615 try { 1616 vendorAppDir = vendorAppDir.getCanonicalFile(); 1617 } catch (IOException e) { 1618 // failed to look up canonical path, continue with original one 1619 } 1620 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1621 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1622 1623 // Collect all OEM packages. 1624 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1625 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1626 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1627 1628 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1629 mInstaller.moveFiles(); 1630 1631 // Prune any system packages that no longer exist. 1632 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1633 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1634 if (!mOnlyCore) { 1635 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1636 while (psit.hasNext()) { 1637 PackageSetting ps = psit.next(); 1638 1639 /* 1640 * If this is not a system app, it can't be a 1641 * disable system app. 1642 */ 1643 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1644 continue; 1645 } 1646 1647 /* 1648 * If the package is scanned, it's not erased. 1649 */ 1650 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1651 if (scannedPkg != null) { 1652 /* 1653 * If the system app is both scanned and in the 1654 * disabled packages list, then it must have been 1655 * added via OTA. Remove it from the currently 1656 * scanned package so the previously user-installed 1657 * application can be scanned. 1658 */ 1659 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1660 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1661 + ps.name + "; removing system app. Last known codePath=" 1662 + ps.codePathString + ", installStatus=" + ps.installStatus 1663 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1664 + scannedPkg.mVersionCode); 1665 removePackageLI(ps, true); 1666 expectingBetter.put(ps.name, ps.codePath); 1667 } 1668 1669 continue; 1670 } 1671 1672 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1673 psit.remove(); 1674 logCriticalInfo(Log.WARN, "System package " + ps.name 1675 + " no longer exists; wiping its data"); 1676 removeDataDirsLI(ps.name); 1677 } else { 1678 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1679 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1680 possiblyDeletedUpdatedSystemApps.add(ps.name); 1681 } 1682 } 1683 } 1684 } 1685 1686 //look for any incomplete package installations 1687 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1688 //clean up list 1689 for(int i = 0; i < deletePkgsList.size(); i++) { 1690 //clean up here 1691 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1692 } 1693 //delete tmp files 1694 deleteTempPackageFiles(); 1695 1696 // Remove any shared userIDs that have no associated packages 1697 mSettings.pruneSharedUsersLPw(); 1698 1699 if (!mOnlyCore) { 1700 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1701 SystemClock.uptimeMillis()); 1702 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1703 1704 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1705 scanFlags, 0); 1706 1707 /** 1708 * Remove disable package settings for any updated system 1709 * apps that were removed via an OTA. If they're not a 1710 * previously-updated app, remove them completely. 1711 * Otherwise, just revoke their system-level permissions. 1712 */ 1713 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1714 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1715 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1716 1717 String msg; 1718 if (deletedPkg == null) { 1719 msg = "Updated system package " + deletedAppName 1720 + " no longer exists; wiping its data"; 1721 removeDataDirsLI(deletedAppName); 1722 } else { 1723 msg = "Updated system app + " + deletedAppName 1724 + " no longer present; removing system privileges for " 1725 + deletedAppName; 1726 1727 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1728 1729 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1730 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1731 } 1732 logCriticalInfo(Log.WARN, msg); 1733 } 1734 1735 /** 1736 * Make sure all system apps that we expected to appear on 1737 * the userdata partition actually showed up. If they never 1738 * appeared, crawl back and revive the system version. 1739 */ 1740 for (int i = 0; i < expectingBetter.size(); i++) { 1741 final String packageName = expectingBetter.keyAt(i); 1742 if (!mPackages.containsKey(packageName)) { 1743 final File scanFile = expectingBetter.valueAt(i); 1744 1745 logCriticalInfo(Log.WARN, "Expected better " + packageName 1746 + " but never showed up; reverting to system"); 1747 1748 final int reparseFlags; 1749 if (FileUtils.contains(privilegedAppDir, scanFile)) { 1750 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1751 | PackageParser.PARSE_IS_SYSTEM_DIR 1752 | PackageParser.PARSE_IS_PRIVILEGED; 1753 } else if (FileUtils.contains(systemAppDir, scanFile)) { 1754 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1755 | PackageParser.PARSE_IS_SYSTEM_DIR; 1756 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 1757 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1758 | PackageParser.PARSE_IS_SYSTEM_DIR; 1759 } else if (FileUtils.contains(oemAppDir, scanFile)) { 1760 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1761 | PackageParser.PARSE_IS_SYSTEM_DIR; 1762 } else { 1763 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 1764 continue; 1765 } 1766 1767 mSettings.enableSystemPackageLPw(packageName); 1768 1769 try { 1770 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 1771 } catch (PackageManagerException e) { 1772 Slog.e(TAG, "Failed to parse original system package: " 1773 + e.getMessage()); 1774 } 1775 } 1776 } 1777 } 1778 1779 // Now that we know all of the shared libraries, update all clients to have 1780 // the correct library paths. 1781 updateAllSharedLibrariesLPw(); 1782 1783 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1784 // NOTE: We ignore potential failures here during a system scan (like 1785 // the rest of the commands above) because there's precious little we 1786 // can do about it. A settings error is reported, though. 1787 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1788 false /* force dexopt */, false /* defer dexopt */); 1789 } 1790 1791 // Now that we know all the packages we are keeping, 1792 // read and update their last usage times. 1793 mPackageUsage.readLP(); 1794 1795 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1796 SystemClock.uptimeMillis()); 1797 Slog.i(TAG, "Time to scan packages: " 1798 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1799 + " seconds"); 1800 1801 // If the platform SDK has changed since the last time we booted, 1802 // we need to re-grant app permission to catch any new ones that 1803 // appear. This is really a hack, and means that apps can in some 1804 // cases get permissions that the user didn't initially explicitly 1805 // allow... it would be nice to have some better way to handle 1806 // this situation. 1807 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1808 != mSdkVersion; 1809 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1810 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1811 + "; regranting permissions for internal storage"); 1812 mSettings.mInternalSdkPlatform = mSdkVersion; 1813 1814 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1815 | (regrantPermissions 1816 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1817 : 0)); 1818 1819 // If this is the first boot, and it is a normal boot, then 1820 // we need to initialize the default preferred apps. 1821 if (!mRestoredSettings && !onlyCore) { 1822 mSettings.readDefaultPreferredAppsLPw(this, 0); 1823 } 1824 1825 // If this is first boot after an OTA, and a normal boot, then 1826 // we need to clear code cache directories. 1827 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 1828 if (mIsUpgrade && !onlyCore) { 1829 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1830 for (String pkgName : mSettings.mPackages.keySet()) { 1831 deleteCodeCacheDirsLI(pkgName); 1832 } 1833 mSettings.mFingerprint = Build.FINGERPRINT; 1834 } 1835 1836 // All the changes are done during package scanning. 1837 mSettings.updateInternalDatabaseVersion(); 1838 1839 // can downgrade to reader 1840 mSettings.writeLPr(); 1841 1842 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1843 SystemClock.uptimeMillis()); 1844 1845 1846 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1847 } // synchronized (mPackages) 1848 } // synchronized (mInstallLock) 1849 1850 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1851 1852 // Now after opening every single application zip, make sure they 1853 // are all flushed. Not really needed, but keeps things nice and 1854 // tidy. 1855 Runtime.getRuntime().gc(); 1856 } 1857 1858 @Override 1859 public boolean isFirstBoot() { 1860 return !mRestoredSettings; 1861 } 1862 1863 @Override 1864 public boolean isOnlyCoreApps() { 1865 return mOnlyCore; 1866 } 1867 1868 @Override 1869 public boolean isUpgrade() { 1870 return mIsUpgrade; 1871 } 1872 1873 private String getRequiredVerifierLPr() { 1874 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1875 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1876 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1877 1878 String requiredVerifier = null; 1879 1880 final int N = receivers.size(); 1881 for (int i = 0; i < N; i++) { 1882 final ResolveInfo info = receivers.get(i); 1883 1884 if (info.activityInfo == null) { 1885 continue; 1886 } 1887 1888 final String packageName = info.activityInfo.packageName; 1889 1890 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 1891 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 1892 continue; 1893 } 1894 1895 if (requiredVerifier != null) { 1896 throw new RuntimeException("There can be only one required verifier"); 1897 } 1898 1899 requiredVerifier = packageName; 1900 } 1901 1902 return requiredVerifier; 1903 } 1904 1905 @Override 1906 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1907 throws RemoteException { 1908 try { 1909 return super.onTransact(code, data, reply, flags); 1910 } catch (RuntimeException e) { 1911 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1912 Slog.wtf(TAG, "Package Manager Crash", e); 1913 } 1914 throw e; 1915 } 1916 } 1917 1918 void cleanupInstallFailedPackage(PackageSetting ps) { 1919 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1920 1921 removeDataDirsLI(ps.name); 1922 if (ps.codePath != null) { 1923 if (ps.codePath.isDirectory()) { 1924 FileUtils.deleteContents(ps.codePath); 1925 } 1926 ps.codePath.delete(); 1927 } 1928 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1929 if (ps.resourcePath.isDirectory()) { 1930 FileUtils.deleteContents(ps.resourcePath); 1931 } 1932 ps.resourcePath.delete(); 1933 } 1934 mSettings.removePackageLPw(ps.name); 1935 } 1936 1937 static int[] appendInts(int[] cur, int[] add) { 1938 if (add == null) return cur; 1939 if (cur == null) return add; 1940 final int N = add.length; 1941 for (int i=0; i<N; i++) { 1942 cur = appendInt(cur, add[i]); 1943 } 1944 return cur; 1945 } 1946 1947 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1948 if (!sUserManager.exists(userId)) return null; 1949 final PackageSetting ps = (PackageSetting) p.mExtras; 1950 if (ps == null) { 1951 return null; 1952 } 1953 1954 PermissionsState permissionsState = ps.getPermissionsState(); 1955 1956 final int[] gids = permissionsState.computeGids(userId); 1957 Set<String> permissions = permissionsState.getPermissions(userId); 1958 1959 final PackageUserState state = ps.readUserState(userId); 1960 return PackageParser.generatePackageInfo(p, gids, flags, 1961 ps.firstInstallTime, ps.lastUpdateTime, permissions, 1962 state, userId); 1963 } 1964 1965 @Override 1966 public boolean isPackageAvailable(String packageName, int userId) { 1967 if (!sUserManager.exists(userId)) return false; 1968 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1969 synchronized (mPackages) { 1970 PackageParser.Package p = mPackages.get(packageName); 1971 if (p != null) { 1972 final PackageSetting ps = (PackageSetting) p.mExtras; 1973 if (ps != null) { 1974 final PackageUserState state = ps.readUserState(userId); 1975 if (state != null) { 1976 return PackageParser.isAvailable(state); 1977 } 1978 } 1979 } 1980 } 1981 return false; 1982 } 1983 1984 @Override 1985 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1986 if (!sUserManager.exists(userId)) return null; 1987 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1988 // reader 1989 synchronized (mPackages) { 1990 PackageParser.Package p = mPackages.get(packageName); 1991 if (DEBUG_PACKAGE_INFO) 1992 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1993 if (p != null) { 1994 return generatePackageInfo(p, flags, userId); 1995 } 1996 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1997 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1998 } 1999 } 2000 return null; 2001 } 2002 2003 @Override 2004 public String[] currentToCanonicalPackageNames(String[] names) { 2005 String[] out = new String[names.length]; 2006 // reader 2007 synchronized (mPackages) { 2008 for (int i=names.length-1; i>=0; i--) { 2009 PackageSetting ps = mSettings.mPackages.get(names[i]); 2010 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2011 } 2012 } 2013 return out; 2014 } 2015 2016 @Override 2017 public String[] canonicalToCurrentPackageNames(String[] names) { 2018 String[] out = new String[names.length]; 2019 // reader 2020 synchronized (mPackages) { 2021 for (int i=names.length-1; i>=0; i--) { 2022 String cur = mSettings.mRenamedPackages.get(names[i]); 2023 out[i] = cur != null ? cur : names[i]; 2024 } 2025 } 2026 return out; 2027 } 2028 2029 @Override 2030 public int getPackageUid(String packageName, int userId) { 2031 if (!sUserManager.exists(userId)) return -1; 2032 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2033 2034 // reader 2035 synchronized (mPackages) { 2036 PackageParser.Package p = mPackages.get(packageName); 2037 if(p != null) { 2038 return UserHandle.getUid(userId, p.applicationInfo.uid); 2039 } 2040 PackageSetting ps = mSettings.mPackages.get(packageName); 2041 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2042 return -1; 2043 } 2044 p = ps.pkg; 2045 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2046 } 2047 } 2048 2049 @Override 2050 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2051 if (!sUserManager.exists(userId)) { 2052 return null; 2053 } 2054 2055 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2056 "getPackageGids"); 2057 2058 // reader 2059 synchronized (mPackages) { 2060 PackageParser.Package p = mPackages.get(packageName); 2061 if (DEBUG_PACKAGE_INFO) { 2062 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2063 } 2064 if (p != null) { 2065 PackageSetting ps = (PackageSetting) p.mExtras; 2066 return ps.getPermissionsState().computeGids(userId); 2067 } 2068 } 2069 2070 return null; 2071 } 2072 2073 static PermissionInfo generatePermissionInfo( 2074 BasePermission bp, int flags) { 2075 if (bp.perm != null) { 2076 return PackageParser.generatePermissionInfo(bp.perm, flags); 2077 } 2078 PermissionInfo pi = new PermissionInfo(); 2079 pi.name = bp.name; 2080 pi.packageName = bp.sourcePackage; 2081 pi.nonLocalizedLabel = bp.name; 2082 pi.protectionLevel = bp.protectionLevel; 2083 return pi; 2084 } 2085 2086 @Override 2087 public PermissionInfo getPermissionInfo(String name, int flags) { 2088 // reader 2089 synchronized (mPackages) { 2090 final BasePermission p = mSettings.mPermissions.get(name); 2091 if (p != null) { 2092 return generatePermissionInfo(p, flags); 2093 } 2094 return null; 2095 } 2096 } 2097 2098 @Override 2099 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2100 // reader 2101 synchronized (mPackages) { 2102 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2103 for (BasePermission p : mSettings.mPermissions.values()) { 2104 if (group == null) { 2105 if (p.perm == null || p.perm.info.group == null) { 2106 out.add(generatePermissionInfo(p, flags)); 2107 } 2108 } else { 2109 if (p.perm != null && group.equals(p.perm.info.group)) { 2110 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2111 } 2112 } 2113 } 2114 2115 if (out.size() > 0) { 2116 return out; 2117 } 2118 return mPermissionGroups.containsKey(group) ? out : null; 2119 } 2120 } 2121 2122 @Override 2123 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2124 // reader 2125 synchronized (mPackages) { 2126 return PackageParser.generatePermissionGroupInfo( 2127 mPermissionGroups.get(name), flags); 2128 } 2129 } 2130 2131 @Override 2132 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2133 // reader 2134 synchronized (mPackages) { 2135 final int N = mPermissionGroups.size(); 2136 ArrayList<PermissionGroupInfo> out 2137 = new ArrayList<PermissionGroupInfo>(N); 2138 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2139 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2140 } 2141 return out; 2142 } 2143 } 2144 2145 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2146 int userId) { 2147 if (!sUserManager.exists(userId)) return null; 2148 PackageSetting ps = mSettings.mPackages.get(packageName); 2149 if (ps != null) { 2150 if (ps.pkg == null) { 2151 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2152 flags, userId); 2153 if (pInfo != null) { 2154 return pInfo.applicationInfo; 2155 } 2156 return null; 2157 } 2158 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2159 ps.readUserState(userId), userId); 2160 } 2161 return null; 2162 } 2163 2164 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2165 int userId) { 2166 if (!sUserManager.exists(userId)) return null; 2167 PackageSetting ps = mSettings.mPackages.get(packageName); 2168 if (ps != null) { 2169 PackageParser.Package pkg = ps.pkg; 2170 if (pkg == null) { 2171 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2172 return null; 2173 } 2174 // Only data remains, so we aren't worried about code paths 2175 pkg = new PackageParser.Package(packageName); 2176 pkg.applicationInfo.packageName = packageName; 2177 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2178 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2179 pkg.applicationInfo.dataDir = 2180 getDataPathForPackage(packageName, 0).getPath(); 2181 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2182 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2183 } 2184 return generatePackageInfo(pkg, flags, userId); 2185 } 2186 return null; 2187 } 2188 2189 @Override 2190 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2191 if (!sUserManager.exists(userId)) return null; 2192 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2193 // writer 2194 synchronized (mPackages) { 2195 PackageParser.Package p = mPackages.get(packageName); 2196 if (DEBUG_PACKAGE_INFO) Log.v( 2197 TAG, "getApplicationInfo " + packageName 2198 + ": " + p); 2199 if (p != null) { 2200 PackageSetting ps = mSettings.mPackages.get(packageName); 2201 if (ps == null) return null; 2202 // Note: isEnabledLP() does not apply here - always return info 2203 return PackageParser.generateApplicationInfo( 2204 p, flags, ps.readUserState(userId), userId); 2205 } 2206 if ("android".equals(packageName)||"system".equals(packageName)) { 2207 return mAndroidApplication; 2208 } 2209 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2210 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2211 } 2212 } 2213 return null; 2214 } 2215 2216 2217 @Override 2218 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2219 mContext.enforceCallingOrSelfPermission( 2220 android.Manifest.permission.CLEAR_APP_CACHE, null); 2221 // Queue up an async operation since clearing cache may take a little while. 2222 mHandler.post(new Runnable() { 2223 public void run() { 2224 mHandler.removeCallbacks(this); 2225 int retCode = -1; 2226 synchronized (mInstallLock) { 2227 retCode = mInstaller.freeCache(freeStorageSize); 2228 if (retCode < 0) { 2229 Slog.w(TAG, "Couldn't clear application caches"); 2230 } 2231 } 2232 if (observer != null) { 2233 try { 2234 observer.onRemoveCompleted(null, (retCode >= 0)); 2235 } catch (RemoteException e) { 2236 Slog.w(TAG, "RemoveException when invoking call back"); 2237 } 2238 } 2239 } 2240 }); 2241 } 2242 2243 @Override 2244 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2245 mContext.enforceCallingOrSelfPermission( 2246 android.Manifest.permission.CLEAR_APP_CACHE, null); 2247 // Queue up an async operation since clearing cache may take a little while. 2248 mHandler.post(new Runnable() { 2249 public void run() { 2250 mHandler.removeCallbacks(this); 2251 int retCode = -1; 2252 synchronized (mInstallLock) { 2253 retCode = mInstaller.freeCache(freeStorageSize); 2254 if (retCode < 0) { 2255 Slog.w(TAG, "Couldn't clear application caches"); 2256 } 2257 } 2258 if(pi != null) { 2259 try { 2260 // Callback via pending intent 2261 int code = (retCode >= 0) ? 1 : 0; 2262 pi.sendIntent(null, code, null, 2263 null, null); 2264 } catch (SendIntentException e1) { 2265 Slog.i(TAG, "Failed to send pending intent"); 2266 } 2267 } 2268 } 2269 }); 2270 } 2271 2272 void freeStorage(long freeStorageSize) throws IOException { 2273 synchronized (mInstallLock) { 2274 if (mInstaller.freeCache(freeStorageSize) < 0) { 2275 throw new IOException("Failed to free enough space"); 2276 } 2277 } 2278 } 2279 2280 @Override 2281 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2282 if (!sUserManager.exists(userId)) return null; 2283 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2284 synchronized (mPackages) { 2285 PackageParser.Activity a = mActivities.mActivities.get(component); 2286 2287 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2288 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2289 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2290 if (ps == null) return null; 2291 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2292 userId); 2293 } 2294 if (mResolveComponentName.equals(component)) { 2295 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2296 new PackageUserState(), userId); 2297 } 2298 } 2299 return null; 2300 } 2301 2302 @Override 2303 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2304 String resolvedType) { 2305 synchronized (mPackages) { 2306 PackageParser.Activity a = mActivities.mActivities.get(component); 2307 if (a == null) { 2308 return false; 2309 } 2310 for (int i=0; i<a.intents.size(); i++) { 2311 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2312 intent.getData(), intent.getCategories(), TAG) >= 0) { 2313 return true; 2314 } 2315 } 2316 return false; 2317 } 2318 } 2319 2320 @Override 2321 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2322 if (!sUserManager.exists(userId)) return null; 2323 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2324 synchronized (mPackages) { 2325 PackageParser.Activity a = mReceivers.mActivities.get(component); 2326 if (DEBUG_PACKAGE_INFO) Log.v( 2327 TAG, "getReceiverInfo " + component + ": " + a); 2328 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2329 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2330 if (ps == null) return null; 2331 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2332 userId); 2333 } 2334 } 2335 return null; 2336 } 2337 2338 @Override 2339 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2340 if (!sUserManager.exists(userId)) return null; 2341 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2342 synchronized (mPackages) { 2343 PackageParser.Service s = mServices.mServices.get(component); 2344 if (DEBUG_PACKAGE_INFO) Log.v( 2345 TAG, "getServiceInfo " + component + ": " + s); 2346 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2347 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2348 if (ps == null) return null; 2349 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2350 userId); 2351 } 2352 } 2353 return null; 2354 } 2355 2356 @Override 2357 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2358 if (!sUserManager.exists(userId)) return null; 2359 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2360 synchronized (mPackages) { 2361 PackageParser.Provider p = mProviders.mProviders.get(component); 2362 if (DEBUG_PACKAGE_INFO) Log.v( 2363 TAG, "getProviderInfo " + component + ": " + p); 2364 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2365 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2366 if (ps == null) return null; 2367 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2368 userId); 2369 } 2370 } 2371 return null; 2372 } 2373 2374 @Override 2375 public String[] getSystemSharedLibraryNames() { 2376 Set<String> libSet; 2377 synchronized (mPackages) { 2378 libSet = mSharedLibraries.keySet(); 2379 int size = libSet.size(); 2380 if (size > 0) { 2381 String[] libs = new String[size]; 2382 libSet.toArray(libs); 2383 return libs; 2384 } 2385 } 2386 return null; 2387 } 2388 2389 /** 2390 * @hide 2391 */ 2392 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2393 synchronized (mPackages) { 2394 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2395 if (lib != null && lib.apk != null) { 2396 return mPackages.get(lib.apk); 2397 } 2398 } 2399 return null; 2400 } 2401 2402 @Override 2403 public FeatureInfo[] getSystemAvailableFeatures() { 2404 Collection<FeatureInfo> featSet; 2405 synchronized (mPackages) { 2406 featSet = mAvailableFeatures.values(); 2407 int size = featSet.size(); 2408 if (size > 0) { 2409 FeatureInfo[] features = new FeatureInfo[size+1]; 2410 featSet.toArray(features); 2411 FeatureInfo fi = new FeatureInfo(); 2412 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2413 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2414 features[size] = fi; 2415 return features; 2416 } 2417 } 2418 return null; 2419 } 2420 2421 @Override 2422 public boolean hasSystemFeature(String name) { 2423 synchronized (mPackages) { 2424 return mAvailableFeatures.containsKey(name); 2425 } 2426 } 2427 2428 private void checkValidCaller(int uid, int userId) { 2429 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2430 return; 2431 2432 throw new SecurityException("Caller uid=" + uid 2433 + " is not privileged to communicate with user=" + userId); 2434 } 2435 2436 @Override 2437 public int checkPermission(String permName, String pkgName, int userId) { 2438 if (!sUserManager.exists(userId)) { 2439 return PackageManager.PERMISSION_DENIED; 2440 } 2441 2442 synchronized (mPackages) { 2443 final PackageParser.Package p = mPackages.get(pkgName); 2444 if (p != null && p.mExtras != null) { 2445 final PackageSetting ps = (PackageSetting) p.mExtras; 2446 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2447 return PackageManager.PERMISSION_GRANTED; 2448 } 2449 } 2450 } 2451 2452 return PackageManager.PERMISSION_DENIED; 2453 } 2454 2455 @Override 2456 public int checkUidPermission(String permName, int uid) { 2457 final int userId = UserHandle.getUserId(uid); 2458 2459 if (!sUserManager.exists(userId)) { 2460 return PackageManager.PERMISSION_DENIED; 2461 } 2462 2463 synchronized (mPackages) { 2464 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2465 if (obj != null) { 2466 final SettingBase ps = (SettingBase) obj; 2467 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2468 return PackageManager.PERMISSION_GRANTED; 2469 } 2470 } else { 2471 ArraySet<String> perms = mSystemPermissions.get(uid); 2472 if (perms != null && perms.contains(permName)) { 2473 return PackageManager.PERMISSION_GRANTED; 2474 } 2475 } 2476 } 2477 2478 return PackageManager.PERMISSION_DENIED; 2479 } 2480 2481 /** 2482 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2483 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2484 * @param checkShell TODO(yamasani): 2485 * @param message the message to log on security exception 2486 */ 2487 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2488 boolean checkShell, String message) { 2489 if (userId < 0) { 2490 throw new IllegalArgumentException("Invalid userId " + userId); 2491 } 2492 if (checkShell) { 2493 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2494 } 2495 if (userId == UserHandle.getUserId(callingUid)) return; 2496 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2497 if (requireFullPermission) { 2498 mContext.enforceCallingOrSelfPermission( 2499 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2500 } else { 2501 try { 2502 mContext.enforceCallingOrSelfPermission( 2503 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2504 } catch (SecurityException se) { 2505 mContext.enforceCallingOrSelfPermission( 2506 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2507 } 2508 } 2509 } 2510 } 2511 2512 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2513 if (callingUid == Process.SHELL_UID) { 2514 if (userHandle >= 0 2515 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2516 throw new SecurityException("Shell does not have permission to access user " 2517 + userHandle); 2518 } else if (userHandle < 0) { 2519 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2520 + Debug.getCallers(3)); 2521 } 2522 } 2523 } 2524 2525 private BasePermission findPermissionTreeLP(String permName) { 2526 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2527 if (permName.startsWith(bp.name) && 2528 permName.length() > bp.name.length() && 2529 permName.charAt(bp.name.length()) == '.') { 2530 return bp; 2531 } 2532 } 2533 return null; 2534 } 2535 2536 private BasePermission checkPermissionTreeLP(String permName) { 2537 if (permName != null) { 2538 BasePermission bp = findPermissionTreeLP(permName); 2539 if (bp != null) { 2540 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2541 return bp; 2542 } 2543 throw new SecurityException("Calling uid " 2544 + Binder.getCallingUid() 2545 + " is not allowed to add to permission tree " 2546 + bp.name + " owned by uid " + bp.uid); 2547 } 2548 } 2549 throw new SecurityException("No permission tree found for " + permName); 2550 } 2551 2552 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2553 if (s1 == null) { 2554 return s2 == null; 2555 } 2556 if (s2 == null) { 2557 return false; 2558 } 2559 if (s1.getClass() != s2.getClass()) { 2560 return false; 2561 } 2562 return s1.equals(s2); 2563 } 2564 2565 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2566 if (pi1.icon != pi2.icon) return false; 2567 if (pi1.logo != pi2.logo) return false; 2568 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2569 if (!compareStrings(pi1.name, pi2.name)) return false; 2570 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2571 // We'll take care of setting this one. 2572 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2573 // These are not currently stored in settings. 2574 //if (!compareStrings(pi1.group, pi2.group)) return false; 2575 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2576 //if (pi1.labelRes != pi2.labelRes) return false; 2577 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2578 return true; 2579 } 2580 2581 int permissionInfoFootprint(PermissionInfo info) { 2582 int size = info.name.length(); 2583 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2584 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2585 return size; 2586 } 2587 2588 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2589 int size = 0; 2590 for (BasePermission perm : mSettings.mPermissions.values()) { 2591 if (perm.uid == tree.uid) { 2592 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2593 } 2594 } 2595 return size; 2596 } 2597 2598 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2599 // We calculate the max size of permissions defined by this uid and throw 2600 // if that plus the size of 'info' would exceed our stated maximum. 2601 if (tree.uid != Process.SYSTEM_UID) { 2602 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2603 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2604 throw new SecurityException("Permission tree size cap exceeded"); 2605 } 2606 } 2607 } 2608 2609 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2610 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2611 throw new SecurityException("Label must be specified in permission"); 2612 } 2613 BasePermission tree = checkPermissionTreeLP(info.name); 2614 BasePermission bp = mSettings.mPermissions.get(info.name); 2615 boolean added = bp == null; 2616 boolean changed = true; 2617 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2618 if (added) { 2619 enforcePermissionCapLocked(info, tree); 2620 bp = new BasePermission(info.name, tree.sourcePackage, 2621 BasePermission.TYPE_DYNAMIC); 2622 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2623 throw new SecurityException( 2624 "Not allowed to modify non-dynamic permission " 2625 + info.name); 2626 } else { 2627 if (bp.protectionLevel == fixedLevel 2628 && bp.perm.owner.equals(tree.perm.owner) 2629 && bp.uid == tree.uid 2630 && comparePermissionInfos(bp.perm.info, info)) { 2631 changed = false; 2632 } 2633 } 2634 bp.protectionLevel = fixedLevel; 2635 info = new PermissionInfo(info); 2636 info.protectionLevel = fixedLevel; 2637 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2638 bp.perm.info.packageName = tree.perm.info.packageName; 2639 bp.uid = tree.uid; 2640 if (added) { 2641 mSettings.mPermissions.put(info.name, bp); 2642 } 2643 if (changed) { 2644 if (!async) { 2645 mSettings.writeLPr(); 2646 } else { 2647 scheduleWriteSettingsLocked(); 2648 } 2649 } 2650 return added; 2651 } 2652 2653 @Override 2654 public boolean addPermission(PermissionInfo info) { 2655 synchronized (mPackages) { 2656 return addPermissionLocked(info, false); 2657 } 2658 } 2659 2660 @Override 2661 public boolean addPermissionAsync(PermissionInfo info) { 2662 synchronized (mPackages) { 2663 return addPermissionLocked(info, true); 2664 } 2665 } 2666 2667 @Override 2668 public void removePermission(String name) { 2669 synchronized (mPackages) { 2670 checkPermissionTreeLP(name); 2671 BasePermission bp = mSettings.mPermissions.get(name); 2672 if (bp != null) { 2673 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2674 throw new SecurityException( 2675 "Not allowed to modify non-dynamic permission " 2676 + name); 2677 } 2678 mSettings.mPermissions.remove(name); 2679 mSettings.writeLPr(); 2680 } 2681 } 2682 } 2683 2684 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 2685 BasePermission bp) { 2686 int index = pkg.requestedPermissions.indexOf(bp.name); 2687 if (index == -1) { 2688 throw new SecurityException("Package " + pkg.packageName 2689 + " has not requested permission " + bp.name); 2690 } 2691 if (!bp.isRuntime()) { 2692 throw new SecurityException("Permission " + bp.name 2693 + " is not a changeable permission type"); 2694 } 2695 } 2696 2697 @Override 2698 public boolean grantPermission(String packageName, String name, int userId) { 2699 if (!sUserManager.exists(userId)) { 2700 return false; 2701 } 2702 2703 mContext.enforceCallingOrSelfPermission( 2704 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 2705 "grantPermission"); 2706 2707 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 2708 "grantPermission"); 2709 2710 synchronized (mPackages) { 2711 final PackageParser.Package pkg = mPackages.get(packageName); 2712 if (pkg == null) { 2713 throw new IllegalArgumentException("Unknown package: " + packageName); 2714 } 2715 2716 final BasePermission bp = mSettings.mPermissions.get(name); 2717 if (bp == null) { 2718 throw new IllegalArgumentException("Unknown permission: " + name); 2719 } 2720 2721 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 2722 2723 final SettingBase sb = (SettingBase) pkg.mExtras; 2724 if (sb == null) { 2725 throw new IllegalArgumentException("Unknown package: " + packageName); 2726 } 2727 2728 final PermissionsState permissionsState = sb.getPermissionsState(); 2729 2730 final int result = permissionsState.grantRuntimePermission(bp, userId); 2731 switch (result) { 2732 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 2733 return false; 2734 } 2735 2736 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 2737 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 2738 } break; 2739 } 2740 2741 // Not critical if that is lost - app has to request again. 2742 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 2743 2744 return true; 2745 } 2746 } 2747 2748 @Override 2749 public boolean revokePermission(String packageName, String name, int userId) { 2750 if (!sUserManager.exists(userId)) { 2751 return false; 2752 } 2753 2754 mContext.enforceCallingOrSelfPermission( 2755 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 2756 "revokePermission"); 2757 2758 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 2759 "revokePermission"); 2760 2761 synchronized (mPackages) { 2762 final PackageParser.Package pkg = mPackages.get(packageName); 2763 if (pkg == null) { 2764 throw new IllegalArgumentException("Unknown package: " + packageName); 2765 } 2766 2767 final BasePermission bp = mSettings.mPermissions.get(name); 2768 if (bp == null) { 2769 throw new IllegalArgumentException("Unknown permission: " + name); 2770 } 2771 2772 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 2773 2774 final SettingBase sb = (SettingBase) pkg.mExtras; 2775 if (sb == null) { 2776 throw new IllegalArgumentException("Unknown package: " + packageName); 2777 } 2778 2779 final PermissionsState permissionsState = sb.getPermissionsState(); 2780 2781 if (permissionsState.revokeRuntimePermission(bp, userId) == 2782 PermissionsState.PERMISSION_OPERATION_FAILURE) { 2783 return false; 2784 } 2785 2786 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 2787 2788 // Critical, after this call all should never have the permission. 2789 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 2790 2791 return true; 2792 } 2793 } 2794 2795 @Override 2796 public boolean isProtectedBroadcast(String actionName) { 2797 synchronized (mPackages) { 2798 return mProtectedBroadcasts.contains(actionName); 2799 } 2800 } 2801 2802 @Override 2803 public int checkSignatures(String pkg1, String pkg2) { 2804 synchronized (mPackages) { 2805 final PackageParser.Package p1 = mPackages.get(pkg1); 2806 final PackageParser.Package p2 = mPackages.get(pkg2); 2807 if (p1 == null || p1.mExtras == null 2808 || p2 == null || p2.mExtras == null) { 2809 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2810 } 2811 return compareSignatures(p1.mSignatures, p2.mSignatures); 2812 } 2813 } 2814 2815 @Override 2816 public int checkUidSignatures(int uid1, int uid2) { 2817 // Map to base uids. 2818 uid1 = UserHandle.getAppId(uid1); 2819 uid2 = UserHandle.getAppId(uid2); 2820 // reader 2821 synchronized (mPackages) { 2822 Signature[] s1; 2823 Signature[] s2; 2824 Object obj = mSettings.getUserIdLPr(uid1); 2825 if (obj != null) { 2826 if (obj instanceof SharedUserSetting) { 2827 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2828 } else if (obj instanceof PackageSetting) { 2829 s1 = ((PackageSetting)obj).signatures.mSignatures; 2830 } else { 2831 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2832 } 2833 } else { 2834 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2835 } 2836 obj = mSettings.getUserIdLPr(uid2); 2837 if (obj != null) { 2838 if (obj instanceof SharedUserSetting) { 2839 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2840 } else if (obj instanceof PackageSetting) { 2841 s2 = ((PackageSetting)obj).signatures.mSignatures; 2842 } else { 2843 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2844 } 2845 } else { 2846 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2847 } 2848 return compareSignatures(s1, s2); 2849 } 2850 } 2851 2852 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 2853 final long identity = Binder.clearCallingIdentity(); 2854 try { 2855 if (sb instanceof SharedUserSetting) { 2856 SharedUserSetting sus = (SharedUserSetting) sb; 2857 final int packageCount = sus.packages.size(); 2858 for (int i = 0; i < packageCount; i++) { 2859 PackageSetting susPs = sus.packages.valueAt(i); 2860 if (userId == UserHandle.USER_ALL) { 2861 killApplication(susPs.pkg.packageName, susPs.appId, reason); 2862 } else { 2863 final int uid = UserHandle.getUid(userId, susPs.appId); 2864 killUid(uid, reason); 2865 } 2866 } 2867 } else if (sb instanceof PackageSetting) { 2868 PackageSetting ps = (PackageSetting) sb; 2869 if (userId == UserHandle.USER_ALL) { 2870 killApplication(ps.pkg.packageName, ps.appId, reason); 2871 } else { 2872 final int uid = UserHandle.getUid(userId, ps.appId); 2873 killUid(uid, reason); 2874 } 2875 } 2876 } finally { 2877 Binder.restoreCallingIdentity(identity); 2878 } 2879 } 2880 2881 private static void killUid(int uid, String reason) { 2882 IActivityManager am = ActivityManagerNative.getDefault(); 2883 if (am != null) { 2884 try { 2885 am.killUid(uid, reason); 2886 } catch (RemoteException e) { 2887 /* ignore - same process */ 2888 } 2889 } 2890 } 2891 2892 /** 2893 * Compares two sets of signatures. Returns: 2894 * <br /> 2895 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2896 * <br /> 2897 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2898 * <br /> 2899 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2900 * <br /> 2901 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2902 * <br /> 2903 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2904 */ 2905 static int compareSignatures(Signature[] s1, Signature[] s2) { 2906 if (s1 == null) { 2907 return s2 == null 2908 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2909 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2910 } 2911 2912 if (s2 == null) { 2913 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2914 } 2915 2916 if (s1.length != s2.length) { 2917 return PackageManager.SIGNATURE_NO_MATCH; 2918 } 2919 2920 // Since both signature sets are of size 1, we can compare without HashSets. 2921 if (s1.length == 1) { 2922 return s1[0].equals(s2[0]) ? 2923 PackageManager.SIGNATURE_MATCH : 2924 PackageManager.SIGNATURE_NO_MATCH; 2925 } 2926 2927 ArraySet<Signature> set1 = new ArraySet<Signature>(); 2928 for (Signature sig : s1) { 2929 set1.add(sig); 2930 } 2931 ArraySet<Signature> set2 = new ArraySet<Signature>(); 2932 for (Signature sig : s2) { 2933 set2.add(sig); 2934 } 2935 // Make sure s2 contains all signatures in s1. 2936 if (set1.equals(set2)) { 2937 return PackageManager.SIGNATURE_MATCH; 2938 } 2939 return PackageManager.SIGNATURE_NO_MATCH; 2940 } 2941 2942 /** 2943 * If the database version for this type of package (internal storage or 2944 * external storage) is less than the version where package signatures 2945 * were updated, return true. 2946 */ 2947 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2948 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2949 DatabaseVersion.SIGNATURE_END_ENTITY)) 2950 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2951 DatabaseVersion.SIGNATURE_END_ENTITY)); 2952 } 2953 2954 /** 2955 * Used for backward compatibility to make sure any packages with 2956 * certificate chains get upgraded to the new style. {@code existingSigs} 2957 * will be in the old format (since they were stored on disk from before the 2958 * system upgrade) and {@code scannedSigs} will be in the newer format. 2959 */ 2960 private int compareSignaturesCompat(PackageSignatures existingSigs, 2961 PackageParser.Package scannedPkg) { 2962 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2963 return PackageManager.SIGNATURE_NO_MATCH; 2964 } 2965 2966 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 2967 for (Signature sig : existingSigs.mSignatures) { 2968 existingSet.add(sig); 2969 } 2970 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 2971 for (Signature sig : scannedPkg.mSignatures) { 2972 try { 2973 Signature[] chainSignatures = sig.getChainSignatures(); 2974 for (Signature chainSig : chainSignatures) { 2975 scannedCompatSet.add(chainSig); 2976 } 2977 } catch (CertificateEncodingException e) { 2978 scannedCompatSet.add(sig); 2979 } 2980 } 2981 /* 2982 * Make sure the expanded scanned set contains all signatures in the 2983 * existing one. 2984 */ 2985 if (scannedCompatSet.equals(existingSet)) { 2986 // Migrate the old signatures to the new scheme. 2987 existingSigs.assignSignatures(scannedPkg.mSignatures); 2988 // The new KeySets will be re-added later in the scanning process. 2989 synchronized (mPackages) { 2990 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2991 } 2992 return PackageManager.SIGNATURE_MATCH; 2993 } 2994 return PackageManager.SIGNATURE_NO_MATCH; 2995 } 2996 2997 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2998 if (isExternal(scannedPkg)) { 2999 return mSettings.isExternalDatabaseVersionOlderThan( 3000 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3001 } else { 3002 return mSettings.isInternalDatabaseVersionOlderThan( 3003 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3004 } 3005 } 3006 3007 private int compareSignaturesRecover(PackageSignatures existingSigs, 3008 PackageParser.Package scannedPkg) { 3009 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3010 return PackageManager.SIGNATURE_NO_MATCH; 3011 } 3012 3013 String msg = null; 3014 try { 3015 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3016 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3017 + scannedPkg.packageName); 3018 return PackageManager.SIGNATURE_MATCH; 3019 } 3020 } catch (CertificateException e) { 3021 msg = e.getMessage(); 3022 } 3023 3024 logCriticalInfo(Log.INFO, 3025 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3026 return PackageManager.SIGNATURE_NO_MATCH; 3027 } 3028 3029 @Override 3030 public String[] getPackagesForUid(int uid) { 3031 uid = UserHandle.getAppId(uid); 3032 // reader 3033 synchronized (mPackages) { 3034 Object obj = mSettings.getUserIdLPr(uid); 3035 if (obj instanceof SharedUserSetting) { 3036 final SharedUserSetting sus = (SharedUserSetting) obj; 3037 final int N = sus.packages.size(); 3038 final String[] res = new String[N]; 3039 final Iterator<PackageSetting> it = sus.packages.iterator(); 3040 int i = 0; 3041 while (it.hasNext()) { 3042 res[i++] = it.next().name; 3043 } 3044 return res; 3045 } else if (obj instanceof PackageSetting) { 3046 final PackageSetting ps = (PackageSetting) obj; 3047 return new String[] { ps.name }; 3048 } 3049 } 3050 return null; 3051 } 3052 3053 @Override 3054 public String getNameForUid(int uid) { 3055 // reader 3056 synchronized (mPackages) { 3057 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3058 if (obj instanceof SharedUserSetting) { 3059 final SharedUserSetting sus = (SharedUserSetting) obj; 3060 return sus.name + ":" + sus.userId; 3061 } else if (obj instanceof PackageSetting) { 3062 final PackageSetting ps = (PackageSetting) obj; 3063 return ps.name; 3064 } 3065 } 3066 return null; 3067 } 3068 3069 @Override 3070 public int getUidForSharedUser(String sharedUserName) { 3071 if(sharedUserName == null) { 3072 return -1; 3073 } 3074 // reader 3075 synchronized (mPackages) { 3076 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3077 if (suid == null) { 3078 return -1; 3079 } 3080 return suid.userId; 3081 } 3082 } 3083 3084 @Override 3085 public int getFlagsForUid(int uid) { 3086 synchronized (mPackages) { 3087 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3088 if (obj instanceof SharedUserSetting) { 3089 final SharedUserSetting sus = (SharedUserSetting) obj; 3090 return sus.pkgFlags; 3091 } else if (obj instanceof PackageSetting) { 3092 final PackageSetting ps = (PackageSetting) obj; 3093 return ps.pkgFlags; 3094 } 3095 } 3096 return 0; 3097 } 3098 3099 @Override 3100 public int getPrivateFlagsForUid(int uid) { 3101 synchronized (mPackages) { 3102 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3103 if (obj instanceof SharedUserSetting) { 3104 final SharedUserSetting sus = (SharedUserSetting) obj; 3105 return sus.pkgPrivateFlags; 3106 } else if (obj instanceof PackageSetting) { 3107 final PackageSetting ps = (PackageSetting) obj; 3108 return ps.pkgPrivateFlags; 3109 } 3110 } 3111 return 0; 3112 } 3113 3114 @Override 3115 public boolean isUidPrivileged(int uid) { 3116 uid = UserHandle.getAppId(uid); 3117 // reader 3118 synchronized (mPackages) { 3119 Object obj = mSettings.getUserIdLPr(uid); 3120 if (obj instanceof SharedUserSetting) { 3121 final SharedUserSetting sus = (SharedUserSetting) obj; 3122 final Iterator<PackageSetting> it = sus.packages.iterator(); 3123 while (it.hasNext()) { 3124 if (it.next().isPrivileged()) { 3125 return true; 3126 } 3127 } 3128 } else if (obj instanceof PackageSetting) { 3129 final PackageSetting ps = (PackageSetting) obj; 3130 return ps.isPrivileged(); 3131 } 3132 } 3133 return false; 3134 } 3135 3136 @Override 3137 public String[] getAppOpPermissionPackages(String permissionName) { 3138 synchronized (mPackages) { 3139 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3140 if (pkgs == null) { 3141 return null; 3142 } 3143 return pkgs.toArray(new String[pkgs.size()]); 3144 } 3145 } 3146 3147 @Override 3148 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3149 int flags, int userId) { 3150 if (!sUserManager.exists(userId)) return null; 3151 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3152 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3153 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3154 } 3155 3156 @Override 3157 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3158 IntentFilter filter, int match, ComponentName activity) { 3159 final int userId = UserHandle.getCallingUserId(); 3160 if (DEBUG_PREFERRED) { 3161 Log.v(TAG, "setLastChosenActivity intent=" + intent 3162 + " resolvedType=" + resolvedType 3163 + " flags=" + flags 3164 + " filter=" + filter 3165 + " match=" + match 3166 + " activity=" + activity); 3167 filter.dump(new PrintStreamPrinter(System.out), " "); 3168 } 3169 intent.setComponent(null); 3170 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3171 // Find any earlier preferred or last chosen entries and nuke them 3172 findPreferredActivity(intent, resolvedType, 3173 flags, query, 0, false, true, false, userId); 3174 // Add the new activity as the last chosen for this filter 3175 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3176 "Setting last chosen"); 3177 } 3178 3179 @Override 3180 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3181 final int userId = UserHandle.getCallingUserId(); 3182 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3183 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3184 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3185 false, false, false, userId); 3186 } 3187 3188 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3189 int flags, List<ResolveInfo> query, int userId) { 3190 if (query != null) { 3191 final int N = query.size(); 3192 if (N == 1) { 3193 return query.get(0); 3194 } else if (N > 1) { 3195 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3196 // If there is more than one activity with the same priority, 3197 // then let the user decide between them. 3198 ResolveInfo r0 = query.get(0); 3199 ResolveInfo r1 = query.get(1); 3200 if (DEBUG_INTENT_MATCHING || debug) { 3201 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3202 + r1.activityInfo.name + "=" + r1.priority); 3203 } 3204 // If the first activity has a higher priority, or a different 3205 // default, then it is always desireable to pick it. 3206 if (r0.priority != r1.priority 3207 || r0.preferredOrder != r1.preferredOrder 3208 || r0.isDefault != r1.isDefault) { 3209 return query.get(0); 3210 } 3211 // If we have saved a preference for a preferred activity for 3212 // this Intent, use that. 3213 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3214 flags, query, r0.priority, true, false, debug, userId); 3215 if (ri != null) { 3216 return ri; 3217 } 3218 if (userId != 0) { 3219 ri = new ResolveInfo(mResolveInfo); 3220 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3221 ri.activityInfo.applicationInfo = new ApplicationInfo( 3222 ri.activityInfo.applicationInfo); 3223 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3224 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3225 return ri; 3226 } 3227 return mResolveInfo; 3228 } 3229 } 3230 return null; 3231 } 3232 3233 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3234 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3235 final int N = query.size(); 3236 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3237 .get(userId); 3238 // Get the list of persistent preferred activities that handle the intent 3239 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3240 List<PersistentPreferredActivity> pprefs = ppir != null 3241 ? ppir.queryIntent(intent, resolvedType, 3242 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3243 : null; 3244 if (pprefs != null && pprefs.size() > 0) { 3245 final int M = pprefs.size(); 3246 for (int i=0; i<M; i++) { 3247 final PersistentPreferredActivity ppa = pprefs.get(i); 3248 if (DEBUG_PREFERRED || debug) { 3249 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3250 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3251 + "\n component=" + ppa.mComponent); 3252 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3253 } 3254 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3255 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3256 if (DEBUG_PREFERRED || debug) { 3257 Slog.v(TAG, "Found persistent preferred activity:"); 3258 if (ai != null) { 3259 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3260 } else { 3261 Slog.v(TAG, " null"); 3262 } 3263 } 3264 if (ai == null) { 3265 // This previously registered persistent preferred activity 3266 // component is no longer known. Ignore it and do NOT remove it. 3267 continue; 3268 } 3269 for (int j=0; j<N; j++) { 3270 final ResolveInfo ri = query.get(j); 3271 if (!ri.activityInfo.applicationInfo.packageName 3272 .equals(ai.applicationInfo.packageName)) { 3273 continue; 3274 } 3275 if (!ri.activityInfo.name.equals(ai.name)) { 3276 continue; 3277 } 3278 // Found a persistent preference that can handle the intent. 3279 if (DEBUG_PREFERRED || debug) { 3280 Slog.v(TAG, "Returning persistent preferred activity: " + 3281 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3282 } 3283 return ri; 3284 } 3285 } 3286 } 3287 return null; 3288 } 3289 3290 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3291 List<ResolveInfo> query, int priority, boolean always, 3292 boolean removeMatches, boolean debug, int userId) { 3293 if (!sUserManager.exists(userId)) return null; 3294 // writer 3295 synchronized (mPackages) { 3296 if (intent.getSelector() != null) { 3297 intent = intent.getSelector(); 3298 } 3299 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3300 3301 // Try to find a matching persistent preferred activity. 3302 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3303 debug, userId); 3304 3305 // If a persistent preferred activity matched, use it. 3306 if (pri != null) { 3307 return pri; 3308 } 3309 3310 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3311 // Get the list of preferred activities that handle the intent 3312 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3313 List<PreferredActivity> prefs = pir != null 3314 ? pir.queryIntent(intent, resolvedType, 3315 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3316 : null; 3317 if (prefs != null && prefs.size() > 0) { 3318 boolean changed = false; 3319 try { 3320 // First figure out how good the original match set is. 3321 // We will only allow preferred activities that came 3322 // from the same match quality. 3323 int match = 0; 3324 3325 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3326 3327 final int N = query.size(); 3328 for (int j=0; j<N; j++) { 3329 final ResolveInfo ri = query.get(j); 3330 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3331 + ": 0x" + Integer.toHexString(match)); 3332 if (ri.match > match) { 3333 match = ri.match; 3334 } 3335 } 3336 3337 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3338 + Integer.toHexString(match)); 3339 3340 match &= IntentFilter.MATCH_CATEGORY_MASK; 3341 final int M = prefs.size(); 3342 for (int i=0; i<M; i++) { 3343 final PreferredActivity pa = prefs.get(i); 3344 if (DEBUG_PREFERRED || debug) { 3345 Slog.v(TAG, "Checking PreferredActivity ds=" 3346 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3347 + "\n component=" + pa.mPref.mComponent); 3348 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3349 } 3350 if (pa.mPref.mMatch != match) { 3351 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3352 + Integer.toHexString(pa.mPref.mMatch)); 3353 continue; 3354 } 3355 // If it's not an "always" type preferred activity and that's what we're 3356 // looking for, skip it. 3357 if (always && !pa.mPref.mAlways) { 3358 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3359 continue; 3360 } 3361 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3362 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3363 if (DEBUG_PREFERRED || debug) { 3364 Slog.v(TAG, "Found preferred activity:"); 3365 if (ai != null) { 3366 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3367 } else { 3368 Slog.v(TAG, " null"); 3369 } 3370 } 3371 if (ai == null) { 3372 // This previously registered preferred activity 3373 // component is no longer known. Most likely an update 3374 // to the app was installed and in the new version this 3375 // component no longer exists. Clean it up by removing 3376 // it from the preferred activities list, and skip it. 3377 Slog.w(TAG, "Removing dangling preferred activity: " 3378 + pa.mPref.mComponent); 3379 pir.removeFilter(pa); 3380 changed = true; 3381 continue; 3382 } 3383 for (int j=0; j<N; j++) { 3384 final ResolveInfo ri = query.get(j); 3385 if (!ri.activityInfo.applicationInfo.packageName 3386 .equals(ai.applicationInfo.packageName)) { 3387 continue; 3388 } 3389 if (!ri.activityInfo.name.equals(ai.name)) { 3390 continue; 3391 } 3392 3393 if (removeMatches) { 3394 pir.removeFilter(pa); 3395 changed = true; 3396 if (DEBUG_PREFERRED) { 3397 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3398 } 3399 break; 3400 } 3401 3402 // Okay we found a previously set preferred or last chosen app. 3403 // If the result set is different from when this 3404 // was created, we need to clear it and re-ask the 3405 // user their preference, if we're looking for an "always" type entry. 3406 if (always && !pa.mPref.sameSet(query)) { 3407 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3408 + intent + " type " + resolvedType); 3409 if (DEBUG_PREFERRED) { 3410 Slog.v(TAG, "Removing preferred activity since set changed " 3411 + pa.mPref.mComponent); 3412 } 3413 pir.removeFilter(pa); 3414 // Re-add the filter as a "last chosen" entry (!always) 3415 PreferredActivity lastChosen = new PreferredActivity( 3416 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3417 pir.addFilter(lastChosen); 3418 changed = true; 3419 return null; 3420 } 3421 3422 // Yay! Either the set matched or we're looking for the last chosen 3423 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3424 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3425 return ri; 3426 } 3427 } 3428 } finally { 3429 if (changed) { 3430 if (DEBUG_PREFERRED) { 3431 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3432 } 3433 scheduleWritePackageRestrictionsLocked(userId); 3434 } 3435 } 3436 } 3437 } 3438 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3439 return null; 3440 } 3441 3442 /* 3443 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3444 */ 3445 @Override 3446 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3447 int targetUserId) { 3448 mContext.enforceCallingOrSelfPermission( 3449 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3450 List<CrossProfileIntentFilter> matches = 3451 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3452 if (matches != null) { 3453 int size = matches.size(); 3454 for (int i = 0; i < size; i++) { 3455 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3456 } 3457 } 3458 return false; 3459 } 3460 3461 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3462 String resolvedType, int userId) { 3463 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3464 if (resolver != null) { 3465 return resolver.queryIntent(intent, resolvedType, false, userId); 3466 } 3467 return null; 3468 } 3469 3470 @Override 3471 public List<ResolveInfo> queryIntentActivities(Intent intent, 3472 String resolvedType, int flags, int userId) { 3473 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3474 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3475 ComponentName comp = intent.getComponent(); 3476 if (comp == null) { 3477 if (intent.getSelector() != null) { 3478 intent = intent.getSelector(); 3479 comp = intent.getComponent(); 3480 } 3481 } 3482 3483 if (comp != null) { 3484 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3485 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3486 if (ai != null) { 3487 final ResolveInfo ri = new ResolveInfo(); 3488 ri.activityInfo = ai; 3489 list.add(ri); 3490 } 3491 return list; 3492 } 3493 3494 // reader 3495 synchronized (mPackages) { 3496 final String pkgName = intent.getPackage(); 3497 if (pkgName == null) { 3498 List<CrossProfileIntentFilter> matchingFilters = 3499 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3500 // Check for results that need to skip the current profile. 3501 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3502 resolvedType, flags, userId); 3503 if (resolveInfo != null) { 3504 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3505 result.add(resolveInfo); 3506 return filterIfNotPrimaryUser(result, userId); 3507 } 3508 // Check for cross profile results. 3509 resolveInfo = queryCrossProfileIntents( 3510 matchingFilters, intent, resolvedType, flags, userId); 3511 3512 // Check for results in the current profile. 3513 List<ResolveInfo> result = mActivities.queryIntent( 3514 intent, resolvedType, flags, userId); 3515 if (resolveInfo != null) { 3516 result.add(resolveInfo); 3517 Collections.sort(result, mResolvePrioritySorter); 3518 } 3519 return filterIfNotPrimaryUser(result, userId); 3520 } 3521 final PackageParser.Package pkg = mPackages.get(pkgName); 3522 if (pkg != null) { 3523 return filterIfNotPrimaryUser( 3524 mActivities.queryIntentForPackage( 3525 intent, resolvedType, flags, pkg.activities, userId), 3526 userId); 3527 } 3528 return new ArrayList<ResolveInfo>(); 3529 } 3530 } 3531 3532 /** 3533 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3534 * 3535 * @return filtered list 3536 */ 3537 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3538 if (userId == UserHandle.USER_OWNER) { 3539 return resolveInfos; 3540 } 3541 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 3542 ResolveInfo info = resolveInfos.get(i); 3543 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 3544 resolveInfos.remove(i); 3545 } 3546 } 3547 return resolveInfos; 3548 } 3549 3550 3551 private ResolveInfo querySkipCurrentProfileIntents( 3552 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3553 int flags, int sourceUserId) { 3554 if (matchingFilters != null) { 3555 int size = matchingFilters.size(); 3556 for (int i = 0; i < size; i ++) { 3557 CrossProfileIntentFilter filter = matchingFilters.get(i); 3558 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3559 // Checking if there are activities in the target user that can handle the 3560 // intent. 3561 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3562 flags, sourceUserId); 3563 if (resolveInfo != null) { 3564 return resolveInfo; 3565 } 3566 } 3567 } 3568 } 3569 return null; 3570 } 3571 3572 // Return matching ResolveInfo if any for skip current profile intent filters. 3573 private ResolveInfo queryCrossProfileIntents( 3574 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3575 int flags, int sourceUserId) { 3576 if (matchingFilters != null) { 3577 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3578 // match the same intent. For performance reasons, it is better not to 3579 // run queryIntent twice for the same userId 3580 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3581 int size = matchingFilters.size(); 3582 for (int i = 0; i < size; i++) { 3583 CrossProfileIntentFilter filter = matchingFilters.get(i); 3584 int targetUserId = filter.getTargetUserId(); 3585 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3586 && !alreadyTriedUserIds.get(targetUserId)) { 3587 // Checking if there are activities in the target user that can handle the 3588 // intent. 3589 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3590 flags, sourceUserId); 3591 if (resolveInfo != null) return resolveInfo; 3592 alreadyTriedUserIds.put(targetUserId, true); 3593 } 3594 } 3595 } 3596 return null; 3597 } 3598 3599 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3600 String resolvedType, int flags, int sourceUserId) { 3601 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3602 resolvedType, flags, filter.getTargetUserId()); 3603 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3604 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3605 } 3606 return null; 3607 } 3608 3609 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3610 int sourceUserId, int targetUserId) { 3611 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3612 String className; 3613 if (targetUserId == UserHandle.USER_OWNER) { 3614 className = FORWARD_INTENT_TO_USER_OWNER; 3615 } else { 3616 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3617 } 3618 ComponentName forwardingActivityComponentName = new ComponentName( 3619 mAndroidApplication.packageName, className); 3620 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3621 sourceUserId); 3622 if (targetUserId == UserHandle.USER_OWNER) { 3623 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3624 forwardingResolveInfo.noResourceId = true; 3625 } 3626 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3627 forwardingResolveInfo.priority = 0; 3628 forwardingResolveInfo.preferredOrder = 0; 3629 forwardingResolveInfo.match = 0; 3630 forwardingResolveInfo.isDefault = true; 3631 forwardingResolveInfo.filter = filter; 3632 forwardingResolveInfo.targetUserId = targetUserId; 3633 return forwardingResolveInfo; 3634 } 3635 3636 @Override 3637 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3638 Intent[] specifics, String[] specificTypes, Intent intent, 3639 String resolvedType, int flags, int userId) { 3640 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3641 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3642 false, "query intent activity options"); 3643 final String resultsAction = intent.getAction(); 3644 3645 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3646 | PackageManager.GET_RESOLVED_FILTER, userId); 3647 3648 if (DEBUG_INTENT_MATCHING) { 3649 Log.v(TAG, "Query " + intent + ": " + results); 3650 } 3651 3652 int specificsPos = 0; 3653 int N; 3654 3655 // todo: note that the algorithm used here is O(N^2). This 3656 // isn't a problem in our current environment, but if we start running 3657 // into situations where we have more than 5 or 10 matches then this 3658 // should probably be changed to something smarter... 3659 3660 // First we go through and resolve each of the specific items 3661 // that were supplied, taking care of removing any corresponding 3662 // duplicate items in the generic resolve list. 3663 if (specifics != null) { 3664 for (int i=0; i<specifics.length; i++) { 3665 final Intent sintent = specifics[i]; 3666 if (sintent == null) { 3667 continue; 3668 } 3669 3670 if (DEBUG_INTENT_MATCHING) { 3671 Log.v(TAG, "Specific #" + i + ": " + sintent); 3672 } 3673 3674 String action = sintent.getAction(); 3675 if (resultsAction != null && resultsAction.equals(action)) { 3676 // If this action was explicitly requested, then don't 3677 // remove things that have it. 3678 action = null; 3679 } 3680 3681 ResolveInfo ri = null; 3682 ActivityInfo ai = null; 3683 3684 ComponentName comp = sintent.getComponent(); 3685 if (comp == null) { 3686 ri = resolveIntent( 3687 sintent, 3688 specificTypes != null ? specificTypes[i] : null, 3689 flags, userId); 3690 if (ri == null) { 3691 continue; 3692 } 3693 if (ri == mResolveInfo) { 3694 // ACK! Must do something better with this. 3695 } 3696 ai = ri.activityInfo; 3697 comp = new ComponentName(ai.applicationInfo.packageName, 3698 ai.name); 3699 } else { 3700 ai = getActivityInfo(comp, flags, userId); 3701 if (ai == null) { 3702 continue; 3703 } 3704 } 3705 3706 // Look for any generic query activities that are duplicates 3707 // of this specific one, and remove them from the results. 3708 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3709 N = results.size(); 3710 int j; 3711 for (j=specificsPos; j<N; j++) { 3712 ResolveInfo sri = results.get(j); 3713 if ((sri.activityInfo.name.equals(comp.getClassName()) 3714 && sri.activityInfo.applicationInfo.packageName.equals( 3715 comp.getPackageName())) 3716 || (action != null && sri.filter.matchAction(action))) { 3717 results.remove(j); 3718 if (DEBUG_INTENT_MATCHING) Log.v( 3719 TAG, "Removing duplicate item from " + j 3720 + " due to specific " + specificsPos); 3721 if (ri == null) { 3722 ri = sri; 3723 } 3724 j--; 3725 N--; 3726 } 3727 } 3728 3729 // Add this specific item to its proper place. 3730 if (ri == null) { 3731 ri = new ResolveInfo(); 3732 ri.activityInfo = ai; 3733 } 3734 results.add(specificsPos, ri); 3735 ri.specificIndex = i; 3736 specificsPos++; 3737 } 3738 } 3739 3740 // Now we go through the remaining generic results and remove any 3741 // duplicate actions that are found here. 3742 N = results.size(); 3743 for (int i=specificsPos; i<N-1; i++) { 3744 final ResolveInfo rii = results.get(i); 3745 if (rii.filter == null) { 3746 continue; 3747 } 3748 3749 // Iterate over all of the actions of this result's intent 3750 // filter... typically this should be just one. 3751 final Iterator<String> it = rii.filter.actionsIterator(); 3752 if (it == null) { 3753 continue; 3754 } 3755 while (it.hasNext()) { 3756 final String action = it.next(); 3757 if (resultsAction != null && resultsAction.equals(action)) { 3758 // If this action was explicitly requested, then don't 3759 // remove things that have it. 3760 continue; 3761 } 3762 for (int j=i+1; j<N; j++) { 3763 final ResolveInfo rij = results.get(j); 3764 if (rij.filter != null && rij.filter.hasAction(action)) { 3765 results.remove(j); 3766 if (DEBUG_INTENT_MATCHING) Log.v( 3767 TAG, "Removing duplicate item from " + j 3768 + " due to action " + action + " at " + i); 3769 j--; 3770 N--; 3771 } 3772 } 3773 } 3774 3775 // If the caller didn't request filter information, drop it now 3776 // so we don't have to marshall/unmarshall it. 3777 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3778 rii.filter = null; 3779 } 3780 } 3781 3782 // Filter out the caller activity if so requested. 3783 if (caller != null) { 3784 N = results.size(); 3785 for (int i=0; i<N; i++) { 3786 ActivityInfo ainfo = results.get(i).activityInfo; 3787 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3788 && caller.getClassName().equals(ainfo.name)) { 3789 results.remove(i); 3790 break; 3791 } 3792 } 3793 } 3794 3795 // If the caller didn't request filter information, 3796 // drop them now so we don't have to 3797 // marshall/unmarshall it. 3798 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3799 N = results.size(); 3800 for (int i=0; i<N; i++) { 3801 results.get(i).filter = null; 3802 } 3803 } 3804 3805 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3806 return results; 3807 } 3808 3809 @Override 3810 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3811 int userId) { 3812 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3813 ComponentName comp = intent.getComponent(); 3814 if (comp == null) { 3815 if (intent.getSelector() != null) { 3816 intent = intent.getSelector(); 3817 comp = intent.getComponent(); 3818 } 3819 } 3820 if (comp != null) { 3821 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3822 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3823 if (ai != null) { 3824 ResolveInfo ri = new ResolveInfo(); 3825 ri.activityInfo = ai; 3826 list.add(ri); 3827 } 3828 return list; 3829 } 3830 3831 // reader 3832 synchronized (mPackages) { 3833 String pkgName = intent.getPackage(); 3834 if (pkgName == null) { 3835 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3836 } 3837 final PackageParser.Package pkg = mPackages.get(pkgName); 3838 if (pkg != null) { 3839 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3840 userId); 3841 } 3842 return null; 3843 } 3844 } 3845 3846 @Override 3847 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3848 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3849 if (!sUserManager.exists(userId)) return null; 3850 if (query != null) { 3851 if (query.size() >= 1) { 3852 // If there is more than one service with the same priority, 3853 // just arbitrarily pick the first one. 3854 return query.get(0); 3855 } 3856 } 3857 return null; 3858 } 3859 3860 @Override 3861 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3862 int userId) { 3863 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3864 ComponentName comp = intent.getComponent(); 3865 if (comp == null) { 3866 if (intent.getSelector() != null) { 3867 intent = intent.getSelector(); 3868 comp = intent.getComponent(); 3869 } 3870 } 3871 if (comp != null) { 3872 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3873 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3874 if (si != null) { 3875 final ResolveInfo ri = new ResolveInfo(); 3876 ri.serviceInfo = si; 3877 list.add(ri); 3878 } 3879 return list; 3880 } 3881 3882 // reader 3883 synchronized (mPackages) { 3884 String pkgName = intent.getPackage(); 3885 if (pkgName == null) { 3886 return mServices.queryIntent(intent, resolvedType, flags, userId); 3887 } 3888 final PackageParser.Package pkg = mPackages.get(pkgName); 3889 if (pkg != null) { 3890 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3891 userId); 3892 } 3893 return null; 3894 } 3895 } 3896 3897 @Override 3898 public List<ResolveInfo> queryIntentContentProviders( 3899 Intent intent, String resolvedType, int flags, int userId) { 3900 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3901 ComponentName comp = intent.getComponent(); 3902 if (comp == null) { 3903 if (intent.getSelector() != null) { 3904 intent = intent.getSelector(); 3905 comp = intent.getComponent(); 3906 } 3907 } 3908 if (comp != null) { 3909 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3910 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3911 if (pi != null) { 3912 final ResolveInfo ri = new ResolveInfo(); 3913 ri.providerInfo = pi; 3914 list.add(ri); 3915 } 3916 return list; 3917 } 3918 3919 // reader 3920 synchronized (mPackages) { 3921 String pkgName = intent.getPackage(); 3922 if (pkgName == null) { 3923 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3924 } 3925 final PackageParser.Package pkg = mPackages.get(pkgName); 3926 if (pkg != null) { 3927 return mProviders.queryIntentForPackage( 3928 intent, resolvedType, flags, pkg.providers, userId); 3929 } 3930 return null; 3931 } 3932 } 3933 3934 @Override 3935 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3936 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3937 3938 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3939 3940 // writer 3941 synchronized (mPackages) { 3942 ArrayList<PackageInfo> list; 3943 if (listUninstalled) { 3944 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3945 for (PackageSetting ps : mSettings.mPackages.values()) { 3946 PackageInfo pi; 3947 if (ps.pkg != null) { 3948 pi = generatePackageInfo(ps.pkg, flags, userId); 3949 } else { 3950 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3951 } 3952 if (pi != null) { 3953 list.add(pi); 3954 } 3955 } 3956 } else { 3957 list = new ArrayList<PackageInfo>(mPackages.size()); 3958 for (PackageParser.Package p : mPackages.values()) { 3959 PackageInfo pi = generatePackageInfo(p, flags, userId); 3960 if (pi != null) { 3961 list.add(pi); 3962 } 3963 } 3964 } 3965 3966 return new ParceledListSlice<PackageInfo>(list); 3967 } 3968 } 3969 3970 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3971 String[] permissions, boolean[] tmp, int flags, int userId) { 3972 int numMatch = 0; 3973 final PermissionsState permissionsState = ps.getPermissionsState(); 3974 for (int i=0; i<permissions.length; i++) { 3975 final String permission = permissions[i]; 3976 if (permissionsState.hasPermission(permission, userId)) { 3977 tmp[i] = true; 3978 numMatch++; 3979 } else { 3980 tmp[i] = false; 3981 } 3982 } 3983 if (numMatch == 0) { 3984 return; 3985 } 3986 PackageInfo pi; 3987 if (ps.pkg != null) { 3988 pi = generatePackageInfo(ps.pkg, flags, userId); 3989 } else { 3990 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3991 } 3992 // The above might return null in cases of uninstalled apps or install-state 3993 // skew across users/profiles. 3994 if (pi != null) { 3995 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3996 if (numMatch == permissions.length) { 3997 pi.requestedPermissions = permissions; 3998 } else { 3999 pi.requestedPermissions = new String[numMatch]; 4000 numMatch = 0; 4001 for (int i=0; i<permissions.length; i++) { 4002 if (tmp[i]) { 4003 pi.requestedPermissions[numMatch] = permissions[i]; 4004 numMatch++; 4005 } 4006 } 4007 } 4008 } 4009 list.add(pi); 4010 } 4011 } 4012 4013 @Override 4014 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4015 String[] permissions, int flags, int userId) { 4016 if (!sUserManager.exists(userId)) return null; 4017 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4018 4019 // writer 4020 synchronized (mPackages) { 4021 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4022 boolean[] tmpBools = new boolean[permissions.length]; 4023 if (listUninstalled) { 4024 for (PackageSetting ps : mSettings.mPackages.values()) { 4025 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4026 } 4027 } else { 4028 for (PackageParser.Package pkg : mPackages.values()) { 4029 PackageSetting ps = (PackageSetting)pkg.mExtras; 4030 if (ps != null) { 4031 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4032 userId); 4033 } 4034 } 4035 } 4036 4037 return new ParceledListSlice<PackageInfo>(list); 4038 } 4039 } 4040 4041 @Override 4042 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4043 if (!sUserManager.exists(userId)) return null; 4044 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4045 4046 // writer 4047 synchronized (mPackages) { 4048 ArrayList<ApplicationInfo> list; 4049 if (listUninstalled) { 4050 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4051 for (PackageSetting ps : mSettings.mPackages.values()) { 4052 ApplicationInfo ai; 4053 if (ps.pkg != null) { 4054 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4055 ps.readUserState(userId), userId); 4056 } else { 4057 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4058 } 4059 if (ai != null) { 4060 list.add(ai); 4061 } 4062 } 4063 } else { 4064 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4065 for (PackageParser.Package p : mPackages.values()) { 4066 if (p.mExtras != null) { 4067 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4068 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4069 if (ai != null) { 4070 list.add(ai); 4071 } 4072 } 4073 } 4074 } 4075 4076 return new ParceledListSlice<ApplicationInfo>(list); 4077 } 4078 } 4079 4080 public List<ApplicationInfo> getPersistentApplications(int flags) { 4081 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4082 4083 // reader 4084 synchronized (mPackages) { 4085 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4086 final int userId = UserHandle.getCallingUserId(); 4087 while (i.hasNext()) { 4088 final PackageParser.Package p = i.next(); 4089 if (p.applicationInfo != null 4090 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4091 && (!mSafeMode || isSystemApp(p))) { 4092 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4093 if (ps != null) { 4094 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4095 ps.readUserState(userId), userId); 4096 if (ai != null) { 4097 finalList.add(ai); 4098 } 4099 } 4100 } 4101 } 4102 } 4103 4104 return finalList; 4105 } 4106 4107 @Override 4108 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4109 if (!sUserManager.exists(userId)) return null; 4110 // reader 4111 synchronized (mPackages) { 4112 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4113 PackageSetting ps = provider != null 4114 ? mSettings.mPackages.get(provider.owner.packageName) 4115 : null; 4116 return ps != null 4117 && mSettings.isEnabledLPr(provider.info, flags, userId) 4118 && (!mSafeMode || (provider.info.applicationInfo.flags 4119 &ApplicationInfo.FLAG_SYSTEM) != 0) 4120 ? PackageParser.generateProviderInfo(provider, flags, 4121 ps.readUserState(userId), userId) 4122 : null; 4123 } 4124 } 4125 4126 /** 4127 * @deprecated 4128 */ 4129 @Deprecated 4130 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4131 // reader 4132 synchronized (mPackages) { 4133 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4134 .entrySet().iterator(); 4135 final int userId = UserHandle.getCallingUserId(); 4136 while (i.hasNext()) { 4137 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4138 PackageParser.Provider p = entry.getValue(); 4139 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4140 4141 if (ps != null && p.syncable 4142 && (!mSafeMode || (p.info.applicationInfo.flags 4143 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4144 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4145 ps.readUserState(userId), userId); 4146 if (info != null) { 4147 outNames.add(entry.getKey()); 4148 outInfo.add(info); 4149 } 4150 } 4151 } 4152 } 4153 } 4154 4155 @Override 4156 public List<ProviderInfo> queryContentProviders(String processName, 4157 int uid, int flags) { 4158 ArrayList<ProviderInfo> finalList = null; 4159 // reader 4160 synchronized (mPackages) { 4161 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4162 final int userId = processName != null ? 4163 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4164 while (i.hasNext()) { 4165 final PackageParser.Provider p = i.next(); 4166 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4167 if (ps != null && p.info.authority != null 4168 && (processName == null 4169 || (p.info.processName.equals(processName) 4170 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4171 && mSettings.isEnabledLPr(p.info, flags, userId) 4172 && (!mSafeMode 4173 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4174 if (finalList == null) { 4175 finalList = new ArrayList<ProviderInfo>(3); 4176 } 4177 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4178 ps.readUserState(userId), userId); 4179 if (info != null) { 4180 finalList.add(info); 4181 } 4182 } 4183 } 4184 } 4185 4186 if (finalList != null) { 4187 Collections.sort(finalList, mProviderInitOrderSorter); 4188 } 4189 4190 return finalList; 4191 } 4192 4193 @Override 4194 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4195 int flags) { 4196 // reader 4197 synchronized (mPackages) { 4198 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4199 return PackageParser.generateInstrumentationInfo(i, flags); 4200 } 4201 } 4202 4203 @Override 4204 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4205 int flags) { 4206 ArrayList<InstrumentationInfo> finalList = 4207 new ArrayList<InstrumentationInfo>(); 4208 4209 // reader 4210 synchronized (mPackages) { 4211 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4212 while (i.hasNext()) { 4213 final PackageParser.Instrumentation p = i.next(); 4214 if (targetPackage == null 4215 || targetPackage.equals(p.info.targetPackage)) { 4216 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4217 flags); 4218 if (ii != null) { 4219 finalList.add(ii); 4220 } 4221 } 4222 } 4223 } 4224 4225 return finalList; 4226 } 4227 4228 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4229 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4230 if (overlays == null) { 4231 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4232 return; 4233 } 4234 for (PackageParser.Package opkg : overlays.values()) { 4235 // Not much to do if idmap fails: we already logged the error 4236 // and we certainly don't want to abort installation of pkg simply 4237 // because an overlay didn't fit properly. For these reasons, 4238 // ignore the return value of createIdmapForPackagePairLI. 4239 createIdmapForPackagePairLI(pkg, opkg); 4240 } 4241 } 4242 4243 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4244 PackageParser.Package opkg) { 4245 if (!opkg.mTrustedOverlay) { 4246 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4247 opkg.baseCodePath + ": overlay not trusted"); 4248 return false; 4249 } 4250 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4251 if (overlaySet == null) { 4252 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4253 opkg.baseCodePath + " but target package has no known overlays"); 4254 return false; 4255 } 4256 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4257 // TODO: generate idmap for split APKs 4258 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4259 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4260 + opkg.baseCodePath); 4261 return false; 4262 } 4263 PackageParser.Package[] overlayArray = 4264 overlaySet.values().toArray(new PackageParser.Package[0]); 4265 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4266 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4267 return p1.mOverlayPriority - p2.mOverlayPriority; 4268 } 4269 }; 4270 Arrays.sort(overlayArray, cmp); 4271 4272 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4273 int i = 0; 4274 for (PackageParser.Package p : overlayArray) { 4275 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4276 } 4277 return true; 4278 } 4279 4280 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4281 final File[] files = dir.listFiles(); 4282 if (ArrayUtils.isEmpty(files)) { 4283 Log.d(TAG, "No files in app dir " + dir); 4284 return; 4285 } 4286 4287 if (DEBUG_PACKAGE_SCANNING) { 4288 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4289 + " flags=0x" + Integer.toHexString(parseFlags)); 4290 } 4291 4292 for (File file : files) { 4293 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4294 && !PackageInstallerService.isStageName(file.getName()); 4295 if (!isPackage) { 4296 // Ignore entries which are not packages 4297 continue; 4298 } 4299 try { 4300 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4301 scanFlags, currentTime, null); 4302 } catch (PackageManagerException e) { 4303 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4304 4305 // Delete invalid userdata apps 4306 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4307 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4308 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4309 if (file.isDirectory()) { 4310 FileUtils.deleteContents(file); 4311 } 4312 file.delete(); 4313 } 4314 } 4315 } 4316 } 4317 4318 private static File getSettingsProblemFile() { 4319 File dataDir = Environment.getDataDirectory(); 4320 File systemDir = new File(dataDir, "system"); 4321 File fname = new File(systemDir, "uiderrors.txt"); 4322 return fname; 4323 } 4324 4325 static void reportSettingsProblem(int priority, String msg) { 4326 logCriticalInfo(priority, msg); 4327 } 4328 4329 static void logCriticalInfo(int priority, String msg) { 4330 Slog.println(priority, TAG, msg); 4331 EventLogTags.writePmCriticalInfo(msg); 4332 try { 4333 File fname = getSettingsProblemFile(); 4334 FileOutputStream out = new FileOutputStream(fname, true); 4335 PrintWriter pw = new FastPrintWriter(out); 4336 SimpleDateFormat formatter = new SimpleDateFormat(); 4337 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4338 pw.println(dateString + ": " + msg); 4339 pw.close(); 4340 FileUtils.setPermissions( 4341 fname.toString(), 4342 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4343 -1, -1); 4344 } catch (java.io.IOException e) { 4345 } 4346 } 4347 4348 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4349 PackageParser.Package pkg, File srcFile, int parseFlags) 4350 throws PackageManagerException { 4351 if (ps != null 4352 && ps.codePath.equals(srcFile) 4353 && ps.timeStamp == srcFile.lastModified() 4354 && !isCompatSignatureUpdateNeeded(pkg) 4355 && !isRecoverSignatureUpdateNeeded(pkg)) { 4356 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4357 if (ps.signatures.mSignatures != null 4358 && ps.signatures.mSignatures.length != 0 4359 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4360 // Optimization: reuse the existing cached certificates 4361 // if the package appears to be unchanged. 4362 pkg.mSignatures = ps.signatures.mSignatures; 4363 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4364 synchronized (mPackages) { 4365 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4366 } 4367 return; 4368 } 4369 4370 Slog.w(TAG, "PackageSetting for " + ps.name 4371 + " is missing signatures. Collecting certs again to recover them."); 4372 } else { 4373 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4374 } 4375 4376 try { 4377 pp.collectCertificates(pkg, parseFlags); 4378 pp.collectManifestDigest(pkg); 4379 } catch (PackageParserException e) { 4380 throw PackageManagerException.from(e); 4381 } 4382 } 4383 4384 /* 4385 * Scan a package and return the newly parsed package. 4386 * Returns null in case of errors and the error code is stored in mLastScanError 4387 */ 4388 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4389 long currentTime, UserHandle user) throws PackageManagerException { 4390 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4391 parseFlags |= mDefParseFlags; 4392 PackageParser pp = new PackageParser(); 4393 pp.setSeparateProcesses(mSeparateProcesses); 4394 pp.setOnlyCoreApps(mOnlyCore); 4395 pp.setDisplayMetrics(mMetrics); 4396 4397 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4398 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4399 } 4400 4401 final PackageParser.Package pkg; 4402 try { 4403 pkg = pp.parsePackage(scanFile, parseFlags); 4404 } catch (PackageParserException e) { 4405 throw PackageManagerException.from(e); 4406 } 4407 4408 PackageSetting ps = null; 4409 PackageSetting updatedPkg; 4410 // reader 4411 synchronized (mPackages) { 4412 // Look to see if we already know about this package. 4413 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4414 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4415 // This package has been renamed to its original name. Let's 4416 // use that. 4417 ps = mSettings.peekPackageLPr(oldName); 4418 } 4419 // If there was no original package, see one for the real package name. 4420 if (ps == null) { 4421 ps = mSettings.peekPackageLPr(pkg.packageName); 4422 } 4423 // Check to see if this package could be hiding/updating a system 4424 // package. Must look for it either under the original or real 4425 // package name depending on our state. 4426 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4427 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4428 } 4429 boolean updatedPkgBetter = false; 4430 // First check if this is a system package that may involve an update 4431 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4432 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4433 // it needs to drop FLAG_PRIVILEGED. 4434 if (locationIsPrivileged(scanFile)) { 4435 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4436 } else { 4437 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4438 } 4439 4440 if (ps != null && !ps.codePath.equals(scanFile)) { 4441 // The path has changed from what was last scanned... check the 4442 // version of the new path against what we have stored to determine 4443 // what to do. 4444 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4445 if (pkg.mVersionCode <= ps.versionCode) { 4446 // The system package has been updated and the code path does not match 4447 // Ignore entry. Skip it. 4448 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4449 + " ignored: updated version " + ps.versionCode 4450 + " better than this " + pkg.mVersionCode); 4451 if (!updatedPkg.codePath.equals(scanFile)) { 4452 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4453 + ps.name + " changing from " + updatedPkg.codePathString 4454 + " to " + scanFile); 4455 updatedPkg.codePath = scanFile; 4456 updatedPkg.codePathString = scanFile.toString(); 4457 updatedPkg.resourcePath = scanFile; 4458 updatedPkg.resourcePathString = scanFile.toString(); 4459 } 4460 updatedPkg.pkg = pkg; 4461 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4462 } else { 4463 // The current app on the system partition is better than 4464 // what we have updated to on the data partition; switch 4465 // back to the system partition version. 4466 // At this point, its safely assumed that package installation for 4467 // apps in system partition will go through. If not there won't be a working 4468 // version of the app 4469 // writer 4470 synchronized (mPackages) { 4471 // Just remove the loaded entries from package lists. 4472 mPackages.remove(ps.name); 4473 } 4474 4475 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4476 + " reverting from " + ps.codePathString 4477 + ": new version " + pkg.mVersionCode 4478 + " better than installed " + ps.versionCode); 4479 4480 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4481 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4482 getAppDexInstructionSets(ps)); 4483 synchronized (mInstallLock) { 4484 args.cleanUpResourcesLI(); 4485 } 4486 synchronized (mPackages) { 4487 mSettings.enableSystemPackageLPw(ps.name); 4488 } 4489 updatedPkgBetter = true; 4490 } 4491 } 4492 } 4493 4494 if (updatedPkg != null) { 4495 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4496 // initially 4497 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4498 4499 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4500 // flag set initially 4501 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4502 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4503 } 4504 } 4505 4506 // Verify certificates against what was last scanned 4507 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4508 4509 /* 4510 * A new system app appeared, but we already had a non-system one of the 4511 * same name installed earlier. 4512 */ 4513 boolean shouldHideSystemApp = false; 4514 if (updatedPkg == null && ps != null 4515 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4516 /* 4517 * Check to make sure the signatures match first. If they don't, 4518 * wipe the installed application and its data. 4519 */ 4520 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4521 != PackageManager.SIGNATURE_MATCH) { 4522 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4523 + " signatures don't match existing userdata copy; removing"); 4524 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4525 ps = null; 4526 } else { 4527 /* 4528 * If the newly-added system app is an older version than the 4529 * already installed version, hide it. It will be scanned later 4530 * and re-added like an update. 4531 */ 4532 if (pkg.mVersionCode <= ps.versionCode) { 4533 shouldHideSystemApp = true; 4534 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4535 + " but new version " + pkg.mVersionCode + " better than installed " 4536 + ps.versionCode + "; hiding system"); 4537 } else { 4538 /* 4539 * The newly found system app is a newer version that the 4540 * one previously installed. Simply remove the 4541 * already-installed application and replace it with our own 4542 * while keeping the application data. 4543 */ 4544 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4545 + " reverting from " + ps.codePathString + ": new version " 4546 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4547 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4548 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4549 getAppDexInstructionSets(ps)); 4550 synchronized (mInstallLock) { 4551 args.cleanUpResourcesLI(); 4552 } 4553 } 4554 } 4555 } 4556 4557 // The apk is forward locked (not public) if its code and resources 4558 // are kept in different files. (except for app in either system or 4559 // vendor path). 4560 // TODO grab this value from PackageSettings 4561 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4562 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4563 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4564 } 4565 } 4566 4567 // TODO: extend to support forward-locked splits 4568 String resourcePath = null; 4569 String baseResourcePath = null; 4570 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4571 if (ps != null && ps.resourcePathString != null) { 4572 resourcePath = ps.resourcePathString; 4573 baseResourcePath = ps.resourcePathString; 4574 } else { 4575 // Should not happen at all. Just log an error. 4576 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4577 } 4578 } else { 4579 resourcePath = pkg.codePath; 4580 baseResourcePath = pkg.baseCodePath; 4581 } 4582 4583 // Set application objects path explicitly. 4584 pkg.applicationInfo.setCodePath(pkg.codePath); 4585 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4586 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4587 pkg.applicationInfo.setResourcePath(resourcePath); 4588 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4589 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4590 4591 // Note that we invoke the following method only if we are about to unpack an application 4592 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4593 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4594 4595 /* 4596 * If the system app should be overridden by a previously installed 4597 * data, hide the system app now and let the /data/app scan pick it up 4598 * again. 4599 */ 4600 if (shouldHideSystemApp) { 4601 synchronized (mPackages) { 4602 /* 4603 * We have to grant systems permissions before we hide, because 4604 * grantPermissions will assume the package update is trying to 4605 * expand its permissions. 4606 */ 4607 grantPermissionsLPw(pkg, true, pkg.packageName); 4608 mSettings.disableSystemPackageLPw(pkg.packageName); 4609 } 4610 } 4611 4612 return scannedPkg; 4613 } 4614 4615 private static String fixProcessName(String defProcessName, 4616 String processName, int uid) { 4617 if (processName == null) { 4618 return defProcessName; 4619 } 4620 return processName; 4621 } 4622 4623 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4624 throws PackageManagerException { 4625 if (pkgSetting.signatures.mSignatures != null) { 4626 // Already existing package. Make sure signatures match 4627 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4628 == PackageManager.SIGNATURE_MATCH; 4629 if (!match) { 4630 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4631 == PackageManager.SIGNATURE_MATCH; 4632 } 4633 if (!match) { 4634 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 4635 == PackageManager.SIGNATURE_MATCH; 4636 } 4637 if (!match) { 4638 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4639 + pkg.packageName + " signatures do not match the " 4640 + "previously installed version; ignoring!"); 4641 } 4642 } 4643 4644 // Check for shared user signatures 4645 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4646 // Already existing package. Make sure signatures match 4647 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4648 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4649 if (!match) { 4650 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4651 == PackageManager.SIGNATURE_MATCH; 4652 } 4653 if (!match) { 4654 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 4655 == PackageManager.SIGNATURE_MATCH; 4656 } 4657 if (!match) { 4658 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4659 "Package " + pkg.packageName 4660 + " has no signatures that match those in shared user " 4661 + pkgSetting.sharedUser.name + "; ignoring!"); 4662 } 4663 } 4664 } 4665 4666 /** 4667 * Enforces that only the system UID or root's UID can call a method exposed 4668 * via Binder. 4669 * 4670 * @param message used as message if SecurityException is thrown 4671 * @throws SecurityException if the caller is not system or root 4672 */ 4673 private static final void enforceSystemOrRoot(String message) { 4674 final int uid = Binder.getCallingUid(); 4675 if (uid != Process.SYSTEM_UID && uid != 0) { 4676 throw new SecurityException(message); 4677 } 4678 } 4679 4680 @Override 4681 public void performBootDexOpt() { 4682 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4683 4684 // Before everything else, see whether we need to fstrim. 4685 try { 4686 IMountService ms = PackageHelper.getMountService(); 4687 if (ms != null) { 4688 final boolean isUpgrade = isUpgrade(); 4689 boolean doTrim = isUpgrade; 4690 if (doTrim) { 4691 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 4692 } else { 4693 final long interval = android.provider.Settings.Global.getLong( 4694 mContext.getContentResolver(), 4695 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 4696 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 4697 if (interval > 0) { 4698 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 4699 if (timeSinceLast > interval) { 4700 doTrim = true; 4701 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 4702 + "; running immediately"); 4703 } 4704 } 4705 } 4706 if (doTrim) { 4707 if (!isFirstBoot()) { 4708 try { 4709 ActivityManagerNative.getDefault().showBootMessage( 4710 mContext.getResources().getString( 4711 R.string.android_upgrading_fstrim), true); 4712 } catch (RemoteException e) { 4713 } 4714 } 4715 ms.runMaintenance(); 4716 } 4717 } else { 4718 Slog.e(TAG, "Mount service unavailable!"); 4719 } 4720 } catch (RemoteException e) { 4721 // Can't happen; MountService is local 4722 } 4723 4724 final ArraySet<PackageParser.Package> pkgs; 4725 synchronized (mPackages) { 4726 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 4727 } 4728 4729 if (pkgs != null) { 4730 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4731 // in case the device runs out of space. 4732 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4733 // Give priority to core apps. 4734 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4735 PackageParser.Package pkg = it.next(); 4736 if (pkg.coreApp) { 4737 if (DEBUG_DEXOPT) { 4738 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 4739 } 4740 sortedPkgs.add(pkg); 4741 it.remove(); 4742 } 4743 } 4744 // Give priority to system apps that listen for pre boot complete. 4745 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4746 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 4747 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4748 PackageParser.Package pkg = it.next(); 4749 if (pkgNames.contains(pkg.packageName)) { 4750 if (DEBUG_DEXOPT) { 4751 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 4752 } 4753 sortedPkgs.add(pkg); 4754 it.remove(); 4755 } 4756 } 4757 // Give priority to system apps. 4758 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4759 PackageParser.Package pkg = it.next(); 4760 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 4761 if (DEBUG_DEXOPT) { 4762 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 4763 } 4764 sortedPkgs.add(pkg); 4765 it.remove(); 4766 } 4767 } 4768 // Give priority to updated system apps. 4769 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4770 PackageParser.Package pkg = it.next(); 4771 if (isUpdatedSystemApp(pkg)) { 4772 if (DEBUG_DEXOPT) { 4773 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 4774 } 4775 sortedPkgs.add(pkg); 4776 it.remove(); 4777 } 4778 } 4779 // Give priority to apps that listen for boot complete. 4780 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4781 pkgNames = getPackageNamesForIntent(intent); 4782 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4783 PackageParser.Package pkg = it.next(); 4784 if (pkgNames.contains(pkg.packageName)) { 4785 if (DEBUG_DEXOPT) { 4786 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 4787 } 4788 sortedPkgs.add(pkg); 4789 it.remove(); 4790 } 4791 } 4792 // Filter out packages that aren't recently used. 4793 filterRecentlyUsedApps(pkgs); 4794 // Add all remaining apps. 4795 for (PackageParser.Package pkg : pkgs) { 4796 if (DEBUG_DEXOPT) { 4797 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 4798 } 4799 sortedPkgs.add(pkg); 4800 } 4801 4802 // If we want to be lazy, filter everything that wasn't recently used. 4803 if (mLazyDexOpt) { 4804 filterRecentlyUsedApps(sortedPkgs); 4805 } 4806 4807 int i = 0; 4808 int total = sortedPkgs.size(); 4809 File dataDir = Environment.getDataDirectory(); 4810 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 4811 if (lowThreshold == 0) { 4812 throw new IllegalStateException("Invalid low memory threshold"); 4813 } 4814 for (PackageParser.Package pkg : sortedPkgs) { 4815 long usableSpace = dataDir.getUsableSpace(); 4816 if (usableSpace < lowThreshold) { 4817 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 4818 break; 4819 } 4820 performBootDexOpt(pkg, ++i, total); 4821 } 4822 } 4823 } 4824 4825 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 4826 // Filter out packages that aren't recently used. 4827 // 4828 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4829 // should do a full dexopt. 4830 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4831 int total = pkgs.size(); 4832 int skipped = 0; 4833 long now = System.currentTimeMillis(); 4834 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4835 PackageParser.Package pkg = i.next(); 4836 long then = pkg.mLastPackageUsageTimeInMills; 4837 if (then + mDexOptLRUThresholdInMills < now) { 4838 if (DEBUG_DEXOPT) { 4839 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4840 ((then == 0) ? "never" : new Date(then))); 4841 } 4842 i.remove(); 4843 skipped++; 4844 } 4845 } 4846 if (DEBUG_DEXOPT) { 4847 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4848 } 4849 } 4850 } 4851 4852 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 4853 List<ResolveInfo> ris = null; 4854 try { 4855 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4856 intent, null, 0, UserHandle.USER_OWNER); 4857 } catch (RemoteException e) { 4858 } 4859 ArraySet<String> pkgNames = new ArraySet<String>(); 4860 if (ris != null) { 4861 for (ResolveInfo ri : ris) { 4862 pkgNames.add(ri.activityInfo.packageName); 4863 } 4864 } 4865 return pkgNames; 4866 } 4867 4868 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4869 if (DEBUG_DEXOPT) { 4870 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4871 } 4872 if (!isFirstBoot()) { 4873 try { 4874 ActivityManagerNative.getDefault().showBootMessage( 4875 mContext.getResources().getString(R.string.android_upgrading_apk, 4876 curr, total), true); 4877 } catch (RemoteException e) { 4878 } 4879 } 4880 PackageParser.Package p = pkg; 4881 synchronized (mInstallLock) { 4882 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 4883 false /* force dex */, false /* defer */, true /* include dependencies */); 4884 } 4885 } 4886 4887 @Override 4888 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4889 return performDexOpt(packageName, instructionSet, false); 4890 } 4891 4892 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4893 if (info.primaryCpuAbi == null) { 4894 return getPreferredInstructionSet(); 4895 } 4896 4897 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4898 } 4899 4900 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4901 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4902 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4903 if (!dexopt && !updateUsage) { 4904 // We aren't going to dexopt or update usage, so bail early. 4905 return false; 4906 } 4907 PackageParser.Package p; 4908 final String targetInstructionSet; 4909 synchronized (mPackages) { 4910 p = mPackages.get(packageName); 4911 if (p == null) { 4912 return false; 4913 } 4914 if (updateUsage) { 4915 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4916 } 4917 mPackageUsage.write(false); 4918 if (!dexopt) { 4919 // We aren't going to dexopt, so bail early. 4920 return false; 4921 } 4922 4923 targetInstructionSet = instructionSet != null ? instructionSet : 4924 getPrimaryInstructionSet(p.applicationInfo); 4925 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4926 return false; 4927 } 4928 } 4929 4930 synchronized (mInstallLock) { 4931 final String[] instructionSets = new String[] { targetInstructionSet }; 4932 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 4933 false /* forceDex */, false /* defer */, true /* inclDependencies */); 4934 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 4935 } 4936 } 4937 4938 public ArraySet<String> getPackagesThatNeedDexOpt() { 4939 ArraySet<String> pkgs = null; 4940 synchronized (mPackages) { 4941 for (PackageParser.Package p : mPackages.values()) { 4942 if (DEBUG_DEXOPT) { 4943 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4944 } 4945 if (!p.mDexOptPerformed.isEmpty()) { 4946 continue; 4947 } 4948 if (pkgs == null) { 4949 pkgs = new ArraySet<String>(); 4950 } 4951 pkgs.add(p.packageName); 4952 } 4953 } 4954 return pkgs; 4955 } 4956 4957 public void shutdown() { 4958 mPackageUsage.write(true); 4959 } 4960 4961 @Override 4962 public void forceDexOpt(String packageName) { 4963 enforceSystemOrRoot("forceDexOpt"); 4964 4965 PackageParser.Package pkg; 4966 synchronized (mPackages) { 4967 pkg = mPackages.get(packageName); 4968 if (pkg == null) { 4969 throw new IllegalArgumentException("Missing package: " + packageName); 4970 } 4971 } 4972 4973 synchronized (mInstallLock) { 4974 final String[] instructionSets = new String[] { 4975 getPrimaryInstructionSet(pkg.applicationInfo) }; 4976 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 4977 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 4978 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 4979 throw new IllegalStateException("Failed to dexopt: " + res); 4980 } 4981 } 4982 } 4983 4984 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4985 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4986 Slog.w(TAG, "Unable to update from " + oldPkg.name 4987 + " to " + newPkg.packageName 4988 + ": old package not in system partition"); 4989 return false; 4990 } else if (mPackages.get(oldPkg.name) != null) { 4991 Slog.w(TAG, "Unable to update from " + oldPkg.name 4992 + " to " + newPkg.packageName 4993 + ": old package still exists"); 4994 return false; 4995 } 4996 return true; 4997 } 4998 4999 private File getDataPathForPackage(String packageName, int userId) { 5000 /* 5001 * Until we fully support multiple users, return the directory we 5002 * previously would have. The PackageManagerTests will need to be 5003 * revised when this is changed back.. 5004 */ 5005 if (userId == 0) { 5006 return new File(mAppDataDir, packageName); 5007 } else { 5008 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 5009 + File.separator + packageName); 5010 } 5011 } 5012 5013 private int createDataDirsLI(String packageName, int uid, String seinfo) { 5014 int[] users = sUserManager.getUserIds(); 5015 int res = mInstaller.install(packageName, uid, uid, seinfo); 5016 if (res < 0) { 5017 return res; 5018 } 5019 for (int user : users) { 5020 if (user != 0) { 5021 res = mInstaller.createUserData(packageName, 5022 UserHandle.getUid(user, uid), user, seinfo); 5023 if (res < 0) { 5024 return res; 5025 } 5026 } 5027 } 5028 return res; 5029 } 5030 5031 private int removeDataDirsLI(String packageName) { 5032 int[] users = sUserManager.getUserIds(); 5033 int res = 0; 5034 for (int user : users) { 5035 int resInner = mInstaller.remove(packageName, user); 5036 if (resInner < 0) { 5037 res = resInner; 5038 } 5039 } 5040 5041 return res; 5042 } 5043 5044 private int deleteCodeCacheDirsLI(String packageName) { 5045 int[] users = sUserManager.getUserIds(); 5046 int res = 0; 5047 for (int user : users) { 5048 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5049 if (resInner < 0) { 5050 res = resInner; 5051 } 5052 } 5053 return res; 5054 } 5055 5056 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5057 PackageParser.Package changingLib) { 5058 if (file.path != null) { 5059 usesLibraryFiles.add(file.path); 5060 return; 5061 } 5062 PackageParser.Package p = mPackages.get(file.apk); 5063 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5064 // If we are doing this while in the middle of updating a library apk, 5065 // then we need to make sure to use that new apk for determining the 5066 // dependencies here. (We haven't yet finished committing the new apk 5067 // to the package manager state.) 5068 if (p == null || p.packageName.equals(changingLib.packageName)) { 5069 p = changingLib; 5070 } 5071 } 5072 if (p != null) { 5073 usesLibraryFiles.addAll(p.getAllCodePaths()); 5074 } 5075 } 5076 5077 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5078 PackageParser.Package changingLib) throws PackageManagerException { 5079 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5080 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5081 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5082 for (int i=0; i<N; i++) { 5083 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5084 if (file == null) { 5085 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5086 "Package " + pkg.packageName + " requires unavailable shared library " 5087 + pkg.usesLibraries.get(i) + "; failing!"); 5088 } 5089 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5090 } 5091 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5092 for (int i=0; i<N; i++) { 5093 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5094 if (file == null) { 5095 Slog.w(TAG, "Package " + pkg.packageName 5096 + " desires unavailable shared library " 5097 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5098 } else { 5099 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5100 } 5101 } 5102 N = usesLibraryFiles.size(); 5103 if (N > 0) { 5104 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5105 } else { 5106 pkg.usesLibraryFiles = null; 5107 } 5108 } 5109 } 5110 5111 private static boolean hasString(List<String> list, List<String> which) { 5112 if (list == null) { 5113 return false; 5114 } 5115 for (int i=list.size()-1; i>=0; i--) { 5116 for (int j=which.size()-1; j>=0; j--) { 5117 if (which.get(j).equals(list.get(i))) { 5118 return true; 5119 } 5120 } 5121 } 5122 return false; 5123 } 5124 5125 private void updateAllSharedLibrariesLPw() { 5126 for (PackageParser.Package pkg : mPackages.values()) { 5127 try { 5128 updateSharedLibrariesLPw(pkg, null); 5129 } catch (PackageManagerException e) { 5130 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5131 } 5132 } 5133 } 5134 5135 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5136 PackageParser.Package changingPkg) { 5137 ArrayList<PackageParser.Package> res = null; 5138 for (PackageParser.Package pkg : mPackages.values()) { 5139 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5140 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5141 if (res == null) { 5142 res = new ArrayList<PackageParser.Package>(); 5143 } 5144 res.add(pkg); 5145 try { 5146 updateSharedLibrariesLPw(pkg, changingPkg); 5147 } catch (PackageManagerException e) { 5148 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5149 } 5150 } 5151 } 5152 return res; 5153 } 5154 5155 /** 5156 * Derive the value of the {@code cpuAbiOverride} based on the provided 5157 * value and an optional stored value from the package settings. 5158 */ 5159 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5160 String cpuAbiOverride = null; 5161 5162 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5163 cpuAbiOverride = null; 5164 } else if (abiOverride != null) { 5165 cpuAbiOverride = abiOverride; 5166 } else if (settings != null) { 5167 cpuAbiOverride = settings.cpuAbiOverrideString; 5168 } 5169 5170 return cpuAbiOverride; 5171 } 5172 5173 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5174 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5175 boolean success = false; 5176 try { 5177 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5178 currentTime, user); 5179 success = true; 5180 return res; 5181 } finally { 5182 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5183 removeDataDirsLI(pkg.packageName); 5184 } 5185 } 5186 } 5187 5188 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5189 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5190 final File scanFile = new File(pkg.codePath); 5191 if (pkg.applicationInfo.getCodePath() == null || 5192 pkg.applicationInfo.getResourcePath() == null) { 5193 // Bail out. The resource and code paths haven't been set. 5194 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5195 "Code and resource paths haven't been set correctly"); 5196 } 5197 5198 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5199 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5200 } else { 5201 // Only allow system apps to be flagged as core apps. 5202 pkg.coreApp = false; 5203 } 5204 5205 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5206 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5207 } 5208 5209 if (mCustomResolverComponentName != null && 5210 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5211 setUpCustomResolverActivity(pkg); 5212 } 5213 5214 if (pkg.packageName.equals("android")) { 5215 synchronized (mPackages) { 5216 if (mAndroidApplication != null) { 5217 Slog.w(TAG, "*************************************************"); 5218 Slog.w(TAG, "Core android package being redefined. Skipping."); 5219 Slog.w(TAG, " file=" + scanFile); 5220 Slog.w(TAG, "*************************************************"); 5221 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5222 "Core android package being redefined. Skipping."); 5223 } 5224 5225 // Set up information for our fall-back user intent resolution activity. 5226 mPlatformPackage = pkg; 5227 pkg.mVersionCode = mSdkVersion; 5228 mAndroidApplication = pkg.applicationInfo; 5229 5230 if (!mResolverReplaced) { 5231 mResolveActivity.applicationInfo = mAndroidApplication; 5232 mResolveActivity.name = ResolverActivity.class.getName(); 5233 mResolveActivity.packageName = mAndroidApplication.packageName; 5234 mResolveActivity.processName = "system:ui"; 5235 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5236 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5237 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5238 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5239 mResolveActivity.exported = true; 5240 mResolveActivity.enabled = true; 5241 mResolveInfo.activityInfo = mResolveActivity; 5242 mResolveInfo.priority = 0; 5243 mResolveInfo.preferredOrder = 0; 5244 mResolveInfo.match = 0; 5245 mResolveComponentName = new ComponentName( 5246 mAndroidApplication.packageName, mResolveActivity.name); 5247 } 5248 } 5249 } 5250 5251 if (DEBUG_PACKAGE_SCANNING) { 5252 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5253 Log.d(TAG, "Scanning package " + pkg.packageName); 5254 } 5255 5256 if (mPackages.containsKey(pkg.packageName) 5257 || mSharedLibraries.containsKey(pkg.packageName)) { 5258 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5259 "Application package " + pkg.packageName 5260 + " already installed. Skipping duplicate."); 5261 } 5262 5263 // Initialize package source and resource directories 5264 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5265 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5266 5267 SharedUserSetting suid = null; 5268 PackageSetting pkgSetting = null; 5269 5270 if (!isSystemApp(pkg)) { 5271 // Only system apps can use these features. 5272 pkg.mOriginalPackages = null; 5273 pkg.mRealPackage = null; 5274 pkg.mAdoptPermissions = null; 5275 } 5276 5277 // writer 5278 synchronized (mPackages) { 5279 if (pkg.mSharedUserId != null) { 5280 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5281 if (suid == null) { 5282 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5283 "Creating application package " + pkg.packageName 5284 + " for shared user failed"); 5285 } 5286 if (DEBUG_PACKAGE_SCANNING) { 5287 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5288 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5289 + "): packages=" + suid.packages); 5290 } 5291 } 5292 5293 // Check if we are renaming from an original package name. 5294 PackageSetting origPackage = null; 5295 String realName = null; 5296 if (pkg.mOriginalPackages != null) { 5297 // This package may need to be renamed to a previously 5298 // installed name. Let's check on that... 5299 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5300 if (pkg.mOriginalPackages.contains(renamed)) { 5301 // This package had originally been installed as the 5302 // original name, and we have already taken care of 5303 // transitioning to the new one. Just update the new 5304 // one to continue using the old name. 5305 realName = pkg.mRealPackage; 5306 if (!pkg.packageName.equals(renamed)) { 5307 // Callers into this function may have already taken 5308 // care of renaming the package; only do it here if 5309 // it is not already done. 5310 pkg.setPackageName(renamed); 5311 } 5312 5313 } else { 5314 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5315 if ((origPackage = mSettings.peekPackageLPr( 5316 pkg.mOriginalPackages.get(i))) != null) { 5317 // We do have the package already installed under its 5318 // original name... should we use it? 5319 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5320 // New package is not compatible with original. 5321 origPackage = null; 5322 continue; 5323 } else if (origPackage.sharedUser != null) { 5324 // Make sure uid is compatible between packages. 5325 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5326 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5327 + " to " + pkg.packageName + ": old uid " 5328 + origPackage.sharedUser.name 5329 + " differs from " + pkg.mSharedUserId); 5330 origPackage = null; 5331 continue; 5332 } 5333 } else { 5334 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5335 + pkg.packageName + " to old name " + origPackage.name); 5336 } 5337 break; 5338 } 5339 } 5340 } 5341 } 5342 5343 if (mTransferedPackages.contains(pkg.packageName)) { 5344 Slog.w(TAG, "Package " + pkg.packageName 5345 + " was transferred to another, but its .apk remains"); 5346 } 5347 5348 // Just create the setting, don't add it yet. For already existing packages 5349 // the PkgSetting exists already and doesn't have to be created. 5350 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5351 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5352 pkg.applicationInfo.primaryCpuAbi, 5353 pkg.applicationInfo.secondaryCpuAbi, 5354 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5355 user, false); 5356 if (pkgSetting == null) { 5357 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5358 "Creating application package " + pkg.packageName + " failed"); 5359 } 5360 5361 if (pkgSetting.origPackage != null) { 5362 // If we are first transitioning from an original package, 5363 // fix up the new package's name now. We need to do this after 5364 // looking up the package under its new name, so getPackageLP 5365 // can take care of fiddling things correctly. 5366 pkg.setPackageName(origPackage.name); 5367 5368 // File a report about this. 5369 String msg = "New package " + pkgSetting.realName 5370 + " renamed to replace old package " + pkgSetting.name; 5371 reportSettingsProblem(Log.WARN, msg); 5372 5373 // Make a note of it. 5374 mTransferedPackages.add(origPackage.name); 5375 5376 // No longer need to retain this. 5377 pkgSetting.origPackage = null; 5378 } 5379 5380 if (realName != null) { 5381 // Make a note of it. 5382 mTransferedPackages.add(pkg.packageName); 5383 } 5384 5385 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5386 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5387 } 5388 5389 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5390 // Check all shared libraries and map to their actual file path. 5391 // We only do this here for apps not on a system dir, because those 5392 // are the only ones that can fail an install due to this. We 5393 // will take care of the system apps by updating all of their 5394 // library paths after the scan is done. 5395 updateSharedLibrariesLPw(pkg, null); 5396 } 5397 5398 if (mFoundPolicyFile) { 5399 SELinuxMMAC.assignSeinfoValue(pkg); 5400 } 5401 5402 pkg.applicationInfo.uid = pkgSetting.appId; 5403 pkg.mExtras = pkgSetting; 5404 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5405 try { 5406 verifySignaturesLP(pkgSetting, pkg); 5407 // We just determined the app is signed correctly, so bring 5408 // over the latest parsed certs. 5409 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5410 } catch (PackageManagerException e) { 5411 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5412 throw e; 5413 } 5414 // The signature has changed, but this package is in the system 5415 // image... let's recover! 5416 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5417 // However... if this package is part of a shared user, but it 5418 // doesn't match the signature of the shared user, let's fail. 5419 // What this means is that you can't change the signatures 5420 // associated with an overall shared user, which doesn't seem all 5421 // that unreasonable. 5422 if (pkgSetting.sharedUser != null) { 5423 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5424 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5425 throw new PackageManagerException( 5426 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5427 "Signature mismatch for shared user : " 5428 + pkgSetting.sharedUser); 5429 } 5430 } 5431 // File a report about this. 5432 String msg = "System package " + pkg.packageName 5433 + " signature changed; retaining data."; 5434 reportSettingsProblem(Log.WARN, msg); 5435 } 5436 } else { 5437 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5438 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5439 + pkg.packageName + " upgrade keys do not match the " 5440 + "previously installed version"); 5441 } else { 5442 // We just determined the app is signed correctly, so bring 5443 // over the latest parsed certs. 5444 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5445 } 5446 } 5447 // Verify that this new package doesn't have any content providers 5448 // that conflict with existing packages. Only do this if the 5449 // package isn't already installed, since we don't want to break 5450 // things that are installed. 5451 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5452 final int N = pkg.providers.size(); 5453 int i; 5454 for (i=0; i<N; i++) { 5455 PackageParser.Provider p = pkg.providers.get(i); 5456 if (p.info.authority != null) { 5457 String names[] = p.info.authority.split(";"); 5458 for (int j = 0; j < names.length; j++) { 5459 if (mProvidersByAuthority.containsKey(names[j])) { 5460 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5461 final String otherPackageName = 5462 ((other != null && other.getComponentName() != null) ? 5463 other.getComponentName().getPackageName() : "?"); 5464 throw new PackageManagerException( 5465 INSTALL_FAILED_CONFLICTING_PROVIDER, 5466 "Can't install because provider name " + names[j] 5467 + " (in package " + pkg.applicationInfo.packageName 5468 + ") is already used by " + otherPackageName); 5469 } 5470 } 5471 } 5472 } 5473 } 5474 5475 if (pkg.mAdoptPermissions != null) { 5476 // This package wants to adopt ownership of permissions from 5477 // another package. 5478 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5479 final String origName = pkg.mAdoptPermissions.get(i); 5480 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5481 if (orig != null) { 5482 if (verifyPackageUpdateLPr(orig, pkg)) { 5483 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5484 + pkg.packageName); 5485 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5486 } 5487 } 5488 } 5489 } 5490 } 5491 5492 final String pkgName = pkg.packageName; 5493 5494 final long scanFileTime = scanFile.lastModified(); 5495 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5496 pkg.applicationInfo.processName = fixProcessName( 5497 pkg.applicationInfo.packageName, 5498 pkg.applicationInfo.processName, 5499 pkg.applicationInfo.uid); 5500 5501 File dataPath; 5502 if (mPlatformPackage == pkg) { 5503 // The system package is special. 5504 dataPath = new File(Environment.getDataDirectory(), "system"); 5505 5506 pkg.applicationInfo.dataDir = dataPath.getPath(); 5507 5508 } else { 5509 // This is a normal package, need to make its data directory. 5510 dataPath = getDataPathForPackage(pkg.packageName, 0); 5511 5512 boolean uidError = false; 5513 if (dataPath.exists()) { 5514 int currentUid = 0; 5515 try { 5516 StructStat stat = Os.stat(dataPath.getPath()); 5517 currentUid = stat.st_uid; 5518 } catch (ErrnoException e) { 5519 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5520 } 5521 5522 // If we have mismatched owners for the data path, we have a problem. 5523 if (currentUid != pkg.applicationInfo.uid) { 5524 boolean recovered = false; 5525 if (currentUid == 0) { 5526 // The directory somehow became owned by root. Wow. 5527 // This is probably because the system was stopped while 5528 // installd was in the middle of messing with its libs 5529 // directory. Ask installd to fix that. 5530 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5531 pkg.applicationInfo.uid); 5532 if (ret >= 0) { 5533 recovered = true; 5534 String msg = "Package " + pkg.packageName 5535 + " unexpectedly changed to uid 0; recovered to " + 5536 + pkg.applicationInfo.uid; 5537 reportSettingsProblem(Log.WARN, msg); 5538 } 5539 } 5540 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5541 || (scanFlags&SCAN_BOOTING) != 0)) { 5542 // If this is a system app, we can at least delete its 5543 // current data so the application will still work. 5544 int ret = removeDataDirsLI(pkgName); 5545 if (ret >= 0) { 5546 // TODO: Kill the processes first 5547 // Old data gone! 5548 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5549 ? "System package " : "Third party package "; 5550 String msg = prefix + pkg.packageName 5551 + " has changed from uid: " 5552 + currentUid + " to " 5553 + pkg.applicationInfo.uid + "; old data erased"; 5554 reportSettingsProblem(Log.WARN, msg); 5555 recovered = true; 5556 5557 // And now re-install the app. 5558 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5559 pkg.applicationInfo.seinfo); 5560 if (ret == -1) { 5561 // Ack should not happen! 5562 msg = prefix + pkg.packageName 5563 + " could not have data directory re-created after delete."; 5564 reportSettingsProblem(Log.WARN, msg); 5565 throw new PackageManagerException( 5566 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5567 } 5568 } 5569 if (!recovered) { 5570 mHasSystemUidErrors = true; 5571 } 5572 } else if (!recovered) { 5573 // If we allow this install to proceed, we will be broken. 5574 // Abort, abort! 5575 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5576 "scanPackageLI"); 5577 } 5578 if (!recovered) { 5579 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5580 + pkg.applicationInfo.uid + "/fs_" 5581 + currentUid; 5582 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5583 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5584 String msg = "Package " + pkg.packageName 5585 + " has mismatched uid: " 5586 + currentUid + " on disk, " 5587 + pkg.applicationInfo.uid + " in settings"; 5588 // writer 5589 synchronized (mPackages) { 5590 mSettings.mReadMessages.append(msg); 5591 mSettings.mReadMessages.append('\n'); 5592 uidError = true; 5593 if (!pkgSetting.uidError) { 5594 reportSettingsProblem(Log.ERROR, msg); 5595 } 5596 } 5597 } 5598 } 5599 pkg.applicationInfo.dataDir = dataPath.getPath(); 5600 if (mShouldRestoreconData) { 5601 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5602 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5603 pkg.applicationInfo.uid); 5604 } 5605 } else { 5606 if (DEBUG_PACKAGE_SCANNING) { 5607 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5608 Log.v(TAG, "Want this data dir: " + dataPath); 5609 } 5610 //invoke installer to do the actual installation 5611 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5612 pkg.applicationInfo.seinfo); 5613 if (ret < 0) { 5614 // Error from installer 5615 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5616 "Unable to create data dirs [errorCode=" + ret + "]"); 5617 } 5618 5619 if (dataPath.exists()) { 5620 pkg.applicationInfo.dataDir = dataPath.getPath(); 5621 } else { 5622 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5623 pkg.applicationInfo.dataDir = null; 5624 } 5625 } 5626 5627 pkgSetting.uidError = uidError; 5628 } 5629 5630 final String path = scanFile.getPath(); 5631 final String codePath = pkg.applicationInfo.getCodePath(); 5632 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5633 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5634 setBundledAppAbisAndRoots(pkg, pkgSetting); 5635 5636 // If we haven't found any native libraries for the app, check if it has 5637 // renderscript code. We'll need to force the app to 32 bit if it has 5638 // renderscript bitcode. 5639 if (pkg.applicationInfo.primaryCpuAbi == null 5640 && pkg.applicationInfo.secondaryCpuAbi == null 5641 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5642 NativeLibraryHelper.Handle handle = null; 5643 try { 5644 handle = NativeLibraryHelper.Handle.create(scanFile); 5645 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5646 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5647 } 5648 } catch (IOException ioe) { 5649 Slog.w(TAG, "Error scanning system app : " + ioe); 5650 } finally { 5651 IoUtils.closeQuietly(handle); 5652 } 5653 } 5654 5655 setNativeLibraryPaths(pkg); 5656 } else { 5657 // TODO: We can probably be smarter about this stuff. For installed apps, 5658 // we can calculate this information at install time once and for all. For 5659 // system apps, we can probably assume that this information doesn't change 5660 // after the first boot scan. As things stand, we do lots of unnecessary work. 5661 5662 // Give ourselves some initial paths; we'll come back for another 5663 // pass once we've determined ABI below. 5664 setNativeLibraryPaths(pkg); 5665 5666 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 5667 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5668 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5669 5670 NativeLibraryHelper.Handle handle = null; 5671 try { 5672 handle = NativeLibraryHelper.Handle.create(scanFile); 5673 // TODO(multiArch): This can be null for apps that didn't go through the 5674 // usual installation process. We can calculate it again, like we 5675 // do during install time. 5676 // 5677 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5678 // unnecessary. 5679 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5680 5681 // Null out the abis so that they can be recalculated. 5682 pkg.applicationInfo.primaryCpuAbi = null; 5683 pkg.applicationInfo.secondaryCpuAbi = null; 5684 if (isMultiArch(pkg.applicationInfo)) { 5685 // Warn if we've set an abiOverride for multi-lib packages.. 5686 // By definition, we need to copy both 32 and 64 bit libraries for 5687 // such packages. 5688 if (pkg.cpuAbiOverride != null 5689 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5690 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5691 } 5692 5693 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5694 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5695 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5696 if (isAsec) { 5697 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5698 } else { 5699 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5700 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5701 useIsaSpecificSubdirs); 5702 } 5703 } 5704 5705 maybeThrowExceptionForMultiArchCopy( 5706 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5707 5708 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5709 if (isAsec) { 5710 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5711 } else { 5712 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5713 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5714 useIsaSpecificSubdirs); 5715 } 5716 } 5717 5718 maybeThrowExceptionForMultiArchCopy( 5719 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5720 5721 if (abi64 >= 0) { 5722 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5723 } 5724 5725 if (abi32 >= 0) { 5726 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5727 if (abi64 >= 0) { 5728 pkg.applicationInfo.secondaryCpuAbi = abi; 5729 } else { 5730 pkg.applicationInfo.primaryCpuAbi = abi; 5731 } 5732 } 5733 } else { 5734 String[] abiList = (cpuAbiOverride != null) ? 5735 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5736 5737 // Enable gross and lame hacks for apps that are built with old 5738 // SDK tools. We must scan their APKs for renderscript bitcode and 5739 // not launch them if it's present. Don't bother checking on devices 5740 // that don't have 64 bit support. 5741 boolean needsRenderScriptOverride = false; 5742 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5743 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5744 abiList = Build.SUPPORTED_32_BIT_ABIS; 5745 needsRenderScriptOverride = true; 5746 } 5747 5748 final int copyRet; 5749 if (isAsec) { 5750 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5751 } else { 5752 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5753 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5754 } 5755 5756 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5757 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5758 "Error unpackaging native libs for app, errorCode=" + copyRet); 5759 } 5760 5761 if (copyRet >= 0) { 5762 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5763 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5764 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5765 } else if (needsRenderScriptOverride) { 5766 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5767 } 5768 } 5769 } catch (IOException ioe) { 5770 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5771 } finally { 5772 IoUtils.closeQuietly(handle); 5773 } 5774 5775 // Now that we've calculated the ABIs and determined if it's an internal app, 5776 // we will go ahead and populate the nativeLibraryPath. 5777 setNativeLibraryPaths(pkg); 5778 5779 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5780 final int[] userIds = sUserManager.getUserIds(); 5781 synchronized (mInstallLock) { 5782 // Create a native library symlink only if we have native libraries 5783 // and if the native libraries are 32 bit libraries. We do not provide 5784 // this symlink for 64 bit libraries. 5785 if (pkg.applicationInfo.primaryCpuAbi != null && 5786 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5787 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5788 for (int userId : userIds) { 5789 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5790 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5791 "Failed linking native library dir (user=" + userId + ")"); 5792 } 5793 } 5794 } 5795 } 5796 } 5797 5798 // This is a special case for the "system" package, where the ABI is 5799 // dictated by the zygote configuration (and init.rc). We should keep track 5800 // of this ABI so that we can deal with "normal" applications that run under 5801 // the same UID correctly. 5802 if (mPlatformPackage == pkg) { 5803 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5804 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5805 } 5806 5807 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5808 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5809 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5810 // Copy the derived override back to the parsed package, so that we can 5811 // update the package settings accordingly. 5812 pkg.cpuAbiOverride = cpuAbiOverride; 5813 5814 if (DEBUG_ABI_SELECTION) { 5815 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5816 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5817 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5818 } 5819 5820 // Push the derived path down into PackageSettings so we know what to 5821 // clean up at uninstall time. 5822 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5823 5824 if (DEBUG_ABI_SELECTION) { 5825 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5826 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5827 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5828 } 5829 5830 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5831 // We don't do this here during boot because we can do it all 5832 // at once after scanning all existing packages. 5833 // 5834 // We also do this *before* we perform dexopt on this package, so that 5835 // we can avoid redundant dexopts, and also to make sure we've got the 5836 // code and package path correct. 5837 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5838 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5839 } 5840 5841 if ((scanFlags & SCAN_NO_DEX) == 0) { 5842 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 5843 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 5844 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5845 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5846 } 5847 } 5848 5849 if (mFactoryTest && pkg.requestedPermissions.contains( 5850 android.Manifest.permission.FACTORY_TEST)) { 5851 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5852 } 5853 5854 ArrayList<PackageParser.Package> clientLibPkgs = null; 5855 5856 // writer 5857 synchronized (mPackages) { 5858 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5859 // Only system apps can add new shared libraries. 5860 if (pkg.libraryNames != null) { 5861 for (int i=0; i<pkg.libraryNames.size(); i++) { 5862 String name = pkg.libraryNames.get(i); 5863 boolean allowed = false; 5864 if (isUpdatedSystemApp(pkg)) { 5865 // New library entries can only be added through the 5866 // system image. This is important to get rid of a lot 5867 // of nasty edge cases: for example if we allowed a non- 5868 // system update of the app to add a library, then uninstalling 5869 // the update would make the library go away, and assumptions 5870 // we made such as through app install filtering would now 5871 // have allowed apps on the device which aren't compatible 5872 // with it. Better to just have the restriction here, be 5873 // conservative, and create many fewer cases that can negatively 5874 // impact the user experience. 5875 final PackageSetting sysPs = mSettings 5876 .getDisabledSystemPkgLPr(pkg.packageName); 5877 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5878 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5879 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5880 allowed = true; 5881 allowed = true; 5882 break; 5883 } 5884 } 5885 } 5886 } else { 5887 allowed = true; 5888 } 5889 if (allowed) { 5890 if (!mSharedLibraries.containsKey(name)) { 5891 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5892 } else if (!name.equals(pkg.packageName)) { 5893 Slog.w(TAG, "Package " + pkg.packageName + " library " 5894 + name + " already exists; skipping"); 5895 } 5896 } else { 5897 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5898 + name + " that is not declared on system image; skipping"); 5899 } 5900 } 5901 if ((scanFlags&SCAN_BOOTING) == 0) { 5902 // If we are not booting, we need to update any applications 5903 // that are clients of our shared library. If we are booting, 5904 // this will all be done once the scan is complete. 5905 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5906 } 5907 } 5908 } 5909 } 5910 5911 // We also need to dexopt any apps that are dependent on this library. Note that 5912 // if these fail, we should abort the install since installing the library will 5913 // result in some apps being broken. 5914 if (clientLibPkgs != null) { 5915 if ((scanFlags & SCAN_NO_DEX) == 0) { 5916 for (int i = 0; i < clientLibPkgs.size(); i++) { 5917 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5918 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 5919 null /* instruction sets */, forceDex, 5920 (scanFlags & SCAN_DEFER_DEX) != 0, false); 5921 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5922 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5923 "scanPackageLI failed to dexopt clientLibPkgs"); 5924 } 5925 } 5926 } 5927 } 5928 5929 // Request the ActivityManager to kill the process(only for existing packages) 5930 // so that we do not end up in a confused state while the user is still using the older 5931 // version of the application while the new one gets installed. 5932 if ((scanFlags & SCAN_REPLACING) != 0) { 5933 killApplication(pkg.applicationInfo.packageName, 5934 pkg.applicationInfo.uid, "update pkg"); 5935 } 5936 5937 // Also need to kill any apps that are dependent on the library. 5938 if (clientLibPkgs != null) { 5939 for (int i=0; i<clientLibPkgs.size(); i++) { 5940 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5941 killApplication(clientPkg.applicationInfo.packageName, 5942 clientPkg.applicationInfo.uid, "update lib"); 5943 } 5944 } 5945 5946 // writer 5947 synchronized (mPackages) { 5948 // We don't expect installation to fail beyond this point 5949 5950 // Add the new setting to mSettings 5951 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5952 // Add the new setting to mPackages 5953 mPackages.put(pkg.applicationInfo.packageName, pkg); 5954 // Make sure we don't accidentally delete its data. 5955 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5956 while (iter.hasNext()) { 5957 PackageCleanItem item = iter.next(); 5958 if (pkgName.equals(item.packageName)) { 5959 iter.remove(); 5960 } 5961 } 5962 5963 // Take care of first install / last update times. 5964 if (currentTime != 0) { 5965 if (pkgSetting.firstInstallTime == 0) { 5966 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5967 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5968 pkgSetting.lastUpdateTime = currentTime; 5969 } 5970 } else if (pkgSetting.firstInstallTime == 0) { 5971 // We need *something*. Take time time stamp of the file. 5972 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5973 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5974 if (scanFileTime != pkgSetting.timeStamp) { 5975 // A package on the system image has changed; consider this 5976 // to be an update. 5977 pkgSetting.lastUpdateTime = scanFileTime; 5978 } 5979 } 5980 5981 // Add the package's KeySets to the global KeySetManagerService 5982 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5983 try { 5984 // Old KeySetData no longer valid. 5985 ksms.removeAppKeySetDataLPw(pkg.packageName); 5986 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5987 if (pkg.mKeySetMapping != null) { 5988 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5989 pkg.mKeySetMapping.entrySet()) { 5990 if (entry.getValue() != null) { 5991 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5992 entry.getValue(), entry.getKey()); 5993 } 5994 } 5995 if (pkg.mUpgradeKeySets != null) { 5996 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5997 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5998 } 5999 } 6000 } 6001 } catch (NullPointerException e) { 6002 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6003 } catch (IllegalArgumentException e) { 6004 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6005 } 6006 6007 int N = pkg.providers.size(); 6008 StringBuilder r = null; 6009 int i; 6010 for (i=0; i<N; i++) { 6011 PackageParser.Provider p = pkg.providers.get(i); 6012 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6013 p.info.processName, pkg.applicationInfo.uid); 6014 mProviders.addProvider(p); 6015 p.syncable = p.info.isSyncable; 6016 if (p.info.authority != null) { 6017 String names[] = p.info.authority.split(";"); 6018 p.info.authority = null; 6019 for (int j = 0; j < names.length; j++) { 6020 if (j == 1 && p.syncable) { 6021 // We only want the first authority for a provider to possibly be 6022 // syncable, so if we already added this provider using a different 6023 // authority clear the syncable flag. We copy the provider before 6024 // changing it because the mProviders object contains a reference 6025 // to a provider that we don't want to change. 6026 // Only do this for the second authority since the resulting provider 6027 // object can be the same for all future authorities for this provider. 6028 p = new PackageParser.Provider(p); 6029 p.syncable = false; 6030 } 6031 if (!mProvidersByAuthority.containsKey(names[j])) { 6032 mProvidersByAuthority.put(names[j], p); 6033 if (p.info.authority == null) { 6034 p.info.authority = names[j]; 6035 } else { 6036 p.info.authority = p.info.authority + ";" + names[j]; 6037 } 6038 if (DEBUG_PACKAGE_SCANNING) { 6039 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6040 Log.d(TAG, "Registered content provider: " + names[j] 6041 + ", className = " + p.info.name + ", isSyncable = " 6042 + p.info.isSyncable); 6043 } 6044 } else { 6045 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6046 Slog.w(TAG, "Skipping provider name " + names[j] + 6047 " (in package " + pkg.applicationInfo.packageName + 6048 "): name already used by " 6049 + ((other != null && other.getComponentName() != null) 6050 ? other.getComponentName().getPackageName() : "?")); 6051 } 6052 } 6053 } 6054 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6055 if (r == null) { 6056 r = new StringBuilder(256); 6057 } else { 6058 r.append(' '); 6059 } 6060 r.append(p.info.name); 6061 } 6062 } 6063 if (r != null) { 6064 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6065 } 6066 6067 N = pkg.services.size(); 6068 r = null; 6069 for (i=0; i<N; i++) { 6070 PackageParser.Service s = pkg.services.get(i); 6071 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6072 s.info.processName, pkg.applicationInfo.uid); 6073 mServices.addService(s); 6074 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6075 if (r == null) { 6076 r = new StringBuilder(256); 6077 } else { 6078 r.append(' '); 6079 } 6080 r.append(s.info.name); 6081 } 6082 } 6083 if (r != null) { 6084 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6085 } 6086 6087 N = pkg.receivers.size(); 6088 r = null; 6089 for (i=0; i<N; i++) { 6090 PackageParser.Activity a = pkg.receivers.get(i); 6091 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6092 a.info.processName, pkg.applicationInfo.uid); 6093 mReceivers.addActivity(a, "receiver"); 6094 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6095 if (r == null) { 6096 r = new StringBuilder(256); 6097 } else { 6098 r.append(' '); 6099 } 6100 r.append(a.info.name); 6101 } 6102 } 6103 if (r != null) { 6104 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6105 } 6106 6107 N = pkg.activities.size(); 6108 r = null; 6109 for (i=0; i<N; i++) { 6110 PackageParser.Activity a = pkg.activities.get(i); 6111 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6112 a.info.processName, pkg.applicationInfo.uid); 6113 mActivities.addActivity(a, "activity"); 6114 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6115 if (r == null) { 6116 r = new StringBuilder(256); 6117 } else { 6118 r.append(' '); 6119 } 6120 r.append(a.info.name); 6121 } 6122 } 6123 if (r != null) { 6124 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6125 } 6126 6127 N = pkg.permissionGroups.size(); 6128 r = null; 6129 for (i=0; i<N; i++) { 6130 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6131 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6132 if (cur == null) { 6133 mPermissionGroups.put(pg.info.name, pg); 6134 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6135 if (r == null) { 6136 r = new StringBuilder(256); 6137 } else { 6138 r.append(' '); 6139 } 6140 r.append(pg.info.name); 6141 } 6142 } else { 6143 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6144 + pg.info.packageName + " ignored: original from " 6145 + cur.info.packageName); 6146 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6147 if (r == null) { 6148 r = new StringBuilder(256); 6149 } else { 6150 r.append(' '); 6151 } 6152 r.append("DUP:"); 6153 r.append(pg.info.name); 6154 } 6155 } 6156 } 6157 if (r != null) { 6158 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6159 } 6160 6161 N = pkg.permissions.size(); 6162 r = null; 6163 for (i=0; i<N; i++) { 6164 PackageParser.Permission p = pkg.permissions.get(i); 6165 ArrayMap<String, BasePermission> permissionMap = 6166 p.tree ? mSettings.mPermissionTrees 6167 : mSettings.mPermissions; 6168 p.group = mPermissionGroups.get(p.info.group); 6169 if (p.info.group == null || p.group != null) { 6170 BasePermission bp = permissionMap.get(p.info.name); 6171 6172 // Allow system apps to redefine non-system permissions 6173 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6174 final boolean currentOwnerIsSystem = (bp.perm != null 6175 && isSystemApp(bp.perm.owner)); 6176 if (isSystemApp(p.owner)) { 6177 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6178 // It's a built-in permission and no owner, take ownership now 6179 bp.packageSetting = pkgSetting; 6180 bp.perm = p; 6181 bp.uid = pkg.applicationInfo.uid; 6182 bp.sourcePackage = p.info.packageName; 6183 } else if (!currentOwnerIsSystem) { 6184 String msg = "New decl " + p.owner + " of permission " 6185 + p.info.name + " is system; overriding " + bp.sourcePackage; 6186 reportSettingsProblem(Log.WARN, msg); 6187 bp = null; 6188 } 6189 } 6190 } 6191 6192 if (bp == null) { 6193 bp = new BasePermission(p.info.name, p.info.packageName, 6194 BasePermission.TYPE_NORMAL); 6195 permissionMap.put(p.info.name, bp); 6196 } 6197 6198 if (bp.perm == null) { 6199 if (bp.sourcePackage == null 6200 || bp.sourcePackage.equals(p.info.packageName)) { 6201 BasePermission tree = findPermissionTreeLP(p.info.name); 6202 if (tree == null 6203 || tree.sourcePackage.equals(p.info.packageName)) { 6204 bp.packageSetting = pkgSetting; 6205 bp.perm = p; 6206 bp.uid = pkg.applicationInfo.uid; 6207 bp.sourcePackage = p.info.packageName; 6208 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6209 if (r == null) { 6210 r = new StringBuilder(256); 6211 } else { 6212 r.append(' '); 6213 } 6214 r.append(p.info.name); 6215 } 6216 } else { 6217 Slog.w(TAG, "Permission " + p.info.name + " from package " 6218 + p.info.packageName + " ignored: base tree " 6219 + tree.name + " is from package " 6220 + tree.sourcePackage); 6221 } 6222 } else { 6223 Slog.w(TAG, "Permission " + p.info.name + " from package " 6224 + p.info.packageName + " ignored: original from " 6225 + bp.sourcePackage); 6226 } 6227 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6228 if (r == null) { 6229 r = new StringBuilder(256); 6230 } else { 6231 r.append(' '); 6232 } 6233 r.append("DUP:"); 6234 r.append(p.info.name); 6235 } 6236 if (bp.perm == p) { 6237 bp.protectionLevel = p.info.protectionLevel; 6238 } 6239 } else { 6240 Slog.w(TAG, "Permission " + p.info.name + " from package " 6241 + p.info.packageName + " ignored: no group " 6242 + p.group); 6243 } 6244 } 6245 if (r != null) { 6246 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6247 } 6248 6249 N = pkg.instrumentation.size(); 6250 r = null; 6251 for (i=0; i<N; i++) { 6252 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6253 a.info.packageName = pkg.applicationInfo.packageName; 6254 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6255 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6256 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6257 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6258 a.info.dataDir = pkg.applicationInfo.dataDir; 6259 6260 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6261 // need other information about the application, like the ABI and what not ? 6262 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6263 mInstrumentation.put(a.getComponentName(), a); 6264 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6265 if (r == null) { 6266 r = new StringBuilder(256); 6267 } else { 6268 r.append(' '); 6269 } 6270 r.append(a.info.name); 6271 } 6272 } 6273 if (r != null) { 6274 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6275 } 6276 6277 if (pkg.protectedBroadcasts != null) { 6278 N = pkg.protectedBroadcasts.size(); 6279 for (i=0; i<N; i++) { 6280 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6281 } 6282 } 6283 6284 pkgSetting.setTimeStamp(scanFileTime); 6285 6286 // Create idmap files for pairs of (packages, overlay packages). 6287 // Note: "android", ie framework-res.apk, is handled by native layers. 6288 if (pkg.mOverlayTarget != null) { 6289 // This is an overlay package. 6290 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6291 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6292 mOverlays.put(pkg.mOverlayTarget, 6293 new ArrayMap<String, PackageParser.Package>()); 6294 } 6295 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6296 map.put(pkg.packageName, pkg); 6297 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6298 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6299 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6300 "scanPackageLI failed to createIdmap"); 6301 } 6302 } 6303 } else if (mOverlays.containsKey(pkg.packageName) && 6304 !pkg.packageName.equals("android")) { 6305 // This is a regular package, with one or more known overlay packages. 6306 createIdmapsForPackageLI(pkg); 6307 } 6308 } 6309 6310 return pkg; 6311 } 6312 6313 /** 6314 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6315 * i.e, so that all packages can be run inside a single process if required. 6316 * 6317 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6318 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6319 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6320 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6321 * updating a package that belongs to a shared user. 6322 * 6323 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6324 * adds unnecessary complexity. 6325 */ 6326 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6327 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6328 String requiredInstructionSet = null; 6329 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6330 requiredInstructionSet = VMRuntime.getInstructionSet( 6331 scannedPackage.applicationInfo.primaryCpuAbi); 6332 } 6333 6334 PackageSetting requirer = null; 6335 for (PackageSetting ps : packagesForUser) { 6336 // If packagesForUser contains scannedPackage, we skip it. This will happen 6337 // when scannedPackage is an update of an existing package. Without this check, 6338 // we will never be able to change the ABI of any package belonging to a shared 6339 // user, even if it's compatible with other packages. 6340 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6341 if (ps.primaryCpuAbiString == null) { 6342 continue; 6343 } 6344 6345 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6346 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6347 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6348 // this but there's not much we can do. 6349 String errorMessage = "Instruction set mismatch, " 6350 + ((requirer == null) ? "[caller]" : requirer) 6351 + " requires " + requiredInstructionSet + " whereas " + ps 6352 + " requires " + instructionSet; 6353 Slog.w(TAG, errorMessage); 6354 } 6355 6356 if (requiredInstructionSet == null) { 6357 requiredInstructionSet = instructionSet; 6358 requirer = ps; 6359 } 6360 } 6361 } 6362 6363 if (requiredInstructionSet != null) { 6364 String adjustedAbi; 6365 if (requirer != null) { 6366 // requirer != null implies that either scannedPackage was null or that scannedPackage 6367 // did not require an ABI, in which case we have to adjust scannedPackage to match 6368 // the ABI of the set (which is the same as requirer's ABI) 6369 adjustedAbi = requirer.primaryCpuAbiString; 6370 if (scannedPackage != null) { 6371 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6372 } 6373 } else { 6374 // requirer == null implies that we're updating all ABIs in the set to 6375 // match scannedPackage. 6376 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6377 } 6378 6379 for (PackageSetting ps : packagesForUser) { 6380 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6381 if (ps.primaryCpuAbiString != null) { 6382 continue; 6383 } 6384 6385 ps.primaryCpuAbiString = adjustedAbi; 6386 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6387 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6388 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6389 6390 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6391 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6392 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6393 ps.primaryCpuAbiString = null; 6394 ps.pkg.applicationInfo.primaryCpuAbi = null; 6395 return; 6396 } else { 6397 mInstaller.rmdex(ps.codePathString, 6398 getDexCodeInstructionSet(getPreferredInstructionSet())); 6399 } 6400 } 6401 } 6402 } 6403 } 6404 } 6405 6406 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6407 synchronized (mPackages) { 6408 mResolverReplaced = true; 6409 // Set up information for custom user intent resolution activity. 6410 mResolveActivity.applicationInfo = pkg.applicationInfo; 6411 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6412 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6413 mResolveActivity.processName = pkg.applicationInfo.packageName; 6414 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6415 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6416 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6417 mResolveActivity.theme = 0; 6418 mResolveActivity.exported = true; 6419 mResolveActivity.enabled = true; 6420 mResolveInfo.activityInfo = mResolveActivity; 6421 mResolveInfo.priority = 0; 6422 mResolveInfo.preferredOrder = 0; 6423 mResolveInfo.match = 0; 6424 mResolveComponentName = mCustomResolverComponentName; 6425 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6426 mResolveComponentName); 6427 } 6428 } 6429 6430 private static String calculateBundledApkRoot(final String codePathString) { 6431 final File codePath = new File(codePathString); 6432 final File codeRoot; 6433 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6434 codeRoot = Environment.getRootDirectory(); 6435 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6436 codeRoot = Environment.getOemDirectory(); 6437 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6438 codeRoot = Environment.getVendorDirectory(); 6439 } else { 6440 // Unrecognized code path; take its top real segment as the apk root: 6441 // e.g. /something/app/blah.apk => /something 6442 try { 6443 File f = codePath.getCanonicalFile(); 6444 File parent = f.getParentFile(); // non-null because codePath is a file 6445 File tmp; 6446 while ((tmp = parent.getParentFile()) != null) { 6447 f = parent; 6448 parent = tmp; 6449 } 6450 codeRoot = f; 6451 Slog.w(TAG, "Unrecognized code path " 6452 + codePath + " - using " + codeRoot); 6453 } catch (IOException e) { 6454 // Can't canonicalize the code path -- shenanigans? 6455 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6456 return Environment.getRootDirectory().getPath(); 6457 } 6458 } 6459 return codeRoot.getPath(); 6460 } 6461 6462 /** 6463 * Derive and set the location of native libraries for the given package, 6464 * which varies depending on where and how the package was installed. 6465 */ 6466 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6467 final ApplicationInfo info = pkg.applicationInfo; 6468 final String codePath = pkg.codePath; 6469 final File codeFile = new File(codePath); 6470 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6471 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6472 6473 info.nativeLibraryRootDir = null; 6474 info.nativeLibraryRootRequiresIsa = false; 6475 info.nativeLibraryDir = null; 6476 info.secondaryNativeLibraryDir = null; 6477 6478 if (isApkFile(codeFile)) { 6479 // Monolithic install 6480 if (bundledApp) { 6481 // If "/system/lib64/apkname" exists, assume that is the per-package 6482 // native library directory to use; otherwise use "/system/lib/apkname". 6483 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6484 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6485 getPrimaryInstructionSet(info)); 6486 6487 // This is a bundled system app so choose the path based on the ABI. 6488 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6489 // is just the default path. 6490 final String apkName = deriveCodePathName(codePath); 6491 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6492 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6493 apkName).getAbsolutePath(); 6494 6495 if (info.secondaryCpuAbi != null) { 6496 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6497 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6498 secondaryLibDir, apkName).getAbsolutePath(); 6499 } 6500 } else if (asecApp) { 6501 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6502 .getAbsolutePath(); 6503 } else { 6504 final String apkName = deriveCodePathName(codePath); 6505 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6506 .getAbsolutePath(); 6507 } 6508 6509 info.nativeLibraryRootRequiresIsa = false; 6510 info.nativeLibraryDir = info.nativeLibraryRootDir; 6511 } else { 6512 // Cluster install 6513 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6514 info.nativeLibraryRootRequiresIsa = true; 6515 6516 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6517 getPrimaryInstructionSet(info)).getAbsolutePath(); 6518 6519 if (info.secondaryCpuAbi != null) { 6520 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6521 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6522 } 6523 } 6524 } 6525 6526 /** 6527 * Calculate the abis and roots for a bundled app. These can uniquely 6528 * be determined from the contents of the system partition, i.e whether 6529 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6530 * of this information, and instead assume that the system was built 6531 * sensibly. 6532 */ 6533 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6534 PackageSetting pkgSetting) { 6535 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6536 6537 // If "/system/lib64/apkname" exists, assume that is the per-package 6538 // native library directory to use; otherwise use "/system/lib/apkname". 6539 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6540 setBundledAppAbi(pkg, apkRoot, apkName); 6541 // pkgSetting might be null during rescan following uninstall of updates 6542 // to a bundled app, so accommodate that possibility. The settings in 6543 // that case will be established later from the parsed package. 6544 // 6545 // If the settings aren't null, sync them up with what we've just derived. 6546 // note that apkRoot isn't stored in the package settings. 6547 if (pkgSetting != null) { 6548 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6549 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6550 } 6551 } 6552 6553 /** 6554 * Deduces the ABI of a bundled app and sets the relevant fields on the 6555 * parsed pkg object. 6556 * 6557 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6558 * under which system libraries are installed. 6559 * @param apkName the name of the installed package. 6560 */ 6561 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6562 final File codeFile = new File(pkg.codePath); 6563 6564 final boolean has64BitLibs; 6565 final boolean has32BitLibs; 6566 if (isApkFile(codeFile)) { 6567 // Monolithic install 6568 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6569 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6570 } else { 6571 // Cluster install 6572 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6573 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6574 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6575 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6576 has64BitLibs = (new File(rootDir, isa)).exists(); 6577 } else { 6578 has64BitLibs = false; 6579 } 6580 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6581 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6582 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6583 has32BitLibs = (new File(rootDir, isa)).exists(); 6584 } else { 6585 has32BitLibs = false; 6586 } 6587 } 6588 6589 if (has64BitLibs && !has32BitLibs) { 6590 // The package has 64 bit libs, but not 32 bit libs. Its primary 6591 // ABI should be 64 bit. We can safely assume here that the bundled 6592 // native libraries correspond to the most preferred ABI in the list. 6593 6594 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6595 pkg.applicationInfo.secondaryCpuAbi = null; 6596 } else if (has32BitLibs && !has64BitLibs) { 6597 // The package has 32 bit libs but not 64 bit libs. Its primary 6598 // ABI should be 32 bit. 6599 6600 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6601 pkg.applicationInfo.secondaryCpuAbi = null; 6602 } else if (has32BitLibs && has64BitLibs) { 6603 // The application has both 64 and 32 bit bundled libraries. We check 6604 // here that the app declares multiArch support, and warn if it doesn't. 6605 // 6606 // We will be lenient here and record both ABIs. The primary will be the 6607 // ABI that's higher on the list, i.e, a device that's configured to prefer 6608 // 64 bit apps will see a 64 bit primary ABI, 6609 6610 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6611 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6612 } 6613 6614 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6615 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6616 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6617 } else { 6618 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6619 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6620 } 6621 } else { 6622 pkg.applicationInfo.primaryCpuAbi = null; 6623 pkg.applicationInfo.secondaryCpuAbi = null; 6624 } 6625 } 6626 6627 private void killApplication(String pkgName, int appId, String reason) { 6628 // Request the ActivityManager to kill the process(only for existing packages) 6629 // so that we do not end up in a confused state while the user is still using the older 6630 // version of the application while the new one gets installed. 6631 IActivityManager am = ActivityManagerNative.getDefault(); 6632 if (am != null) { 6633 try { 6634 am.killApplicationWithAppId(pkgName, appId, reason); 6635 } catch (RemoteException e) { 6636 } 6637 } 6638 } 6639 6640 void removePackageLI(PackageSetting ps, boolean chatty) { 6641 if (DEBUG_INSTALL) { 6642 if (chatty) 6643 Log.d(TAG, "Removing package " + ps.name); 6644 } 6645 6646 // writer 6647 synchronized (mPackages) { 6648 mPackages.remove(ps.name); 6649 final PackageParser.Package pkg = ps.pkg; 6650 if (pkg != null) { 6651 cleanPackageDataStructuresLILPw(pkg, chatty); 6652 } 6653 } 6654 } 6655 6656 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6657 if (DEBUG_INSTALL) { 6658 if (chatty) 6659 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6660 } 6661 6662 // writer 6663 synchronized (mPackages) { 6664 mPackages.remove(pkg.applicationInfo.packageName); 6665 cleanPackageDataStructuresLILPw(pkg, chatty); 6666 } 6667 } 6668 6669 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6670 int N = pkg.providers.size(); 6671 StringBuilder r = null; 6672 int i; 6673 for (i=0; i<N; i++) { 6674 PackageParser.Provider p = pkg.providers.get(i); 6675 mProviders.removeProvider(p); 6676 if (p.info.authority == null) { 6677 6678 /* There was another ContentProvider with this authority when 6679 * this app was installed so this authority is null, 6680 * Ignore it as we don't have to unregister the provider. 6681 */ 6682 continue; 6683 } 6684 String names[] = p.info.authority.split(";"); 6685 for (int j = 0; j < names.length; j++) { 6686 if (mProvidersByAuthority.get(names[j]) == p) { 6687 mProvidersByAuthority.remove(names[j]); 6688 if (DEBUG_REMOVE) { 6689 if (chatty) 6690 Log.d(TAG, "Unregistered content provider: " + names[j] 6691 + ", className = " + p.info.name + ", isSyncable = " 6692 + p.info.isSyncable); 6693 } 6694 } 6695 } 6696 if (DEBUG_REMOVE && chatty) { 6697 if (r == null) { 6698 r = new StringBuilder(256); 6699 } else { 6700 r.append(' '); 6701 } 6702 r.append(p.info.name); 6703 } 6704 } 6705 if (r != null) { 6706 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6707 } 6708 6709 N = pkg.services.size(); 6710 r = null; 6711 for (i=0; i<N; i++) { 6712 PackageParser.Service s = pkg.services.get(i); 6713 mServices.removeService(s); 6714 if (chatty) { 6715 if (r == null) { 6716 r = new StringBuilder(256); 6717 } else { 6718 r.append(' '); 6719 } 6720 r.append(s.info.name); 6721 } 6722 } 6723 if (r != null) { 6724 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6725 } 6726 6727 N = pkg.receivers.size(); 6728 r = null; 6729 for (i=0; i<N; i++) { 6730 PackageParser.Activity a = pkg.receivers.get(i); 6731 mReceivers.removeActivity(a, "receiver"); 6732 if (DEBUG_REMOVE && chatty) { 6733 if (r == null) { 6734 r = new StringBuilder(256); 6735 } else { 6736 r.append(' '); 6737 } 6738 r.append(a.info.name); 6739 } 6740 } 6741 if (r != null) { 6742 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6743 } 6744 6745 N = pkg.activities.size(); 6746 r = null; 6747 for (i=0; i<N; i++) { 6748 PackageParser.Activity a = pkg.activities.get(i); 6749 mActivities.removeActivity(a, "activity"); 6750 if (DEBUG_REMOVE && chatty) { 6751 if (r == null) { 6752 r = new StringBuilder(256); 6753 } else { 6754 r.append(' '); 6755 } 6756 r.append(a.info.name); 6757 } 6758 } 6759 if (r != null) { 6760 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6761 } 6762 6763 N = pkg.permissions.size(); 6764 r = null; 6765 for (i=0; i<N; i++) { 6766 PackageParser.Permission p = pkg.permissions.get(i); 6767 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6768 if (bp == null) { 6769 bp = mSettings.mPermissionTrees.get(p.info.name); 6770 } 6771 if (bp != null && bp.perm == p) { 6772 bp.perm = null; 6773 if (DEBUG_REMOVE && chatty) { 6774 if (r == null) { 6775 r = new StringBuilder(256); 6776 } else { 6777 r.append(' '); 6778 } 6779 r.append(p.info.name); 6780 } 6781 } 6782 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6783 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6784 if (appOpPerms != null) { 6785 appOpPerms.remove(pkg.packageName); 6786 } 6787 } 6788 } 6789 if (r != null) { 6790 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6791 } 6792 6793 N = pkg.requestedPermissions.size(); 6794 r = null; 6795 for (i=0; i<N; i++) { 6796 String perm = pkg.requestedPermissions.get(i); 6797 BasePermission bp = mSettings.mPermissions.get(perm); 6798 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6799 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6800 if (appOpPerms != null) { 6801 appOpPerms.remove(pkg.packageName); 6802 if (appOpPerms.isEmpty()) { 6803 mAppOpPermissionPackages.remove(perm); 6804 } 6805 } 6806 } 6807 } 6808 if (r != null) { 6809 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6810 } 6811 6812 N = pkg.instrumentation.size(); 6813 r = null; 6814 for (i=0; i<N; i++) { 6815 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6816 mInstrumentation.remove(a.getComponentName()); 6817 if (DEBUG_REMOVE && chatty) { 6818 if (r == null) { 6819 r = new StringBuilder(256); 6820 } else { 6821 r.append(' '); 6822 } 6823 r.append(a.info.name); 6824 } 6825 } 6826 if (r != null) { 6827 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6828 } 6829 6830 r = null; 6831 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6832 // Only system apps can hold shared libraries. 6833 if (pkg.libraryNames != null) { 6834 for (i=0; i<pkg.libraryNames.size(); i++) { 6835 String name = pkg.libraryNames.get(i); 6836 SharedLibraryEntry cur = mSharedLibraries.get(name); 6837 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6838 mSharedLibraries.remove(name); 6839 if (DEBUG_REMOVE && chatty) { 6840 if (r == null) { 6841 r = new StringBuilder(256); 6842 } else { 6843 r.append(' '); 6844 } 6845 r.append(name); 6846 } 6847 } 6848 } 6849 } 6850 } 6851 if (r != null) { 6852 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6853 } 6854 } 6855 6856 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6857 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6858 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6859 return true; 6860 } 6861 } 6862 return false; 6863 } 6864 6865 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6866 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6867 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6868 6869 private void updatePermissionsLPw(String changingPkg, 6870 PackageParser.Package pkgInfo, int flags) { 6871 // Make sure there are no dangling permission trees. 6872 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6873 while (it.hasNext()) { 6874 final BasePermission bp = it.next(); 6875 if (bp.packageSetting == null) { 6876 // We may not yet have parsed the package, so just see if 6877 // we still know about its settings. 6878 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6879 } 6880 if (bp.packageSetting == null) { 6881 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6882 + " from package " + bp.sourcePackage); 6883 it.remove(); 6884 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6885 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6886 Slog.i(TAG, "Removing old permission tree: " + bp.name 6887 + " from package " + bp.sourcePackage); 6888 flags |= UPDATE_PERMISSIONS_ALL; 6889 it.remove(); 6890 } 6891 } 6892 } 6893 6894 // Make sure all dynamic permissions have been assigned to a package, 6895 // and make sure there are no dangling permissions. 6896 it = mSettings.mPermissions.values().iterator(); 6897 while (it.hasNext()) { 6898 final BasePermission bp = it.next(); 6899 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6900 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6901 + bp.name + " pkg=" + bp.sourcePackage 6902 + " info=" + bp.pendingInfo); 6903 if (bp.packageSetting == null && bp.pendingInfo != null) { 6904 final BasePermission tree = findPermissionTreeLP(bp.name); 6905 if (tree != null && tree.perm != null) { 6906 bp.packageSetting = tree.packageSetting; 6907 bp.perm = new PackageParser.Permission(tree.perm.owner, 6908 new PermissionInfo(bp.pendingInfo)); 6909 bp.perm.info.packageName = tree.perm.info.packageName; 6910 bp.perm.info.name = bp.name; 6911 bp.uid = tree.uid; 6912 } 6913 } 6914 } 6915 if (bp.packageSetting == null) { 6916 // We may not yet have parsed the package, so just see if 6917 // we still know about its settings. 6918 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6919 } 6920 if (bp.packageSetting == null) { 6921 Slog.w(TAG, "Removing dangling permission: " + bp.name 6922 + " from package " + bp.sourcePackage); 6923 it.remove(); 6924 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6925 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6926 Slog.i(TAG, "Removing old permission: " + bp.name 6927 + " from package " + bp.sourcePackage); 6928 flags |= UPDATE_PERMISSIONS_ALL; 6929 it.remove(); 6930 } 6931 } 6932 } 6933 6934 // Now update the permissions for all packages, in particular 6935 // replace the granted permissions of the system packages. 6936 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6937 for (PackageParser.Package pkg : mPackages.values()) { 6938 if (pkg != pkgInfo) { 6939 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6940 changingPkg); 6941 } 6942 } 6943 } 6944 6945 if (pkgInfo != null) { 6946 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6947 } 6948 } 6949 6950 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6951 String packageOfInterest) { 6952 // IMPORTANT: There are two types of permissions: install and runtime. 6953 // Install time permissions are granted when the app is installed to 6954 // all device users and users added in the future. Runtime permissions 6955 // are granted at runtime explicitly to specific users. Normal and signature 6956 // protected permissions are install time permissions. Dangerous permissions 6957 // are install permissions if the app's target SDK is Lollipop MR1 or older, 6958 // otherwise they are runtime permissions. This function does not manage 6959 // runtime permissions except for the case an app targeting Lollipop MR1 6960 // being upgraded to target a newer SDK, in which case dangerous permissions 6961 // are transformed from install time to runtime ones. 6962 6963 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6964 if (ps == null) { 6965 return; 6966 } 6967 6968 PermissionsState permissionsState = ps.getPermissionsState(); 6969 PermissionsState origPermissions = permissionsState; 6970 6971 boolean changedPermission = false; 6972 6973 if (replace) { 6974 ps.permissionsFixed = false; 6975 origPermissions = new PermissionsState(permissionsState); 6976 permissionsState.reset(); 6977 } 6978 6979 permissionsState.setGlobalGids(mGlobalGids); 6980 6981 final int N = pkg.requestedPermissions.size(); 6982 for (int i=0; i<N; i++) { 6983 final String name = pkg.requestedPermissions.get(i); 6984 final BasePermission bp = mSettings.mPermissions.get(name); 6985 6986 if (DEBUG_INSTALL) { 6987 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6988 } 6989 6990 if (bp == null || bp.packageSetting == null) { 6991 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6992 Slog.w(TAG, "Unknown permission " + name 6993 + " in package " + pkg.packageName); 6994 } 6995 continue; 6996 } 6997 6998 final String perm = bp.name; 6999 boolean allowedSig = false; 7000 int grant = GRANT_DENIED; 7001 7002 // Keep track of app op permissions. 7003 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7004 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7005 if (pkgs == null) { 7006 pkgs = new ArraySet<>(); 7007 mAppOpPermissionPackages.put(bp.name, pkgs); 7008 } 7009 pkgs.add(pkg.packageName); 7010 } 7011 7012 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7013 switch (level) { 7014 case PermissionInfo.PROTECTION_NORMAL: { 7015 // For all apps normal permissions are install time ones. 7016 grant = GRANT_INSTALL; 7017 } break; 7018 7019 case PermissionInfo.PROTECTION_DANGEROUS: { 7020 if (!RUNTIME_PERMISSIONS_ENABLED 7021 || pkg.applicationInfo.targetSdkVersion 7022 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7023 // For legacy apps dangerous permissions are install time ones. 7024 grant = GRANT_INSTALL; 7025 } else if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 7026 // For modern system apps dangerous permissions are install time ones. 7027 grant = GRANT_INSTALL; 7028 } else { 7029 if (origPermissions.hasInstallPermission(bp.name)) { 7030 // For legacy apps that became modern, install becomes runtime. 7031 grant = GRANT_UPGRADE; 7032 } else if (replace) { 7033 // For upgraded modern apps keep runtime permissions unchanged. 7034 grant = GRANT_RUNTIME; 7035 } 7036 } 7037 } break; 7038 7039 case PermissionInfo.PROTECTION_SIGNATURE: { 7040 // For all apps signature permissions are install time ones. 7041 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7042 if (allowedSig) { 7043 grant = GRANT_INSTALL; 7044 } 7045 } break; 7046 } 7047 7048 if (DEBUG_INSTALL) { 7049 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7050 } 7051 7052 if (grant != GRANT_DENIED) { 7053 if (!isSystemApp(ps) && ps.permissionsFixed) { 7054 // If this is an existing, non-system package, then 7055 // we can't add any new permissions to it. 7056 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7057 // Except... if this is a permission that was added 7058 // to the platform (note: need to only do this when 7059 // updating the platform). 7060 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7061 grant = GRANT_DENIED; 7062 } 7063 } 7064 } 7065 7066 switch (grant) { 7067 case GRANT_INSTALL: { 7068 // Grant an install permission. 7069 if (permissionsState.grantInstallPermission(bp) != 7070 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7071 changedPermission = true; 7072 } 7073 } break; 7074 7075 case GRANT_RUNTIME: { 7076 // Grant previously granted runtime permissions. 7077 for (int userId : UserManagerService.getInstance().getUserIds()) { 7078 // Make sure runtime permissions are loaded. 7079 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7080 if (permissionsState.grantRuntimePermission(bp, userId) != 7081 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7082 changedPermission = true; 7083 } 7084 } 7085 } 7086 } break; 7087 7088 case GRANT_UPGRADE: { 7089 // Grant runtime permissions for a previously held install permission. 7090 permissionsState.revokeInstallPermission(bp); 7091 for (int userId : UserManagerService.getInstance().getUserIds()) { 7092 // Make sure runtime permissions are loaded. 7093 if (permissionsState.grantRuntimePermission(bp, userId) != 7094 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7095 changedPermission = true; 7096 } 7097 } 7098 } break; 7099 7100 default: { 7101 if (packageOfInterest == null 7102 || packageOfInterest.equals(pkg.packageName)) { 7103 Slog.w(TAG, "Not granting permission " + perm 7104 + " to package " + pkg.packageName 7105 + " because it was previously installed without"); 7106 } 7107 } break; 7108 } 7109 } else { 7110 if (permissionsState.revokeInstallPermission(bp) != 7111 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7112 changedPermission = true; 7113 Slog.i(TAG, "Un-granting permission " + perm 7114 + " from package " + pkg.packageName 7115 + " (protectionLevel=" + bp.protectionLevel 7116 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7117 + ")"); 7118 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7119 // Don't print warning for app op permissions, since it is fine for them 7120 // not to be granted, there is a UI for the user to decide. 7121 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7122 Slog.w(TAG, "Not granting permission " + perm 7123 + " to package " + pkg.packageName 7124 + " (protectionLevel=" + bp.protectionLevel 7125 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7126 + ")"); 7127 } 7128 } 7129 } 7130 } 7131 7132 if ((changedPermission || replace) && !ps.permissionsFixed && 7133 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7134 // This is the first that we have heard about this package, so the 7135 // permissions we have now selected are fixed until explicitly 7136 // changed. 7137 ps.permissionsFixed = true; 7138 } 7139 } 7140 7141 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7142 boolean allowed = false; 7143 final int NP = PackageParser.NEW_PERMISSIONS.length; 7144 for (int ip=0; ip<NP; ip++) { 7145 final PackageParser.NewPermissionInfo npi 7146 = PackageParser.NEW_PERMISSIONS[ip]; 7147 if (npi.name.equals(perm) 7148 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7149 allowed = true; 7150 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7151 + pkg.packageName); 7152 break; 7153 } 7154 } 7155 return allowed; 7156 } 7157 7158 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7159 BasePermission bp, PermissionsState origPermissions) { 7160 boolean allowed; 7161 allowed = (compareSignatures( 7162 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7163 == PackageManager.SIGNATURE_MATCH) 7164 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7165 == PackageManager.SIGNATURE_MATCH); 7166 if (!allowed && (bp.protectionLevel 7167 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7168 if (isSystemApp(pkg)) { 7169 // For updated system applications, a system permission 7170 // is granted only if it had been defined by the original application. 7171 if (isUpdatedSystemApp(pkg)) { 7172 final PackageSetting sysPs = mSettings 7173 .getDisabledSystemPkgLPr(pkg.packageName); 7174 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7175 // If the original was granted this permission, we take 7176 // that grant decision as read and propagate it to the 7177 // update. 7178 if (sysPs.isPrivileged()) { 7179 allowed = true; 7180 } 7181 } else { 7182 // The system apk may have been updated with an older 7183 // version of the one on the data partition, but which 7184 // granted a new system permission that it didn't have 7185 // before. In this case we do want to allow the app to 7186 // now get the new permission if the ancestral apk is 7187 // privileged to get it. 7188 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7189 for (int j=0; 7190 j<sysPs.pkg.requestedPermissions.size(); j++) { 7191 if (perm.equals( 7192 sysPs.pkg.requestedPermissions.get(j))) { 7193 allowed = true; 7194 break; 7195 } 7196 } 7197 } 7198 } 7199 } else { 7200 allowed = isPrivilegedApp(pkg); 7201 } 7202 } 7203 } 7204 if (!allowed && (bp.protectionLevel 7205 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7206 // For development permissions, a development permission 7207 // is granted only if it was already granted. 7208 allowed = origPermissions.hasInstallPermission(perm); 7209 } 7210 return allowed; 7211 } 7212 7213 final class ActivityIntentResolver 7214 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7215 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7216 boolean defaultOnly, int userId) { 7217 if (!sUserManager.exists(userId)) return null; 7218 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7219 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7220 } 7221 7222 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7223 int userId) { 7224 if (!sUserManager.exists(userId)) return null; 7225 mFlags = flags; 7226 return super.queryIntent(intent, resolvedType, 7227 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7228 } 7229 7230 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7231 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7232 if (!sUserManager.exists(userId)) return null; 7233 if (packageActivities == null) { 7234 return null; 7235 } 7236 mFlags = flags; 7237 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7238 final int N = packageActivities.size(); 7239 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7240 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7241 7242 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7243 for (int i = 0; i < N; ++i) { 7244 intentFilters = packageActivities.get(i).intents; 7245 if (intentFilters != null && intentFilters.size() > 0) { 7246 PackageParser.ActivityIntentInfo[] array = 7247 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7248 intentFilters.toArray(array); 7249 listCut.add(array); 7250 } 7251 } 7252 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7253 } 7254 7255 public final void addActivity(PackageParser.Activity a, String type) { 7256 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7257 mActivities.put(a.getComponentName(), a); 7258 if (DEBUG_SHOW_INFO) 7259 Log.v( 7260 TAG, " " + type + " " + 7261 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7262 if (DEBUG_SHOW_INFO) 7263 Log.v(TAG, " Class=" + a.info.name); 7264 final int NI = a.intents.size(); 7265 for (int j=0; j<NI; j++) { 7266 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7267 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7268 intent.setPriority(0); 7269 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7270 + a.className + " with priority > 0, forcing to 0"); 7271 } 7272 if (DEBUG_SHOW_INFO) { 7273 Log.v(TAG, " IntentFilter:"); 7274 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7275 } 7276 if (!intent.debugCheck()) { 7277 Log.w(TAG, "==> For Activity " + a.info.name); 7278 } 7279 addFilter(intent); 7280 } 7281 } 7282 7283 public final void removeActivity(PackageParser.Activity a, String type) { 7284 mActivities.remove(a.getComponentName()); 7285 if (DEBUG_SHOW_INFO) { 7286 Log.v(TAG, " " + type + " " 7287 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7288 : a.info.name) + ":"); 7289 Log.v(TAG, " Class=" + a.info.name); 7290 } 7291 final int NI = a.intents.size(); 7292 for (int j=0; j<NI; j++) { 7293 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7294 if (DEBUG_SHOW_INFO) { 7295 Log.v(TAG, " IntentFilter:"); 7296 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7297 } 7298 removeFilter(intent); 7299 } 7300 } 7301 7302 @Override 7303 protected boolean allowFilterResult( 7304 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7305 ActivityInfo filterAi = filter.activity.info; 7306 for (int i=dest.size()-1; i>=0; i--) { 7307 ActivityInfo destAi = dest.get(i).activityInfo; 7308 if (destAi.name == filterAi.name 7309 && destAi.packageName == filterAi.packageName) { 7310 return false; 7311 } 7312 } 7313 return true; 7314 } 7315 7316 @Override 7317 protected ActivityIntentInfo[] newArray(int size) { 7318 return new ActivityIntentInfo[size]; 7319 } 7320 7321 @Override 7322 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7323 if (!sUserManager.exists(userId)) return true; 7324 PackageParser.Package p = filter.activity.owner; 7325 if (p != null) { 7326 PackageSetting ps = (PackageSetting)p.mExtras; 7327 if (ps != null) { 7328 // System apps are never considered stopped for purposes of 7329 // filtering, because there may be no way for the user to 7330 // actually re-launch them. 7331 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7332 && ps.getStopped(userId); 7333 } 7334 } 7335 return false; 7336 } 7337 7338 @Override 7339 protected boolean isPackageForFilter(String packageName, 7340 PackageParser.ActivityIntentInfo info) { 7341 return packageName.equals(info.activity.owner.packageName); 7342 } 7343 7344 @Override 7345 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7346 int match, int userId) { 7347 if (!sUserManager.exists(userId)) return null; 7348 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7349 return null; 7350 } 7351 final PackageParser.Activity activity = info.activity; 7352 if (mSafeMode && (activity.info.applicationInfo.flags 7353 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7354 return null; 7355 } 7356 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7357 if (ps == null) { 7358 return null; 7359 } 7360 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7361 ps.readUserState(userId), userId); 7362 if (ai == null) { 7363 return null; 7364 } 7365 final ResolveInfo res = new ResolveInfo(); 7366 res.activityInfo = ai; 7367 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7368 res.filter = info; 7369 } 7370 res.priority = info.getPriority(); 7371 res.preferredOrder = activity.owner.mPreferredOrder; 7372 //System.out.println("Result: " + res.activityInfo.className + 7373 // " = " + res.priority); 7374 res.match = match; 7375 res.isDefault = info.hasDefault; 7376 res.labelRes = info.labelRes; 7377 res.nonLocalizedLabel = info.nonLocalizedLabel; 7378 if (userNeedsBadging(userId)) { 7379 res.noResourceId = true; 7380 } else { 7381 res.icon = info.icon; 7382 } 7383 res.system = isSystemApp(res.activityInfo.applicationInfo); 7384 return res; 7385 } 7386 7387 @Override 7388 protected void sortResults(List<ResolveInfo> results) { 7389 Collections.sort(results, mResolvePrioritySorter); 7390 } 7391 7392 @Override 7393 protected void dumpFilter(PrintWriter out, String prefix, 7394 PackageParser.ActivityIntentInfo filter) { 7395 out.print(prefix); out.print( 7396 Integer.toHexString(System.identityHashCode(filter.activity))); 7397 out.print(' '); 7398 filter.activity.printComponentShortName(out); 7399 out.print(" filter "); 7400 out.println(Integer.toHexString(System.identityHashCode(filter))); 7401 } 7402 7403 @Override 7404 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7405 return filter.activity; 7406 } 7407 7408 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7409 PackageParser.Activity activity = (PackageParser.Activity)label; 7410 out.print(prefix); out.print( 7411 Integer.toHexString(System.identityHashCode(activity))); 7412 out.print(' '); 7413 activity.printComponentShortName(out); 7414 if (count > 1) { 7415 out.print(" ("); out.print(count); out.print(" filters)"); 7416 } 7417 out.println(); 7418 } 7419 7420// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7421// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7422// final List<ResolveInfo> retList = Lists.newArrayList(); 7423// while (i.hasNext()) { 7424// final ResolveInfo resolveInfo = i.next(); 7425// if (isEnabledLP(resolveInfo.activityInfo)) { 7426// retList.add(resolveInfo); 7427// } 7428// } 7429// return retList; 7430// } 7431 7432 // Keys are String (activity class name), values are Activity. 7433 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7434 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7435 private int mFlags; 7436 } 7437 7438 private final class ServiceIntentResolver 7439 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7440 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7441 boolean defaultOnly, int userId) { 7442 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7443 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7444 } 7445 7446 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7447 int userId) { 7448 if (!sUserManager.exists(userId)) return null; 7449 mFlags = flags; 7450 return super.queryIntent(intent, resolvedType, 7451 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7452 } 7453 7454 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7455 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7456 if (!sUserManager.exists(userId)) return null; 7457 if (packageServices == null) { 7458 return null; 7459 } 7460 mFlags = flags; 7461 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7462 final int N = packageServices.size(); 7463 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7464 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7465 7466 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7467 for (int i = 0; i < N; ++i) { 7468 intentFilters = packageServices.get(i).intents; 7469 if (intentFilters != null && intentFilters.size() > 0) { 7470 PackageParser.ServiceIntentInfo[] array = 7471 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7472 intentFilters.toArray(array); 7473 listCut.add(array); 7474 } 7475 } 7476 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7477 } 7478 7479 public final void addService(PackageParser.Service s) { 7480 mServices.put(s.getComponentName(), s); 7481 if (DEBUG_SHOW_INFO) { 7482 Log.v(TAG, " " 7483 + (s.info.nonLocalizedLabel != null 7484 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7485 Log.v(TAG, " Class=" + s.info.name); 7486 } 7487 final int NI = s.intents.size(); 7488 int j; 7489 for (j=0; j<NI; j++) { 7490 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7491 if (DEBUG_SHOW_INFO) { 7492 Log.v(TAG, " IntentFilter:"); 7493 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7494 } 7495 if (!intent.debugCheck()) { 7496 Log.w(TAG, "==> For Service " + s.info.name); 7497 } 7498 addFilter(intent); 7499 } 7500 } 7501 7502 public final void removeService(PackageParser.Service s) { 7503 mServices.remove(s.getComponentName()); 7504 if (DEBUG_SHOW_INFO) { 7505 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7506 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7507 Log.v(TAG, " Class=" + s.info.name); 7508 } 7509 final int NI = s.intents.size(); 7510 int j; 7511 for (j=0; j<NI; j++) { 7512 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7513 if (DEBUG_SHOW_INFO) { 7514 Log.v(TAG, " IntentFilter:"); 7515 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7516 } 7517 removeFilter(intent); 7518 } 7519 } 7520 7521 @Override 7522 protected boolean allowFilterResult( 7523 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7524 ServiceInfo filterSi = filter.service.info; 7525 for (int i=dest.size()-1; i>=0; i--) { 7526 ServiceInfo destAi = dest.get(i).serviceInfo; 7527 if (destAi.name == filterSi.name 7528 && destAi.packageName == filterSi.packageName) { 7529 return false; 7530 } 7531 } 7532 return true; 7533 } 7534 7535 @Override 7536 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7537 return new PackageParser.ServiceIntentInfo[size]; 7538 } 7539 7540 @Override 7541 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7542 if (!sUserManager.exists(userId)) return true; 7543 PackageParser.Package p = filter.service.owner; 7544 if (p != null) { 7545 PackageSetting ps = (PackageSetting)p.mExtras; 7546 if (ps != null) { 7547 // System apps are never considered stopped for purposes of 7548 // filtering, because there may be no way for the user to 7549 // actually re-launch them. 7550 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7551 && ps.getStopped(userId); 7552 } 7553 } 7554 return false; 7555 } 7556 7557 @Override 7558 protected boolean isPackageForFilter(String packageName, 7559 PackageParser.ServiceIntentInfo info) { 7560 return packageName.equals(info.service.owner.packageName); 7561 } 7562 7563 @Override 7564 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7565 int match, int userId) { 7566 if (!sUserManager.exists(userId)) return null; 7567 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7568 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7569 return null; 7570 } 7571 final PackageParser.Service service = info.service; 7572 if (mSafeMode && (service.info.applicationInfo.flags 7573 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7574 return null; 7575 } 7576 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7577 if (ps == null) { 7578 return null; 7579 } 7580 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7581 ps.readUserState(userId), userId); 7582 if (si == null) { 7583 return null; 7584 } 7585 final ResolveInfo res = new ResolveInfo(); 7586 res.serviceInfo = si; 7587 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7588 res.filter = filter; 7589 } 7590 res.priority = info.getPriority(); 7591 res.preferredOrder = service.owner.mPreferredOrder; 7592 //System.out.println("Result: " + res.activityInfo.className + 7593 // " = " + res.priority); 7594 res.match = match; 7595 res.isDefault = info.hasDefault; 7596 res.labelRes = info.labelRes; 7597 res.nonLocalizedLabel = info.nonLocalizedLabel; 7598 res.icon = info.icon; 7599 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7600 return res; 7601 } 7602 7603 @Override 7604 protected void sortResults(List<ResolveInfo> results) { 7605 Collections.sort(results, mResolvePrioritySorter); 7606 } 7607 7608 @Override 7609 protected void dumpFilter(PrintWriter out, String prefix, 7610 PackageParser.ServiceIntentInfo filter) { 7611 out.print(prefix); out.print( 7612 Integer.toHexString(System.identityHashCode(filter.service))); 7613 out.print(' '); 7614 filter.service.printComponentShortName(out); 7615 out.print(" filter "); 7616 out.println(Integer.toHexString(System.identityHashCode(filter))); 7617 } 7618 7619 @Override 7620 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 7621 return filter.service; 7622 } 7623 7624 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7625 PackageParser.Service service = (PackageParser.Service)label; 7626 out.print(prefix); out.print( 7627 Integer.toHexString(System.identityHashCode(service))); 7628 out.print(' '); 7629 service.printComponentShortName(out); 7630 if (count > 1) { 7631 out.print(" ("); out.print(count); out.print(" filters)"); 7632 } 7633 out.println(); 7634 } 7635 7636// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7637// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7638// final List<ResolveInfo> retList = Lists.newArrayList(); 7639// while (i.hasNext()) { 7640// final ResolveInfo resolveInfo = (ResolveInfo) i; 7641// if (isEnabledLP(resolveInfo.serviceInfo)) { 7642// retList.add(resolveInfo); 7643// } 7644// } 7645// return retList; 7646// } 7647 7648 // Keys are String (activity class name), values are Activity. 7649 private final ArrayMap<ComponentName, PackageParser.Service> mServices 7650 = new ArrayMap<ComponentName, PackageParser.Service>(); 7651 private int mFlags; 7652 }; 7653 7654 private final class ProviderIntentResolver 7655 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7656 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7657 boolean defaultOnly, int userId) { 7658 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7659 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7660 } 7661 7662 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7663 int userId) { 7664 if (!sUserManager.exists(userId)) 7665 return null; 7666 mFlags = flags; 7667 return super.queryIntent(intent, resolvedType, 7668 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7669 } 7670 7671 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7672 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7673 if (!sUserManager.exists(userId)) 7674 return null; 7675 if (packageProviders == null) { 7676 return null; 7677 } 7678 mFlags = flags; 7679 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7680 final int N = packageProviders.size(); 7681 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7682 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7683 7684 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7685 for (int i = 0; i < N; ++i) { 7686 intentFilters = packageProviders.get(i).intents; 7687 if (intentFilters != null && intentFilters.size() > 0) { 7688 PackageParser.ProviderIntentInfo[] array = 7689 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7690 intentFilters.toArray(array); 7691 listCut.add(array); 7692 } 7693 } 7694 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7695 } 7696 7697 public final void addProvider(PackageParser.Provider p) { 7698 if (mProviders.containsKey(p.getComponentName())) { 7699 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7700 return; 7701 } 7702 7703 mProviders.put(p.getComponentName(), p); 7704 if (DEBUG_SHOW_INFO) { 7705 Log.v(TAG, " " 7706 + (p.info.nonLocalizedLabel != null 7707 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7708 Log.v(TAG, " Class=" + p.info.name); 7709 } 7710 final int NI = p.intents.size(); 7711 int j; 7712 for (j = 0; j < NI; j++) { 7713 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7714 if (DEBUG_SHOW_INFO) { 7715 Log.v(TAG, " IntentFilter:"); 7716 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7717 } 7718 if (!intent.debugCheck()) { 7719 Log.w(TAG, "==> For Provider " + p.info.name); 7720 } 7721 addFilter(intent); 7722 } 7723 } 7724 7725 public final void removeProvider(PackageParser.Provider p) { 7726 mProviders.remove(p.getComponentName()); 7727 if (DEBUG_SHOW_INFO) { 7728 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7729 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7730 Log.v(TAG, " Class=" + p.info.name); 7731 } 7732 final int NI = p.intents.size(); 7733 int j; 7734 for (j = 0; j < NI; j++) { 7735 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7736 if (DEBUG_SHOW_INFO) { 7737 Log.v(TAG, " IntentFilter:"); 7738 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7739 } 7740 removeFilter(intent); 7741 } 7742 } 7743 7744 @Override 7745 protected boolean allowFilterResult( 7746 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7747 ProviderInfo filterPi = filter.provider.info; 7748 for (int i = dest.size() - 1; i >= 0; i--) { 7749 ProviderInfo destPi = dest.get(i).providerInfo; 7750 if (destPi.name == filterPi.name 7751 && destPi.packageName == filterPi.packageName) { 7752 return false; 7753 } 7754 } 7755 return true; 7756 } 7757 7758 @Override 7759 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7760 return new PackageParser.ProviderIntentInfo[size]; 7761 } 7762 7763 @Override 7764 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7765 if (!sUserManager.exists(userId)) 7766 return true; 7767 PackageParser.Package p = filter.provider.owner; 7768 if (p != null) { 7769 PackageSetting ps = (PackageSetting) p.mExtras; 7770 if (ps != null) { 7771 // System apps are never considered stopped for purposes of 7772 // filtering, because there may be no way for the user to 7773 // actually re-launch them. 7774 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7775 && ps.getStopped(userId); 7776 } 7777 } 7778 return false; 7779 } 7780 7781 @Override 7782 protected boolean isPackageForFilter(String packageName, 7783 PackageParser.ProviderIntentInfo info) { 7784 return packageName.equals(info.provider.owner.packageName); 7785 } 7786 7787 @Override 7788 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7789 int match, int userId) { 7790 if (!sUserManager.exists(userId)) 7791 return null; 7792 final PackageParser.ProviderIntentInfo info = filter; 7793 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7794 return null; 7795 } 7796 final PackageParser.Provider provider = info.provider; 7797 if (mSafeMode && (provider.info.applicationInfo.flags 7798 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7799 return null; 7800 } 7801 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7802 if (ps == null) { 7803 return null; 7804 } 7805 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7806 ps.readUserState(userId), userId); 7807 if (pi == null) { 7808 return null; 7809 } 7810 final ResolveInfo res = new ResolveInfo(); 7811 res.providerInfo = pi; 7812 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7813 res.filter = filter; 7814 } 7815 res.priority = info.getPriority(); 7816 res.preferredOrder = provider.owner.mPreferredOrder; 7817 res.match = match; 7818 res.isDefault = info.hasDefault; 7819 res.labelRes = info.labelRes; 7820 res.nonLocalizedLabel = info.nonLocalizedLabel; 7821 res.icon = info.icon; 7822 res.system = isSystemApp(res.providerInfo.applicationInfo); 7823 return res; 7824 } 7825 7826 @Override 7827 protected void sortResults(List<ResolveInfo> results) { 7828 Collections.sort(results, mResolvePrioritySorter); 7829 } 7830 7831 @Override 7832 protected void dumpFilter(PrintWriter out, String prefix, 7833 PackageParser.ProviderIntentInfo filter) { 7834 out.print(prefix); 7835 out.print( 7836 Integer.toHexString(System.identityHashCode(filter.provider))); 7837 out.print(' '); 7838 filter.provider.printComponentShortName(out); 7839 out.print(" filter "); 7840 out.println(Integer.toHexString(System.identityHashCode(filter))); 7841 } 7842 7843 @Override 7844 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 7845 return filter.provider; 7846 } 7847 7848 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7849 PackageParser.Provider provider = (PackageParser.Provider)label; 7850 out.print(prefix); out.print( 7851 Integer.toHexString(System.identityHashCode(provider))); 7852 out.print(' '); 7853 provider.printComponentShortName(out); 7854 if (count > 1) { 7855 out.print(" ("); out.print(count); out.print(" filters)"); 7856 } 7857 out.println(); 7858 } 7859 7860 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 7861 = new ArrayMap<ComponentName, PackageParser.Provider>(); 7862 private int mFlags; 7863 }; 7864 7865 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7866 new Comparator<ResolveInfo>() { 7867 public int compare(ResolveInfo r1, ResolveInfo r2) { 7868 int v1 = r1.priority; 7869 int v2 = r2.priority; 7870 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7871 if (v1 != v2) { 7872 return (v1 > v2) ? -1 : 1; 7873 } 7874 v1 = r1.preferredOrder; 7875 v2 = r2.preferredOrder; 7876 if (v1 != v2) { 7877 return (v1 > v2) ? -1 : 1; 7878 } 7879 if (r1.isDefault != r2.isDefault) { 7880 return r1.isDefault ? -1 : 1; 7881 } 7882 v1 = r1.match; 7883 v2 = r2.match; 7884 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7885 if (v1 != v2) { 7886 return (v1 > v2) ? -1 : 1; 7887 } 7888 if (r1.system != r2.system) { 7889 return r1.system ? -1 : 1; 7890 } 7891 return 0; 7892 } 7893 }; 7894 7895 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7896 new Comparator<ProviderInfo>() { 7897 public int compare(ProviderInfo p1, ProviderInfo p2) { 7898 final int v1 = p1.initOrder; 7899 final int v2 = p2.initOrder; 7900 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7901 } 7902 }; 7903 7904 static final void sendPackageBroadcast(String action, String pkg, 7905 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7906 int[] userIds) { 7907 IActivityManager am = ActivityManagerNative.getDefault(); 7908 if (am != null) { 7909 try { 7910 if (userIds == null) { 7911 userIds = am.getRunningUserIds(); 7912 } 7913 for (int id : userIds) { 7914 final Intent intent = new Intent(action, 7915 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7916 if (extras != null) { 7917 intent.putExtras(extras); 7918 } 7919 if (targetPkg != null) { 7920 intent.setPackage(targetPkg); 7921 } 7922 // Modify the UID when posting to other users 7923 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7924 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7925 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7926 intent.putExtra(Intent.EXTRA_UID, uid); 7927 } 7928 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7929 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7930 if (DEBUG_BROADCASTS) { 7931 RuntimeException here = new RuntimeException("here"); 7932 here.fillInStackTrace(); 7933 Slog.d(TAG, "Sending to user " + id + ": " 7934 + intent.toShortString(false, true, false, false) 7935 + " " + intent.getExtras(), here); 7936 } 7937 am.broadcastIntent(null, intent, null, finishedReceiver, 7938 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7939 finishedReceiver != null, false, id); 7940 } 7941 } catch (RemoteException ex) { 7942 } 7943 } 7944 } 7945 7946 /** 7947 * Check if the external storage media is available. This is true if there 7948 * is a mounted external storage medium or if the external storage is 7949 * emulated. 7950 */ 7951 private boolean isExternalMediaAvailable() { 7952 return mMediaMounted || Environment.isExternalStorageEmulated(); 7953 } 7954 7955 @Override 7956 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7957 // writer 7958 synchronized (mPackages) { 7959 if (!isExternalMediaAvailable()) { 7960 // If the external storage is no longer mounted at this point, 7961 // the caller may not have been able to delete all of this 7962 // packages files and can not delete any more. Bail. 7963 return null; 7964 } 7965 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7966 if (lastPackage != null) { 7967 pkgs.remove(lastPackage); 7968 } 7969 if (pkgs.size() > 0) { 7970 return pkgs.get(0); 7971 } 7972 } 7973 return null; 7974 } 7975 7976 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7977 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7978 userId, andCode ? 1 : 0, packageName); 7979 if (mSystemReady) { 7980 msg.sendToTarget(); 7981 } else { 7982 if (mPostSystemReadyMessages == null) { 7983 mPostSystemReadyMessages = new ArrayList<>(); 7984 } 7985 mPostSystemReadyMessages.add(msg); 7986 } 7987 } 7988 7989 void startCleaningPackages() { 7990 // reader 7991 synchronized (mPackages) { 7992 if (!isExternalMediaAvailable()) { 7993 return; 7994 } 7995 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7996 return; 7997 } 7998 } 7999 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8000 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8001 IActivityManager am = ActivityManagerNative.getDefault(); 8002 if (am != null) { 8003 try { 8004 am.startService(null, intent, null, UserHandle.USER_OWNER); 8005 } catch (RemoteException e) { 8006 } 8007 } 8008 } 8009 8010 @Override 8011 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8012 int installFlags, String installerPackageName, VerificationParams verificationParams, 8013 String packageAbiOverride) { 8014 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 8015 packageAbiOverride, UserHandle.getCallingUserId()); 8016 } 8017 8018 @Override 8019 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8020 int installFlags, String installerPackageName, VerificationParams verificationParams, 8021 String packageAbiOverride, int userId) { 8022 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8023 8024 final int callingUid = Binder.getCallingUid(); 8025 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8026 8027 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8028 try { 8029 if (observer != null) { 8030 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8031 } 8032 } catch (RemoteException re) { 8033 } 8034 return; 8035 } 8036 8037 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8038 installFlags |= PackageManager.INSTALL_FROM_ADB; 8039 8040 } else { 8041 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8042 // about installerPackageName. 8043 8044 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8045 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8046 } 8047 8048 UserHandle user; 8049 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8050 user = UserHandle.ALL; 8051 } else { 8052 user = new UserHandle(userId); 8053 } 8054 8055 verificationParams.setInstallerUid(callingUid); 8056 8057 final File originFile = new File(originPath); 8058 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8059 8060 final Message msg = mHandler.obtainMessage(INIT_COPY); 8061 msg.obj = new InstallParams(origin, observer, installFlags, 8062 installerPackageName, verificationParams, user, packageAbiOverride); 8063 mHandler.sendMessage(msg); 8064 } 8065 8066 void installStage(String packageName, File stagedDir, String stagedCid, 8067 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8068 String installerPackageName, int installerUid, UserHandle user) { 8069 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8070 params.referrerUri, installerUid, null); 8071 8072 final OriginInfo origin; 8073 if (stagedDir != null) { 8074 origin = OriginInfo.fromStagedFile(stagedDir); 8075 } else { 8076 origin = OriginInfo.fromStagedContainer(stagedCid); 8077 } 8078 8079 final Message msg = mHandler.obtainMessage(INIT_COPY); 8080 msg.obj = new InstallParams(origin, observer, params.installFlags, 8081 installerPackageName, verifParams, user, params.abiOverride); 8082 mHandler.sendMessage(msg); 8083 } 8084 8085 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8086 Bundle extras = new Bundle(1); 8087 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8088 8089 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8090 packageName, extras, null, null, new int[] {userId}); 8091 try { 8092 IActivityManager am = ActivityManagerNative.getDefault(); 8093 final boolean isSystem = 8094 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8095 if (isSystem && am.isUserRunning(userId, false)) { 8096 // The just-installed/enabled app is bundled on the system, so presumed 8097 // to be able to run automatically without needing an explicit launch. 8098 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8099 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8100 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8101 .setPackage(packageName); 8102 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8103 android.app.AppOpsManager.OP_NONE, false, false, userId); 8104 } 8105 } catch (RemoteException e) { 8106 // shouldn't happen 8107 Slog.w(TAG, "Unable to bootstrap installed package", e); 8108 } 8109 } 8110 8111 @Override 8112 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8113 int userId) { 8114 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8115 PackageSetting pkgSetting; 8116 final int uid = Binder.getCallingUid(); 8117 enforceCrossUserPermission(uid, userId, true, true, 8118 "setApplicationHiddenSetting for user " + userId); 8119 8120 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8121 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8122 return false; 8123 } 8124 8125 long callingId = Binder.clearCallingIdentity(); 8126 try { 8127 boolean sendAdded = false; 8128 boolean sendRemoved = false; 8129 // writer 8130 synchronized (mPackages) { 8131 pkgSetting = mSettings.mPackages.get(packageName); 8132 if (pkgSetting == null) { 8133 return false; 8134 } 8135 if (pkgSetting.getHidden(userId) != hidden) { 8136 pkgSetting.setHidden(hidden, userId); 8137 mSettings.writePackageRestrictionsLPr(userId); 8138 if (hidden) { 8139 sendRemoved = true; 8140 } else { 8141 sendAdded = true; 8142 } 8143 } 8144 } 8145 if (sendAdded) { 8146 sendPackageAddedForUser(packageName, pkgSetting, userId); 8147 return true; 8148 } 8149 if (sendRemoved) { 8150 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8151 "hiding pkg"); 8152 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8153 } 8154 } finally { 8155 Binder.restoreCallingIdentity(callingId); 8156 } 8157 return false; 8158 } 8159 8160 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8161 int userId) { 8162 final PackageRemovedInfo info = new PackageRemovedInfo(); 8163 info.removedPackage = packageName; 8164 info.removedUsers = new int[] {userId}; 8165 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8166 info.sendBroadcast(false, false, false); 8167 } 8168 8169 /** 8170 * Returns true if application is not found or there was an error. Otherwise it returns 8171 * the hidden state of the package for the given user. 8172 */ 8173 @Override 8174 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8175 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8176 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8177 false, "getApplicationHidden for user " + userId); 8178 PackageSetting pkgSetting; 8179 long callingId = Binder.clearCallingIdentity(); 8180 try { 8181 // writer 8182 synchronized (mPackages) { 8183 pkgSetting = mSettings.mPackages.get(packageName); 8184 if (pkgSetting == null) { 8185 return true; 8186 } 8187 return pkgSetting.getHidden(userId); 8188 } 8189 } finally { 8190 Binder.restoreCallingIdentity(callingId); 8191 } 8192 } 8193 8194 /** 8195 * @hide 8196 */ 8197 @Override 8198 public int installExistingPackageAsUser(String packageName, int userId) { 8199 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8200 null); 8201 PackageSetting pkgSetting; 8202 final int uid = Binder.getCallingUid(); 8203 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8204 + userId); 8205 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8206 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8207 } 8208 8209 long callingId = Binder.clearCallingIdentity(); 8210 try { 8211 boolean sendAdded = false; 8212 Bundle extras = new Bundle(1); 8213 8214 // writer 8215 synchronized (mPackages) { 8216 pkgSetting = mSettings.mPackages.get(packageName); 8217 if (pkgSetting == null) { 8218 return PackageManager.INSTALL_FAILED_INVALID_URI; 8219 } 8220 if (!pkgSetting.getInstalled(userId)) { 8221 pkgSetting.setInstalled(true, userId); 8222 pkgSetting.setHidden(false, userId); 8223 mSettings.writePackageRestrictionsLPr(userId); 8224 sendAdded = true; 8225 } 8226 } 8227 8228 if (sendAdded) { 8229 sendPackageAddedForUser(packageName, pkgSetting, userId); 8230 } 8231 } finally { 8232 Binder.restoreCallingIdentity(callingId); 8233 } 8234 8235 return PackageManager.INSTALL_SUCCEEDED; 8236 } 8237 8238 boolean isUserRestricted(int userId, String restrictionKey) { 8239 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8240 if (restrictions.getBoolean(restrictionKey, false)) { 8241 Log.w(TAG, "User is restricted: " + restrictionKey); 8242 return true; 8243 } 8244 return false; 8245 } 8246 8247 @Override 8248 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8249 mContext.enforceCallingOrSelfPermission( 8250 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8251 "Only package verification agents can verify applications"); 8252 8253 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8254 final PackageVerificationResponse response = new PackageVerificationResponse( 8255 verificationCode, Binder.getCallingUid()); 8256 msg.arg1 = id; 8257 msg.obj = response; 8258 mHandler.sendMessage(msg); 8259 } 8260 8261 @Override 8262 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8263 long millisecondsToDelay) { 8264 mContext.enforceCallingOrSelfPermission( 8265 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8266 "Only package verification agents can extend verification timeouts"); 8267 8268 final PackageVerificationState state = mPendingVerification.get(id); 8269 final PackageVerificationResponse response = new PackageVerificationResponse( 8270 verificationCodeAtTimeout, Binder.getCallingUid()); 8271 8272 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8273 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8274 } 8275 if (millisecondsToDelay < 0) { 8276 millisecondsToDelay = 0; 8277 } 8278 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8279 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8280 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8281 } 8282 8283 if ((state != null) && !state.timeoutExtended()) { 8284 state.extendTimeout(); 8285 8286 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8287 msg.arg1 = id; 8288 msg.obj = response; 8289 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8290 } 8291 } 8292 8293 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8294 int verificationCode, UserHandle user) { 8295 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8296 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8297 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8298 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8299 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8300 8301 mContext.sendBroadcastAsUser(intent, user, 8302 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8303 } 8304 8305 private ComponentName matchComponentForVerifier(String packageName, 8306 List<ResolveInfo> receivers) { 8307 ActivityInfo targetReceiver = null; 8308 8309 final int NR = receivers.size(); 8310 for (int i = 0; i < NR; i++) { 8311 final ResolveInfo info = receivers.get(i); 8312 if (info.activityInfo == null) { 8313 continue; 8314 } 8315 8316 if (packageName.equals(info.activityInfo.packageName)) { 8317 targetReceiver = info.activityInfo; 8318 break; 8319 } 8320 } 8321 8322 if (targetReceiver == null) { 8323 return null; 8324 } 8325 8326 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8327 } 8328 8329 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8330 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8331 if (pkgInfo.verifiers.length == 0) { 8332 return null; 8333 } 8334 8335 final int N = pkgInfo.verifiers.length; 8336 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8337 for (int i = 0; i < N; i++) { 8338 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8339 8340 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8341 receivers); 8342 if (comp == null) { 8343 continue; 8344 } 8345 8346 final int verifierUid = getUidForVerifier(verifierInfo); 8347 if (verifierUid == -1) { 8348 continue; 8349 } 8350 8351 if (DEBUG_VERIFY) { 8352 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8353 + " with the correct signature"); 8354 } 8355 sufficientVerifiers.add(comp); 8356 verificationState.addSufficientVerifier(verifierUid); 8357 } 8358 8359 return sufficientVerifiers; 8360 } 8361 8362 private int getUidForVerifier(VerifierInfo verifierInfo) { 8363 synchronized (mPackages) { 8364 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8365 if (pkg == null) { 8366 return -1; 8367 } else if (pkg.mSignatures.length != 1) { 8368 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8369 + " has more than one signature; ignoring"); 8370 return -1; 8371 } 8372 8373 /* 8374 * If the public key of the package's signature does not match 8375 * our expected public key, then this is a different package and 8376 * we should skip. 8377 */ 8378 8379 final byte[] expectedPublicKey; 8380 try { 8381 final Signature verifierSig = pkg.mSignatures[0]; 8382 final PublicKey publicKey = verifierSig.getPublicKey(); 8383 expectedPublicKey = publicKey.getEncoded(); 8384 } catch (CertificateException e) { 8385 return -1; 8386 } 8387 8388 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8389 8390 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8391 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8392 + " does not have the expected public key; ignoring"); 8393 return -1; 8394 } 8395 8396 return pkg.applicationInfo.uid; 8397 } 8398 } 8399 8400 @Override 8401 public void finishPackageInstall(int token) { 8402 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8403 8404 if (DEBUG_INSTALL) { 8405 Slog.v(TAG, "BM finishing package install for " + token); 8406 } 8407 8408 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8409 mHandler.sendMessage(msg); 8410 } 8411 8412 /** 8413 * Get the verification agent timeout. 8414 * 8415 * @return verification timeout in milliseconds 8416 */ 8417 private long getVerificationTimeout() { 8418 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8419 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8420 DEFAULT_VERIFICATION_TIMEOUT); 8421 } 8422 8423 /** 8424 * Get the default verification agent response code. 8425 * 8426 * @return default verification response code 8427 */ 8428 private int getDefaultVerificationResponse() { 8429 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8430 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8431 DEFAULT_VERIFICATION_RESPONSE); 8432 } 8433 8434 /** 8435 * Check whether or not package verification has been enabled. 8436 * 8437 * @return true if verification should be performed 8438 */ 8439 private boolean isVerificationEnabled(int userId, int installFlags) { 8440 if (!DEFAULT_VERIFY_ENABLE) { 8441 return false; 8442 } 8443 8444 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8445 8446 // Check if installing from ADB 8447 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8448 // Do not run verification in a test harness environment 8449 if (ActivityManager.isRunningInTestHarness()) { 8450 return false; 8451 } 8452 if (ensureVerifyAppsEnabled) { 8453 return true; 8454 } 8455 // Check if the developer does not want package verification for ADB installs 8456 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8457 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8458 return false; 8459 } 8460 } 8461 8462 if (ensureVerifyAppsEnabled) { 8463 return true; 8464 } 8465 8466 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8467 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8468 } 8469 8470 /** 8471 * Get the "allow unknown sources" setting. 8472 * 8473 * @return the current "allow unknown sources" setting 8474 */ 8475 private int getUnknownSourcesSettings() { 8476 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8477 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8478 -1); 8479 } 8480 8481 @Override 8482 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8483 final int uid = Binder.getCallingUid(); 8484 // writer 8485 synchronized (mPackages) { 8486 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8487 if (targetPackageSetting == null) { 8488 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8489 } 8490 8491 PackageSetting installerPackageSetting; 8492 if (installerPackageName != null) { 8493 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8494 if (installerPackageSetting == null) { 8495 throw new IllegalArgumentException("Unknown installer package: " 8496 + installerPackageName); 8497 } 8498 } else { 8499 installerPackageSetting = null; 8500 } 8501 8502 Signature[] callerSignature; 8503 Object obj = mSettings.getUserIdLPr(uid); 8504 if (obj != null) { 8505 if (obj instanceof SharedUserSetting) { 8506 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8507 } else if (obj instanceof PackageSetting) { 8508 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8509 } else { 8510 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8511 } 8512 } else { 8513 throw new SecurityException("Unknown calling uid " + uid); 8514 } 8515 8516 // Verify: can't set installerPackageName to a package that is 8517 // not signed with the same cert as the caller. 8518 if (installerPackageSetting != null) { 8519 if (compareSignatures(callerSignature, 8520 installerPackageSetting.signatures.mSignatures) 8521 != PackageManager.SIGNATURE_MATCH) { 8522 throw new SecurityException( 8523 "Caller does not have same cert as new installer package " 8524 + installerPackageName); 8525 } 8526 } 8527 8528 // Verify: if target already has an installer package, it must 8529 // be signed with the same cert as the caller. 8530 if (targetPackageSetting.installerPackageName != null) { 8531 PackageSetting setting = mSettings.mPackages.get( 8532 targetPackageSetting.installerPackageName); 8533 // If the currently set package isn't valid, then it's always 8534 // okay to change it. 8535 if (setting != null) { 8536 if (compareSignatures(callerSignature, 8537 setting.signatures.mSignatures) 8538 != PackageManager.SIGNATURE_MATCH) { 8539 throw new SecurityException( 8540 "Caller does not have same cert as old installer package " 8541 + targetPackageSetting.installerPackageName); 8542 } 8543 } 8544 } 8545 8546 // Okay! 8547 targetPackageSetting.installerPackageName = installerPackageName; 8548 scheduleWriteSettingsLocked(); 8549 } 8550 } 8551 8552 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8553 // Queue up an async operation since the package installation may take a little while. 8554 mHandler.post(new Runnable() { 8555 public void run() { 8556 mHandler.removeCallbacks(this); 8557 // Result object to be returned 8558 PackageInstalledInfo res = new PackageInstalledInfo(); 8559 res.returnCode = currentStatus; 8560 res.uid = -1; 8561 res.pkg = null; 8562 res.removedInfo = new PackageRemovedInfo(); 8563 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8564 args.doPreInstall(res.returnCode); 8565 synchronized (mInstallLock) { 8566 installPackageLI(args, res); 8567 } 8568 args.doPostInstall(res.returnCode, res.uid); 8569 } 8570 8571 // A restore should be performed at this point if (a) the install 8572 // succeeded, (b) the operation is not an update, and (c) the new 8573 // package has not opted out of backup participation. 8574 final boolean update = res.removedInfo.removedPackage != null; 8575 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8576 boolean doRestore = !update 8577 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8578 8579 // Set up the post-install work request bookkeeping. This will be used 8580 // and cleaned up by the post-install event handling regardless of whether 8581 // there's a restore pass performed. Token values are >= 1. 8582 int token; 8583 if (mNextInstallToken < 0) mNextInstallToken = 1; 8584 token = mNextInstallToken++; 8585 8586 PostInstallData data = new PostInstallData(args, res); 8587 mRunningInstalls.put(token, data); 8588 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8589 8590 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8591 // Pass responsibility to the Backup Manager. It will perform a 8592 // restore if appropriate, then pass responsibility back to the 8593 // Package Manager to run the post-install observer callbacks 8594 // and broadcasts. 8595 IBackupManager bm = IBackupManager.Stub.asInterface( 8596 ServiceManager.getService(Context.BACKUP_SERVICE)); 8597 if (bm != null) { 8598 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8599 + " to BM for possible restore"); 8600 try { 8601 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 8602 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8603 } else { 8604 doRestore = false; 8605 } 8606 } catch (RemoteException e) { 8607 // can't happen; the backup manager is local 8608 } catch (Exception e) { 8609 Slog.e(TAG, "Exception trying to enqueue restore", e); 8610 doRestore = false; 8611 } 8612 } else { 8613 Slog.e(TAG, "Backup Manager not found!"); 8614 doRestore = false; 8615 } 8616 } 8617 8618 if (!doRestore) { 8619 // No restore possible, or the Backup Manager was mysteriously not 8620 // available -- just fire the post-install work request directly. 8621 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8622 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8623 mHandler.sendMessage(msg); 8624 } 8625 } 8626 }); 8627 } 8628 8629 private abstract class HandlerParams { 8630 private static final int MAX_RETRIES = 4; 8631 8632 /** 8633 * Number of times startCopy() has been attempted and had a non-fatal 8634 * error. 8635 */ 8636 private int mRetries = 0; 8637 8638 /** User handle for the user requesting the information or installation. */ 8639 private final UserHandle mUser; 8640 8641 HandlerParams(UserHandle user) { 8642 mUser = user; 8643 } 8644 8645 UserHandle getUser() { 8646 return mUser; 8647 } 8648 8649 final boolean startCopy() { 8650 boolean res; 8651 try { 8652 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8653 8654 if (++mRetries > MAX_RETRIES) { 8655 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8656 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8657 handleServiceError(); 8658 return false; 8659 } else { 8660 handleStartCopy(); 8661 res = true; 8662 } 8663 } catch (RemoteException e) { 8664 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8665 mHandler.sendEmptyMessage(MCS_RECONNECT); 8666 res = false; 8667 } 8668 handleReturnCode(); 8669 return res; 8670 } 8671 8672 final void serviceError() { 8673 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8674 handleServiceError(); 8675 handleReturnCode(); 8676 } 8677 8678 abstract void handleStartCopy() throws RemoteException; 8679 abstract void handleServiceError(); 8680 abstract void handleReturnCode(); 8681 } 8682 8683 class MeasureParams extends HandlerParams { 8684 private final PackageStats mStats; 8685 private boolean mSuccess; 8686 8687 private final IPackageStatsObserver mObserver; 8688 8689 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8690 super(new UserHandle(stats.userHandle)); 8691 mObserver = observer; 8692 mStats = stats; 8693 } 8694 8695 @Override 8696 public String toString() { 8697 return "MeasureParams{" 8698 + Integer.toHexString(System.identityHashCode(this)) 8699 + " " + mStats.packageName + "}"; 8700 } 8701 8702 @Override 8703 void handleStartCopy() throws RemoteException { 8704 synchronized (mInstallLock) { 8705 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8706 } 8707 8708 if (mSuccess) { 8709 final boolean mounted; 8710 if (Environment.isExternalStorageEmulated()) { 8711 mounted = true; 8712 } else { 8713 final String status = Environment.getExternalStorageState(); 8714 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8715 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8716 } 8717 8718 if (mounted) { 8719 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8720 8721 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8722 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8723 8724 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8725 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8726 8727 // Always subtract cache size, since it's a subdirectory 8728 mStats.externalDataSize -= mStats.externalCacheSize; 8729 8730 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8731 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8732 8733 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8734 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8735 } 8736 } 8737 } 8738 8739 @Override 8740 void handleReturnCode() { 8741 if (mObserver != null) { 8742 try { 8743 mObserver.onGetStatsCompleted(mStats, mSuccess); 8744 } catch (RemoteException e) { 8745 Slog.i(TAG, "Observer no longer exists."); 8746 } 8747 } 8748 } 8749 8750 @Override 8751 void handleServiceError() { 8752 Slog.e(TAG, "Could not measure application " + mStats.packageName 8753 + " external storage"); 8754 } 8755 } 8756 8757 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8758 throws RemoteException { 8759 long result = 0; 8760 for (File path : paths) { 8761 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8762 } 8763 return result; 8764 } 8765 8766 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8767 for (File path : paths) { 8768 try { 8769 mcs.clearDirectory(path.getAbsolutePath()); 8770 } catch (RemoteException e) { 8771 } 8772 } 8773 } 8774 8775 static class OriginInfo { 8776 /** 8777 * Location where install is coming from, before it has been 8778 * copied/renamed into place. This could be a single monolithic APK 8779 * file, or a cluster directory. This location may be untrusted. 8780 */ 8781 final File file; 8782 final String cid; 8783 8784 /** 8785 * Flag indicating that {@link #file} or {@link #cid} has already been 8786 * staged, meaning downstream users don't need to defensively copy the 8787 * contents. 8788 */ 8789 final boolean staged; 8790 8791 /** 8792 * Flag indicating that {@link #file} or {@link #cid} is an already 8793 * installed app that is being moved. 8794 */ 8795 final boolean existing; 8796 8797 final String resolvedPath; 8798 final File resolvedFile; 8799 8800 static OriginInfo fromNothing() { 8801 return new OriginInfo(null, null, false, false); 8802 } 8803 8804 static OriginInfo fromUntrustedFile(File file) { 8805 return new OriginInfo(file, null, false, false); 8806 } 8807 8808 static OriginInfo fromExistingFile(File file) { 8809 return new OriginInfo(file, null, false, true); 8810 } 8811 8812 static OriginInfo fromStagedFile(File file) { 8813 return new OriginInfo(file, null, true, false); 8814 } 8815 8816 static OriginInfo fromStagedContainer(String cid) { 8817 return new OriginInfo(null, cid, true, false); 8818 } 8819 8820 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8821 this.file = file; 8822 this.cid = cid; 8823 this.staged = staged; 8824 this.existing = existing; 8825 8826 if (cid != null) { 8827 resolvedPath = PackageHelper.getSdDir(cid); 8828 resolvedFile = new File(resolvedPath); 8829 } else if (file != null) { 8830 resolvedPath = file.getAbsolutePath(); 8831 resolvedFile = file; 8832 } else { 8833 resolvedPath = null; 8834 resolvedFile = null; 8835 } 8836 } 8837 } 8838 8839 class InstallParams extends HandlerParams { 8840 final OriginInfo origin; 8841 final IPackageInstallObserver2 observer; 8842 int installFlags; 8843 final String installerPackageName; 8844 final VerificationParams verificationParams; 8845 private InstallArgs mArgs; 8846 private int mRet; 8847 final String packageAbiOverride; 8848 8849 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8850 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8851 String packageAbiOverride) { 8852 super(user); 8853 this.origin = origin; 8854 this.observer = observer; 8855 this.installFlags = installFlags; 8856 this.installerPackageName = installerPackageName; 8857 this.verificationParams = verificationParams; 8858 this.packageAbiOverride = packageAbiOverride; 8859 } 8860 8861 @Override 8862 public String toString() { 8863 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8864 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8865 } 8866 8867 public ManifestDigest getManifestDigest() { 8868 if (verificationParams == null) { 8869 return null; 8870 } 8871 return verificationParams.getManifestDigest(); 8872 } 8873 8874 private int installLocationPolicy(PackageInfoLite pkgLite) { 8875 String packageName = pkgLite.packageName; 8876 int installLocation = pkgLite.installLocation; 8877 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8878 // reader 8879 synchronized (mPackages) { 8880 PackageParser.Package pkg = mPackages.get(packageName); 8881 if (pkg != null) { 8882 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8883 // Check for downgrading. 8884 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8885 try { 8886 checkDowngrade(pkg, pkgLite); 8887 } catch (PackageManagerException e) { 8888 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 8889 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8890 } 8891 } 8892 // Check for updated system application. 8893 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8894 if (onSd) { 8895 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8896 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8897 } 8898 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8899 } else { 8900 if (onSd) { 8901 // Install flag overrides everything. 8902 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8903 } 8904 // If current upgrade specifies particular preference 8905 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8906 // Application explicitly specified internal. 8907 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8908 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8909 // App explictly prefers external. Let policy decide 8910 } else { 8911 // Prefer previous location 8912 if (isExternal(pkg)) { 8913 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8914 } 8915 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8916 } 8917 } 8918 } else { 8919 // Invalid install. Return error code 8920 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8921 } 8922 } 8923 } 8924 // All the special cases have been taken care of. 8925 // Return result based on recommended install location. 8926 if (onSd) { 8927 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8928 } 8929 return pkgLite.recommendedInstallLocation; 8930 } 8931 8932 /* 8933 * Invoke remote method to get package information and install 8934 * location values. Override install location based on default 8935 * policy if needed and then create install arguments based 8936 * on the install location. 8937 */ 8938 public void handleStartCopy() throws RemoteException { 8939 int ret = PackageManager.INSTALL_SUCCEEDED; 8940 8941 // If we're already staged, we've firmly committed to an install location 8942 if (origin.staged) { 8943 if (origin.file != null) { 8944 installFlags |= PackageManager.INSTALL_INTERNAL; 8945 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8946 } else if (origin.cid != null) { 8947 installFlags |= PackageManager.INSTALL_EXTERNAL; 8948 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8949 } else { 8950 throw new IllegalStateException("Invalid stage location"); 8951 } 8952 } 8953 8954 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8955 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8956 8957 PackageInfoLite pkgLite = null; 8958 8959 if (onInt && onSd) { 8960 // Check if both bits are set. 8961 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8962 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8963 } else { 8964 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8965 packageAbiOverride); 8966 8967 /* 8968 * If we have too little free space, try to free cache 8969 * before giving up. 8970 */ 8971 if (!origin.staged && pkgLite.recommendedInstallLocation 8972 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8973 // TODO: focus freeing disk space on the target device 8974 final StorageManager storage = StorageManager.from(mContext); 8975 final long lowThreshold = storage.getStorageLowBytes( 8976 Environment.getDataDirectory()); 8977 8978 final long sizeBytes = mContainerService.calculateInstalledSize( 8979 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8980 8981 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8982 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8983 installFlags, packageAbiOverride); 8984 } 8985 8986 /* 8987 * The cache free must have deleted the file we 8988 * downloaded to install. 8989 * 8990 * TODO: fix the "freeCache" call to not delete 8991 * the file we care about. 8992 */ 8993 if (pkgLite.recommendedInstallLocation 8994 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8995 pkgLite.recommendedInstallLocation 8996 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8997 } 8998 } 8999 } 9000 9001 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9002 int loc = pkgLite.recommendedInstallLocation; 9003 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9004 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9005 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9006 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9007 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9008 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9009 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9010 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9011 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9012 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9013 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9014 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9015 } else { 9016 // Override with defaults if needed. 9017 loc = installLocationPolicy(pkgLite); 9018 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9019 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9020 } else if (!onSd && !onInt) { 9021 // Override install location with flags 9022 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9023 // Set the flag to install on external media. 9024 installFlags |= PackageManager.INSTALL_EXTERNAL; 9025 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9026 } else { 9027 // Make sure the flag for installing on external 9028 // media is unset 9029 installFlags |= PackageManager.INSTALL_INTERNAL; 9030 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9031 } 9032 } 9033 } 9034 } 9035 9036 final InstallArgs args = createInstallArgs(this); 9037 mArgs = args; 9038 9039 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9040 /* 9041 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9042 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9043 */ 9044 int userIdentifier = getUser().getIdentifier(); 9045 if (userIdentifier == UserHandle.USER_ALL 9046 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9047 userIdentifier = UserHandle.USER_OWNER; 9048 } 9049 9050 /* 9051 * Determine if we have any installed package verifiers. If we 9052 * do, then we'll defer to them to verify the packages. 9053 */ 9054 final int requiredUid = mRequiredVerifierPackage == null ? -1 9055 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9056 if (!origin.existing && requiredUid != -1 9057 && isVerificationEnabled(userIdentifier, installFlags)) { 9058 final Intent verification = new Intent( 9059 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9060 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9061 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9062 PACKAGE_MIME_TYPE); 9063 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9064 9065 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9066 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9067 0 /* TODO: Which userId? */); 9068 9069 if (DEBUG_VERIFY) { 9070 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9071 + verification.toString() + " with " + pkgLite.verifiers.length 9072 + " optional verifiers"); 9073 } 9074 9075 final int verificationId = mPendingVerificationToken++; 9076 9077 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9078 9079 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9080 installerPackageName); 9081 9082 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9083 installFlags); 9084 9085 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9086 pkgLite.packageName); 9087 9088 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9089 pkgLite.versionCode); 9090 9091 if (verificationParams != null) { 9092 if (verificationParams.getVerificationURI() != null) { 9093 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9094 verificationParams.getVerificationURI()); 9095 } 9096 if (verificationParams.getOriginatingURI() != null) { 9097 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9098 verificationParams.getOriginatingURI()); 9099 } 9100 if (verificationParams.getReferrer() != null) { 9101 verification.putExtra(Intent.EXTRA_REFERRER, 9102 verificationParams.getReferrer()); 9103 } 9104 if (verificationParams.getOriginatingUid() >= 0) { 9105 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9106 verificationParams.getOriginatingUid()); 9107 } 9108 if (verificationParams.getInstallerUid() >= 0) { 9109 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9110 verificationParams.getInstallerUid()); 9111 } 9112 } 9113 9114 final PackageVerificationState verificationState = new PackageVerificationState( 9115 requiredUid, args); 9116 9117 mPendingVerification.append(verificationId, verificationState); 9118 9119 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9120 receivers, verificationState); 9121 9122 /* 9123 * If any sufficient verifiers were listed in the package 9124 * manifest, attempt to ask them. 9125 */ 9126 if (sufficientVerifiers != null) { 9127 final int N = sufficientVerifiers.size(); 9128 if (N == 0) { 9129 Slog.i(TAG, "Additional verifiers required, but none installed."); 9130 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9131 } else { 9132 for (int i = 0; i < N; i++) { 9133 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9134 9135 final Intent sufficientIntent = new Intent(verification); 9136 sufficientIntent.setComponent(verifierComponent); 9137 9138 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9139 } 9140 } 9141 } 9142 9143 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9144 mRequiredVerifierPackage, receivers); 9145 if (ret == PackageManager.INSTALL_SUCCEEDED 9146 && mRequiredVerifierPackage != null) { 9147 /* 9148 * Send the intent to the required verification agent, 9149 * but only start the verification timeout after the 9150 * target BroadcastReceivers have run. 9151 */ 9152 verification.setComponent(requiredVerifierComponent); 9153 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9154 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9155 new BroadcastReceiver() { 9156 @Override 9157 public void onReceive(Context context, Intent intent) { 9158 final Message msg = mHandler 9159 .obtainMessage(CHECK_PENDING_VERIFICATION); 9160 msg.arg1 = verificationId; 9161 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9162 } 9163 }, null, 0, null, null); 9164 9165 /* 9166 * We don't want the copy to proceed until verification 9167 * succeeds, so null out this field. 9168 */ 9169 mArgs = null; 9170 } 9171 } else { 9172 /* 9173 * No package verification is enabled, so immediately start 9174 * the remote call to initiate copy using temporary file. 9175 */ 9176 ret = args.copyApk(mContainerService, true); 9177 } 9178 } 9179 9180 mRet = ret; 9181 } 9182 9183 @Override 9184 void handleReturnCode() { 9185 // If mArgs is null, then MCS couldn't be reached. When it 9186 // reconnects, it will try again to install. At that point, this 9187 // will succeed. 9188 if (mArgs != null) { 9189 processPendingInstall(mArgs, mRet); 9190 } 9191 } 9192 9193 @Override 9194 void handleServiceError() { 9195 mArgs = createInstallArgs(this); 9196 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9197 } 9198 9199 public boolean isForwardLocked() { 9200 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9201 } 9202 } 9203 9204 /** 9205 * Used during creation of InstallArgs 9206 * 9207 * @param installFlags package installation flags 9208 * @return true if should be installed on external storage 9209 */ 9210 private static boolean installOnSd(int installFlags) { 9211 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9212 return false; 9213 } 9214 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9215 return true; 9216 } 9217 return false; 9218 } 9219 9220 /** 9221 * Used during creation of InstallArgs 9222 * 9223 * @param installFlags package installation flags 9224 * @return true if should be installed as forward locked 9225 */ 9226 private static boolean installForwardLocked(int installFlags) { 9227 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9228 } 9229 9230 private InstallArgs createInstallArgs(InstallParams params) { 9231 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9232 return new AsecInstallArgs(params); 9233 } else { 9234 return new FileInstallArgs(params); 9235 } 9236 } 9237 9238 /** 9239 * Create args that describe an existing installed package. Typically used 9240 * when cleaning up old installs, or used as a move source. 9241 */ 9242 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9243 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9244 final boolean isInAsec; 9245 if (installOnSd(installFlags)) { 9246 /* Apps on SD card are always in ASEC containers. */ 9247 isInAsec = true; 9248 } else if (installForwardLocked(installFlags) 9249 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9250 /* 9251 * Forward-locked apps are only in ASEC containers if they're the 9252 * new style 9253 */ 9254 isInAsec = true; 9255 } else { 9256 isInAsec = false; 9257 } 9258 9259 if (isInAsec) { 9260 return new AsecInstallArgs(codePath, instructionSets, 9261 installOnSd(installFlags), installForwardLocked(installFlags)); 9262 } else { 9263 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9264 instructionSets); 9265 } 9266 } 9267 9268 static abstract class InstallArgs { 9269 /** @see InstallParams#origin */ 9270 final OriginInfo origin; 9271 9272 final IPackageInstallObserver2 observer; 9273 // Always refers to PackageManager flags only 9274 final int installFlags; 9275 final String installerPackageName; 9276 final ManifestDigest manifestDigest; 9277 final UserHandle user; 9278 final String abiOverride; 9279 9280 // The list of instruction sets supported by this app. This is currently 9281 // only used during the rmdex() phase to clean up resources. We can get rid of this 9282 // if we move dex files under the common app path. 9283 /* nullable */ String[] instructionSets; 9284 9285 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9286 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9287 String[] instructionSets, String abiOverride) { 9288 this.origin = origin; 9289 this.installFlags = installFlags; 9290 this.observer = observer; 9291 this.installerPackageName = installerPackageName; 9292 this.manifestDigest = manifestDigest; 9293 this.user = user; 9294 this.instructionSets = instructionSets; 9295 this.abiOverride = abiOverride; 9296 } 9297 9298 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9299 abstract int doPreInstall(int status); 9300 9301 /** 9302 * Rename package into final resting place. All paths on the given 9303 * scanned package should be updated to reflect the rename. 9304 */ 9305 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9306 abstract int doPostInstall(int status, int uid); 9307 9308 /** @see PackageSettingBase#codePathString */ 9309 abstract String getCodePath(); 9310 /** @see PackageSettingBase#resourcePathString */ 9311 abstract String getResourcePath(); 9312 abstract String getLegacyNativeLibraryPath(); 9313 9314 // Need installer lock especially for dex file removal. 9315 abstract void cleanUpResourcesLI(); 9316 abstract boolean doPostDeleteLI(boolean delete); 9317 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9318 9319 /** 9320 * Called before the source arguments are copied. This is used mostly 9321 * for MoveParams when it needs to read the source file to put it in the 9322 * destination. 9323 */ 9324 int doPreCopy() { 9325 return PackageManager.INSTALL_SUCCEEDED; 9326 } 9327 9328 /** 9329 * Called after the source arguments are copied. This is used mostly for 9330 * MoveParams when it needs to read the source file to put it in the 9331 * destination. 9332 * 9333 * @return 9334 */ 9335 int doPostCopy(int uid) { 9336 return PackageManager.INSTALL_SUCCEEDED; 9337 } 9338 9339 protected boolean isFwdLocked() { 9340 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9341 } 9342 9343 protected boolean isExternal() { 9344 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9345 } 9346 9347 UserHandle getUser() { 9348 return user; 9349 } 9350 } 9351 9352 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9353 if (!allCodePaths.isEmpty()) { 9354 if (instructionSets == null) { 9355 throw new IllegalStateException("instructionSet == null"); 9356 } 9357 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9358 for (String codePath : allCodePaths) { 9359 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9360 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9361 if (retCode < 0) { 9362 Slog.w(TAG, "Couldn't remove dex file for package: " 9363 + " at location " + codePath + ", retcode=" + retCode); 9364 // we don't consider this to be a failure of the core package deletion 9365 } 9366 } 9367 } 9368 } 9369 } 9370 9371 /** 9372 * Logic to handle installation of non-ASEC applications, including copying 9373 * and renaming logic. 9374 */ 9375 class FileInstallArgs extends InstallArgs { 9376 private File codeFile; 9377 private File resourceFile; 9378 private File legacyNativeLibraryPath; 9379 9380 // Example topology: 9381 // /data/app/com.example/base.apk 9382 // /data/app/com.example/split_foo.apk 9383 // /data/app/com.example/lib/arm/libfoo.so 9384 // /data/app/com.example/lib/arm64/libfoo.so 9385 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9386 9387 /** New install */ 9388 FileInstallArgs(InstallParams params) { 9389 super(params.origin, params.observer, params.installFlags, 9390 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9391 null /* instruction sets */, params.packageAbiOverride); 9392 if (isFwdLocked()) { 9393 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9394 } 9395 } 9396 9397 /** Existing install */ 9398 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9399 String[] instructionSets) { 9400 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9401 this.codeFile = (codePath != null) ? new File(codePath) : null; 9402 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9403 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9404 new File(legacyNativeLibraryPath) : null; 9405 } 9406 9407 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9408 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9409 isFwdLocked(), abiOverride); 9410 9411 final StorageManager storage = StorageManager.from(mContext); 9412 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9413 } 9414 9415 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9416 if (origin.staged) { 9417 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9418 codeFile = origin.file; 9419 resourceFile = origin.file; 9420 return PackageManager.INSTALL_SUCCEEDED; 9421 } 9422 9423 try { 9424 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9425 codeFile = tempDir; 9426 resourceFile = tempDir; 9427 } catch (IOException e) { 9428 Slog.w(TAG, "Failed to create copy file: " + e); 9429 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9430 } 9431 9432 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9433 @Override 9434 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9435 if (!FileUtils.isValidExtFilename(name)) { 9436 throw new IllegalArgumentException("Invalid filename: " + name); 9437 } 9438 try { 9439 final File file = new File(codeFile, name); 9440 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9441 O_RDWR | O_CREAT, 0644); 9442 Os.chmod(file.getAbsolutePath(), 0644); 9443 return new ParcelFileDescriptor(fd); 9444 } catch (ErrnoException e) { 9445 throw new RemoteException("Failed to open: " + e.getMessage()); 9446 } 9447 } 9448 }; 9449 9450 int ret = PackageManager.INSTALL_SUCCEEDED; 9451 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9452 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9453 Slog.e(TAG, "Failed to copy package"); 9454 return ret; 9455 } 9456 9457 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9458 NativeLibraryHelper.Handle handle = null; 9459 try { 9460 handle = NativeLibraryHelper.Handle.create(codeFile); 9461 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9462 abiOverride); 9463 } catch (IOException e) { 9464 Slog.e(TAG, "Copying native libraries failed", e); 9465 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9466 } finally { 9467 IoUtils.closeQuietly(handle); 9468 } 9469 9470 return ret; 9471 } 9472 9473 int doPreInstall(int status) { 9474 if (status != PackageManager.INSTALL_SUCCEEDED) { 9475 cleanUp(); 9476 } 9477 return status; 9478 } 9479 9480 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9481 if (status != PackageManager.INSTALL_SUCCEEDED) { 9482 cleanUp(); 9483 return false; 9484 } else { 9485 final File beforeCodeFile = codeFile; 9486 final File afterCodeFile = getNextCodePath(pkg.packageName); 9487 9488 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9489 try { 9490 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9491 } catch (ErrnoException e) { 9492 Slog.d(TAG, "Failed to rename", e); 9493 return false; 9494 } 9495 9496 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9497 Slog.d(TAG, "Failed to restorecon"); 9498 return false; 9499 } 9500 9501 // Reflect the rename internally 9502 codeFile = afterCodeFile; 9503 resourceFile = afterCodeFile; 9504 9505 // Reflect the rename in scanned details 9506 pkg.codePath = afterCodeFile.getAbsolutePath(); 9507 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9508 pkg.baseCodePath); 9509 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9510 pkg.splitCodePaths); 9511 9512 // Reflect the rename in app info 9513 pkg.applicationInfo.setCodePath(pkg.codePath); 9514 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9515 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9516 pkg.applicationInfo.setResourcePath(pkg.codePath); 9517 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9518 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9519 9520 return true; 9521 } 9522 } 9523 9524 int doPostInstall(int status, int uid) { 9525 if (status != PackageManager.INSTALL_SUCCEEDED) { 9526 cleanUp(); 9527 } 9528 return status; 9529 } 9530 9531 @Override 9532 String getCodePath() { 9533 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9534 } 9535 9536 @Override 9537 String getResourcePath() { 9538 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9539 } 9540 9541 @Override 9542 String getLegacyNativeLibraryPath() { 9543 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9544 } 9545 9546 private boolean cleanUp() { 9547 if (codeFile == null || !codeFile.exists()) { 9548 return false; 9549 } 9550 9551 if (codeFile.isDirectory()) { 9552 FileUtils.deleteContents(codeFile); 9553 } 9554 codeFile.delete(); 9555 9556 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9557 resourceFile.delete(); 9558 } 9559 9560 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9561 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9562 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9563 } 9564 legacyNativeLibraryPath.delete(); 9565 } 9566 9567 return true; 9568 } 9569 9570 void cleanUpResourcesLI() { 9571 // Try enumerating all code paths before deleting 9572 List<String> allCodePaths = Collections.EMPTY_LIST; 9573 if (codeFile != null && codeFile.exists()) { 9574 try { 9575 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9576 allCodePaths = pkg.getAllCodePaths(); 9577 } catch (PackageParserException e) { 9578 // Ignored; we tried our best 9579 } 9580 } 9581 9582 cleanUp(); 9583 removeDexFiles(allCodePaths, instructionSets); 9584 } 9585 9586 boolean doPostDeleteLI(boolean delete) { 9587 // XXX err, shouldn't we respect the delete flag? 9588 cleanUpResourcesLI(); 9589 return true; 9590 } 9591 } 9592 9593 private boolean isAsecExternal(String cid) { 9594 final String asecPath = PackageHelper.getSdFilesystem(cid); 9595 return !asecPath.startsWith(mAsecInternalPath); 9596 } 9597 9598 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9599 PackageManagerException { 9600 if (copyRet < 0) { 9601 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9602 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9603 throw new PackageManagerException(copyRet, message); 9604 } 9605 } 9606 } 9607 9608 /** 9609 * Extract the MountService "container ID" from the full code path of an 9610 * .apk. 9611 */ 9612 static String cidFromCodePath(String fullCodePath) { 9613 int eidx = fullCodePath.lastIndexOf("/"); 9614 String subStr1 = fullCodePath.substring(0, eidx); 9615 int sidx = subStr1.lastIndexOf("/"); 9616 return subStr1.substring(sidx+1, eidx); 9617 } 9618 9619 /** 9620 * Logic to handle installation of ASEC applications, including copying and 9621 * renaming logic. 9622 */ 9623 class AsecInstallArgs extends InstallArgs { 9624 static final String RES_FILE_NAME = "pkg.apk"; 9625 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9626 9627 String cid; 9628 String packagePath; 9629 String resourcePath; 9630 String legacyNativeLibraryDir; 9631 9632 /** New install */ 9633 AsecInstallArgs(InstallParams params) { 9634 super(params.origin, params.observer, params.installFlags, 9635 params.installerPackageName, params.getManifestDigest(), 9636 params.getUser(), null /* instruction sets */, 9637 params.packageAbiOverride); 9638 } 9639 9640 /** Existing install */ 9641 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9642 boolean isExternal, boolean isForwardLocked) { 9643 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9644 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9645 instructionSets, null); 9646 // Hackily pretend we're still looking at a full code path 9647 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9648 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9649 } 9650 9651 // Extract cid from fullCodePath 9652 int eidx = fullCodePath.lastIndexOf("/"); 9653 String subStr1 = fullCodePath.substring(0, eidx); 9654 int sidx = subStr1.lastIndexOf("/"); 9655 cid = subStr1.substring(sidx+1, eidx); 9656 setMountPath(subStr1); 9657 } 9658 9659 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9660 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9661 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9662 instructionSets, null); 9663 this.cid = cid; 9664 setMountPath(PackageHelper.getSdDir(cid)); 9665 } 9666 9667 void createCopyFile() { 9668 cid = mInstallerService.allocateExternalStageCidLegacy(); 9669 } 9670 9671 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9672 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9673 abiOverride); 9674 9675 final File target; 9676 if (isExternal()) { 9677 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9678 } else { 9679 target = Environment.getDataDirectory(); 9680 } 9681 9682 final StorageManager storage = StorageManager.from(mContext); 9683 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9684 } 9685 9686 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9687 if (origin.staged) { 9688 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9689 cid = origin.cid; 9690 setMountPath(PackageHelper.getSdDir(cid)); 9691 return PackageManager.INSTALL_SUCCEEDED; 9692 } 9693 9694 if (temp) { 9695 createCopyFile(); 9696 } else { 9697 /* 9698 * Pre-emptively destroy the container since it's destroyed if 9699 * copying fails due to it existing anyway. 9700 */ 9701 PackageHelper.destroySdDir(cid); 9702 } 9703 9704 final String newMountPath = imcs.copyPackageToContainer( 9705 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9706 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9707 9708 if (newMountPath != null) { 9709 setMountPath(newMountPath); 9710 return PackageManager.INSTALL_SUCCEEDED; 9711 } else { 9712 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9713 } 9714 } 9715 9716 @Override 9717 String getCodePath() { 9718 return packagePath; 9719 } 9720 9721 @Override 9722 String getResourcePath() { 9723 return resourcePath; 9724 } 9725 9726 @Override 9727 String getLegacyNativeLibraryPath() { 9728 return legacyNativeLibraryDir; 9729 } 9730 9731 int doPreInstall(int status) { 9732 if (status != PackageManager.INSTALL_SUCCEEDED) { 9733 // Destroy container 9734 PackageHelper.destroySdDir(cid); 9735 } else { 9736 boolean mounted = PackageHelper.isContainerMounted(cid); 9737 if (!mounted) { 9738 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9739 Process.SYSTEM_UID); 9740 if (newMountPath != null) { 9741 setMountPath(newMountPath); 9742 } else { 9743 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9744 } 9745 } 9746 } 9747 return status; 9748 } 9749 9750 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9751 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9752 String newMountPath = null; 9753 if (PackageHelper.isContainerMounted(cid)) { 9754 // Unmount the container 9755 if (!PackageHelper.unMountSdDir(cid)) { 9756 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9757 return false; 9758 } 9759 } 9760 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9761 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9762 " which might be stale. Will try to clean up."); 9763 // Clean up the stale container and proceed to recreate. 9764 if (!PackageHelper.destroySdDir(newCacheId)) { 9765 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9766 return false; 9767 } 9768 // Successfully cleaned up stale container. Try to rename again. 9769 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9770 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9771 + " inspite of cleaning it up."); 9772 return false; 9773 } 9774 } 9775 if (!PackageHelper.isContainerMounted(newCacheId)) { 9776 Slog.w(TAG, "Mounting container " + newCacheId); 9777 newMountPath = PackageHelper.mountSdDir(newCacheId, 9778 getEncryptKey(), Process.SYSTEM_UID); 9779 } else { 9780 newMountPath = PackageHelper.getSdDir(newCacheId); 9781 } 9782 if (newMountPath == null) { 9783 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9784 return false; 9785 } 9786 Log.i(TAG, "Succesfully renamed " + cid + 9787 " to " + newCacheId + 9788 " at new path: " + newMountPath); 9789 cid = newCacheId; 9790 9791 final File beforeCodeFile = new File(packagePath); 9792 setMountPath(newMountPath); 9793 final File afterCodeFile = new File(packagePath); 9794 9795 // Reflect the rename in scanned details 9796 pkg.codePath = afterCodeFile.getAbsolutePath(); 9797 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9798 pkg.baseCodePath); 9799 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9800 pkg.splitCodePaths); 9801 9802 // Reflect the rename in app info 9803 pkg.applicationInfo.setCodePath(pkg.codePath); 9804 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9805 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9806 pkg.applicationInfo.setResourcePath(pkg.codePath); 9807 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9808 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9809 9810 return true; 9811 } 9812 9813 private void setMountPath(String mountPath) { 9814 final File mountFile = new File(mountPath); 9815 9816 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9817 if (monolithicFile.exists()) { 9818 packagePath = monolithicFile.getAbsolutePath(); 9819 if (isFwdLocked()) { 9820 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9821 } else { 9822 resourcePath = packagePath; 9823 } 9824 } else { 9825 packagePath = mountFile.getAbsolutePath(); 9826 resourcePath = packagePath; 9827 } 9828 9829 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9830 } 9831 9832 int doPostInstall(int status, int uid) { 9833 if (status != PackageManager.INSTALL_SUCCEEDED) { 9834 cleanUp(); 9835 } else { 9836 final int groupOwner; 9837 final String protectedFile; 9838 if (isFwdLocked()) { 9839 groupOwner = UserHandle.getSharedAppGid(uid); 9840 protectedFile = RES_FILE_NAME; 9841 } else { 9842 groupOwner = -1; 9843 protectedFile = null; 9844 } 9845 9846 if (uid < Process.FIRST_APPLICATION_UID 9847 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9848 Slog.e(TAG, "Failed to finalize " + cid); 9849 PackageHelper.destroySdDir(cid); 9850 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9851 } 9852 9853 boolean mounted = PackageHelper.isContainerMounted(cid); 9854 if (!mounted) { 9855 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9856 } 9857 } 9858 return status; 9859 } 9860 9861 private void cleanUp() { 9862 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9863 9864 // Destroy secure container 9865 PackageHelper.destroySdDir(cid); 9866 } 9867 9868 private List<String> getAllCodePaths() { 9869 final File codeFile = new File(getCodePath()); 9870 if (codeFile != null && codeFile.exists()) { 9871 try { 9872 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9873 return pkg.getAllCodePaths(); 9874 } catch (PackageParserException e) { 9875 // Ignored; we tried our best 9876 } 9877 } 9878 return Collections.EMPTY_LIST; 9879 } 9880 9881 void cleanUpResourcesLI() { 9882 // Enumerate all code paths before deleting 9883 cleanUpResourcesLI(getAllCodePaths()); 9884 } 9885 9886 private void cleanUpResourcesLI(List<String> allCodePaths) { 9887 cleanUp(); 9888 removeDexFiles(allCodePaths, instructionSets); 9889 } 9890 9891 9892 9893 String getPackageName() { 9894 return getAsecPackageName(cid); 9895 } 9896 9897 boolean doPostDeleteLI(boolean delete) { 9898 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9899 final List<String> allCodePaths = getAllCodePaths(); 9900 boolean mounted = PackageHelper.isContainerMounted(cid); 9901 if (mounted) { 9902 // Unmount first 9903 if (PackageHelper.unMountSdDir(cid)) { 9904 mounted = false; 9905 } 9906 } 9907 if (!mounted && delete) { 9908 cleanUpResourcesLI(allCodePaths); 9909 } 9910 return !mounted; 9911 } 9912 9913 @Override 9914 int doPreCopy() { 9915 if (isFwdLocked()) { 9916 if (!PackageHelper.fixSdPermissions(cid, 9917 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9918 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9919 } 9920 } 9921 9922 return PackageManager.INSTALL_SUCCEEDED; 9923 } 9924 9925 @Override 9926 int doPostCopy(int uid) { 9927 if (isFwdLocked()) { 9928 if (uid < Process.FIRST_APPLICATION_UID 9929 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9930 RES_FILE_NAME)) { 9931 Slog.e(TAG, "Failed to finalize " + cid); 9932 PackageHelper.destroySdDir(cid); 9933 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9934 } 9935 } 9936 9937 return PackageManager.INSTALL_SUCCEEDED; 9938 } 9939 } 9940 9941 static String getAsecPackageName(String packageCid) { 9942 int idx = packageCid.lastIndexOf("-"); 9943 if (idx == -1) { 9944 return packageCid; 9945 } 9946 return packageCid.substring(0, idx); 9947 } 9948 9949 // Utility method used to create code paths based on package name and available index. 9950 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9951 String idxStr = ""; 9952 int idx = 1; 9953 // Fall back to default value of idx=1 if prefix is not 9954 // part of oldCodePath 9955 if (oldCodePath != null) { 9956 String subStr = oldCodePath; 9957 // Drop the suffix right away 9958 if (suffix != null && subStr.endsWith(suffix)) { 9959 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9960 } 9961 // If oldCodePath already contains prefix find out the 9962 // ending index to either increment or decrement. 9963 int sidx = subStr.lastIndexOf(prefix); 9964 if (sidx != -1) { 9965 subStr = subStr.substring(sidx + prefix.length()); 9966 if (subStr != null) { 9967 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9968 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9969 } 9970 try { 9971 idx = Integer.parseInt(subStr); 9972 if (idx <= 1) { 9973 idx++; 9974 } else { 9975 idx--; 9976 } 9977 } catch(NumberFormatException e) { 9978 } 9979 } 9980 } 9981 } 9982 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9983 return prefix + idxStr; 9984 } 9985 9986 private File getNextCodePath(String packageName) { 9987 int suffix = 1; 9988 File result; 9989 do { 9990 result = new File(mAppInstallDir, packageName + "-" + suffix); 9991 suffix++; 9992 } while (result.exists()); 9993 return result; 9994 } 9995 9996 // Utility method used to ignore ADD/REMOVE events 9997 // by directory observer. 9998 private static boolean ignoreCodePath(String fullPathStr) { 9999 String apkName = deriveCodePathName(fullPathStr); 10000 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 10001 if (idx != -1 && ((idx+1) < apkName.length())) { 10002 // Make sure the package ends with a numeral 10003 String version = apkName.substring(idx+1); 10004 try { 10005 Integer.parseInt(version); 10006 return true; 10007 } catch (NumberFormatException e) {} 10008 } 10009 return false; 10010 } 10011 10012 // Utility method that returns the relative package path with respect 10013 // to the installation directory. Like say for /data/data/com.test-1.apk 10014 // string com.test-1 is returned. 10015 static String deriveCodePathName(String codePath) { 10016 if (codePath == null) { 10017 return null; 10018 } 10019 final File codeFile = new File(codePath); 10020 final String name = codeFile.getName(); 10021 if (codeFile.isDirectory()) { 10022 return name; 10023 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10024 final int lastDot = name.lastIndexOf('.'); 10025 return name.substring(0, lastDot); 10026 } else { 10027 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10028 return null; 10029 } 10030 } 10031 10032 class PackageInstalledInfo { 10033 String name; 10034 int uid; 10035 // The set of users that originally had this package installed. 10036 int[] origUsers; 10037 // The set of users that now have this package installed. 10038 int[] newUsers; 10039 PackageParser.Package pkg; 10040 int returnCode; 10041 String returnMsg; 10042 PackageRemovedInfo removedInfo; 10043 10044 public void setError(int code, String msg) { 10045 returnCode = code; 10046 returnMsg = msg; 10047 Slog.w(TAG, msg); 10048 } 10049 10050 public void setError(String msg, PackageParserException e) { 10051 returnCode = e.error; 10052 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10053 Slog.w(TAG, msg, e); 10054 } 10055 10056 public void setError(String msg, PackageManagerException e) { 10057 returnCode = e.error; 10058 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10059 Slog.w(TAG, msg, e); 10060 } 10061 10062 // In some error cases we want to convey more info back to the observer 10063 String origPackage; 10064 String origPermission; 10065 } 10066 10067 /* 10068 * Install a non-existing package. 10069 */ 10070 private void installNewPackageLI(PackageParser.Package pkg, 10071 int parseFlags, int scanFlags, UserHandle user, 10072 String installerPackageName, PackageInstalledInfo res) { 10073 // Remember this for later, in case we need to rollback this install 10074 String pkgName = pkg.packageName; 10075 10076 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10077 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10078 synchronized(mPackages) { 10079 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10080 // A package with the same name is already installed, though 10081 // it has been renamed to an older name. The package we 10082 // are trying to install should be installed as an update to 10083 // the existing one, but that has not been requested, so bail. 10084 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10085 + " without first uninstalling package running as " 10086 + mSettings.mRenamedPackages.get(pkgName)); 10087 return; 10088 } 10089 if (mPackages.containsKey(pkgName)) { 10090 // Don't allow installation over an existing package with the same name. 10091 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10092 + " without first uninstalling."); 10093 return; 10094 } 10095 } 10096 10097 try { 10098 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10099 System.currentTimeMillis(), user); 10100 10101 updateSettingsLI(newPackage, installerPackageName, null, null, res, user); 10102 // delete the partially installed application. the data directory will have to be 10103 // restored if it was already existing 10104 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10105 // remove package from internal structures. Note that we want deletePackageX to 10106 // delete the package data and cache directories that it created in 10107 // scanPackageLocked, unless those directories existed before we even tried to 10108 // install. 10109 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10110 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10111 res.removedInfo, true); 10112 } 10113 10114 } catch (PackageManagerException e) { 10115 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10116 } 10117 } 10118 10119 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10120 // Upgrade keysets are being used. Determine if new package has a superset of the 10121 // required keys. 10122 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10123 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10124 for (int i = 0; i < upgradeKeySets.length; i++) { 10125 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10126 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10127 return true; 10128 } 10129 } 10130 return false; 10131 } 10132 10133 private void replacePackageLI(PackageParser.Package pkg, 10134 int parseFlags, int scanFlags, UserHandle user, 10135 String installerPackageName, PackageInstalledInfo res) { 10136 PackageParser.Package oldPackage; 10137 String pkgName = pkg.packageName; 10138 int[] allUsers; 10139 boolean[] perUserInstalled; 10140 10141 // First find the old package info and check signatures 10142 synchronized(mPackages) { 10143 oldPackage = mPackages.get(pkgName); 10144 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10145 PackageSetting ps = mSettings.mPackages.get(pkgName); 10146 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10147 // default to original signature matching 10148 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10149 != PackageManager.SIGNATURE_MATCH) { 10150 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10151 "New package has a different signature: " + pkgName); 10152 return; 10153 } 10154 } else { 10155 if(!checkUpgradeKeySetLP(ps, pkg)) { 10156 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10157 "New package not signed by keys specified by upgrade-keysets: " 10158 + pkgName); 10159 return; 10160 } 10161 } 10162 10163 // In case of rollback, remember per-user/profile install state 10164 allUsers = sUserManager.getUserIds(); 10165 perUserInstalled = new boolean[allUsers.length]; 10166 for (int i = 0; i < allUsers.length; i++) { 10167 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10168 } 10169 } 10170 10171 boolean sysPkg = (isSystemApp(oldPackage)); 10172 if (sysPkg) { 10173 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10174 user, allUsers, perUserInstalled, installerPackageName, res); 10175 } else { 10176 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10177 user, allUsers, perUserInstalled, installerPackageName, res); 10178 } 10179 } 10180 10181 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10182 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10183 int[] allUsers, boolean[] perUserInstalled, 10184 String installerPackageName, PackageInstalledInfo res) { 10185 String pkgName = deletedPackage.packageName; 10186 boolean deletedPkg = true; 10187 boolean updatedSettings = false; 10188 10189 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10190 + deletedPackage); 10191 long origUpdateTime; 10192 if (pkg.mExtras != null) { 10193 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10194 } else { 10195 origUpdateTime = 0; 10196 } 10197 10198 // First delete the existing package while retaining the data directory 10199 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10200 res.removedInfo, true)) { 10201 // If the existing package wasn't successfully deleted 10202 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10203 deletedPkg = false; 10204 } else { 10205 // Successfully deleted the old package; proceed with replace. 10206 10207 // If deleted package lived in a container, give users a chance to 10208 // relinquish resources before killing. 10209 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10210 if (DEBUG_INSTALL) { 10211 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10212 } 10213 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10214 final ArrayList<String> pkgList = new ArrayList<String>(1); 10215 pkgList.add(deletedPackage.applicationInfo.packageName); 10216 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10217 } 10218 10219 deleteCodeCacheDirsLI(pkgName); 10220 try { 10221 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10222 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10223 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res, 10224 user); 10225 updatedSettings = true; 10226 } catch (PackageManagerException e) { 10227 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10228 } 10229 } 10230 10231 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10232 // remove package from internal structures. Note that we want deletePackageX to 10233 // delete the package data and cache directories that it created in 10234 // scanPackageLocked, unless those directories existed before we even tried to 10235 // install. 10236 if(updatedSettings) { 10237 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10238 deletePackageLI( 10239 pkgName, null, true, allUsers, perUserInstalled, 10240 PackageManager.DELETE_KEEP_DATA, 10241 res.removedInfo, true); 10242 } 10243 // Since we failed to install the new package we need to restore the old 10244 // package that we deleted. 10245 if (deletedPkg) { 10246 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10247 File restoreFile = new File(deletedPackage.codePath); 10248 // Parse old package 10249 boolean oldOnSd = isExternal(deletedPackage); 10250 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10251 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10252 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10253 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10254 try { 10255 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10256 } catch (PackageManagerException e) { 10257 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10258 + e.getMessage()); 10259 return; 10260 } 10261 // Restore of old package succeeded. Update permissions. 10262 // writer 10263 synchronized (mPackages) { 10264 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10265 UPDATE_PERMISSIONS_ALL); 10266 // can downgrade to reader 10267 mSettings.writeLPr(); 10268 } 10269 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10270 } 10271 } 10272 } 10273 10274 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10275 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10276 int[] allUsers, boolean[] perUserInstalled, 10277 String installerPackageName, PackageInstalledInfo res) { 10278 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10279 + ", old=" + deletedPackage); 10280 boolean disabledSystem = false; 10281 boolean updatedSettings = false; 10282 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10283 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10284 != 0) { 10285 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10286 } 10287 String packageName = deletedPackage.packageName; 10288 if (packageName == null) { 10289 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10290 "Attempt to delete null packageName."); 10291 return; 10292 } 10293 PackageParser.Package oldPkg; 10294 PackageSetting oldPkgSetting; 10295 // reader 10296 synchronized (mPackages) { 10297 oldPkg = mPackages.get(packageName); 10298 oldPkgSetting = mSettings.mPackages.get(packageName); 10299 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10300 (oldPkgSetting == null)) { 10301 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10302 "Couldn't find package:" + packageName + " information"); 10303 return; 10304 } 10305 } 10306 10307 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10308 10309 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10310 res.removedInfo.removedPackage = packageName; 10311 // Remove existing system package 10312 removePackageLI(oldPkgSetting, true); 10313 // writer 10314 synchronized (mPackages) { 10315 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10316 if (!disabledSystem && deletedPackage != null) { 10317 // We didn't need to disable the .apk as a current system package, 10318 // which means we are replacing another update that is already 10319 // installed. We need to make sure to delete the older one's .apk. 10320 res.removedInfo.args = createInstallArgsForExisting(0, 10321 deletedPackage.applicationInfo.getCodePath(), 10322 deletedPackage.applicationInfo.getResourcePath(), 10323 deletedPackage.applicationInfo.nativeLibraryRootDir, 10324 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10325 } else { 10326 res.removedInfo.args = null; 10327 } 10328 } 10329 10330 // Successfully disabled the old package. Now proceed with re-installation 10331 deleteCodeCacheDirsLI(packageName); 10332 10333 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10334 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10335 10336 PackageParser.Package newPackage = null; 10337 try { 10338 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10339 if (newPackage.mExtras != null) { 10340 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10341 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10342 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10343 10344 // is the update attempting to change shared user? that isn't going to work... 10345 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10346 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10347 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10348 + " to " + newPkgSetting.sharedUser); 10349 updatedSettings = true; 10350 } 10351 } 10352 10353 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10354 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res, 10355 user); 10356 updatedSettings = true; 10357 } 10358 10359 } catch (PackageManagerException e) { 10360 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10361 } 10362 10363 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10364 // Re installation failed. Restore old information 10365 // Remove new pkg information 10366 if (newPackage != null) { 10367 removeInstalledPackageLI(newPackage, true); 10368 } 10369 // Add back the old system package 10370 try { 10371 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10372 } catch (PackageManagerException e) { 10373 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10374 } 10375 // Restore the old system information in Settings 10376 synchronized (mPackages) { 10377 if (disabledSystem) { 10378 mSettings.enableSystemPackageLPw(packageName); 10379 } 10380 if (updatedSettings) { 10381 mSettings.setInstallerPackageName(packageName, 10382 oldPkgSetting.installerPackageName); 10383 } 10384 mSettings.writeLPr(); 10385 } 10386 } 10387 } 10388 10389 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10390 int[] allUsers, boolean[] perUserInstalled, 10391 PackageInstalledInfo res, UserHandle user) { 10392 String pkgName = newPackage.packageName; 10393 synchronized (mPackages) { 10394 //write settings. the installStatus will be incomplete at this stage. 10395 //note that the new package setting would have already been 10396 //added to mPackages. It hasn't been persisted yet. 10397 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10398 mSettings.writeLPr(); 10399 } 10400 10401 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10402 10403 synchronized (mPackages) { 10404 updatePermissionsLPw(newPackage.packageName, newPackage, 10405 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10406 ? UPDATE_PERMISSIONS_ALL : 0)); 10407 // For system-bundled packages, we assume that installing an upgraded version 10408 // of the package implies that the user actually wants to run that new code, 10409 // so we enable the package. 10410 PackageSetting ps = mSettings.mPackages.get(pkgName); 10411 if (ps != null) { 10412 if (isSystemApp(newPackage)) { 10413 // NB: implicit assumption that system package upgrades apply to all users 10414 if (DEBUG_INSTALL) { 10415 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10416 } 10417 if (res.origUsers != null) { 10418 for (int userHandle : res.origUsers) { 10419 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10420 userHandle, installerPackageName); 10421 } 10422 } 10423 // Also convey the prior install/uninstall state 10424 if (allUsers != null && perUserInstalled != null) { 10425 for (int i = 0; i < allUsers.length; i++) { 10426 if (DEBUG_INSTALL) { 10427 Slog.d(TAG, " user " + allUsers[i] 10428 + " => " + perUserInstalled[i]); 10429 } 10430 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10431 } 10432 // these install state changes will be persisted in the 10433 // upcoming call to mSettings.writeLPr(). 10434 } 10435 } 10436 // It's implied that when a user requests installation, they want the app to be 10437 // installed and enabled. 10438 int userId = user.getIdentifier(); 10439 if (userId != UserHandle.USER_ALL) { 10440 ps.setInstalled(true, userId); 10441 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 10442 } 10443 } 10444 res.name = pkgName; 10445 res.uid = newPackage.applicationInfo.uid; 10446 res.pkg = newPackage; 10447 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10448 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10449 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10450 //to update install status 10451 mSettings.writeLPr(); 10452 } 10453 } 10454 10455 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10456 final int installFlags = args.installFlags; 10457 String installerPackageName = args.installerPackageName; 10458 File tmpPackageFile = new File(args.getCodePath()); 10459 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10460 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10461 boolean replace = false; 10462 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10463 // Result object to be returned 10464 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10465 10466 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10467 // Retrieve PackageSettings and parse package 10468 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10469 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10470 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10471 PackageParser pp = new PackageParser(); 10472 pp.setSeparateProcesses(mSeparateProcesses); 10473 pp.setDisplayMetrics(mMetrics); 10474 10475 final PackageParser.Package pkg; 10476 try { 10477 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10478 } catch (PackageParserException e) { 10479 res.setError("Failed parse during installPackageLI", e); 10480 return; 10481 } 10482 10483 // Mark that we have an install time CPU ABI override. 10484 pkg.cpuAbiOverride = args.abiOverride; 10485 10486 String pkgName = res.name = pkg.packageName; 10487 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10488 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10489 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10490 return; 10491 } 10492 } 10493 10494 try { 10495 pp.collectCertificates(pkg, parseFlags); 10496 pp.collectManifestDigest(pkg); 10497 } catch (PackageParserException e) { 10498 res.setError("Failed collect during installPackageLI", e); 10499 return; 10500 } 10501 10502 /* If the installer passed in a manifest digest, compare it now. */ 10503 if (args.manifestDigest != null) { 10504 if (DEBUG_INSTALL) { 10505 final String parsedManifest = pkg.manifestDigest == null ? "null" 10506 : pkg.manifestDigest.toString(); 10507 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10508 + parsedManifest); 10509 } 10510 10511 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10512 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10513 return; 10514 } 10515 } else if (DEBUG_INSTALL) { 10516 final String parsedManifest = pkg.manifestDigest == null 10517 ? "null" : pkg.manifestDigest.toString(); 10518 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10519 } 10520 10521 // Get rid of all references to package scan path via parser. 10522 pp = null; 10523 String oldCodePath = null; 10524 boolean systemApp = false; 10525 synchronized (mPackages) { 10526 // Check if installing already existing package 10527 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10528 String oldName = mSettings.mRenamedPackages.get(pkgName); 10529 if (pkg.mOriginalPackages != null 10530 && pkg.mOriginalPackages.contains(oldName) 10531 && mPackages.containsKey(oldName)) { 10532 // This package is derived from an original package, 10533 // and this device has been updating from that original 10534 // name. We must continue using the original name, so 10535 // rename the new package here. 10536 pkg.setPackageName(oldName); 10537 pkgName = pkg.packageName; 10538 replace = true; 10539 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10540 + oldName + " pkgName=" + pkgName); 10541 } else if (mPackages.containsKey(pkgName)) { 10542 // This package, under its official name, already exists 10543 // on the device; we should replace it. 10544 replace = true; 10545 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10546 } 10547 } 10548 10549 PackageSetting ps = mSettings.mPackages.get(pkgName); 10550 if (ps != null) { 10551 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10552 10553 // Quick sanity check that we're signed correctly if updating; 10554 // we'll check this again later when scanning, but we want to 10555 // bail early here before tripping over redefined permissions. 10556 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10557 try { 10558 verifySignaturesLP(ps, pkg); 10559 } catch (PackageManagerException e) { 10560 res.setError(e.error, e.getMessage()); 10561 return; 10562 } 10563 } else { 10564 if (!checkUpgradeKeySetLP(ps, pkg)) { 10565 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 10566 + pkg.packageName + " upgrade keys do not match the " 10567 + "previously installed version"); 10568 return; 10569 } 10570 } 10571 10572 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10573 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10574 systemApp = (ps.pkg.applicationInfo.flags & 10575 ApplicationInfo.FLAG_SYSTEM) != 0; 10576 } 10577 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10578 } 10579 10580 // Check whether the newly-scanned package wants to define an already-defined perm 10581 int N = pkg.permissions.size(); 10582 for (int i = N-1; i >= 0; i--) { 10583 PackageParser.Permission perm = pkg.permissions.get(i); 10584 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10585 if (bp != null) { 10586 // If the defining package is signed with our cert, it's okay. This 10587 // also includes the "updating the same package" case, of course. 10588 // "updating same package" could also involve key-rotation. 10589 final boolean sigsOk; 10590 if (!bp.sourcePackage.equals(pkg.packageName) 10591 || !(bp.packageSetting instanceof PackageSetting) 10592 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10593 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10594 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10595 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10596 } else { 10597 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10598 } 10599 if (!sigsOk) { 10600 // If the owning package is the system itself, we log but allow 10601 // install to proceed; we fail the install on all other permission 10602 // redefinitions. 10603 if (!bp.sourcePackage.equals("android")) { 10604 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10605 + pkg.packageName + " attempting to redeclare permission " 10606 + perm.info.name + " already owned by " + bp.sourcePackage); 10607 res.origPermission = perm.info.name; 10608 res.origPackage = bp.sourcePackage; 10609 return; 10610 } else { 10611 Slog.w(TAG, "Package " + pkg.packageName 10612 + " attempting to redeclare system permission " 10613 + perm.info.name + "; ignoring new declaration"); 10614 pkg.permissions.remove(i); 10615 } 10616 } 10617 } 10618 } 10619 10620 } 10621 10622 if (systemApp && onSd) { 10623 // Disable updates to system apps on sdcard 10624 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10625 "Cannot install updates to system apps on sdcard"); 10626 return; 10627 } 10628 10629 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10630 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10631 return; 10632 } 10633 10634 if (replace) { 10635 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10636 installerPackageName, res); 10637 } else { 10638 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10639 args.user, installerPackageName, res); 10640 } 10641 synchronized (mPackages) { 10642 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10643 if (ps != null) { 10644 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10645 } 10646 } 10647 } 10648 10649 private static boolean isMultiArch(PackageSetting ps) { 10650 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10651 } 10652 10653 private static boolean isMultiArch(ApplicationInfo info) { 10654 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10655 } 10656 10657 private static boolean isExternal(PackageParser.Package pkg) { 10658 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10659 } 10660 10661 private static boolean isExternal(PackageSetting ps) { 10662 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10663 } 10664 10665 private static boolean isExternal(ApplicationInfo info) { 10666 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10667 } 10668 10669 private static boolean isSystemApp(PackageParser.Package pkg) { 10670 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10671 } 10672 10673 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10674 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 10675 } 10676 10677 private static boolean isSystemApp(ApplicationInfo info) { 10678 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10679 } 10680 10681 private static boolean isSystemApp(PackageSetting ps) { 10682 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10683 } 10684 10685 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10686 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10687 } 10688 10689 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10690 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10691 } 10692 10693 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10694 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10695 } 10696 10697 private int packageFlagsToInstallFlags(PackageSetting ps) { 10698 int installFlags = 0; 10699 if (isExternal(ps)) { 10700 installFlags |= PackageManager.INSTALL_EXTERNAL; 10701 } 10702 if (ps.isForwardLocked()) { 10703 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10704 } 10705 return installFlags; 10706 } 10707 10708 private void deleteTempPackageFiles() { 10709 final FilenameFilter filter = new FilenameFilter() { 10710 public boolean accept(File dir, String name) { 10711 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10712 } 10713 }; 10714 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10715 file.delete(); 10716 } 10717 } 10718 10719 @Override 10720 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10721 int flags) { 10722 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10723 flags); 10724 } 10725 10726 @Override 10727 public void deletePackage(final String packageName, 10728 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10729 mContext.enforceCallingOrSelfPermission( 10730 android.Manifest.permission.DELETE_PACKAGES, null); 10731 final int uid = Binder.getCallingUid(); 10732 if (UserHandle.getUserId(uid) != userId) { 10733 mContext.enforceCallingPermission( 10734 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10735 "deletePackage for user " + userId); 10736 } 10737 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10738 try { 10739 observer.onPackageDeleted(packageName, 10740 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10741 } catch (RemoteException re) { 10742 } 10743 return; 10744 } 10745 10746 boolean uninstallBlocked = false; 10747 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10748 int[] users = sUserManager.getUserIds(); 10749 for (int i = 0; i < users.length; ++i) { 10750 if (getBlockUninstallForUser(packageName, users[i])) { 10751 uninstallBlocked = true; 10752 break; 10753 } 10754 } 10755 } else { 10756 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10757 } 10758 if (uninstallBlocked) { 10759 try { 10760 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10761 null); 10762 } catch (RemoteException re) { 10763 } 10764 return; 10765 } 10766 10767 if (DEBUG_REMOVE) { 10768 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10769 } 10770 // Queue up an async operation since the package deletion may take a little while. 10771 mHandler.post(new Runnable() { 10772 public void run() { 10773 mHandler.removeCallbacks(this); 10774 final int returnCode = deletePackageX(packageName, userId, flags); 10775 if (observer != null) { 10776 try { 10777 observer.onPackageDeleted(packageName, returnCode, null); 10778 } catch (RemoteException e) { 10779 Log.i(TAG, "Observer no longer exists."); 10780 } //end catch 10781 } //end if 10782 } //end run 10783 }); 10784 } 10785 10786 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10787 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10788 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10789 try { 10790 if (dpm != null) { 10791 if (dpm.isDeviceOwner(packageName)) { 10792 return true; 10793 } 10794 int[] users; 10795 if (userId == UserHandle.USER_ALL) { 10796 users = sUserManager.getUserIds(); 10797 } else { 10798 users = new int[]{userId}; 10799 } 10800 for (int i = 0; i < users.length; ++i) { 10801 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10802 return true; 10803 } 10804 } 10805 } 10806 } catch (RemoteException e) { 10807 } 10808 return false; 10809 } 10810 10811 /** 10812 * This method is an internal method that could be get invoked either 10813 * to delete an installed package or to clean up a failed installation. 10814 * After deleting an installed package, a broadcast is sent to notify any 10815 * listeners that the package has been installed. For cleaning up a failed 10816 * installation, the broadcast is not necessary since the package's 10817 * installation wouldn't have sent the initial broadcast either 10818 * The key steps in deleting a package are 10819 * deleting the package information in internal structures like mPackages, 10820 * deleting the packages base directories through installd 10821 * updating mSettings to reflect current status 10822 * persisting settings for later use 10823 * sending a broadcast if necessary 10824 */ 10825 private int deletePackageX(String packageName, int userId, int flags) { 10826 final PackageRemovedInfo info = new PackageRemovedInfo(); 10827 final boolean res; 10828 10829 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10830 ? UserHandle.ALL : new UserHandle(userId); 10831 10832 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10833 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10834 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10835 } 10836 10837 boolean removedForAllUsers = false; 10838 boolean systemUpdate = false; 10839 10840 // for the uninstall-updates case and restricted profiles, remember the per- 10841 // userhandle installed state 10842 int[] allUsers; 10843 boolean[] perUserInstalled; 10844 synchronized (mPackages) { 10845 PackageSetting ps = mSettings.mPackages.get(packageName); 10846 allUsers = sUserManager.getUserIds(); 10847 perUserInstalled = new boolean[allUsers.length]; 10848 for (int i = 0; i < allUsers.length; i++) { 10849 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10850 } 10851 } 10852 10853 synchronized (mInstallLock) { 10854 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10855 res = deletePackageLI(packageName, removeForUser, 10856 true, allUsers, perUserInstalled, 10857 flags | REMOVE_CHATTY, info, true); 10858 systemUpdate = info.isRemovedPackageSystemUpdate; 10859 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10860 removedForAllUsers = true; 10861 } 10862 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10863 + " removedForAllUsers=" + removedForAllUsers); 10864 } 10865 10866 if (res) { 10867 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10868 10869 // If the removed package was a system update, the old system package 10870 // was re-enabled; we need to broadcast this information 10871 if (systemUpdate) { 10872 Bundle extras = new Bundle(1); 10873 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10874 ? info.removedAppId : info.uid); 10875 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10876 10877 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10878 extras, null, null, null); 10879 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10880 extras, null, null, null); 10881 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10882 null, packageName, null, null); 10883 } 10884 } 10885 // Force a gc here. 10886 Runtime.getRuntime().gc(); 10887 // Delete the resources here after sending the broadcast to let 10888 // other processes clean up before deleting resources. 10889 if (info.args != null) { 10890 synchronized (mInstallLock) { 10891 info.args.doPostDeleteLI(true); 10892 } 10893 } 10894 10895 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10896 } 10897 10898 static class PackageRemovedInfo { 10899 String removedPackage; 10900 int uid = -1; 10901 int removedAppId = -1; 10902 int[] removedUsers = null; 10903 boolean isRemovedPackageSystemUpdate = false; 10904 // Clean up resources deleted packages. 10905 InstallArgs args = null; 10906 10907 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10908 Bundle extras = new Bundle(1); 10909 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10910 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10911 if (replacing) { 10912 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10913 } 10914 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10915 if (removedPackage != null) { 10916 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10917 extras, null, null, removedUsers); 10918 if (fullRemove && !replacing) { 10919 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10920 extras, null, null, removedUsers); 10921 } 10922 } 10923 if (removedAppId >= 0) { 10924 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10925 removedUsers); 10926 } 10927 } 10928 } 10929 10930 /* 10931 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10932 * flag is not set, the data directory is removed as well. 10933 * make sure this flag is set for partially installed apps. If not its meaningless to 10934 * delete a partially installed application. 10935 */ 10936 private void removePackageDataLI(PackageSetting ps, 10937 int[] allUserHandles, boolean[] perUserInstalled, 10938 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10939 String packageName = ps.name; 10940 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10941 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10942 // Retrieve object to delete permissions for shared user later on 10943 final PackageSetting deletedPs; 10944 // reader 10945 synchronized (mPackages) { 10946 deletedPs = mSettings.mPackages.get(packageName); 10947 if (outInfo != null) { 10948 outInfo.removedPackage = packageName; 10949 outInfo.removedUsers = deletedPs != null 10950 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10951 : null; 10952 } 10953 } 10954 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10955 removeDataDirsLI(packageName); 10956 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10957 } 10958 // writer 10959 synchronized (mPackages) { 10960 if (deletedPs != null) { 10961 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10962 if (outInfo != null) { 10963 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10964 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10965 } 10966 updatePermissionsLPw(deletedPs.name, null, 0); 10967 if (deletedPs.sharedUser != null) { 10968 // Remove permissions associated with package. Since runtime 10969 // permissions are per user we have to kill the removed package 10970 // or packages running under the shared user of the removed 10971 // package if revoking the permissions requested only by the removed 10972 // package is successful and this causes a change in gids. 10973 for (int userId : UserManagerService.getInstance().getUserIds()) { 10974 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 10975 userId); 10976 if (userIdToKill == userId) { 10977 // If gids changed for this user, kill all affected packages. 10978 killSettingPackagesForUser(deletedPs, userIdToKill, 10979 KILL_APP_REASON_GIDS_CHANGED); 10980 } else if (userIdToKill == UserHandle.USER_ALL) { 10981 // If gids changed for all users, kill them all - done. 10982 killSettingPackagesForUser(deletedPs, userIdToKill, 10983 KILL_APP_REASON_GIDS_CHANGED); 10984 break; 10985 } 10986 } 10987 } 10988 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10989 } 10990 // make sure to preserve per-user disabled state if this removal was just 10991 // a downgrade of a system app to the factory package 10992 if (allUserHandles != null && perUserInstalled != null) { 10993 if (DEBUG_REMOVE) { 10994 Slog.d(TAG, "Propagating install state across downgrade"); 10995 } 10996 for (int i = 0; i < allUserHandles.length; i++) { 10997 if (DEBUG_REMOVE) { 10998 Slog.d(TAG, " user " + allUserHandles[i] 10999 + " => " + perUserInstalled[i]); 11000 } 11001 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11002 } 11003 } 11004 } 11005 // can downgrade to reader 11006 if (writeSettings) { 11007 // Save settings now 11008 mSettings.writeLPr(); 11009 } 11010 } 11011 if (outInfo != null) { 11012 // A user ID was deleted here. Go through all users and remove it 11013 // from KeyStore. 11014 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11015 } 11016 } 11017 11018 static boolean locationIsPrivileged(File path) { 11019 try { 11020 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11021 .getCanonicalPath(); 11022 return path.getCanonicalPath().startsWith(privilegedAppDir); 11023 } catch (IOException e) { 11024 Slog.e(TAG, "Unable to access code path " + path); 11025 } 11026 return false; 11027 } 11028 11029 /* 11030 * Tries to delete system package. 11031 */ 11032 private boolean deleteSystemPackageLI(PackageSetting newPs, 11033 int[] allUserHandles, boolean[] perUserInstalled, 11034 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11035 final boolean applyUserRestrictions 11036 = (allUserHandles != null) && (perUserInstalled != null); 11037 PackageSetting disabledPs = null; 11038 // Confirm if the system package has been updated 11039 // An updated system app can be deleted. This will also have to restore 11040 // the system pkg from system partition 11041 // reader 11042 synchronized (mPackages) { 11043 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11044 } 11045 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11046 + " disabledPs=" + disabledPs); 11047 if (disabledPs == null) { 11048 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11049 return false; 11050 } else if (DEBUG_REMOVE) { 11051 Slog.d(TAG, "Deleting system pkg from data partition"); 11052 } 11053 if (DEBUG_REMOVE) { 11054 if (applyUserRestrictions) { 11055 Slog.d(TAG, "Remembering install states:"); 11056 for (int i = 0; i < allUserHandles.length; i++) { 11057 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11058 } 11059 } 11060 } 11061 // Delete the updated package 11062 outInfo.isRemovedPackageSystemUpdate = true; 11063 if (disabledPs.versionCode < newPs.versionCode) { 11064 // Delete data for downgrades 11065 flags &= ~PackageManager.DELETE_KEEP_DATA; 11066 } else { 11067 // Preserve data by setting flag 11068 flags |= PackageManager.DELETE_KEEP_DATA; 11069 } 11070 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11071 allUserHandles, perUserInstalled, outInfo, writeSettings); 11072 if (!ret) { 11073 return false; 11074 } 11075 // writer 11076 synchronized (mPackages) { 11077 // Reinstate the old system package 11078 mSettings.enableSystemPackageLPw(newPs.name); 11079 // Remove any native libraries from the upgraded package. 11080 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11081 } 11082 // Install the system package 11083 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11084 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11085 if (locationIsPrivileged(disabledPs.codePath)) { 11086 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11087 } 11088 11089 final PackageParser.Package newPkg; 11090 try { 11091 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11092 } catch (PackageManagerException e) { 11093 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11094 return false; 11095 } 11096 11097 // writer 11098 synchronized (mPackages) { 11099 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11100 updatePermissionsLPw(newPkg.packageName, newPkg, 11101 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11102 if (applyUserRestrictions) { 11103 if (DEBUG_REMOVE) { 11104 Slog.d(TAG, "Propagating install state across reinstall"); 11105 } 11106 for (int i = 0; i < allUserHandles.length; i++) { 11107 if (DEBUG_REMOVE) { 11108 Slog.d(TAG, " user " + allUserHandles[i] 11109 + " => " + perUserInstalled[i]); 11110 } 11111 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11112 } 11113 // Regardless of writeSettings we need to ensure that this restriction 11114 // state propagation is persisted 11115 mSettings.writeAllUsersPackageRestrictionsLPr(); 11116 } 11117 // can downgrade to reader here 11118 if (writeSettings) { 11119 mSettings.writeLPr(); 11120 } 11121 } 11122 return true; 11123 } 11124 11125 private boolean deleteInstalledPackageLI(PackageSetting ps, 11126 boolean deleteCodeAndResources, int flags, 11127 int[] allUserHandles, boolean[] perUserInstalled, 11128 PackageRemovedInfo outInfo, boolean writeSettings) { 11129 if (outInfo != null) { 11130 outInfo.uid = ps.appId; 11131 } 11132 11133 // Delete package data from internal structures and also remove data if flag is set 11134 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11135 11136 // Delete application code and resources 11137 if (deleteCodeAndResources && (outInfo != null)) { 11138 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11139 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11140 getAppDexInstructionSets(ps)); 11141 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11142 } 11143 return true; 11144 } 11145 11146 @Override 11147 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11148 int userId) { 11149 mContext.enforceCallingOrSelfPermission( 11150 android.Manifest.permission.DELETE_PACKAGES, null); 11151 synchronized (mPackages) { 11152 PackageSetting ps = mSettings.mPackages.get(packageName); 11153 if (ps == null) { 11154 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11155 return false; 11156 } 11157 if (!ps.getInstalled(userId)) { 11158 // Can't block uninstall for an app that is not installed or enabled. 11159 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11160 return false; 11161 } 11162 ps.setBlockUninstall(blockUninstall, userId); 11163 mSettings.writePackageRestrictionsLPr(userId); 11164 } 11165 return true; 11166 } 11167 11168 @Override 11169 public boolean getBlockUninstallForUser(String packageName, int userId) { 11170 synchronized (mPackages) { 11171 PackageSetting ps = mSettings.mPackages.get(packageName); 11172 if (ps == null) { 11173 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11174 return false; 11175 } 11176 return ps.getBlockUninstall(userId); 11177 } 11178 } 11179 11180 /* 11181 * This method handles package deletion in general 11182 */ 11183 private boolean deletePackageLI(String packageName, UserHandle user, 11184 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11185 int flags, PackageRemovedInfo outInfo, 11186 boolean writeSettings) { 11187 if (packageName == null) { 11188 Slog.w(TAG, "Attempt to delete null packageName."); 11189 return false; 11190 } 11191 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11192 PackageSetting ps; 11193 boolean dataOnly = false; 11194 int removeUser = -1; 11195 int appId = -1; 11196 synchronized (mPackages) { 11197 ps = mSettings.mPackages.get(packageName); 11198 if (ps == null) { 11199 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11200 return false; 11201 } 11202 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11203 && user.getIdentifier() != UserHandle.USER_ALL) { 11204 // The caller is asking that the package only be deleted for a single 11205 // user. To do this, we just mark its uninstalled state and delete 11206 // its data. If this is a system app, we only allow this to happen if 11207 // they have set the special DELETE_SYSTEM_APP which requests different 11208 // semantics than normal for uninstalling system apps. 11209 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11210 ps.setUserState(user.getIdentifier(), 11211 COMPONENT_ENABLED_STATE_DEFAULT, 11212 false, //installed 11213 true, //stopped 11214 true, //notLaunched 11215 false, //hidden 11216 null, null, null, 11217 false // blockUninstall 11218 ); 11219 if (!isSystemApp(ps)) { 11220 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11221 // Other user still have this package installed, so all 11222 // we need to do is clear this user's data and save that 11223 // it is uninstalled. 11224 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11225 removeUser = user.getIdentifier(); 11226 appId = ps.appId; 11227 scheduleWritePackageRestrictionsLocked(removeUser); 11228 } else { 11229 // We need to set it back to 'installed' so the uninstall 11230 // broadcasts will be sent correctly. 11231 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11232 ps.setInstalled(true, user.getIdentifier()); 11233 } 11234 } else { 11235 // This is a system app, so we assume that the 11236 // other users still have this package installed, so all 11237 // we need to do is clear this user's data and save that 11238 // it is uninstalled. 11239 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11240 removeUser = user.getIdentifier(); 11241 appId = ps.appId; 11242 scheduleWritePackageRestrictionsLocked(removeUser); 11243 } 11244 } 11245 } 11246 11247 if (removeUser >= 0) { 11248 // From above, we determined that we are deleting this only 11249 // for a single user. Continue the work here. 11250 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11251 if (outInfo != null) { 11252 outInfo.removedPackage = packageName; 11253 outInfo.removedAppId = appId; 11254 outInfo.removedUsers = new int[] {removeUser}; 11255 } 11256 mInstaller.clearUserData(packageName, removeUser); 11257 removeKeystoreDataIfNeeded(removeUser, appId); 11258 schedulePackageCleaning(packageName, removeUser, false); 11259 synchronized (mPackages) { 11260 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 11261 scheduleWritePackageRestrictionsLocked(removeUser); 11262 } 11263 } 11264 return true; 11265 } 11266 11267 if (dataOnly) { 11268 // Delete application data first 11269 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11270 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11271 return true; 11272 } 11273 11274 boolean ret = false; 11275 if (isSystemApp(ps)) { 11276 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11277 // When an updated system application is deleted we delete the existing resources as well and 11278 // fall back to existing code in system partition 11279 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11280 flags, outInfo, writeSettings); 11281 } else { 11282 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11283 // Kill application pre-emptively especially for apps on sd. 11284 killApplication(packageName, ps.appId, "uninstall pkg"); 11285 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11286 allUserHandles, perUserInstalled, 11287 outInfo, writeSettings); 11288 } 11289 11290 return ret; 11291 } 11292 11293 private final class ClearStorageConnection implements ServiceConnection { 11294 IMediaContainerService mContainerService; 11295 11296 @Override 11297 public void onServiceConnected(ComponentName name, IBinder service) { 11298 synchronized (this) { 11299 mContainerService = IMediaContainerService.Stub.asInterface(service); 11300 notifyAll(); 11301 } 11302 } 11303 11304 @Override 11305 public void onServiceDisconnected(ComponentName name) { 11306 } 11307 } 11308 11309 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11310 final boolean mounted; 11311 if (Environment.isExternalStorageEmulated()) { 11312 mounted = true; 11313 } else { 11314 final String status = Environment.getExternalStorageState(); 11315 11316 mounted = status.equals(Environment.MEDIA_MOUNTED) 11317 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11318 } 11319 11320 if (!mounted) { 11321 return; 11322 } 11323 11324 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11325 int[] users; 11326 if (userId == UserHandle.USER_ALL) { 11327 users = sUserManager.getUserIds(); 11328 } else { 11329 users = new int[] { userId }; 11330 } 11331 final ClearStorageConnection conn = new ClearStorageConnection(); 11332 if (mContext.bindServiceAsUser( 11333 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11334 try { 11335 for (int curUser : users) { 11336 long timeout = SystemClock.uptimeMillis() + 5000; 11337 synchronized (conn) { 11338 long now = SystemClock.uptimeMillis(); 11339 while (conn.mContainerService == null && now < timeout) { 11340 try { 11341 conn.wait(timeout - now); 11342 } catch (InterruptedException e) { 11343 } 11344 } 11345 } 11346 if (conn.mContainerService == null) { 11347 return; 11348 } 11349 11350 final UserEnvironment userEnv = new UserEnvironment(curUser); 11351 clearDirectory(conn.mContainerService, 11352 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11353 if (allData) { 11354 clearDirectory(conn.mContainerService, 11355 userEnv.buildExternalStorageAppDataDirs(packageName)); 11356 clearDirectory(conn.mContainerService, 11357 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11358 } 11359 } 11360 } finally { 11361 mContext.unbindService(conn); 11362 } 11363 } 11364 } 11365 11366 @Override 11367 public void clearApplicationUserData(final String packageName, 11368 final IPackageDataObserver observer, final int userId) { 11369 mContext.enforceCallingOrSelfPermission( 11370 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11371 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11372 // Queue up an async operation since the package deletion may take a little while. 11373 mHandler.post(new Runnable() { 11374 public void run() { 11375 mHandler.removeCallbacks(this); 11376 final boolean succeeded; 11377 synchronized (mInstallLock) { 11378 succeeded = clearApplicationUserDataLI(packageName, userId); 11379 } 11380 clearExternalStorageDataSync(packageName, userId, true); 11381 if (succeeded) { 11382 // invoke DeviceStorageMonitor's update method to clear any notifications 11383 DeviceStorageMonitorInternal 11384 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11385 if (dsm != null) { 11386 dsm.checkMemory(); 11387 } 11388 } 11389 if(observer != null) { 11390 try { 11391 observer.onRemoveCompleted(packageName, succeeded); 11392 } catch (RemoteException e) { 11393 Log.i(TAG, "Observer no longer exists."); 11394 } 11395 } //end if observer 11396 } //end run 11397 }); 11398 } 11399 11400 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11401 if (packageName == null) { 11402 Slog.w(TAG, "Attempt to delete null packageName."); 11403 return false; 11404 } 11405 11406 // Try finding details about the requested package 11407 PackageParser.Package pkg; 11408 synchronized (mPackages) { 11409 pkg = mPackages.get(packageName); 11410 if (pkg == null) { 11411 final PackageSetting ps = mSettings.mPackages.get(packageName); 11412 if (ps != null) { 11413 pkg = ps.pkg; 11414 } 11415 } 11416 } 11417 11418 if (pkg == null) { 11419 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11420 } 11421 11422 // Always delete data directories for package, even if we found no other 11423 // record of app. This helps users recover from UID mismatches without 11424 // resorting to a full data wipe. 11425 int retCode = mInstaller.clearUserData(packageName, userId); 11426 if (retCode < 0) { 11427 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11428 return false; 11429 } 11430 11431 if (pkg == null) { 11432 return false; 11433 } 11434 11435 if (pkg != null && pkg.applicationInfo != null) { 11436 final int appId = pkg.applicationInfo.uid; 11437 removeKeystoreDataIfNeeded(userId, appId); 11438 } 11439 11440 // Create a native library symlink only if we have native libraries 11441 // and if the native libraries are 32 bit libraries. We do not provide 11442 // this symlink for 64 bit libraries. 11443 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11444 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11445 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11446 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11447 Slog.w(TAG, "Failed linking native library dir"); 11448 return false; 11449 } 11450 } 11451 11452 return true; 11453 } 11454 11455 /** 11456 * Remove entries from the keystore daemon. Will only remove it if the 11457 * {@code appId} is valid. 11458 */ 11459 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11460 if (appId < 0) { 11461 return; 11462 } 11463 11464 final KeyStore keyStore = KeyStore.getInstance(); 11465 if (keyStore != null) { 11466 if (userId == UserHandle.USER_ALL) { 11467 for (final int individual : sUserManager.getUserIds()) { 11468 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11469 } 11470 } else { 11471 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11472 } 11473 } else { 11474 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11475 } 11476 } 11477 11478 @Override 11479 public void deleteApplicationCacheFiles(final String packageName, 11480 final IPackageDataObserver observer) { 11481 mContext.enforceCallingOrSelfPermission( 11482 android.Manifest.permission.DELETE_CACHE_FILES, null); 11483 // Queue up an async operation since the package deletion may take a little while. 11484 final int userId = UserHandle.getCallingUserId(); 11485 mHandler.post(new Runnable() { 11486 public void run() { 11487 mHandler.removeCallbacks(this); 11488 final boolean succeded; 11489 synchronized (mInstallLock) { 11490 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11491 } 11492 clearExternalStorageDataSync(packageName, userId, false); 11493 if(observer != null) { 11494 try { 11495 observer.onRemoveCompleted(packageName, succeded); 11496 } catch (RemoteException e) { 11497 Log.i(TAG, "Observer no longer exists."); 11498 } 11499 } //end if observer 11500 } //end run 11501 }); 11502 } 11503 11504 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11505 if (packageName == null) { 11506 Slog.w(TAG, "Attempt to delete null packageName."); 11507 return false; 11508 } 11509 PackageParser.Package p; 11510 synchronized (mPackages) { 11511 p = mPackages.get(packageName); 11512 } 11513 if (p == null) { 11514 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11515 return false; 11516 } 11517 final ApplicationInfo applicationInfo = p.applicationInfo; 11518 if (applicationInfo == null) { 11519 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11520 return false; 11521 } 11522 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11523 if (retCode < 0) { 11524 Slog.w(TAG, "Couldn't remove cache files for package: " 11525 + packageName + " u" + userId); 11526 return false; 11527 } 11528 return true; 11529 } 11530 11531 @Override 11532 public void getPackageSizeInfo(final String packageName, int userHandle, 11533 final IPackageStatsObserver observer) { 11534 mContext.enforceCallingOrSelfPermission( 11535 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11536 if (packageName == null) { 11537 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11538 } 11539 11540 PackageStats stats = new PackageStats(packageName, userHandle); 11541 11542 /* 11543 * Queue up an async operation since the package measurement may take a 11544 * little while. 11545 */ 11546 Message msg = mHandler.obtainMessage(INIT_COPY); 11547 msg.obj = new MeasureParams(stats, observer); 11548 mHandler.sendMessage(msg); 11549 } 11550 11551 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11552 PackageStats pStats) { 11553 if (packageName == null) { 11554 Slog.w(TAG, "Attempt to get size of null packageName."); 11555 return false; 11556 } 11557 PackageParser.Package p; 11558 boolean dataOnly = false; 11559 String libDirRoot = null; 11560 String asecPath = null; 11561 PackageSetting ps = null; 11562 synchronized (mPackages) { 11563 p = mPackages.get(packageName); 11564 ps = mSettings.mPackages.get(packageName); 11565 if(p == null) { 11566 dataOnly = true; 11567 if((ps == null) || (ps.pkg == null)) { 11568 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11569 return false; 11570 } 11571 p = ps.pkg; 11572 } 11573 if (ps != null) { 11574 libDirRoot = ps.legacyNativeLibraryPathString; 11575 } 11576 if (p != null && (isExternal(p) || p.isForwardLocked())) { 11577 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11578 if (secureContainerId != null) { 11579 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11580 } 11581 } 11582 } 11583 String publicSrcDir = null; 11584 if(!dataOnly) { 11585 final ApplicationInfo applicationInfo = p.applicationInfo; 11586 if (applicationInfo == null) { 11587 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11588 return false; 11589 } 11590 if (p.isForwardLocked()) { 11591 publicSrcDir = applicationInfo.getBaseResourcePath(); 11592 } 11593 } 11594 // TODO: extend to measure size of split APKs 11595 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11596 // not just the first level. 11597 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11598 // just the primary. 11599 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11600 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11601 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11602 if (res < 0) { 11603 return false; 11604 } 11605 11606 // Fix-up for forward-locked applications in ASEC containers. 11607 if (!isExternal(p)) { 11608 pStats.codeSize += pStats.externalCodeSize; 11609 pStats.externalCodeSize = 0L; 11610 } 11611 11612 return true; 11613 } 11614 11615 11616 @Override 11617 public void addPackageToPreferred(String packageName) { 11618 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11619 } 11620 11621 @Override 11622 public void removePackageFromPreferred(String packageName) { 11623 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11624 } 11625 11626 @Override 11627 public List<PackageInfo> getPreferredPackages(int flags) { 11628 return new ArrayList<PackageInfo>(); 11629 } 11630 11631 private int getUidTargetSdkVersionLockedLPr(int uid) { 11632 Object obj = mSettings.getUserIdLPr(uid); 11633 if (obj instanceof SharedUserSetting) { 11634 final SharedUserSetting sus = (SharedUserSetting) obj; 11635 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11636 final Iterator<PackageSetting> it = sus.packages.iterator(); 11637 while (it.hasNext()) { 11638 final PackageSetting ps = it.next(); 11639 if (ps.pkg != null) { 11640 int v = ps.pkg.applicationInfo.targetSdkVersion; 11641 if (v < vers) vers = v; 11642 } 11643 } 11644 return vers; 11645 } else if (obj instanceof PackageSetting) { 11646 final PackageSetting ps = (PackageSetting) obj; 11647 if (ps.pkg != null) { 11648 return ps.pkg.applicationInfo.targetSdkVersion; 11649 } 11650 } 11651 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11652 } 11653 11654 @Override 11655 public void addPreferredActivity(IntentFilter filter, int match, 11656 ComponentName[] set, ComponentName activity, int userId) { 11657 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11658 "Adding preferred"); 11659 } 11660 11661 private void addPreferredActivityInternal(IntentFilter filter, int match, 11662 ComponentName[] set, ComponentName activity, boolean always, int userId, 11663 String opname) { 11664 // writer 11665 int callingUid = Binder.getCallingUid(); 11666 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11667 if (filter.countActions() == 0) { 11668 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11669 return; 11670 } 11671 synchronized (mPackages) { 11672 if (mContext.checkCallingOrSelfPermission( 11673 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11674 != PackageManager.PERMISSION_GRANTED) { 11675 if (getUidTargetSdkVersionLockedLPr(callingUid) 11676 < Build.VERSION_CODES.FROYO) { 11677 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11678 + callingUid); 11679 return; 11680 } 11681 mContext.enforceCallingOrSelfPermission( 11682 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11683 } 11684 11685 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11686 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11687 + userId + ":"); 11688 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11689 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11690 scheduleWritePackageRestrictionsLocked(userId); 11691 } 11692 } 11693 11694 @Override 11695 public void replacePreferredActivity(IntentFilter filter, int match, 11696 ComponentName[] set, ComponentName activity, int userId) { 11697 if (filter.countActions() != 1) { 11698 throw new IllegalArgumentException( 11699 "replacePreferredActivity expects filter to have only 1 action."); 11700 } 11701 if (filter.countDataAuthorities() != 0 11702 || filter.countDataPaths() != 0 11703 || filter.countDataSchemes() > 1 11704 || filter.countDataTypes() != 0) { 11705 throw new IllegalArgumentException( 11706 "replacePreferredActivity expects filter to have no data authorities, " + 11707 "paths, or types; and at most one scheme."); 11708 } 11709 11710 final int callingUid = Binder.getCallingUid(); 11711 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11712 synchronized (mPackages) { 11713 if (mContext.checkCallingOrSelfPermission( 11714 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11715 != PackageManager.PERMISSION_GRANTED) { 11716 if (getUidTargetSdkVersionLockedLPr(callingUid) 11717 < Build.VERSION_CODES.FROYO) { 11718 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11719 + Binder.getCallingUid()); 11720 return; 11721 } 11722 mContext.enforceCallingOrSelfPermission( 11723 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11724 } 11725 11726 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11727 if (pir != null) { 11728 // Get all of the existing entries that exactly match this filter. 11729 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11730 if (existing != null && existing.size() == 1) { 11731 PreferredActivity cur = existing.get(0); 11732 if (DEBUG_PREFERRED) { 11733 Slog.i(TAG, "Checking replace of preferred:"); 11734 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11735 if (!cur.mPref.mAlways) { 11736 Slog.i(TAG, " -- CUR; not mAlways!"); 11737 } else { 11738 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11739 Slog.i(TAG, " -- CUR: mSet=" 11740 + Arrays.toString(cur.mPref.mSetComponents)); 11741 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11742 Slog.i(TAG, " -- NEW: mMatch=" 11743 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11744 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11745 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11746 } 11747 } 11748 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11749 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11750 && cur.mPref.sameSet(set)) { 11751 // Setting the preferred activity to what it happens to be already 11752 if (DEBUG_PREFERRED) { 11753 Slog.i(TAG, "Replacing with same preferred activity " 11754 + cur.mPref.mShortComponent + " for user " 11755 + userId + ":"); 11756 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11757 } 11758 return; 11759 } 11760 } 11761 11762 if (existing != null) { 11763 if (DEBUG_PREFERRED) { 11764 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11765 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11766 } 11767 for (int i = 0; i < existing.size(); i++) { 11768 PreferredActivity pa = existing.get(i); 11769 if (DEBUG_PREFERRED) { 11770 Slog.i(TAG, "Removing existing preferred activity " 11771 + pa.mPref.mComponent + ":"); 11772 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11773 } 11774 pir.removeFilter(pa); 11775 } 11776 } 11777 } 11778 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11779 "Replacing preferred"); 11780 } 11781 } 11782 11783 @Override 11784 public void clearPackagePreferredActivities(String packageName) { 11785 final int uid = Binder.getCallingUid(); 11786 // writer 11787 synchronized (mPackages) { 11788 PackageParser.Package pkg = mPackages.get(packageName); 11789 if (pkg == null || pkg.applicationInfo.uid != uid) { 11790 if (mContext.checkCallingOrSelfPermission( 11791 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11792 != PackageManager.PERMISSION_GRANTED) { 11793 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11794 < Build.VERSION_CODES.FROYO) { 11795 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11796 + Binder.getCallingUid()); 11797 return; 11798 } 11799 mContext.enforceCallingOrSelfPermission( 11800 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11801 } 11802 } 11803 11804 int user = UserHandle.getCallingUserId(); 11805 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11806 scheduleWritePackageRestrictionsLocked(user); 11807 } 11808 } 11809 } 11810 11811 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11812 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11813 ArrayList<PreferredActivity> removed = null; 11814 boolean changed = false; 11815 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11816 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11817 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11818 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11819 continue; 11820 } 11821 Iterator<PreferredActivity> it = pir.filterIterator(); 11822 while (it.hasNext()) { 11823 PreferredActivity pa = it.next(); 11824 // Mark entry for removal only if it matches the package name 11825 // and the entry is of type "always". 11826 if (packageName == null || 11827 (pa.mPref.mComponent.getPackageName().equals(packageName) 11828 && pa.mPref.mAlways)) { 11829 if (removed == null) { 11830 removed = new ArrayList<PreferredActivity>(); 11831 } 11832 removed.add(pa); 11833 } 11834 } 11835 if (removed != null) { 11836 for (int j=0; j<removed.size(); j++) { 11837 PreferredActivity pa = removed.get(j); 11838 pir.removeFilter(pa); 11839 } 11840 changed = true; 11841 } 11842 } 11843 return changed; 11844 } 11845 11846 @Override 11847 public void resetPreferredActivities(int userId) { 11848 /* TODO: Actually use userId. Why is it being passed in? */ 11849 mContext.enforceCallingOrSelfPermission( 11850 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11851 // writer 11852 synchronized (mPackages) { 11853 int user = UserHandle.getCallingUserId(); 11854 clearPackagePreferredActivitiesLPw(null, user); 11855 mSettings.readDefaultPreferredAppsLPw(this, user); 11856 scheduleWritePackageRestrictionsLocked(user); 11857 } 11858 } 11859 11860 @Override 11861 public int getPreferredActivities(List<IntentFilter> outFilters, 11862 List<ComponentName> outActivities, String packageName) { 11863 11864 int num = 0; 11865 final int userId = UserHandle.getCallingUserId(); 11866 // reader 11867 synchronized (mPackages) { 11868 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11869 if (pir != null) { 11870 final Iterator<PreferredActivity> it = pir.filterIterator(); 11871 while (it.hasNext()) { 11872 final PreferredActivity pa = it.next(); 11873 if (packageName == null 11874 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11875 && pa.mPref.mAlways)) { 11876 if (outFilters != null) { 11877 outFilters.add(new IntentFilter(pa)); 11878 } 11879 if (outActivities != null) { 11880 outActivities.add(pa.mPref.mComponent); 11881 } 11882 } 11883 } 11884 } 11885 } 11886 11887 return num; 11888 } 11889 11890 @Override 11891 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11892 int userId) { 11893 int callingUid = Binder.getCallingUid(); 11894 if (callingUid != Process.SYSTEM_UID) { 11895 throw new SecurityException( 11896 "addPersistentPreferredActivity can only be run by the system"); 11897 } 11898 if (filter.countActions() == 0) { 11899 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11900 return; 11901 } 11902 synchronized (mPackages) { 11903 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11904 " :"); 11905 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11906 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11907 new PersistentPreferredActivity(filter, activity)); 11908 scheduleWritePackageRestrictionsLocked(userId); 11909 } 11910 } 11911 11912 @Override 11913 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11914 int callingUid = Binder.getCallingUid(); 11915 if (callingUid != Process.SYSTEM_UID) { 11916 throw new SecurityException( 11917 "clearPackagePersistentPreferredActivities can only be run by the system"); 11918 } 11919 ArrayList<PersistentPreferredActivity> removed = null; 11920 boolean changed = false; 11921 synchronized (mPackages) { 11922 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11923 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11924 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11925 .valueAt(i); 11926 if (userId != thisUserId) { 11927 continue; 11928 } 11929 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11930 while (it.hasNext()) { 11931 PersistentPreferredActivity ppa = it.next(); 11932 // Mark entry for removal only if it matches the package name. 11933 if (ppa.mComponent.getPackageName().equals(packageName)) { 11934 if (removed == null) { 11935 removed = new ArrayList<PersistentPreferredActivity>(); 11936 } 11937 removed.add(ppa); 11938 } 11939 } 11940 if (removed != null) { 11941 for (int j=0; j<removed.size(); j++) { 11942 PersistentPreferredActivity ppa = removed.get(j); 11943 ppir.removeFilter(ppa); 11944 } 11945 changed = true; 11946 } 11947 } 11948 11949 if (changed) { 11950 scheduleWritePackageRestrictionsLocked(userId); 11951 } 11952 } 11953 } 11954 11955 @Override 11956 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11957 int sourceUserId, int targetUserId, int flags) { 11958 mContext.enforceCallingOrSelfPermission( 11959 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11960 int callingUid = Binder.getCallingUid(); 11961 enforceOwnerRights(ownerPackage, callingUid); 11962 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11963 if (intentFilter.countActions() == 0) { 11964 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11965 return; 11966 } 11967 synchronized (mPackages) { 11968 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 11969 ownerPackage, targetUserId, flags); 11970 CrossProfileIntentResolver resolver = 11971 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11972 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 11973 // We have all those whose filter is equal. Now checking if the rest is equal as well. 11974 if (existing != null) { 11975 int size = existing.size(); 11976 for (int i = 0; i < size; i++) { 11977 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 11978 return; 11979 } 11980 } 11981 } 11982 resolver.addFilter(newFilter); 11983 scheduleWritePackageRestrictionsLocked(sourceUserId); 11984 } 11985 } 11986 11987 @Override 11988 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 11989 mContext.enforceCallingOrSelfPermission( 11990 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11991 int callingUid = Binder.getCallingUid(); 11992 enforceOwnerRights(ownerPackage, callingUid); 11993 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11994 synchronized (mPackages) { 11995 CrossProfileIntentResolver resolver = 11996 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11997 ArraySet<CrossProfileIntentFilter> set = 11998 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 11999 for (CrossProfileIntentFilter filter : set) { 12000 if (filter.getOwnerPackage().equals(ownerPackage)) { 12001 resolver.removeFilter(filter); 12002 } 12003 } 12004 scheduleWritePackageRestrictionsLocked(sourceUserId); 12005 } 12006 } 12007 12008 // Enforcing that callingUid is owning pkg on userId 12009 private void enforceOwnerRights(String pkg, int callingUid) { 12010 // The system owns everything. 12011 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12012 return; 12013 } 12014 int callingUserId = UserHandle.getUserId(callingUid); 12015 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12016 if (pi == null) { 12017 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12018 + callingUserId); 12019 } 12020 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12021 throw new SecurityException("Calling uid " + callingUid 12022 + " does not own package " + pkg); 12023 } 12024 } 12025 12026 @Override 12027 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12028 Intent intent = new Intent(Intent.ACTION_MAIN); 12029 intent.addCategory(Intent.CATEGORY_HOME); 12030 12031 final int callingUserId = UserHandle.getCallingUserId(); 12032 List<ResolveInfo> list = queryIntentActivities(intent, null, 12033 PackageManager.GET_META_DATA, callingUserId); 12034 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12035 true, false, false, callingUserId); 12036 12037 allHomeCandidates.clear(); 12038 if (list != null) { 12039 for (ResolveInfo ri : list) { 12040 allHomeCandidates.add(ri); 12041 } 12042 } 12043 return (preferred == null || preferred.activityInfo == null) 12044 ? null 12045 : new ComponentName(preferred.activityInfo.packageName, 12046 preferred.activityInfo.name); 12047 } 12048 12049 @Override 12050 public void setApplicationEnabledSetting(String appPackageName, 12051 int newState, int flags, int userId, String callingPackage) { 12052 if (!sUserManager.exists(userId)) return; 12053 if (callingPackage == null) { 12054 callingPackage = Integer.toString(Binder.getCallingUid()); 12055 } 12056 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12057 } 12058 12059 @Override 12060 public void setComponentEnabledSetting(ComponentName componentName, 12061 int newState, int flags, int userId) { 12062 if (!sUserManager.exists(userId)) return; 12063 setEnabledSetting(componentName.getPackageName(), 12064 componentName.getClassName(), newState, flags, userId, null); 12065 } 12066 12067 private void setEnabledSetting(final String packageName, String className, int newState, 12068 final int flags, int userId, String callingPackage) { 12069 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12070 || newState == COMPONENT_ENABLED_STATE_ENABLED 12071 || newState == COMPONENT_ENABLED_STATE_DISABLED 12072 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12073 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12074 throw new IllegalArgumentException("Invalid new component state: " 12075 + newState); 12076 } 12077 PackageSetting pkgSetting; 12078 final int uid = Binder.getCallingUid(); 12079 final int permission = mContext.checkCallingOrSelfPermission( 12080 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12081 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12082 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12083 boolean sendNow = false; 12084 boolean isApp = (className == null); 12085 String componentName = isApp ? packageName : className; 12086 int packageUid = -1; 12087 ArrayList<String> components; 12088 12089 // writer 12090 synchronized (mPackages) { 12091 pkgSetting = mSettings.mPackages.get(packageName); 12092 if (pkgSetting == null) { 12093 if (className == null) { 12094 throw new IllegalArgumentException( 12095 "Unknown package: " + packageName); 12096 } 12097 throw new IllegalArgumentException( 12098 "Unknown component: " + packageName 12099 + "/" + className); 12100 } 12101 // Allow root and verify that userId is not being specified by a different user 12102 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12103 throw new SecurityException( 12104 "Permission Denial: attempt to change component state from pid=" 12105 + Binder.getCallingPid() 12106 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12107 } 12108 if (className == null) { 12109 // We're dealing with an application/package level state change 12110 if (pkgSetting.getEnabled(userId) == newState) { 12111 // Nothing to do 12112 return; 12113 } 12114 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12115 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12116 // Don't care about who enables an app. 12117 callingPackage = null; 12118 } 12119 pkgSetting.setEnabled(newState, userId, callingPackage); 12120 // pkgSetting.pkg.mSetEnabled = newState; 12121 } else { 12122 // We're dealing with a component level state change 12123 // First, verify that this is a valid class name. 12124 PackageParser.Package pkg = pkgSetting.pkg; 12125 if (pkg == null || !pkg.hasComponentClassName(className)) { 12126 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12127 throw new IllegalArgumentException("Component class " + className 12128 + " does not exist in " + packageName); 12129 } else { 12130 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12131 + className + " does not exist in " + packageName); 12132 } 12133 } 12134 switch (newState) { 12135 case COMPONENT_ENABLED_STATE_ENABLED: 12136 if (!pkgSetting.enableComponentLPw(className, userId)) { 12137 return; 12138 } 12139 break; 12140 case COMPONENT_ENABLED_STATE_DISABLED: 12141 if (!pkgSetting.disableComponentLPw(className, userId)) { 12142 return; 12143 } 12144 break; 12145 case COMPONENT_ENABLED_STATE_DEFAULT: 12146 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12147 return; 12148 } 12149 break; 12150 default: 12151 Slog.e(TAG, "Invalid new component state: " + newState); 12152 return; 12153 } 12154 } 12155 scheduleWritePackageRestrictionsLocked(userId); 12156 components = mPendingBroadcasts.get(userId, packageName); 12157 final boolean newPackage = components == null; 12158 if (newPackage) { 12159 components = new ArrayList<String>(); 12160 } 12161 if (!components.contains(componentName)) { 12162 components.add(componentName); 12163 } 12164 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12165 sendNow = true; 12166 // Purge entry from pending broadcast list if another one exists already 12167 // since we are sending one right away. 12168 mPendingBroadcasts.remove(userId, packageName); 12169 } else { 12170 if (newPackage) { 12171 mPendingBroadcasts.put(userId, packageName, components); 12172 } 12173 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12174 // Schedule a message 12175 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12176 } 12177 } 12178 } 12179 12180 long callingId = Binder.clearCallingIdentity(); 12181 try { 12182 if (sendNow) { 12183 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12184 sendPackageChangedBroadcast(packageName, 12185 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12186 } 12187 } finally { 12188 Binder.restoreCallingIdentity(callingId); 12189 } 12190 } 12191 12192 private void sendPackageChangedBroadcast(String packageName, 12193 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12194 if (DEBUG_INSTALL) 12195 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12196 + componentNames); 12197 Bundle extras = new Bundle(4); 12198 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12199 String nameList[] = new String[componentNames.size()]; 12200 componentNames.toArray(nameList); 12201 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12202 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12203 extras.putInt(Intent.EXTRA_UID, packageUid); 12204 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12205 new int[] {UserHandle.getUserId(packageUid)}); 12206 } 12207 12208 @Override 12209 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12210 if (!sUserManager.exists(userId)) return; 12211 final int uid = Binder.getCallingUid(); 12212 final int permission = mContext.checkCallingOrSelfPermission( 12213 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12214 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12215 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12216 // writer 12217 synchronized (mPackages) { 12218 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12219 uid, userId)) { 12220 scheduleWritePackageRestrictionsLocked(userId); 12221 } 12222 } 12223 } 12224 12225 @Override 12226 public String getInstallerPackageName(String packageName) { 12227 // reader 12228 synchronized (mPackages) { 12229 return mSettings.getInstallerPackageNameLPr(packageName); 12230 } 12231 } 12232 12233 @Override 12234 public int getApplicationEnabledSetting(String packageName, int userId) { 12235 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12236 int uid = Binder.getCallingUid(); 12237 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12238 // reader 12239 synchronized (mPackages) { 12240 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12241 } 12242 } 12243 12244 @Override 12245 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12246 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12247 int uid = Binder.getCallingUid(); 12248 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12249 // reader 12250 synchronized (mPackages) { 12251 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12252 } 12253 } 12254 12255 @Override 12256 public void enterSafeMode() { 12257 enforceSystemOrRoot("Only the system can request entering safe mode"); 12258 12259 if (!mSystemReady) { 12260 mSafeMode = true; 12261 } 12262 } 12263 12264 @Override 12265 public void systemReady() { 12266 mSystemReady = true; 12267 12268 // Read the compatibilty setting when the system is ready. 12269 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12270 mContext.getContentResolver(), 12271 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12272 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12273 if (DEBUG_SETTINGS) { 12274 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12275 } 12276 12277 synchronized (mPackages) { 12278 // Verify that all of the preferred activity components actually 12279 // exist. It is possible for applications to be updated and at 12280 // that point remove a previously declared activity component that 12281 // had been set as a preferred activity. We try to clean this up 12282 // the next time we encounter that preferred activity, but it is 12283 // possible for the user flow to never be able to return to that 12284 // situation so here we do a sanity check to make sure we haven't 12285 // left any junk around. 12286 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12287 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12288 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12289 removed.clear(); 12290 for (PreferredActivity pa : pir.filterSet()) { 12291 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12292 removed.add(pa); 12293 } 12294 } 12295 if (removed.size() > 0) { 12296 for (int r=0; r<removed.size(); r++) { 12297 PreferredActivity pa = removed.get(r); 12298 Slog.w(TAG, "Removing dangling preferred activity: " 12299 + pa.mPref.mComponent); 12300 pir.removeFilter(pa); 12301 } 12302 mSettings.writePackageRestrictionsLPr( 12303 mSettings.mPreferredActivities.keyAt(i)); 12304 } 12305 } 12306 } 12307 sUserManager.systemReady(); 12308 12309 // Kick off any messages waiting for system ready 12310 if (mPostSystemReadyMessages != null) { 12311 for (Message msg : mPostSystemReadyMessages) { 12312 msg.sendToTarget(); 12313 } 12314 mPostSystemReadyMessages = null; 12315 } 12316 } 12317 12318 @Override 12319 public boolean isSafeMode() { 12320 return mSafeMode; 12321 } 12322 12323 @Override 12324 public boolean hasSystemUidErrors() { 12325 return mHasSystemUidErrors; 12326 } 12327 12328 static String arrayToString(int[] array) { 12329 StringBuffer buf = new StringBuffer(128); 12330 buf.append('['); 12331 if (array != null) { 12332 for (int i=0; i<array.length; i++) { 12333 if (i > 0) buf.append(", "); 12334 buf.append(array[i]); 12335 } 12336 } 12337 buf.append(']'); 12338 return buf.toString(); 12339 } 12340 12341 static class DumpState { 12342 public static final int DUMP_LIBS = 1 << 0; 12343 public static final int DUMP_FEATURES = 1 << 1; 12344 public static final int DUMP_RESOLVERS = 1 << 2; 12345 public static final int DUMP_PERMISSIONS = 1 << 3; 12346 public static final int DUMP_PACKAGES = 1 << 4; 12347 public static final int DUMP_SHARED_USERS = 1 << 5; 12348 public static final int DUMP_MESSAGES = 1 << 6; 12349 public static final int DUMP_PROVIDERS = 1 << 7; 12350 public static final int DUMP_VERIFIERS = 1 << 8; 12351 public static final int DUMP_PREFERRED = 1 << 9; 12352 public static final int DUMP_PREFERRED_XML = 1 << 10; 12353 public static final int DUMP_KEYSETS = 1 << 11; 12354 public static final int DUMP_VERSION = 1 << 12; 12355 public static final int DUMP_INSTALLS = 1 << 13; 12356 12357 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12358 12359 private int mTypes; 12360 12361 private int mOptions; 12362 12363 private boolean mTitlePrinted; 12364 12365 private SharedUserSetting mSharedUser; 12366 12367 public boolean isDumping(int type) { 12368 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12369 return true; 12370 } 12371 12372 return (mTypes & type) != 0; 12373 } 12374 12375 public void setDump(int type) { 12376 mTypes |= type; 12377 } 12378 12379 public boolean isOptionEnabled(int option) { 12380 return (mOptions & option) != 0; 12381 } 12382 12383 public void setOptionEnabled(int option) { 12384 mOptions |= option; 12385 } 12386 12387 public boolean onTitlePrinted() { 12388 final boolean printed = mTitlePrinted; 12389 mTitlePrinted = true; 12390 return printed; 12391 } 12392 12393 public boolean getTitlePrinted() { 12394 return mTitlePrinted; 12395 } 12396 12397 public void setTitlePrinted(boolean enabled) { 12398 mTitlePrinted = enabled; 12399 } 12400 12401 public SharedUserSetting getSharedUser() { 12402 return mSharedUser; 12403 } 12404 12405 public void setSharedUser(SharedUserSetting user) { 12406 mSharedUser = user; 12407 } 12408 } 12409 12410 @Override 12411 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12412 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12413 != PackageManager.PERMISSION_GRANTED) { 12414 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12415 + Binder.getCallingPid() 12416 + ", uid=" + Binder.getCallingUid() 12417 + " without permission " 12418 + android.Manifest.permission.DUMP); 12419 return; 12420 } 12421 12422 DumpState dumpState = new DumpState(); 12423 boolean fullPreferred = false; 12424 boolean checkin = false; 12425 12426 String packageName = null; 12427 12428 int opti = 0; 12429 while (opti < args.length) { 12430 String opt = args[opti]; 12431 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12432 break; 12433 } 12434 opti++; 12435 12436 if ("-a".equals(opt)) { 12437 // Right now we only know how to print all. 12438 } else if ("-h".equals(opt)) { 12439 pw.println("Package manager dump options:"); 12440 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12441 pw.println(" --checkin: dump for a checkin"); 12442 pw.println(" -f: print details of intent filters"); 12443 pw.println(" -h: print this help"); 12444 pw.println(" cmd may be one of:"); 12445 pw.println(" l[ibraries]: list known shared libraries"); 12446 pw.println(" f[ibraries]: list device features"); 12447 pw.println(" k[eysets]: print known keysets"); 12448 pw.println(" r[esolvers]: dump intent resolvers"); 12449 pw.println(" perm[issions]: dump permissions"); 12450 pw.println(" pref[erred]: print preferred package settings"); 12451 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12452 pw.println(" prov[iders]: dump content providers"); 12453 pw.println(" p[ackages]: dump installed packages"); 12454 pw.println(" s[hared-users]: dump shared user IDs"); 12455 pw.println(" m[essages]: print collected runtime messages"); 12456 pw.println(" v[erifiers]: print package verifier info"); 12457 pw.println(" version: print database version info"); 12458 pw.println(" write: write current settings now"); 12459 pw.println(" <package.name>: info about given package"); 12460 pw.println(" installs: details about install sessions"); 12461 return; 12462 } else if ("--checkin".equals(opt)) { 12463 checkin = true; 12464 } else if ("-f".equals(opt)) { 12465 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12466 } else { 12467 pw.println("Unknown argument: " + opt + "; use -h for help"); 12468 } 12469 } 12470 12471 // Is the caller requesting to dump a particular piece of data? 12472 if (opti < args.length) { 12473 String cmd = args[opti]; 12474 opti++; 12475 // Is this a package name? 12476 if ("android".equals(cmd) || cmd.contains(".")) { 12477 packageName = cmd; 12478 // When dumping a single package, we always dump all of its 12479 // filter information since the amount of data will be reasonable. 12480 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12481 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12482 dumpState.setDump(DumpState.DUMP_LIBS); 12483 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12484 dumpState.setDump(DumpState.DUMP_FEATURES); 12485 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12486 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12487 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12488 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12489 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12490 dumpState.setDump(DumpState.DUMP_PREFERRED); 12491 } else if ("preferred-xml".equals(cmd)) { 12492 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12493 if (opti < args.length && "--full".equals(args[opti])) { 12494 fullPreferred = true; 12495 opti++; 12496 } 12497 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12498 dumpState.setDump(DumpState.DUMP_PACKAGES); 12499 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12500 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12501 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12502 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12503 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12504 dumpState.setDump(DumpState.DUMP_MESSAGES); 12505 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12506 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12507 } else if ("version".equals(cmd)) { 12508 dumpState.setDump(DumpState.DUMP_VERSION); 12509 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12510 dumpState.setDump(DumpState.DUMP_KEYSETS); 12511 } else if ("installs".equals(cmd)) { 12512 dumpState.setDump(DumpState.DUMP_INSTALLS); 12513 } else if ("write".equals(cmd)) { 12514 synchronized (mPackages) { 12515 mSettings.writeLPr(); 12516 pw.println("Settings written."); 12517 return; 12518 } 12519 } 12520 } 12521 12522 if (checkin) { 12523 pw.println("vers,1"); 12524 } 12525 12526 // reader 12527 synchronized (mPackages) { 12528 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12529 if (!checkin) { 12530 if (dumpState.onTitlePrinted()) 12531 pw.println(); 12532 pw.println("Database versions:"); 12533 pw.print(" SDK Version:"); 12534 pw.print(" internal="); 12535 pw.print(mSettings.mInternalSdkPlatform); 12536 pw.print(" external="); 12537 pw.println(mSettings.mExternalSdkPlatform); 12538 pw.print(" DB Version:"); 12539 pw.print(" internal="); 12540 pw.print(mSettings.mInternalDatabaseVersion); 12541 pw.print(" external="); 12542 pw.println(mSettings.mExternalDatabaseVersion); 12543 } 12544 } 12545 12546 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12547 if (!checkin) { 12548 if (dumpState.onTitlePrinted()) 12549 pw.println(); 12550 pw.println("Verifiers:"); 12551 pw.print(" Required: "); 12552 pw.print(mRequiredVerifierPackage); 12553 pw.print(" (uid="); 12554 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12555 pw.println(")"); 12556 } else if (mRequiredVerifierPackage != null) { 12557 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12558 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12559 } 12560 } 12561 12562 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12563 boolean printedHeader = false; 12564 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12565 while (it.hasNext()) { 12566 String name = it.next(); 12567 SharedLibraryEntry ent = mSharedLibraries.get(name); 12568 if (!checkin) { 12569 if (!printedHeader) { 12570 if (dumpState.onTitlePrinted()) 12571 pw.println(); 12572 pw.println("Libraries:"); 12573 printedHeader = true; 12574 } 12575 pw.print(" "); 12576 } else { 12577 pw.print("lib,"); 12578 } 12579 pw.print(name); 12580 if (!checkin) { 12581 pw.print(" -> "); 12582 } 12583 if (ent.path != null) { 12584 if (!checkin) { 12585 pw.print("(jar) "); 12586 pw.print(ent.path); 12587 } else { 12588 pw.print(",jar,"); 12589 pw.print(ent.path); 12590 } 12591 } else { 12592 if (!checkin) { 12593 pw.print("(apk) "); 12594 pw.print(ent.apk); 12595 } else { 12596 pw.print(",apk,"); 12597 pw.print(ent.apk); 12598 } 12599 } 12600 pw.println(); 12601 } 12602 } 12603 12604 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12605 if (dumpState.onTitlePrinted()) 12606 pw.println(); 12607 if (!checkin) { 12608 pw.println("Features:"); 12609 } 12610 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12611 while (it.hasNext()) { 12612 String name = it.next(); 12613 if (!checkin) { 12614 pw.print(" "); 12615 } else { 12616 pw.print("feat,"); 12617 } 12618 pw.println(name); 12619 } 12620 } 12621 12622 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12623 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12624 : "Activity Resolver Table:", " ", packageName, 12625 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12626 dumpState.setTitlePrinted(true); 12627 } 12628 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12629 : "Receiver Resolver Table:", " ", packageName, 12630 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12631 dumpState.setTitlePrinted(true); 12632 } 12633 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12634 : "Service Resolver Table:", " ", packageName, 12635 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12636 dumpState.setTitlePrinted(true); 12637 } 12638 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12639 : "Provider Resolver Table:", " ", packageName, 12640 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12641 dumpState.setTitlePrinted(true); 12642 } 12643 } 12644 12645 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12646 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12647 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12648 int user = mSettings.mPreferredActivities.keyAt(i); 12649 if (pir.dump(pw, 12650 dumpState.getTitlePrinted() 12651 ? "\nPreferred Activities User " + user + ":" 12652 : "Preferred Activities User " + user + ":", " ", 12653 packageName, true, false)) { 12654 dumpState.setTitlePrinted(true); 12655 } 12656 } 12657 } 12658 12659 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12660 pw.flush(); 12661 FileOutputStream fout = new FileOutputStream(fd); 12662 BufferedOutputStream str = new BufferedOutputStream(fout); 12663 XmlSerializer serializer = new FastXmlSerializer(); 12664 try { 12665 serializer.setOutput(str, "utf-8"); 12666 serializer.startDocument(null, true); 12667 serializer.setFeature( 12668 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12669 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12670 serializer.endDocument(); 12671 serializer.flush(); 12672 } catch (IllegalArgumentException e) { 12673 pw.println("Failed writing: " + e); 12674 } catch (IllegalStateException e) { 12675 pw.println("Failed writing: " + e); 12676 } catch (IOException e) { 12677 pw.println("Failed writing: " + e); 12678 } 12679 } 12680 12681 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12682 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12683 if (packageName == null) { 12684 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12685 if (iperm == 0) { 12686 if (dumpState.onTitlePrinted()) 12687 pw.println(); 12688 pw.println("AppOp Permissions:"); 12689 } 12690 pw.print(" AppOp Permission "); 12691 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12692 pw.println(":"); 12693 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12694 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12695 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12696 } 12697 } 12698 } 12699 } 12700 12701 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12702 boolean printedSomething = false; 12703 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12704 if (packageName != null && !packageName.equals(p.info.packageName)) { 12705 continue; 12706 } 12707 if (!printedSomething) { 12708 if (dumpState.onTitlePrinted()) 12709 pw.println(); 12710 pw.println("Registered ContentProviders:"); 12711 printedSomething = true; 12712 } 12713 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12714 pw.print(" "); pw.println(p.toString()); 12715 } 12716 printedSomething = false; 12717 for (Map.Entry<String, PackageParser.Provider> entry : 12718 mProvidersByAuthority.entrySet()) { 12719 PackageParser.Provider p = entry.getValue(); 12720 if (packageName != null && !packageName.equals(p.info.packageName)) { 12721 continue; 12722 } 12723 if (!printedSomething) { 12724 if (dumpState.onTitlePrinted()) 12725 pw.println(); 12726 pw.println("ContentProvider Authorities:"); 12727 printedSomething = true; 12728 } 12729 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12730 pw.print(" "); pw.println(p.toString()); 12731 if (p.info != null && p.info.applicationInfo != null) { 12732 final String appInfo = p.info.applicationInfo.toString(); 12733 pw.print(" applicationInfo="); pw.println(appInfo); 12734 } 12735 } 12736 } 12737 12738 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12739 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12740 } 12741 12742 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12743 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12744 } 12745 12746 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12747 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 12748 } 12749 12750 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12751 // XXX should handle packageName != null by dumping only install data that 12752 // the given package is involved with. 12753 if (dumpState.onTitlePrinted()) pw.println(); 12754 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12755 } 12756 12757 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12758 if (dumpState.onTitlePrinted()) pw.println(); 12759 mSettings.dumpReadMessagesLPr(pw, dumpState); 12760 12761 pw.println(); 12762 pw.println("Package warning messages:"); 12763 BufferedReader in = null; 12764 String line = null; 12765 try { 12766 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12767 while ((line = in.readLine()) != null) { 12768 if (line.contains("ignored: updated version")) continue; 12769 pw.println(line); 12770 } 12771 } catch (IOException ignored) { 12772 } finally { 12773 IoUtils.closeQuietly(in); 12774 } 12775 } 12776 12777 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12778 BufferedReader in = null; 12779 String line = null; 12780 try { 12781 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12782 while ((line = in.readLine()) != null) { 12783 if (line.contains("ignored: updated version")) continue; 12784 pw.print("msg,"); 12785 pw.println(line); 12786 } 12787 } catch (IOException ignored) { 12788 } finally { 12789 IoUtils.closeQuietly(in); 12790 } 12791 } 12792 } 12793 } 12794 12795 // ------- apps on sdcard specific code ------- 12796 static final boolean DEBUG_SD_INSTALL = false; 12797 12798 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12799 12800 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12801 12802 private boolean mMediaMounted = false; 12803 12804 static String getEncryptKey() { 12805 try { 12806 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12807 SD_ENCRYPTION_KEYSTORE_NAME); 12808 if (sdEncKey == null) { 12809 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12810 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12811 if (sdEncKey == null) { 12812 Slog.e(TAG, "Failed to create encryption keys"); 12813 return null; 12814 } 12815 } 12816 return sdEncKey; 12817 } catch (NoSuchAlgorithmException nsae) { 12818 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12819 return null; 12820 } catch (IOException ioe) { 12821 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12822 return null; 12823 } 12824 } 12825 12826 /* 12827 * Update media status on PackageManager. 12828 */ 12829 @Override 12830 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12831 int callingUid = Binder.getCallingUid(); 12832 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12833 throw new SecurityException("Media status can only be updated by the system"); 12834 } 12835 // reader; this apparently protects mMediaMounted, but should probably 12836 // be a different lock in that case. 12837 synchronized (mPackages) { 12838 Log.i(TAG, "Updating external media status from " 12839 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12840 + (mediaStatus ? "mounted" : "unmounted")); 12841 if (DEBUG_SD_INSTALL) 12842 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12843 + ", mMediaMounted=" + mMediaMounted); 12844 if (mediaStatus == mMediaMounted) { 12845 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12846 : 0, -1); 12847 mHandler.sendMessage(msg); 12848 return; 12849 } 12850 mMediaMounted = mediaStatus; 12851 } 12852 // Queue up an async operation since the package installation may take a 12853 // little while. 12854 mHandler.post(new Runnable() { 12855 public void run() { 12856 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12857 } 12858 }); 12859 } 12860 12861 /** 12862 * Called by MountService when the initial ASECs to scan are available. 12863 * Should block until all the ASEC containers are finished being scanned. 12864 */ 12865 public void scanAvailableAsecs() { 12866 updateExternalMediaStatusInner(true, false, false); 12867 if (mShouldRestoreconData) { 12868 SELinuxMMAC.setRestoreconDone(); 12869 mShouldRestoreconData = false; 12870 } 12871 } 12872 12873 /* 12874 * Collect information of applications on external media, map them against 12875 * existing containers and update information based on current mount status. 12876 * Please note that we always have to report status if reportStatus has been 12877 * set to true especially when unloading packages. 12878 */ 12879 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12880 boolean externalStorage) { 12881 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12882 int[] uidArr = EmptyArray.INT; 12883 12884 final String[] list = PackageHelper.getSecureContainerList(); 12885 if (ArrayUtils.isEmpty(list)) { 12886 Log.i(TAG, "No secure containers found"); 12887 } else { 12888 // Process list of secure containers and categorize them 12889 // as active or stale based on their package internal state. 12890 12891 // reader 12892 synchronized (mPackages) { 12893 for (String cid : list) { 12894 // Leave stages untouched for now; installer service owns them 12895 if (PackageInstallerService.isStageName(cid)) continue; 12896 12897 if (DEBUG_SD_INSTALL) 12898 Log.i(TAG, "Processing container " + cid); 12899 String pkgName = getAsecPackageName(cid); 12900 if (pkgName == null) { 12901 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12902 continue; 12903 } 12904 if (DEBUG_SD_INSTALL) 12905 Log.i(TAG, "Looking for pkg : " + pkgName); 12906 12907 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12908 if (ps == null) { 12909 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12910 continue; 12911 } 12912 12913 /* 12914 * Skip packages that are not external if we're unmounting 12915 * external storage. 12916 */ 12917 if (externalStorage && !isMounted && !isExternal(ps)) { 12918 continue; 12919 } 12920 12921 final AsecInstallArgs args = new AsecInstallArgs(cid, 12922 getAppDexInstructionSets(ps), ps.isForwardLocked()); 12923 // The package status is changed only if the code path 12924 // matches between settings and the container id. 12925 if (ps.codePathString != null 12926 && ps.codePathString.startsWith(args.getCodePath())) { 12927 if (DEBUG_SD_INSTALL) { 12928 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12929 + " at code path: " + ps.codePathString); 12930 } 12931 12932 // We do have a valid package installed on sdcard 12933 processCids.put(args, ps.codePathString); 12934 final int uid = ps.appId; 12935 if (uid != -1) { 12936 uidArr = ArrayUtils.appendInt(uidArr, uid); 12937 } 12938 } else { 12939 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12940 + ps.codePathString); 12941 } 12942 } 12943 } 12944 12945 Arrays.sort(uidArr); 12946 } 12947 12948 // Process packages with valid entries. 12949 if (isMounted) { 12950 if (DEBUG_SD_INSTALL) 12951 Log.i(TAG, "Loading packages"); 12952 loadMediaPackages(processCids, uidArr); 12953 startCleaningPackages(); 12954 mInstallerService.onSecureContainersAvailable(); 12955 } else { 12956 if (DEBUG_SD_INSTALL) 12957 Log.i(TAG, "Unloading packages"); 12958 unloadMediaPackages(processCids, uidArr, reportStatus); 12959 } 12960 } 12961 12962 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12963 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12964 int size = pkgList.size(); 12965 if (size > 0) { 12966 // Send broadcasts here 12967 Bundle extras = new Bundle(); 12968 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12969 .toArray(new String[size])); 12970 if (uidArr != null) { 12971 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12972 } 12973 if (replacing) { 12974 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12975 } 12976 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12977 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12978 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12979 } 12980 } 12981 12982 /* 12983 * Look at potentially valid container ids from processCids If package 12984 * information doesn't match the one on record or package scanning fails, 12985 * the cid is added to list of removeCids. We currently don't delete stale 12986 * containers. 12987 */ 12988 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12989 ArrayList<String> pkgList = new ArrayList<String>(); 12990 Set<AsecInstallArgs> keys = processCids.keySet(); 12991 12992 for (AsecInstallArgs args : keys) { 12993 String codePath = processCids.get(args); 12994 if (DEBUG_SD_INSTALL) 12995 Log.i(TAG, "Loading container : " + args.cid); 12996 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12997 try { 12998 // Make sure there are no container errors first. 12999 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 13000 Slog.e(TAG, "Failed to mount cid : " + args.cid 13001 + " when installing from sdcard"); 13002 continue; 13003 } 13004 // Check code path here. 13005 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 13006 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 13007 + " does not match one in settings " + codePath); 13008 continue; 13009 } 13010 // Parse package 13011 int parseFlags = mDefParseFlags; 13012 if (args.isExternal()) { 13013 parseFlags |= PackageParser.PARSE_ON_SDCARD; 13014 } 13015 if (args.isFwdLocked()) { 13016 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13017 } 13018 13019 synchronized (mInstallLock) { 13020 PackageParser.Package pkg = null; 13021 try { 13022 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13023 } catch (PackageManagerException e) { 13024 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 13025 } 13026 // Scan the package 13027 if (pkg != null) { 13028 /* 13029 * TODO why is the lock being held? doPostInstall is 13030 * called in other places without the lock. This needs 13031 * to be straightened out. 13032 */ 13033 // writer 13034 synchronized (mPackages) { 13035 retCode = PackageManager.INSTALL_SUCCEEDED; 13036 pkgList.add(pkg.packageName); 13037 // Post process args 13038 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 13039 pkg.applicationInfo.uid); 13040 } 13041 } else { 13042 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13043 } 13044 } 13045 13046 } finally { 13047 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13048 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13049 } 13050 } 13051 } 13052 // writer 13053 synchronized (mPackages) { 13054 // If the platform SDK has changed since the last time we booted, 13055 // we need to re-grant app permission to catch any new ones that 13056 // appear. This is really a hack, and means that apps can in some 13057 // cases get permissions that the user didn't initially explicitly 13058 // allow... it would be nice to have some better way to handle 13059 // this situation. 13060 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13061 if (regrantPermissions) 13062 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13063 + mSdkVersion + "; regranting permissions for external storage"); 13064 mSettings.mExternalSdkPlatform = mSdkVersion; 13065 13066 // Make sure group IDs have been assigned, and any permission 13067 // changes in other apps are accounted for 13068 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13069 | (regrantPermissions 13070 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13071 : 0)); 13072 13073 mSettings.updateExternalDatabaseVersion(); 13074 13075 // can downgrade to reader 13076 // Persist settings 13077 mSettings.writeLPr(); 13078 } 13079 // Send a broadcast to let everyone know we are done processing 13080 if (pkgList.size() > 0) { 13081 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13082 } 13083 } 13084 13085 /* 13086 * Utility method to unload a list of specified containers 13087 */ 13088 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13089 // Just unmount all valid containers. 13090 for (AsecInstallArgs arg : cidArgs) { 13091 synchronized (mInstallLock) { 13092 arg.doPostDeleteLI(false); 13093 } 13094 } 13095 } 13096 13097 /* 13098 * Unload packages mounted on external media. This involves deleting package 13099 * data from internal structures, sending broadcasts about diabled packages, 13100 * gc'ing to free up references, unmounting all secure containers 13101 * corresponding to packages on external media, and posting a 13102 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 13103 * that we always have to post this message if status has been requested no 13104 * matter what. 13105 */ 13106 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 13107 final boolean reportStatus) { 13108 if (DEBUG_SD_INSTALL) 13109 Log.i(TAG, "unloading media packages"); 13110 ArrayList<String> pkgList = new ArrayList<String>(); 13111 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 13112 final Set<AsecInstallArgs> keys = processCids.keySet(); 13113 for (AsecInstallArgs args : keys) { 13114 String pkgName = args.getPackageName(); 13115 if (DEBUG_SD_INSTALL) 13116 Log.i(TAG, "Trying to unload pkg : " + pkgName); 13117 // Delete package internally 13118 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13119 synchronized (mInstallLock) { 13120 boolean res = deletePackageLI(pkgName, null, false, null, null, 13121 PackageManager.DELETE_KEEP_DATA, outInfo, false); 13122 if (res) { 13123 pkgList.add(pkgName); 13124 } else { 13125 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13126 failedList.add(args); 13127 } 13128 } 13129 } 13130 13131 // reader 13132 synchronized (mPackages) { 13133 // We didn't update the settings after removing each package; 13134 // write them now for all packages. 13135 mSettings.writeLPr(); 13136 } 13137 13138 // We have to absolutely send UPDATED_MEDIA_STATUS only 13139 // after confirming that all the receivers processed the ordered 13140 // broadcast when packages get disabled, force a gc to clean things up. 13141 // and unload all the containers. 13142 if (pkgList.size() > 0) { 13143 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13144 new IIntentReceiver.Stub() { 13145 public void performReceive(Intent intent, int resultCode, String data, 13146 Bundle extras, boolean ordered, boolean sticky, 13147 int sendingUser) throws RemoteException { 13148 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13149 reportStatus ? 1 : 0, 1, keys); 13150 mHandler.sendMessage(msg); 13151 } 13152 }); 13153 } else { 13154 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13155 keys); 13156 mHandler.sendMessage(msg); 13157 } 13158 } 13159 13160 /** Binder call */ 13161 @Override 13162 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13163 final int flags) { 13164 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13165 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13166 int returnCode = PackageManager.MOVE_SUCCEEDED; 13167 int currInstallFlags = 0; 13168 int newInstallFlags = 0; 13169 13170 File codeFile = null; 13171 String installerPackageName = null; 13172 String packageAbiOverride = null; 13173 13174 // reader 13175 synchronized (mPackages) { 13176 final PackageParser.Package pkg = mPackages.get(packageName); 13177 final PackageSetting ps = mSettings.mPackages.get(packageName); 13178 if (pkg == null || ps == null) { 13179 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13180 } else { 13181 // Disable moving fwd locked apps and system packages 13182 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13183 Slog.w(TAG, "Cannot move system application"); 13184 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13185 } else if (pkg.mOperationPending) { 13186 Slog.w(TAG, "Attempt to move package which has pending operations"); 13187 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13188 } else { 13189 // Find install location first 13190 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13191 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13192 Slog.w(TAG, "Ambigous flags specified for move location."); 13193 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13194 } else { 13195 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13196 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13197 currInstallFlags = isExternal(pkg) 13198 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13199 13200 if (newInstallFlags == currInstallFlags) { 13201 Slog.w(TAG, "No move required. Trying to move to same location"); 13202 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13203 } else { 13204 if (pkg.isForwardLocked()) { 13205 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13206 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13207 } 13208 } 13209 } 13210 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13211 pkg.mOperationPending = true; 13212 } 13213 } 13214 13215 codeFile = new File(pkg.codePath); 13216 installerPackageName = ps.installerPackageName; 13217 packageAbiOverride = ps.cpuAbiOverrideString; 13218 } 13219 } 13220 13221 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13222 try { 13223 observer.packageMoved(packageName, returnCode); 13224 } catch (RemoteException ignored) { 13225 } 13226 return; 13227 } 13228 13229 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13230 @Override 13231 public void onUserActionRequired(Intent intent) throws RemoteException { 13232 throw new IllegalStateException(); 13233 } 13234 13235 @Override 13236 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13237 Bundle extras) throws RemoteException { 13238 Slog.d(TAG, "Install result for move: " 13239 + PackageManager.installStatusToString(returnCode, msg)); 13240 13241 // We usually have a new package now after the install, but if 13242 // we failed we need to clear the pending flag on the original 13243 // package object. 13244 synchronized (mPackages) { 13245 final PackageParser.Package pkg = mPackages.get(packageName); 13246 if (pkg != null) { 13247 pkg.mOperationPending = false; 13248 } 13249 } 13250 13251 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13252 switch (status) { 13253 case PackageInstaller.STATUS_SUCCESS: 13254 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13255 break; 13256 case PackageInstaller.STATUS_FAILURE_STORAGE: 13257 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13258 break; 13259 default: 13260 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13261 break; 13262 } 13263 } 13264 }; 13265 13266 // Treat a move like reinstalling an existing app, which ensures that we 13267 // process everythign uniformly, like unpacking native libraries. 13268 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13269 13270 final Message msg = mHandler.obtainMessage(INIT_COPY); 13271 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13272 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13273 installerPackageName, null, user, packageAbiOverride); 13274 mHandler.sendMessage(msg); 13275 } 13276 13277 @Override 13278 public boolean setInstallLocation(int loc) { 13279 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13280 null); 13281 if (getInstallLocation() == loc) { 13282 return true; 13283 } 13284 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13285 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13286 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13287 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13288 return true; 13289 } 13290 return false; 13291 } 13292 13293 @Override 13294 public int getInstallLocation() { 13295 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13296 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13297 PackageHelper.APP_INSTALL_AUTO); 13298 } 13299 13300 /** Called by UserManagerService */ 13301 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13302 mDirtyUsers.remove(userHandle); 13303 mSettings.removeUserLPw(userHandle); 13304 mPendingBroadcasts.remove(userHandle); 13305 if (mInstaller != null) { 13306 // Technically, we shouldn't be doing this with the package lock 13307 // held. However, this is very rare, and there is already so much 13308 // other disk I/O going on, that we'll let it slide for now. 13309 mInstaller.removeUserDataDirs(userHandle); 13310 } 13311 mUserNeedsBadging.delete(userHandle); 13312 removeUnusedPackagesLILPw(userManager, userHandle); 13313 } 13314 13315 /** 13316 * We're removing userHandle and would like to remove any downloaded packages 13317 * that are no longer in use by any other user. 13318 * @param userHandle the user being removed 13319 */ 13320 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13321 final boolean DEBUG_CLEAN_APKS = false; 13322 int [] users = userManager.getUserIdsLPr(); 13323 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13324 while (psit.hasNext()) { 13325 PackageSetting ps = psit.next(); 13326 if (ps.pkg == null) { 13327 continue; 13328 } 13329 final String packageName = ps.pkg.packageName; 13330 // Skip over if system app 13331 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13332 continue; 13333 } 13334 if (DEBUG_CLEAN_APKS) { 13335 Slog.i(TAG, "Checking package " + packageName); 13336 } 13337 boolean keep = false; 13338 for (int i = 0; i < users.length; i++) { 13339 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13340 keep = true; 13341 if (DEBUG_CLEAN_APKS) { 13342 Slog.i(TAG, " Keeping package " + packageName + " for user " 13343 + users[i]); 13344 } 13345 break; 13346 } 13347 } 13348 if (!keep) { 13349 if (DEBUG_CLEAN_APKS) { 13350 Slog.i(TAG, " Removing package " + packageName); 13351 } 13352 mHandler.post(new Runnable() { 13353 public void run() { 13354 deletePackageX(packageName, userHandle, 0); 13355 } //end run 13356 }); 13357 } 13358 } 13359 } 13360 13361 /** Called by UserManagerService */ 13362 void createNewUserLILPw(int userHandle, File path) { 13363 if (mInstaller != null) { 13364 mInstaller.createUserConfig(userHandle); 13365 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13366 } 13367 } 13368 13369 @Override 13370 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13371 mContext.enforceCallingOrSelfPermission( 13372 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13373 "Only package verification agents can read the verifier device identity"); 13374 13375 synchronized (mPackages) { 13376 return mSettings.getVerifierDeviceIdentityLPw(); 13377 } 13378 } 13379 13380 @Override 13381 public void setPermissionEnforced(String permission, boolean enforced) { 13382 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13383 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13384 synchronized (mPackages) { 13385 if (mSettings.mReadExternalStorageEnforced == null 13386 || mSettings.mReadExternalStorageEnforced != enforced) { 13387 mSettings.mReadExternalStorageEnforced = enforced; 13388 mSettings.writeLPr(); 13389 } 13390 } 13391 // kill any non-foreground processes so we restart them and 13392 // grant/revoke the GID. 13393 final IActivityManager am = ActivityManagerNative.getDefault(); 13394 if (am != null) { 13395 final long token = Binder.clearCallingIdentity(); 13396 try { 13397 am.killProcessesBelowForeground("setPermissionEnforcement"); 13398 } catch (RemoteException e) { 13399 } finally { 13400 Binder.restoreCallingIdentity(token); 13401 } 13402 } 13403 } else { 13404 throw new IllegalArgumentException("No selective enforcement for " + permission); 13405 } 13406 } 13407 13408 @Override 13409 @Deprecated 13410 public boolean isPermissionEnforced(String permission) { 13411 return true; 13412 } 13413 13414 @Override 13415 public boolean isStorageLow() { 13416 final long token = Binder.clearCallingIdentity(); 13417 try { 13418 final DeviceStorageMonitorInternal 13419 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13420 if (dsm != null) { 13421 return dsm.isMemoryLow(); 13422 } else { 13423 return false; 13424 } 13425 } finally { 13426 Binder.restoreCallingIdentity(token); 13427 } 13428 } 13429 13430 @Override 13431 public IPackageInstaller getPackageInstaller() { 13432 return mInstallerService; 13433 } 13434 13435 private boolean userNeedsBadging(int userId) { 13436 int index = mUserNeedsBadging.indexOfKey(userId); 13437 if (index < 0) { 13438 final UserInfo userInfo; 13439 final long token = Binder.clearCallingIdentity(); 13440 try { 13441 userInfo = sUserManager.getUserInfo(userId); 13442 } finally { 13443 Binder.restoreCallingIdentity(token); 13444 } 13445 final boolean b; 13446 if (userInfo != null && userInfo.isManagedProfile()) { 13447 b = true; 13448 } else { 13449 b = false; 13450 } 13451 mUserNeedsBadging.put(userId, b); 13452 return b; 13453 } 13454 return mUserNeedsBadging.valueAt(index); 13455 } 13456 13457 @Override 13458 public KeySet getKeySetByAlias(String packageName, String alias) { 13459 if (packageName == null || alias == null) { 13460 return null; 13461 } 13462 synchronized(mPackages) { 13463 final PackageParser.Package pkg = mPackages.get(packageName); 13464 if (pkg == null) { 13465 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13466 throw new IllegalArgumentException("Unknown package: " + packageName); 13467 } 13468 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13469 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13470 } 13471 } 13472 13473 @Override 13474 public KeySet getSigningKeySet(String packageName) { 13475 if (packageName == null) { 13476 return null; 13477 } 13478 synchronized(mPackages) { 13479 final PackageParser.Package pkg = mPackages.get(packageName); 13480 if (pkg == null) { 13481 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13482 throw new IllegalArgumentException("Unknown package: " + packageName); 13483 } 13484 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13485 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13486 throw new SecurityException("May not access signing KeySet of other apps."); 13487 } 13488 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13489 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13490 } 13491 } 13492 13493 @Override 13494 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13495 if (packageName == null || ks == null) { 13496 return false; 13497 } 13498 synchronized(mPackages) { 13499 final PackageParser.Package pkg = mPackages.get(packageName); 13500 if (pkg == null) { 13501 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13502 throw new IllegalArgumentException("Unknown package: " + packageName); 13503 } 13504 IBinder ksh = ks.getToken(); 13505 if (ksh instanceof KeySetHandle) { 13506 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13507 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13508 } 13509 return false; 13510 } 13511 } 13512 13513 @Override 13514 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13515 if (packageName == null || ks == null) { 13516 return false; 13517 } 13518 synchronized(mPackages) { 13519 final PackageParser.Package pkg = mPackages.get(packageName); 13520 if (pkg == null) { 13521 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13522 throw new IllegalArgumentException("Unknown package: " + packageName); 13523 } 13524 IBinder ksh = ks.getToken(); 13525 if (ksh instanceof KeySetHandle) { 13526 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13527 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13528 } 13529 return false; 13530 } 13531 } 13532 13533 public void getUsageStatsIfNoPackageUsageInfo() { 13534 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 13535 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 13536 if (usm == null) { 13537 throw new IllegalStateException("UsageStatsManager must be initialized"); 13538 } 13539 long now = System.currentTimeMillis(); 13540 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 13541 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 13542 String packageName = entry.getKey(); 13543 PackageParser.Package pkg = mPackages.get(packageName); 13544 if (pkg == null) { 13545 continue; 13546 } 13547 UsageStats usage = entry.getValue(); 13548 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 13549 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 13550 } 13551 } 13552 } 13553 13554 /** 13555 * Check and throw if the given before/after packages would be considered a 13556 * downgrade. 13557 */ 13558 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 13559 throws PackageManagerException { 13560 if (after.versionCode < before.mVersionCode) { 13561 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13562 "Update version code " + after.versionCode + " is older than current " 13563 + before.mVersionCode); 13564 } else if (after.versionCode == before.mVersionCode) { 13565 if (after.baseRevisionCode < before.baseRevisionCode) { 13566 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13567 "Update base revision code " + after.baseRevisionCode 13568 + " is older than current " + before.baseRevisionCode); 13569 } 13570 13571 if (!ArrayUtils.isEmpty(after.splitNames)) { 13572 for (int i = 0; i < after.splitNames.length; i++) { 13573 final String splitName = after.splitNames[i]; 13574 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 13575 if (j != -1) { 13576 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 13577 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13578 "Update split " + splitName + " revision code " 13579 + after.splitRevisionCodes[i] + " is older than current " 13580 + before.splitRevisionCodes[j]); 13581 } 13582 } 13583 } 13584 } 13585 } 13586 } 13587} 13588