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