PackageManagerService.java revision fa54ab7950b7ad7605cb842b47826b71a685bc28
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 47import static android.content.pm.PackageParser.isApkFile; 48import static android.os.Process.PACKAGE_INFO_GID; 49import static android.os.Process.SYSTEM_UID; 50import static android.system.OsConstants.O_CREAT; 51import static android.system.OsConstants.O_RDWR; 52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 53import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 54import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 55import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 56import static com.android.internal.util.ArrayUtils.appendInt; 57import static com.android.internal.util.ArrayUtils.removeInt; 58import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 59import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 60import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 61import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 62import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 63import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 64 65import android.util.ArrayMap; 66 67import com.android.internal.R; 68import com.android.internal.app.IMediaContainerService; 69import com.android.internal.app.ResolverActivity; 70import com.android.internal.content.NativeLibraryHelper; 71import com.android.internal.content.PackageHelper; 72import com.android.internal.os.IParcelFileDescriptorFactory; 73import com.android.internal.util.ArrayUtils; 74import com.android.internal.util.FastPrintWriter; 75import com.android.internal.util.FastXmlSerializer; 76import com.android.internal.util.IndentingPrintWriter; 77import com.android.server.EventLogTags; 78import com.android.server.IntentResolver; 79import com.android.server.LocalServices; 80import com.android.server.ServiceThread; 81import com.android.server.SystemConfig; 82import com.android.server.Watchdog; 83import com.android.server.pm.Settings.DatabaseVersion; 84import com.android.server.storage.DeviceStorageMonitorInternal; 85 86import org.xmlpull.v1.XmlSerializer; 87 88import android.app.ActivityManager; 89import android.app.ActivityManagerNative; 90import android.app.AppGlobals; 91import android.app.IActivityManager; 92import android.app.admin.IDevicePolicyManager; 93import android.app.backup.IBackupManager; 94import android.app.usage.UsageStats; 95import android.app.usage.UsageStatsManager; 96import android.content.BroadcastReceiver; 97import android.content.ComponentName; 98import android.content.Context; 99import android.content.IIntentReceiver; 100import android.content.Intent; 101import android.content.IntentFilter; 102import android.content.IntentSender; 103import android.content.IntentSender.SendIntentException; 104import android.content.ServiceConnection; 105import android.content.pm.ActivityInfo; 106import android.content.pm.ApplicationInfo; 107import android.content.pm.FeatureInfo; 108import android.content.pm.IPackageDataObserver; 109import android.content.pm.IPackageDeleteObserver; 110import android.content.pm.IPackageDeleteObserver2; 111import android.content.pm.IPackageInstallObserver2; 112import android.content.pm.IPackageInstaller; 113import android.content.pm.IPackageManager; 114import android.content.pm.IPackageMoveObserver; 115import android.content.pm.IPackageStatsObserver; 116import android.content.pm.InstrumentationInfo; 117import android.content.pm.KeySet; 118import android.content.pm.ManifestDigest; 119import android.content.pm.PackageCleanItem; 120import android.content.pm.PackageInfo; 121import android.content.pm.PackageInfoLite; 122import android.content.pm.PackageInstaller; 123import android.content.pm.PackageManager; 124import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 125import android.content.pm.PackageParser.ActivityIntentInfo; 126import android.content.pm.PackageParser.PackageLite; 127import android.content.pm.PackageParser.PackageParserException; 128import android.content.pm.PackageParser; 129import android.content.pm.PackageStats; 130import android.content.pm.PackageUserState; 131import android.content.pm.ParceledListSlice; 132import android.content.pm.PermissionGroupInfo; 133import android.content.pm.PermissionInfo; 134import android.content.pm.ProviderInfo; 135import android.content.pm.ResolveInfo; 136import android.content.pm.ServiceInfo; 137import android.content.pm.Signature; 138import android.content.pm.UserInfo; 139import android.content.pm.VerificationParams; 140import android.content.pm.VerifierDeviceIdentity; 141import android.content.pm.VerifierInfo; 142import android.content.res.Resources; 143import android.hardware.display.DisplayManager; 144import android.net.Uri; 145import android.os.Binder; 146import android.os.Build; 147import android.os.Bundle; 148import android.os.Environment; 149import android.os.Environment.UserEnvironment; 150import android.os.storage.IMountService; 151import android.os.storage.StorageManager; 152import android.os.Debug; 153import android.os.FileUtils; 154import android.os.Handler; 155import android.os.IBinder; 156import android.os.Looper; 157import android.os.Message; 158import android.os.Parcel; 159import android.os.ParcelFileDescriptor; 160import android.os.Process; 161import android.os.RemoteException; 162import android.os.SELinux; 163import android.os.ServiceManager; 164import android.os.SystemClock; 165import android.os.SystemProperties; 166import android.os.UserHandle; 167import android.os.UserManager; 168import android.security.KeyStore; 169import android.security.SystemKeyStore; 170import android.system.ErrnoException; 171import android.system.Os; 172import android.system.StructStat; 173import android.text.TextUtils; 174import android.text.format.DateUtils; 175import android.util.ArraySet; 176import android.util.AtomicFile; 177import android.util.DisplayMetrics; 178import android.util.EventLog; 179import android.util.ExceptionUtils; 180import android.util.Log; 181import android.util.LogPrinter; 182import android.util.PrintStreamPrinter; 183import android.util.Slog; 184import android.util.SparseArray; 185import android.util.SparseBooleanArray; 186import android.view.Display; 187 188import java.io.BufferedInputStream; 189import java.io.BufferedOutputStream; 190import java.io.BufferedReader; 191import java.io.File; 192import java.io.FileDescriptor; 193import java.io.FileNotFoundException; 194import java.io.FileOutputStream; 195import java.io.FileReader; 196import java.io.FilenameFilter; 197import java.io.IOException; 198import java.io.InputStream; 199import java.io.PrintWriter; 200import java.nio.charset.StandardCharsets; 201import java.security.NoSuchAlgorithmException; 202import java.security.PublicKey; 203import java.security.cert.CertificateEncodingException; 204import java.security.cert.CertificateException; 205import java.text.SimpleDateFormat; 206import java.util.ArrayList; 207import java.util.Arrays; 208import java.util.Collection; 209import java.util.Collections; 210import java.util.Comparator; 211import java.util.Date; 212import java.util.Iterator; 213import java.util.List; 214import java.util.Map; 215import java.util.Objects; 216import java.util.Set; 217import java.util.concurrent.atomic.AtomicBoolean; 218import java.util.concurrent.atomic.AtomicLong; 219 220import dalvik.system.DexFile; 221import dalvik.system.VMRuntime; 222 223import libcore.io.IoUtils; 224import libcore.util.EmptyArray; 225 226/** 227 * Keep track of all those .apks everywhere. 228 * 229 * This is very central to the platform's security; please run the unit 230 * tests whenever making modifications here: 231 * 232mmm frameworks/base/tests/AndroidTests 233adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 234adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 235 * 236 * {@hide} 237 */ 238public class PackageManagerService extends IPackageManager.Stub { 239 static final String TAG = "PackageManager"; 240 static final boolean DEBUG_SETTINGS = false; 241 static final boolean DEBUG_PREFERRED = false; 242 static final boolean DEBUG_UPGRADE = false; 243 private static final boolean DEBUG_INSTALL = false; 244 private static final boolean DEBUG_REMOVE = false; 245 private static final boolean DEBUG_BROADCASTS = false; 246 private static final boolean DEBUG_SHOW_INFO = false; 247 private static final boolean DEBUG_PACKAGE_INFO = false; 248 private static final boolean DEBUG_INTENT_MATCHING = false; 249 private static final boolean DEBUG_PACKAGE_SCANNING = false; 250 private static final boolean DEBUG_VERIFY = false; 251 private static final boolean DEBUG_DEXOPT = false; 252 private static final boolean DEBUG_ABI_SELECTION = false; 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 PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 327 328 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 329 330 final ServiceThread mHandlerThread; 331 332 final PackageHandler mHandler; 333 334 /** 335 * Messages for {@link #mHandler} that need to wait for system ready before 336 * being dispatched. 337 */ 338 private ArrayList<Message> mPostSystemReadyMessages; 339 340 final int mSdkVersion = Build.VERSION.SDK_INT; 341 342 final Context mContext; 343 final boolean mFactoryTest; 344 final boolean mOnlyCore; 345 final boolean mLazyDexOpt; 346 final long mDexOptLRUThresholdInMills; 347 final DisplayMetrics mMetrics; 348 final int mDefParseFlags; 349 final String[] mSeparateProcesses; 350 final boolean mIsUpgrade; 351 352 // This is where all application persistent data goes. 353 final File mAppDataDir; 354 355 // This is where all application persistent data goes for secondary users. 356 final File mUserAppDataDir; 357 358 /** The location for ASEC container files on internal storage. */ 359 final String mAsecInternalPath; 360 361 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 362 // LOCK HELD. Can be called with mInstallLock held. 363 final Installer mInstaller; 364 365 /** Directory where installed third-party apps stored */ 366 final File mAppInstallDir; 367 368 /** 369 * Directory to which applications installed internally have their 370 * 32 bit native libraries copied. 371 */ 372 private File mAppLib32InstallDir; 373 374 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 375 // apps. 376 final File mDrmAppPrivateInstallDir; 377 378 // ---------------------------------------------------------------- 379 380 // Lock for state used when installing and doing other long running 381 // operations. Methods that must be called with this lock held have 382 // the suffix "LI". 383 final Object mInstallLock = new Object(); 384 385 // ---------------------------------------------------------------- 386 387 // Keys are String (package name), values are Package. This also serves 388 // as the lock for the global state. Methods that must be called with 389 // this lock held have the prefix "LP". 390 final ArrayMap<String, PackageParser.Package> mPackages = 391 new ArrayMap<String, PackageParser.Package>(); 392 393 // Tracks available target package names -> overlay package paths. 394 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 395 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 396 397 final Settings mSettings; 398 boolean mRestoredSettings; 399 400 // System configuration read by SystemConfig. 401 final int[] mGlobalGids; 402 final SparseArray<ArraySet<String>> mSystemPermissions; 403 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 404 405 // If mac_permissions.xml was found for seinfo labeling. 406 boolean mFoundPolicyFile; 407 408 // If a recursive restorecon of /data/data/<pkg> is needed. 409 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 410 411 public static final class SharedLibraryEntry { 412 public final String path; 413 public final String apk; 414 415 SharedLibraryEntry(String _path, String _apk) { 416 path = _path; 417 apk = _apk; 418 } 419 } 420 421 // Currently known shared libraries. 422 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 423 new ArrayMap<String, SharedLibraryEntry>(); 424 425 // All available activities, for your resolving pleasure. 426 final ActivityIntentResolver mActivities = 427 new ActivityIntentResolver(); 428 429 // All available receivers, for your resolving pleasure. 430 final ActivityIntentResolver mReceivers = 431 new ActivityIntentResolver(); 432 433 // All available services, for your resolving pleasure. 434 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 435 436 // All available providers, for your resolving pleasure. 437 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 438 439 // Mapping from provider base names (first directory in content URI codePath) 440 // to the provider information. 441 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 442 new ArrayMap<String, PackageParser.Provider>(); 443 444 // Mapping from instrumentation class names to info about them. 445 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 446 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 447 448 // Mapping from permission names to info about them. 449 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 450 new ArrayMap<String, PackageParser.PermissionGroup>(); 451 452 // Packages whose data we have transfered into another package, thus 453 // should no longer exist. 454 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 455 456 // Broadcast actions that are only available to the system. 457 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 458 459 /** List of packages waiting for verification. */ 460 final SparseArray<PackageVerificationState> mPendingVerification 461 = new SparseArray<PackageVerificationState>(); 462 463 /** Set of packages associated with each app op permission. */ 464 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 465 466 final PackageInstallerService mInstallerService; 467 468 private final PackageDexOptimizer mPackageDexOptimizer; 469 // Cache of users who need badging. 470 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 471 472 /** Token for keys in mPendingVerification. */ 473 private int mPendingVerificationToken = 0; 474 475 volatile boolean mSystemReady; 476 volatile boolean mSafeMode; 477 volatile boolean mHasSystemUidErrors; 478 479 ApplicationInfo mAndroidApplication; 480 final ActivityInfo mResolveActivity = new ActivityInfo(); 481 final ResolveInfo mResolveInfo = new ResolveInfo(); 482 ComponentName mResolveComponentName; 483 PackageParser.Package mPlatformPackage; 484 ComponentName mCustomResolverComponentName; 485 486 boolean mResolverReplaced = false; 487 488 // Set of pending broadcasts for aggregating enable/disable of components. 489 static class PendingPackageBroadcasts { 490 // for each user id, a map of <package name -> components within that package> 491 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 492 493 public PendingPackageBroadcasts() { 494 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 495 } 496 497 public ArrayList<String> get(int userId, String packageName) { 498 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 499 return packages.get(packageName); 500 } 501 502 public void put(int userId, String packageName, ArrayList<String> components) { 503 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 504 packages.put(packageName, components); 505 } 506 507 public void remove(int userId, String packageName) { 508 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 509 if (packages != null) { 510 packages.remove(packageName); 511 } 512 } 513 514 public void remove(int userId) { 515 mUidMap.remove(userId); 516 } 517 518 public int userIdCount() { 519 return mUidMap.size(); 520 } 521 522 public int userIdAt(int n) { 523 return mUidMap.keyAt(n); 524 } 525 526 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 527 return mUidMap.get(userId); 528 } 529 530 public int size() { 531 // total number of pending broadcast entries across all userIds 532 int num = 0; 533 for (int i = 0; i< mUidMap.size(); i++) { 534 num += mUidMap.valueAt(i).size(); 535 } 536 return num; 537 } 538 539 public void clear() { 540 mUidMap.clear(); 541 } 542 543 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 544 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 545 if (map == null) { 546 map = new ArrayMap<String, ArrayList<String>>(); 547 mUidMap.put(userId, map); 548 } 549 return map; 550 } 551 } 552 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 553 554 // Service Connection to remote media container service to copy 555 // package uri's from external media onto secure containers 556 // or internal storage. 557 private IMediaContainerService mContainerService = null; 558 559 static final int SEND_PENDING_BROADCAST = 1; 560 static final int MCS_BOUND = 3; 561 static final int END_COPY = 4; 562 static final int INIT_COPY = 5; 563 static final int MCS_UNBIND = 6; 564 static final int START_CLEANING_PACKAGE = 7; 565 static final int FIND_INSTALL_LOC = 8; 566 static final int POST_INSTALL = 9; 567 static final int MCS_RECONNECT = 10; 568 static final int MCS_GIVE_UP = 11; 569 static final int UPDATED_MEDIA_STATUS = 12; 570 static final int WRITE_SETTINGS = 13; 571 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 572 static final int PACKAGE_VERIFIED = 15; 573 static final int CHECK_PENDING_VERIFICATION = 16; 574 575 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 576 577 // Delay time in millisecs 578 static final int BROADCAST_DELAY = 10 * 1000; 579 580 static UserManagerService sUserManager; 581 582 // Stores a list of users whose package restrictions file needs to be updated 583 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 584 585 final private DefaultContainerConnection mDefContainerConn = 586 new DefaultContainerConnection(); 587 class DefaultContainerConnection implements ServiceConnection { 588 public void onServiceConnected(ComponentName name, IBinder service) { 589 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 590 IMediaContainerService imcs = 591 IMediaContainerService.Stub.asInterface(service); 592 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 593 } 594 595 public void onServiceDisconnected(ComponentName name) { 596 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 597 } 598 }; 599 600 // Recordkeeping of restore-after-install operations that are currently in flight 601 // between the Package Manager and the Backup Manager 602 class PostInstallData { 603 public InstallArgs args; 604 public PackageInstalledInfo res; 605 606 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 607 args = _a; 608 res = _r; 609 } 610 }; 611 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 612 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 613 614 private final String mRequiredVerifierPackage; 615 616 private final PackageUsage mPackageUsage = new PackageUsage(); 617 618 private class PackageUsage { 619 private static final int WRITE_INTERVAL 620 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 621 622 private final Object mFileLock = new Object(); 623 private final AtomicLong mLastWritten = new AtomicLong(0); 624 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 625 626 private boolean mIsHistoricalPackageUsageAvailable = true; 627 628 boolean isHistoricalPackageUsageAvailable() { 629 return mIsHistoricalPackageUsageAvailable; 630 } 631 632 void write(boolean force) { 633 if (force) { 634 writeInternal(); 635 return; 636 } 637 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 638 && !DEBUG_DEXOPT) { 639 return; 640 } 641 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 642 new Thread("PackageUsage_DiskWriter") { 643 @Override 644 public void run() { 645 try { 646 writeInternal(); 647 } finally { 648 mBackgroundWriteRunning.set(false); 649 } 650 } 651 }.start(); 652 } 653 } 654 655 private void writeInternal() { 656 synchronized (mPackages) { 657 synchronized (mFileLock) { 658 AtomicFile file = getFile(); 659 FileOutputStream f = null; 660 try { 661 f = file.startWrite(); 662 BufferedOutputStream out = new BufferedOutputStream(f); 663 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 664 StringBuilder sb = new StringBuilder(); 665 for (PackageParser.Package pkg : mPackages.values()) { 666 if (pkg.mLastPackageUsageTimeInMills == 0) { 667 continue; 668 } 669 sb.setLength(0); 670 sb.append(pkg.packageName); 671 sb.append(' '); 672 sb.append((long)pkg.mLastPackageUsageTimeInMills); 673 sb.append('\n'); 674 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 675 } 676 out.flush(); 677 file.finishWrite(f); 678 } catch (IOException e) { 679 if (f != null) { 680 file.failWrite(f); 681 } 682 Log.e(TAG, "Failed to write package usage times", e); 683 } 684 } 685 } 686 mLastWritten.set(SystemClock.elapsedRealtime()); 687 } 688 689 void readLP() { 690 synchronized (mFileLock) { 691 AtomicFile file = getFile(); 692 BufferedInputStream in = null; 693 try { 694 in = new BufferedInputStream(file.openRead()); 695 StringBuffer sb = new StringBuffer(); 696 while (true) { 697 String packageName = readToken(in, sb, ' '); 698 if (packageName == null) { 699 break; 700 } 701 String timeInMillisString = readToken(in, sb, '\n'); 702 if (timeInMillisString == null) { 703 throw new IOException("Failed to find last usage time for package " 704 + packageName); 705 } 706 PackageParser.Package pkg = mPackages.get(packageName); 707 if (pkg == null) { 708 continue; 709 } 710 long timeInMillis; 711 try { 712 timeInMillis = Long.parseLong(timeInMillisString.toString()); 713 } catch (NumberFormatException e) { 714 throw new IOException("Failed to parse " + timeInMillisString 715 + " as a long.", e); 716 } 717 pkg.mLastPackageUsageTimeInMills = timeInMillis; 718 } 719 } catch (FileNotFoundException expected) { 720 mIsHistoricalPackageUsageAvailable = false; 721 } catch (IOException e) { 722 Log.w(TAG, "Failed to read package usage times", e); 723 } finally { 724 IoUtils.closeQuietly(in); 725 } 726 } 727 mLastWritten.set(SystemClock.elapsedRealtime()); 728 } 729 730 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 731 throws IOException { 732 sb.setLength(0); 733 while (true) { 734 int ch = in.read(); 735 if (ch == -1) { 736 if (sb.length() == 0) { 737 return null; 738 } 739 throw new IOException("Unexpected EOF"); 740 } 741 if (ch == endOfToken) { 742 return sb.toString(); 743 } 744 sb.append((char)ch); 745 } 746 } 747 748 private AtomicFile getFile() { 749 File dataDir = Environment.getDataDirectory(); 750 File systemDir = new File(dataDir, "system"); 751 File fname = new File(systemDir, "package-usage.list"); 752 return new AtomicFile(fname); 753 } 754 } 755 756 class PackageHandler extends Handler { 757 private boolean mBound = false; 758 final ArrayList<HandlerParams> mPendingInstalls = 759 new ArrayList<HandlerParams>(); 760 761 private boolean connectToService() { 762 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 763 " DefaultContainerService"); 764 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 765 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 766 if (mContext.bindServiceAsUser(service, mDefContainerConn, 767 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 768 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 769 mBound = true; 770 return true; 771 } 772 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 773 return false; 774 } 775 776 private void disconnectService() { 777 mContainerService = null; 778 mBound = false; 779 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 780 mContext.unbindService(mDefContainerConn); 781 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 782 } 783 784 PackageHandler(Looper looper) { 785 super(looper); 786 } 787 788 public void handleMessage(Message msg) { 789 try { 790 doHandleMessage(msg); 791 } finally { 792 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 793 } 794 } 795 796 void doHandleMessage(Message msg) { 797 switch (msg.what) { 798 case INIT_COPY: { 799 HandlerParams params = (HandlerParams) msg.obj; 800 int idx = mPendingInstalls.size(); 801 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 802 // If a bind was already initiated we dont really 803 // need to do anything. The pending install 804 // will be processed later on. 805 if (!mBound) { 806 // If this is the only one pending we might 807 // have to bind to the service again. 808 if (!connectToService()) { 809 Slog.e(TAG, "Failed to bind to media container service"); 810 params.serviceError(); 811 return; 812 } else { 813 // Once we bind to the service, the first 814 // pending request will be processed. 815 mPendingInstalls.add(idx, params); 816 } 817 } else { 818 mPendingInstalls.add(idx, params); 819 // Already bound to the service. Just make 820 // sure we trigger off processing the first request. 821 if (idx == 0) { 822 mHandler.sendEmptyMessage(MCS_BOUND); 823 } 824 } 825 break; 826 } 827 case MCS_BOUND: { 828 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 829 if (msg.obj != null) { 830 mContainerService = (IMediaContainerService) msg.obj; 831 } 832 if (mContainerService == null) { 833 // Something seriously wrong. Bail out 834 Slog.e(TAG, "Cannot bind to media container service"); 835 for (HandlerParams params : mPendingInstalls) { 836 // Indicate service bind error 837 params.serviceError(); 838 } 839 mPendingInstalls.clear(); 840 } else if (mPendingInstalls.size() > 0) { 841 HandlerParams params = mPendingInstalls.get(0); 842 if (params != null) { 843 if (params.startCopy()) { 844 // We are done... look for more work or to 845 // go idle. 846 if (DEBUG_SD_INSTALL) Log.i(TAG, 847 "Checking for more work or unbind..."); 848 // Delete pending install 849 if (mPendingInstalls.size() > 0) { 850 mPendingInstalls.remove(0); 851 } 852 if (mPendingInstalls.size() == 0) { 853 if (mBound) { 854 if (DEBUG_SD_INSTALL) Log.i(TAG, 855 "Posting delayed MCS_UNBIND"); 856 removeMessages(MCS_UNBIND); 857 Message ubmsg = obtainMessage(MCS_UNBIND); 858 // Unbind after a little delay, to avoid 859 // continual thrashing. 860 sendMessageDelayed(ubmsg, 10000); 861 } 862 } else { 863 // There are more pending requests in queue. 864 // Just post MCS_BOUND message to trigger processing 865 // of next pending install. 866 if (DEBUG_SD_INSTALL) Log.i(TAG, 867 "Posting MCS_BOUND for next work"); 868 mHandler.sendEmptyMessage(MCS_BOUND); 869 } 870 } 871 } 872 } else { 873 // Should never happen ideally. 874 Slog.w(TAG, "Empty queue"); 875 } 876 break; 877 } 878 case MCS_RECONNECT: { 879 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 880 if (mPendingInstalls.size() > 0) { 881 if (mBound) { 882 disconnectService(); 883 } 884 if (!connectToService()) { 885 Slog.e(TAG, "Failed to bind to media container service"); 886 for (HandlerParams params : mPendingInstalls) { 887 // Indicate service bind error 888 params.serviceError(); 889 } 890 mPendingInstalls.clear(); 891 } 892 } 893 break; 894 } 895 case MCS_UNBIND: { 896 // If there is no actual work left, then time to unbind. 897 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 898 899 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 900 if (mBound) { 901 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 902 903 disconnectService(); 904 } 905 } else if (mPendingInstalls.size() > 0) { 906 // There are more pending requests in queue. 907 // Just post MCS_BOUND message to trigger processing 908 // of next pending install. 909 mHandler.sendEmptyMessage(MCS_BOUND); 910 } 911 912 break; 913 } 914 case MCS_GIVE_UP: { 915 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 916 mPendingInstalls.remove(0); 917 break; 918 } 919 case SEND_PENDING_BROADCAST: { 920 String packages[]; 921 ArrayList<String> components[]; 922 int size = 0; 923 int uids[]; 924 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 925 synchronized (mPackages) { 926 if (mPendingBroadcasts == null) { 927 return; 928 } 929 size = mPendingBroadcasts.size(); 930 if (size <= 0) { 931 // Nothing to be done. Just return 932 return; 933 } 934 packages = new String[size]; 935 components = new ArrayList[size]; 936 uids = new int[size]; 937 int i = 0; // filling out the above arrays 938 939 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 940 int packageUserId = mPendingBroadcasts.userIdAt(n); 941 Iterator<Map.Entry<String, ArrayList<String>>> it 942 = mPendingBroadcasts.packagesForUserId(packageUserId) 943 .entrySet().iterator(); 944 while (it.hasNext() && i < size) { 945 Map.Entry<String, ArrayList<String>> ent = it.next(); 946 packages[i] = ent.getKey(); 947 components[i] = ent.getValue(); 948 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 949 uids[i] = (ps != null) 950 ? UserHandle.getUid(packageUserId, ps.appId) 951 : -1; 952 i++; 953 } 954 } 955 size = i; 956 mPendingBroadcasts.clear(); 957 } 958 // Send broadcasts 959 for (int i = 0; i < size; i++) { 960 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 961 } 962 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 963 break; 964 } 965 case START_CLEANING_PACKAGE: { 966 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 967 final String packageName = (String)msg.obj; 968 final int userId = msg.arg1; 969 final boolean andCode = msg.arg2 != 0; 970 synchronized (mPackages) { 971 if (userId == UserHandle.USER_ALL) { 972 int[] users = sUserManager.getUserIds(); 973 for (int user : users) { 974 mSettings.addPackageToCleanLPw( 975 new PackageCleanItem(user, packageName, andCode)); 976 } 977 } else { 978 mSettings.addPackageToCleanLPw( 979 new PackageCleanItem(userId, packageName, andCode)); 980 } 981 } 982 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 983 startCleaningPackages(); 984 } break; 985 case POST_INSTALL: { 986 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 987 PostInstallData data = mRunningInstalls.get(msg.arg1); 988 mRunningInstalls.delete(msg.arg1); 989 boolean deleteOld = false; 990 991 if (data != null) { 992 InstallArgs args = data.args; 993 PackageInstalledInfo res = data.res; 994 995 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 996 res.removedInfo.sendBroadcast(false, true, false); 997 Bundle extras = new Bundle(1); 998 extras.putInt(Intent.EXTRA_UID, res.uid); 999 // Determine the set of users who are adding this 1000 // package for the first time vs. those who are seeing 1001 // an update. 1002 int[] firstUsers; 1003 int[] updateUsers = new int[0]; 1004 if (res.origUsers == null || res.origUsers.length == 0) { 1005 firstUsers = res.newUsers; 1006 } else { 1007 firstUsers = new int[0]; 1008 for (int i=0; i<res.newUsers.length; i++) { 1009 int user = res.newUsers[i]; 1010 boolean isNew = true; 1011 for (int j=0; j<res.origUsers.length; j++) { 1012 if (res.origUsers[j] == user) { 1013 isNew = false; 1014 break; 1015 } 1016 } 1017 if (isNew) { 1018 int[] newFirst = new int[firstUsers.length+1]; 1019 System.arraycopy(firstUsers, 0, newFirst, 0, 1020 firstUsers.length); 1021 newFirst[firstUsers.length] = user; 1022 firstUsers = newFirst; 1023 } else { 1024 int[] newUpdate = new int[updateUsers.length+1]; 1025 System.arraycopy(updateUsers, 0, newUpdate, 0, 1026 updateUsers.length); 1027 newUpdate[updateUsers.length] = user; 1028 updateUsers = newUpdate; 1029 } 1030 } 1031 } 1032 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1033 res.pkg.applicationInfo.packageName, 1034 extras, null, null, firstUsers); 1035 final boolean update = res.removedInfo.removedPackage != null; 1036 if (update) { 1037 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1038 } 1039 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1040 res.pkg.applicationInfo.packageName, 1041 extras, null, null, updateUsers); 1042 if (update) { 1043 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1044 res.pkg.applicationInfo.packageName, 1045 extras, null, null, updateUsers); 1046 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1047 null, null, 1048 res.pkg.applicationInfo.packageName, null, updateUsers); 1049 1050 // treat asec-hosted packages like removable media on upgrade 1051 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1052 if (DEBUG_INSTALL) { 1053 Slog.i(TAG, "upgrading pkg " + res.pkg 1054 + " is ASEC-hosted -> AVAILABLE"); 1055 } 1056 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1057 ArrayList<String> pkgList = new ArrayList<String>(1); 1058 pkgList.add(res.pkg.applicationInfo.packageName); 1059 sendResourcesChangedBroadcast(true, true, 1060 pkgList,uidArray, null); 1061 } 1062 } 1063 if (res.removedInfo.args != null) { 1064 // Remove the replaced package's older resources safely now 1065 deleteOld = true; 1066 } 1067 1068 // Log current value of "unknown sources" setting 1069 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1070 getUnknownSourcesSettings()); 1071 } 1072 // Force a gc to clear up things 1073 Runtime.getRuntime().gc(); 1074 // We delete after a gc for applications on sdcard. 1075 if (deleteOld) { 1076 synchronized (mInstallLock) { 1077 res.removedInfo.args.doPostDeleteLI(true); 1078 } 1079 } 1080 if (args.observer != null) { 1081 try { 1082 Bundle extras = extrasForInstallResult(res); 1083 args.observer.onPackageInstalled(res.name, res.returnCode, 1084 res.returnMsg, extras); 1085 } catch (RemoteException e) { 1086 Slog.i(TAG, "Observer no longer exists."); 1087 } 1088 } 1089 } else { 1090 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1091 } 1092 } break; 1093 case UPDATED_MEDIA_STATUS: { 1094 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1095 boolean reportStatus = msg.arg1 == 1; 1096 boolean doGc = msg.arg2 == 1; 1097 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1098 if (doGc) { 1099 // Force a gc to clear up stale containers. 1100 Runtime.getRuntime().gc(); 1101 } 1102 if (msg.obj != null) { 1103 @SuppressWarnings("unchecked") 1104 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1105 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1106 // Unload containers 1107 unloadAllContainers(args); 1108 } 1109 if (reportStatus) { 1110 try { 1111 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1112 PackageHelper.getMountService().finishMediaUpdate(); 1113 } catch (RemoteException e) { 1114 Log.e(TAG, "MountService not running?"); 1115 } 1116 } 1117 } break; 1118 case WRITE_SETTINGS: { 1119 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1120 synchronized (mPackages) { 1121 removeMessages(WRITE_SETTINGS); 1122 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1123 mSettings.writeLPr(); 1124 mDirtyUsers.clear(); 1125 } 1126 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1127 } break; 1128 case WRITE_PACKAGE_RESTRICTIONS: { 1129 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1130 synchronized (mPackages) { 1131 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1132 for (int userId : mDirtyUsers) { 1133 mSettings.writePackageRestrictionsLPr(userId); 1134 } 1135 mDirtyUsers.clear(); 1136 } 1137 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1138 } break; 1139 case CHECK_PENDING_VERIFICATION: { 1140 final int verificationId = msg.arg1; 1141 final PackageVerificationState state = mPendingVerification.get(verificationId); 1142 1143 if ((state != null) && !state.timeoutExtended()) { 1144 final InstallArgs args = state.getInstallArgs(); 1145 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1146 1147 Slog.i(TAG, "Verification timed out for " + originUri); 1148 mPendingVerification.remove(verificationId); 1149 1150 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1151 1152 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1153 Slog.i(TAG, "Continuing with installation of " + originUri); 1154 state.setVerifierResponse(Binder.getCallingUid(), 1155 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1156 broadcastPackageVerified(verificationId, originUri, 1157 PackageManager.VERIFICATION_ALLOW, 1158 state.getInstallArgs().getUser()); 1159 try { 1160 ret = args.copyApk(mContainerService, true); 1161 } catch (RemoteException e) { 1162 Slog.e(TAG, "Could not contact the ContainerService"); 1163 } 1164 } else { 1165 broadcastPackageVerified(verificationId, originUri, 1166 PackageManager.VERIFICATION_REJECT, 1167 state.getInstallArgs().getUser()); 1168 } 1169 1170 processPendingInstall(args, ret); 1171 mHandler.sendEmptyMessage(MCS_UNBIND); 1172 } 1173 break; 1174 } 1175 case PACKAGE_VERIFIED: { 1176 final int verificationId = msg.arg1; 1177 1178 final PackageVerificationState state = mPendingVerification.get(verificationId); 1179 if (state == null) { 1180 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1181 break; 1182 } 1183 1184 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1185 1186 state.setVerifierResponse(response.callerUid, response.code); 1187 1188 if (state.isVerificationComplete()) { 1189 mPendingVerification.remove(verificationId); 1190 1191 final InstallArgs args = state.getInstallArgs(); 1192 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1193 1194 int ret; 1195 if (state.isInstallAllowed()) { 1196 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1197 broadcastPackageVerified(verificationId, originUri, 1198 response.code, state.getInstallArgs().getUser()); 1199 try { 1200 ret = args.copyApk(mContainerService, true); 1201 } catch (RemoteException e) { 1202 Slog.e(TAG, "Could not contact the ContainerService"); 1203 } 1204 } else { 1205 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1206 } 1207 1208 processPendingInstall(args, ret); 1209 1210 mHandler.sendEmptyMessage(MCS_UNBIND); 1211 } 1212 1213 break; 1214 } 1215 } 1216 } 1217 } 1218 1219 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1220 Bundle extras = null; 1221 switch (res.returnCode) { 1222 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1223 extras = new Bundle(); 1224 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1225 res.origPermission); 1226 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1227 res.origPackage); 1228 break; 1229 } 1230 } 1231 return extras; 1232 } 1233 1234 void scheduleWriteSettingsLocked() { 1235 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1236 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1237 } 1238 } 1239 1240 void scheduleWritePackageRestrictionsLocked(int userId) { 1241 if (!sUserManager.exists(userId)) return; 1242 mDirtyUsers.add(userId); 1243 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1244 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1245 } 1246 } 1247 1248 public static final PackageManagerService main(Context context, Installer installer, 1249 boolean factoryTest, boolean onlyCore) { 1250 PackageManagerService m = new PackageManagerService(context, installer, 1251 factoryTest, onlyCore); 1252 ServiceManager.addService("package", m); 1253 return m; 1254 } 1255 1256 static String[] splitString(String str, char sep) { 1257 int count = 1; 1258 int i = 0; 1259 while ((i=str.indexOf(sep, i)) >= 0) { 1260 count++; 1261 i++; 1262 } 1263 1264 String[] res = new String[count]; 1265 i=0; 1266 count = 0; 1267 int lastI=0; 1268 while ((i=str.indexOf(sep, i)) >= 0) { 1269 res[count] = str.substring(lastI, i); 1270 count++; 1271 i++; 1272 lastI = i; 1273 } 1274 res[count] = str.substring(lastI, str.length()); 1275 return res; 1276 } 1277 1278 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1279 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1280 Context.DISPLAY_SERVICE); 1281 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1282 } 1283 1284 public PackageManagerService(Context context, Installer installer, 1285 boolean factoryTest, boolean onlyCore) { 1286 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1287 SystemClock.uptimeMillis()); 1288 1289 if (mSdkVersion <= 0) { 1290 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1291 } 1292 1293 mContext = context; 1294 mFactoryTest = factoryTest; 1295 mOnlyCore = onlyCore; 1296 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1297 mMetrics = new DisplayMetrics(); 1298 mSettings = new Settings(context); 1299 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1300 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1301 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1302 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1303 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1304 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1305 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1306 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1307 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1308 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1309 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1310 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1311 1312 // TODO: add a property to control this? 1313 long dexOptLRUThresholdInMinutes; 1314 if (mLazyDexOpt) { 1315 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1316 } else { 1317 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1318 } 1319 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1320 1321 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1322 if (separateProcesses != null && separateProcesses.length() > 0) { 1323 if ("*".equals(separateProcesses)) { 1324 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1325 mSeparateProcesses = null; 1326 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1327 } else { 1328 mDefParseFlags = 0; 1329 mSeparateProcesses = separateProcesses.split(","); 1330 Slog.w(TAG, "Running with debug.separate_processes: " 1331 + separateProcesses); 1332 } 1333 } else { 1334 mDefParseFlags = 0; 1335 mSeparateProcesses = null; 1336 } 1337 1338 mInstaller = installer; 1339 mPackageDexOptimizer = new PackageDexOptimizer(this); 1340 1341 getDefaultDisplayMetrics(context, mMetrics); 1342 1343 SystemConfig systemConfig = SystemConfig.getInstance(); 1344 mGlobalGids = systemConfig.getGlobalGids(); 1345 mSystemPermissions = systemConfig.getSystemPermissions(); 1346 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1347 1348 synchronized (mInstallLock) { 1349 // writer 1350 synchronized (mPackages) { 1351 mHandlerThread = new ServiceThread(TAG, 1352 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1353 mHandlerThread.start(); 1354 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1355 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1356 1357 File dataDir = Environment.getDataDirectory(); 1358 mAppDataDir = new File(dataDir, "data"); 1359 mAppInstallDir = new File(dataDir, "app"); 1360 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1361 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1362 mUserAppDataDir = new File(dataDir, "user"); 1363 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1364 1365 sUserManager = new UserManagerService(context, this, 1366 mInstallLock, mPackages); 1367 1368 // Propagate permission configuration in to package manager. 1369 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1370 = systemConfig.getPermissions(); 1371 for (int i=0; i<permConfig.size(); i++) { 1372 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1373 BasePermission bp = mSettings.mPermissions.get(perm.name); 1374 if (bp == null) { 1375 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1376 mSettings.mPermissions.put(perm.name, bp); 1377 } 1378 if (perm.gids != null) { 1379 bp.gids = appendInts(bp.gids, perm.gids); 1380 } 1381 } 1382 1383 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1384 for (int i=0; i<libConfig.size(); i++) { 1385 mSharedLibraries.put(libConfig.keyAt(i), 1386 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1387 } 1388 1389 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1390 1391 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1392 mSdkVersion, mOnlyCore); 1393 1394 String customResolverActivity = Resources.getSystem().getString( 1395 R.string.config_customResolverActivity); 1396 if (TextUtils.isEmpty(customResolverActivity)) { 1397 customResolverActivity = null; 1398 } else { 1399 mCustomResolverComponentName = ComponentName.unflattenFromString( 1400 customResolverActivity); 1401 } 1402 1403 long startTime = SystemClock.uptimeMillis(); 1404 1405 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1406 startTime); 1407 1408 // Set flag to monitor and not change apk file paths when 1409 // scanning install directories. 1410 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1411 1412 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1413 1414 /** 1415 * Add everything in the in the boot class path to the 1416 * list of process files because dexopt will have been run 1417 * if necessary during zygote startup. 1418 */ 1419 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1420 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1421 1422 if (bootClassPath != null) { 1423 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1424 for (String element : bootClassPathElements) { 1425 alreadyDexOpted.add(element); 1426 } 1427 } else { 1428 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1429 } 1430 1431 if (systemServerClassPath != null) { 1432 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1433 for (String element : systemServerClassPathElements) { 1434 alreadyDexOpted.add(element); 1435 } 1436 } else { 1437 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1438 } 1439 1440 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1441 final String[] dexCodeInstructionSets = 1442 getDexCodeInstructionSets( 1443 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1444 1445 /** 1446 * Ensure all external libraries have had dexopt run on them. 1447 */ 1448 if (mSharedLibraries.size() > 0) { 1449 // NOTE: For now, we're compiling these system "shared libraries" 1450 // (and framework jars) into all available architectures. It's possible 1451 // to compile them only when we come across an app that uses them (there's 1452 // already logic for that in scanPackageLI) but that adds some complexity. 1453 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1454 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1455 final String lib = libEntry.path; 1456 if (lib == null) { 1457 continue; 1458 } 1459 1460 try { 1461 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1462 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1463 alreadyDexOpted.add(lib); 1464 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 1465 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 1466 } 1467 } catch (FileNotFoundException e) { 1468 Slog.w(TAG, "Library not found: " + lib); 1469 } catch (IOException e) { 1470 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1471 + e.getMessage()); 1472 } 1473 } 1474 } 1475 } 1476 1477 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1478 1479 // Gross hack for now: we know this file doesn't contain any 1480 // code, so don't dexopt it to avoid the resulting log spew. 1481 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1482 1483 // Gross hack for now: we know this file is only part of 1484 // the boot class path for art, so don't dexopt it to 1485 // avoid the resulting log spew. 1486 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1487 1488 /** 1489 * And there are a number of commands implemented in Java, which 1490 * we currently need to do the dexopt on so that they can be 1491 * run from a non-root shell. 1492 */ 1493 String[] frameworkFiles = frameworkDir.list(); 1494 if (frameworkFiles != null) { 1495 // TODO: We could compile these only for the most preferred ABI. We should 1496 // first double check that the dex files for these commands are not referenced 1497 // by other system apps. 1498 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1499 for (int i=0; i<frameworkFiles.length; i++) { 1500 File libPath = new File(frameworkDir, frameworkFiles[i]); 1501 String path = libPath.getPath(); 1502 // Skip the file if we already did it. 1503 if (alreadyDexOpted.contains(path)) { 1504 continue; 1505 } 1506 // Skip the file if it is not a type we want to dexopt. 1507 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1508 continue; 1509 } 1510 try { 1511 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1512 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1513 mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet, 1514 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 1515 } 1516 } catch (FileNotFoundException e) { 1517 Slog.w(TAG, "Jar not found: " + path); 1518 } catch (IOException e) { 1519 Slog.w(TAG, "Exception reading jar: " + path, e); 1520 } 1521 } 1522 } 1523 } 1524 1525 // Collect vendor overlay packages. 1526 // (Do this before scanning any apps.) 1527 // For security and version matching reason, only consider 1528 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1529 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1530 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1531 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1532 1533 // Find base frameworks (resource packages without code). 1534 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1535 | PackageParser.PARSE_IS_SYSTEM_DIR 1536 | PackageParser.PARSE_IS_PRIVILEGED, 1537 scanFlags | SCAN_NO_DEX, 0); 1538 1539 // Collected privileged system packages. 1540 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1541 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1542 | PackageParser.PARSE_IS_SYSTEM_DIR 1543 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1544 1545 // Collect ordinary system packages. 1546 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1547 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1548 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1549 1550 // Collect all vendor packages. 1551 File vendorAppDir = new File("/vendor/app"); 1552 try { 1553 vendorAppDir = vendorAppDir.getCanonicalFile(); 1554 } catch (IOException e) { 1555 // failed to look up canonical path, continue with original one 1556 } 1557 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1558 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1559 1560 // Collect all OEM packages. 1561 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1562 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1563 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1564 1565 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1566 mInstaller.moveFiles(); 1567 1568 // Prune any system packages that no longer exist. 1569 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1570 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1571 if (!mOnlyCore) { 1572 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1573 while (psit.hasNext()) { 1574 PackageSetting ps = psit.next(); 1575 1576 /* 1577 * If this is not a system app, it can't be a 1578 * disable system app. 1579 */ 1580 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1581 continue; 1582 } 1583 1584 /* 1585 * If the package is scanned, it's not erased. 1586 */ 1587 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1588 if (scannedPkg != null) { 1589 /* 1590 * If the system app is both scanned and in the 1591 * disabled packages list, then it must have been 1592 * added via OTA. Remove it from the currently 1593 * scanned package so the previously user-installed 1594 * application can be scanned. 1595 */ 1596 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1597 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1598 + ps.name + "; removing system app. Last known codePath=" 1599 + ps.codePathString + ", installStatus=" + ps.installStatus 1600 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1601 + scannedPkg.mVersionCode); 1602 removePackageLI(ps, true); 1603 expectingBetter.put(ps.name, ps.codePath); 1604 } 1605 1606 continue; 1607 } 1608 1609 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1610 psit.remove(); 1611 logCriticalInfo(Log.WARN, "System package " + ps.name 1612 + " no longer exists; wiping its data"); 1613 removeDataDirsLI(ps.name); 1614 } else { 1615 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1616 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1617 possiblyDeletedUpdatedSystemApps.add(ps.name); 1618 } 1619 } 1620 } 1621 } 1622 1623 //look for any incomplete package installations 1624 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1625 //clean up list 1626 for(int i = 0; i < deletePkgsList.size(); i++) { 1627 //clean up here 1628 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1629 } 1630 //delete tmp files 1631 deleteTempPackageFiles(); 1632 1633 // Remove any shared userIDs that have no associated packages 1634 mSettings.pruneSharedUsersLPw(); 1635 1636 if (!mOnlyCore) { 1637 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1638 SystemClock.uptimeMillis()); 1639 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1640 1641 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1642 scanFlags, 0); 1643 1644 /** 1645 * Remove disable package settings for any updated system 1646 * apps that were removed via an OTA. If they're not a 1647 * previously-updated app, remove them completely. 1648 * Otherwise, just revoke their system-level permissions. 1649 */ 1650 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1651 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1652 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1653 1654 String msg; 1655 if (deletedPkg == null) { 1656 msg = "Updated system package " + deletedAppName 1657 + " no longer exists; wiping its data"; 1658 removeDataDirsLI(deletedAppName); 1659 } else { 1660 msg = "Updated system app + " + deletedAppName 1661 + " no longer present; removing system privileges for " 1662 + deletedAppName; 1663 1664 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1665 1666 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1667 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1668 } 1669 logCriticalInfo(Log.WARN, msg); 1670 } 1671 1672 /** 1673 * Make sure all system apps that we expected to appear on 1674 * the userdata partition actually showed up. If they never 1675 * appeared, crawl back and revive the system version. 1676 */ 1677 for (int i = 0; i < expectingBetter.size(); i++) { 1678 final String packageName = expectingBetter.keyAt(i); 1679 if (!mPackages.containsKey(packageName)) { 1680 final File scanFile = expectingBetter.valueAt(i); 1681 1682 logCriticalInfo(Log.WARN, "Expected better " + packageName 1683 + " but never showed up; reverting to system"); 1684 1685 final int reparseFlags; 1686 if (FileUtils.contains(privilegedAppDir, scanFile)) { 1687 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1688 | PackageParser.PARSE_IS_SYSTEM_DIR 1689 | PackageParser.PARSE_IS_PRIVILEGED; 1690 } else if (FileUtils.contains(systemAppDir, scanFile)) { 1691 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1692 | PackageParser.PARSE_IS_SYSTEM_DIR; 1693 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 1694 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1695 | PackageParser.PARSE_IS_SYSTEM_DIR; 1696 } else if (FileUtils.contains(oemAppDir, scanFile)) { 1697 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1698 | PackageParser.PARSE_IS_SYSTEM_DIR; 1699 } else { 1700 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 1701 continue; 1702 } 1703 1704 mSettings.enableSystemPackageLPw(packageName); 1705 1706 try { 1707 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 1708 } catch (PackageManagerException e) { 1709 Slog.e(TAG, "Failed to parse original system package: " 1710 + e.getMessage()); 1711 } 1712 } 1713 } 1714 } 1715 1716 // Now that we know all of the shared libraries, update all clients to have 1717 // the correct library paths. 1718 updateAllSharedLibrariesLPw(); 1719 1720 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1721 // NOTE: We ignore potential failures here during a system scan (like 1722 // the rest of the commands above) because there's precious little we 1723 // can do about it. A settings error is reported, though. 1724 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1725 false /* force dexopt */, false /* defer dexopt */, 1726 false /* boot complete */); 1727 } 1728 1729 // Now that we know all the packages we are keeping, 1730 // read and update their last usage times. 1731 mPackageUsage.readLP(); 1732 1733 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1734 SystemClock.uptimeMillis()); 1735 Slog.i(TAG, "Time to scan packages: " 1736 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1737 + " seconds"); 1738 1739 // If the platform SDK has changed since the last time we booted, 1740 // we need to re-grant app permission to catch any new ones that 1741 // appear. This is really a hack, and means that apps can in some 1742 // cases get permissions that the user didn't initially explicitly 1743 // allow... it would be nice to have some better way to handle 1744 // this situation. 1745 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1746 != mSdkVersion; 1747 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1748 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1749 + "; regranting permissions for internal storage"); 1750 mSettings.mInternalSdkPlatform = mSdkVersion; 1751 1752 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1753 | (regrantPermissions 1754 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1755 : 0)); 1756 1757 // If this is the first boot, and it is a normal boot, then 1758 // we need to initialize the default preferred apps. 1759 if (!mRestoredSettings && !onlyCore) { 1760 mSettings.readDefaultPreferredAppsLPw(this, 0); 1761 } 1762 1763 // If this is first boot after an OTA, and a normal boot, then 1764 // we need to clear code cache directories. 1765 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 1766 if (mIsUpgrade && !onlyCore) { 1767 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1768 for (String pkgName : mSettings.mPackages.keySet()) { 1769 deleteCodeCacheDirsLI(pkgName); 1770 } 1771 mSettings.mFingerprint = Build.FINGERPRINT; 1772 } 1773 1774 // All the changes are done during package scanning. 1775 mSettings.updateInternalDatabaseVersion(); 1776 1777 // can downgrade to reader 1778 mSettings.writeLPr(); 1779 1780 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1781 SystemClock.uptimeMillis()); 1782 1783 1784 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1785 } // synchronized (mPackages) 1786 } // synchronized (mInstallLock) 1787 1788 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1789 1790 // Now after opening every single application zip, make sure they 1791 // are all flushed. Not really needed, but keeps things nice and 1792 // tidy. 1793 Runtime.getRuntime().gc(); 1794 } 1795 1796 @Override 1797 public boolean isFirstBoot() { 1798 return !mRestoredSettings; 1799 } 1800 1801 @Override 1802 public boolean isOnlyCoreApps() { 1803 return mOnlyCore; 1804 } 1805 1806 @Override 1807 public boolean isUpgrade() { 1808 return mIsUpgrade; 1809 } 1810 1811 private String getRequiredVerifierLPr() { 1812 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1813 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1814 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1815 1816 String requiredVerifier = null; 1817 1818 final int N = receivers.size(); 1819 for (int i = 0; i < N; i++) { 1820 final ResolveInfo info = receivers.get(i); 1821 1822 if (info.activityInfo == null) { 1823 continue; 1824 } 1825 1826 final String packageName = info.activityInfo.packageName; 1827 1828 final PackageSetting ps = mSettings.mPackages.get(packageName); 1829 if (ps == null) { 1830 continue; 1831 } 1832 1833 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1834 if (!gp.grantedPermissions 1835 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1836 continue; 1837 } 1838 1839 if (requiredVerifier != null) { 1840 throw new RuntimeException("There can be only one required verifier"); 1841 } 1842 1843 requiredVerifier = packageName; 1844 } 1845 1846 return requiredVerifier; 1847 } 1848 1849 @Override 1850 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1851 throws RemoteException { 1852 try { 1853 return super.onTransact(code, data, reply, flags); 1854 } catch (RuntimeException e) { 1855 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1856 Slog.wtf(TAG, "Package Manager Crash", e); 1857 } 1858 throw e; 1859 } 1860 } 1861 1862 void cleanupInstallFailedPackage(PackageSetting ps) { 1863 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1864 1865 removeDataDirsLI(ps.name); 1866 if (ps.codePath != null) { 1867 if (ps.codePath.isDirectory()) { 1868 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 1869 } else { 1870 ps.codePath.delete(); 1871 } 1872 } 1873 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1874 if (ps.resourcePath.isDirectory()) { 1875 FileUtils.deleteContents(ps.resourcePath); 1876 } 1877 ps.resourcePath.delete(); 1878 } 1879 mSettings.removePackageLPw(ps.name); 1880 } 1881 1882 static int[] appendInts(int[] cur, int[] add) { 1883 if (add == null) return cur; 1884 if (cur == null) return add; 1885 final int N = add.length; 1886 for (int i=0; i<N; i++) { 1887 cur = appendInt(cur, add[i]); 1888 } 1889 return cur; 1890 } 1891 1892 static int[] removeInts(int[] cur, int[] rem) { 1893 if (rem == null) return cur; 1894 if (cur == null) return cur; 1895 final int N = rem.length; 1896 for (int i=0; i<N; i++) { 1897 cur = removeInt(cur, rem[i]); 1898 } 1899 return cur; 1900 } 1901 1902 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1903 if (!sUserManager.exists(userId)) return null; 1904 final PackageSetting ps = (PackageSetting) p.mExtras; 1905 if (ps == null) { 1906 return null; 1907 } 1908 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1909 final PackageUserState state = ps.readUserState(userId); 1910 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1911 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1912 state, userId); 1913 } 1914 1915 @Override 1916 public boolean isPackageAvailable(String packageName, int userId) { 1917 if (!sUserManager.exists(userId)) return false; 1918 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1919 synchronized (mPackages) { 1920 PackageParser.Package p = mPackages.get(packageName); 1921 if (p != null) { 1922 final PackageSetting ps = (PackageSetting) p.mExtras; 1923 if (ps != null) { 1924 final PackageUserState state = ps.readUserState(userId); 1925 if (state != null) { 1926 return PackageParser.isAvailable(state); 1927 } 1928 } 1929 } 1930 } 1931 return false; 1932 } 1933 1934 @Override 1935 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1936 if (!sUserManager.exists(userId)) return null; 1937 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1938 // reader 1939 synchronized (mPackages) { 1940 PackageParser.Package p = mPackages.get(packageName); 1941 if (DEBUG_PACKAGE_INFO) 1942 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1943 if (p != null) { 1944 return generatePackageInfo(p, flags, userId); 1945 } 1946 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1947 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1948 } 1949 } 1950 return null; 1951 } 1952 1953 @Override 1954 public String[] currentToCanonicalPackageNames(String[] names) { 1955 String[] out = new String[names.length]; 1956 // reader 1957 synchronized (mPackages) { 1958 for (int i=names.length-1; i>=0; i--) { 1959 PackageSetting ps = mSettings.mPackages.get(names[i]); 1960 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1961 } 1962 } 1963 return out; 1964 } 1965 1966 @Override 1967 public String[] canonicalToCurrentPackageNames(String[] names) { 1968 String[] out = new String[names.length]; 1969 // reader 1970 synchronized (mPackages) { 1971 for (int i=names.length-1; i>=0; i--) { 1972 String cur = mSettings.mRenamedPackages.get(names[i]); 1973 out[i] = cur != null ? cur : names[i]; 1974 } 1975 } 1976 return out; 1977 } 1978 1979 @Override 1980 public int getPackageUid(String packageName, int userId) { 1981 if (!sUserManager.exists(userId)) return -1; 1982 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1983 // reader 1984 synchronized (mPackages) { 1985 PackageParser.Package p = mPackages.get(packageName); 1986 if(p != null) { 1987 return UserHandle.getUid(userId, p.applicationInfo.uid); 1988 } 1989 PackageSetting ps = mSettings.mPackages.get(packageName); 1990 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1991 return -1; 1992 } 1993 p = ps.pkg; 1994 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1995 } 1996 } 1997 1998 @Override 1999 public int[] getPackageGids(String packageName) { 2000 // reader 2001 synchronized (mPackages) { 2002 PackageParser.Package p = mPackages.get(packageName); 2003 if (DEBUG_PACKAGE_INFO) 2004 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2005 if (p != null) { 2006 final PackageSetting ps = (PackageSetting)p.mExtras; 2007 return ps.getGids(); 2008 } 2009 } 2010 // stupid thing to indicate an error. 2011 return new int[0]; 2012 } 2013 2014 static final PermissionInfo generatePermissionInfo( 2015 BasePermission bp, int flags) { 2016 if (bp.perm != null) { 2017 return PackageParser.generatePermissionInfo(bp.perm, flags); 2018 } 2019 PermissionInfo pi = new PermissionInfo(); 2020 pi.name = bp.name; 2021 pi.packageName = bp.sourcePackage; 2022 pi.nonLocalizedLabel = bp.name; 2023 pi.protectionLevel = bp.protectionLevel; 2024 return pi; 2025 } 2026 2027 @Override 2028 public PermissionInfo getPermissionInfo(String name, int flags) { 2029 // reader 2030 synchronized (mPackages) { 2031 final BasePermission p = mSettings.mPermissions.get(name); 2032 if (p != null) { 2033 return generatePermissionInfo(p, flags); 2034 } 2035 return null; 2036 } 2037 } 2038 2039 @Override 2040 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2041 // reader 2042 synchronized (mPackages) { 2043 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2044 for (BasePermission p : mSettings.mPermissions.values()) { 2045 if (group == null) { 2046 if (p.perm == null || p.perm.info.group == null) { 2047 out.add(generatePermissionInfo(p, flags)); 2048 } 2049 } else { 2050 if (p.perm != null && group.equals(p.perm.info.group)) { 2051 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2052 } 2053 } 2054 } 2055 2056 if (out.size() > 0) { 2057 return out; 2058 } 2059 return mPermissionGroups.containsKey(group) ? out : null; 2060 } 2061 } 2062 2063 @Override 2064 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2065 // reader 2066 synchronized (mPackages) { 2067 return PackageParser.generatePermissionGroupInfo( 2068 mPermissionGroups.get(name), flags); 2069 } 2070 } 2071 2072 @Override 2073 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2074 // reader 2075 synchronized (mPackages) { 2076 final int N = mPermissionGroups.size(); 2077 ArrayList<PermissionGroupInfo> out 2078 = new ArrayList<PermissionGroupInfo>(N); 2079 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2080 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2081 } 2082 return out; 2083 } 2084 } 2085 2086 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2087 int userId) { 2088 if (!sUserManager.exists(userId)) return null; 2089 PackageSetting ps = mSettings.mPackages.get(packageName); 2090 if (ps != null) { 2091 if (ps.pkg == null) { 2092 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2093 flags, userId); 2094 if (pInfo != null) { 2095 return pInfo.applicationInfo; 2096 } 2097 return null; 2098 } 2099 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2100 ps.readUserState(userId), userId); 2101 } 2102 return null; 2103 } 2104 2105 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2106 int userId) { 2107 if (!sUserManager.exists(userId)) return null; 2108 PackageSetting ps = mSettings.mPackages.get(packageName); 2109 if (ps != null) { 2110 PackageParser.Package pkg = ps.pkg; 2111 if (pkg == null) { 2112 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2113 return null; 2114 } 2115 // Only data remains, so we aren't worried about code paths 2116 pkg = new PackageParser.Package(packageName); 2117 pkg.applicationInfo.packageName = packageName; 2118 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2119 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2120 pkg.applicationInfo.dataDir = 2121 getDataPathForPackage(packageName, 0).getPath(); 2122 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2123 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2124 } 2125 return generatePackageInfo(pkg, flags, userId); 2126 } 2127 return null; 2128 } 2129 2130 @Override 2131 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2132 if (!sUserManager.exists(userId)) return null; 2133 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2134 // writer 2135 synchronized (mPackages) { 2136 PackageParser.Package p = mPackages.get(packageName); 2137 if (DEBUG_PACKAGE_INFO) Log.v( 2138 TAG, "getApplicationInfo " + packageName 2139 + ": " + p); 2140 if (p != null) { 2141 PackageSetting ps = mSettings.mPackages.get(packageName); 2142 if (ps == null) return null; 2143 // Note: isEnabledLP() does not apply here - always return info 2144 return PackageParser.generateApplicationInfo( 2145 p, flags, ps.readUserState(userId), userId); 2146 } 2147 if ("android".equals(packageName)||"system".equals(packageName)) { 2148 return mAndroidApplication; 2149 } 2150 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2151 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2152 } 2153 } 2154 return null; 2155 } 2156 2157 2158 @Override 2159 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2160 mContext.enforceCallingOrSelfPermission( 2161 android.Manifest.permission.CLEAR_APP_CACHE, null); 2162 // Queue up an async operation since clearing cache may take a little while. 2163 mHandler.post(new Runnable() { 2164 public void run() { 2165 mHandler.removeCallbacks(this); 2166 int retCode = -1; 2167 synchronized (mInstallLock) { 2168 retCode = mInstaller.freeCache(freeStorageSize); 2169 if (retCode < 0) { 2170 Slog.w(TAG, "Couldn't clear application caches"); 2171 } 2172 } 2173 if (observer != null) { 2174 try { 2175 observer.onRemoveCompleted(null, (retCode >= 0)); 2176 } catch (RemoteException e) { 2177 Slog.w(TAG, "RemoveException when invoking call back"); 2178 } 2179 } 2180 } 2181 }); 2182 } 2183 2184 @Override 2185 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2186 mContext.enforceCallingOrSelfPermission( 2187 android.Manifest.permission.CLEAR_APP_CACHE, null); 2188 // Queue up an async operation since clearing cache may take a little while. 2189 mHandler.post(new Runnable() { 2190 public void run() { 2191 mHandler.removeCallbacks(this); 2192 int retCode = -1; 2193 synchronized (mInstallLock) { 2194 retCode = mInstaller.freeCache(freeStorageSize); 2195 if (retCode < 0) { 2196 Slog.w(TAG, "Couldn't clear application caches"); 2197 } 2198 } 2199 if(pi != null) { 2200 try { 2201 // Callback via pending intent 2202 int code = (retCode >= 0) ? 1 : 0; 2203 pi.sendIntent(null, code, null, 2204 null, null); 2205 } catch (SendIntentException e1) { 2206 Slog.i(TAG, "Failed to send pending intent"); 2207 } 2208 } 2209 } 2210 }); 2211 } 2212 2213 void freeStorage(long freeStorageSize) throws IOException { 2214 synchronized (mInstallLock) { 2215 if (mInstaller.freeCache(freeStorageSize) < 0) { 2216 throw new IOException("Failed to free enough space"); 2217 } 2218 } 2219 } 2220 2221 @Override 2222 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2223 if (!sUserManager.exists(userId)) return null; 2224 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2225 synchronized (mPackages) { 2226 PackageParser.Activity a = mActivities.mActivities.get(component); 2227 2228 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2229 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2230 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2231 if (ps == null) return null; 2232 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2233 userId); 2234 } 2235 if (mResolveComponentName.equals(component)) { 2236 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2237 new PackageUserState(), userId); 2238 } 2239 } 2240 return null; 2241 } 2242 2243 @Override 2244 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2245 String resolvedType) { 2246 synchronized (mPackages) { 2247 PackageParser.Activity a = mActivities.mActivities.get(component); 2248 if (a == null) { 2249 return false; 2250 } 2251 for (int i=0; i<a.intents.size(); i++) { 2252 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2253 intent.getData(), intent.getCategories(), TAG) >= 0) { 2254 return true; 2255 } 2256 } 2257 return false; 2258 } 2259 } 2260 2261 @Override 2262 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2263 if (!sUserManager.exists(userId)) return null; 2264 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2265 synchronized (mPackages) { 2266 PackageParser.Activity a = mReceivers.mActivities.get(component); 2267 if (DEBUG_PACKAGE_INFO) Log.v( 2268 TAG, "getReceiverInfo " + component + ": " + a); 2269 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2270 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2271 if (ps == null) return null; 2272 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2273 userId); 2274 } 2275 } 2276 return null; 2277 } 2278 2279 @Override 2280 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2281 if (!sUserManager.exists(userId)) return null; 2282 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2283 synchronized (mPackages) { 2284 PackageParser.Service s = mServices.mServices.get(component); 2285 if (DEBUG_PACKAGE_INFO) Log.v( 2286 TAG, "getServiceInfo " + component + ": " + s); 2287 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2288 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2289 if (ps == null) return null; 2290 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2291 userId); 2292 } 2293 } 2294 return null; 2295 } 2296 2297 @Override 2298 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2299 if (!sUserManager.exists(userId)) return null; 2300 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2301 synchronized (mPackages) { 2302 PackageParser.Provider p = mProviders.mProviders.get(component); 2303 if (DEBUG_PACKAGE_INFO) Log.v( 2304 TAG, "getProviderInfo " + component + ": " + p); 2305 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2306 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2307 if (ps == null) return null; 2308 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2309 userId); 2310 } 2311 } 2312 return null; 2313 } 2314 2315 @Override 2316 public String[] getSystemSharedLibraryNames() { 2317 Set<String> libSet; 2318 synchronized (mPackages) { 2319 libSet = mSharedLibraries.keySet(); 2320 int size = libSet.size(); 2321 if (size > 0) { 2322 String[] libs = new String[size]; 2323 libSet.toArray(libs); 2324 return libs; 2325 } 2326 } 2327 return null; 2328 } 2329 2330 /** 2331 * @hide 2332 */ 2333 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2334 synchronized (mPackages) { 2335 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2336 if (lib != null && lib.apk != null) { 2337 return mPackages.get(lib.apk); 2338 } 2339 } 2340 return null; 2341 } 2342 2343 @Override 2344 public FeatureInfo[] getSystemAvailableFeatures() { 2345 Collection<FeatureInfo> featSet; 2346 synchronized (mPackages) { 2347 featSet = mAvailableFeatures.values(); 2348 int size = featSet.size(); 2349 if (size > 0) { 2350 FeatureInfo[] features = new FeatureInfo[size+1]; 2351 featSet.toArray(features); 2352 FeatureInfo fi = new FeatureInfo(); 2353 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2354 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2355 features[size] = fi; 2356 return features; 2357 } 2358 } 2359 return null; 2360 } 2361 2362 @Override 2363 public boolean hasSystemFeature(String name) { 2364 synchronized (mPackages) { 2365 return mAvailableFeatures.containsKey(name); 2366 } 2367 } 2368 2369 private void checkValidCaller(int uid, int userId) { 2370 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2371 return; 2372 2373 throw new SecurityException("Caller uid=" + uid 2374 + " is not privileged to communicate with user=" + userId); 2375 } 2376 2377 @Override 2378 public int checkPermission(String permName, String pkgName) { 2379 synchronized (mPackages) { 2380 PackageParser.Package p = mPackages.get(pkgName); 2381 if (p != null && p.mExtras != null) { 2382 PackageSetting ps = (PackageSetting)p.mExtras; 2383 if (ps.sharedUser != null) { 2384 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2385 return PackageManager.PERMISSION_GRANTED; 2386 } 2387 } else if (ps.grantedPermissions.contains(permName)) { 2388 return PackageManager.PERMISSION_GRANTED; 2389 } 2390 } 2391 } 2392 return PackageManager.PERMISSION_DENIED; 2393 } 2394 2395 @Override 2396 public int checkUidPermission(String permName, int uid) { 2397 synchronized (mPackages) { 2398 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2399 if (obj != null) { 2400 GrantedPermissions gp = (GrantedPermissions)obj; 2401 if (gp.grantedPermissions.contains(permName)) { 2402 return PackageManager.PERMISSION_GRANTED; 2403 } 2404 } else { 2405 ArraySet<String> perms = mSystemPermissions.get(uid); 2406 if (perms != null && perms.contains(permName)) { 2407 return PackageManager.PERMISSION_GRANTED; 2408 } 2409 } 2410 } 2411 return PackageManager.PERMISSION_DENIED; 2412 } 2413 2414 /** 2415 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2416 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2417 * @param checkShell TODO(yamasani): 2418 * @param message the message to log on security exception 2419 */ 2420 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2421 boolean checkShell, String message) { 2422 if (userId < 0) { 2423 throw new IllegalArgumentException("Invalid userId " + userId); 2424 } 2425 if (checkShell) { 2426 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2427 } 2428 if (userId == UserHandle.getUserId(callingUid)) return; 2429 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2430 if (requireFullPermission) { 2431 mContext.enforceCallingOrSelfPermission( 2432 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2433 } else { 2434 try { 2435 mContext.enforceCallingOrSelfPermission( 2436 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2437 } catch (SecurityException se) { 2438 mContext.enforceCallingOrSelfPermission( 2439 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2440 } 2441 } 2442 } 2443 } 2444 2445 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2446 if (callingUid == Process.SHELL_UID) { 2447 if (userHandle >= 0 2448 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2449 throw new SecurityException("Shell does not have permission to access user " 2450 + userHandle); 2451 } else if (userHandle < 0) { 2452 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2453 + Debug.getCallers(3)); 2454 } 2455 } 2456 } 2457 2458 private BasePermission findPermissionTreeLP(String permName) { 2459 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2460 if (permName.startsWith(bp.name) && 2461 permName.length() > bp.name.length() && 2462 permName.charAt(bp.name.length()) == '.') { 2463 return bp; 2464 } 2465 } 2466 return null; 2467 } 2468 2469 private BasePermission checkPermissionTreeLP(String permName) { 2470 if (permName != null) { 2471 BasePermission bp = findPermissionTreeLP(permName); 2472 if (bp != null) { 2473 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2474 return bp; 2475 } 2476 throw new SecurityException("Calling uid " 2477 + Binder.getCallingUid() 2478 + " is not allowed to add to permission tree " 2479 + bp.name + " owned by uid " + bp.uid); 2480 } 2481 } 2482 throw new SecurityException("No permission tree found for " + permName); 2483 } 2484 2485 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2486 if (s1 == null) { 2487 return s2 == null; 2488 } 2489 if (s2 == null) { 2490 return false; 2491 } 2492 if (s1.getClass() != s2.getClass()) { 2493 return false; 2494 } 2495 return s1.equals(s2); 2496 } 2497 2498 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2499 if (pi1.icon != pi2.icon) return false; 2500 if (pi1.logo != pi2.logo) return false; 2501 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2502 if (!compareStrings(pi1.name, pi2.name)) return false; 2503 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2504 // We'll take care of setting this one. 2505 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2506 // These are not currently stored in settings. 2507 //if (!compareStrings(pi1.group, pi2.group)) return false; 2508 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2509 //if (pi1.labelRes != pi2.labelRes) return false; 2510 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2511 return true; 2512 } 2513 2514 int permissionInfoFootprint(PermissionInfo info) { 2515 int size = info.name.length(); 2516 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2517 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2518 return size; 2519 } 2520 2521 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2522 int size = 0; 2523 for (BasePermission perm : mSettings.mPermissions.values()) { 2524 if (perm.uid == tree.uid) { 2525 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2526 } 2527 } 2528 return size; 2529 } 2530 2531 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2532 // We calculate the max size of permissions defined by this uid and throw 2533 // if that plus the size of 'info' would exceed our stated maximum. 2534 if (tree.uid != Process.SYSTEM_UID) { 2535 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2536 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2537 throw new SecurityException("Permission tree size cap exceeded"); 2538 } 2539 } 2540 } 2541 2542 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2543 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2544 throw new SecurityException("Label must be specified in permission"); 2545 } 2546 BasePermission tree = checkPermissionTreeLP(info.name); 2547 BasePermission bp = mSettings.mPermissions.get(info.name); 2548 boolean added = bp == null; 2549 boolean changed = true; 2550 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2551 if (added) { 2552 enforcePermissionCapLocked(info, tree); 2553 bp = new BasePermission(info.name, tree.sourcePackage, 2554 BasePermission.TYPE_DYNAMIC); 2555 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2556 throw new SecurityException( 2557 "Not allowed to modify non-dynamic permission " 2558 + info.name); 2559 } else { 2560 if (bp.protectionLevel == fixedLevel 2561 && bp.perm.owner.equals(tree.perm.owner) 2562 && bp.uid == tree.uid 2563 && comparePermissionInfos(bp.perm.info, info)) { 2564 changed = false; 2565 } 2566 } 2567 bp.protectionLevel = fixedLevel; 2568 info = new PermissionInfo(info); 2569 info.protectionLevel = fixedLevel; 2570 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2571 bp.perm.info.packageName = tree.perm.info.packageName; 2572 bp.uid = tree.uid; 2573 if (added) { 2574 mSettings.mPermissions.put(info.name, bp); 2575 } 2576 if (changed) { 2577 if (!async) { 2578 mSettings.writeLPr(); 2579 } else { 2580 scheduleWriteSettingsLocked(); 2581 } 2582 } 2583 return added; 2584 } 2585 2586 @Override 2587 public boolean addPermission(PermissionInfo info) { 2588 synchronized (mPackages) { 2589 return addPermissionLocked(info, false); 2590 } 2591 } 2592 2593 @Override 2594 public boolean addPermissionAsync(PermissionInfo info) { 2595 synchronized (mPackages) { 2596 return addPermissionLocked(info, true); 2597 } 2598 } 2599 2600 @Override 2601 public void removePermission(String name) { 2602 synchronized (mPackages) { 2603 checkPermissionTreeLP(name); 2604 BasePermission bp = mSettings.mPermissions.get(name); 2605 if (bp != null) { 2606 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2607 throw new SecurityException( 2608 "Not allowed to modify non-dynamic permission " 2609 + name); 2610 } 2611 mSettings.mPermissions.remove(name); 2612 mSettings.writeLPr(); 2613 } 2614 } 2615 } 2616 2617 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2618 int index = pkg.requestedPermissions.indexOf(bp.name); 2619 if (index == -1) { 2620 throw new SecurityException("Package " + pkg.packageName 2621 + " has not requested permission " + bp.name); 2622 } 2623 boolean isNormal = 2624 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2625 == PermissionInfo.PROTECTION_NORMAL); 2626 boolean isDangerous = 2627 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2628 == PermissionInfo.PROTECTION_DANGEROUS); 2629 boolean isDevelopment = 2630 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2631 2632 if (!isNormal && !isDangerous && !isDevelopment) { 2633 throw new SecurityException("Permission " + bp.name 2634 + " is not a changeable permission type"); 2635 } 2636 2637 if (isNormal || isDangerous) { 2638 if (pkg.requestedPermissionsRequired.get(index)) { 2639 throw new SecurityException("Can't change " + bp.name 2640 + ". It is required by the application"); 2641 } 2642 } 2643 } 2644 2645 @Override 2646 public void grantPermission(String packageName, String permissionName) { 2647 mContext.enforceCallingOrSelfPermission( 2648 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2649 synchronized (mPackages) { 2650 final PackageParser.Package pkg = mPackages.get(packageName); 2651 if (pkg == null) { 2652 throw new IllegalArgumentException("Unknown package: " + packageName); 2653 } 2654 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2655 if (bp == null) { 2656 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2657 } 2658 2659 checkGrantRevokePermissions(pkg, bp); 2660 2661 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2662 if (ps == null) { 2663 return; 2664 } 2665 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2666 if (gp.grantedPermissions.add(permissionName)) { 2667 if (ps.haveGids) { 2668 gp.gids = appendInts(gp.gids, bp.gids); 2669 } 2670 mSettings.writeLPr(); 2671 } 2672 } 2673 } 2674 2675 @Override 2676 public void revokePermission(String packageName, String permissionName) { 2677 int changedAppId = -1; 2678 2679 synchronized (mPackages) { 2680 final PackageParser.Package pkg = mPackages.get(packageName); 2681 if (pkg == null) { 2682 throw new IllegalArgumentException("Unknown package: " + packageName); 2683 } 2684 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2685 mContext.enforceCallingOrSelfPermission( 2686 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2687 } 2688 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2689 if (bp == null) { 2690 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2691 } 2692 2693 checkGrantRevokePermissions(pkg, bp); 2694 2695 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2696 if (ps == null) { 2697 return; 2698 } 2699 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2700 if (gp.grantedPermissions.remove(permissionName)) { 2701 gp.grantedPermissions.remove(permissionName); 2702 if (ps.haveGids) { 2703 gp.gids = removeInts(gp.gids, bp.gids); 2704 } 2705 mSettings.writeLPr(); 2706 changedAppId = ps.appId; 2707 } 2708 } 2709 2710 if (changedAppId >= 0) { 2711 // We changed the perm on someone, kill its processes. 2712 IActivityManager am = ActivityManagerNative.getDefault(); 2713 if (am != null) { 2714 final int callingUserId = UserHandle.getCallingUserId(); 2715 final long ident = Binder.clearCallingIdentity(); 2716 try { 2717 //XXX we should only revoke for the calling user's app permissions, 2718 // but for now we impact all users. 2719 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2720 // "revoke " + permissionName); 2721 int[] users = sUserManager.getUserIds(); 2722 for (int user : users) { 2723 am.killUid(UserHandle.getUid(user, changedAppId), 2724 "revoke " + permissionName); 2725 } 2726 } catch (RemoteException e) { 2727 } finally { 2728 Binder.restoreCallingIdentity(ident); 2729 } 2730 } 2731 } 2732 } 2733 2734 @Override 2735 public boolean isProtectedBroadcast(String actionName) { 2736 synchronized (mPackages) { 2737 return mProtectedBroadcasts.contains(actionName); 2738 } 2739 } 2740 2741 @Override 2742 public int checkSignatures(String pkg1, String pkg2) { 2743 synchronized (mPackages) { 2744 final PackageParser.Package p1 = mPackages.get(pkg1); 2745 final PackageParser.Package p2 = mPackages.get(pkg2); 2746 if (p1 == null || p1.mExtras == null 2747 || p2 == null || p2.mExtras == null) { 2748 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2749 } 2750 return compareSignatures(p1.mSignatures, p2.mSignatures); 2751 } 2752 } 2753 2754 @Override 2755 public int checkUidSignatures(int uid1, int uid2) { 2756 // Map to base uids. 2757 uid1 = UserHandle.getAppId(uid1); 2758 uid2 = UserHandle.getAppId(uid2); 2759 // reader 2760 synchronized (mPackages) { 2761 Signature[] s1; 2762 Signature[] s2; 2763 Object obj = mSettings.getUserIdLPr(uid1); 2764 if (obj != null) { 2765 if (obj instanceof SharedUserSetting) { 2766 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2767 } else if (obj instanceof PackageSetting) { 2768 s1 = ((PackageSetting)obj).signatures.mSignatures; 2769 } else { 2770 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2771 } 2772 } else { 2773 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2774 } 2775 obj = mSettings.getUserIdLPr(uid2); 2776 if (obj != null) { 2777 if (obj instanceof SharedUserSetting) { 2778 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2779 } else if (obj instanceof PackageSetting) { 2780 s2 = ((PackageSetting)obj).signatures.mSignatures; 2781 } else { 2782 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2783 } 2784 } else { 2785 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2786 } 2787 return compareSignatures(s1, s2); 2788 } 2789 } 2790 2791 /** 2792 * Compares two sets of signatures. Returns: 2793 * <br /> 2794 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2795 * <br /> 2796 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2797 * <br /> 2798 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2799 * <br /> 2800 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2801 * <br /> 2802 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2803 */ 2804 static int compareSignatures(Signature[] s1, Signature[] s2) { 2805 if (s1 == null) { 2806 return s2 == null 2807 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2808 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2809 } 2810 2811 if (s2 == null) { 2812 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2813 } 2814 2815 if (s1.length != s2.length) { 2816 return PackageManager.SIGNATURE_NO_MATCH; 2817 } 2818 2819 // Since both signature sets are of size 1, we can compare without HashSets. 2820 if (s1.length == 1) { 2821 return s1[0].equals(s2[0]) ? 2822 PackageManager.SIGNATURE_MATCH : 2823 PackageManager.SIGNATURE_NO_MATCH; 2824 } 2825 2826 ArraySet<Signature> set1 = new ArraySet<Signature>(); 2827 for (Signature sig : s1) { 2828 set1.add(sig); 2829 } 2830 ArraySet<Signature> set2 = new ArraySet<Signature>(); 2831 for (Signature sig : s2) { 2832 set2.add(sig); 2833 } 2834 // Make sure s2 contains all signatures in s1. 2835 if (set1.equals(set2)) { 2836 return PackageManager.SIGNATURE_MATCH; 2837 } 2838 return PackageManager.SIGNATURE_NO_MATCH; 2839 } 2840 2841 /** 2842 * If the database version for this type of package (internal storage or 2843 * external storage) is less than the version where package signatures 2844 * were updated, return true. 2845 */ 2846 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2847 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2848 DatabaseVersion.SIGNATURE_END_ENTITY)) 2849 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2850 DatabaseVersion.SIGNATURE_END_ENTITY)); 2851 } 2852 2853 /** 2854 * Used for backward compatibility to make sure any packages with 2855 * certificate chains get upgraded to the new style. {@code existingSigs} 2856 * will be in the old format (since they were stored on disk from before the 2857 * system upgrade) and {@code scannedSigs} will be in the newer format. 2858 */ 2859 private int compareSignaturesCompat(PackageSignatures existingSigs, 2860 PackageParser.Package scannedPkg) { 2861 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2862 return PackageManager.SIGNATURE_NO_MATCH; 2863 } 2864 2865 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 2866 for (Signature sig : existingSigs.mSignatures) { 2867 existingSet.add(sig); 2868 } 2869 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 2870 for (Signature sig : scannedPkg.mSignatures) { 2871 try { 2872 Signature[] chainSignatures = sig.getChainSignatures(); 2873 for (Signature chainSig : chainSignatures) { 2874 scannedCompatSet.add(chainSig); 2875 } 2876 } catch (CertificateEncodingException e) { 2877 scannedCompatSet.add(sig); 2878 } 2879 } 2880 /* 2881 * Make sure the expanded scanned set contains all signatures in the 2882 * existing one. 2883 */ 2884 if (scannedCompatSet.equals(existingSet)) { 2885 // Migrate the old signatures to the new scheme. 2886 existingSigs.assignSignatures(scannedPkg.mSignatures); 2887 // The new KeySets will be re-added later in the scanning process. 2888 synchronized (mPackages) { 2889 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2890 } 2891 return PackageManager.SIGNATURE_MATCH; 2892 } 2893 return PackageManager.SIGNATURE_NO_MATCH; 2894 } 2895 2896 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2897 if (isExternal(scannedPkg)) { 2898 return mSettings.isExternalDatabaseVersionOlderThan( 2899 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2900 } else { 2901 return mSettings.isInternalDatabaseVersionOlderThan( 2902 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2903 } 2904 } 2905 2906 private int compareSignaturesRecover(PackageSignatures existingSigs, 2907 PackageParser.Package scannedPkg) { 2908 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 2909 return PackageManager.SIGNATURE_NO_MATCH; 2910 } 2911 2912 String msg = null; 2913 try { 2914 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 2915 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 2916 + scannedPkg.packageName); 2917 return PackageManager.SIGNATURE_MATCH; 2918 } 2919 } catch (CertificateException e) { 2920 msg = e.getMessage(); 2921 } 2922 2923 logCriticalInfo(Log.INFO, 2924 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 2925 return PackageManager.SIGNATURE_NO_MATCH; 2926 } 2927 2928 @Override 2929 public String[] getPackagesForUid(int uid) { 2930 uid = UserHandle.getAppId(uid); 2931 // reader 2932 synchronized (mPackages) { 2933 Object obj = mSettings.getUserIdLPr(uid); 2934 if (obj instanceof SharedUserSetting) { 2935 final SharedUserSetting sus = (SharedUserSetting) obj; 2936 final int N = sus.packages.size(); 2937 final String[] res = new String[N]; 2938 final Iterator<PackageSetting> it = sus.packages.iterator(); 2939 int i = 0; 2940 while (it.hasNext()) { 2941 res[i++] = it.next().name; 2942 } 2943 return res; 2944 } else if (obj instanceof PackageSetting) { 2945 final PackageSetting ps = (PackageSetting) obj; 2946 return new String[] { ps.name }; 2947 } 2948 } 2949 return null; 2950 } 2951 2952 @Override 2953 public String getNameForUid(int uid) { 2954 // reader 2955 synchronized (mPackages) { 2956 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2957 if (obj instanceof SharedUserSetting) { 2958 final SharedUserSetting sus = (SharedUserSetting) obj; 2959 return sus.name + ":" + sus.userId; 2960 } else if (obj instanceof PackageSetting) { 2961 final PackageSetting ps = (PackageSetting) obj; 2962 return ps.name; 2963 } 2964 } 2965 return null; 2966 } 2967 2968 @Override 2969 public int getUidForSharedUser(String sharedUserName) { 2970 if(sharedUserName == null) { 2971 return -1; 2972 } 2973 // reader 2974 synchronized (mPackages) { 2975 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 2976 if (suid == null) { 2977 return -1; 2978 } 2979 return suid.userId; 2980 } 2981 } 2982 2983 @Override 2984 public int getFlagsForUid(int uid) { 2985 synchronized (mPackages) { 2986 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2987 if (obj instanceof SharedUserSetting) { 2988 final SharedUserSetting sus = (SharedUserSetting) obj; 2989 return sus.pkgFlags; 2990 } else if (obj instanceof PackageSetting) { 2991 final PackageSetting ps = (PackageSetting) obj; 2992 return ps.pkgFlags; 2993 } 2994 } 2995 return 0; 2996 } 2997 2998 @Override 2999 public int getPrivateFlagsForUid(int uid) { 3000 synchronized (mPackages) { 3001 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3002 if (obj instanceof SharedUserSetting) { 3003 final SharedUserSetting sus = (SharedUserSetting) obj; 3004 return sus.pkgPrivateFlags; 3005 } else if (obj instanceof PackageSetting) { 3006 final PackageSetting ps = (PackageSetting) obj; 3007 return ps.pkgPrivateFlags; 3008 } 3009 } 3010 return 0; 3011 } 3012 3013 @Override 3014 public boolean isUidPrivileged(int uid) { 3015 uid = UserHandle.getAppId(uid); 3016 // reader 3017 synchronized (mPackages) { 3018 Object obj = mSettings.getUserIdLPr(uid); 3019 if (obj instanceof SharedUserSetting) { 3020 final SharedUserSetting sus = (SharedUserSetting) obj; 3021 final Iterator<PackageSetting> it = sus.packages.iterator(); 3022 while (it.hasNext()) { 3023 if (it.next().isPrivileged()) { 3024 return true; 3025 } 3026 } 3027 } else if (obj instanceof PackageSetting) { 3028 final PackageSetting ps = (PackageSetting) obj; 3029 return ps.isPrivileged(); 3030 } 3031 } 3032 return false; 3033 } 3034 3035 @Override 3036 public String[] getAppOpPermissionPackages(String permissionName) { 3037 synchronized (mPackages) { 3038 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3039 if (pkgs == null) { 3040 return null; 3041 } 3042 return pkgs.toArray(new String[pkgs.size()]); 3043 } 3044 } 3045 3046 @Override 3047 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3048 int flags, int userId) { 3049 if (!sUserManager.exists(userId)) return null; 3050 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3051 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3052 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3053 } 3054 3055 @Override 3056 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3057 IntentFilter filter, int match, ComponentName activity) { 3058 final int userId = UserHandle.getCallingUserId(); 3059 if (DEBUG_PREFERRED) { 3060 Log.v(TAG, "setLastChosenActivity intent=" + intent 3061 + " resolvedType=" + resolvedType 3062 + " flags=" + flags 3063 + " filter=" + filter 3064 + " match=" + match 3065 + " activity=" + activity); 3066 filter.dump(new PrintStreamPrinter(System.out), " "); 3067 } 3068 intent.setComponent(null); 3069 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3070 // Find any earlier preferred or last chosen entries and nuke them 3071 findPreferredActivity(intent, resolvedType, 3072 flags, query, 0, false, true, false, userId); 3073 // Add the new activity as the last chosen for this filter 3074 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3075 "Setting last chosen"); 3076 } 3077 3078 @Override 3079 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3080 final int userId = UserHandle.getCallingUserId(); 3081 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3082 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3083 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3084 false, false, false, userId); 3085 } 3086 3087 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3088 int flags, List<ResolveInfo> query, int userId) { 3089 if (query != null) { 3090 final int N = query.size(); 3091 if (N == 1) { 3092 return query.get(0); 3093 } else if (N > 1) { 3094 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3095 // If there is more than one activity with the same priority, 3096 // then let the user decide between them. 3097 ResolveInfo r0 = query.get(0); 3098 ResolveInfo r1 = query.get(1); 3099 if (DEBUG_INTENT_MATCHING || debug) { 3100 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3101 + r1.activityInfo.name + "=" + r1.priority); 3102 } 3103 // If the first activity has a higher priority, or a different 3104 // default, then it is always desireable to pick it. 3105 if (r0.priority != r1.priority 3106 || r0.preferredOrder != r1.preferredOrder 3107 || r0.isDefault != r1.isDefault) { 3108 return query.get(0); 3109 } 3110 // If we have saved a preference for a preferred activity for 3111 // this Intent, use that. 3112 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3113 flags, query, r0.priority, true, false, debug, userId); 3114 if (ri != null) { 3115 return ri; 3116 } 3117 if (userId != 0) { 3118 ri = new ResolveInfo(mResolveInfo); 3119 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3120 ri.activityInfo.applicationInfo = new ApplicationInfo( 3121 ri.activityInfo.applicationInfo); 3122 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3123 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3124 return ri; 3125 } 3126 return mResolveInfo; 3127 } 3128 } 3129 return null; 3130 } 3131 3132 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3133 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3134 final int N = query.size(); 3135 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3136 .get(userId); 3137 // Get the list of persistent preferred activities that handle the intent 3138 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3139 List<PersistentPreferredActivity> pprefs = ppir != null 3140 ? ppir.queryIntent(intent, resolvedType, 3141 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3142 : null; 3143 if (pprefs != null && pprefs.size() > 0) { 3144 final int M = pprefs.size(); 3145 for (int i=0; i<M; i++) { 3146 final PersistentPreferredActivity ppa = pprefs.get(i); 3147 if (DEBUG_PREFERRED || debug) { 3148 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3149 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3150 + "\n component=" + ppa.mComponent); 3151 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3152 } 3153 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3154 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3155 if (DEBUG_PREFERRED || debug) { 3156 Slog.v(TAG, "Found persistent preferred activity:"); 3157 if (ai != null) { 3158 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3159 } else { 3160 Slog.v(TAG, " null"); 3161 } 3162 } 3163 if (ai == null) { 3164 // This previously registered persistent preferred activity 3165 // component is no longer known. Ignore it and do NOT remove it. 3166 continue; 3167 } 3168 for (int j=0; j<N; j++) { 3169 final ResolveInfo ri = query.get(j); 3170 if (!ri.activityInfo.applicationInfo.packageName 3171 .equals(ai.applicationInfo.packageName)) { 3172 continue; 3173 } 3174 if (!ri.activityInfo.name.equals(ai.name)) { 3175 continue; 3176 } 3177 // Found a persistent preference that can handle the intent. 3178 if (DEBUG_PREFERRED || debug) { 3179 Slog.v(TAG, "Returning persistent preferred activity: " + 3180 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3181 } 3182 return ri; 3183 } 3184 } 3185 } 3186 return null; 3187 } 3188 3189 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3190 List<ResolveInfo> query, int priority, boolean always, 3191 boolean removeMatches, boolean debug, int userId) { 3192 if (!sUserManager.exists(userId)) return null; 3193 // writer 3194 synchronized (mPackages) { 3195 if (intent.getSelector() != null) { 3196 intent = intent.getSelector(); 3197 } 3198 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3199 3200 // Try to find a matching persistent preferred activity. 3201 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3202 debug, userId); 3203 3204 // If a persistent preferred activity matched, use it. 3205 if (pri != null) { 3206 return pri; 3207 } 3208 3209 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3210 // Get the list of preferred activities that handle the intent 3211 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3212 List<PreferredActivity> prefs = pir != null 3213 ? pir.queryIntent(intent, resolvedType, 3214 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3215 : null; 3216 if (prefs != null && prefs.size() > 0) { 3217 boolean changed = false; 3218 try { 3219 // First figure out how good the original match set is. 3220 // We will only allow preferred activities that came 3221 // from the same match quality. 3222 int match = 0; 3223 3224 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3225 3226 final int N = query.size(); 3227 for (int j=0; j<N; j++) { 3228 final ResolveInfo ri = query.get(j); 3229 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3230 + ": 0x" + Integer.toHexString(match)); 3231 if (ri.match > match) { 3232 match = ri.match; 3233 } 3234 } 3235 3236 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3237 + Integer.toHexString(match)); 3238 3239 match &= IntentFilter.MATCH_CATEGORY_MASK; 3240 final int M = prefs.size(); 3241 for (int i=0; i<M; i++) { 3242 final PreferredActivity pa = prefs.get(i); 3243 if (DEBUG_PREFERRED || debug) { 3244 Slog.v(TAG, "Checking PreferredActivity ds=" 3245 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3246 + "\n component=" + pa.mPref.mComponent); 3247 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3248 } 3249 if (pa.mPref.mMatch != match) { 3250 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3251 + Integer.toHexString(pa.mPref.mMatch)); 3252 continue; 3253 } 3254 // If it's not an "always" type preferred activity and that's what we're 3255 // looking for, skip it. 3256 if (always && !pa.mPref.mAlways) { 3257 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3258 continue; 3259 } 3260 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3261 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3262 if (DEBUG_PREFERRED || debug) { 3263 Slog.v(TAG, "Found preferred activity:"); 3264 if (ai != null) { 3265 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3266 } else { 3267 Slog.v(TAG, " null"); 3268 } 3269 } 3270 if (ai == null) { 3271 // This previously registered preferred activity 3272 // component is no longer known. Most likely an update 3273 // to the app was installed and in the new version this 3274 // component no longer exists. Clean it up by removing 3275 // it from the preferred activities list, and skip it. 3276 Slog.w(TAG, "Removing dangling preferred activity: " 3277 + pa.mPref.mComponent); 3278 pir.removeFilter(pa); 3279 changed = true; 3280 continue; 3281 } 3282 for (int j=0; j<N; j++) { 3283 final ResolveInfo ri = query.get(j); 3284 if (!ri.activityInfo.applicationInfo.packageName 3285 .equals(ai.applicationInfo.packageName)) { 3286 continue; 3287 } 3288 if (!ri.activityInfo.name.equals(ai.name)) { 3289 continue; 3290 } 3291 3292 if (removeMatches) { 3293 pir.removeFilter(pa); 3294 changed = true; 3295 if (DEBUG_PREFERRED) { 3296 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3297 } 3298 break; 3299 } 3300 3301 // Okay we found a previously set preferred or last chosen app. 3302 // If the result set is different from when this 3303 // was created, we need to clear it and re-ask the 3304 // user their preference, if we're looking for an "always" type entry. 3305 if (always && !pa.mPref.sameSet(query)) { 3306 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3307 + intent + " type " + resolvedType); 3308 if (DEBUG_PREFERRED) { 3309 Slog.v(TAG, "Removing preferred activity since set changed " 3310 + pa.mPref.mComponent); 3311 } 3312 pir.removeFilter(pa); 3313 // Re-add the filter as a "last chosen" entry (!always) 3314 PreferredActivity lastChosen = new PreferredActivity( 3315 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3316 pir.addFilter(lastChosen); 3317 changed = true; 3318 return null; 3319 } 3320 3321 // Yay! Either the set matched or we're looking for the last chosen 3322 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3323 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3324 return ri; 3325 } 3326 } 3327 } finally { 3328 if (changed) { 3329 if (DEBUG_PREFERRED) { 3330 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3331 } 3332 scheduleWritePackageRestrictionsLocked(userId); 3333 } 3334 } 3335 } 3336 } 3337 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3338 return null; 3339 } 3340 3341 /* 3342 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3343 */ 3344 @Override 3345 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3346 int targetUserId) { 3347 mContext.enforceCallingOrSelfPermission( 3348 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3349 List<CrossProfileIntentFilter> matches = 3350 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3351 if (matches != null) { 3352 int size = matches.size(); 3353 for (int i = 0; i < size; i++) { 3354 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3355 } 3356 } 3357 return false; 3358 } 3359 3360 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3361 String resolvedType, int userId) { 3362 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3363 if (resolver != null) { 3364 return resolver.queryIntent(intent, resolvedType, false, userId); 3365 } 3366 return null; 3367 } 3368 3369 @Override 3370 public List<ResolveInfo> queryIntentActivities(Intent intent, 3371 String resolvedType, int flags, int userId) { 3372 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3373 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3374 ComponentName comp = intent.getComponent(); 3375 if (comp == null) { 3376 if (intent.getSelector() != null) { 3377 intent = intent.getSelector(); 3378 comp = intent.getComponent(); 3379 } 3380 } 3381 3382 if (comp != null) { 3383 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3384 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3385 if (ai != null) { 3386 final ResolveInfo ri = new ResolveInfo(); 3387 ri.activityInfo = ai; 3388 list.add(ri); 3389 } 3390 return list; 3391 } 3392 3393 // reader 3394 synchronized (mPackages) { 3395 final String pkgName = intent.getPackage(); 3396 if (pkgName == null) { 3397 List<CrossProfileIntentFilter> matchingFilters = 3398 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3399 // Check for results that need to skip the current profile. 3400 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3401 resolvedType, flags, userId); 3402 if (resolveInfo != null) { 3403 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3404 result.add(resolveInfo); 3405 return result; 3406 } 3407 // Check for cross profile results. 3408 resolveInfo = queryCrossProfileIntents( 3409 matchingFilters, intent, resolvedType, flags, userId); 3410 3411 // Check for results in the current profile. 3412 List<ResolveInfo> result = mActivities.queryIntent( 3413 intent, resolvedType, flags, userId); 3414 if (resolveInfo != null) { 3415 result.add(resolveInfo); 3416 Collections.sort(result, mResolvePrioritySorter); 3417 } 3418 return result; 3419 } 3420 final PackageParser.Package pkg = mPackages.get(pkgName); 3421 if (pkg != null) { 3422 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3423 pkg.activities, userId); 3424 } 3425 return new ArrayList<ResolveInfo>(); 3426 } 3427 } 3428 3429 private ResolveInfo querySkipCurrentProfileIntents( 3430 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3431 int flags, int sourceUserId) { 3432 if (matchingFilters != null) { 3433 int size = matchingFilters.size(); 3434 for (int i = 0; i < size; i ++) { 3435 CrossProfileIntentFilter filter = matchingFilters.get(i); 3436 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3437 // Checking if there are activities in the target user that can handle the 3438 // intent. 3439 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3440 flags, sourceUserId); 3441 if (resolveInfo != null) { 3442 return resolveInfo; 3443 } 3444 } 3445 } 3446 } 3447 return null; 3448 } 3449 3450 // Return matching ResolveInfo if any for skip current profile intent filters. 3451 private ResolveInfo queryCrossProfileIntents( 3452 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3453 int flags, int sourceUserId) { 3454 if (matchingFilters != null) { 3455 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3456 // match the same intent. For performance reasons, it is better not to 3457 // run queryIntent twice for the same userId 3458 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3459 int size = matchingFilters.size(); 3460 for (int i = 0; i < size; i++) { 3461 CrossProfileIntentFilter filter = matchingFilters.get(i); 3462 int targetUserId = filter.getTargetUserId(); 3463 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3464 && !alreadyTriedUserIds.get(targetUserId)) { 3465 // Checking if there are activities in the target user that can handle the 3466 // intent. 3467 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3468 flags, sourceUserId); 3469 if (resolveInfo != null) return resolveInfo; 3470 alreadyTriedUserIds.put(targetUserId, true); 3471 } 3472 } 3473 } 3474 return null; 3475 } 3476 3477 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3478 String resolvedType, int flags, int sourceUserId) { 3479 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3480 resolvedType, flags, filter.getTargetUserId()); 3481 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3482 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3483 } 3484 return null; 3485 } 3486 3487 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3488 int sourceUserId, int targetUserId) { 3489 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3490 String className; 3491 if (targetUserId == UserHandle.USER_OWNER) { 3492 className = FORWARD_INTENT_TO_USER_OWNER; 3493 } else { 3494 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3495 } 3496 ComponentName forwardingActivityComponentName = new ComponentName( 3497 mAndroidApplication.packageName, className); 3498 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3499 sourceUserId); 3500 if (targetUserId == UserHandle.USER_OWNER) { 3501 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3502 forwardingResolveInfo.noResourceId = true; 3503 } 3504 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3505 forwardingResolveInfo.priority = 0; 3506 forwardingResolveInfo.preferredOrder = 0; 3507 forwardingResolveInfo.match = 0; 3508 forwardingResolveInfo.isDefault = true; 3509 forwardingResolveInfo.filter = filter; 3510 forwardingResolveInfo.targetUserId = targetUserId; 3511 return forwardingResolveInfo; 3512 } 3513 3514 @Override 3515 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3516 Intent[] specifics, String[] specificTypes, Intent intent, 3517 String resolvedType, int flags, int userId) { 3518 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3519 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3520 false, "query intent activity options"); 3521 final String resultsAction = intent.getAction(); 3522 3523 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3524 | PackageManager.GET_RESOLVED_FILTER, userId); 3525 3526 if (DEBUG_INTENT_MATCHING) { 3527 Log.v(TAG, "Query " + intent + ": " + results); 3528 } 3529 3530 int specificsPos = 0; 3531 int N; 3532 3533 // todo: note that the algorithm used here is O(N^2). This 3534 // isn't a problem in our current environment, but if we start running 3535 // into situations where we have more than 5 or 10 matches then this 3536 // should probably be changed to something smarter... 3537 3538 // First we go through and resolve each of the specific items 3539 // that were supplied, taking care of removing any corresponding 3540 // duplicate items in the generic resolve list. 3541 if (specifics != null) { 3542 for (int i=0; i<specifics.length; i++) { 3543 final Intent sintent = specifics[i]; 3544 if (sintent == null) { 3545 continue; 3546 } 3547 3548 if (DEBUG_INTENT_MATCHING) { 3549 Log.v(TAG, "Specific #" + i + ": " + sintent); 3550 } 3551 3552 String action = sintent.getAction(); 3553 if (resultsAction != null && resultsAction.equals(action)) { 3554 // If this action was explicitly requested, then don't 3555 // remove things that have it. 3556 action = null; 3557 } 3558 3559 ResolveInfo ri = null; 3560 ActivityInfo ai = null; 3561 3562 ComponentName comp = sintent.getComponent(); 3563 if (comp == null) { 3564 ri = resolveIntent( 3565 sintent, 3566 specificTypes != null ? specificTypes[i] : null, 3567 flags, userId); 3568 if (ri == null) { 3569 continue; 3570 } 3571 if (ri == mResolveInfo) { 3572 // ACK! Must do something better with this. 3573 } 3574 ai = ri.activityInfo; 3575 comp = new ComponentName(ai.applicationInfo.packageName, 3576 ai.name); 3577 } else { 3578 ai = getActivityInfo(comp, flags, userId); 3579 if (ai == null) { 3580 continue; 3581 } 3582 } 3583 3584 // Look for any generic query activities that are duplicates 3585 // of this specific one, and remove them from the results. 3586 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3587 N = results.size(); 3588 int j; 3589 for (j=specificsPos; j<N; j++) { 3590 ResolveInfo sri = results.get(j); 3591 if ((sri.activityInfo.name.equals(comp.getClassName()) 3592 && sri.activityInfo.applicationInfo.packageName.equals( 3593 comp.getPackageName())) 3594 || (action != null && sri.filter.matchAction(action))) { 3595 results.remove(j); 3596 if (DEBUG_INTENT_MATCHING) Log.v( 3597 TAG, "Removing duplicate item from " + j 3598 + " due to specific " + specificsPos); 3599 if (ri == null) { 3600 ri = sri; 3601 } 3602 j--; 3603 N--; 3604 } 3605 } 3606 3607 // Add this specific item to its proper place. 3608 if (ri == null) { 3609 ri = new ResolveInfo(); 3610 ri.activityInfo = ai; 3611 } 3612 results.add(specificsPos, ri); 3613 ri.specificIndex = i; 3614 specificsPos++; 3615 } 3616 } 3617 3618 // Now we go through the remaining generic results and remove any 3619 // duplicate actions that are found here. 3620 N = results.size(); 3621 for (int i=specificsPos; i<N-1; i++) { 3622 final ResolveInfo rii = results.get(i); 3623 if (rii.filter == null) { 3624 continue; 3625 } 3626 3627 // Iterate over all of the actions of this result's intent 3628 // filter... typically this should be just one. 3629 final Iterator<String> it = rii.filter.actionsIterator(); 3630 if (it == null) { 3631 continue; 3632 } 3633 while (it.hasNext()) { 3634 final String action = it.next(); 3635 if (resultsAction != null && resultsAction.equals(action)) { 3636 // If this action was explicitly requested, then don't 3637 // remove things that have it. 3638 continue; 3639 } 3640 for (int j=i+1; j<N; j++) { 3641 final ResolveInfo rij = results.get(j); 3642 if (rij.filter != null && rij.filter.hasAction(action)) { 3643 results.remove(j); 3644 if (DEBUG_INTENT_MATCHING) Log.v( 3645 TAG, "Removing duplicate item from " + j 3646 + " due to action " + action + " at " + i); 3647 j--; 3648 N--; 3649 } 3650 } 3651 } 3652 3653 // If the caller didn't request filter information, drop it now 3654 // so we don't have to marshall/unmarshall it. 3655 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3656 rii.filter = null; 3657 } 3658 } 3659 3660 // Filter out the caller activity if so requested. 3661 if (caller != null) { 3662 N = results.size(); 3663 for (int i=0; i<N; i++) { 3664 ActivityInfo ainfo = results.get(i).activityInfo; 3665 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3666 && caller.getClassName().equals(ainfo.name)) { 3667 results.remove(i); 3668 break; 3669 } 3670 } 3671 } 3672 3673 // If the caller didn't request filter information, 3674 // drop them now so we don't have to 3675 // marshall/unmarshall it. 3676 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3677 N = results.size(); 3678 for (int i=0; i<N; i++) { 3679 results.get(i).filter = null; 3680 } 3681 } 3682 3683 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3684 return results; 3685 } 3686 3687 @Override 3688 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3689 int userId) { 3690 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3691 ComponentName comp = intent.getComponent(); 3692 if (comp == null) { 3693 if (intent.getSelector() != null) { 3694 intent = intent.getSelector(); 3695 comp = intent.getComponent(); 3696 } 3697 } 3698 if (comp != null) { 3699 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3700 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3701 if (ai != null) { 3702 ResolveInfo ri = new ResolveInfo(); 3703 ri.activityInfo = ai; 3704 list.add(ri); 3705 } 3706 return list; 3707 } 3708 3709 // reader 3710 synchronized (mPackages) { 3711 String pkgName = intent.getPackage(); 3712 if (pkgName == null) { 3713 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3714 } 3715 final PackageParser.Package pkg = mPackages.get(pkgName); 3716 if (pkg != null) { 3717 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3718 userId); 3719 } 3720 return null; 3721 } 3722 } 3723 3724 @Override 3725 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3726 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3727 if (!sUserManager.exists(userId)) return null; 3728 if (query != null) { 3729 if (query.size() >= 1) { 3730 // If there is more than one service with the same priority, 3731 // just arbitrarily pick the first one. 3732 return query.get(0); 3733 } 3734 } 3735 return null; 3736 } 3737 3738 @Override 3739 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3740 int userId) { 3741 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3742 ComponentName comp = intent.getComponent(); 3743 if (comp == null) { 3744 if (intent.getSelector() != null) { 3745 intent = intent.getSelector(); 3746 comp = intent.getComponent(); 3747 } 3748 } 3749 if (comp != null) { 3750 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3751 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3752 if (si != null) { 3753 final ResolveInfo ri = new ResolveInfo(); 3754 ri.serviceInfo = si; 3755 list.add(ri); 3756 } 3757 return list; 3758 } 3759 3760 // reader 3761 synchronized (mPackages) { 3762 String pkgName = intent.getPackage(); 3763 if (pkgName == null) { 3764 return mServices.queryIntent(intent, resolvedType, flags, userId); 3765 } 3766 final PackageParser.Package pkg = mPackages.get(pkgName); 3767 if (pkg != null) { 3768 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3769 userId); 3770 } 3771 return null; 3772 } 3773 } 3774 3775 @Override 3776 public List<ResolveInfo> queryIntentContentProviders( 3777 Intent intent, String resolvedType, int flags, int userId) { 3778 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3779 ComponentName comp = intent.getComponent(); 3780 if (comp == null) { 3781 if (intent.getSelector() != null) { 3782 intent = intent.getSelector(); 3783 comp = intent.getComponent(); 3784 } 3785 } 3786 if (comp != null) { 3787 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3788 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3789 if (pi != null) { 3790 final ResolveInfo ri = new ResolveInfo(); 3791 ri.providerInfo = pi; 3792 list.add(ri); 3793 } 3794 return list; 3795 } 3796 3797 // reader 3798 synchronized (mPackages) { 3799 String pkgName = intent.getPackage(); 3800 if (pkgName == null) { 3801 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3802 } 3803 final PackageParser.Package pkg = mPackages.get(pkgName); 3804 if (pkg != null) { 3805 return mProviders.queryIntentForPackage( 3806 intent, resolvedType, flags, pkg.providers, userId); 3807 } 3808 return null; 3809 } 3810 } 3811 3812 @Override 3813 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3814 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3815 3816 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3817 3818 // writer 3819 synchronized (mPackages) { 3820 ArrayList<PackageInfo> list; 3821 if (listUninstalled) { 3822 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3823 for (PackageSetting ps : mSettings.mPackages.values()) { 3824 PackageInfo pi; 3825 if (ps.pkg != null) { 3826 pi = generatePackageInfo(ps.pkg, flags, userId); 3827 } else { 3828 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3829 } 3830 if (pi != null) { 3831 list.add(pi); 3832 } 3833 } 3834 } else { 3835 list = new ArrayList<PackageInfo>(mPackages.size()); 3836 for (PackageParser.Package p : mPackages.values()) { 3837 PackageInfo pi = generatePackageInfo(p, flags, userId); 3838 if (pi != null) { 3839 list.add(pi); 3840 } 3841 } 3842 } 3843 3844 return new ParceledListSlice<PackageInfo>(list); 3845 } 3846 } 3847 3848 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3849 String[] permissions, boolean[] tmp, int flags, int userId) { 3850 int numMatch = 0; 3851 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3852 for (int i=0; i<permissions.length; i++) { 3853 if (gp.grantedPermissions.contains(permissions[i])) { 3854 tmp[i] = true; 3855 numMatch++; 3856 } else { 3857 tmp[i] = false; 3858 } 3859 } 3860 if (numMatch == 0) { 3861 return; 3862 } 3863 PackageInfo pi; 3864 if (ps.pkg != null) { 3865 pi = generatePackageInfo(ps.pkg, flags, userId); 3866 } else { 3867 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3868 } 3869 // The above might return null in cases of uninstalled apps or install-state 3870 // skew across users/profiles. 3871 if (pi != null) { 3872 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3873 if (numMatch == permissions.length) { 3874 pi.requestedPermissions = permissions; 3875 } else { 3876 pi.requestedPermissions = new String[numMatch]; 3877 numMatch = 0; 3878 for (int i=0; i<permissions.length; i++) { 3879 if (tmp[i]) { 3880 pi.requestedPermissions[numMatch] = permissions[i]; 3881 numMatch++; 3882 } 3883 } 3884 } 3885 } 3886 list.add(pi); 3887 } 3888 } 3889 3890 @Override 3891 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3892 String[] permissions, int flags, int userId) { 3893 if (!sUserManager.exists(userId)) return null; 3894 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3895 3896 // writer 3897 synchronized (mPackages) { 3898 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3899 boolean[] tmpBools = new boolean[permissions.length]; 3900 if (listUninstalled) { 3901 for (PackageSetting ps : mSettings.mPackages.values()) { 3902 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3903 } 3904 } else { 3905 for (PackageParser.Package pkg : mPackages.values()) { 3906 PackageSetting ps = (PackageSetting)pkg.mExtras; 3907 if (ps != null) { 3908 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3909 userId); 3910 } 3911 } 3912 } 3913 3914 return new ParceledListSlice<PackageInfo>(list); 3915 } 3916 } 3917 3918 @Override 3919 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3920 if (!sUserManager.exists(userId)) return null; 3921 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3922 3923 // writer 3924 synchronized (mPackages) { 3925 ArrayList<ApplicationInfo> list; 3926 if (listUninstalled) { 3927 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3928 for (PackageSetting ps : mSettings.mPackages.values()) { 3929 ApplicationInfo ai; 3930 if (ps.pkg != null) { 3931 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3932 ps.readUserState(userId), userId); 3933 } else { 3934 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3935 } 3936 if (ai != null) { 3937 list.add(ai); 3938 } 3939 } 3940 } else { 3941 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3942 for (PackageParser.Package p : mPackages.values()) { 3943 if (p.mExtras != null) { 3944 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3945 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3946 if (ai != null) { 3947 list.add(ai); 3948 } 3949 } 3950 } 3951 } 3952 3953 return new ParceledListSlice<ApplicationInfo>(list); 3954 } 3955 } 3956 3957 public List<ApplicationInfo> getPersistentApplications(int flags) { 3958 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3959 3960 // reader 3961 synchronized (mPackages) { 3962 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3963 final int userId = UserHandle.getCallingUserId(); 3964 while (i.hasNext()) { 3965 final PackageParser.Package p = i.next(); 3966 if (p.applicationInfo != null 3967 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3968 && (!mSafeMode || isSystemApp(p))) { 3969 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3970 if (ps != null) { 3971 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3972 ps.readUserState(userId), userId); 3973 if (ai != null) { 3974 finalList.add(ai); 3975 } 3976 } 3977 } 3978 } 3979 } 3980 3981 return finalList; 3982 } 3983 3984 @Override 3985 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3986 if (!sUserManager.exists(userId)) return null; 3987 // reader 3988 synchronized (mPackages) { 3989 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3990 PackageSetting ps = provider != null 3991 ? mSettings.mPackages.get(provider.owner.packageName) 3992 : null; 3993 return ps != null 3994 && mSettings.isEnabledLPr(provider.info, flags, userId) 3995 && (!mSafeMode || (provider.info.applicationInfo.flags 3996 &ApplicationInfo.FLAG_SYSTEM) != 0) 3997 ? PackageParser.generateProviderInfo(provider, flags, 3998 ps.readUserState(userId), userId) 3999 : null; 4000 } 4001 } 4002 4003 /** 4004 * @deprecated 4005 */ 4006 @Deprecated 4007 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4008 // reader 4009 synchronized (mPackages) { 4010 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4011 .entrySet().iterator(); 4012 final int userId = UserHandle.getCallingUserId(); 4013 while (i.hasNext()) { 4014 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4015 PackageParser.Provider p = entry.getValue(); 4016 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4017 4018 if (ps != null && p.syncable 4019 && (!mSafeMode || (p.info.applicationInfo.flags 4020 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4021 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4022 ps.readUserState(userId), userId); 4023 if (info != null) { 4024 outNames.add(entry.getKey()); 4025 outInfo.add(info); 4026 } 4027 } 4028 } 4029 } 4030 } 4031 4032 @Override 4033 public List<ProviderInfo> queryContentProviders(String processName, 4034 int uid, int flags) { 4035 ArrayList<ProviderInfo> finalList = null; 4036 // reader 4037 synchronized (mPackages) { 4038 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4039 final int userId = processName != null ? 4040 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4041 while (i.hasNext()) { 4042 final PackageParser.Provider p = i.next(); 4043 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4044 if (ps != null && p.info.authority != null 4045 && (processName == null 4046 || (p.info.processName.equals(processName) 4047 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4048 && mSettings.isEnabledLPr(p.info, flags, userId) 4049 && (!mSafeMode 4050 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4051 if (finalList == null) { 4052 finalList = new ArrayList<ProviderInfo>(3); 4053 } 4054 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4055 ps.readUserState(userId), userId); 4056 if (info != null) { 4057 finalList.add(info); 4058 } 4059 } 4060 } 4061 } 4062 4063 if (finalList != null) { 4064 Collections.sort(finalList, mProviderInitOrderSorter); 4065 } 4066 4067 return finalList; 4068 } 4069 4070 @Override 4071 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4072 int flags) { 4073 // reader 4074 synchronized (mPackages) { 4075 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4076 return PackageParser.generateInstrumentationInfo(i, flags); 4077 } 4078 } 4079 4080 @Override 4081 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4082 int flags) { 4083 ArrayList<InstrumentationInfo> finalList = 4084 new ArrayList<InstrumentationInfo>(); 4085 4086 // reader 4087 synchronized (mPackages) { 4088 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4089 while (i.hasNext()) { 4090 final PackageParser.Instrumentation p = i.next(); 4091 if (targetPackage == null 4092 || targetPackage.equals(p.info.targetPackage)) { 4093 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4094 flags); 4095 if (ii != null) { 4096 finalList.add(ii); 4097 } 4098 } 4099 } 4100 } 4101 4102 return finalList; 4103 } 4104 4105 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4106 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4107 if (overlays == null) { 4108 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4109 return; 4110 } 4111 for (PackageParser.Package opkg : overlays.values()) { 4112 // Not much to do if idmap fails: we already logged the error 4113 // and we certainly don't want to abort installation of pkg simply 4114 // because an overlay didn't fit properly. For these reasons, 4115 // ignore the return value of createIdmapForPackagePairLI. 4116 createIdmapForPackagePairLI(pkg, opkg); 4117 } 4118 } 4119 4120 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4121 PackageParser.Package opkg) { 4122 if (!opkg.mTrustedOverlay) { 4123 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4124 opkg.baseCodePath + ": overlay not trusted"); 4125 return false; 4126 } 4127 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4128 if (overlaySet == null) { 4129 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4130 opkg.baseCodePath + " but target package has no known overlays"); 4131 return false; 4132 } 4133 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4134 // TODO: generate idmap for split APKs 4135 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4136 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4137 + opkg.baseCodePath); 4138 return false; 4139 } 4140 PackageParser.Package[] overlayArray = 4141 overlaySet.values().toArray(new PackageParser.Package[0]); 4142 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4143 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4144 return p1.mOverlayPriority - p2.mOverlayPriority; 4145 } 4146 }; 4147 Arrays.sort(overlayArray, cmp); 4148 4149 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4150 int i = 0; 4151 for (PackageParser.Package p : overlayArray) { 4152 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4153 } 4154 return true; 4155 } 4156 4157 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4158 final File[] files = dir.listFiles(); 4159 if (ArrayUtils.isEmpty(files)) { 4160 Log.d(TAG, "No files in app dir " + dir); 4161 return; 4162 } 4163 4164 if (DEBUG_PACKAGE_SCANNING) { 4165 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4166 + " flags=0x" + Integer.toHexString(parseFlags)); 4167 } 4168 4169 for (File file : files) { 4170 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4171 && !PackageInstallerService.isStageName(file.getName()); 4172 if (!isPackage) { 4173 // Ignore entries which are not packages 4174 continue; 4175 } 4176 try { 4177 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4178 scanFlags, currentTime, null); 4179 } catch (PackageManagerException e) { 4180 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4181 4182 // Delete invalid userdata apps 4183 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4184 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4185 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4186 if (file.isDirectory()) { 4187 mInstaller.rmPackageDir(file.getAbsolutePath()); 4188 } else { 4189 file.delete(); 4190 } 4191 } 4192 } 4193 } 4194 } 4195 4196 private static File getSettingsProblemFile() { 4197 File dataDir = Environment.getDataDirectory(); 4198 File systemDir = new File(dataDir, "system"); 4199 File fname = new File(systemDir, "uiderrors.txt"); 4200 return fname; 4201 } 4202 4203 static void reportSettingsProblem(int priority, String msg) { 4204 logCriticalInfo(priority, msg); 4205 } 4206 4207 static void logCriticalInfo(int priority, String msg) { 4208 Slog.println(priority, TAG, msg); 4209 EventLogTags.writePmCriticalInfo(msg); 4210 try { 4211 File fname = getSettingsProblemFile(); 4212 FileOutputStream out = new FileOutputStream(fname, true); 4213 PrintWriter pw = new FastPrintWriter(out); 4214 SimpleDateFormat formatter = new SimpleDateFormat(); 4215 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4216 pw.println(dateString + ": " + msg); 4217 pw.close(); 4218 FileUtils.setPermissions( 4219 fname.toString(), 4220 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4221 -1, -1); 4222 } catch (java.io.IOException e) { 4223 } 4224 } 4225 4226 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4227 PackageParser.Package pkg, File srcFile, int parseFlags) 4228 throws PackageManagerException { 4229 if (ps != null 4230 && ps.codePath.equals(srcFile) 4231 && ps.timeStamp == srcFile.lastModified() 4232 && !isCompatSignatureUpdateNeeded(pkg) 4233 && !isRecoverSignatureUpdateNeeded(pkg)) { 4234 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4235 if (ps.signatures.mSignatures != null 4236 && ps.signatures.mSignatures.length != 0 4237 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4238 // Optimization: reuse the existing cached certificates 4239 // if the package appears to be unchanged. 4240 pkg.mSignatures = ps.signatures.mSignatures; 4241 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4242 synchronized (mPackages) { 4243 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4244 } 4245 return; 4246 } 4247 4248 Slog.w(TAG, "PackageSetting for " + ps.name 4249 + " is missing signatures. Collecting certs again to recover them."); 4250 } else { 4251 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4252 } 4253 4254 try { 4255 pp.collectCertificates(pkg, parseFlags); 4256 pp.collectManifestDigest(pkg); 4257 } catch (PackageParserException e) { 4258 throw PackageManagerException.from(e); 4259 } 4260 } 4261 4262 /* 4263 * Scan a package and return the newly parsed package. 4264 * Returns null in case of errors and the error code is stored in mLastScanError 4265 */ 4266 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4267 long currentTime, UserHandle user) throws PackageManagerException { 4268 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4269 parseFlags |= mDefParseFlags; 4270 PackageParser pp = new PackageParser(); 4271 pp.setSeparateProcesses(mSeparateProcesses); 4272 pp.setOnlyCoreApps(mOnlyCore); 4273 pp.setDisplayMetrics(mMetrics); 4274 4275 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4276 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4277 } 4278 4279 final PackageParser.Package pkg; 4280 try { 4281 pkg = pp.parsePackage(scanFile, parseFlags); 4282 } catch (PackageParserException e) { 4283 throw PackageManagerException.from(e); 4284 } 4285 4286 PackageSetting ps = null; 4287 PackageSetting updatedPkg; 4288 // reader 4289 synchronized (mPackages) { 4290 // Look to see if we already know about this package. 4291 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4292 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4293 // This package has been renamed to its original name. Let's 4294 // use that. 4295 ps = mSettings.peekPackageLPr(oldName); 4296 } 4297 // If there was no original package, see one for the real package name. 4298 if (ps == null) { 4299 ps = mSettings.peekPackageLPr(pkg.packageName); 4300 } 4301 // Check to see if this package could be hiding/updating a system 4302 // package. Must look for it either under the original or real 4303 // package name depending on our state. 4304 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4305 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4306 } 4307 boolean updatedPkgBetter = false; 4308 // First check if this is a system package that may involve an update 4309 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4310 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4311 // it needs to drop FLAG_PRIVILEGED. 4312 if (locationIsPrivileged(scanFile)) { 4313 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4314 } else { 4315 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4316 } 4317 4318 if (ps != null && !ps.codePath.equals(scanFile)) { 4319 // The path has changed from what was last scanned... check the 4320 // version of the new path against what we have stored to determine 4321 // what to do. 4322 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4323 if (pkg.mVersionCode <= ps.versionCode) { 4324 // The system package has been updated and the code path does not match 4325 // Ignore entry. Skip it. 4326 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4327 + " ignored: updated version " + ps.versionCode 4328 + " better than this " + pkg.mVersionCode); 4329 if (!updatedPkg.codePath.equals(scanFile)) { 4330 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4331 + ps.name + " changing from " + updatedPkg.codePathString 4332 + " to " + scanFile); 4333 updatedPkg.codePath = scanFile; 4334 updatedPkg.codePathString = scanFile.toString(); 4335 updatedPkg.resourcePath = scanFile; 4336 updatedPkg.resourcePathString = scanFile.toString(); 4337 } 4338 updatedPkg.pkg = pkg; 4339 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4340 } else { 4341 // The current app on the system partition is better than 4342 // what we have updated to on the data partition; switch 4343 // back to the system partition version. 4344 // At this point, its safely assumed that package installation for 4345 // apps in system partition will go through. If not there won't be a working 4346 // version of the app 4347 // writer 4348 synchronized (mPackages) { 4349 // Just remove the loaded entries from package lists. 4350 mPackages.remove(ps.name); 4351 } 4352 4353 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4354 + " reverting from " + ps.codePathString 4355 + ": new version " + pkg.mVersionCode 4356 + " better than installed " + ps.versionCode); 4357 4358 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4359 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4360 getAppDexInstructionSets(ps)); 4361 synchronized (mInstallLock) { 4362 args.cleanUpResourcesLI(); 4363 } 4364 synchronized (mPackages) { 4365 mSettings.enableSystemPackageLPw(ps.name); 4366 } 4367 updatedPkgBetter = true; 4368 } 4369 } 4370 } 4371 4372 if (updatedPkg != null) { 4373 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4374 // initially 4375 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4376 4377 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4378 // flag set initially 4379 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4380 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4381 } 4382 } 4383 4384 // Verify certificates against what was last scanned 4385 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4386 4387 /* 4388 * A new system app appeared, but we already had a non-system one of the 4389 * same name installed earlier. 4390 */ 4391 boolean shouldHideSystemApp = false; 4392 if (updatedPkg == null && ps != null 4393 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4394 /* 4395 * Check to make sure the signatures match first. If they don't, 4396 * wipe the installed application and its data. 4397 */ 4398 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4399 != PackageManager.SIGNATURE_MATCH) { 4400 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4401 + " signatures don't match existing userdata copy; removing"); 4402 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4403 ps = null; 4404 } else { 4405 /* 4406 * If the newly-added system app is an older version than the 4407 * already installed version, hide it. It will be scanned later 4408 * and re-added like an update. 4409 */ 4410 if (pkg.mVersionCode <= ps.versionCode) { 4411 shouldHideSystemApp = true; 4412 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4413 + " but new version " + pkg.mVersionCode + " better than installed " 4414 + ps.versionCode + "; hiding system"); 4415 } else { 4416 /* 4417 * The newly found system app is a newer version that the 4418 * one previously installed. Simply remove the 4419 * already-installed application and replace it with our own 4420 * while keeping the application data. 4421 */ 4422 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4423 + " reverting from " + ps.codePathString + ": new version " 4424 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4425 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4426 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4427 getAppDexInstructionSets(ps)); 4428 synchronized (mInstallLock) { 4429 args.cleanUpResourcesLI(); 4430 } 4431 } 4432 } 4433 } 4434 4435 // The apk is forward locked (not public) if its code and resources 4436 // are kept in different files. (except for app in either system or 4437 // vendor path). 4438 // TODO grab this value from PackageSettings 4439 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4440 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4441 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4442 } 4443 } 4444 4445 // TODO: extend to support forward-locked splits 4446 String resourcePath = null; 4447 String baseResourcePath = null; 4448 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4449 if (ps != null && ps.resourcePathString != null) { 4450 resourcePath = ps.resourcePathString; 4451 baseResourcePath = ps.resourcePathString; 4452 } else { 4453 // Should not happen at all. Just log an error. 4454 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4455 } 4456 } else { 4457 resourcePath = pkg.codePath; 4458 baseResourcePath = pkg.baseCodePath; 4459 } 4460 4461 // Set application objects path explicitly. 4462 pkg.applicationInfo.setCodePath(pkg.codePath); 4463 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4464 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4465 pkg.applicationInfo.setResourcePath(resourcePath); 4466 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4467 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4468 4469 // Note that we invoke the following method only if we are about to unpack an application 4470 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4471 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4472 4473 /* 4474 * If the system app should be overridden by a previously installed 4475 * data, hide the system app now and let the /data/app scan pick it up 4476 * again. 4477 */ 4478 if (shouldHideSystemApp) { 4479 synchronized (mPackages) { 4480 /* 4481 * We have to grant systems permissions before we hide, because 4482 * grantPermissions will assume the package update is trying to 4483 * expand its permissions. 4484 */ 4485 grantPermissionsLPw(pkg, true, pkg.packageName); 4486 mSettings.disableSystemPackageLPw(pkg.packageName); 4487 } 4488 } 4489 4490 return scannedPkg; 4491 } 4492 4493 private static String fixProcessName(String defProcessName, 4494 String processName, int uid) { 4495 if (processName == null) { 4496 return defProcessName; 4497 } 4498 return processName; 4499 } 4500 4501 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4502 throws PackageManagerException { 4503 if (pkgSetting.signatures.mSignatures != null) { 4504 // Already existing package. Make sure signatures match 4505 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4506 == PackageManager.SIGNATURE_MATCH; 4507 if (!match) { 4508 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4509 == PackageManager.SIGNATURE_MATCH; 4510 } 4511 if (!match) { 4512 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 4513 == PackageManager.SIGNATURE_MATCH; 4514 } 4515 if (!match) { 4516 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4517 + pkg.packageName + " signatures do not match the " 4518 + "previously installed version; ignoring!"); 4519 } 4520 } 4521 4522 // Check for shared user signatures 4523 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4524 // Already existing package. Make sure signatures match 4525 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4526 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4527 if (!match) { 4528 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4529 == PackageManager.SIGNATURE_MATCH; 4530 } 4531 if (!match) { 4532 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 4533 == PackageManager.SIGNATURE_MATCH; 4534 } 4535 if (!match) { 4536 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4537 "Package " + pkg.packageName 4538 + " has no signatures that match those in shared user " 4539 + pkgSetting.sharedUser.name + "; ignoring!"); 4540 } 4541 } 4542 } 4543 4544 /** 4545 * Enforces that only the system UID or root's UID can call a method exposed 4546 * via Binder. 4547 * 4548 * @param message used as message if SecurityException is thrown 4549 * @throws SecurityException if the caller is not system or root 4550 */ 4551 private static final void enforceSystemOrRoot(String message) { 4552 final int uid = Binder.getCallingUid(); 4553 if (uid != Process.SYSTEM_UID && uid != 0) { 4554 throw new SecurityException(message); 4555 } 4556 } 4557 4558 @Override 4559 public void performBootDexOpt() { 4560 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4561 4562 // Before everything else, see whether we need to fstrim. 4563 try { 4564 IMountService ms = PackageHelper.getMountService(); 4565 if (ms != null) { 4566 final boolean isUpgrade = isUpgrade(); 4567 boolean doTrim = isUpgrade; 4568 if (doTrim) { 4569 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 4570 } else { 4571 final long interval = android.provider.Settings.Global.getLong( 4572 mContext.getContentResolver(), 4573 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 4574 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 4575 if (interval > 0) { 4576 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 4577 if (timeSinceLast > interval) { 4578 doTrim = true; 4579 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 4580 + "; running immediately"); 4581 } 4582 } 4583 } 4584 if (doTrim) { 4585 if (!isFirstBoot()) { 4586 try { 4587 ActivityManagerNative.getDefault().showBootMessage( 4588 mContext.getResources().getString( 4589 R.string.android_upgrading_fstrim), true); 4590 } catch (RemoteException e) { 4591 } 4592 } 4593 ms.runMaintenance(); 4594 } 4595 } else { 4596 Slog.e(TAG, "Mount service unavailable!"); 4597 } 4598 } catch (RemoteException e) { 4599 // Can't happen; MountService is local 4600 } 4601 4602 final ArraySet<PackageParser.Package> pkgs; 4603 synchronized (mPackages) { 4604 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 4605 } 4606 4607 if (pkgs != null) { 4608 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4609 // in case the device runs out of space. 4610 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4611 // Give priority to core apps. 4612 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4613 PackageParser.Package pkg = it.next(); 4614 if (pkg.coreApp) { 4615 if (DEBUG_DEXOPT) { 4616 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 4617 } 4618 sortedPkgs.add(pkg); 4619 it.remove(); 4620 } 4621 } 4622 // Give priority to system apps that listen for pre boot complete. 4623 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4624 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 4625 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4626 PackageParser.Package pkg = it.next(); 4627 if (pkgNames.contains(pkg.packageName)) { 4628 if (DEBUG_DEXOPT) { 4629 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 4630 } 4631 sortedPkgs.add(pkg); 4632 it.remove(); 4633 } 4634 } 4635 // Filter out packages that aren't recently used. 4636 filterRecentlyUsedApps(pkgs); 4637 // Add all remaining apps. 4638 for (PackageParser.Package pkg : pkgs) { 4639 if (DEBUG_DEXOPT) { 4640 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 4641 } 4642 sortedPkgs.add(pkg); 4643 } 4644 4645 // If we want to be lazy, filter everything that wasn't recently used. 4646 if (mLazyDexOpt) { 4647 filterRecentlyUsedApps(sortedPkgs); 4648 } 4649 4650 int i = 0; 4651 int total = sortedPkgs.size(); 4652 File dataDir = Environment.getDataDirectory(); 4653 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 4654 if (lowThreshold == 0) { 4655 throw new IllegalStateException("Invalid low memory threshold"); 4656 } 4657 for (PackageParser.Package pkg : sortedPkgs) { 4658 long usableSpace = dataDir.getUsableSpace(); 4659 if (usableSpace < lowThreshold) { 4660 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 4661 break; 4662 } 4663 performBootDexOpt(pkg, ++i, total); 4664 } 4665 } 4666 } 4667 4668 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 4669 // Filter out packages that aren't recently used. 4670 // 4671 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4672 // should do a full dexopt. 4673 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4674 int total = pkgs.size(); 4675 int skipped = 0; 4676 long now = System.currentTimeMillis(); 4677 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4678 PackageParser.Package pkg = i.next(); 4679 long then = pkg.mLastPackageUsageTimeInMills; 4680 if (then + mDexOptLRUThresholdInMills < now) { 4681 if (DEBUG_DEXOPT) { 4682 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4683 ((then == 0) ? "never" : new Date(then))); 4684 } 4685 i.remove(); 4686 skipped++; 4687 } 4688 } 4689 if (DEBUG_DEXOPT) { 4690 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4691 } 4692 } 4693 } 4694 4695 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 4696 List<ResolveInfo> ris = null; 4697 try { 4698 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4699 intent, null, 0, UserHandle.USER_OWNER); 4700 } catch (RemoteException e) { 4701 } 4702 ArraySet<String> pkgNames = new ArraySet<String>(); 4703 if (ris != null) { 4704 for (ResolveInfo ri : ris) { 4705 pkgNames.add(ri.activityInfo.packageName); 4706 } 4707 } 4708 return pkgNames; 4709 } 4710 4711 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4712 if (DEBUG_DEXOPT) { 4713 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4714 } 4715 if (!isFirstBoot()) { 4716 try { 4717 ActivityManagerNative.getDefault().showBootMessage( 4718 mContext.getResources().getString(R.string.android_upgrading_apk, 4719 curr, total), true); 4720 } catch (RemoteException e) { 4721 } 4722 } 4723 PackageParser.Package p = pkg; 4724 synchronized (mInstallLock) { 4725 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 4726 false /* force dex */, false /* defer */, true /* include dependencies */, 4727 false /* boot complete */); 4728 } 4729 } 4730 4731 @Override 4732 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4733 return performDexOpt(packageName, instructionSet, false); 4734 } 4735 4736 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4737 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4738 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4739 if (!dexopt && !updateUsage) { 4740 // We aren't going to dexopt or update usage, so bail early. 4741 return false; 4742 } 4743 PackageParser.Package p; 4744 final String targetInstructionSet; 4745 synchronized (mPackages) { 4746 p = mPackages.get(packageName); 4747 if (p == null) { 4748 return false; 4749 } 4750 if (updateUsage) { 4751 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4752 } 4753 mPackageUsage.write(false); 4754 if (!dexopt) { 4755 // We aren't going to dexopt, so bail early. 4756 return false; 4757 } 4758 4759 targetInstructionSet = instructionSet != null ? instructionSet : 4760 getPrimaryInstructionSet(p.applicationInfo); 4761 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4762 return false; 4763 } 4764 } 4765 4766 synchronized (mInstallLock) { 4767 final String[] instructionSets = new String[] { targetInstructionSet }; 4768 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 4769 false /* forceDex */, false /* defer */, true /* inclDependencies */, 4770 true /* boot complete */); 4771 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 4772 } 4773 } 4774 4775 public ArraySet<String> getPackagesThatNeedDexOpt() { 4776 ArraySet<String> pkgs = null; 4777 synchronized (mPackages) { 4778 for (PackageParser.Package p : mPackages.values()) { 4779 if (DEBUG_DEXOPT) { 4780 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4781 } 4782 if (!p.mDexOptPerformed.isEmpty()) { 4783 continue; 4784 } 4785 if (pkgs == null) { 4786 pkgs = new ArraySet<String>(); 4787 } 4788 pkgs.add(p.packageName); 4789 } 4790 } 4791 return pkgs; 4792 } 4793 4794 public void shutdown() { 4795 mPackageUsage.write(true); 4796 } 4797 4798 @Override 4799 public void forceDexOpt(String packageName) { 4800 enforceSystemOrRoot("forceDexOpt"); 4801 4802 PackageParser.Package pkg; 4803 synchronized (mPackages) { 4804 pkg = mPackages.get(packageName); 4805 if (pkg == null) { 4806 throw new IllegalArgumentException("Missing package: " + packageName); 4807 } 4808 } 4809 4810 synchronized (mInstallLock) { 4811 final String[] instructionSets = new String[] { 4812 getPrimaryInstructionSet(pkg.applicationInfo) }; 4813 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 4814 true /*forceDex*/, false /* defer */, true /* inclDependencies */, 4815 true /* boot complete */); 4816 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 4817 throw new IllegalStateException("Failed to dexopt: " + res); 4818 } 4819 } 4820 } 4821 4822 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4823 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4824 Slog.w(TAG, "Unable to update from " + oldPkg.name 4825 + " to " + newPkg.packageName 4826 + ": old package not in system partition"); 4827 return false; 4828 } else if (mPackages.get(oldPkg.name) != null) { 4829 Slog.w(TAG, "Unable to update from " + oldPkg.name 4830 + " to " + newPkg.packageName 4831 + ": old package still exists"); 4832 return false; 4833 } 4834 return true; 4835 } 4836 4837 private File getDataPathForPackage(String packageName, int userId) { 4838 /* 4839 * Until we fully support multiple users, return the directory we 4840 * previously would have. The PackageManagerTests will need to be 4841 * revised when this is changed back.. 4842 */ 4843 if (userId == 0) { 4844 return new File(mAppDataDir, packageName); 4845 } else { 4846 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4847 + File.separator + packageName); 4848 } 4849 } 4850 4851 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4852 int[] users = sUserManager.getUserIds(); 4853 int res = mInstaller.install(packageName, uid, uid, seinfo); 4854 if (res < 0) { 4855 return res; 4856 } 4857 for (int user : users) { 4858 if (user != 0) { 4859 res = mInstaller.createUserData(packageName, 4860 UserHandle.getUid(user, uid), user, seinfo); 4861 if (res < 0) { 4862 return res; 4863 } 4864 } 4865 } 4866 return res; 4867 } 4868 4869 private int removeDataDirsLI(String packageName) { 4870 int[] users = sUserManager.getUserIds(); 4871 int res = 0; 4872 for (int user : users) { 4873 int resInner = mInstaller.remove(packageName, user); 4874 if (resInner < 0) { 4875 res = resInner; 4876 } 4877 } 4878 4879 return res; 4880 } 4881 4882 private int deleteCodeCacheDirsLI(String packageName) { 4883 int[] users = sUserManager.getUserIds(); 4884 int res = 0; 4885 for (int user : users) { 4886 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4887 if (resInner < 0) { 4888 res = resInner; 4889 } 4890 } 4891 return res; 4892 } 4893 4894 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4895 PackageParser.Package changingLib) { 4896 if (file.path != null) { 4897 usesLibraryFiles.add(file.path); 4898 return; 4899 } 4900 PackageParser.Package p = mPackages.get(file.apk); 4901 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4902 // If we are doing this while in the middle of updating a library apk, 4903 // then we need to make sure to use that new apk for determining the 4904 // dependencies here. (We haven't yet finished committing the new apk 4905 // to the package manager state.) 4906 if (p == null || p.packageName.equals(changingLib.packageName)) { 4907 p = changingLib; 4908 } 4909 } 4910 if (p != null) { 4911 usesLibraryFiles.addAll(p.getAllCodePaths()); 4912 } 4913 } 4914 4915 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4916 PackageParser.Package changingLib) throws PackageManagerException { 4917 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4918 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4919 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4920 for (int i=0; i<N; i++) { 4921 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4922 if (file == null) { 4923 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4924 "Package " + pkg.packageName + " requires unavailable shared library " 4925 + pkg.usesLibraries.get(i) + "; failing!"); 4926 } 4927 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4928 } 4929 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4930 for (int i=0; i<N; i++) { 4931 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4932 if (file == null) { 4933 Slog.w(TAG, "Package " + pkg.packageName 4934 + " desires unavailable shared library " 4935 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4936 } else { 4937 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4938 } 4939 } 4940 N = usesLibraryFiles.size(); 4941 if (N > 0) { 4942 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4943 } else { 4944 pkg.usesLibraryFiles = null; 4945 } 4946 } 4947 } 4948 4949 private static boolean hasString(List<String> list, List<String> which) { 4950 if (list == null) { 4951 return false; 4952 } 4953 for (int i=list.size()-1; i>=0; i--) { 4954 for (int j=which.size()-1; j>=0; j--) { 4955 if (which.get(j).equals(list.get(i))) { 4956 return true; 4957 } 4958 } 4959 } 4960 return false; 4961 } 4962 4963 private void updateAllSharedLibrariesLPw() { 4964 for (PackageParser.Package pkg : mPackages.values()) { 4965 try { 4966 updateSharedLibrariesLPw(pkg, null); 4967 } catch (PackageManagerException e) { 4968 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4969 } 4970 } 4971 } 4972 4973 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4974 PackageParser.Package changingPkg) { 4975 ArrayList<PackageParser.Package> res = null; 4976 for (PackageParser.Package pkg : mPackages.values()) { 4977 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4978 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4979 if (res == null) { 4980 res = new ArrayList<PackageParser.Package>(); 4981 } 4982 res.add(pkg); 4983 try { 4984 updateSharedLibrariesLPw(pkg, changingPkg); 4985 } catch (PackageManagerException e) { 4986 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4987 } 4988 } 4989 } 4990 return res; 4991 } 4992 4993 /** 4994 * Derive the value of the {@code cpuAbiOverride} based on the provided 4995 * value and an optional stored value from the package settings. 4996 */ 4997 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 4998 String cpuAbiOverride = null; 4999 5000 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5001 cpuAbiOverride = null; 5002 } else if (abiOverride != null) { 5003 cpuAbiOverride = abiOverride; 5004 } else if (settings != null) { 5005 cpuAbiOverride = settings.cpuAbiOverrideString; 5006 } 5007 5008 return cpuAbiOverride; 5009 } 5010 5011 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5012 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5013 boolean success = false; 5014 try { 5015 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5016 currentTime, user); 5017 success = true; 5018 return res; 5019 } finally { 5020 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5021 removeDataDirsLI(pkg.packageName); 5022 } 5023 } 5024 } 5025 5026 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5027 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5028 final File scanFile = new File(pkg.codePath); 5029 if (pkg.applicationInfo.getCodePath() == null || 5030 pkg.applicationInfo.getResourcePath() == null) { 5031 // Bail out. The resource and code paths haven't been set. 5032 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5033 "Code and resource paths haven't been set correctly"); 5034 } 5035 5036 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5037 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5038 } else { 5039 // Only allow system apps to be flagged as core apps. 5040 pkg.coreApp = false; 5041 } 5042 5043 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5044 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5045 } 5046 5047 if (mCustomResolverComponentName != null && 5048 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5049 setUpCustomResolverActivity(pkg); 5050 } 5051 5052 if (pkg.packageName.equals("android")) { 5053 synchronized (mPackages) { 5054 if (mAndroidApplication != null) { 5055 Slog.w(TAG, "*************************************************"); 5056 Slog.w(TAG, "Core android package being redefined. Skipping."); 5057 Slog.w(TAG, " file=" + scanFile); 5058 Slog.w(TAG, "*************************************************"); 5059 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5060 "Core android package being redefined. Skipping."); 5061 } 5062 5063 // Set up information for our fall-back user intent resolution activity. 5064 mPlatformPackage = pkg; 5065 pkg.mVersionCode = mSdkVersion; 5066 mAndroidApplication = pkg.applicationInfo; 5067 5068 if (!mResolverReplaced) { 5069 mResolveActivity.applicationInfo = mAndroidApplication; 5070 mResolveActivity.name = ResolverActivity.class.getName(); 5071 mResolveActivity.packageName = mAndroidApplication.packageName; 5072 mResolveActivity.processName = "system:ui"; 5073 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5074 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5075 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5076 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5077 mResolveActivity.exported = true; 5078 mResolveActivity.enabled = true; 5079 mResolveInfo.activityInfo = mResolveActivity; 5080 mResolveInfo.priority = 0; 5081 mResolveInfo.preferredOrder = 0; 5082 mResolveInfo.match = 0; 5083 mResolveComponentName = new ComponentName( 5084 mAndroidApplication.packageName, mResolveActivity.name); 5085 } 5086 } 5087 } 5088 5089 if (DEBUG_PACKAGE_SCANNING) { 5090 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5091 Log.d(TAG, "Scanning package " + pkg.packageName); 5092 } 5093 5094 if (mPackages.containsKey(pkg.packageName) 5095 || mSharedLibraries.containsKey(pkg.packageName)) { 5096 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5097 "Application package " + pkg.packageName 5098 + " already installed. Skipping duplicate."); 5099 } 5100 5101 // Initialize package source and resource directories 5102 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5103 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5104 5105 SharedUserSetting suid = null; 5106 PackageSetting pkgSetting = null; 5107 5108 if (!isSystemApp(pkg)) { 5109 // Only system apps can use these features. 5110 pkg.mOriginalPackages = null; 5111 pkg.mRealPackage = null; 5112 pkg.mAdoptPermissions = null; 5113 } 5114 5115 // writer 5116 synchronized (mPackages) { 5117 if (pkg.mSharedUserId != null) { 5118 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5119 if (suid == null) { 5120 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5121 "Creating application package " + pkg.packageName 5122 + " for shared user failed"); 5123 } 5124 if (DEBUG_PACKAGE_SCANNING) { 5125 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5126 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5127 + "): packages=" + suid.packages); 5128 } 5129 } 5130 5131 // Check if we are renaming from an original package name. 5132 PackageSetting origPackage = null; 5133 String realName = null; 5134 if (pkg.mOriginalPackages != null) { 5135 // This package may need to be renamed to a previously 5136 // installed name. Let's check on that... 5137 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5138 if (pkg.mOriginalPackages.contains(renamed)) { 5139 // This package had originally been installed as the 5140 // original name, and we have already taken care of 5141 // transitioning to the new one. Just update the new 5142 // one to continue using the old name. 5143 realName = pkg.mRealPackage; 5144 if (!pkg.packageName.equals(renamed)) { 5145 // Callers into this function may have already taken 5146 // care of renaming the package; only do it here if 5147 // it is not already done. 5148 pkg.setPackageName(renamed); 5149 } 5150 5151 } else { 5152 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5153 if ((origPackage = mSettings.peekPackageLPr( 5154 pkg.mOriginalPackages.get(i))) != null) { 5155 // We do have the package already installed under its 5156 // original name... should we use it? 5157 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5158 // New package is not compatible with original. 5159 origPackage = null; 5160 continue; 5161 } else if (origPackage.sharedUser != null) { 5162 // Make sure uid is compatible between packages. 5163 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5164 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5165 + " to " + pkg.packageName + ": old uid " 5166 + origPackage.sharedUser.name 5167 + " differs from " + pkg.mSharedUserId); 5168 origPackage = null; 5169 continue; 5170 } 5171 } else { 5172 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5173 + pkg.packageName + " to old name " + origPackage.name); 5174 } 5175 break; 5176 } 5177 } 5178 } 5179 } 5180 5181 if (mTransferedPackages.contains(pkg.packageName)) { 5182 Slog.w(TAG, "Package " + pkg.packageName 5183 + " was transferred to another, but its .apk remains"); 5184 } 5185 5186 // Just create the setting, don't add it yet. For already existing packages 5187 // the PkgSetting exists already and doesn't have to be created. 5188 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5189 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5190 pkg.applicationInfo.primaryCpuAbi, 5191 pkg.applicationInfo.secondaryCpuAbi, 5192 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5193 user, false); 5194 if (pkgSetting == null) { 5195 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5196 "Creating application package " + pkg.packageName + " failed"); 5197 } 5198 5199 if (pkgSetting.origPackage != null) { 5200 // If we are first transitioning from an original package, 5201 // fix up the new package's name now. We need to do this after 5202 // looking up the package under its new name, so getPackageLP 5203 // can take care of fiddling things correctly. 5204 pkg.setPackageName(origPackage.name); 5205 5206 // File a report about this. 5207 String msg = "New package " + pkgSetting.realName 5208 + " renamed to replace old package " + pkgSetting.name; 5209 reportSettingsProblem(Log.WARN, msg); 5210 5211 // Make a note of it. 5212 mTransferedPackages.add(origPackage.name); 5213 5214 // No longer need to retain this. 5215 pkgSetting.origPackage = null; 5216 } 5217 5218 if (realName != null) { 5219 // Make a note of it. 5220 mTransferedPackages.add(pkg.packageName); 5221 } 5222 5223 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5224 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5225 } 5226 5227 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5228 // Check all shared libraries and map to their actual file path. 5229 // We only do this here for apps not on a system dir, because those 5230 // are the only ones that can fail an install due to this. We 5231 // will take care of the system apps by updating all of their 5232 // library paths after the scan is done. 5233 updateSharedLibrariesLPw(pkg, null); 5234 } 5235 5236 if (mFoundPolicyFile) { 5237 SELinuxMMAC.assignSeinfoValue(pkg); 5238 } 5239 5240 pkg.applicationInfo.uid = pkgSetting.appId; 5241 pkg.mExtras = pkgSetting; 5242 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5243 try { 5244 verifySignaturesLP(pkgSetting, pkg); 5245 // We just determined the app is signed correctly, so bring 5246 // over the latest parsed certs. 5247 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5248 } catch (PackageManagerException e) { 5249 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5250 throw e; 5251 } 5252 // The signature has changed, but this package is in the system 5253 // image... let's recover! 5254 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5255 // However... if this package is part of a shared user, but it 5256 // doesn't match the signature of the shared user, let's fail. 5257 // What this means is that you can't change the signatures 5258 // associated with an overall shared user, which doesn't seem all 5259 // that unreasonable. 5260 if (pkgSetting.sharedUser != null) { 5261 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5262 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5263 throw new PackageManagerException( 5264 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5265 "Signature mismatch for shared user : " 5266 + pkgSetting.sharedUser); 5267 } 5268 } 5269 // File a report about this. 5270 String msg = "System package " + pkg.packageName 5271 + " signature changed; retaining data."; 5272 reportSettingsProblem(Log.WARN, msg); 5273 } 5274 } else { 5275 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5276 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5277 + pkg.packageName + " upgrade keys do not match the " 5278 + "previously installed version"); 5279 } else { 5280 // We just determined the app is signed correctly, so bring 5281 // over the latest parsed certs. 5282 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5283 } 5284 } 5285 // Verify that this new package doesn't have any content providers 5286 // that conflict with existing packages. Only do this if the 5287 // package isn't already installed, since we don't want to break 5288 // things that are installed. 5289 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5290 final int N = pkg.providers.size(); 5291 int i; 5292 for (i=0; i<N; i++) { 5293 PackageParser.Provider p = pkg.providers.get(i); 5294 if (p.info.authority != null) { 5295 String names[] = p.info.authority.split(";"); 5296 for (int j = 0; j < names.length; j++) { 5297 if (mProvidersByAuthority.containsKey(names[j])) { 5298 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5299 final String otherPackageName = 5300 ((other != null && other.getComponentName() != null) ? 5301 other.getComponentName().getPackageName() : "?"); 5302 throw new PackageManagerException( 5303 INSTALL_FAILED_CONFLICTING_PROVIDER, 5304 "Can't install because provider name " + names[j] 5305 + " (in package " + pkg.applicationInfo.packageName 5306 + ") is already used by " + otherPackageName); 5307 } 5308 } 5309 } 5310 } 5311 } 5312 5313 if (pkg.mAdoptPermissions != null) { 5314 // This package wants to adopt ownership of permissions from 5315 // another package. 5316 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5317 final String origName = pkg.mAdoptPermissions.get(i); 5318 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5319 if (orig != null) { 5320 if (verifyPackageUpdateLPr(orig, pkg)) { 5321 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5322 + pkg.packageName); 5323 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5324 } 5325 } 5326 } 5327 } 5328 } 5329 5330 final String pkgName = pkg.packageName; 5331 5332 final long scanFileTime = scanFile.lastModified(); 5333 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5334 pkg.applicationInfo.processName = fixProcessName( 5335 pkg.applicationInfo.packageName, 5336 pkg.applicationInfo.processName, 5337 pkg.applicationInfo.uid); 5338 5339 File dataPath; 5340 if (mPlatformPackage == pkg) { 5341 // The system package is special. 5342 dataPath = new File(Environment.getDataDirectory(), "system"); 5343 5344 pkg.applicationInfo.dataDir = dataPath.getPath(); 5345 5346 } else { 5347 // This is a normal package, need to make its data directory. 5348 dataPath = getDataPathForPackage(pkg.packageName, 0); 5349 5350 boolean uidError = false; 5351 if (dataPath.exists()) { 5352 int currentUid = 0; 5353 try { 5354 StructStat stat = Os.stat(dataPath.getPath()); 5355 currentUid = stat.st_uid; 5356 } catch (ErrnoException e) { 5357 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5358 } 5359 5360 // If we have mismatched owners for the data path, we have a problem. 5361 if (currentUid != pkg.applicationInfo.uid) { 5362 boolean recovered = false; 5363 if (currentUid == 0) { 5364 // The directory somehow became owned by root. Wow. 5365 // This is probably because the system was stopped while 5366 // installd was in the middle of messing with its libs 5367 // directory. Ask installd to fix that. 5368 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5369 pkg.applicationInfo.uid); 5370 if (ret >= 0) { 5371 recovered = true; 5372 String msg = "Package " + pkg.packageName 5373 + " unexpectedly changed to uid 0; recovered to " + 5374 + pkg.applicationInfo.uid; 5375 reportSettingsProblem(Log.WARN, msg); 5376 } 5377 } 5378 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5379 || (scanFlags&SCAN_BOOTING) != 0)) { 5380 // If this is a system app, we can at least delete its 5381 // current data so the application will still work. 5382 int ret = removeDataDirsLI(pkgName); 5383 if (ret >= 0) { 5384 // TODO: Kill the processes first 5385 // Old data gone! 5386 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5387 ? "System package " : "Third party package "; 5388 String msg = prefix + pkg.packageName 5389 + " has changed from uid: " 5390 + currentUid + " to " 5391 + pkg.applicationInfo.uid + "; old data erased"; 5392 reportSettingsProblem(Log.WARN, msg); 5393 recovered = true; 5394 5395 // And now re-install the app. 5396 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5397 pkg.applicationInfo.seinfo); 5398 if (ret == -1) { 5399 // Ack should not happen! 5400 msg = prefix + pkg.packageName 5401 + " could not have data directory re-created after delete."; 5402 reportSettingsProblem(Log.WARN, msg); 5403 throw new PackageManagerException( 5404 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5405 } 5406 } 5407 if (!recovered) { 5408 mHasSystemUidErrors = true; 5409 } 5410 } else if (!recovered) { 5411 // If we allow this install to proceed, we will be broken. 5412 // Abort, abort! 5413 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5414 "scanPackageLI"); 5415 } 5416 if (!recovered) { 5417 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5418 + pkg.applicationInfo.uid + "/fs_" 5419 + currentUid; 5420 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5421 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5422 String msg = "Package " + pkg.packageName 5423 + " has mismatched uid: " 5424 + currentUid + " on disk, " 5425 + pkg.applicationInfo.uid + " in settings"; 5426 // writer 5427 synchronized (mPackages) { 5428 mSettings.mReadMessages.append(msg); 5429 mSettings.mReadMessages.append('\n'); 5430 uidError = true; 5431 if (!pkgSetting.uidError) { 5432 reportSettingsProblem(Log.ERROR, msg); 5433 } 5434 } 5435 } 5436 } 5437 pkg.applicationInfo.dataDir = dataPath.getPath(); 5438 if (mShouldRestoreconData) { 5439 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5440 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5441 pkg.applicationInfo.uid); 5442 } 5443 } else { 5444 if (DEBUG_PACKAGE_SCANNING) { 5445 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5446 Log.v(TAG, "Want this data dir: " + dataPath); 5447 } 5448 //invoke installer to do the actual installation 5449 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5450 pkg.applicationInfo.seinfo); 5451 if (ret < 0) { 5452 // Error from installer 5453 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5454 "Unable to create data dirs [errorCode=" + ret + "]"); 5455 } 5456 5457 if (dataPath.exists()) { 5458 pkg.applicationInfo.dataDir = dataPath.getPath(); 5459 } else { 5460 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5461 pkg.applicationInfo.dataDir = null; 5462 } 5463 } 5464 5465 pkgSetting.uidError = uidError; 5466 } 5467 5468 final String path = scanFile.getPath(); 5469 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5470 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5471 setBundledAppAbisAndRoots(pkg, pkgSetting); 5472 5473 // If we haven't found any native libraries for the app, check if it has 5474 // renderscript code. We'll need to force the app to 32 bit if it has 5475 // renderscript bitcode. 5476 if (pkg.applicationInfo.primaryCpuAbi == null 5477 && pkg.applicationInfo.secondaryCpuAbi == null 5478 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5479 NativeLibraryHelper.Handle handle = null; 5480 try { 5481 handle = NativeLibraryHelper.Handle.create(scanFile); 5482 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5483 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5484 } 5485 } catch (IOException ioe) { 5486 Slog.w(TAG, "Error scanning system app : " + ioe); 5487 } finally { 5488 IoUtils.closeQuietly(handle); 5489 } 5490 } 5491 5492 setNativeLibraryPaths(pkg); 5493 } else { 5494 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 5495 deriveNonSystemPackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 5496 } else { 5497 // TODO: We need this second call to derive in two cases : 5498 // 5499 // - To update the native library paths based on the final install location. 5500 // - We don't call dexopt when moving packages, and so we have to scan again. 5501 // 5502 // We can simplify this and avoid having to scan the package again by letting 5503 // scanPackageLI know if the current install was a move (and deriving things only 5504 // in that case) and by "reparenting" the native lib directory in the case of 5505 // a normal (non-move) install. 5506 deriveNonSystemPackageAbi(pkg, scanFile, cpuAbiOverride, false /* extract libs */); 5507 } 5508 5509 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5510 final int[] userIds = sUserManager.getUserIds(); 5511 synchronized (mInstallLock) { 5512 // Create a native library symlink only if we have native libraries 5513 // and if the native libraries are 32 bit libraries. We do not provide 5514 // this symlink for 64 bit libraries. 5515 if (pkg.applicationInfo.primaryCpuAbi != null && 5516 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5517 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5518 for (int userId : userIds) { 5519 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5520 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5521 "Failed linking native library dir (user=" + userId + ")"); 5522 } 5523 } 5524 } 5525 } 5526 } 5527 5528 // This is a special case for the "system" package, where the ABI is 5529 // dictated by the zygote configuration (and init.rc). We should keep track 5530 // of this ABI so that we can deal with "normal" applications that run under 5531 // the same UID correctly. 5532 if (mPlatformPackage == pkg) { 5533 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5534 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5535 } 5536 5537 // If there's a mismatch between the abi-override in the package setting 5538 // and the abiOverride specified for the install. Warn about this because we 5539 // would've already compiled the app without taking the package setting into 5540 // account. 5541 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 5542 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 5543 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 5544 " for package: " + pkg.packageName); 5545 } 5546 } 5547 5548 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5549 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5550 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5551 5552 // Copy the derived override back to the parsed package, so that we can 5553 // update the package settings accordingly. 5554 pkg.cpuAbiOverride = cpuAbiOverride; 5555 5556 if (DEBUG_ABI_SELECTION) { 5557 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5558 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5559 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5560 } 5561 5562 // Push the derived path down into PackageSettings so we know what to 5563 // clean up at uninstall time. 5564 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5565 5566 if (DEBUG_ABI_SELECTION) { 5567 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5568 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5569 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5570 } 5571 5572 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5573 // We don't do this here during boot because we can do it all 5574 // at once after scanning all existing packages. 5575 // 5576 // We also do this *before* we perform dexopt on this package, so that 5577 // we can avoid redundant dexopts, and also to make sure we've got the 5578 // code and package path correct. 5579 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5580 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */); 5581 } 5582 5583 if ((scanFlags & SCAN_NO_DEX) == 0) { 5584 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 5585 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */, 5586 (scanFlags & SCAN_BOOTING) == 0); 5587 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5588 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5589 } 5590 } 5591 if (mFactoryTest && pkg.requestedPermissions.contains( 5592 android.Manifest.permission.FACTORY_TEST)) { 5593 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5594 } 5595 5596 ArrayList<PackageParser.Package> clientLibPkgs = null; 5597 5598 // writer 5599 synchronized (mPackages) { 5600 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5601 // Only system apps can add new shared libraries. 5602 if (pkg.libraryNames != null) { 5603 for (int i=0; i<pkg.libraryNames.size(); i++) { 5604 String name = pkg.libraryNames.get(i); 5605 boolean allowed = false; 5606 if (pkg.isUpdatedSystemApp()) { 5607 // New library entries can only be added through the 5608 // system image. This is important to get rid of a lot 5609 // of nasty edge cases: for example if we allowed a non- 5610 // system update of the app to add a library, then uninstalling 5611 // the update would make the library go away, and assumptions 5612 // we made such as through app install filtering would now 5613 // have allowed apps on the device which aren't compatible 5614 // with it. Better to just have the restriction here, be 5615 // conservative, and create many fewer cases that can negatively 5616 // impact the user experience. 5617 final PackageSetting sysPs = mSettings 5618 .getDisabledSystemPkgLPr(pkg.packageName); 5619 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5620 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5621 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5622 allowed = true; 5623 allowed = true; 5624 break; 5625 } 5626 } 5627 } 5628 } else { 5629 allowed = true; 5630 } 5631 if (allowed) { 5632 if (!mSharedLibraries.containsKey(name)) { 5633 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5634 } else if (!name.equals(pkg.packageName)) { 5635 Slog.w(TAG, "Package " + pkg.packageName + " library " 5636 + name + " already exists; skipping"); 5637 } 5638 } else { 5639 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5640 + name + " that is not declared on system image; skipping"); 5641 } 5642 } 5643 if ((scanFlags&SCAN_BOOTING) == 0) { 5644 // If we are not booting, we need to update any applications 5645 // that are clients of our shared library. If we are booting, 5646 // this will all be done once the scan is complete. 5647 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5648 } 5649 } 5650 } 5651 } 5652 5653 // We also need to dexopt any apps that are dependent on this library. Note that 5654 // if these fail, we should abort the install since installing the library will 5655 // result in some apps being broken. 5656 if (clientLibPkgs != null) { 5657 if ((scanFlags & SCAN_NO_DEX) == 0) { 5658 for (int i = 0; i < clientLibPkgs.size(); i++) { 5659 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5660 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 5661 null /* instruction sets */, forceDex, 5662 (scanFlags & SCAN_DEFER_DEX) != 0, false, 5663 (scanFlags & SCAN_BOOTING) == 0); 5664 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5665 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5666 "scanPackageLI failed to dexopt clientLibPkgs"); 5667 } 5668 } 5669 } 5670 } 5671 5672 // Request the ActivityManager to kill the process(only for existing packages) 5673 // so that we do not end up in a confused state while the user is still using the older 5674 // version of the application while the new one gets installed. 5675 if ((scanFlags & SCAN_REPLACING) != 0) { 5676 killApplication(pkg.applicationInfo.packageName, 5677 pkg.applicationInfo.uid, "update pkg"); 5678 } 5679 5680 // Also need to kill any apps that are dependent on the library. 5681 if (clientLibPkgs != null) { 5682 for (int i=0; i<clientLibPkgs.size(); i++) { 5683 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5684 killApplication(clientPkg.applicationInfo.packageName, 5685 clientPkg.applicationInfo.uid, "update lib"); 5686 } 5687 } 5688 5689 // writer 5690 synchronized (mPackages) { 5691 // We don't expect installation to fail beyond this point 5692 5693 // Add the new setting to mSettings 5694 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5695 // Add the new setting to mPackages 5696 mPackages.put(pkg.applicationInfo.packageName, pkg); 5697 // Make sure we don't accidentally delete its data. 5698 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5699 while (iter.hasNext()) { 5700 PackageCleanItem item = iter.next(); 5701 if (pkgName.equals(item.packageName)) { 5702 iter.remove(); 5703 } 5704 } 5705 5706 // Take care of first install / last update times. 5707 if (currentTime != 0) { 5708 if (pkgSetting.firstInstallTime == 0) { 5709 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5710 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5711 pkgSetting.lastUpdateTime = currentTime; 5712 } 5713 } else if (pkgSetting.firstInstallTime == 0) { 5714 // We need *something*. Take time time stamp of the file. 5715 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5716 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5717 if (scanFileTime != pkgSetting.timeStamp) { 5718 // A package on the system image has changed; consider this 5719 // to be an update. 5720 pkgSetting.lastUpdateTime = scanFileTime; 5721 } 5722 } 5723 5724 // Add the package's KeySets to the global KeySetManagerService 5725 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5726 try { 5727 // Old KeySetData no longer valid. 5728 ksms.removeAppKeySetDataLPw(pkg.packageName); 5729 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5730 if (pkg.mKeySetMapping != null) { 5731 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5732 pkg.mKeySetMapping.entrySet()) { 5733 if (entry.getValue() != null) { 5734 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5735 entry.getValue(), entry.getKey()); 5736 } 5737 } 5738 if (pkg.mUpgradeKeySets != null) { 5739 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5740 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5741 } 5742 } 5743 } 5744 } catch (NullPointerException e) { 5745 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5746 } catch (IllegalArgumentException e) { 5747 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5748 } 5749 5750 int N = pkg.providers.size(); 5751 StringBuilder r = null; 5752 int i; 5753 for (i=0; i<N; i++) { 5754 PackageParser.Provider p = pkg.providers.get(i); 5755 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5756 p.info.processName, pkg.applicationInfo.uid); 5757 mProviders.addProvider(p); 5758 p.syncable = p.info.isSyncable; 5759 if (p.info.authority != null) { 5760 String names[] = p.info.authority.split(";"); 5761 p.info.authority = null; 5762 for (int j = 0; j < names.length; j++) { 5763 if (j == 1 && p.syncable) { 5764 // We only want the first authority for a provider to possibly be 5765 // syncable, so if we already added this provider using a different 5766 // authority clear the syncable flag. We copy the provider before 5767 // changing it because the mProviders object contains a reference 5768 // to a provider that we don't want to change. 5769 // Only do this for the second authority since the resulting provider 5770 // object can be the same for all future authorities for this provider. 5771 p = new PackageParser.Provider(p); 5772 p.syncable = false; 5773 } 5774 if (!mProvidersByAuthority.containsKey(names[j])) { 5775 mProvidersByAuthority.put(names[j], p); 5776 if (p.info.authority == null) { 5777 p.info.authority = names[j]; 5778 } else { 5779 p.info.authority = p.info.authority + ";" + names[j]; 5780 } 5781 if (DEBUG_PACKAGE_SCANNING) { 5782 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5783 Log.d(TAG, "Registered content provider: " + names[j] 5784 + ", className = " + p.info.name + ", isSyncable = " 5785 + p.info.isSyncable); 5786 } 5787 } else { 5788 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5789 Slog.w(TAG, "Skipping provider name " + names[j] + 5790 " (in package " + pkg.applicationInfo.packageName + 5791 "): name already used by " 5792 + ((other != null && other.getComponentName() != null) 5793 ? other.getComponentName().getPackageName() : "?")); 5794 } 5795 } 5796 } 5797 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5798 if (r == null) { 5799 r = new StringBuilder(256); 5800 } else { 5801 r.append(' '); 5802 } 5803 r.append(p.info.name); 5804 } 5805 } 5806 if (r != null) { 5807 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5808 } 5809 5810 N = pkg.services.size(); 5811 r = null; 5812 for (i=0; i<N; i++) { 5813 PackageParser.Service s = pkg.services.get(i); 5814 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5815 s.info.processName, pkg.applicationInfo.uid); 5816 mServices.addService(s); 5817 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5818 if (r == null) { 5819 r = new StringBuilder(256); 5820 } else { 5821 r.append(' '); 5822 } 5823 r.append(s.info.name); 5824 } 5825 } 5826 if (r != null) { 5827 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5828 } 5829 5830 N = pkg.receivers.size(); 5831 r = null; 5832 for (i=0; i<N; i++) { 5833 PackageParser.Activity a = pkg.receivers.get(i); 5834 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5835 a.info.processName, pkg.applicationInfo.uid); 5836 mReceivers.addActivity(a, "receiver"); 5837 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5838 if (r == null) { 5839 r = new StringBuilder(256); 5840 } else { 5841 r.append(' '); 5842 } 5843 r.append(a.info.name); 5844 } 5845 } 5846 if (r != null) { 5847 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5848 } 5849 5850 N = pkg.activities.size(); 5851 r = null; 5852 for (i=0; i<N; i++) { 5853 PackageParser.Activity a = pkg.activities.get(i); 5854 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5855 a.info.processName, pkg.applicationInfo.uid); 5856 mActivities.addActivity(a, "activity"); 5857 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5858 if (r == null) { 5859 r = new StringBuilder(256); 5860 } else { 5861 r.append(' '); 5862 } 5863 r.append(a.info.name); 5864 } 5865 } 5866 if (r != null) { 5867 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5868 } 5869 5870 N = pkg.permissionGroups.size(); 5871 r = null; 5872 for (i=0; i<N; i++) { 5873 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5874 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5875 if (cur == null) { 5876 mPermissionGroups.put(pg.info.name, pg); 5877 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5878 if (r == null) { 5879 r = new StringBuilder(256); 5880 } else { 5881 r.append(' '); 5882 } 5883 r.append(pg.info.name); 5884 } 5885 } else { 5886 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5887 + pg.info.packageName + " ignored: original from " 5888 + cur.info.packageName); 5889 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5890 if (r == null) { 5891 r = new StringBuilder(256); 5892 } else { 5893 r.append(' '); 5894 } 5895 r.append("DUP:"); 5896 r.append(pg.info.name); 5897 } 5898 } 5899 } 5900 if (r != null) { 5901 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5902 } 5903 5904 N = pkg.permissions.size(); 5905 r = null; 5906 for (i=0; i<N; i++) { 5907 PackageParser.Permission p = pkg.permissions.get(i); 5908 ArrayMap<String, BasePermission> permissionMap = 5909 p.tree ? mSettings.mPermissionTrees 5910 : mSettings.mPermissions; 5911 p.group = mPermissionGroups.get(p.info.group); 5912 if (p.info.group == null || p.group != null) { 5913 BasePermission bp = permissionMap.get(p.info.name); 5914 5915 // Allow system apps to redefine non-system permissions 5916 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 5917 final boolean currentOwnerIsSystem = (bp.perm != null 5918 && isSystemApp(bp.perm.owner)); 5919 if (isSystemApp(p.owner)) { 5920 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 5921 // It's a built-in permission and no owner, take ownership now 5922 bp.packageSetting = pkgSetting; 5923 bp.perm = p; 5924 bp.uid = pkg.applicationInfo.uid; 5925 bp.sourcePackage = p.info.packageName; 5926 } else if (!currentOwnerIsSystem) { 5927 String msg = "New decl " + p.owner + " of permission " 5928 + p.info.name + " is system; overriding " + bp.sourcePackage; 5929 reportSettingsProblem(Log.WARN, msg); 5930 bp = null; 5931 } 5932 } 5933 } 5934 5935 if (bp == null) { 5936 bp = new BasePermission(p.info.name, p.info.packageName, 5937 BasePermission.TYPE_NORMAL); 5938 permissionMap.put(p.info.name, bp); 5939 } 5940 5941 if (bp.perm == null) { 5942 if (bp.sourcePackage == null 5943 || bp.sourcePackage.equals(p.info.packageName)) { 5944 BasePermission tree = findPermissionTreeLP(p.info.name); 5945 if (tree == null 5946 || tree.sourcePackage.equals(p.info.packageName)) { 5947 bp.packageSetting = pkgSetting; 5948 bp.perm = p; 5949 bp.uid = pkg.applicationInfo.uid; 5950 bp.sourcePackage = p.info.packageName; 5951 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5952 if (r == null) { 5953 r = new StringBuilder(256); 5954 } else { 5955 r.append(' '); 5956 } 5957 r.append(p.info.name); 5958 } 5959 } else { 5960 Slog.w(TAG, "Permission " + p.info.name + " from package " 5961 + p.info.packageName + " ignored: base tree " 5962 + tree.name + " is from package " 5963 + tree.sourcePackage); 5964 } 5965 } else { 5966 Slog.w(TAG, "Permission " + p.info.name + " from package " 5967 + p.info.packageName + " ignored: original from " 5968 + bp.sourcePackage); 5969 } 5970 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5971 if (r == null) { 5972 r = new StringBuilder(256); 5973 } else { 5974 r.append(' '); 5975 } 5976 r.append("DUP:"); 5977 r.append(p.info.name); 5978 } 5979 if (bp.perm == p) { 5980 bp.protectionLevel = p.info.protectionLevel; 5981 } 5982 } else { 5983 Slog.w(TAG, "Permission " + p.info.name + " from package " 5984 + p.info.packageName + " ignored: no group " 5985 + p.group); 5986 } 5987 } 5988 if (r != null) { 5989 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5990 } 5991 5992 N = pkg.instrumentation.size(); 5993 r = null; 5994 for (i=0; i<N; i++) { 5995 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5996 a.info.packageName = pkg.applicationInfo.packageName; 5997 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5998 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5999 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6000 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6001 a.info.dataDir = pkg.applicationInfo.dataDir; 6002 6003 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6004 // need other information about the application, like the ABI and what not ? 6005 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6006 mInstrumentation.put(a.getComponentName(), a); 6007 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6008 if (r == null) { 6009 r = new StringBuilder(256); 6010 } else { 6011 r.append(' '); 6012 } 6013 r.append(a.info.name); 6014 } 6015 } 6016 if (r != null) { 6017 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6018 } 6019 6020 if (pkg.protectedBroadcasts != null) { 6021 N = pkg.protectedBroadcasts.size(); 6022 for (i=0; i<N; i++) { 6023 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6024 } 6025 } 6026 6027 pkgSetting.setTimeStamp(scanFileTime); 6028 6029 // Create idmap files for pairs of (packages, overlay packages). 6030 // Note: "android", ie framework-res.apk, is handled by native layers. 6031 if (pkg.mOverlayTarget != null) { 6032 // This is an overlay package. 6033 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6034 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6035 mOverlays.put(pkg.mOverlayTarget, 6036 new ArrayMap<String, PackageParser.Package>()); 6037 } 6038 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6039 map.put(pkg.packageName, pkg); 6040 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6041 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6042 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6043 "scanPackageLI failed to createIdmap"); 6044 } 6045 } 6046 } else if (mOverlays.containsKey(pkg.packageName) && 6047 !pkg.packageName.equals("android")) { 6048 // This is a regular package, with one or more known overlay packages. 6049 createIdmapsForPackageLI(pkg); 6050 } 6051 } 6052 6053 return pkg; 6054 } 6055 6056 /** 6057 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6058 * is derived purely on the basis of the contents of {@code scanFile} and 6059 * {@code cpuAbiOverride}. 6060 * 6061 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6062 */ 6063 public void deriveNonSystemPackageAbi(PackageParser.Package pkg, File scanFile, 6064 String cpuAbiOverride, boolean extractLibs) 6065 throws PackageManagerException { 6066 // TODO: We can probably be smarter about this stuff. For installed apps, 6067 // we can calculate this information at install time once and for all. For 6068 // system apps, we can probably assume that this information doesn't change 6069 // after the first boot scan. As things stand, we do lots of unnecessary work. 6070 6071 // Give ourselves some initial paths; we'll come back for another 6072 // pass once we've determined ABI below. 6073 setNativeLibraryPaths(pkg); 6074 6075 // We would never need to extract libs for forward-locked and external packages, 6076 // since the container service will do it for us. 6077 if (pkg.isForwardLocked() || isExternal(pkg)) { 6078 extractLibs = false; 6079 } 6080 6081 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6082 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6083 6084 NativeLibraryHelper.Handle handle = null; 6085 try { 6086 handle = NativeLibraryHelper.Handle.create(scanFile); 6087 // TODO(multiArch): This can be null for apps that didn't go through the 6088 // usual installation process. We can calculate it again, like we 6089 // do during install time. 6090 // 6091 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6092 // unnecessary. 6093 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6094 6095 // Null out the abis so that they can be recalculated. 6096 pkg.applicationInfo.primaryCpuAbi = null; 6097 pkg.applicationInfo.secondaryCpuAbi = null; 6098 if (isMultiArch(pkg.applicationInfo)) { 6099 // Warn if we've set an abiOverride for multi-lib packages.. 6100 // By definition, we need to copy both 32 and 64 bit libraries for 6101 // such packages. 6102 if (pkg.cpuAbiOverride != null 6103 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6104 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6105 } 6106 6107 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6108 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6109 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6110 if (extractLibs) { 6111 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6112 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6113 useIsaSpecificSubdirs); 6114 } else { 6115 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6116 } 6117 } 6118 6119 maybeThrowExceptionForMultiArchCopy( 6120 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6121 6122 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6123 if (extractLibs) { 6124 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6125 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6126 useIsaSpecificSubdirs); 6127 } else { 6128 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6129 } 6130 } 6131 6132 maybeThrowExceptionForMultiArchCopy( 6133 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6134 6135 if (abi64 >= 0) { 6136 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6137 } 6138 6139 if (abi32 >= 0) { 6140 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6141 if (abi64 >= 0) { 6142 pkg.applicationInfo.secondaryCpuAbi = abi; 6143 } else { 6144 pkg.applicationInfo.primaryCpuAbi = abi; 6145 } 6146 } 6147 } else { 6148 String[] abiList = (cpuAbiOverride != null) ? 6149 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6150 6151 // Enable gross and lame hacks for apps that are built with old 6152 // SDK tools. We must scan their APKs for renderscript bitcode and 6153 // not launch them if it's present. Don't bother checking on devices 6154 // that don't have 64 bit support. 6155 boolean needsRenderScriptOverride = false; 6156 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6157 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6158 abiList = Build.SUPPORTED_32_BIT_ABIS; 6159 needsRenderScriptOverride = true; 6160 } 6161 6162 final int copyRet; 6163 if (extractLibs) { 6164 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6165 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6166 } else { 6167 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6168 } 6169 6170 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6171 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6172 "Error unpackaging native libs for app, errorCode=" + copyRet); 6173 } 6174 6175 if (copyRet >= 0) { 6176 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6177 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6178 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6179 } else if (needsRenderScriptOverride) { 6180 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6181 } 6182 } 6183 } catch (IOException ioe) { 6184 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6185 } finally { 6186 IoUtils.closeQuietly(handle); 6187 } 6188 6189 // Now that we've calculated the ABIs and determined if it's an internal app, 6190 // we will go ahead and populate the nativeLibraryPath. 6191 setNativeLibraryPaths(pkg); 6192 } 6193 6194 /** 6195 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6196 * i.e, so that all packages can be run inside a single process if required. 6197 * 6198 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6199 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6200 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6201 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6202 * updating a package that belongs to a shared user. 6203 * 6204 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6205 * adds unnecessary complexity. 6206 */ 6207 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6208 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt, 6209 boolean bootComplete) { 6210 String requiredInstructionSet = null; 6211 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6212 requiredInstructionSet = VMRuntime.getInstructionSet( 6213 scannedPackage.applicationInfo.primaryCpuAbi); 6214 } 6215 6216 PackageSetting requirer = null; 6217 for (PackageSetting ps : packagesForUser) { 6218 // If packagesForUser contains scannedPackage, we skip it. This will happen 6219 // when scannedPackage is an update of an existing package. Without this check, 6220 // we will never be able to change the ABI of any package belonging to a shared 6221 // user, even if it's compatible with other packages. 6222 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6223 if (ps.primaryCpuAbiString == null) { 6224 continue; 6225 } 6226 6227 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6228 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6229 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6230 // this but there's not much we can do. 6231 String errorMessage = "Instruction set mismatch, " 6232 + ((requirer == null) ? "[caller]" : requirer) 6233 + " requires " + requiredInstructionSet + " whereas " + ps 6234 + " requires " + instructionSet; 6235 Slog.w(TAG, errorMessage); 6236 } 6237 6238 if (requiredInstructionSet == null) { 6239 requiredInstructionSet = instructionSet; 6240 requirer = ps; 6241 } 6242 } 6243 } 6244 6245 if (requiredInstructionSet != null) { 6246 String adjustedAbi; 6247 if (requirer != null) { 6248 // requirer != null implies that either scannedPackage was null or that scannedPackage 6249 // did not require an ABI, in which case we have to adjust scannedPackage to match 6250 // the ABI of the set (which is the same as requirer's ABI) 6251 adjustedAbi = requirer.primaryCpuAbiString; 6252 if (scannedPackage != null) { 6253 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6254 } 6255 } else { 6256 // requirer == null implies that we're updating all ABIs in the set to 6257 // match scannedPackage. 6258 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6259 } 6260 6261 for (PackageSetting ps : packagesForUser) { 6262 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6263 if (ps.primaryCpuAbiString != null) { 6264 continue; 6265 } 6266 6267 ps.primaryCpuAbiString = adjustedAbi; 6268 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6269 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6270 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6271 6272 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6273 null /* instruction sets */, forceDexOpt, deferDexOpt, true, 6274 bootComplete); 6275 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6276 ps.primaryCpuAbiString = null; 6277 ps.pkg.applicationInfo.primaryCpuAbi = null; 6278 return; 6279 } else { 6280 mInstaller.rmdex(ps.codePathString, 6281 getDexCodeInstructionSet(getPreferredInstructionSet())); 6282 } 6283 } 6284 } 6285 } 6286 } 6287 } 6288 6289 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6290 synchronized (mPackages) { 6291 mResolverReplaced = true; 6292 // Set up information for custom user intent resolution activity. 6293 mResolveActivity.applicationInfo = pkg.applicationInfo; 6294 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6295 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6296 mResolveActivity.processName = pkg.applicationInfo.packageName; 6297 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6298 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6299 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6300 mResolveActivity.theme = 0; 6301 mResolveActivity.exported = true; 6302 mResolveActivity.enabled = true; 6303 mResolveInfo.activityInfo = mResolveActivity; 6304 mResolveInfo.priority = 0; 6305 mResolveInfo.preferredOrder = 0; 6306 mResolveInfo.match = 0; 6307 mResolveComponentName = mCustomResolverComponentName; 6308 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6309 mResolveComponentName); 6310 } 6311 } 6312 6313 private static String calculateBundledApkRoot(final String codePathString) { 6314 final File codePath = new File(codePathString); 6315 final File codeRoot; 6316 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6317 codeRoot = Environment.getRootDirectory(); 6318 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6319 codeRoot = Environment.getOemDirectory(); 6320 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6321 codeRoot = Environment.getVendorDirectory(); 6322 } else { 6323 // Unrecognized code path; take its top real segment as the apk root: 6324 // e.g. /something/app/blah.apk => /something 6325 try { 6326 File f = codePath.getCanonicalFile(); 6327 File parent = f.getParentFile(); // non-null because codePath is a file 6328 File tmp; 6329 while ((tmp = parent.getParentFile()) != null) { 6330 f = parent; 6331 parent = tmp; 6332 } 6333 codeRoot = f; 6334 Slog.w(TAG, "Unrecognized code path " 6335 + codePath + " - using " + codeRoot); 6336 } catch (IOException e) { 6337 // Can't canonicalize the code path -- shenanigans? 6338 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6339 return Environment.getRootDirectory().getPath(); 6340 } 6341 } 6342 return codeRoot.getPath(); 6343 } 6344 6345 /** 6346 * Derive and set the location of native libraries for the given package, 6347 * which varies depending on where and how the package was installed. 6348 */ 6349 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6350 final ApplicationInfo info = pkg.applicationInfo; 6351 final String codePath = pkg.codePath; 6352 final File codeFile = new File(codePath); 6353 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 6354 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6355 6356 info.nativeLibraryRootDir = null; 6357 info.nativeLibraryRootRequiresIsa = false; 6358 info.nativeLibraryDir = null; 6359 info.secondaryNativeLibraryDir = null; 6360 6361 if (isApkFile(codeFile)) { 6362 // Monolithic install 6363 if (bundledApp) { 6364 // If "/system/lib64/apkname" exists, assume that is the per-package 6365 // native library directory to use; otherwise use "/system/lib/apkname". 6366 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6367 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6368 getPrimaryInstructionSet(info)); 6369 6370 // This is a bundled system app so choose the path based on the ABI. 6371 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6372 // is just the default path. 6373 final String apkName = deriveCodePathName(codePath); 6374 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6375 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6376 apkName).getAbsolutePath(); 6377 6378 if (info.secondaryCpuAbi != null) { 6379 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6380 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6381 secondaryLibDir, apkName).getAbsolutePath(); 6382 } 6383 } else if (asecApp) { 6384 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6385 .getAbsolutePath(); 6386 } else { 6387 final String apkName = deriveCodePathName(codePath); 6388 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6389 .getAbsolutePath(); 6390 } 6391 6392 info.nativeLibraryRootRequiresIsa = false; 6393 info.nativeLibraryDir = info.nativeLibraryRootDir; 6394 } else { 6395 // Cluster install 6396 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6397 info.nativeLibraryRootRequiresIsa = true; 6398 6399 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6400 getPrimaryInstructionSet(info)).getAbsolutePath(); 6401 6402 if (info.secondaryCpuAbi != null) { 6403 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6404 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6405 } 6406 } 6407 } 6408 6409 /** 6410 * Calculate the abis and roots for a bundled app. These can uniquely 6411 * be determined from the contents of the system partition, i.e whether 6412 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6413 * of this information, and instead assume that the system was built 6414 * sensibly. 6415 */ 6416 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6417 PackageSetting pkgSetting) { 6418 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6419 6420 // If "/system/lib64/apkname" exists, assume that is the per-package 6421 // native library directory to use; otherwise use "/system/lib/apkname". 6422 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6423 setBundledAppAbi(pkg, apkRoot, apkName); 6424 // pkgSetting might be null during rescan following uninstall of updates 6425 // to a bundled app, so accommodate that possibility. The settings in 6426 // that case will be established later from the parsed package. 6427 // 6428 // If the settings aren't null, sync them up with what we've just derived. 6429 // note that apkRoot isn't stored in the package settings. 6430 if (pkgSetting != null) { 6431 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6432 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6433 } 6434 } 6435 6436 /** 6437 * Deduces the ABI of a bundled app and sets the relevant fields on the 6438 * parsed pkg object. 6439 * 6440 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6441 * under which system libraries are installed. 6442 * @param apkName the name of the installed package. 6443 */ 6444 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6445 final File codeFile = new File(pkg.codePath); 6446 6447 final boolean has64BitLibs; 6448 final boolean has32BitLibs; 6449 if (isApkFile(codeFile)) { 6450 // Monolithic install 6451 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6452 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6453 } else { 6454 // Cluster install 6455 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6456 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6457 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6458 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6459 has64BitLibs = (new File(rootDir, isa)).exists(); 6460 } else { 6461 has64BitLibs = false; 6462 } 6463 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6464 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6465 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6466 has32BitLibs = (new File(rootDir, isa)).exists(); 6467 } else { 6468 has32BitLibs = false; 6469 } 6470 } 6471 6472 if (has64BitLibs && !has32BitLibs) { 6473 // The package has 64 bit libs, but not 32 bit libs. Its primary 6474 // ABI should be 64 bit. We can safely assume here that the bundled 6475 // native libraries correspond to the most preferred ABI in the list. 6476 6477 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6478 pkg.applicationInfo.secondaryCpuAbi = null; 6479 } else if (has32BitLibs && !has64BitLibs) { 6480 // The package has 32 bit libs but not 64 bit libs. Its primary 6481 // ABI should be 32 bit. 6482 6483 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6484 pkg.applicationInfo.secondaryCpuAbi = null; 6485 } else if (has32BitLibs && has64BitLibs) { 6486 // The application has both 64 and 32 bit bundled libraries. We check 6487 // here that the app declares multiArch support, and warn if it doesn't. 6488 // 6489 // We will be lenient here and record both ABIs. The primary will be the 6490 // ABI that's higher on the list, i.e, a device that's configured to prefer 6491 // 64 bit apps will see a 64 bit primary ABI, 6492 6493 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6494 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6495 } 6496 6497 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6498 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6499 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6500 } else { 6501 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6502 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6503 } 6504 } else { 6505 pkg.applicationInfo.primaryCpuAbi = null; 6506 pkg.applicationInfo.secondaryCpuAbi = null; 6507 } 6508 } 6509 6510 private void killApplication(String pkgName, int appId, String reason) { 6511 // Request the ActivityManager to kill the process(only for existing packages) 6512 // so that we do not end up in a confused state while the user is still using the older 6513 // version of the application while the new one gets installed. 6514 IActivityManager am = ActivityManagerNative.getDefault(); 6515 if (am != null) { 6516 try { 6517 am.killApplicationWithAppId(pkgName, appId, reason); 6518 } catch (RemoteException e) { 6519 } 6520 } 6521 } 6522 6523 void removePackageLI(PackageSetting ps, boolean chatty) { 6524 if (DEBUG_INSTALL) { 6525 if (chatty) 6526 Log.d(TAG, "Removing package " + ps.name); 6527 } 6528 6529 // writer 6530 synchronized (mPackages) { 6531 mPackages.remove(ps.name); 6532 final PackageParser.Package pkg = ps.pkg; 6533 if (pkg != null) { 6534 cleanPackageDataStructuresLILPw(pkg, chatty); 6535 } 6536 } 6537 } 6538 6539 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6540 if (DEBUG_INSTALL) { 6541 if (chatty) 6542 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6543 } 6544 6545 // writer 6546 synchronized (mPackages) { 6547 mPackages.remove(pkg.applicationInfo.packageName); 6548 cleanPackageDataStructuresLILPw(pkg, chatty); 6549 } 6550 } 6551 6552 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6553 int N = pkg.providers.size(); 6554 StringBuilder r = null; 6555 int i; 6556 for (i=0; i<N; i++) { 6557 PackageParser.Provider p = pkg.providers.get(i); 6558 mProviders.removeProvider(p); 6559 if (p.info.authority == null) { 6560 6561 /* There was another ContentProvider with this authority when 6562 * this app was installed so this authority is null, 6563 * Ignore it as we don't have to unregister the provider. 6564 */ 6565 continue; 6566 } 6567 String names[] = p.info.authority.split(";"); 6568 for (int j = 0; j < names.length; j++) { 6569 if (mProvidersByAuthority.get(names[j]) == p) { 6570 mProvidersByAuthority.remove(names[j]); 6571 if (DEBUG_REMOVE) { 6572 if (chatty) 6573 Log.d(TAG, "Unregistered content provider: " + names[j] 6574 + ", className = " + p.info.name + ", isSyncable = " 6575 + p.info.isSyncable); 6576 } 6577 } 6578 } 6579 if (DEBUG_REMOVE && chatty) { 6580 if (r == null) { 6581 r = new StringBuilder(256); 6582 } else { 6583 r.append(' '); 6584 } 6585 r.append(p.info.name); 6586 } 6587 } 6588 if (r != null) { 6589 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6590 } 6591 6592 N = pkg.services.size(); 6593 r = null; 6594 for (i=0; i<N; i++) { 6595 PackageParser.Service s = pkg.services.get(i); 6596 mServices.removeService(s); 6597 if (chatty) { 6598 if (r == null) { 6599 r = new StringBuilder(256); 6600 } else { 6601 r.append(' '); 6602 } 6603 r.append(s.info.name); 6604 } 6605 } 6606 if (r != null) { 6607 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6608 } 6609 6610 N = pkg.receivers.size(); 6611 r = null; 6612 for (i=0; i<N; i++) { 6613 PackageParser.Activity a = pkg.receivers.get(i); 6614 mReceivers.removeActivity(a, "receiver"); 6615 if (DEBUG_REMOVE && chatty) { 6616 if (r == null) { 6617 r = new StringBuilder(256); 6618 } else { 6619 r.append(' '); 6620 } 6621 r.append(a.info.name); 6622 } 6623 } 6624 if (r != null) { 6625 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6626 } 6627 6628 N = pkg.activities.size(); 6629 r = null; 6630 for (i=0; i<N; i++) { 6631 PackageParser.Activity a = pkg.activities.get(i); 6632 mActivities.removeActivity(a, "activity"); 6633 if (DEBUG_REMOVE && chatty) { 6634 if (r == null) { 6635 r = new StringBuilder(256); 6636 } else { 6637 r.append(' '); 6638 } 6639 r.append(a.info.name); 6640 } 6641 } 6642 if (r != null) { 6643 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6644 } 6645 6646 N = pkg.permissions.size(); 6647 r = null; 6648 for (i=0; i<N; i++) { 6649 PackageParser.Permission p = pkg.permissions.get(i); 6650 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6651 if (bp == null) { 6652 bp = mSettings.mPermissionTrees.get(p.info.name); 6653 } 6654 if (bp != null && bp.perm == p) { 6655 bp.perm = null; 6656 if (DEBUG_REMOVE && chatty) { 6657 if (r == null) { 6658 r = new StringBuilder(256); 6659 } else { 6660 r.append(' '); 6661 } 6662 r.append(p.info.name); 6663 } 6664 } 6665 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6666 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6667 if (appOpPerms != null) { 6668 appOpPerms.remove(pkg.packageName); 6669 } 6670 } 6671 } 6672 if (r != null) { 6673 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6674 } 6675 6676 N = pkg.requestedPermissions.size(); 6677 r = null; 6678 for (i=0; i<N; i++) { 6679 String perm = pkg.requestedPermissions.get(i); 6680 BasePermission bp = mSettings.mPermissions.get(perm); 6681 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6682 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6683 if (appOpPerms != null) { 6684 appOpPerms.remove(pkg.packageName); 6685 if (appOpPerms.isEmpty()) { 6686 mAppOpPermissionPackages.remove(perm); 6687 } 6688 } 6689 } 6690 } 6691 if (r != null) { 6692 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6693 } 6694 6695 N = pkg.instrumentation.size(); 6696 r = null; 6697 for (i=0; i<N; i++) { 6698 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6699 mInstrumentation.remove(a.getComponentName()); 6700 if (DEBUG_REMOVE && chatty) { 6701 if (r == null) { 6702 r = new StringBuilder(256); 6703 } else { 6704 r.append(' '); 6705 } 6706 r.append(a.info.name); 6707 } 6708 } 6709 if (r != null) { 6710 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6711 } 6712 6713 r = null; 6714 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6715 // Only system apps can hold shared libraries. 6716 if (pkg.libraryNames != null) { 6717 for (i=0; i<pkg.libraryNames.size(); i++) { 6718 String name = pkg.libraryNames.get(i); 6719 SharedLibraryEntry cur = mSharedLibraries.get(name); 6720 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6721 mSharedLibraries.remove(name); 6722 if (DEBUG_REMOVE && chatty) { 6723 if (r == null) { 6724 r = new StringBuilder(256); 6725 } else { 6726 r.append(' '); 6727 } 6728 r.append(name); 6729 } 6730 } 6731 } 6732 } 6733 } 6734 if (r != null) { 6735 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6736 } 6737 } 6738 6739 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6740 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6741 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6742 return true; 6743 } 6744 } 6745 return false; 6746 } 6747 6748 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6749 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6750 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6751 6752 private void updatePermissionsLPw(String changingPkg, 6753 PackageParser.Package pkgInfo, int flags) { 6754 // Make sure there are no dangling permission trees. 6755 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6756 while (it.hasNext()) { 6757 final BasePermission bp = it.next(); 6758 if (bp.packageSetting == null) { 6759 // We may not yet have parsed the package, so just see if 6760 // we still know about its settings. 6761 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6762 } 6763 if (bp.packageSetting == null) { 6764 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6765 + " from package " + bp.sourcePackage); 6766 it.remove(); 6767 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6768 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6769 Slog.i(TAG, "Removing old permission tree: " + bp.name 6770 + " from package " + bp.sourcePackage); 6771 flags |= UPDATE_PERMISSIONS_ALL; 6772 it.remove(); 6773 } 6774 } 6775 } 6776 6777 // Make sure all dynamic permissions have been assigned to a package, 6778 // and make sure there are no dangling permissions. 6779 it = mSettings.mPermissions.values().iterator(); 6780 while (it.hasNext()) { 6781 final BasePermission bp = it.next(); 6782 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6783 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6784 + bp.name + " pkg=" + bp.sourcePackage 6785 + " info=" + bp.pendingInfo); 6786 if (bp.packageSetting == null && bp.pendingInfo != null) { 6787 final BasePermission tree = findPermissionTreeLP(bp.name); 6788 if (tree != null && tree.perm != null) { 6789 bp.packageSetting = tree.packageSetting; 6790 bp.perm = new PackageParser.Permission(tree.perm.owner, 6791 new PermissionInfo(bp.pendingInfo)); 6792 bp.perm.info.packageName = tree.perm.info.packageName; 6793 bp.perm.info.name = bp.name; 6794 bp.uid = tree.uid; 6795 } 6796 } 6797 } 6798 if (bp.packageSetting == null) { 6799 // We may not yet have parsed the package, so just see if 6800 // we still know about its settings. 6801 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6802 } 6803 if (bp.packageSetting == null) { 6804 Slog.w(TAG, "Removing dangling permission: " + bp.name 6805 + " from package " + bp.sourcePackage); 6806 it.remove(); 6807 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6808 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6809 Slog.i(TAG, "Removing old permission: " + bp.name 6810 + " from package " + bp.sourcePackage); 6811 flags |= UPDATE_PERMISSIONS_ALL; 6812 it.remove(); 6813 } 6814 } 6815 } 6816 6817 // Now update the permissions for all packages, in particular 6818 // replace the granted permissions of the system packages. 6819 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6820 for (PackageParser.Package pkg : mPackages.values()) { 6821 if (pkg != pkgInfo) { 6822 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6823 changingPkg); 6824 } 6825 } 6826 } 6827 6828 if (pkgInfo != null) { 6829 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6830 } 6831 } 6832 6833 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6834 String packageOfInterest) { 6835 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6836 if (ps == null) { 6837 return; 6838 } 6839 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6840 ArraySet<String> origPermissions = gp.grantedPermissions; 6841 boolean changedPermission = false; 6842 6843 if (replace) { 6844 ps.permissionsFixed = false; 6845 if (gp == ps) { 6846 origPermissions = new ArraySet<String>(gp.grantedPermissions); 6847 gp.grantedPermissions.clear(); 6848 gp.gids = mGlobalGids; 6849 } 6850 } 6851 6852 if (gp.gids == null) { 6853 gp.gids = mGlobalGids; 6854 } 6855 6856 final int N = pkg.requestedPermissions.size(); 6857 for (int i=0; i<N; i++) { 6858 final String name = pkg.requestedPermissions.get(i); 6859 final boolean required = pkg.requestedPermissionsRequired.get(i); 6860 final BasePermission bp = mSettings.mPermissions.get(name); 6861 if (DEBUG_INSTALL) { 6862 if (gp != ps) { 6863 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6864 } 6865 } 6866 6867 if (bp == null || bp.packageSetting == null) { 6868 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6869 Slog.w(TAG, "Unknown permission " + name 6870 + " in package " + pkg.packageName); 6871 } 6872 continue; 6873 } 6874 6875 final String perm = bp.name; 6876 boolean allowed; 6877 boolean allowedSig = false; 6878 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6879 // Keep track of app op permissions. 6880 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6881 if (pkgs == null) { 6882 pkgs = new ArraySet<>(); 6883 mAppOpPermissionPackages.put(bp.name, pkgs); 6884 } 6885 pkgs.add(pkg.packageName); 6886 } 6887 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6888 if (level == PermissionInfo.PROTECTION_NORMAL 6889 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6890 // We grant a normal or dangerous permission if any of the following 6891 // are true: 6892 // 1) The permission is required 6893 // 2) The permission is optional, but was granted in the past 6894 // 3) The permission is optional, but was requested by an 6895 // app in /system (not /data) 6896 // 6897 // Otherwise, reject the permission. 6898 allowed = (required || origPermissions.contains(perm) 6899 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6900 } else if (bp.packageSetting == null) { 6901 // This permission is invalid; skip it. 6902 allowed = false; 6903 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6904 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6905 if (allowed) { 6906 allowedSig = true; 6907 } 6908 } else { 6909 allowed = false; 6910 } 6911 if (DEBUG_INSTALL) { 6912 if (gp != ps) { 6913 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6914 } 6915 } 6916 if (allowed) { 6917 if (!isSystemApp(ps) && ps.permissionsFixed) { 6918 // If this is an existing, non-system package, then 6919 // we can't add any new permissions to it. 6920 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6921 // Except... if this is a permission that was added 6922 // to the platform (note: need to only do this when 6923 // updating the platform). 6924 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6925 } 6926 } 6927 if (allowed) { 6928 if (!gp.grantedPermissions.contains(perm)) { 6929 changedPermission = true; 6930 gp.grantedPermissions.add(perm); 6931 gp.gids = appendInts(gp.gids, bp.gids); 6932 } else if (!ps.haveGids) { 6933 gp.gids = appendInts(gp.gids, bp.gids); 6934 } 6935 } else { 6936 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6937 Slog.w(TAG, "Not granting permission " + perm 6938 + " to package " + pkg.packageName 6939 + " because it was previously installed without"); 6940 } 6941 } 6942 } else { 6943 if (gp.grantedPermissions.remove(perm)) { 6944 changedPermission = true; 6945 gp.gids = removeInts(gp.gids, bp.gids); 6946 Slog.i(TAG, "Un-granting permission " + perm 6947 + " from package " + pkg.packageName 6948 + " (protectionLevel=" + bp.protectionLevel 6949 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6950 + ")"); 6951 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6952 // Don't print warning for app op permissions, since it is fine for them 6953 // not to be granted, there is a UI for the user to decide. 6954 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6955 Slog.w(TAG, "Not granting permission " + perm 6956 + " to package " + pkg.packageName 6957 + " (protectionLevel=" + bp.protectionLevel 6958 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6959 + ")"); 6960 } 6961 } 6962 } 6963 } 6964 6965 if ((changedPermission || replace) && !ps.permissionsFixed && 6966 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6967 // This is the first that we have heard about this package, so the 6968 // permissions we have now selected are fixed until explicitly 6969 // changed. 6970 ps.permissionsFixed = true; 6971 } 6972 ps.haveGids = true; 6973 } 6974 6975 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6976 boolean allowed = false; 6977 final int NP = PackageParser.NEW_PERMISSIONS.length; 6978 for (int ip=0; ip<NP; ip++) { 6979 final PackageParser.NewPermissionInfo npi 6980 = PackageParser.NEW_PERMISSIONS[ip]; 6981 if (npi.name.equals(perm) 6982 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6983 allowed = true; 6984 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6985 + pkg.packageName); 6986 break; 6987 } 6988 } 6989 return allowed; 6990 } 6991 6992 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6993 BasePermission bp, ArraySet<String> origPermissions) { 6994 boolean allowed; 6995 allowed = (compareSignatures( 6996 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6997 == PackageManager.SIGNATURE_MATCH) 6998 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6999 == PackageManager.SIGNATURE_MATCH); 7000 if (!allowed && (bp.protectionLevel 7001 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7002 if (isSystemApp(pkg)) { 7003 // For updated system applications, a system permission 7004 // is granted only if it had been defined by the original application. 7005 if (pkg.isUpdatedSystemApp()) { 7006 final PackageSetting sysPs = mSettings 7007 .getDisabledSystemPkgLPr(pkg.packageName); 7008 final GrantedPermissions origGp = sysPs.sharedUser != null 7009 ? sysPs.sharedUser : sysPs; 7010 7011 if (origGp.grantedPermissions.contains(perm)) { 7012 // If the original was granted this permission, we take 7013 // that grant decision as read and propagate it to the 7014 // update. 7015 if (sysPs.isPrivileged()) { 7016 allowed = true; 7017 } 7018 } else { 7019 // The system apk may have been updated with an older 7020 // version of the one on the data partition, but which 7021 // granted a new system permission that it didn't have 7022 // before. In this case we do want to allow the app to 7023 // now get the new permission if the ancestral apk is 7024 // privileged to get it. 7025 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7026 for (int j=0; 7027 j<sysPs.pkg.requestedPermissions.size(); j++) { 7028 if (perm.equals( 7029 sysPs.pkg.requestedPermissions.get(j))) { 7030 allowed = true; 7031 break; 7032 } 7033 } 7034 } 7035 } 7036 } else { 7037 allowed = isPrivilegedApp(pkg); 7038 } 7039 } 7040 } 7041 if (!allowed && (bp.protectionLevel 7042 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7043 // For development permissions, a development permission 7044 // is granted only if it was already granted. 7045 allowed = origPermissions.contains(perm); 7046 } 7047 return allowed; 7048 } 7049 7050 final class ActivityIntentResolver 7051 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7052 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7053 boolean defaultOnly, int userId) { 7054 if (!sUserManager.exists(userId)) return null; 7055 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7056 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7057 } 7058 7059 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7060 int userId) { 7061 if (!sUserManager.exists(userId)) return null; 7062 mFlags = flags; 7063 return super.queryIntent(intent, resolvedType, 7064 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7065 } 7066 7067 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7068 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7069 if (!sUserManager.exists(userId)) return null; 7070 if (packageActivities == null) { 7071 return null; 7072 } 7073 mFlags = flags; 7074 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7075 final int N = packageActivities.size(); 7076 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7077 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7078 7079 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7080 for (int i = 0; i < N; ++i) { 7081 intentFilters = packageActivities.get(i).intents; 7082 if (intentFilters != null && intentFilters.size() > 0) { 7083 PackageParser.ActivityIntentInfo[] array = 7084 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7085 intentFilters.toArray(array); 7086 listCut.add(array); 7087 } 7088 } 7089 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7090 } 7091 7092 public final void addActivity(PackageParser.Activity a, String type) { 7093 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7094 mActivities.put(a.getComponentName(), a); 7095 if (DEBUG_SHOW_INFO) 7096 Log.v( 7097 TAG, " " + type + " " + 7098 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7099 if (DEBUG_SHOW_INFO) 7100 Log.v(TAG, " Class=" + a.info.name); 7101 final int NI = a.intents.size(); 7102 for (int j=0; j<NI; j++) { 7103 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7104 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7105 intent.setPriority(0); 7106 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7107 + a.className + " with priority > 0, forcing to 0"); 7108 } 7109 if (DEBUG_SHOW_INFO) { 7110 Log.v(TAG, " IntentFilter:"); 7111 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7112 } 7113 if (!intent.debugCheck()) { 7114 Log.w(TAG, "==> For Activity " + a.info.name); 7115 } 7116 addFilter(intent); 7117 } 7118 } 7119 7120 public final void removeActivity(PackageParser.Activity a, String type) { 7121 mActivities.remove(a.getComponentName()); 7122 if (DEBUG_SHOW_INFO) { 7123 Log.v(TAG, " " + type + " " 7124 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7125 : a.info.name) + ":"); 7126 Log.v(TAG, " Class=" + a.info.name); 7127 } 7128 final int NI = a.intents.size(); 7129 for (int j=0; j<NI; j++) { 7130 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7131 if (DEBUG_SHOW_INFO) { 7132 Log.v(TAG, " IntentFilter:"); 7133 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7134 } 7135 removeFilter(intent); 7136 } 7137 } 7138 7139 @Override 7140 protected boolean allowFilterResult( 7141 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7142 ActivityInfo filterAi = filter.activity.info; 7143 for (int i=dest.size()-1; i>=0; i--) { 7144 ActivityInfo destAi = dest.get(i).activityInfo; 7145 if (destAi.name == filterAi.name 7146 && destAi.packageName == filterAi.packageName) { 7147 return false; 7148 } 7149 } 7150 return true; 7151 } 7152 7153 @Override 7154 protected ActivityIntentInfo[] newArray(int size) { 7155 return new ActivityIntentInfo[size]; 7156 } 7157 7158 @Override 7159 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7160 if (!sUserManager.exists(userId)) return true; 7161 PackageParser.Package p = filter.activity.owner; 7162 if (p != null) { 7163 PackageSetting ps = (PackageSetting)p.mExtras; 7164 if (ps != null) { 7165 // System apps are never considered stopped for purposes of 7166 // filtering, because there may be no way for the user to 7167 // actually re-launch them. 7168 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7169 && ps.getStopped(userId); 7170 } 7171 } 7172 return false; 7173 } 7174 7175 @Override 7176 protected boolean isPackageForFilter(String packageName, 7177 PackageParser.ActivityIntentInfo info) { 7178 return packageName.equals(info.activity.owner.packageName); 7179 } 7180 7181 @Override 7182 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7183 int match, int userId) { 7184 if (!sUserManager.exists(userId)) return null; 7185 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7186 return null; 7187 } 7188 final PackageParser.Activity activity = info.activity; 7189 if (mSafeMode && (activity.info.applicationInfo.flags 7190 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7191 return null; 7192 } 7193 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7194 if (ps == null) { 7195 return null; 7196 } 7197 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7198 ps.readUserState(userId), userId); 7199 if (ai == null) { 7200 return null; 7201 } 7202 final ResolveInfo res = new ResolveInfo(); 7203 res.activityInfo = ai; 7204 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7205 res.filter = info; 7206 } 7207 res.priority = info.getPriority(); 7208 res.preferredOrder = activity.owner.mPreferredOrder; 7209 //System.out.println("Result: " + res.activityInfo.className + 7210 // " = " + res.priority); 7211 res.match = match; 7212 res.isDefault = info.hasDefault; 7213 res.labelRes = info.labelRes; 7214 res.nonLocalizedLabel = info.nonLocalizedLabel; 7215 if (userNeedsBadging(userId)) { 7216 res.noResourceId = true; 7217 } else { 7218 res.icon = info.icon; 7219 } 7220 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7221 return res; 7222 } 7223 7224 @Override 7225 protected void sortResults(List<ResolveInfo> results) { 7226 Collections.sort(results, mResolvePrioritySorter); 7227 } 7228 7229 @Override 7230 protected void dumpFilter(PrintWriter out, String prefix, 7231 PackageParser.ActivityIntentInfo filter) { 7232 out.print(prefix); out.print( 7233 Integer.toHexString(System.identityHashCode(filter.activity))); 7234 out.print(' '); 7235 filter.activity.printComponentShortName(out); 7236 out.print(" filter "); 7237 out.println(Integer.toHexString(System.identityHashCode(filter))); 7238 } 7239 7240 @Override 7241 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7242 return filter.activity; 7243 } 7244 7245 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7246 PackageParser.Activity activity = (PackageParser.Activity)label; 7247 out.print(prefix); out.print( 7248 Integer.toHexString(System.identityHashCode(activity))); 7249 out.print(' '); 7250 activity.printComponentShortName(out); 7251 if (count > 1) { 7252 out.print(" ("); out.print(count); out.print(" filters)"); 7253 } 7254 out.println(); 7255 } 7256 7257// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7258// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7259// final List<ResolveInfo> retList = Lists.newArrayList(); 7260// while (i.hasNext()) { 7261// final ResolveInfo resolveInfo = i.next(); 7262// if (isEnabledLP(resolveInfo.activityInfo)) { 7263// retList.add(resolveInfo); 7264// } 7265// } 7266// return retList; 7267// } 7268 7269 // Keys are String (activity class name), values are Activity. 7270 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7271 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7272 private int mFlags; 7273 } 7274 7275 private final class ServiceIntentResolver 7276 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7277 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7278 boolean defaultOnly, int userId) { 7279 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7280 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7281 } 7282 7283 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7284 int userId) { 7285 if (!sUserManager.exists(userId)) return null; 7286 mFlags = flags; 7287 return super.queryIntent(intent, resolvedType, 7288 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7289 } 7290 7291 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7292 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7293 if (!sUserManager.exists(userId)) return null; 7294 if (packageServices == null) { 7295 return null; 7296 } 7297 mFlags = flags; 7298 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7299 final int N = packageServices.size(); 7300 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7301 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7302 7303 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7304 for (int i = 0; i < N; ++i) { 7305 intentFilters = packageServices.get(i).intents; 7306 if (intentFilters != null && intentFilters.size() > 0) { 7307 PackageParser.ServiceIntentInfo[] array = 7308 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7309 intentFilters.toArray(array); 7310 listCut.add(array); 7311 } 7312 } 7313 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7314 } 7315 7316 public final void addService(PackageParser.Service s) { 7317 mServices.put(s.getComponentName(), s); 7318 if (DEBUG_SHOW_INFO) { 7319 Log.v(TAG, " " 7320 + (s.info.nonLocalizedLabel != null 7321 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7322 Log.v(TAG, " Class=" + s.info.name); 7323 } 7324 final int NI = s.intents.size(); 7325 int j; 7326 for (j=0; j<NI; j++) { 7327 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7328 if (DEBUG_SHOW_INFO) { 7329 Log.v(TAG, " IntentFilter:"); 7330 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7331 } 7332 if (!intent.debugCheck()) { 7333 Log.w(TAG, "==> For Service " + s.info.name); 7334 } 7335 addFilter(intent); 7336 } 7337 } 7338 7339 public final void removeService(PackageParser.Service s) { 7340 mServices.remove(s.getComponentName()); 7341 if (DEBUG_SHOW_INFO) { 7342 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7343 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7344 Log.v(TAG, " Class=" + s.info.name); 7345 } 7346 final int NI = s.intents.size(); 7347 int j; 7348 for (j=0; j<NI; j++) { 7349 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7350 if (DEBUG_SHOW_INFO) { 7351 Log.v(TAG, " IntentFilter:"); 7352 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7353 } 7354 removeFilter(intent); 7355 } 7356 } 7357 7358 @Override 7359 protected boolean allowFilterResult( 7360 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7361 ServiceInfo filterSi = filter.service.info; 7362 for (int i=dest.size()-1; i>=0; i--) { 7363 ServiceInfo destAi = dest.get(i).serviceInfo; 7364 if (destAi.name == filterSi.name 7365 && destAi.packageName == filterSi.packageName) { 7366 return false; 7367 } 7368 } 7369 return true; 7370 } 7371 7372 @Override 7373 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7374 return new PackageParser.ServiceIntentInfo[size]; 7375 } 7376 7377 @Override 7378 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7379 if (!sUserManager.exists(userId)) return true; 7380 PackageParser.Package p = filter.service.owner; 7381 if (p != null) { 7382 PackageSetting ps = (PackageSetting)p.mExtras; 7383 if (ps != null) { 7384 // System apps are never considered stopped for purposes of 7385 // filtering, because there may be no way for the user to 7386 // actually re-launch them. 7387 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7388 && ps.getStopped(userId); 7389 } 7390 } 7391 return false; 7392 } 7393 7394 @Override 7395 protected boolean isPackageForFilter(String packageName, 7396 PackageParser.ServiceIntentInfo info) { 7397 return packageName.equals(info.service.owner.packageName); 7398 } 7399 7400 @Override 7401 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7402 int match, int userId) { 7403 if (!sUserManager.exists(userId)) return null; 7404 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7405 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7406 return null; 7407 } 7408 final PackageParser.Service service = info.service; 7409 if (mSafeMode && (service.info.applicationInfo.flags 7410 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7411 return null; 7412 } 7413 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7414 if (ps == null) { 7415 return null; 7416 } 7417 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7418 ps.readUserState(userId), userId); 7419 if (si == null) { 7420 return null; 7421 } 7422 final ResolveInfo res = new ResolveInfo(); 7423 res.serviceInfo = si; 7424 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7425 res.filter = filter; 7426 } 7427 res.priority = info.getPriority(); 7428 res.preferredOrder = service.owner.mPreferredOrder; 7429 //System.out.println("Result: " + res.activityInfo.className + 7430 // " = " + res.priority); 7431 res.match = match; 7432 res.isDefault = info.hasDefault; 7433 res.labelRes = info.labelRes; 7434 res.nonLocalizedLabel = info.nonLocalizedLabel; 7435 res.icon = info.icon; 7436 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 7437 return res; 7438 } 7439 7440 @Override 7441 protected void sortResults(List<ResolveInfo> results) { 7442 Collections.sort(results, mResolvePrioritySorter); 7443 } 7444 7445 @Override 7446 protected void dumpFilter(PrintWriter out, String prefix, 7447 PackageParser.ServiceIntentInfo filter) { 7448 out.print(prefix); out.print( 7449 Integer.toHexString(System.identityHashCode(filter.service))); 7450 out.print(' '); 7451 filter.service.printComponentShortName(out); 7452 out.print(" filter "); 7453 out.println(Integer.toHexString(System.identityHashCode(filter))); 7454 } 7455 7456 @Override 7457 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 7458 return filter.service; 7459 } 7460 7461 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7462 PackageParser.Service service = (PackageParser.Service)label; 7463 out.print(prefix); out.print( 7464 Integer.toHexString(System.identityHashCode(service))); 7465 out.print(' '); 7466 service.printComponentShortName(out); 7467 if (count > 1) { 7468 out.print(" ("); out.print(count); out.print(" filters)"); 7469 } 7470 out.println(); 7471 } 7472 7473// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7474// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7475// final List<ResolveInfo> retList = Lists.newArrayList(); 7476// while (i.hasNext()) { 7477// final ResolveInfo resolveInfo = (ResolveInfo) i; 7478// if (isEnabledLP(resolveInfo.serviceInfo)) { 7479// retList.add(resolveInfo); 7480// } 7481// } 7482// return retList; 7483// } 7484 7485 // Keys are String (activity class name), values are Activity. 7486 private final ArrayMap<ComponentName, PackageParser.Service> mServices 7487 = new ArrayMap<ComponentName, PackageParser.Service>(); 7488 private int mFlags; 7489 }; 7490 7491 private final class ProviderIntentResolver 7492 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7493 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7494 boolean defaultOnly, int userId) { 7495 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7496 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7497 } 7498 7499 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7500 int userId) { 7501 if (!sUserManager.exists(userId)) 7502 return null; 7503 mFlags = flags; 7504 return super.queryIntent(intent, resolvedType, 7505 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7506 } 7507 7508 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7509 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7510 if (!sUserManager.exists(userId)) 7511 return null; 7512 if (packageProviders == null) { 7513 return null; 7514 } 7515 mFlags = flags; 7516 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7517 final int N = packageProviders.size(); 7518 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7519 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7520 7521 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7522 for (int i = 0; i < N; ++i) { 7523 intentFilters = packageProviders.get(i).intents; 7524 if (intentFilters != null && intentFilters.size() > 0) { 7525 PackageParser.ProviderIntentInfo[] array = 7526 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7527 intentFilters.toArray(array); 7528 listCut.add(array); 7529 } 7530 } 7531 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7532 } 7533 7534 public final void addProvider(PackageParser.Provider p) { 7535 if (mProviders.containsKey(p.getComponentName())) { 7536 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7537 return; 7538 } 7539 7540 mProviders.put(p.getComponentName(), p); 7541 if (DEBUG_SHOW_INFO) { 7542 Log.v(TAG, " " 7543 + (p.info.nonLocalizedLabel != null 7544 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7545 Log.v(TAG, " Class=" + p.info.name); 7546 } 7547 final int NI = p.intents.size(); 7548 int j; 7549 for (j = 0; j < NI; j++) { 7550 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7551 if (DEBUG_SHOW_INFO) { 7552 Log.v(TAG, " IntentFilter:"); 7553 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7554 } 7555 if (!intent.debugCheck()) { 7556 Log.w(TAG, "==> For Provider " + p.info.name); 7557 } 7558 addFilter(intent); 7559 } 7560 } 7561 7562 public final void removeProvider(PackageParser.Provider p) { 7563 mProviders.remove(p.getComponentName()); 7564 if (DEBUG_SHOW_INFO) { 7565 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7566 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7567 Log.v(TAG, " Class=" + p.info.name); 7568 } 7569 final int NI = p.intents.size(); 7570 int j; 7571 for (j = 0; j < NI; j++) { 7572 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7573 if (DEBUG_SHOW_INFO) { 7574 Log.v(TAG, " IntentFilter:"); 7575 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7576 } 7577 removeFilter(intent); 7578 } 7579 } 7580 7581 @Override 7582 protected boolean allowFilterResult( 7583 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7584 ProviderInfo filterPi = filter.provider.info; 7585 for (int i = dest.size() - 1; i >= 0; i--) { 7586 ProviderInfo destPi = dest.get(i).providerInfo; 7587 if (destPi.name == filterPi.name 7588 && destPi.packageName == filterPi.packageName) { 7589 return false; 7590 } 7591 } 7592 return true; 7593 } 7594 7595 @Override 7596 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7597 return new PackageParser.ProviderIntentInfo[size]; 7598 } 7599 7600 @Override 7601 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7602 if (!sUserManager.exists(userId)) 7603 return true; 7604 PackageParser.Package p = filter.provider.owner; 7605 if (p != null) { 7606 PackageSetting ps = (PackageSetting) p.mExtras; 7607 if (ps != null) { 7608 // System apps are never considered stopped for purposes of 7609 // filtering, because there may be no way for the user to 7610 // actually re-launch them. 7611 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7612 && ps.getStopped(userId); 7613 } 7614 } 7615 return false; 7616 } 7617 7618 @Override 7619 protected boolean isPackageForFilter(String packageName, 7620 PackageParser.ProviderIntentInfo info) { 7621 return packageName.equals(info.provider.owner.packageName); 7622 } 7623 7624 @Override 7625 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7626 int match, int userId) { 7627 if (!sUserManager.exists(userId)) 7628 return null; 7629 final PackageParser.ProviderIntentInfo info = filter; 7630 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7631 return null; 7632 } 7633 final PackageParser.Provider provider = info.provider; 7634 if (mSafeMode && (provider.info.applicationInfo.flags 7635 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7636 return null; 7637 } 7638 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7639 if (ps == null) { 7640 return null; 7641 } 7642 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7643 ps.readUserState(userId), userId); 7644 if (pi == null) { 7645 return null; 7646 } 7647 final ResolveInfo res = new ResolveInfo(); 7648 res.providerInfo = pi; 7649 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7650 res.filter = filter; 7651 } 7652 res.priority = info.getPriority(); 7653 res.preferredOrder = provider.owner.mPreferredOrder; 7654 res.match = match; 7655 res.isDefault = info.hasDefault; 7656 res.labelRes = info.labelRes; 7657 res.nonLocalizedLabel = info.nonLocalizedLabel; 7658 res.icon = info.icon; 7659 res.system = res.providerInfo.applicationInfo.isSystemApp(); 7660 return res; 7661 } 7662 7663 @Override 7664 protected void sortResults(List<ResolveInfo> results) { 7665 Collections.sort(results, mResolvePrioritySorter); 7666 } 7667 7668 @Override 7669 protected void dumpFilter(PrintWriter out, String prefix, 7670 PackageParser.ProviderIntentInfo filter) { 7671 out.print(prefix); 7672 out.print( 7673 Integer.toHexString(System.identityHashCode(filter.provider))); 7674 out.print(' '); 7675 filter.provider.printComponentShortName(out); 7676 out.print(" filter "); 7677 out.println(Integer.toHexString(System.identityHashCode(filter))); 7678 } 7679 7680 @Override 7681 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 7682 return filter.provider; 7683 } 7684 7685 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7686 PackageParser.Provider provider = (PackageParser.Provider)label; 7687 out.print(prefix); out.print( 7688 Integer.toHexString(System.identityHashCode(provider))); 7689 out.print(' '); 7690 provider.printComponentShortName(out); 7691 if (count > 1) { 7692 out.print(" ("); out.print(count); out.print(" filters)"); 7693 } 7694 out.println(); 7695 } 7696 7697 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 7698 = new ArrayMap<ComponentName, PackageParser.Provider>(); 7699 private int mFlags; 7700 }; 7701 7702 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7703 new Comparator<ResolveInfo>() { 7704 public int compare(ResolveInfo r1, ResolveInfo r2) { 7705 int v1 = r1.priority; 7706 int v2 = r2.priority; 7707 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7708 if (v1 != v2) { 7709 return (v1 > v2) ? -1 : 1; 7710 } 7711 v1 = r1.preferredOrder; 7712 v2 = r2.preferredOrder; 7713 if (v1 != v2) { 7714 return (v1 > v2) ? -1 : 1; 7715 } 7716 if (r1.isDefault != r2.isDefault) { 7717 return r1.isDefault ? -1 : 1; 7718 } 7719 v1 = r1.match; 7720 v2 = r2.match; 7721 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7722 if (v1 != v2) { 7723 return (v1 > v2) ? -1 : 1; 7724 } 7725 if (r1.system != r2.system) { 7726 return r1.system ? -1 : 1; 7727 } 7728 return 0; 7729 } 7730 }; 7731 7732 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7733 new Comparator<ProviderInfo>() { 7734 public int compare(ProviderInfo p1, ProviderInfo p2) { 7735 final int v1 = p1.initOrder; 7736 final int v2 = p2.initOrder; 7737 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7738 } 7739 }; 7740 7741 static final void sendPackageBroadcast(String action, String pkg, 7742 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7743 int[] userIds) { 7744 IActivityManager am = ActivityManagerNative.getDefault(); 7745 if (am != null) { 7746 try { 7747 if (userIds == null) { 7748 userIds = am.getRunningUserIds(); 7749 } 7750 for (int id : userIds) { 7751 final Intent intent = new Intent(action, 7752 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7753 if (extras != null) { 7754 intent.putExtras(extras); 7755 } 7756 if (targetPkg != null) { 7757 intent.setPackage(targetPkg); 7758 } 7759 // Modify the UID when posting to other users 7760 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7761 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7762 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7763 intent.putExtra(Intent.EXTRA_UID, uid); 7764 } 7765 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7766 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7767 if (DEBUG_BROADCASTS) { 7768 RuntimeException here = new RuntimeException("here"); 7769 here.fillInStackTrace(); 7770 Slog.d(TAG, "Sending to user " + id + ": " 7771 + intent.toShortString(false, true, false, false) 7772 + " " + intent.getExtras(), here); 7773 } 7774 am.broadcastIntent(null, intent, null, finishedReceiver, 7775 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7776 finishedReceiver != null, false, id); 7777 } 7778 } catch (RemoteException ex) { 7779 } 7780 } 7781 } 7782 7783 /** 7784 * Check if the external storage media is available. This is true if there 7785 * is a mounted external storage medium or if the external storage is 7786 * emulated. 7787 */ 7788 private boolean isExternalMediaAvailable() { 7789 return mMediaMounted || Environment.isExternalStorageEmulated(); 7790 } 7791 7792 @Override 7793 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7794 // writer 7795 synchronized (mPackages) { 7796 if (!isExternalMediaAvailable()) { 7797 // If the external storage is no longer mounted at this point, 7798 // the caller may not have been able to delete all of this 7799 // packages files and can not delete any more. Bail. 7800 return null; 7801 } 7802 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7803 if (lastPackage != null) { 7804 pkgs.remove(lastPackage); 7805 } 7806 if (pkgs.size() > 0) { 7807 return pkgs.get(0); 7808 } 7809 } 7810 return null; 7811 } 7812 7813 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7814 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7815 userId, andCode ? 1 : 0, packageName); 7816 if (mSystemReady) { 7817 msg.sendToTarget(); 7818 } else { 7819 if (mPostSystemReadyMessages == null) { 7820 mPostSystemReadyMessages = new ArrayList<>(); 7821 } 7822 mPostSystemReadyMessages.add(msg); 7823 } 7824 } 7825 7826 void startCleaningPackages() { 7827 // reader 7828 synchronized (mPackages) { 7829 if (!isExternalMediaAvailable()) { 7830 return; 7831 } 7832 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7833 return; 7834 } 7835 } 7836 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7837 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7838 IActivityManager am = ActivityManagerNative.getDefault(); 7839 if (am != null) { 7840 try { 7841 am.startService(null, intent, null, UserHandle.USER_OWNER); 7842 } catch (RemoteException e) { 7843 } 7844 } 7845 } 7846 7847 @Override 7848 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7849 int installFlags, String installerPackageName, VerificationParams verificationParams, 7850 String packageAbiOverride) { 7851 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7852 packageAbiOverride, UserHandle.getCallingUserId()); 7853 } 7854 7855 @Override 7856 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7857 int installFlags, String installerPackageName, VerificationParams verificationParams, 7858 String packageAbiOverride, int userId) { 7859 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 7860 7861 final int callingUid = Binder.getCallingUid(); 7862 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 7863 7864 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7865 try { 7866 if (observer != null) { 7867 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7868 } 7869 } catch (RemoteException re) { 7870 } 7871 return; 7872 } 7873 7874 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 7875 installFlags |= PackageManager.INSTALL_FROM_ADB; 7876 7877 } else { 7878 // Caller holds INSTALL_PACKAGES permission, so we're less strict 7879 // about installerPackageName. 7880 7881 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 7882 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 7883 } 7884 7885 UserHandle user; 7886 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7887 user = UserHandle.ALL; 7888 } else { 7889 user = new UserHandle(userId); 7890 } 7891 7892 verificationParams.setInstallerUid(callingUid); 7893 7894 final File originFile = new File(originPath); 7895 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7896 7897 final Message msg = mHandler.obtainMessage(INIT_COPY); 7898 msg.obj = new InstallParams(origin, observer, installFlags, 7899 installerPackageName, verificationParams, user, packageAbiOverride); 7900 mHandler.sendMessage(msg); 7901 } 7902 7903 void installStage(String packageName, File stagedDir, String stagedCid, 7904 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7905 String installerPackageName, int installerUid, UserHandle user) { 7906 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7907 params.referrerUri, installerUid, null); 7908 7909 final OriginInfo origin; 7910 if (stagedDir != null) { 7911 origin = OriginInfo.fromStagedFile(stagedDir); 7912 } else { 7913 origin = OriginInfo.fromStagedContainer(stagedCid); 7914 } 7915 7916 final Message msg = mHandler.obtainMessage(INIT_COPY); 7917 msg.obj = new InstallParams(origin, observer, params.installFlags, 7918 installerPackageName, verifParams, user, params.abiOverride); 7919 mHandler.sendMessage(msg); 7920 } 7921 7922 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7923 Bundle extras = new Bundle(1); 7924 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7925 7926 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7927 packageName, extras, null, null, new int[] {userId}); 7928 try { 7929 IActivityManager am = ActivityManagerNative.getDefault(); 7930 final boolean isSystem = 7931 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7932 if (isSystem && am.isUserRunning(userId, false)) { 7933 // The just-installed/enabled app is bundled on the system, so presumed 7934 // to be able to run automatically without needing an explicit launch. 7935 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7936 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7937 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7938 .setPackage(packageName); 7939 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7940 android.app.AppOpsManager.OP_NONE, false, false, userId); 7941 } 7942 } catch (RemoteException e) { 7943 // shouldn't happen 7944 Slog.w(TAG, "Unable to bootstrap installed package", e); 7945 } 7946 } 7947 7948 @Override 7949 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7950 int userId) { 7951 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7952 PackageSetting pkgSetting; 7953 final int uid = Binder.getCallingUid(); 7954 enforceCrossUserPermission(uid, userId, true, true, 7955 "setApplicationHiddenSetting for user " + userId); 7956 7957 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7958 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7959 return false; 7960 } 7961 7962 long callingId = Binder.clearCallingIdentity(); 7963 try { 7964 boolean sendAdded = false; 7965 boolean sendRemoved = false; 7966 // writer 7967 synchronized (mPackages) { 7968 pkgSetting = mSettings.mPackages.get(packageName); 7969 if (pkgSetting == null) { 7970 return false; 7971 } 7972 if (pkgSetting.getHidden(userId) != hidden) { 7973 pkgSetting.setHidden(hidden, userId); 7974 mSettings.writePackageRestrictionsLPr(userId); 7975 if (hidden) { 7976 sendRemoved = true; 7977 } else { 7978 sendAdded = true; 7979 } 7980 } 7981 } 7982 if (sendAdded) { 7983 sendPackageAddedForUser(packageName, pkgSetting, userId); 7984 return true; 7985 } 7986 if (sendRemoved) { 7987 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7988 "hiding pkg"); 7989 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7990 } 7991 } finally { 7992 Binder.restoreCallingIdentity(callingId); 7993 } 7994 return false; 7995 } 7996 7997 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7998 int userId) { 7999 final PackageRemovedInfo info = new PackageRemovedInfo(); 8000 info.removedPackage = packageName; 8001 info.removedUsers = new int[] {userId}; 8002 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8003 info.sendBroadcast(false, false, false); 8004 } 8005 8006 /** 8007 * Returns true if application is not found or there was an error. Otherwise it returns 8008 * the hidden state of the package for the given user. 8009 */ 8010 @Override 8011 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8012 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8013 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8014 false, "getApplicationHidden for user " + userId); 8015 PackageSetting pkgSetting; 8016 long callingId = Binder.clearCallingIdentity(); 8017 try { 8018 // writer 8019 synchronized (mPackages) { 8020 pkgSetting = mSettings.mPackages.get(packageName); 8021 if (pkgSetting == null) { 8022 return true; 8023 } 8024 return pkgSetting.getHidden(userId); 8025 } 8026 } finally { 8027 Binder.restoreCallingIdentity(callingId); 8028 } 8029 } 8030 8031 /** 8032 * @hide 8033 */ 8034 @Override 8035 public int installExistingPackageAsUser(String packageName, int userId) { 8036 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8037 null); 8038 PackageSetting pkgSetting; 8039 final int uid = Binder.getCallingUid(); 8040 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8041 + userId); 8042 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8043 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8044 } 8045 8046 long callingId = Binder.clearCallingIdentity(); 8047 try { 8048 boolean sendAdded = false; 8049 Bundle extras = new Bundle(1); 8050 8051 // writer 8052 synchronized (mPackages) { 8053 pkgSetting = mSettings.mPackages.get(packageName); 8054 if (pkgSetting == null) { 8055 return PackageManager.INSTALL_FAILED_INVALID_URI; 8056 } 8057 if (!pkgSetting.getInstalled(userId)) { 8058 pkgSetting.setInstalled(true, userId); 8059 pkgSetting.setHidden(false, userId); 8060 mSettings.writePackageRestrictionsLPr(userId); 8061 sendAdded = true; 8062 } 8063 } 8064 8065 if (sendAdded) { 8066 sendPackageAddedForUser(packageName, pkgSetting, userId); 8067 } 8068 } finally { 8069 Binder.restoreCallingIdentity(callingId); 8070 } 8071 8072 return PackageManager.INSTALL_SUCCEEDED; 8073 } 8074 8075 boolean isUserRestricted(int userId, String restrictionKey) { 8076 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8077 if (restrictions.getBoolean(restrictionKey, false)) { 8078 Log.w(TAG, "User is restricted: " + restrictionKey); 8079 return true; 8080 } 8081 return false; 8082 } 8083 8084 @Override 8085 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8086 mContext.enforceCallingOrSelfPermission( 8087 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8088 "Only package verification agents can verify applications"); 8089 8090 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8091 final PackageVerificationResponse response = new PackageVerificationResponse( 8092 verificationCode, Binder.getCallingUid()); 8093 msg.arg1 = id; 8094 msg.obj = response; 8095 mHandler.sendMessage(msg); 8096 } 8097 8098 @Override 8099 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8100 long millisecondsToDelay) { 8101 mContext.enforceCallingOrSelfPermission( 8102 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8103 "Only package verification agents can extend verification timeouts"); 8104 8105 final PackageVerificationState state = mPendingVerification.get(id); 8106 final PackageVerificationResponse response = new PackageVerificationResponse( 8107 verificationCodeAtTimeout, Binder.getCallingUid()); 8108 8109 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8110 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8111 } 8112 if (millisecondsToDelay < 0) { 8113 millisecondsToDelay = 0; 8114 } 8115 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8116 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8117 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8118 } 8119 8120 if ((state != null) && !state.timeoutExtended()) { 8121 state.extendTimeout(); 8122 8123 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8124 msg.arg1 = id; 8125 msg.obj = response; 8126 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8127 } 8128 } 8129 8130 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8131 int verificationCode, UserHandle user) { 8132 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8133 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8134 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8135 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8136 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8137 8138 mContext.sendBroadcastAsUser(intent, user, 8139 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8140 } 8141 8142 private ComponentName matchComponentForVerifier(String packageName, 8143 List<ResolveInfo> receivers) { 8144 ActivityInfo targetReceiver = null; 8145 8146 final int NR = receivers.size(); 8147 for (int i = 0; i < NR; i++) { 8148 final ResolveInfo info = receivers.get(i); 8149 if (info.activityInfo == null) { 8150 continue; 8151 } 8152 8153 if (packageName.equals(info.activityInfo.packageName)) { 8154 targetReceiver = info.activityInfo; 8155 break; 8156 } 8157 } 8158 8159 if (targetReceiver == null) { 8160 return null; 8161 } 8162 8163 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8164 } 8165 8166 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8167 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8168 if (pkgInfo.verifiers.length == 0) { 8169 return null; 8170 } 8171 8172 final int N = pkgInfo.verifiers.length; 8173 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8174 for (int i = 0; i < N; i++) { 8175 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8176 8177 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8178 receivers); 8179 if (comp == null) { 8180 continue; 8181 } 8182 8183 final int verifierUid = getUidForVerifier(verifierInfo); 8184 if (verifierUid == -1) { 8185 continue; 8186 } 8187 8188 if (DEBUG_VERIFY) { 8189 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8190 + " with the correct signature"); 8191 } 8192 sufficientVerifiers.add(comp); 8193 verificationState.addSufficientVerifier(verifierUid); 8194 } 8195 8196 return sufficientVerifiers; 8197 } 8198 8199 private int getUidForVerifier(VerifierInfo verifierInfo) { 8200 synchronized (mPackages) { 8201 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8202 if (pkg == null) { 8203 return -1; 8204 } else if (pkg.mSignatures.length != 1) { 8205 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8206 + " has more than one signature; ignoring"); 8207 return -1; 8208 } 8209 8210 /* 8211 * If the public key of the package's signature does not match 8212 * our expected public key, then this is a different package and 8213 * we should skip. 8214 */ 8215 8216 final byte[] expectedPublicKey; 8217 try { 8218 final Signature verifierSig = pkg.mSignatures[0]; 8219 final PublicKey publicKey = verifierSig.getPublicKey(); 8220 expectedPublicKey = publicKey.getEncoded(); 8221 } catch (CertificateException e) { 8222 return -1; 8223 } 8224 8225 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8226 8227 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8228 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8229 + " does not have the expected public key; ignoring"); 8230 return -1; 8231 } 8232 8233 return pkg.applicationInfo.uid; 8234 } 8235 } 8236 8237 @Override 8238 public void finishPackageInstall(int token) { 8239 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8240 8241 if (DEBUG_INSTALL) { 8242 Slog.v(TAG, "BM finishing package install for " + token); 8243 } 8244 8245 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8246 mHandler.sendMessage(msg); 8247 } 8248 8249 /** 8250 * Get the verification agent timeout. 8251 * 8252 * @return verification timeout in milliseconds 8253 */ 8254 private long getVerificationTimeout() { 8255 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8256 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8257 DEFAULT_VERIFICATION_TIMEOUT); 8258 } 8259 8260 /** 8261 * Get the default verification agent response code. 8262 * 8263 * @return default verification response code 8264 */ 8265 private int getDefaultVerificationResponse() { 8266 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8267 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8268 DEFAULT_VERIFICATION_RESPONSE); 8269 } 8270 8271 /** 8272 * Check whether or not package verification has been enabled. 8273 * 8274 * @return true if verification should be performed 8275 */ 8276 private boolean isVerificationEnabled(int userId, int installFlags) { 8277 if (!DEFAULT_VERIFY_ENABLE) { 8278 return false; 8279 } 8280 8281 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8282 8283 // Check if installing from ADB 8284 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8285 // Do not run verification in a test harness environment 8286 if (ActivityManager.isRunningInTestHarness()) { 8287 return false; 8288 } 8289 if (ensureVerifyAppsEnabled) { 8290 return true; 8291 } 8292 // Check if the developer does not want package verification for ADB installs 8293 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8294 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8295 return false; 8296 } 8297 } 8298 8299 if (ensureVerifyAppsEnabled) { 8300 return true; 8301 } 8302 8303 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8304 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8305 } 8306 8307 /** 8308 * Get the "allow unknown sources" setting. 8309 * 8310 * @return the current "allow unknown sources" setting 8311 */ 8312 private int getUnknownSourcesSettings() { 8313 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8314 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8315 -1); 8316 } 8317 8318 @Override 8319 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8320 final int uid = Binder.getCallingUid(); 8321 // writer 8322 synchronized (mPackages) { 8323 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8324 if (targetPackageSetting == null) { 8325 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8326 } 8327 8328 PackageSetting installerPackageSetting; 8329 if (installerPackageName != null) { 8330 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8331 if (installerPackageSetting == null) { 8332 throw new IllegalArgumentException("Unknown installer package: " 8333 + installerPackageName); 8334 } 8335 } else { 8336 installerPackageSetting = null; 8337 } 8338 8339 Signature[] callerSignature; 8340 Object obj = mSettings.getUserIdLPr(uid); 8341 if (obj != null) { 8342 if (obj instanceof SharedUserSetting) { 8343 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8344 } else if (obj instanceof PackageSetting) { 8345 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8346 } else { 8347 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8348 } 8349 } else { 8350 throw new SecurityException("Unknown calling uid " + uid); 8351 } 8352 8353 // Verify: can't set installerPackageName to a package that is 8354 // not signed with the same cert as the caller. 8355 if (installerPackageSetting != null) { 8356 if (compareSignatures(callerSignature, 8357 installerPackageSetting.signatures.mSignatures) 8358 != PackageManager.SIGNATURE_MATCH) { 8359 throw new SecurityException( 8360 "Caller does not have same cert as new installer package " 8361 + installerPackageName); 8362 } 8363 } 8364 8365 // Verify: if target already has an installer package, it must 8366 // be signed with the same cert as the caller. 8367 if (targetPackageSetting.installerPackageName != null) { 8368 PackageSetting setting = mSettings.mPackages.get( 8369 targetPackageSetting.installerPackageName); 8370 // If the currently set package isn't valid, then it's always 8371 // okay to change it. 8372 if (setting != null) { 8373 if (compareSignatures(callerSignature, 8374 setting.signatures.mSignatures) 8375 != PackageManager.SIGNATURE_MATCH) { 8376 throw new SecurityException( 8377 "Caller does not have same cert as old installer package " 8378 + targetPackageSetting.installerPackageName); 8379 } 8380 } 8381 } 8382 8383 // Okay! 8384 targetPackageSetting.installerPackageName = installerPackageName; 8385 scheduleWriteSettingsLocked(); 8386 } 8387 } 8388 8389 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8390 // Queue up an async operation since the package installation may take a little while. 8391 mHandler.post(new Runnable() { 8392 public void run() { 8393 mHandler.removeCallbacks(this); 8394 // Result object to be returned 8395 PackageInstalledInfo res = new PackageInstalledInfo(); 8396 res.returnCode = currentStatus; 8397 res.uid = -1; 8398 res.pkg = null; 8399 res.removedInfo = new PackageRemovedInfo(); 8400 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8401 args.doPreInstall(res.returnCode); 8402 synchronized (mInstallLock) { 8403 installPackageLI(args, res); 8404 } 8405 args.doPostInstall(res.returnCode, res.uid); 8406 } 8407 8408 // A restore should be performed at this point if (a) the install 8409 // succeeded, (b) the operation is not an update, and (c) the new 8410 // package has not opted out of backup participation. 8411 final boolean update = res.removedInfo.removedPackage != null; 8412 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8413 boolean doRestore = !update 8414 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8415 8416 // Set up the post-install work request bookkeeping. This will be used 8417 // and cleaned up by the post-install event handling regardless of whether 8418 // there's a restore pass performed. Token values are >= 1. 8419 int token; 8420 if (mNextInstallToken < 0) mNextInstallToken = 1; 8421 token = mNextInstallToken++; 8422 8423 PostInstallData data = new PostInstallData(args, res); 8424 mRunningInstalls.put(token, data); 8425 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8426 8427 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8428 // Pass responsibility to the Backup Manager. It will perform a 8429 // restore if appropriate, then pass responsibility back to the 8430 // Package Manager to run the post-install observer callbacks 8431 // and broadcasts. 8432 IBackupManager bm = IBackupManager.Stub.asInterface( 8433 ServiceManager.getService(Context.BACKUP_SERVICE)); 8434 if (bm != null) { 8435 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8436 + " to BM for possible restore"); 8437 try { 8438 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 8439 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8440 } else { 8441 doRestore = false; 8442 } 8443 } catch (RemoteException e) { 8444 // can't happen; the backup manager is local 8445 } catch (Exception e) { 8446 Slog.e(TAG, "Exception trying to enqueue restore", e); 8447 doRestore = false; 8448 } 8449 } else { 8450 Slog.e(TAG, "Backup Manager not found!"); 8451 doRestore = false; 8452 } 8453 } 8454 8455 if (!doRestore) { 8456 // No restore possible, or the Backup Manager was mysteriously not 8457 // available -- just fire the post-install work request directly. 8458 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8459 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8460 mHandler.sendMessage(msg); 8461 } 8462 } 8463 }); 8464 } 8465 8466 private abstract class HandlerParams { 8467 private static final int MAX_RETRIES = 4; 8468 8469 /** 8470 * Number of times startCopy() has been attempted and had a non-fatal 8471 * error. 8472 */ 8473 private int mRetries = 0; 8474 8475 /** User handle for the user requesting the information or installation. */ 8476 private final UserHandle mUser; 8477 8478 HandlerParams(UserHandle user) { 8479 mUser = user; 8480 } 8481 8482 UserHandle getUser() { 8483 return mUser; 8484 } 8485 8486 final boolean startCopy() { 8487 boolean res; 8488 try { 8489 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8490 8491 if (++mRetries > MAX_RETRIES) { 8492 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8493 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8494 handleServiceError(); 8495 return false; 8496 } else { 8497 handleStartCopy(); 8498 res = true; 8499 } 8500 } catch (RemoteException e) { 8501 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8502 mHandler.sendEmptyMessage(MCS_RECONNECT); 8503 res = false; 8504 } 8505 handleReturnCode(); 8506 return res; 8507 } 8508 8509 final void serviceError() { 8510 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8511 handleServiceError(); 8512 handleReturnCode(); 8513 } 8514 8515 abstract void handleStartCopy() throws RemoteException; 8516 abstract void handleServiceError(); 8517 abstract void handleReturnCode(); 8518 } 8519 8520 class MeasureParams extends HandlerParams { 8521 private final PackageStats mStats; 8522 private boolean mSuccess; 8523 8524 private final IPackageStatsObserver mObserver; 8525 8526 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8527 super(new UserHandle(stats.userHandle)); 8528 mObserver = observer; 8529 mStats = stats; 8530 } 8531 8532 @Override 8533 public String toString() { 8534 return "MeasureParams{" 8535 + Integer.toHexString(System.identityHashCode(this)) 8536 + " " + mStats.packageName + "}"; 8537 } 8538 8539 @Override 8540 void handleStartCopy() throws RemoteException { 8541 synchronized (mInstallLock) { 8542 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8543 } 8544 8545 if (mSuccess) { 8546 final boolean mounted; 8547 if (Environment.isExternalStorageEmulated()) { 8548 mounted = true; 8549 } else { 8550 final String status = Environment.getExternalStorageState(); 8551 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8552 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8553 } 8554 8555 if (mounted) { 8556 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8557 8558 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8559 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8560 8561 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8562 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8563 8564 // Always subtract cache size, since it's a subdirectory 8565 mStats.externalDataSize -= mStats.externalCacheSize; 8566 8567 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8568 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8569 8570 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8571 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8572 } 8573 } 8574 } 8575 8576 @Override 8577 void handleReturnCode() { 8578 if (mObserver != null) { 8579 try { 8580 mObserver.onGetStatsCompleted(mStats, mSuccess); 8581 } catch (RemoteException e) { 8582 Slog.i(TAG, "Observer no longer exists."); 8583 } 8584 } 8585 } 8586 8587 @Override 8588 void handleServiceError() { 8589 Slog.e(TAG, "Could not measure application " + mStats.packageName 8590 + " external storage"); 8591 } 8592 } 8593 8594 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8595 throws RemoteException { 8596 long result = 0; 8597 for (File path : paths) { 8598 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8599 } 8600 return result; 8601 } 8602 8603 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8604 for (File path : paths) { 8605 try { 8606 mcs.clearDirectory(path.getAbsolutePath()); 8607 } catch (RemoteException e) { 8608 } 8609 } 8610 } 8611 8612 static class OriginInfo { 8613 /** 8614 * Location where install is coming from, before it has been 8615 * copied/renamed into place. This could be a single monolithic APK 8616 * file, or a cluster directory. This location may be untrusted. 8617 */ 8618 final File file; 8619 final String cid; 8620 8621 /** 8622 * Flag indicating that {@link #file} or {@link #cid} has already been 8623 * staged, meaning downstream users don't need to defensively copy the 8624 * contents. 8625 */ 8626 final boolean staged; 8627 8628 /** 8629 * Flag indicating that {@link #file} or {@link #cid} is an already 8630 * installed app that is being moved. 8631 */ 8632 final boolean existing; 8633 8634 final String resolvedPath; 8635 final File resolvedFile; 8636 8637 static OriginInfo fromNothing() { 8638 return new OriginInfo(null, null, false, false); 8639 } 8640 8641 static OriginInfo fromUntrustedFile(File file) { 8642 return new OriginInfo(file, null, false, false); 8643 } 8644 8645 static OriginInfo fromExistingFile(File file) { 8646 return new OriginInfo(file, null, false, true); 8647 } 8648 8649 static OriginInfo fromStagedFile(File file) { 8650 return new OriginInfo(file, null, true, false); 8651 } 8652 8653 static OriginInfo fromStagedContainer(String cid) { 8654 return new OriginInfo(null, cid, true, false); 8655 } 8656 8657 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8658 this.file = file; 8659 this.cid = cid; 8660 this.staged = staged; 8661 this.existing = existing; 8662 8663 if (cid != null) { 8664 resolvedPath = PackageHelper.getSdDir(cid); 8665 resolvedFile = new File(resolvedPath); 8666 } else if (file != null) { 8667 resolvedPath = file.getAbsolutePath(); 8668 resolvedFile = file; 8669 } else { 8670 resolvedPath = null; 8671 resolvedFile = null; 8672 } 8673 } 8674 } 8675 8676 class InstallParams extends HandlerParams { 8677 final OriginInfo origin; 8678 final IPackageInstallObserver2 observer; 8679 int installFlags; 8680 final String installerPackageName; 8681 final VerificationParams verificationParams; 8682 private InstallArgs mArgs; 8683 private int mRet; 8684 final String packageAbiOverride; 8685 8686 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8687 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8688 String packageAbiOverride) { 8689 super(user); 8690 this.origin = origin; 8691 this.observer = observer; 8692 this.installFlags = installFlags; 8693 this.installerPackageName = installerPackageName; 8694 this.verificationParams = verificationParams; 8695 this.packageAbiOverride = packageAbiOverride; 8696 } 8697 8698 @Override 8699 public String toString() { 8700 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8701 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8702 } 8703 8704 public ManifestDigest getManifestDigest() { 8705 if (verificationParams == null) { 8706 return null; 8707 } 8708 return verificationParams.getManifestDigest(); 8709 } 8710 8711 private int installLocationPolicy(PackageInfoLite pkgLite) { 8712 String packageName = pkgLite.packageName; 8713 int installLocation = pkgLite.installLocation; 8714 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8715 // reader 8716 synchronized (mPackages) { 8717 PackageParser.Package pkg = mPackages.get(packageName); 8718 if (pkg != null) { 8719 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8720 // Check for downgrading. 8721 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8722 try { 8723 checkDowngrade(pkg, pkgLite); 8724 } catch (PackageManagerException e) { 8725 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 8726 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8727 } 8728 } 8729 // Check for updated system application. 8730 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8731 if (onSd) { 8732 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8733 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8734 } 8735 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8736 } else { 8737 if (onSd) { 8738 // Install flag overrides everything. 8739 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8740 } 8741 // If current upgrade specifies particular preference 8742 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8743 // Application explicitly specified internal. 8744 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8745 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8746 // App explictly prefers external. Let policy decide 8747 } else { 8748 // Prefer previous location 8749 if (isExternal(pkg)) { 8750 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8751 } 8752 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8753 } 8754 } 8755 } else { 8756 // Invalid install. Return error code 8757 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8758 } 8759 } 8760 } 8761 // All the special cases have been taken care of. 8762 // Return result based on recommended install location. 8763 if (onSd) { 8764 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8765 } 8766 return pkgLite.recommendedInstallLocation; 8767 } 8768 8769 /* 8770 * Invoke remote method to get package information and install 8771 * location values. Override install location based on default 8772 * policy if needed and then create install arguments based 8773 * on the install location. 8774 */ 8775 public void handleStartCopy() throws RemoteException { 8776 int ret = PackageManager.INSTALL_SUCCEEDED; 8777 8778 // If we're already staged, we've firmly committed to an install location 8779 if (origin.staged) { 8780 if (origin.file != null) { 8781 installFlags |= PackageManager.INSTALL_INTERNAL; 8782 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8783 } else if (origin.cid != null) { 8784 installFlags |= PackageManager.INSTALL_EXTERNAL; 8785 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8786 } else { 8787 throw new IllegalStateException("Invalid stage location"); 8788 } 8789 } 8790 8791 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8792 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8793 8794 PackageInfoLite pkgLite = null; 8795 8796 if (onInt && onSd) { 8797 // Check if both bits are set. 8798 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8799 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8800 } else { 8801 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8802 packageAbiOverride); 8803 8804 /* 8805 * If we have too little free space, try to free cache 8806 * before giving up. 8807 */ 8808 if (!origin.staged && pkgLite.recommendedInstallLocation 8809 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8810 // TODO: focus freeing disk space on the target device 8811 final StorageManager storage = StorageManager.from(mContext); 8812 final long lowThreshold = storage.getStorageLowBytes( 8813 Environment.getDataDirectory()); 8814 8815 final long sizeBytes = mContainerService.calculateInstalledSize( 8816 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8817 8818 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8819 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8820 installFlags, packageAbiOverride); 8821 } 8822 8823 /* 8824 * The cache free must have deleted the file we 8825 * downloaded to install. 8826 * 8827 * TODO: fix the "freeCache" call to not delete 8828 * the file we care about. 8829 */ 8830 if (pkgLite.recommendedInstallLocation 8831 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8832 pkgLite.recommendedInstallLocation 8833 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8834 } 8835 } 8836 } 8837 8838 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8839 int loc = pkgLite.recommendedInstallLocation; 8840 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8841 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8842 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8843 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8844 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8845 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8846 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8847 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8848 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8849 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8850 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8851 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8852 } else { 8853 // Override with defaults if needed. 8854 loc = installLocationPolicy(pkgLite); 8855 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8856 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8857 } else if (!onSd && !onInt) { 8858 // Override install location with flags 8859 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8860 // Set the flag to install on external media. 8861 installFlags |= PackageManager.INSTALL_EXTERNAL; 8862 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8863 } else { 8864 // Make sure the flag for installing on external 8865 // media is unset 8866 installFlags |= PackageManager.INSTALL_INTERNAL; 8867 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8868 } 8869 } 8870 } 8871 } 8872 8873 final InstallArgs args = createInstallArgs(this); 8874 mArgs = args; 8875 8876 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8877 /* 8878 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8879 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8880 */ 8881 int userIdentifier = getUser().getIdentifier(); 8882 if (userIdentifier == UserHandle.USER_ALL 8883 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8884 userIdentifier = UserHandle.USER_OWNER; 8885 } 8886 8887 /* 8888 * Determine if we have any installed package verifiers. If we 8889 * do, then we'll defer to them to verify the packages. 8890 */ 8891 final int requiredUid = mRequiredVerifierPackage == null ? -1 8892 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8893 if (!origin.existing && requiredUid != -1 8894 && isVerificationEnabled(userIdentifier, installFlags)) { 8895 final Intent verification = new Intent( 8896 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8897 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 8898 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8899 PACKAGE_MIME_TYPE); 8900 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8901 8902 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8903 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8904 0 /* TODO: Which userId? */); 8905 8906 if (DEBUG_VERIFY) { 8907 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8908 + verification.toString() + " with " + pkgLite.verifiers.length 8909 + " optional verifiers"); 8910 } 8911 8912 final int verificationId = mPendingVerificationToken++; 8913 8914 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8915 8916 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8917 installerPackageName); 8918 8919 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8920 installFlags); 8921 8922 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8923 pkgLite.packageName); 8924 8925 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8926 pkgLite.versionCode); 8927 8928 if (verificationParams != null) { 8929 if (verificationParams.getVerificationURI() != null) { 8930 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8931 verificationParams.getVerificationURI()); 8932 } 8933 if (verificationParams.getOriginatingURI() != null) { 8934 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8935 verificationParams.getOriginatingURI()); 8936 } 8937 if (verificationParams.getReferrer() != null) { 8938 verification.putExtra(Intent.EXTRA_REFERRER, 8939 verificationParams.getReferrer()); 8940 } 8941 if (verificationParams.getOriginatingUid() >= 0) { 8942 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8943 verificationParams.getOriginatingUid()); 8944 } 8945 if (verificationParams.getInstallerUid() >= 0) { 8946 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8947 verificationParams.getInstallerUid()); 8948 } 8949 } 8950 8951 final PackageVerificationState verificationState = new PackageVerificationState( 8952 requiredUid, args); 8953 8954 mPendingVerification.append(verificationId, verificationState); 8955 8956 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8957 receivers, verificationState); 8958 8959 /* 8960 * If any sufficient verifiers were listed in the package 8961 * manifest, attempt to ask them. 8962 */ 8963 if (sufficientVerifiers != null) { 8964 final int N = sufficientVerifiers.size(); 8965 if (N == 0) { 8966 Slog.i(TAG, "Additional verifiers required, but none installed."); 8967 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8968 } else { 8969 for (int i = 0; i < N; i++) { 8970 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8971 8972 final Intent sufficientIntent = new Intent(verification); 8973 sufficientIntent.setComponent(verifierComponent); 8974 8975 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8976 } 8977 } 8978 } 8979 8980 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8981 mRequiredVerifierPackage, receivers); 8982 if (ret == PackageManager.INSTALL_SUCCEEDED 8983 && mRequiredVerifierPackage != null) { 8984 /* 8985 * Send the intent to the required verification agent, 8986 * but only start the verification timeout after the 8987 * target BroadcastReceivers have run. 8988 */ 8989 verification.setComponent(requiredVerifierComponent); 8990 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8991 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8992 new BroadcastReceiver() { 8993 @Override 8994 public void onReceive(Context context, Intent intent) { 8995 final Message msg = mHandler 8996 .obtainMessage(CHECK_PENDING_VERIFICATION); 8997 msg.arg1 = verificationId; 8998 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8999 } 9000 }, null, 0, null, null); 9001 9002 /* 9003 * We don't want the copy to proceed until verification 9004 * succeeds, so null out this field. 9005 */ 9006 mArgs = null; 9007 } 9008 } else { 9009 /* 9010 * No package verification is enabled, so immediately start 9011 * the remote call to initiate copy using temporary file. 9012 */ 9013 ret = args.copyApk(mContainerService, true); 9014 } 9015 } 9016 9017 mRet = ret; 9018 } 9019 9020 @Override 9021 void handleReturnCode() { 9022 // If mArgs is null, then MCS couldn't be reached. When it 9023 // reconnects, it will try again to install. At that point, this 9024 // will succeed. 9025 if (mArgs != null) { 9026 processPendingInstall(mArgs, mRet); 9027 } 9028 } 9029 9030 @Override 9031 void handleServiceError() { 9032 mArgs = createInstallArgs(this); 9033 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9034 } 9035 9036 public boolean isForwardLocked() { 9037 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9038 } 9039 } 9040 9041 /** 9042 * Used during creation of InstallArgs 9043 * 9044 * @param installFlags package installation flags 9045 * @return true if should be installed on external storage 9046 */ 9047 private static boolean installOnSd(int installFlags) { 9048 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9049 return false; 9050 } 9051 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9052 return true; 9053 } 9054 return false; 9055 } 9056 9057 /** 9058 * Used during creation of InstallArgs 9059 * 9060 * @param installFlags package installation flags 9061 * @return true if should be installed as forward locked 9062 */ 9063 private static boolean installForwardLocked(int installFlags) { 9064 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9065 } 9066 9067 private InstallArgs createInstallArgs(InstallParams params) { 9068 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9069 return new AsecInstallArgs(params); 9070 } else { 9071 return new FileInstallArgs(params); 9072 } 9073 } 9074 9075 /** 9076 * Create args that describe an existing installed package. Typically used 9077 * when cleaning up old installs, or used as a move source. 9078 */ 9079 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9080 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9081 final boolean isInAsec; 9082 if (installOnSd(installFlags)) { 9083 /* Apps on SD card are always in ASEC containers. */ 9084 isInAsec = true; 9085 } else if (installForwardLocked(installFlags) 9086 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9087 /* 9088 * Forward-locked apps are only in ASEC containers if they're the 9089 * new style 9090 */ 9091 isInAsec = true; 9092 } else { 9093 isInAsec = false; 9094 } 9095 9096 if (isInAsec) { 9097 return new AsecInstallArgs(codePath, instructionSets, 9098 installOnSd(installFlags), installForwardLocked(installFlags)); 9099 } else { 9100 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9101 instructionSets); 9102 } 9103 } 9104 9105 static abstract class InstallArgs { 9106 /** @see InstallParams#origin */ 9107 final OriginInfo origin; 9108 9109 final IPackageInstallObserver2 observer; 9110 // Always refers to PackageManager flags only 9111 final int installFlags; 9112 final String installerPackageName; 9113 final ManifestDigest manifestDigest; 9114 final UserHandle user; 9115 final String abiOverride; 9116 9117 // The list of instruction sets supported by this app. This is currently 9118 // only used during the rmdex() phase to clean up resources. We can get rid of this 9119 // if we move dex files under the common app path. 9120 /* nullable */ String[] instructionSets; 9121 9122 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9123 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9124 String[] instructionSets, String abiOverride) { 9125 this.origin = origin; 9126 this.installFlags = installFlags; 9127 this.observer = observer; 9128 this.installerPackageName = installerPackageName; 9129 this.manifestDigest = manifestDigest; 9130 this.user = user; 9131 this.instructionSets = instructionSets; 9132 this.abiOverride = abiOverride; 9133 } 9134 9135 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9136 abstract int doPreInstall(int status); 9137 9138 /** 9139 * Rename package into final resting place. All paths on the given 9140 * scanned package should be updated to reflect the rename. 9141 */ 9142 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9143 abstract int doPostInstall(int status, int uid); 9144 9145 /** @see PackageSettingBase#codePathString */ 9146 abstract String getCodePath(); 9147 /** @see PackageSettingBase#resourcePathString */ 9148 abstract String getResourcePath(); 9149 abstract String getLegacyNativeLibraryPath(); 9150 9151 // Need installer lock especially for dex file removal. 9152 abstract void cleanUpResourcesLI(); 9153 abstract boolean doPostDeleteLI(boolean delete); 9154 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9155 9156 /** 9157 * Called before the source arguments are copied. This is used mostly 9158 * for MoveParams when it needs to read the source file to put it in the 9159 * destination. 9160 */ 9161 int doPreCopy() { 9162 return PackageManager.INSTALL_SUCCEEDED; 9163 } 9164 9165 /** 9166 * Called after the source arguments are copied. This is used mostly for 9167 * MoveParams when it needs to read the source file to put it in the 9168 * destination. 9169 * 9170 * @return 9171 */ 9172 int doPostCopy(int uid) { 9173 return PackageManager.INSTALL_SUCCEEDED; 9174 } 9175 9176 protected boolean isFwdLocked() { 9177 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9178 } 9179 9180 protected boolean isExternal() { 9181 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9182 } 9183 9184 UserHandle getUser() { 9185 return user; 9186 } 9187 } 9188 9189 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9190 if (!allCodePaths.isEmpty()) { 9191 if (instructionSets == null) { 9192 throw new IllegalStateException("instructionSet == null"); 9193 } 9194 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9195 for (String codePath : allCodePaths) { 9196 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9197 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9198 if (retCode < 0) { 9199 Slog.w(TAG, "Couldn't remove dex file for package: " 9200 + " at location " + codePath + ", retcode=" + retCode); 9201 // we don't consider this to be a failure of the core package deletion 9202 } 9203 } 9204 } 9205 } 9206 } 9207 9208 /** 9209 * Logic to handle installation of non-ASEC applications, including copying 9210 * and renaming logic. 9211 */ 9212 class FileInstallArgs extends InstallArgs { 9213 private File codeFile; 9214 private File resourceFile; 9215 private File legacyNativeLibraryPath; 9216 9217 // Example topology: 9218 // /data/app/com.example/base.apk 9219 // /data/app/com.example/split_foo.apk 9220 // /data/app/com.example/lib/arm/libfoo.so 9221 // /data/app/com.example/lib/arm64/libfoo.so 9222 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9223 9224 /** New install */ 9225 FileInstallArgs(InstallParams params) { 9226 super(params.origin, params.observer, params.installFlags, 9227 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9228 null /* instruction sets */, params.packageAbiOverride); 9229 if (isFwdLocked()) { 9230 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9231 } 9232 } 9233 9234 /** Existing install */ 9235 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9236 String[] instructionSets) { 9237 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9238 this.codeFile = (codePath != null) ? new File(codePath) : null; 9239 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9240 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9241 new File(legacyNativeLibraryPath) : null; 9242 } 9243 9244 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9245 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9246 isFwdLocked(), abiOverride); 9247 9248 final StorageManager storage = StorageManager.from(mContext); 9249 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9250 } 9251 9252 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9253 if (origin.staged) { 9254 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9255 codeFile = origin.file; 9256 resourceFile = origin.file; 9257 return PackageManager.INSTALL_SUCCEEDED; 9258 } 9259 9260 try { 9261 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9262 codeFile = tempDir; 9263 resourceFile = tempDir; 9264 } catch (IOException e) { 9265 Slog.w(TAG, "Failed to create copy file: " + e); 9266 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9267 } 9268 9269 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9270 @Override 9271 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9272 if (!FileUtils.isValidExtFilename(name)) { 9273 throw new IllegalArgumentException("Invalid filename: " + name); 9274 } 9275 try { 9276 final File file = new File(codeFile, name); 9277 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9278 O_RDWR | O_CREAT, 0644); 9279 Os.chmod(file.getAbsolutePath(), 0644); 9280 return new ParcelFileDescriptor(fd); 9281 } catch (ErrnoException e) { 9282 throw new RemoteException("Failed to open: " + e.getMessage()); 9283 } 9284 } 9285 }; 9286 9287 int ret = PackageManager.INSTALL_SUCCEEDED; 9288 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9289 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9290 Slog.e(TAG, "Failed to copy package"); 9291 return ret; 9292 } 9293 9294 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9295 NativeLibraryHelper.Handle handle = null; 9296 try { 9297 handle = NativeLibraryHelper.Handle.create(codeFile); 9298 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9299 abiOverride); 9300 } catch (IOException e) { 9301 Slog.e(TAG, "Copying native libraries failed", e); 9302 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9303 } finally { 9304 IoUtils.closeQuietly(handle); 9305 } 9306 9307 return ret; 9308 } 9309 9310 int doPreInstall(int status) { 9311 if (status != PackageManager.INSTALL_SUCCEEDED) { 9312 cleanUp(); 9313 } 9314 return status; 9315 } 9316 9317 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9318 if (status != PackageManager.INSTALL_SUCCEEDED) { 9319 cleanUp(); 9320 return false; 9321 } else { 9322 final File beforeCodeFile = codeFile; 9323 final File afterCodeFile = getNextCodePath(pkg.packageName); 9324 9325 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9326 try { 9327 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9328 } catch (ErrnoException e) { 9329 Slog.d(TAG, "Failed to rename", e); 9330 return false; 9331 } 9332 9333 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9334 Slog.d(TAG, "Failed to restorecon"); 9335 return false; 9336 } 9337 9338 // Reflect the rename internally 9339 codeFile = afterCodeFile; 9340 resourceFile = afterCodeFile; 9341 9342 // Reflect the rename in scanned details 9343 pkg.codePath = afterCodeFile.getAbsolutePath(); 9344 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9345 pkg.baseCodePath); 9346 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9347 pkg.splitCodePaths); 9348 9349 // Reflect the rename in app info 9350 pkg.applicationInfo.setCodePath(pkg.codePath); 9351 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9352 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9353 pkg.applicationInfo.setResourcePath(pkg.codePath); 9354 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9355 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9356 9357 return true; 9358 } 9359 } 9360 9361 int doPostInstall(int status, int uid) { 9362 if (status != PackageManager.INSTALL_SUCCEEDED) { 9363 cleanUp(); 9364 } 9365 return status; 9366 } 9367 9368 @Override 9369 String getCodePath() { 9370 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9371 } 9372 9373 @Override 9374 String getResourcePath() { 9375 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9376 } 9377 9378 @Override 9379 String getLegacyNativeLibraryPath() { 9380 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9381 } 9382 9383 private boolean cleanUp() { 9384 if (codeFile == null || !codeFile.exists()) { 9385 return false; 9386 } 9387 9388 if (codeFile.isDirectory()) { 9389 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 9390 } else { 9391 codeFile.delete(); 9392 } 9393 9394 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9395 resourceFile.delete(); 9396 } 9397 9398 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9399 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9400 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9401 } 9402 legacyNativeLibraryPath.delete(); 9403 } 9404 9405 return true; 9406 } 9407 9408 void cleanUpResourcesLI() { 9409 // Try enumerating all code paths before deleting 9410 List<String> allCodePaths = Collections.EMPTY_LIST; 9411 if (codeFile != null && codeFile.exists()) { 9412 try { 9413 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9414 allCodePaths = pkg.getAllCodePaths(); 9415 } catch (PackageParserException e) { 9416 // Ignored; we tried our best 9417 } 9418 } 9419 9420 cleanUp(); 9421 removeDexFiles(allCodePaths, instructionSets); 9422 } 9423 9424 boolean doPostDeleteLI(boolean delete) { 9425 // XXX err, shouldn't we respect the delete flag? 9426 cleanUpResourcesLI(); 9427 return true; 9428 } 9429 } 9430 9431 private boolean isAsecExternal(String cid) { 9432 final String asecPath = PackageHelper.getSdFilesystem(cid); 9433 return !asecPath.startsWith(mAsecInternalPath); 9434 } 9435 9436 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9437 PackageManagerException { 9438 if (copyRet < 0) { 9439 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9440 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9441 throw new PackageManagerException(copyRet, message); 9442 } 9443 } 9444 } 9445 9446 /** 9447 * Extract the MountService "container ID" from the full code path of an 9448 * .apk. 9449 */ 9450 static String cidFromCodePath(String fullCodePath) { 9451 int eidx = fullCodePath.lastIndexOf("/"); 9452 String subStr1 = fullCodePath.substring(0, eidx); 9453 int sidx = subStr1.lastIndexOf("/"); 9454 return subStr1.substring(sidx+1, eidx); 9455 } 9456 9457 /** 9458 * Logic to handle installation of ASEC applications, including copying and 9459 * renaming logic. 9460 */ 9461 class AsecInstallArgs extends InstallArgs { 9462 static final String RES_FILE_NAME = "pkg.apk"; 9463 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9464 9465 String cid; 9466 String packagePath; 9467 String resourcePath; 9468 String legacyNativeLibraryDir; 9469 9470 /** New install */ 9471 AsecInstallArgs(InstallParams params) { 9472 super(params.origin, params.observer, params.installFlags, 9473 params.installerPackageName, params.getManifestDigest(), 9474 params.getUser(), null /* instruction sets */, 9475 params.packageAbiOverride); 9476 } 9477 9478 /** Existing install */ 9479 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9480 boolean isExternal, boolean isForwardLocked) { 9481 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9482 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9483 instructionSets, null); 9484 // Hackily pretend we're still looking at a full code path 9485 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9486 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9487 } 9488 9489 // Extract cid from fullCodePath 9490 int eidx = fullCodePath.lastIndexOf("/"); 9491 String subStr1 = fullCodePath.substring(0, eidx); 9492 int sidx = subStr1.lastIndexOf("/"); 9493 cid = subStr1.substring(sidx+1, eidx); 9494 setMountPath(subStr1); 9495 } 9496 9497 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9498 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9499 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9500 instructionSets, null); 9501 this.cid = cid; 9502 setMountPath(PackageHelper.getSdDir(cid)); 9503 } 9504 9505 void createCopyFile() { 9506 cid = mInstallerService.allocateExternalStageCidLegacy(); 9507 } 9508 9509 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9510 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9511 abiOverride); 9512 9513 final File target; 9514 if (isExternal()) { 9515 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9516 } else { 9517 target = Environment.getDataDirectory(); 9518 } 9519 9520 final StorageManager storage = StorageManager.from(mContext); 9521 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9522 } 9523 9524 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9525 if (origin.staged) { 9526 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9527 cid = origin.cid; 9528 setMountPath(PackageHelper.getSdDir(cid)); 9529 return PackageManager.INSTALL_SUCCEEDED; 9530 } 9531 9532 if (temp) { 9533 createCopyFile(); 9534 } else { 9535 /* 9536 * Pre-emptively destroy the container since it's destroyed if 9537 * copying fails due to it existing anyway. 9538 */ 9539 PackageHelper.destroySdDir(cid); 9540 } 9541 9542 final String newMountPath = imcs.copyPackageToContainer( 9543 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9544 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9545 9546 if (newMountPath != null) { 9547 setMountPath(newMountPath); 9548 return PackageManager.INSTALL_SUCCEEDED; 9549 } else { 9550 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9551 } 9552 } 9553 9554 @Override 9555 String getCodePath() { 9556 return packagePath; 9557 } 9558 9559 @Override 9560 String getResourcePath() { 9561 return resourcePath; 9562 } 9563 9564 @Override 9565 String getLegacyNativeLibraryPath() { 9566 return legacyNativeLibraryDir; 9567 } 9568 9569 int doPreInstall(int status) { 9570 if (status != PackageManager.INSTALL_SUCCEEDED) { 9571 // Destroy container 9572 PackageHelper.destroySdDir(cid); 9573 } else { 9574 boolean mounted = PackageHelper.isContainerMounted(cid); 9575 if (!mounted) { 9576 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9577 Process.SYSTEM_UID); 9578 if (newMountPath != null) { 9579 setMountPath(newMountPath); 9580 } else { 9581 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9582 } 9583 } 9584 } 9585 return status; 9586 } 9587 9588 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9589 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9590 String newMountPath = null; 9591 if (PackageHelper.isContainerMounted(cid)) { 9592 // Unmount the container 9593 if (!PackageHelper.unMountSdDir(cid)) { 9594 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9595 return false; 9596 } 9597 } 9598 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9599 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9600 " which might be stale. Will try to clean up."); 9601 // Clean up the stale container and proceed to recreate. 9602 if (!PackageHelper.destroySdDir(newCacheId)) { 9603 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9604 return false; 9605 } 9606 // Successfully cleaned up stale container. Try to rename again. 9607 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9608 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9609 + " inspite of cleaning it up."); 9610 return false; 9611 } 9612 } 9613 if (!PackageHelper.isContainerMounted(newCacheId)) { 9614 Slog.w(TAG, "Mounting container " + newCacheId); 9615 newMountPath = PackageHelper.mountSdDir(newCacheId, 9616 getEncryptKey(), Process.SYSTEM_UID); 9617 } else { 9618 newMountPath = PackageHelper.getSdDir(newCacheId); 9619 } 9620 if (newMountPath == null) { 9621 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9622 return false; 9623 } 9624 Log.i(TAG, "Succesfully renamed " + cid + 9625 " to " + newCacheId + 9626 " at new path: " + newMountPath); 9627 cid = newCacheId; 9628 9629 final File beforeCodeFile = new File(packagePath); 9630 setMountPath(newMountPath); 9631 final File afterCodeFile = new File(packagePath); 9632 9633 // Reflect the rename in scanned details 9634 pkg.codePath = afterCodeFile.getAbsolutePath(); 9635 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9636 pkg.baseCodePath); 9637 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9638 pkg.splitCodePaths); 9639 9640 // Reflect the rename in app info 9641 pkg.applicationInfo.setCodePath(pkg.codePath); 9642 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9643 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9644 pkg.applicationInfo.setResourcePath(pkg.codePath); 9645 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9646 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9647 9648 return true; 9649 } 9650 9651 private void setMountPath(String mountPath) { 9652 final File mountFile = new File(mountPath); 9653 9654 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9655 if (monolithicFile.exists()) { 9656 packagePath = monolithicFile.getAbsolutePath(); 9657 if (isFwdLocked()) { 9658 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9659 } else { 9660 resourcePath = packagePath; 9661 } 9662 } else { 9663 packagePath = mountFile.getAbsolutePath(); 9664 resourcePath = packagePath; 9665 } 9666 9667 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9668 } 9669 9670 int doPostInstall(int status, int uid) { 9671 if (status != PackageManager.INSTALL_SUCCEEDED) { 9672 cleanUp(); 9673 } else { 9674 final int groupOwner; 9675 final String protectedFile; 9676 if (isFwdLocked()) { 9677 groupOwner = UserHandle.getSharedAppGid(uid); 9678 protectedFile = RES_FILE_NAME; 9679 } else { 9680 groupOwner = -1; 9681 protectedFile = null; 9682 } 9683 9684 if (uid < Process.FIRST_APPLICATION_UID 9685 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9686 Slog.e(TAG, "Failed to finalize " + cid); 9687 PackageHelper.destroySdDir(cid); 9688 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9689 } 9690 9691 boolean mounted = PackageHelper.isContainerMounted(cid); 9692 if (!mounted) { 9693 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9694 } 9695 } 9696 return status; 9697 } 9698 9699 private void cleanUp() { 9700 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9701 9702 // Destroy secure container 9703 PackageHelper.destroySdDir(cid); 9704 } 9705 9706 private List<String> getAllCodePaths() { 9707 final File codeFile = new File(getCodePath()); 9708 if (codeFile != null && codeFile.exists()) { 9709 try { 9710 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9711 return pkg.getAllCodePaths(); 9712 } catch (PackageParserException e) { 9713 // Ignored; we tried our best 9714 } 9715 } 9716 return Collections.EMPTY_LIST; 9717 } 9718 9719 void cleanUpResourcesLI() { 9720 // Enumerate all code paths before deleting 9721 cleanUpResourcesLI(getAllCodePaths()); 9722 } 9723 9724 private void cleanUpResourcesLI(List<String> allCodePaths) { 9725 cleanUp(); 9726 removeDexFiles(allCodePaths, instructionSets); 9727 } 9728 9729 9730 9731 String getPackageName() { 9732 return getAsecPackageName(cid); 9733 } 9734 9735 boolean doPostDeleteLI(boolean delete) { 9736 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9737 final List<String> allCodePaths = getAllCodePaths(); 9738 boolean mounted = PackageHelper.isContainerMounted(cid); 9739 if (mounted) { 9740 // Unmount first 9741 if (PackageHelper.unMountSdDir(cid)) { 9742 mounted = false; 9743 } 9744 } 9745 if (!mounted && delete) { 9746 cleanUpResourcesLI(allCodePaths); 9747 } 9748 return !mounted; 9749 } 9750 9751 @Override 9752 int doPreCopy() { 9753 if (isFwdLocked()) { 9754 if (!PackageHelper.fixSdPermissions(cid, 9755 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9756 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9757 } 9758 } 9759 9760 return PackageManager.INSTALL_SUCCEEDED; 9761 } 9762 9763 @Override 9764 int doPostCopy(int uid) { 9765 if (isFwdLocked()) { 9766 if (uid < Process.FIRST_APPLICATION_UID 9767 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9768 RES_FILE_NAME)) { 9769 Slog.e(TAG, "Failed to finalize " + cid); 9770 PackageHelper.destroySdDir(cid); 9771 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9772 } 9773 } 9774 9775 return PackageManager.INSTALL_SUCCEEDED; 9776 } 9777 } 9778 9779 static String getAsecPackageName(String packageCid) { 9780 int idx = packageCid.lastIndexOf("-"); 9781 if (idx == -1) { 9782 return packageCid; 9783 } 9784 return packageCid.substring(0, idx); 9785 } 9786 9787 // Utility method used to create code paths based on package name and available index. 9788 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9789 String idxStr = ""; 9790 int idx = 1; 9791 // Fall back to default value of idx=1 if prefix is not 9792 // part of oldCodePath 9793 if (oldCodePath != null) { 9794 String subStr = oldCodePath; 9795 // Drop the suffix right away 9796 if (suffix != null && subStr.endsWith(suffix)) { 9797 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9798 } 9799 // If oldCodePath already contains prefix find out the 9800 // ending index to either increment or decrement. 9801 int sidx = subStr.lastIndexOf(prefix); 9802 if (sidx != -1) { 9803 subStr = subStr.substring(sidx + prefix.length()); 9804 if (subStr != null) { 9805 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9806 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9807 } 9808 try { 9809 idx = Integer.parseInt(subStr); 9810 if (idx <= 1) { 9811 idx++; 9812 } else { 9813 idx--; 9814 } 9815 } catch(NumberFormatException e) { 9816 } 9817 } 9818 } 9819 } 9820 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9821 return prefix + idxStr; 9822 } 9823 9824 private File getNextCodePath(String packageName) { 9825 int suffix = 1; 9826 File result; 9827 do { 9828 result = new File(mAppInstallDir, packageName + "-" + suffix); 9829 suffix++; 9830 } while (result.exists()); 9831 return result; 9832 } 9833 9834 // Utility method that returns the relative package path with respect 9835 // to the installation directory. Like say for /data/data/com.test-1.apk 9836 // string com.test-1 is returned. 9837 static String deriveCodePathName(String codePath) { 9838 if (codePath == null) { 9839 return null; 9840 } 9841 final File codeFile = new File(codePath); 9842 final String name = codeFile.getName(); 9843 if (codeFile.isDirectory()) { 9844 return name; 9845 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9846 final int lastDot = name.lastIndexOf('.'); 9847 return name.substring(0, lastDot); 9848 } else { 9849 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9850 return null; 9851 } 9852 } 9853 9854 class PackageInstalledInfo { 9855 String name; 9856 int uid; 9857 // The set of users that originally had this package installed. 9858 int[] origUsers; 9859 // The set of users that now have this package installed. 9860 int[] newUsers; 9861 PackageParser.Package pkg; 9862 int returnCode; 9863 String returnMsg; 9864 PackageRemovedInfo removedInfo; 9865 9866 public void setError(int code, String msg) { 9867 returnCode = code; 9868 returnMsg = msg; 9869 Slog.w(TAG, msg); 9870 } 9871 9872 public void setError(String msg, PackageParserException e) { 9873 returnCode = e.error; 9874 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9875 Slog.w(TAG, msg, e); 9876 } 9877 9878 public void setError(String msg, PackageManagerException e) { 9879 returnCode = e.error; 9880 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9881 Slog.w(TAG, msg, e); 9882 } 9883 9884 // In some error cases we want to convey more info back to the observer 9885 String origPackage; 9886 String origPermission; 9887 } 9888 9889 /* 9890 * Install a non-existing package. 9891 */ 9892 private void installNewPackageLI(PackageParser.Package pkg, 9893 int parseFlags, int scanFlags, UserHandle user, 9894 String installerPackageName, PackageInstalledInfo res) { 9895 // Remember this for later, in case we need to rollback this install 9896 String pkgName = pkg.packageName; 9897 9898 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9899 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9900 synchronized(mPackages) { 9901 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9902 // A package with the same name is already installed, though 9903 // it has been renamed to an older name. The package we 9904 // are trying to install should be installed as an update to 9905 // the existing one, but that has not been requested, so bail. 9906 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9907 + " without first uninstalling package running as " 9908 + mSettings.mRenamedPackages.get(pkgName)); 9909 return; 9910 } 9911 if (mPackages.containsKey(pkgName)) { 9912 // Don't allow installation over an existing package with the same name. 9913 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9914 + " without first uninstalling."); 9915 return; 9916 } 9917 } 9918 9919 try { 9920 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9921 System.currentTimeMillis(), user); 9922 9923 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9924 // delete the partially installed application. the data directory will have to be 9925 // restored if it was already existing 9926 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9927 // remove package from internal structures. Note that we want deletePackageX to 9928 // delete the package data and cache directories that it created in 9929 // scanPackageLocked, unless those directories existed before we even tried to 9930 // install. 9931 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9932 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9933 res.removedInfo, true); 9934 } 9935 9936 } catch (PackageManagerException e) { 9937 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9938 } 9939 } 9940 9941 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9942 // Upgrade keysets are being used. Determine if new package has a superset of the 9943 // required keys. 9944 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9945 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9946 for (int i = 0; i < upgradeKeySets.length; i++) { 9947 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9948 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9949 return true; 9950 } 9951 } 9952 return false; 9953 } 9954 9955 private void replacePackageLI(PackageParser.Package pkg, 9956 int parseFlags, int scanFlags, UserHandle user, 9957 String installerPackageName, PackageInstalledInfo res) { 9958 PackageParser.Package oldPackage; 9959 String pkgName = pkg.packageName; 9960 int[] allUsers; 9961 boolean[] perUserInstalled; 9962 9963 // First find the old package info and check signatures 9964 synchronized(mPackages) { 9965 oldPackage = mPackages.get(pkgName); 9966 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9967 PackageSetting ps = mSettings.mPackages.get(pkgName); 9968 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9969 // default to original signature matching 9970 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9971 != PackageManager.SIGNATURE_MATCH) { 9972 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9973 "New package has a different signature: " + pkgName); 9974 return; 9975 } 9976 } else { 9977 if(!checkUpgradeKeySetLP(ps, pkg)) { 9978 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9979 "New package not signed by keys specified by upgrade-keysets: " 9980 + pkgName); 9981 return; 9982 } 9983 } 9984 9985 // In case of rollback, remember per-user/profile install state 9986 allUsers = sUserManager.getUserIds(); 9987 perUserInstalled = new boolean[allUsers.length]; 9988 for (int i = 0; i < allUsers.length; i++) { 9989 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9990 } 9991 } 9992 9993 boolean sysPkg = (isSystemApp(oldPackage)); 9994 if (sysPkg) { 9995 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9996 user, allUsers, perUserInstalled, installerPackageName, res); 9997 } else { 9998 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9999 user, allUsers, perUserInstalled, installerPackageName, res); 10000 } 10001 } 10002 10003 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10004 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10005 int[] allUsers, boolean[] perUserInstalled, 10006 String installerPackageName, PackageInstalledInfo res) { 10007 String pkgName = deletedPackage.packageName; 10008 boolean deletedPkg = true; 10009 boolean updatedSettings = false; 10010 10011 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10012 + deletedPackage); 10013 long origUpdateTime; 10014 if (pkg.mExtras != null) { 10015 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10016 } else { 10017 origUpdateTime = 0; 10018 } 10019 10020 // First delete the existing package while retaining the data directory 10021 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10022 res.removedInfo, true)) { 10023 // If the existing package wasn't successfully deleted 10024 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10025 deletedPkg = false; 10026 } else { 10027 // Successfully deleted the old package; proceed with replace. 10028 10029 // If deleted package lived in a container, give users a chance to 10030 // relinquish resources before killing. 10031 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10032 if (DEBUG_INSTALL) { 10033 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10034 } 10035 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10036 final ArrayList<String> pkgList = new ArrayList<String>(1); 10037 pkgList.add(deletedPackage.applicationInfo.packageName); 10038 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10039 } 10040 10041 deleteCodeCacheDirsLI(pkgName); 10042 try { 10043 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10044 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10045 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10046 updatedSettings = true; 10047 } catch (PackageManagerException e) { 10048 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10049 } 10050 } 10051 10052 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10053 // remove package from internal structures. Note that we want deletePackageX to 10054 // delete the package data and cache directories that it created in 10055 // scanPackageLocked, unless those directories existed before we even tried to 10056 // install. 10057 if(updatedSettings) { 10058 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10059 deletePackageLI( 10060 pkgName, null, true, allUsers, perUserInstalled, 10061 PackageManager.DELETE_KEEP_DATA, 10062 res.removedInfo, true); 10063 } 10064 // Since we failed to install the new package we need to restore the old 10065 // package that we deleted. 10066 if (deletedPkg) { 10067 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10068 File restoreFile = new File(deletedPackage.codePath); 10069 // Parse old package 10070 boolean oldOnSd = isExternal(deletedPackage); 10071 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10072 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10073 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10074 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10075 try { 10076 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10077 } catch (PackageManagerException e) { 10078 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10079 + e.getMessage()); 10080 return; 10081 } 10082 // Restore of old package succeeded. Update permissions. 10083 // writer 10084 synchronized (mPackages) { 10085 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10086 UPDATE_PERMISSIONS_ALL); 10087 // can downgrade to reader 10088 mSettings.writeLPr(); 10089 } 10090 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10091 } 10092 } 10093 } 10094 10095 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10096 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10097 int[] allUsers, boolean[] perUserInstalled, 10098 String installerPackageName, PackageInstalledInfo res) { 10099 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10100 + ", old=" + deletedPackage); 10101 boolean disabledSystem = false; 10102 boolean updatedSettings = false; 10103 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10104 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10105 != 0) { 10106 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10107 } 10108 String packageName = deletedPackage.packageName; 10109 if (packageName == null) { 10110 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10111 "Attempt to delete null packageName."); 10112 return; 10113 } 10114 PackageParser.Package oldPkg; 10115 PackageSetting oldPkgSetting; 10116 // reader 10117 synchronized (mPackages) { 10118 oldPkg = mPackages.get(packageName); 10119 oldPkgSetting = mSettings.mPackages.get(packageName); 10120 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10121 (oldPkgSetting == null)) { 10122 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10123 "Couldn't find package:" + packageName + " information"); 10124 return; 10125 } 10126 } 10127 10128 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10129 10130 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10131 res.removedInfo.removedPackage = packageName; 10132 // Remove existing system package 10133 removePackageLI(oldPkgSetting, true); 10134 // writer 10135 synchronized (mPackages) { 10136 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10137 if (!disabledSystem && deletedPackage != null) { 10138 // We didn't need to disable the .apk as a current system package, 10139 // which means we are replacing another update that is already 10140 // installed. We need to make sure to delete the older one's .apk. 10141 res.removedInfo.args = createInstallArgsForExisting(0, 10142 deletedPackage.applicationInfo.getCodePath(), 10143 deletedPackage.applicationInfo.getResourcePath(), 10144 deletedPackage.applicationInfo.nativeLibraryRootDir, 10145 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10146 } else { 10147 res.removedInfo.args = null; 10148 } 10149 } 10150 10151 // Successfully disabled the old package. Now proceed with re-installation 10152 deleteCodeCacheDirsLI(packageName); 10153 10154 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10155 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10156 10157 PackageParser.Package newPackage = null; 10158 try { 10159 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10160 if (newPackage.mExtras != null) { 10161 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10162 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10163 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10164 10165 // is the update attempting to change shared user? that isn't going to work... 10166 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10167 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10168 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10169 + " to " + newPkgSetting.sharedUser); 10170 updatedSettings = true; 10171 } 10172 } 10173 10174 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10175 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10176 updatedSettings = true; 10177 } 10178 10179 } catch (PackageManagerException e) { 10180 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10181 } 10182 10183 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10184 // Re installation failed. Restore old information 10185 // Remove new pkg information 10186 if (newPackage != null) { 10187 removeInstalledPackageLI(newPackage, true); 10188 } 10189 // Add back the old system package 10190 try { 10191 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10192 } catch (PackageManagerException e) { 10193 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10194 } 10195 // Restore the old system information in Settings 10196 synchronized (mPackages) { 10197 if (disabledSystem) { 10198 mSettings.enableSystemPackageLPw(packageName); 10199 } 10200 if (updatedSettings) { 10201 mSettings.setInstallerPackageName(packageName, 10202 oldPkgSetting.installerPackageName); 10203 } 10204 mSettings.writeLPr(); 10205 } 10206 } 10207 } 10208 10209 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10210 int[] allUsers, boolean[] perUserInstalled, 10211 PackageInstalledInfo res) { 10212 String pkgName = newPackage.packageName; 10213 synchronized (mPackages) { 10214 //write settings. the installStatus will be incomplete at this stage. 10215 //note that the new package setting would have already been 10216 //added to mPackages. It hasn't been persisted yet. 10217 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10218 mSettings.writeLPr(); 10219 } 10220 10221 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10222 10223 synchronized (mPackages) { 10224 updatePermissionsLPw(newPackage.packageName, newPackage, 10225 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10226 ? UPDATE_PERMISSIONS_ALL : 0)); 10227 // For system-bundled packages, we assume that installing an upgraded version 10228 // of the package implies that the user actually wants to run that new code, 10229 // so we enable the package. 10230 if (isSystemApp(newPackage)) { 10231 // NB: implicit assumption that system package upgrades apply to all users 10232 if (DEBUG_INSTALL) { 10233 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10234 } 10235 PackageSetting ps = mSettings.mPackages.get(pkgName); 10236 if (ps != null) { 10237 if (res.origUsers != null) { 10238 for (int userHandle : res.origUsers) { 10239 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10240 userHandle, installerPackageName); 10241 } 10242 } 10243 // Also convey the prior install/uninstall state 10244 if (allUsers != null && perUserInstalled != null) { 10245 for (int i = 0; i < allUsers.length; i++) { 10246 if (DEBUG_INSTALL) { 10247 Slog.d(TAG, " user " + allUsers[i] 10248 + " => " + perUserInstalled[i]); 10249 } 10250 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10251 } 10252 // these install state changes will be persisted in the 10253 // upcoming call to mSettings.writeLPr(). 10254 } 10255 } 10256 } 10257 res.name = pkgName; 10258 res.uid = newPackage.applicationInfo.uid; 10259 res.pkg = newPackage; 10260 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10261 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10262 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10263 //to update install status 10264 mSettings.writeLPr(); 10265 } 10266 } 10267 10268 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10269 final int installFlags = args.installFlags; 10270 String installerPackageName = args.installerPackageName; 10271 File tmpPackageFile = new File(args.getCodePath()); 10272 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10273 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10274 boolean replace = false; 10275 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10276 // Result object to be returned 10277 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10278 10279 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10280 // Retrieve PackageSettings and parse package 10281 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10282 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10283 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10284 PackageParser pp = new PackageParser(); 10285 pp.setSeparateProcesses(mSeparateProcesses); 10286 pp.setDisplayMetrics(mMetrics); 10287 10288 final PackageParser.Package pkg; 10289 try { 10290 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10291 } catch (PackageParserException e) { 10292 res.setError("Failed parse during installPackageLI", e); 10293 return; 10294 } 10295 10296 // Mark that we have an install time CPU ABI override. 10297 pkg.cpuAbiOverride = args.abiOverride; 10298 10299 String pkgName = res.name = pkg.packageName; 10300 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10301 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10302 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10303 return; 10304 } 10305 } 10306 10307 try { 10308 pp.collectCertificates(pkg, parseFlags); 10309 pp.collectManifestDigest(pkg); 10310 } catch (PackageParserException e) { 10311 res.setError("Failed collect during installPackageLI", e); 10312 return; 10313 } 10314 10315 /* If the installer passed in a manifest digest, compare it now. */ 10316 if (args.manifestDigest != null) { 10317 if (DEBUG_INSTALL) { 10318 final String parsedManifest = pkg.manifestDigest == null ? "null" 10319 : pkg.manifestDigest.toString(); 10320 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10321 + parsedManifest); 10322 } 10323 10324 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10325 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10326 return; 10327 } 10328 } else if (DEBUG_INSTALL) { 10329 final String parsedManifest = pkg.manifestDigest == null 10330 ? "null" : pkg.manifestDigest.toString(); 10331 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10332 } 10333 10334 // Get rid of all references to package scan path via parser. 10335 pp = null; 10336 String oldCodePath = null; 10337 boolean systemApp = false; 10338 synchronized (mPackages) { 10339 // Check if installing already existing package 10340 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10341 String oldName = mSettings.mRenamedPackages.get(pkgName); 10342 if (pkg.mOriginalPackages != null 10343 && pkg.mOriginalPackages.contains(oldName) 10344 && mPackages.containsKey(oldName)) { 10345 // This package is derived from an original package, 10346 // and this device has been updating from that original 10347 // name. We must continue using the original name, so 10348 // rename the new package here. 10349 pkg.setPackageName(oldName); 10350 pkgName = pkg.packageName; 10351 replace = true; 10352 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10353 + oldName + " pkgName=" + pkgName); 10354 } else if (mPackages.containsKey(pkgName)) { 10355 // This package, under its official name, already exists 10356 // on the device; we should replace it. 10357 replace = true; 10358 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10359 } 10360 } 10361 10362 PackageSetting ps = mSettings.mPackages.get(pkgName); 10363 if (ps != null) { 10364 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10365 10366 // Quick sanity check that we're signed correctly if updating; 10367 // we'll check this again later when scanning, but we want to 10368 // bail early here before tripping over redefined permissions. 10369 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10370 try { 10371 verifySignaturesLP(ps, pkg); 10372 } catch (PackageManagerException e) { 10373 res.setError(e.error, e.getMessage()); 10374 return; 10375 } 10376 } else { 10377 if (!checkUpgradeKeySetLP(ps, pkg)) { 10378 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 10379 + pkg.packageName + " upgrade keys do not match the " 10380 + "previously installed version"); 10381 return; 10382 } 10383 } 10384 10385 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10386 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10387 systemApp = (ps.pkg.applicationInfo.flags & 10388 ApplicationInfo.FLAG_SYSTEM) != 0; 10389 } 10390 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10391 } 10392 10393 // Check whether the newly-scanned package wants to define an already-defined perm 10394 int N = pkg.permissions.size(); 10395 for (int i = N-1; i >= 0; i--) { 10396 PackageParser.Permission perm = pkg.permissions.get(i); 10397 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10398 if (bp != null) { 10399 // If the defining package is signed with our cert, it's okay. This 10400 // also includes the "updating the same package" case, of course. 10401 // "updating same package" could also involve key-rotation. 10402 final boolean sigsOk; 10403 if (!bp.sourcePackage.equals(pkg.packageName) 10404 || !(bp.packageSetting instanceof PackageSetting) 10405 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10406 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10407 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10408 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10409 } else { 10410 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10411 } 10412 if (!sigsOk) { 10413 // If the owning package is the system itself, we log but allow 10414 // install to proceed; we fail the install on all other permission 10415 // redefinitions. 10416 if (!bp.sourcePackage.equals("android")) { 10417 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10418 + pkg.packageName + " attempting to redeclare permission " 10419 + perm.info.name + " already owned by " + bp.sourcePackage); 10420 res.origPermission = perm.info.name; 10421 res.origPackage = bp.sourcePackage; 10422 return; 10423 } else { 10424 Slog.w(TAG, "Package " + pkg.packageName 10425 + " attempting to redeclare system permission " 10426 + perm.info.name + "; ignoring new declaration"); 10427 pkg.permissions.remove(i); 10428 } 10429 } 10430 } 10431 } 10432 10433 } 10434 10435 if (systemApp && onSd) { 10436 // Disable updates to system apps on sdcard 10437 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10438 "Cannot install updates to system apps on sdcard"); 10439 return; 10440 } 10441 10442 // If app directory is not writable, dexopt will be called after the rename 10443 if (!forwardLocked && pkg.applicationInfo.isInternal()) { 10444 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 10445 scanFlags |= SCAN_NO_DEX; 10446 try { 10447 deriveNonSystemPackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 10448 true /* extract libs */); 10449 } catch (PackageManagerException pme) { 10450 Slog.e(TAG, "Error deriving application ABI", pme); 10451 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 10452 return; 10453 } 10454 10455 // Run dexopt before old package gets removed, to minimize time when app is unavailable 10456 int result = mPackageDexOptimizer 10457 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 10458 false /* defer */, false /* inclDependencies */, 10459 true /*bootComplete*/); 10460 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 10461 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 10462 return; 10463 } 10464 } 10465 10466 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10467 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10468 return; 10469 } 10470 10471 if (replace) { 10472 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10473 installerPackageName, res); 10474 } else { 10475 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10476 args.user, installerPackageName, res); 10477 } 10478 synchronized (mPackages) { 10479 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10480 if (ps != null) { 10481 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10482 } 10483 } 10484 } 10485 10486 private static boolean isMultiArch(PackageSetting ps) { 10487 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10488 } 10489 10490 private static boolean isMultiArch(ApplicationInfo info) { 10491 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10492 } 10493 10494 private static boolean isExternal(PackageParser.Package pkg) { 10495 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10496 } 10497 10498 private static boolean isExternal(PackageSetting ps) { 10499 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10500 } 10501 10502 private static boolean isExternal(ApplicationInfo info) { 10503 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10504 } 10505 10506 private static boolean isSystemApp(PackageParser.Package pkg) { 10507 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10508 } 10509 10510 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10511 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 10512 } 10513 10514 private static boolean isSystemApp(PackageSetting ps) { 10515 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10516 } 10517 10518 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10519 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10520 } 10521 10522 private int packageFlagsToInstallFlags(PackageSetting ps) { 10523 int installFlags = 0; 10524 if (isExternal(ps)) { 10525 installFlags |= PackageManager.INSTALL_EXTERNAL; 10526 } 10527 if (ps.isForwardLocked()) { 10528 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10529 } 10530 return installFlags; 10531 } 10532 10533 private void deleteTempPackageFiles() { 10534 final FilenameFilter filter = new FilenameFilter() { 10535 public boolean accept(File dir, String name) { 10536 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10537 } 10538 }; 10539 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10540 file.delete(); 10541 } 10542 } 10543 10544 @Override 10545 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10546 int flags) { 10547 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10548 flags); 10549 } 10550 10551 @Override 10552 public void deletePackage(final String packageName, 10553 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10554 mContext.enforceCallingOrSelfPermission( 10555 android.Manifest.permission.DELETE_PACKAGES, null); 10556 final int uid = Binder.getCallingUid(); 10557 if (UserHandle.getUserId(uid) != userId) { 10558 mContext.enforceCallingPermission( 10559 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10560 "deletePackage for user " + userId); 10561 } 10562 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10563 try { 10564 observer.onPackageDeleted(packageName, 10565 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10566 } catch (RemoteException re) { 10567 } 10568 return; 10569 } 10570 10571 boolean uninstallBlocked = false; 10572 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10573 int[] users = sUserManager.getUserIds(); 10574 for (int i = 0; i < users.length; ++i) { 10575 if (getBlockUninstallForUser(packageName, users[i])) { 10576 uninstallBlocked = true; 10577 break; 10578 } 10579 } 10580 } else { 10581 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10582 } 10583 if (uninstallBlocked) { 10584 try { 10585 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10586 null); 10587 } catch (RemoteException re) { 10588 } 10589 return; 10590 } 10591 10592 if (DEBUG_REMOVE) { 10593 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10594 } 10595 // Queue up an async operation since the package deletion may take a little while. 10596 mHandler.post(new Runnable() { 10597 public void run() { 10598 mHandler.removeCallbacks(this); 10599 final int returnCode = deletePackageX(packageName, userId, flags); 10600 if (observer != null) { 10601 try { 10602 observer.onPackageDeleted(packageName, returnCode, null); 10603 } catch (RemoteException e) { 10604 Log.i(TAG, "Observer no longer exists."); 10605 } //end catch 10606 } //end if 10607 } //end run 10608 }); 10609 } 10610 10611 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10612 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10613 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10614 try { 10615 if (dpm != null) { 10616 if (dpm.isDeviceOwner(packageName)) { 10617 return true; 10618 } 10619 int[] users; 10620 if (userId == UserHandle.USER_ALL) { 10621 users = sUserManager.getUserIds(); 10622 } else { 10623 users = new int[]{userId}; 10624 } 10625 for (int i = 0; i < users.length; ++i) { 10626 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10627 return true; 10628 } 10629 } 10630 } 10631 } catch (RemoteException e) { 10632 } 10633 return false; 10634 } 10635 10636 /** 10637 * This method is an internal method that could be get invoked either 10638 * to delete an installed package or to clean up a failed installation. 10639 * After deleting an installed package, a broadcast is sent to notify any 10640 * listeners that the package has been installed. For cleaning up a failed 10641 * installation, the broadcast is not necessary since the package's 10642 * installation wouldn't have sent the initial broadcast either 10643 * The key steps in deleting a package are 10644 * deleting the package information in internal structures like mPackages, 10645 * deleting the packages base directories through installd 10646 * updating mSettings to reflect current status 10647 * persisting settings for later use 10648 * sending a broadcast if necessary 10649 */ 10650 private int deletePackageX(String packageName, int userId, int flags) { 10651 final PackageRemovedInfo info = new PackageRemovedInfo(); 10652 final boolean res; 10653 10654 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10655 ? UserHandle.ALL : new UserHandle(userId); 10656 10657 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10658 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10659 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10660 } 10661 10662 boolean removedForAllUsers = false; 10663 boolean systemUpdate = false; 10664 10665 // for the uninstall-updates case and restricted profiles, remember the per- 10666 // userhandle installed state 10667 int[] allUsers; 10668 boolean[] perUserInstalled; 10669 synchronized (mPackages) { 10670 PackageSetting ps = mSettings.mPackages.get(packageName); 10671 allUsers = sUserManager.getUserIds(); 10672 perUserInstalled = new boolean[allUsers.length]; 10673 for (int i = 0; i < allUsers.length; i++) { 10674 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10675 } 10676 } 10677 10678 synchronized (mInstallLock) { 10679 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10680 res = deletePackageLI(packageName, removeForUser, 10681 true, allUsers, perUserInstalled, 10682 flags | REMOVE_CHATTY, info, true); 10683 systemUpdate = info.isRemovedPackageSystemUpdate; 10684 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10685 removedForAllUsers = true; 10686 } 10687 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10688 + " removedForAllUsers=" + removedForAllUsers); 10689 } 10690 10691 if (res) { 10692 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10693 10694 // If the removed package was a system update, the old system package 10695 // was re-enabled; we need to broadcast this information 10696 if (systemUpdate) { 10697 Bundle extras = new Bundle(1); 10698 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10699 ? info.removedAppId : info.uid); 10700 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10701 10702 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10703 extras, null, null, null); 10704 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10705 extras, null, null, null); 10706 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10707 null, packageName, null, null); 10708 } 10709 } 10710 // Force a gc here. 10711 Runtime.getRuntime().gc(); 10712 // Delete the resources here after sending the broadcast to let 10713 // other processes clean up before deleting resources. 10714 if (info.args != null) { 10715 synchronized (mInstallLock) { 10716 info.args.doPostDeleteLI(true); 10717 } 10718 } 10719 10720 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10721 } 10722 10723 static class PackageRemovedInfo { 10724 String removedPackage; 10725 int uid = -1; 10726 int removedAppId = -1; 10727 int[] removedUsers = null; 10728 boolean isRemovedPackageSystemUpdate = false; 10729 // Clean up resources deleted packages. 10730 InstallArgs args = null; 10731 10732 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10733 Bundle extras = new Bundle(1); 10734 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10735 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10736 if (replacing) { 10737 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10738 } 10739 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10740 if (removedPackage != null) { 10741 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10742 extras, null, null, removedUsers); 10743 if (fullRemove && !replacing) { 10744 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10745 extras, null, null, removedUsers); 10746 } 10747 } 10748 if (removedAppId >= 0) { 10749 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10750 removedUsers); 10751 } 10752 } 10753 } 10754 10755 /* 10756 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10757 * flag is not set, the data directory is removed as well. 10758 * make sure this flag is set for partially installed apps. If not its meaningless to 10759 * delete a partially installed application. 10760 */ 10761 private void removePackageDataLI(PackageSetting ps, 10762 int[] allUserHandles, boolean[] perUserInstalled, 10763 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10764 String packageName = ps.name; 10765 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10766 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10767 // Retrieve object to delete permissions for shared user later on 10768 final PackageSetting deletedPs; 10769 // reader 10770 synchronized (mPackages) { 10771 deletedPs = mSettings.mPackages.get(packageName); 10772 if (outInfo != null) { 10773 outInfo.removedPackage = packageName; 10774 outInfo.removedUsers = deletedPs != null 10775 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10776 : null; 10777 } 10778 } 10779 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10780 removeDataDirsLI(packageName); 10781 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10782 } 10783 // writer 10784 synchronized (mPackages) { 10785 if (deletedPs != null) { 10786 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10787 if (outInfo != null) { 10788 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10789 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10790 } 10791 if (deletedPs != null) { 10792 updatePermissionsLPw(deletedPs.name, null, 0); 10793 if (deletedPs.sharedUser != null) { 10794 // remove permissions associated with package 10795 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10796 } 10797 } 10798 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10799 } 10800 // make sure to preserve per-user disabled state if this removal was just 10801 // a downgrade of a system app to the factory package 10802 if (allUserHandles != null && perUserInstalled != null) { 10803 if (DEBUG_REMOVE) { 10804 Slog.d(TAG, "Propagating install state across downgrade"); 10805 } 10806 for (int i = 0; i < allUserHandles.length; i++) { 10807 if (DEBUG_REMOVE) { 10808 Slog.d(TAG, " user " + allUserHandles[i] 10809 + " => " + perUserInstalled[i]); 10810 } 10811 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10812 } 10813 } 10814 } 10815 // can downgrade to reader 10816 if (writeSettings) { 10817 // Save settings now 10818 mSettings.writeLPr(); 10819 } 10820 } 10821 if (outInfo != null) { 10822 // A user ID was deleted here. Go through all users and remove it 10823 // from KeyStore. 10824 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10825 } 10826 } 10827 10828 static boolean locationIsPrivileged(File path) { 10829 try { 10830 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10831 .getCanonicalPath(); 10832 return path.getCanonicalPath().startsWith(privilegedAppDir); 10833 } catch (IOException e) { 10834 Slog.e(TAG, "Unable to access code path " + path); 10835 } 10836 return false; 10837 } 10838 10839 /* 10840 * Tries to delete system package. 10841 */ 10842 private boolean deleteSystemPackageLI(PackageSetting newPs, 10843 int[] allUserHandles, boolean[] perUserInstalled, 10844 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10845 final boolean applyUserRestrictions 10846 = (allUserHandles != null) && (perUserInstalled != null); 10847 PackageSetting disabledPs = null; 10848 // Confirm if the system package has been updated 10849 // An updated system app can be deleted. This will also have to restore 10850 // the system pkg from system partition 10851 // reader 10852 synchronized (mPackages) { 10853 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10854 } 10855 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10856 + " disabledPs=" + disabledPs); 10857 if (disabledPs == null) { 10858 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10859 return false; 10860 } else if (DEBUG_REMOVE) { 10861 Slog.d(TAG, "Deleting system pkg from data partition"); 10862 } 10863 if (DEBUG_REMOVE) { 10864 if (applyUserRestrictions) { 10865 Slog.d(TAG, "Remembering install states:"); 10866 for (int i = 0; i < allUserHandles.length; i++) { 10867 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10868 } 10869 } 10870 } 10871 // Delete the updated package 10872 outInfo.isRemovedPackageSystemUpdate = true; 10873 if (disabledPs.versionCode < newPs.versionCode) { 10874 // Delete data for downgrades 10875 flags &= ~PackageManager.DELETE_KEEP_DATA; 10876 } else { 10877 // Preserve data by setting flag 10878 flags |= PackageManager.DELETE_KEEP_DATA; 10879 } 10880 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10881 allUserHandles, perUserInstalled, outInfo, writeSettings); 10882 if (!ret) { 10883 return false; 10884 } 10885 // writer 10886 synchronized (mPackages) { 10887 // Reinstate the old system package 10888 mSettings.enableSystemPackageLPw(newPs.name); 10889 // Remove any native libraries from the upgraded package. 10890 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10891 } 10892 // Install the system package 10893 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10894 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10895 if (locationIsPrivileged(disabledPs.codePath)) { 10896 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10897 } 10898 10899 final PackageParser.Package newPkg; 10900 try { 10901 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10902 } catch (PackageManagerException e) { 10903 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10904 return false; 10905 } 10906 10907 // writer 10908 synchronized (mPackages) { 10909 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10910 updatePermissionsLPw(newPkg.packageName, newPkg, 10911 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10912 if (applyUserRestrictions) { 10913 if (DEBUG_REMOVE) { 10914 Slog.d(TAG, "Propagating install state across reinstall"); 10915 } 10916 for (int i = 0; i < allUserHandles.length; i++) { 10917 if (DEBUG_REMOVE) { 10918 Slog.d(TAG, " user " + allUserHandles[i] 10919 + " => " + perUserInstalled[i]); 10920 } 10921 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10922 } 10923 // Regardless of writeSettings we need to ensure that this restriction 10924 // state propagation is persisted 10925 mSettings.writeAllUsersPackageRestrictionsLPr(); 10926 } 10927 // can downgrade to reader here 10928 if (writeSettings) { 10929 mSettings.writeLPr(); 10930 } 10931 } 10932 return true; 10933 } 10934 10935 private boolean deleteInstalledPackageLI(PackageSetting ps, 10936 boolean deleteCodeAndResources, int flags, 10937 int[] allUserHandles, boolean[] perUserInstalled, 10938 PackageRemovedInfo outInfo, boolean writeSettings) { 10939 if (outInfo != null) { 10940 outInfo.uid = ps.appId; 10941 } 10942 10943 // Delete package data from internal structures and also remove data if flag is set 10944 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10945 10946 // Delete application code and resources 10947 if (deleteCodeAndResources && (outInfo != null)) { 10948 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10949 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10950 getAppDexInstructionSets(ps)); 10951 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10952 } 10953 return true; 10954 } 10955 10956 @Override 10957 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10958 int userId) { 10959 mContext.enforceCallingOrSelfPermission( 10960 android.Manifest.permission.DELETE_PACKAGES, null); 10961 synchronized (mPackages) { 10962 PackageSetting ps = mSettings.mPackages.get(packageName); 10963 if (ps == null) { 10964 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10965 return false; 10966 } 10967 if (!ps.getInstalled(userId)) { 10968 // Can't block uninstall for an app that is not installed or enabled. 10969 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10970 return false; 10971 } 10972 ps.setBlockUninstall(blockUninstall, userId); 10973 mSettings.writePackageRestrictionsLPr(userId); 10974 } 10975 return true; 10976 } 10977 10978 @Override 10979 public boolean getBlockUninstallForUser(String packageName, int userId) { 10980 synchronized (mPackages) { 10981 PackageSetting ps = mSettings.mPackages.get(packageName); 10982 if (ps == null) { 10983 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10984 return false; 10985 } 10986 return ps.getBlockUninstall(userId); 10987 } 10988 } 10989 10990 /* 10991 * This method handles package deletion in general 10992 */ 10993 private boolean deletePackageLI(String packageName, UserHandle user, 10994 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10995 int flags, PackageRemovedInfo outInfo, 10996 boolean writeSettings) { 10997 if (packageName == null) { 10998 Slog.w(TAG, "Attempt to delete null packageName."); 10999 return false; 11000 } 11001 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11002 PackageSetting ps; 11003 boolean dataOnly = false; 11004 int removeUser = -1; 11005 int appId = -1; 11006 synchronized (mPackages) { 11007 ps = mSettings.mPackages.get(packageName); 11008 if (ps == null) { 11009 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11010 return false; 11011 } 11012 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11013 && user.getIdentifier() != UserHandle.USER_ALL) { 11014 // The caller is asking that the package only be deleted for a single 11015 // user. To do this, we just mark its uninstalled state and delete 11016 // its data. If this is a system app, we only allow this to happen if 11017 // they have set the special DELETE_SYSTEM_APP which requests different 11018 // semantics than normal for uninstalling system apps. 11019 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11020 ps.setUserState(user.getIdentifier(), 11021 COMPONENT_ENABLED_STATE_DEFAULT, 11022 false, //installed 11023 true, //stopped 11024 true, //notLaunched 11025 false, //hidden 11026 null, null, null, 11027 false // blockUninstall 11028 ); 11029 if (!isSystemApp(ps)) { 11030 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11031 // Other user still have this package installed, so all 11032 // we need to do is clear this user's data and save that 11033 // it is uninstalled. 11034 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11035 removeUser = user.getIdentifier(); 11036 appId = ps.appId; 11037 mSettings.writePackageRestrictionsLPr(removeUser); 11038 } else { 11039 // We need to set it back to 'installed' so the uninstall 11040 // broadcasts will be sent correctly. 11041 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11042 ps.setInstalled(true, user.getIdentifier()); 11043 } 11044 } else { 11045 // This is a system app, so we assume that the 11046 // other users still have this package installed, so all 11047 // we need to do is clear this user's data and save that 11048 // it is uninstalled. 11049 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11050 removeUser = user.getIdentifier(); 11051 appId = ps.appId; 11052 mSettings.writePackageRestrictionsLPr(removeUser); 11053 } 11054 } 11055 } 11056 11057 if (removeUser >= 0) { 11058 // From above, we determined that we are deleting this only 11059 // for a single user. Continue the work here. 11060 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11061 if (outInfo != null) { 11062 outInfo.removedPackage = packageName; 11063 outInfo.removedAppId = appId; 11064 outInfo.removedUsers = new int[] {removeUser}; 11065 } 11066 mInstaller.clearUserData(packageName, removeUser); 11067 removeKeystoreDataIfNeeded(removeUser, appId); 11068 schedulePackageCleaning(packageName, removeUser, false); 11069 return true; 11070 } 11071 11072 if (dataOnly) { 11073 // Delete application data first 11074 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11075 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11076 return true; 11077 } 11078 11079 boolean ret = false; 11080 if (isSystemApp(ps)) { 11081 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11082 // When an updated system application is deleted we delete the existing resources as well and 11083 // fall back to existing code in system partition 11084 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11085 flags, outInfo, writeSettings); 11086 } else { 11087 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11088 // Kill application pre-emptively especially for apps on sd. 11089 killApplication(packageName, ps.appId, "uninstall pkg"); 11090 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11091 allUserHandles, perUserInstalled, 11092 outInfo, writeSettings); 11093 } 11094 11095 return ret; 11096 } 11097 11098 private final class ClearStorageConnection implements ServiceConnection { 11099 IMediaContainerService mContainerService; 11100 11101 @Override 11102 public void onServiceConnected(ComponentName name, IBinder service) { 11103 synchronized (this) { 11104 mContainerService = IMediaContainerService.Stub.asInterface(service); 11105 notifyAll(); 11106 } 11107 } 11108 11109 @Override 11110 public void onServiceDisconnected(ComponentName name) { 11111 } 11112 } 11113 11114 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11115 final boolean mounted; 11116 if (Environment.isExternalStorageEmulated()) { 11117 mounted = true; 11118 } else { 11119 final String status = Environment.getExternalStorageState(); 11120 11121 mounted = status.equals(Environment.MEDIA_MOUNTED) 11122 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11123 } 11124 11125 if (!mounted) { 11126 return; 11127 } 11128 11129 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11130 int[] users; 11131 if (userId == UserHandle.USER_ALL) { 11132 users = sUserManager.getUserIds(); 11133 } else { 11134 users = new int[] { userId }; 11135 } 11136 final ClearStorageConnection conn = new ClearStorageConnection(); 11137 if (mContext.bindServiceAsUser( 11138 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11139 try { 11140 for (int curUser : users) { 11141 long timeout = SystemClock.uptimeMillis() + 5000; 11142 synchronized (conn) { 11143 long now = SystemClock.uptimeMillis(); 11144 while (conn.mContainerService == null && now < timeout) { 11145 try { 11146 conn.wait(timeout - now); 11147 } catch (InterruptedException e) { 11148 } 11149 } 11150 } 11151 if (conn.mContainerService == null) { 11152 return; 11153 } 11154 11155 final UserEnvironment userEnv = new UserEnvironment(curUser); 11156 clearDirectory(conn.mContainerService, 11157 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11158 if (allData) { 11159 clearDirectory(conn.mContainerService, 11160 userEnv.buildExternalStorageAppDataDirs(packageName)); 11161 clearDirectory(conn.mContainerService, 11162 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11163 } 11164 } 11165 } finally { 11166 mContext.unbindService(conn); 11167 } 11168 } 11169 } 11170 11171 @Override 11172 public void clearApplicationUserData(final String packageName, 11173 final IPackageDataObserver observer, final int userId) { 11174 mContext.enforceCallingOrSelfPermission( 11175 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11176 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11177 // Queue up an async operation since the package deletion may take a little while. 11178 mHandler.post(new Runnable() { 11179 public void run() { 11180 mHandler.removeCallbacks(this); 11181 final boolean succeeded; 11182 synchronized (mInstallLock) { 11183 succeeded = clearApplicationUserDataLI(packageName, userId); 11184 } 11185 clearExternalStorageDataSync(packageName, userId, true); 11186 if (succeeded) { 11187 // invoke DeviceStorageMonitor's update method to clear any notifications 11188 DeviceStorageMonitorInternal 11189 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11190 if (dsm != null) { 11191 dsm.checkMemory(); 11192 } 11193 } 11194 if(observer != null) { 11195 try { 11196 observer.onRemoveCompleted(packageName, succeeded); 11197 } catch (RemoteException e) { 11198 Log.i(TAG, "Observer no longer exists."); 11199 } 11200 } //end if observer 11201 } //end run 11202 }); 11203 } 11204 11205 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11206 if (packageName == null) { 11207 Slog.w(TAG, "Attempt to delete null packageName."); 11208 return false; 11209 } 11210 11211 // Try finding details about the requested package 11212 PackageParser.Package pkg; 11213 synchronized (mPackages) { 11214 pkg = mPackages.get(packageName); 11215 if (pkg == null) { 11216 final PackageSetting ps = mSettings.mPackages.get(packageName); 11217 if (ps != null) { 11218 pkg = ps.pkg; 11219 } 11220 } 11221 } 11222 11223 if (pkg == null) { 11224 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11225 } 11226 11227 // Always delete data directories for package, even if we found no other 11228 // record of app. This helps users recover from UID mismatches without 11229 // resorting to a full data wipe. 11230 int retCode = mInstaller.clearUserData(packageName, userId); 11231 if (retCode < 0) { 11232 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11233 return false; 11234 } 11235 11236 if (pkg == null) { 11237 return false; 11238 } 11239 11240 if (pkg != null && pkg.applicationInfo != null) { 11241 final int appId = pkg.applicationInfo.uid; 11242 removeKeystoreDataIfNeeded(userId, appId); 11243 } 11244 11245 // Create a native library symlink only if we have native libraries 11246 // and if the native libraries are 32 bit libraries. We do not provide 11247 // this symlink for 64 bit libraries. 11248 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11249 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11250 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11251 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11252 Slog.w(TAG, "Failed linking native library dir"); 11253 return false; 11254 } 11255 } 11256 11257 return true; 11258 } 11259 11260 /** 11261 * Remove entries from the keystore daemon. Will only remove it if the 11262 * {@code appId} is valid. 11263 */ 11264 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11265 if (appId < 0) { 11266 return; 11267 } 11268 11269 final KeyStore keyStore = KeyStore.getInstance(); 11270 if (keyStore != null) { 11271 if (userId == UserHandle.USER_ALL) { 11272 for (final int individual : sUserManager.getUserIds()) { 11273 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11274 } 11275 } else { 11276 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11277 } 11278 } else { 11279 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11280 } 11281 } 11282 11283 @Override 11284 public void deleteApplicationCacheFiles(final String packageName, 11285 final IPackageDataObserver observer) { 11286 mContext.enforceCallingOrSelfPermission( 11287 android.Manifest.permission.DELETE_CACHE_FILES, null); 11288 // Queue up an async operation since the package deletion may take a little while. 11289 final int userId = UserHandle.getCallingUserId(); 11290 mHandler.post(new Runnable() { 11291 public void run() { 11292 mHandler.removeCallbacks(this); 11293 final boolean succeded; 11294 synchronized (mInstallLock) { 11295 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11296 } 11297 clearExternalStorageDataSync(packageName, userId, false); 11298 if(observer != null) { 11299 try { 11300 observer.onRemoveCompleted(packageName, succeded); 11301 } catch (RemoteException e) { 11302 Log.i(TAG, "Observer no longer exists."); 11303 } 11304 } //end if observer 11305 } //end run 11306 }); 11307 } 11308 11309 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11310 if (packageName == null) { 11311 Slog.w(TAG, "Attempt to delete null packageName."); 11312 return false; 11313 } 11314 PackageParser.Package p; 11315 synchronized (mPackages) { 11316 p = mPackages.get(packageName); 11317 } 11318 if (p == null) { 11319 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11320 return false; 11321 } 11322 final ApplicationInfo applicationInfo = p.applicationInfo; 11323 if (applicationInfo == null) { 11324 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11325 return false; 11326 } 11327 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11328 if (retCode < 0) { 11329 Slog.w(TAG, "Couldn't remove cache files for package: " 11330 + packageName + " u" + userId); 11331 return false; 11332 } 11333 return true; 11334 } 11335 11336 @Override 11337 public void getPackageSizeInfo(final String packageName, int userHandle, 11338 final IPackageStatsObserver observer) { 11339 mContext.enforceCallingOrSelfPermission( 11340 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11341 if (packageName == null) { 11342 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11343 } 11344 11345 PackageStats stats = new PackageStats(packageName, userHandle); 11346 11347 /* 11348 * Queue up an async operation since the package measurement may take a 11349 * little while. 11350 */ 11351 Message msg = mHandler.obtainMessage(INIT_COPY); 11352 msg.obj = new MeasureParams(stats, observer); 11353 mHandler.sendMessage(msg); 11354 } 11355 11356 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11357 PackageStats pStats) { 11358 if (packageName == null) { 11359 Slog.w(TAG, "Attempt to get size of null packageName."); 11360 return false; 11361 } 11362 PackageParser.Package p; 11363 boolean dataOnly = false; 11364 String libDirRoot = null; 11365 String asecPath = null; 11366 PackageSetting ps = null; 11367 synchronized (mPackages) { 11368 p = mPackages.get(packageName); 11369 ps = mSettings.mPackages.get(packageName); 11370 if(p == null) { 11371 dataOnly = true; 11372 if((ps == null) || (ps.pkg == null)) { 11373 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11374 return false; 11375 } 11376 p = ps.pkg; 11377 } 11378 if (ps != null) { 11379 libDirRoot = ps.legacyNativeLibraryPathString; 11380 } 11381 if (p != null && (isExternal(p) || p.isForwardLocked())) { 11382 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11383 if (secureContainerId != null) { 11384 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11385 } 11386 } 11387 } 11388 String publicSrcDir = null; 11389 if(!dataOnly) { 11390 final ApplicationInfo applicationInfo = p.applicationInfo; 11391 if (applicationInfo == null) { 11392 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11393 return false; 11394 } 11395 if (p.isForwardLocked()) { 11396 publicSrcDir = applicationInfo.getBaseResourcePath(); 11397 } 11398 } 11399 // TODO: extend to measure size of split APKs 11400 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11401 // not just the first level. 11402 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11403 // just the primary. 11404 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11405 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11406 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11407 if (res < 0) { 11408 return false; 11409 } 11410 11411 // Fix-up for forward-locked applications in ASEC containers. 11412 if (!isExternal(p)) { 11413 pStats.codeSize += pStats.externalCodeSize; 11414 pStats.externalCodeSize = 0L; 11415 } 11416 11417 return true; 11418 } 11419 11420 11421 @Override 11422 public void addPackageToPreferred(String packageName) { 11423 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11424 } 11425 11426 @Override 11427 public void removePackageFromPreferred(String packageName) { 11428 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11429 } 11430 11431 @Override 11432 public List<PackageInfo> getPreferredPackages(int flags) { 11433 return new ArrayList<PackageInfo>(); 11434 } 11435 11436 private int getUidTargetSdkVersionLockedLPr(int uid) { 11437 Object obj = mSettings.getUserIdLPr(uid); 11438 if (obj instanceof SharedUserSetting) { 11439 final SharedUserSetting sus = (SharedUserSetting) obj; 11440 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11441 final Iterator<PackageSetting> it = sus.packages.iterator(); 11442 while (it.hasNext()) { 11443 final PackageSetting ps = it.next(); 11444 if (ps.pkg != null) { 11445 int v = ps.pkg.applicationInfo.targetSdkVersion; 11446 if (v < vers) vers = v; 11447 } 11448 } 11449 return vers; 11450 } else if (obj instanceof PackageSetting) { 11451 final PackageSetting ps = (PackageSetting) obj; 11452 if (ps.pkg != null) { 11453 return ps.pkg.applicationInfo.targetSdkVersion; 11454 } 11455 } 11456 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11457 } 11458 11459 @Override 11460 public void addPreferredActivity(IntentFilter filter, int match, 11461 ComponentName[] set, ComponentName activity, int userId) { 11462 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11463 "Adding preferred"); 11464 } 11465 11466 private void addPreferredActivityInternal(IntentFilter filter, int match, 11467 ComponentName[] set, ComponentName activity, boolean always, int userId, 11468 String opname) { 11469 // writer 11470 int callingUid = Binder.getCallingUid(); 11471 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11472 if (filter.countActions() == 0) { 11473 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11474 return; 11475 } 11476 synchronized (mPackages) { 11477 if (mContext.checkCallingOrSelfPermission( 11478 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11479 != PackageManager.PERMISSION_GRANTED) { 11480 if (getUidTargetSdkVersionLockedLPr(callingUid) 11481 < Build.VERSION_CODES.FROYO) { 11482 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11483 + callingUid); 11484 return; 11485 } 11486 mContext.enforceCallingOrSelfPermission( 11487 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11488 } 11489 11490 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11491 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11492 + userId + ":"); 11493 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11494 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11495 scheduleWritePackageRestrictionsLocked(userId); 11496 } 11497 } 11498 11499 @Override 11500 public void replacePreferredActivity(IntentFilter filter, int match, 11501 ComponentName[] set, ComponentName activity, int userId) { 11502 if (filter.countActions() != 1) { 11503 throw new IllegalArgumentException( 11504 "replacePreferredActivity expects filter to have only 1 action."); 11505 } 11506 if (filter.countDataAuthorities() != 0 11507 || filter.countDataPaths() != 0 11508 || filter.countDataSchemes() > 1 11509 || filter.countDataTypes() != 0) { 11510 throw new IllegalArgumentException( 11511 "replacePreferredActivity expects filter to have no data authorities, " + 11512 "paths, or types; and at most one scheme."); 11513 } 11514 11515 final int callingUid = Binder.getCallingUid(); 11516 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11517 synchronized (mPackages) { 11518 if (mContext.checkCallingOrSelfPermission( 11519 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11520 != PackageManager.PERMISSION_GRANTED) { 11521 if (getUidTargetSdkVersionLockedLPr(callingUid) 11522 < Build.VERSION_CODES.FROYO) { 11523 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11524 + Binder.getCallingUid()); 11525 return; 11526 } 11527 mContext.enforceCallingOrSelfPermission( 11528 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11529 } 11530 11531 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11532 if (pir != null) { 11533 // Get all of the existing entries that exactly match this filter. 11534 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11535 if (existing != null && existing.size() == 1) { 11536 PreferredActivity cur = existing.get(0); 11537 if (DEBUG_PREFERRED) { 11538 Slog.i(TAG, "Checking replace of preferred:"); 11539 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11540 if (!cur.mPref.mAlways) { 11541 Slog.i(TAG, " -- CUR; not mAlways!"); 11542 } else { 11543 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11544 Slog.i(TAG, " -- CUR: mSet=" 11545 + Arrays.toString(cur.mPref.mSetComponents)); 11546 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11547 Slog.i(TAG, " -- NEW: mMatch=" 11548 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11549 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11550 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11551 } 11552 } 11553 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11554 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11555 && cur.mPref.sameSet(set)) { 11556 // Setting the preferred activity to what it happens to be already 11557 if (DEBUG_PREFERRED) { 11558 Slog.i(TAG, "Replacing with same preferred activity " 11559 + cur.mPref.mShortComponent + " for user " 11560 + userId + ":"); 11561 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11562 } 11563 return; 11564 } 11565 } 11566 11567 if (existing != null) { 11568 if (DEBUG_PREFERRED) { 11569 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11570 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11571 } 11572 for (int i = 0; i < existing.size(); i++) { 11573 PreferredActivity pa = existing.get(i); 11574 if (DEBUG_PREFERRED) { 11575 Slog.i(TAG, "Removing existing preferred activity " 11576 + pa.mPref.mComponent + ":"); 11577 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11578 } 11579 pir.removeFilter(pa); 11580 } 11581 } 11582 } 11583 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11584 "Replacing preferred"); 11585 } 11586 } 11587 11588 @Override 11589 public void clearPackagePreferredActivities(String packageName) { 11590 final int uid = Binder.getCallingUid(); 11591 // writer 11592 synchronized (mPackages) { 11593 PackageParser.Package pkg = mPackages.get(packageName); 11594 if (pkg == null || pkg.applicationInfo.uid != uid) { 11595 if (mContext.checkCallingOrSelfPermission( 11596 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11597 != PackageManager.PERMISSION_GRANTED) { 11598 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11599 < Build.VERSION_CODES.FROYO) { 11600 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11601 + Binder.getCallingUid()); 11602 return; 11603 } 11604 mContext.enforceCallingOrSelfPermission( 11605 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11606 } 11607 } 11608 11609 int user = UserHandle.getCallingUserId(); 11610 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11611 scheduleWritePackageRestrictionsLocked(user); 11612 } 11613 } 11614 } 11615 11616 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11617 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11618 ArrayList<PreferredActivity> removed = null; 11619 boolean changed = false; 11620 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11621 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11622 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11623 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11624 continue; 11625 } 11626 Iterator<PreferredActivity> it = pir.filterIterator(); 11627 while (it.hasNext()) { 11628 PreferredActivity pa = it.next(); 11629 // Mark entry for removal only if it matches the package name 11630 // and the entry is of type "always". 11631 if (packageName == null || 11632 (pa.mPref.mComponent.getPackageName().equals(packageName) 11633 && pa.mPref.mAlways)) { 11634 if (removed == null) { 11635 removed = new ArrayList<PreferredActivity>(); 11636 } 11637 removed.add(pa); 11638 } 11639 } 11640 if (removed != null) { 11641 for (int j=0; j<removed.size(); j++) { 11642 PreferredActivity pa = removed.get(j); 11643 pir.removeFilter(pa); 11644 } 11645 changed = true; 11646 } 11647 } 11648 return changed; 11649 } 11650 11651 @Override 11652 public void resetPreferredActivities(int userId) { 11653 /* TODO: Actually use userId. Why is it being passed in? */ 11654 mContext.enforceCallingOrSelfPermission( 11655 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11656 // writer 11657 synchronized (mPackages) { 11658 int user = UserHandle.getCallingUserId(); 11659 clearPackagePreferredActivitiesLPw(null, user); 11660 mSettings.readDefaultPreferredAppsLPw(this, user); 11661 scheduleWritePackageRestrictionsLocked(user); 11662 } 11663 } 11664 11665 @Override 11666 public int getPreferredActivities(List<IntentFilter> outFilters, 11667 List<ComponentName> outActivities, String packageName) { 11668 11669 int num = 0; 11670 final int userId = UserHandle.getCallingUserId(); 11671 // reader 11672 synchronized (mPackages) { 11673 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11674 if (pir != null) { 11675 final Iterator<PreferredActivity> it = pir.filterIterator(); 11676 while (it.hasNext()) { 11677 final PreferredActivity pa = it.next(); 11678 if (packageName == null 11679 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11680 && pa.mPref.mAlways)) { 11681 if (outFilters != null) { 11682 outFilters.add(new IntentFilter(pa)); 11683 } 11684 if (outActivities != null) { 11685 outActivities.add(pa.mPref.mComponent); 11686 } 11687 } 11688 } 11689 } 11690 } 11691 11692 return num; 11693 } 11694 11695 @Override 11696 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11697 int userId) { 11698 int callingUid = Binder.getCallingUid(); 11699 if (callingUid != Process.SYSTEM_UID) { 11700 throw new SecurityException( 11701 "addPersistentPreferredActivity can only be run by the system"); 11702 } 11703 if (filter.countActions() == 0) { 11704 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11705 return; 11706 } 11707 synchronized (mPackages) { 11708 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11709 " :"); 11710 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11711 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11712 new PersistentPreferredActivity(filter, activity)); 11713 scheduleWritePackageRestrictionsLocked(userId); 11714 } 11715 } 11716 11717 @Override 11718 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11719 int callingUid = Binder.getCallingUid(); 11720 if (callingUid != Process.SYSTEM_UID) { 11721 throw new SecurityException( 11722 "clearPackagePersistentPreferredActivities can only be run by the system"); 11723 } 11724 ArrayList<PersistentPreferredActivity> removed = null; 11725 boolean changed = false; 11726 synchronized (mPackages) { 11727 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11728 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11729 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11730 .valueAt(i); 11731 if (userId != thisUserId) { 11732 continue; 11733 } 11734 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11735 while (it.hasNext()) { 11736 PersistentPreferredActivity ppa = it.next(); 11737 // Mark entry for removal only if it matches the package name. 11738 if (ppa.mComponent.getPackageName().equals(packageName)) { 11739 if (removed == null) { 11740 removed = new ArrayList<PersistentPreferredActivity>(); 11741 } 11742 removed.add(ppa); 11743 } 11744 } 11745 if (removed != null) { 11746 for (int j=0; j<removed.size(); j++) { 11747 PersistentPreferredActivity ppa = removed.get(j); 11748 ppir.removeFilter(ppa); 11749 } 11750 changed = true; 11751 } 11752 } 11753 11754 if (changed) { 11755 scheduleWritePackageRestrictionsLocked(userId); 11756 } 11757 } 11758 } 11759 11760 @Override 11761 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11762 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11763 mContext.enforceCallingOrSelfPermission( 11764 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11765 int callingUid = Binder.getCallingUid(); 11766 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11767 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11768 if (intentFilter.countActions() == 0) { 11769 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11770 return; 11771 } 11772 synchronized (mPackages) { 11773 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 11774 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11775 CrossProfileIntentResolver resolver = 11776 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11777 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 11778 // We have all those whose filter is equal. Now checking if the rest is equal as well. 11779 if (existing != null) { 11780 int size = existing.size(); 11781 for (int i = 0; i < size; i++) { 11782 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 11783 return; 11784 } 11785 } 11786 } 11787 resolver.addFilter(newFilter); 11788 scheduleWritePackageRestrictionsLocked(sourceUserId); 11789 } 11790 } 11791 11792 @Override 11793 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11794 int ownerUserId) { 11795 mContext.enforceCallingOrSelfPermission( 11796 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11797 int callingUid = Binder.getCallingUid(); 11798 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11799 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11800 int callingUserId = UserHandle.getUserId(callingUid); 11801 synchronized (mPackages) { 11802 CrossProfileIntentResolver resolver = 11803 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11804 ArraySet<CrossProfileIntentFilter> set = 11805 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 11806 for (CrossProfileIntentFilter filter : set) { 11807 if (filter.getOwnerPackage().equals(ownerPackage) 11808 && filter.getOwnerUserId() == callingUserId) { 11809 resolver.removeFilter(filter); 11810 } 11811 } 11812 scheduleWritePackageRestrictionsLocked(sourceUserId); 11813 } 11814 } 11815 11816 // Enforcing that callingUid is owning pkg on userId 11817 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11818 // The system owns everything. 11819 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11820 return; 11821 } 11822 int callingUserId = UserHandle.getUserId(callingUid); 11823 if (callingUserId != userId) { 11824 throw new SecurityException("calling uid " + callingUid 11825 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11826 + callingUserId); 11827 } 11828 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11829 if (pi == null) { 11830 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11831 + callingUserId); 11832 } 11833 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11834 throw new SecurityException("Calling uid " + callingUid 11835 + " does not own package " + pkg); 11836 } 11837 } 11838 11839 @Override 11840 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11841 Intent intent = new Intent(Intent.ACTION_MAIN); 11842 intent.addCategory(Intent.CATEGORY_HOME); 11843 11844 final int callingUserId = UserHandle.getCallingUserId(); 11845 List<ResolveInfo> list = queryIntentActivities(intent, null, 11846 PackageManager.GET_META_DATA, callingUserId); 11847 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11848 true, false, false, callingUserId); 11849 11850 allHomeCandidates.clear(); 11851 if (list != null) { 11852 for (ResolveInfo ri : list) { 11853 allHomeCandidates.add(ri); 11854 } 11855 } 11856 return (preferred == null || preferred.activityInfo == null) 11857 ? null 11858 : new ComponentName(preferred.activityInfo.packageName, 11859 preferred.activityInfo.name); 11860 } 11861 11862 @Override 11863 public void setApplicationEnabledSetting(String appPackageName, 11864 int newState, int flags, int userId, String callingPackage) { 11865 if (!sUserManager.exists(userId)) return; 11866 if (callingPackage == null) { 11867 callingPackage = Integer.toString(Binder.getCallingUid()); 11868 } 11869 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11870 } 11871 11872 @Override 11873 public void setComponentEnabledSetting(ComponentName componentName, 11874 int newState, int flags, int userId) { 11875 if (!sUserManager.exists(userId)) return; 11876 setEnabledSetting(componentName.getPackageName(), 11877 componentName.getClassName(), newState, flags, userId, null); 11878 } 11879 11880 private void setEnabledSetting(final String packageName, String className, int newState, 11881 final int flags, int userId, String callingPackage) { 11882 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11883 || newState == COMPONENT_ENABLED_STATE_ENABLED 11884 || newState == COMPONENT_ENABLED_STATE_DISABLED 11885 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11886 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11887 throw new IllegalArgumentException("Invalid new component state: " 11888 + newState); 11889 } 11890 PackageSetting pkgSetting; 11891 final int uid = Binder.getCallingUid(); 11892 final int permission = mContext.checkCallingOrSelfPermission( 11893 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11894 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 11895 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11896 boolean sendNow = false; 11897 boolean isApp = (className == null); 11898 String componentName = isApp ? packageName : className; 11899 int packageUid = -1; 11900 ArrayList<String> components; 11901 11902 // writer 11903 synchronized (mPackages) { 11904 pkgSetting = mSettings.mPackages.get(packageName); 11905 if (pkgSetting == null) { 11906 if (className == null) { 11907 throw new IllegalArgumentException( 11908 "Unknown package: " + packageName); 11909 } 11910 throw new IllegalArgumentException( 11911 "Unknown component: " + packageName 11912 + "/" + className); 11913 } 11914 // Allow root and verify that userId is not being specified by a different user 11915 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11916 throw new SecurityException( 11917 "Permission Denial: attempt to change component state from pid=" 11918 + Binder.getCallingPid() 11919 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11920 } 11921 if (className == null) { 11922 // We're dealing with an application/package level state change 11923 if (pkgSetting.getEnabled(userId) == newState) { 11924 // Nothing to do 11925 return; 11926 } 11927 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11928 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11929 // Don't care about who enables an app. 11930 callingPackage = null; 11931 } 11932 pkgSetting.setEnabled(newState, userId, callingPackage); 11933 // pkgSetting.pkg.mSetEnabled = newState; 11934 } else { 11935 // We're dealing with a component level state change 11936 // First, verify that this is a valid class name. 11937 PackageParser.Package pkg = pkgSetting.pkg; 11938 if (pkg == null || !pkg.hasComponentClassName(className)) { 11939 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11940 throw new IllegalArgumentException("Component class " + className 11941 + " does not exist in " + packageName); 11942 } else { 11943 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11944 + className + " does not exist in " + packageName); 11945 } 11946 } 11947 switch (newState) { 11948 case COMPONENT_ENABLED_STATE_ENABLED: 11949 if (!pkgSetting.enableComponentLPw(className, userId)) { 11950 return; 11951 } 11952 break; 11953 case COMPONENT_ENABLED_STATE_DISABLED: 11954 if (!pkgSetting.disableComponentLPw(className, userId)) { 11955 return; 11956 } 11957 break; 11958 case COMPONENT_ENABLED_STATE_DEFAULT: 11959 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11960 return; 11961 } 11962 break; 11963 default: 11964 Slog.e(TAG, "Invalid new component state: " + newState); 11965 return; 11966 } 11967 } 11968 mSettings.writePackageRestrictionsLPr(userId); 11969 components = mPendingBroadcasts.get(userId, packageName); 11970 final boolean newPackage = components == null; 11971 if (newPackage) { 11972 components = new ArrayList<String>(); 11973 } 11974 if (!components.contains(componentName)) { 11975 components.add(componentName); 11976 } 11977 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11978 sendNow = true; 11979 // Purge entry from pending broadcast list if another one exists already 11980 // since we are sending one right away. 11981 mPendingBroadcasts.remove(userId, packageName); 11982 } else { 11983 if (newPackage) { 11984 mPendingBroadcasts.put(userId, packageName, components); 11985 } 11986 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11987 // Schedule a message 11988 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11989 } 11990 } 11991 } 11992 11993 long callingId = Binder.clearCallingIdentity(); 11994 try { 11995 if (sendNow) { 11996 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11997 sendPackageChangedBroadcast(packageName, 11998 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11999 } 12000 } finally { 12001 Binder.restoreCallingIdentity(callingId); 12002 } 12003 } 12004 12005 private void sendPackageChangedBroadcast(String packageName, 12006 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12007 if (DEBUG_INSTALL) 12008 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12009 + componentNames); 12010 Bundle extras = new Bundle(4); 12011 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12012 String nameList[] = new String[componentNames.size()]; 12013 componentNames.toArray(nameList); 12014 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12015 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12016 extras.putInt(Intent.EXTRA_UID, packageUid); 12017 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12018 new int[] {UserHandle.getUserId(packageUid)}); 12019 } 12020 12021 @Override 12022 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12023 if (!sUserManager.exists(userId)) return; 12024 final int uid = Binder.getCallingUid(); 12025 final int permission = mContext.checkCallingOrSelfPermission( 12026 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12027 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12028 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12029 // writer 12030 synchronized (mPackages) { 12031 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12032 uid, userId)) { 12033 scheduleWritePackageRestrictionsLocked(userId); 12034 } 12035 } 12036 } 12037 12038 @Override 12039 public String getInstallerPackageName(String packageName) { 12040 // reader 12041 synchronized (mPackages) { 12042 return mSettings.getInstallerPackageNameLPr(packageName); 12043 } 12044 } 12045 12046 @Override 12047 public int getApplicationEnabledSetting(String packageName, int userId) { 12048 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12049 int uid = Binder.getCallingUid(); 12050 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12051 // reader 12052 synchronized (mPackages) { 12053 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12054 } 12055 } 12056 12057 @Override 12058 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12059 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12060 int uid = Binder.getCallingUid(); 12061 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12062 // reader 12063 synchronized (mPackages) { 12064 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12065 } 12066 } 12067 12068 @Override 12069 public void enterSafeMode() { 12070 enforceSystemOrRoot("Only the system can request entering safe mode"); 12071 12072 if (!mSystemReady) { 12073 mSafeMode = true; 12074 } 12075 } 12076 12077 @Override 12078 public void systemReady() { 12079 mSystemReady = true; 12080 12081 // Read the compatibilty setting when the system is ready. 12082 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12083 mContext.getContentResolver(), 12084 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12085 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12086 if (DEBUG_SETTINGS) { 12087 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12088 } 12089 12090 synchronized (mPackages) { 12091 // Verify that all of the preferred activity components actually 12092 // exist. It is possible for applications to be updated and at 12093 // that point remove a previously declared activity component that 12094 // had been set as a preferred activity. We try to clean this up 12095 // the next time we encounter that preferred activity, but it is 12096 // possible for the user flow to never be able to return to that 12097 // situation so here we do a sanity check to make sure we haven't 12098 // left any junk around. 12099 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12100 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12101 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12102 removed.clear(); 12103 for (PreferredActivity pa : pir.filterSet()) { 12104 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12105 removed.add(pa); 12106 } 12107 } 12108 if (removed.size() > 0) { 12109 for (int r=0; r<removed.size(); r++) { 12110 PreferredActivity pa = removed.get(r); 12111 Slog.w(TAG, "Removing dangling preferred activity: " 12112 + pa.mPref.mComponent); 12113 pir.removeFilter(pa); 12114 } 12115 mSettings.writePackageRestrictionsLPr( 12116 mSettings.mPreferredActivities.keyAt(i)); 12117 } 12118 } 12119 } 12120 sUserManager.systemReady(); 12121 12122 // Kick off any messages waiting for system ready 12123 if (mPostSystemReadyMessages != null) { 12124 for (Message msg : mPostSystemReadyMessages) { 12125 msg.sendToTarget(); 12126 } 12127 mPostSystemReadyMessages = null; 12128 } 12129 } 12130 12131 @Override 12132 public boolean isSafeMode() { 12133 return mSafeMode; 12134 } 12135 12136 @Override 12137 public boolean hasSystemUidErrors() { 12138 return mHasSystemUidErrors; 12139 } 12140 12141 static String arrayToString(int[] array) { 12142 StringBuffer buf = new StringBuffer(128); 12143 buf.append('['); 12144 if (array != null) { 12145 for (int i=0; i<array.length; i++) { 12146 if (i > 0) buf.append(", "); 12147 buf.append(array[i]); 12148 } 12149 } 12150 buf.append(']'); 12151 return buf.toString(); 12152 } 12153 12154 static class DumpState { 12155 public static final int DUMP_LIBS = 1 << 0; 12156 public static final int DUMP_FEATURES = 1 << 1; 12157 public static final int DUMP_RESOLVERS = 1 << 2; 12158 public static final int DUMP_PERMISSIONS = 1 << 3; 12159 public static final int DUMP_PACKAGES = 1 << 4; 12160 public static final int DUMP_SHARED_USERS = 1 << 5; 12161 public static final int DUMP_MESSAGES = 1 << 6; 12162 public static final int DUMP_PROVIDERS = 1 << 7; 12163 public static final int DUMP_VERIFIERS = 1 << 8; 12164 public static final int DUMP_PREFERRED = 1 << 9; 12165 public static final int DUMP_PREFERRED_XML = 1 << 10; 12166 public static final int DUMP_KEYSETS = 1 << 11; 12167 public static final int DUMP_VERSION = 1 << 12; 12168 public static final int DUMP_INSTALLS = 1 << 13; 12169 12170 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12171 12172 private int mTypes; 12173 12174 private int mOptions; 12175 12176 private boolean mTitlePrinted; 12177 12178 private SharedUserSetting mSharedUser; 12179 12180 public boolean isDumping(int type) { 12181 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12182 return true; 12183 } 12184 12185 return (mTypes & type) != 0; 12186 } 12187 12188 public void setDump(int type) { 12189 mTypes |= type; 12190 } 12191 12192 public boolean isOptionEnabled(int option) { 12193 return (mOptions & option) != 0; 12194 } 12195 12196 public void setOptionEnabled(int option) { 12197 mOptions |= option; 12198 } 12199 12200 public boolean onTitlePrinted() { 12201 final boolean printed = mTitlePrinted; 12202 mTitlePrinted = true; 12203 return printed; 12204 } 12205 12206 public boolean getTitlePrinted() { 12207 return mTitlePrinted; 12208 } 12209 12210 public void setTitlePrinted(boolean enabled) { 12211 mTitlePrinted = enabled; 12212 } 12213 12214 public SharedUserSetting getSharedUser() { 12215 return mSharedUser; 12216 } 12217 12218 public void setSharedUser(SharedUserSetting user) { 12219 mSharedUser = user; 12220 } 12221 } 12222 12223 @Override 12224 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12225 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12226 != PackageManager.PERMISSION_GRANTED) { 12227 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12228 + Binder.getCallingPid() 12229 + ", uid=" + Binder.getCallingUid() 12230 + " without permission " 12231 + android.Manifest.permission.DUMP); 12232 return; 12233 } 12234 12235 DumpState dumpState = new DumpState(); 12236 boolean fullPreferred = false; 12237 boolean checkin = false; 12238 12239 String packageName = null; 12240 12241 int opti = 0; 12242 while (opti < args.length) { 12243 String opt = args[opti]; 12244 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12245 break; 12246 } 12247 opti++; 12248 12249 if ("-a".equals(opt)) { 12250 // Right now we only know how to print all. 12251 } else if ("-h".equals(opt)) { 12252 pw.println("Package manager dump options:"); 12253 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12254 pw.println(" --checkin: dump for a checkin"); 12255 pw.println(" -f: print details of intent filters"); 12256 pw.println(" -h: print this help"); 12257 pw.println(" cmd may be one of:"); 12258 pw.println(" l[ibraries]: list known shared libraries"); 12259 pw.println(" f[ibraries]: list device features"); 12260 pw.println(" k[eysets]: print known keysets"); 12261 pw.println(" r[esolvers]: dump intent resolvers"); 12262 pw.println(" perm[issions]: dump permissions"); 12263 pw.println(" pref[erred]: print preferred package settings"); 12264 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12265 pw.println(" prov[iders]: dump content providers"); 12266 pw.println(" p[ackages]: dump installed packages"); 12267 pw.println(" s[hared-users]: dump shared user IDs"); 12268 pw.println(" m[essages]: print collected runtime messages"); 12269 pw.println(" v[erifiers]: print package verifier info"); 12270 pw.println(" version: print database version info"); 12271 pw.println(" write: write current settings now"); 12272 pw.println(" <package.name>: info about given package"); 12273 pw.println(" installs: details about install sessions"); 12274 return; 12275 } else if ("--checkin".equals(opt)) { 12276 checkin = true; 12277 } else if ("-f".equals(opt)) { 12278 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12279 } else { 12280 pw.println("Unknown argument: " + opt + "; use -h for help"); 12281 } 12282 } 12283 12284 // Is the caller requesting to dump a particular piece of data? 12285 if (opti < args.length) { 12286 String cmd = args[opti]; 12287 opti++; 12288 // Is this a package name? 12289 if ("android".equals(cmd) || cmd.contains(".")) { 12290 packageName = cmd; 12291 // When dumping a single package, we always dump all of its 12292 // filter information since the amount of data will be reasonable. 12293 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12294 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12295 dumpState.setDump(DumpState.DUMP_LIBS); 12296 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12297 dumpState.setDump(DumpState.DUMP_FEATURES); 12298 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12299 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12300 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12301 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12302 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12303 dumpState.setDump(DumpState.DUMP_PREFERRED); 12304 } else if ("preferred-xml".equals(cmd)) { 12305 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12306 if (opti < args.length && "--full".equals(args[opti])) { 12307 fullPreferred = true; 12308 opti++; 12309 } 12310 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12311 dumpState.setDump(DumpState.DUMP_PACKAGES); 12312 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12313 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12314 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12315 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12316 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12317 dumpState.setDump(DumpState.DUMP_MESSAGES); 12318 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12319 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12320 } else if ("version".equals(cmd)) { 12321 dumpState.setDump(DumpState.DUMP_VERSION); 12322 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12323 dumpState.setDump(DumpState.DUMP_KEYSETS); 12324 } else if ("installs".equals(cmd)) { 12325 dumpState.setDump(DumpState.DUMP_INSTALLS); 12326 } else if ("write".equals(cmd)) { 12327 synchronized (mPackages) { 12328 mSettings.writeLPr(); 12329 pw.println("Settings written."); 12330 return; 12331 } 12332 } 12333 } 12334 12335 if (checkin) { 12336 pw.println("vers,1"); 12337 } 12338 12339 // reader 12340 synchronized (mPackages) { 12341 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12342 if (!checkin) { 12343 if (dumpState.onTitlePrinted()) 12344 pw.println(); 12345 pw.println("Database versions:"); 12346 pw.print(" SDK Version:"); 12347 pw.print(" internal="); 12348 pw.print(mSettings.mInternalSdkPlatform); 12349 pw.print(" external="); 12350 pw.println(mSettings.mExternalSdkPlatform); 12351 pw.print(" DB Version:"); 12352 pw.print(" internal="); 12353 pw.print(mSettings.mInternalDatabaseVersion); 12354 pw.print(" external="); 12355 pw.println(mSettings.mExternalDatabaseVersion); 12356 } 12357 } 12358 12359 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12360 if (!checkin) { 12361 if (dumpState.onTitlePrinted()) 12362 pw.println(); 12363 pw.println("Verifiers:"); 12364 pw.print(" Required: "); 12365 pw.print(mRequiredVerifierPackage); 12366 pw.print(" (uid="); 12367 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12368 pw.println(")"); 12369 } else if (mRequiredVerifierPackage != null) { 12370 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12371 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12372 } 12373 } 12374 12375 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12376 boolean printedHeader = false; 12377 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12378 while (it.hasNext()) { 12379 String name = it.next(); 12380 SharedLibraryEntry ent = mSharedLibraries.get(name); 12381 if (!checkin) { 12382 if (!printedHeader) { 12383 if (dumpState.onTitlePrinted()) 12384 pw.println(); 12385 pw.println("Libraries:"); 12386 printedHeader = true; 12387 } 12388 pw.print(" "); 12389 } else { 12390 pw.print("lib,"); 12391 } 12392 pw.print(name); 12393 if (!checkin) { 12394 pw.print(" -> "); 12395 } 12396 if (ent.path != null) { 12397 if (!checkin) { 12398 pw.print("(jar) "); 12399 pw.print(ent.path); 12400 } else { 12401 pw.print(",jar,"); 12402 pw.print(ent.path); 12403 } 12404 } else { 12405 if (!checkin) { 12406 pw.print("(apk) "); 12407 pw.print(ent.apk); 12408 } else { 12409 pw.print(",apk,"); 12410 pw.print(ent.apk); 12411 } 12412 } 12413 pw.println(); 12414 } 12415 } 12416 12417 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12418 if (dumpState.onTitlePrinted()) 12419 pw.println(); 12420 if (!checkin) { 12421 pw.println("Features:"); 12422 } 12423 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12424 while (it.hasNext()) { 12425 String name = it.next(); 12426 if (!checkin) { 12427 pw.print(" "); 12428 } else { 12429 pw.print("feat,"); 12430 } 12431 pw.println(name); 12432 } 12433 } 12434 12435 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12436 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12437 : "Activity Resolver Table:", " ", packageName, 12438 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12439 dumpState.setTitlePrinted(true); 12440 } 12441 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12442 : "Receiver Resolver Table:", " ", packageName, 12443 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12444 dumpState.setTitlePrinted(true); 12445 } 12446 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12447 : "Service Resolver Table:", " ", packageName, 12448 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12449 dumpState.setTitlePrinted(true); 12450 } 12451 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12452 : "Provider Resolver Table:", " ", packageName, 12453 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12454 dumpState.setTitlePrinted(true); 12455 } 12456 } 12457 12458 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12459 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12460 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12461 int user = mSettings.mPreferredActivities.keyAt(i); 12462 if (pir.dump(pw, 12463 dumpState.getTitlePrinted() 12464 ? "\nPreferred Activities User " + user + ":" 12465 : "Preferred Activities User " + user + ":", " ", 12466 packageName, true, false)) { 12467 dumpState.setTitlePrinted(true); 12468 } 12469 } 12470 } 12471 12472 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12473 pw.flush(); 12474 FileOutputStream fout = new FileOutputStream(fd); 12475 BufferedOutputStream str = new BufferedOutputStream(fout); 12476 XmlSerializer serializer = new FastXmlSerializer(); 12477 try { 12478 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 12479 serializer.startDocument(null, true); 12480 serializer.setFeature( 12481 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12482 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12483 serializer.endDocument(); 12484 serializer.flush(); 12485 } catch (IllegalArgumentException e) { 12486 pw.println("Failed writing: " + e); 12487 } catch (IllegalStateException e) { 12488 pw.println("Failed writing: " + e); 12489 } catch (IOException e) { 12490 pw.println("Failed writing: " + e); 12491 } 12492 } 12493 12494 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12495 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12496 if (packageName == null) { 12497 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12498 if (iperm == 0) { 12499 if (dumpState.onTitlePrinted()) 12500 pw.println(); 12501 pw.println("AppOp Permissions:"); 12502 } 12503 pw.print(" AppOp Permission "); 12504 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12505 pw.println(":"); 12506 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12507 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12508 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12509 } 12510 } 12511 } 12512 } 12513 12514 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12515 boolean printedSomething = false; 12516 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12517 if (packageName != null && !packageName.equals(p.info.packageName)) { 12518 continue; 12519 } 12520 if (!printedSomething) { 12521 if (dumpState.onTitlePrinted()) 12522 pw.println(); 12523 pw.println("Registered ContentProviders:"); 12524 printedSomething = true; 12525 } 12526 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12527 pw.print(" "); pw.println(p.toString()); 12528 } 12529 printedSomething = false; 12530 for (Map.Entry<String, PackageParser.Provider> entry : 12531 mProvidersByAuthority.entrySet()) { 12532 PackageParser.Provider p = entry.getValue(); 12533 if (packageName != null && !packageName.equals(p.info.packageName)) { 12534 continue; 12535 } 12536 if (!printedSomething) { 12537 if (dumpState.onTitlePrinted()) 12538 pw.println(); 12539 pw.println("ContentProvider Authorities:"); 12540 printedSomething = true; 12541 } 12542 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12543 pw.print(" "); pw.println(p.toString()); 12544 if (p.info != null && p.info.applicationInfo != null) { 12545 final String appInfo = p.info.applicationInfo.toString(); 12546 pw.print(" applicationInfo="); pw.println(appInfo); 12547 } 12548 } 12549 } 12550 12551 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12552 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12553 } 12554 12555 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12556 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12557 } 12558 12559 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12560 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 12561 } 12562 12563 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12564 // XXX should handle packageName != null by dumping only install data that 12565 // the given package is involved with. 12566 if (dumpState.onTitlePrinted()) pw.println(); 12567 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12568 } 12569 12570 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12571 if (dumpState.onTitlePrinted()) pw.println(); 12572 mSettings.dumpReadMessagesLPr(pw, dumpState); 12573 12574 pw.println(); 12575 pw.println("Package warning messages:"); 12576 BufferedReader in = null; 12577 String line = null; 12578 try { 12579 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12580 while ((line = in.readLine()) != null) { 12581 if (line.contains("ignored: updated version")) continue; 12582 pw.println(line); 12583 } 12584 } catch (IOException ignored) { 12585 } finally { 12586 IoUtils.closeQuietly(in); 12587 } 12588 } 12589 12590 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12591 BufferedReader in = null; 12592 String line = null; 12593 try { 12594 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12595 while ((line = in.readLine()) != null) { 12596 if (line.contains("ignored: updated version")) continue; 12597 pw.print("msg,"); 12598 pw.println(line); 12599 } 12600 } catch (IOException ignored) { 12601 } finally { 12602 IoUtils.closeQuietly(in); 12603 } 12604 } 12605 } 12606 } 12607 12608 // ------- apps on sdcard specific code ------- 12609 static final boolean DEBUG_SD_INSTALL = false; 12610 12611 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12612 12613 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12614 12615 private boolean mMediaMounted = false; 12616 12617 static String getEncryptKey() { 12618 try { 12619 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12620 SD_ENCRYPTION_KEYSTORE_NAME); 12621 if (sdEncKey == null) { 12622 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12623 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12624 if (sdEncKey == null) { 12625 Slog.e(TAG, "Failed to create encryption keys"); 12626 return null; 12627 } 12628 } 12629 return sdEncKey; 12630 } catch (NoSuchAlgorithmException nsae) { 12631 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12632 return null; 12633 } catch (IOException ioe) { 12634 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12635 return null; 12636 } 12637 } 12638 12639 /* 12640 * Update media status on PackageManager. 12641 */ 12642 @Override 12643 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12644 int callingUid = Binder.getCallingUid(); 12645 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12646 throw new SecurityException("Media status can only be updated by the system"); 12647 } 12648 // reader; this apparently protects mMediaMounted, but should probably 12649 // be a different lock in that case. 12650 synchronized (mPackages) { 12651 Log.i(TAG, "Updating external media status from " 12652 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12653 + (mediaStatus ? "mounted" : "unmounted")); 12654 if (DEBUG_SD_INSTALL) 12655 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12656 + ", mMediaMounted=" + mMediaMounted); 12657 if (mediaStatus == mMediaMounted) { 12658 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12659 : 0, -1); 12660 mHandler.sendMessage(msg); 12661 return; 12662 } 12663 mMediaMounted = mediaStatus; 12664 } 12665 // Queue up an async operation since the package installation may take a 12666 // little while. 12667 mHandler.post(new Runnable() { 12668 public void run() { 12669 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12670 } 12671 }); 12672 } 12673 12674 /** 12675 * Called by MountService when the initial ASECs to scan are available. 12676 * Should block until all the ASEC containers are finished being scanned. 12677 */ 12678 public void scanAvailableAsecs() { 12679 updateExternalMediaStatusInner(true, false, false); 12680 if (mShouldRestoreconData) { 12681 SELinuxMMAC.setRestoreconDone(); 12682 mShouldRestoreconData = false; 12683 } 12684 } 12685 12686 /* 12687 * Collect information of applications on external media, map them against 12688 * existing containers and update information based on current mount status. 12689 * Please note that we always have to report status if reportStatus has been 12690 * set to true especially when unloading packages. 12691 */ 12692 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12693 boolean externalStorage) { 12694 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12695 int[] uidArr = EmptyArray.INT; 12696 12697 final String[] list = PackageHelper.getSecureContainerList(); 12698 if (ArrayUtils.isEmpty(list)) { 12699 Log.i(TAG, "No secure containers found"); 12700 } else { 12701 // Process list of secure containers and categorize them 12702 // as active or stale based on their package internal state. 12703 12704 // reader 12705 synchronized (mPackages) { 12706 for (String cid : list) { 12707 // Leave stages untouched for now; installer service owns them 12708 if (PackageInstallerService.isStageName(cid)) continue; 12709 12710 if (DEBUG_SD_INSTALL) 12711 Log.i(TAG, "Processing container " + cid); 12712 String pkgName = getAsecPackageName(cid); 12713 if (pkgName == null) { 12714 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12715 continue; 12716 } 12717 if (DEBUG_SD_INSTALL) 12718 Log.i(TAG, "Looking for pkg : " + pkgName); 12719 12720 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12721 if (ps == null) { 12722 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12723 continue; 12724 } 12725 12726 /* 12727 * Skip packages that are not external if we're unmounting 12728 * external storage. 12729 */ 12730 if (externalStorage && !isMounted && !isExternal(ps)) { 12731 continue; 12732 } 12733 12734 final AsecInstallArgs args = new AsecInstallArgs(cid, 12735 getAppDexInstructionSets(ps), ps.isForwardLocked()); 12736 // The package status is changed only if the code path 12737 // matches between settings and the container id. 12738 if (ps.codePathString != null 12739 && ps.codePathString.startsWith(args.getCodePath())) { 12740 if (DEBUG_SD_INSTALL) { 12741 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12742 + " at code path: " + ps.codePathString); 12743 } 12744 12745 // We do have a valid package installed on sdcard 12746 processCids.put(args, ps.codePathString); 12747 final int uid = ps.appId; 12748 if (uid != -1) { 12749 uidArr = ArrayUtils.appendInt(uidArr, uid); 12750 } 12751 } else { 12752 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12753 + ps.codePathString); 12754 } 12755 } 12756 } 12757 12758 Arrays.sort(uidArr); 12759 } 12760 12761 // Process packages with valid entries. 12762 if (isMounted) { 12763 if (DEBUG_SD_INSTALL) 12764 Log.i(TAG, "Loading packages"); 12765 loadMediaPackages(processCids, uidArr); 12766 startCleaningPackages(); 12767 mInstallerService.onSecureContainersAvailable(); 12768 } else { 12769 if (DEBUG_SD_INSTALL) 12770 Log.i(TAG, "Unloading packages"); 12771 unloadMediaPackages(processCids, uidArr, reportStatus); 12772 } 12773 } 12774 12775 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12776 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12777 int size = pkgList.size(); 12778 if (size > 0) { 12779 // Send broadcasts here 12780 Bundle extras = new Bundle(); 12781 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12782 .toArray(new String[size])); 12783 if (uidArr != null) { 12784 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12785 } 12786 if (replacing) { 12787 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12788 } 12789 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12790 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12791 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12792 } 12793 } 12794 12795 /* 12796 * Look at potentially valid container ids from processCids If package 12797 * information doesn't match the one on record or package scanning fails, 12798 * the cid is added to list of removeCids. We currently don't delete stale 12799 * containers. 12800 */ 12801 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12802 ArrayList<String> pkgList = new ArrayList<String>(); 12803 Set<AsecInstallArgs> keys = processCids.keySet(); 12804 12805 for (AsecInstallArgs args : keys) { 12806 String codePath = processCids.get(args); 12807 if (DEBUG_SD_INSTALL) 12808 Log.i(TAG, "Loading container : " + args.cid); 12809 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12810 try { 12811 // Make sure there are no container errors first. 12812 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12813 Slog.e(TAG, "Failed to mount cid : " + args.cid 12814 + " when installing from sdcard"); 12815 continue; 12816 } 12817 // Check code path here. 12818 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12819 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12820 + " does not match one in settings " + codePath); 12821 continue; 12822 } 12823 // Parse package 12824 int parseFlags = mDefParseFlags; 12825 if (args.isExternal()) { 12826 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12827 } 12828 if (args.isFwdLocked()) { 12829 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12830 } 12831 12832 synchronized (mInstallLock) { 12833 PackageParser.Package pkg = null; 12834 try { 12835 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12836 } catch (PackageManagerException e) { 12837 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12838 } 12839 // Scan the package 12840 if (pkg != null) { 12841 /* 12842 * TODO why is the lock being held? doPostInstall is 12843 * called in other places without the lock. This needs 12844 * to be straightened out. 12845 */ 12846 // writer 12847 synchronized (mPackages) { 12848 retCode = PackageManager.INSTALL_SUCCEEDED; 12849 pkgList.add(pkg.packageName); 12850 // Post process args 12851 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12852 pkg.applicationInfo.uid); 12853 } 12854 } else { 12855 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12856 } 12857 } 12858 12859 } finally { 12860 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12861 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12862 } 12863 } 12864 } 12865 // writer 12866 synchronized (mPackages) { 12867 // If the platform SDK has changed since the last time we booted, 12868 // we need to re-grant app permission to catch any new ones that 12869 // appear. This is really a hack, and means that apps can in some 12870 // cases get permissions that the user didn't initially explicitly 12871 // allow... it would be nice to have some better way to handle 12872 // this situation. 12873 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12874 if (regrantPermissions) 12875 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12876 + mSdkVersion + "; regranting permissions for external storage"); 12877 mSettings.mExternalSdkPlatform = mSdkVersion; 12878 12879 // Make sure group IDs have been assigned, and any permission 12880 // changes in other apps are accounted for 12881 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12882 | (regrantPermissions 12883 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12884 : 0)); 12885 12886 mSettings.updateExternalDatabaseVersion(); 12887 12888 // can downgrade to reader 12889 // Persist settings 12890 mSettings.writeLPr(); 12891 } 12892 // Send a broadcast to let everyone know we are done processing 12893 if (pkgList.size() > 0) { 12894 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12895 } 12896 } 12897 12898 /* 12899 * Utility method to unload a list of specified containers 12900 */ 12901 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12902 // Just unmount all valid containers. 12903 for (AsecInstallArgs arg : cidArgs) { 12904 synchronized (mInstallLock) { 12905 arg.doPostDeleteLI(false); 12906 } 12907 } 12908 } 12909 12910 /* 12911 * Unload packages mounted on external media. This involves deleting package 12912 * data from internal structures, sending broadcasts about diabled packages, 12913 * gc'ing to free up references, unmounting all secure containers 12914 * corresponding to packages on external media, and posting a 12915 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12916 * that we always have to post this message if status has been requested no 12917 * matter what. 12918 */ 12919 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12920 final boolean reportStatus) { 12921 if (DEBUG_SD_INSTALL) 12922 Log.i(TAG, "unloading media packages"); 12923 ArrayList<String> pkgList = new ArrayList<String>(); 12924 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12925 final Set<AsecInstallArgs> keys = processCids.keySet(); 12926 for (AsecInstallArgs args : keys) { 12927 String pkgName = args.getPackageName(); 12928 if (DEBUG_SD_INSTALL) 12929 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12930 // Delete package internally 12931 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12932 synchronized (mInstallLock) { 12933 boolean res = deletePackageLI(pkgName, null, false, null, null, 12934 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12935 if (res) { 12936 pkgList.add(pkgName); 12937 } else { 12938 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12939 failedList.add(args); 12940 } 12941 } 12942 } 12943 12944 // reader 12945 synchronized (mPackages) { 12946 // We didn't update the settings after removing each package; 12947 // write them now for all packages. 12948 mSettings.writeLPr(); 12949 } 12950 12951 // We have to absolutely send UPDATED_MEDIA_STATUS only 12952 // after confirming that all the receivers processed the ordered 12953 // broadcast when packages get disabled, force a gc to clean things up. 12954 // and unload all the containers. 12955 if (pkgList.size() > 0) { 12956 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12957 new IIntentReceiver.Stub() { 12958 public void performReceive(Intent intent, int resultCode, String data, 12959 Bundle extras, boolean ordered, boolean sticky, 12960 int sendingUser) throws RemoteException { 12961 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12962 reportStatus ? 1 : 0, 1, keys); 12963 mHandler.sendMessage(msg); 12964 } 12965 }); 12966 } else { 12967 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12968 keys); 12969 mHandler.sendMessage(msg); 12970 } 12971 } 12972 12973 /** Binder call */ 12974 @Override 12975 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12976 final int flags) { 12977 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12978 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12979 int returnCode = PackageManager.MOVE_SUCCEEDED; 12980 int currInstallFlags = 0; 12981 int newInstallFlags = 0; 12982 12983 File codeFile = null; 12984 String installerPackageName = null; 12985 String packageAbiOverride = null; 12986 12987 // reader 12988 synchronized (mPackages) { 12989 final PackageParser.Package pkg = mPackages.get(packageName); 12990 final PackageSetting ps = mSettings.mPackages.get(packageName); 12991 if (pkg == null || ps == null) { 12992 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12993 } else { 12994 // Disable moving fwd locked apps and system packages 12995 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12996 Slog.w(TAG, "Cannot move system application"); 12997 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12998 } else if (pkg.mOperationPending) { 12999 Slog.w(TAG, "Attempt to move package which has pending operations"); 13000 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13001 } else { 13002 // Find install location first 13003 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13004 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13005 Slog.w(TAG, "Ambigous flags specified for move location."); 13006 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13007 } else { 13008 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13009 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13010 currInstallFlags = isExternal(pkg) 13011 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13012 13013 if (newInstallFlags == currInstallFlags) { 13014 Slog.w(TAG, "No move required. Trying to move to same location"); 13015 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13016 } else { 13017 if (pkg.isForwardLocked()) { 13018 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13019 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13020 } 13021 } 13022 } 13023 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13024 pkg.mOperationPending = true; 13025 } 13026 } 13027 13028 codeFile = new File(pkg.codePath); 13029 installerPackageName = ps.installerPackageName; 13030 packageAbiOverride = ps.cpuAbiOverrideString; 13031 } 13032 } 13033 13034 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13035 try { 13036 observer.packageMoved(packageName, returnCode); 13037 } catch (RemoteException ignored) { 13038 } 13039 return; 13040 } 13041 13042 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13043 @Override 13044 public void onUserActionRequired(Intent intent) throws RemoteException { 13045 throw new IllegalStateException(); 13046 } 13047 13048 @Override 13049 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13050 Bundle extras) throws RemoteException { 13051 Slog.d(TAG, "Install result for move: " 13052 + PackageManager.installStatusToString(returnCode, msg)); 13053 13054 // We usually have a new package now after the install, but if 13055 // we failed we need to clear the pending flag on the original 13056 // package object. 13057 synchronized (mPackages) { 13058 final PackageParser.Package pkg = mPackages.get(packageName); 13059 if (pkg != null) { 13060 pkg.mOperationPending = false; 13061 } 13062 } 13063 13064 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13065 switch (status) { 13066 case PackageInstaller.STATUS_SUCCESS: 13067 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13068 break; 13069 case PackageInstaller.STATUS_FAILURE_STORAGE: 13070 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13071 break; 13072 default: 13073 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13074 break; 13075 } 13076 } 13077 }; 13078 13079 // Treat a move like reinstalling an existing app, which ensures that we 13080 // process everythign uniformly, like unpacking native libraries. 13081 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13082 13083 final Message msg = mHandler.obtainMessage(INIT_COPY); 13084 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13085 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13086 installerPackageName, null, user, packageAbiOverride); 13087 mHandler.sendMessage(msg); 13088 } 13089 13090 @Override 13091 public boolean setInstallLocation(int loc) { 13092 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13093 null); 13094 if (getInstallLocation() == loc) { 13095 return true; 13096 } 13097 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13098 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13099 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13100 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13101 return true; 13102 } 13103 return false; 13104 } 13105 13106 @Override 13107 public int getInstallLocation() { 13108 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13109 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13110 PackageHelper.APP_INSTALL_AUTO); 13111 } 13112 13113 /** Called by UserManagerService */ 13114 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13115 mDirtyUsers.remove(userHandle); 13116 mSettings.removeUserLPw(userHandle); 13117 mPendingBroadcasts.remove(userHandle); 13118 if (mInstaller != null) { 13119 // Technically, we shouldn't be doing this with the package lock 13120 // held. However, this is very rare, and there is already so much 13121 // other disk I/O going on, that we'll let it slide for now. 13122 mInstaller.removeUserDataDirs(userHandle); 13123 } 13124 mUserNeedsBadging.delete(userHandle); 13125 removeUnusedPackagesLILPw(userManager, userHandle); 13126 } 13127 13128 /** 13129 * We're removing userHandle and would like to remove any downloaded packages 13130 * that are no longer in use by any other user. 13131 * @param userHandle the user being removed 13132 */ 13133 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13134 final boolean DEBUG_CLEAN_APKS = false; 13135 int [] users = userManager.getUserIdsLPr(); 13136 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13137 while (psit.hasNext()) { 13138 PackageSetting ps = psit.next(); 13139 if (ps.pkg == null) { 13140 continue; 13141 } 13142 final String packageName = ps.pkg.packageName; 13143 // Skip over if system app 13144 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13145 continue; 13146 } 13147 if (DEBUG_CLEAN_APKS) { 13148 Slog.i(TAG, "Checking package " + packageName); 13149 } 13150 boolean keep = false; 13151 for (int i = 0; i < users.length; i++) { 13152 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13153 keep = true; 13154 if (DEBUG_CLEAN_APKS) { 13155 Slog.i(TAG, " Keeping package " + packageName + " for user " 13156 + users[i]); 13157 } 13158 break; 13159 } 13160 } 13161 if (!keep) { 13162 if (DEBUG_CLEAN_APKS) { 13163 Slog.i(TAG, " Removing package " + packageName); 13164 } 13165 mHandler.post(new Runnable() { 13166 public void run() { 13167 deletePackageX(packageName, userHandle, 0); 13168 } //end run 13169 }); 13170 } 13171 } 13172 } 13173 13174 /** Called by UserManagerService */ 13175 void createNewUserLILPw(int userHandle, File path) { 13176 if (mInstaller != null) { 13177 mInstaller.createUserConfig(userHandle); 13178 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13179 } 13180 } 13181 13182 @Override 13183 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13184 mContext.enforceCallingOrSelfPermission( 13185 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13186 "Only package verification agents can read the verifier device identity"); 13187 13188 synchronized (mPackages) { 13189 return mSettings.getVerifierDeviceIdentityLPw(); 13190 } 13191 } 13192 13193 @Override 13194 public void setPermissionEnforced(String permission, boolean enforced) { 13195 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13196 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13197 synchronized (mPackages) { 13198 if (mSettings.mReadExternalStorageEnforced == null 13199 || mSettings.mReadExternalStorageEnforced != enforced) { 13200 mSettings.mReadExternalStorageEnforced = enforced; 13201 mSettings.writeLPr(); 13202 } 13203 } 13204 // kill any non-foreground processes so we restart them and 13205 // grant/revoke the GID. 13206 final IActivityManager am = ActivityManagerNative.getDefault(); 13207 if (am != null) { 13208 final long token = Binder.clearCallingIdentity(); 13209 try { 13210 am.killProcessesBelowForeground("setPermissionEnforcement"); 13211 } catch (RemoteException e) { 13212 } finally { 13213 Binder.restoreCallingIdentity(token); 13214 } 13215 } 13216 } else { 13217 throw new IllegalArgumentException("No selective enforcement for " + permission); 13218 } 13219 } 13220 13221 @Override 13222 @Deprecated 13223 public boolean isPermissionEnforced(String permission) { 13224 return true; 13225 } 13226 13227 @Override 13228 public boolean isStorageLow() { 13229 final long token = Binder.clearCallingIdentity(); 13230 try { 13231 final DeviceStorageMonitorInternal 13232 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13233 if (dsm != null) { 13234 return dsm.isMemoryLow(); 13235 } else { 13236 return false; 13237 } 13238 } finally { 13239 Binder.restoreCallingIdentity(token); 13240 } 13241 } 13242 13243 @Override 13244 public IPackageInstaller getPackageInstaller() { 13245 return mInstallerService; 13246 } 13247 13248 private boolean userNeedsBadging(int userId) { 13249 int index = mUserNeedsBadging.indexOfKey(userId); 13250 if (index < 0) { 13251 final UserInfo userInfo; 13252 final long token = Binder.clearCallingIdentity(); 13253 try { 13254 userInfo = sUserManager.getUserInfo(userId); 13255 } finally { 13256 Binder.restoreCallingIdentity(token); 13257 } 13258 final boolean b; 13259 if (userInfo != null && userInfo.isManagedProfile()) { 13260 b = true; 13261 } else { 13262 b = false; 13263 } 13264 mUserNeedsBadging.put(userId, b); 13265 return b; 13266 } 13267 return mUserNeedsBadging.valueAt(index); 13268 } 13269 13270 @Override 13271 public KeySet getKeySetByAlias(String packageName, String alias) { 13272 if (packageName == null || alias == null) { 13273 return null; 13274 } 13275 synchronized(mPackages) { 13276 final PackageParser.Package pkg = mPackages.get(packageName); 13277 if (pkg == null) { 13278 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13279 throw new IllegalArgumentException("Unknown package: " + packageName); 13280 } 13281 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13282 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13283 } 13284 } 13285 13286 @Override 13287 public KeySet getSigningKeySet(String packageName) { 13288 if (packageName == null) { 13289 return null; 13290 } 13291 synchronized(mPackages) { 13292 final PackageParser.Package pkg = mPackages.get(packageName); 13293 if (pkg == null) { 13294 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13295 throw new IllegalArgumentException("Unknown package: " + packageName); 13296 } 13297 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13298 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13299 throw new SecurityException("May not access signing KeySet of other apps."); 13300 } 13301 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13302 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13303 } 13304 } 13305 13306 @Override 13307 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13308 if (packageName == null || ks == null) { 13309 return false; 13310 } 13311 synchronized(mPackages) { 13312 final PackageParser.Package pkg = mPackages.get(packageName); 13313 if (pkg == null) { 13314 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13315 throw new IllegalArgumentException("Unknown package: " + packageName); 13316 } 13317 IBinder ksh = ks.getToken(); 13318 if (ksh instanceof KeySetHandle) { 13319 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13320 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13321 } 13322 return false; 13323 } 13324 } 13325 13326 @Override 13327 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13328 if (packageName == null || ks == null) { 13329 return false; 13330 } 13331 synchronized(mPackages) { 13332 final PackageParser.Package pkg = mPackages.get(packageName); 13333 if (pkg == null) { 13334 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13335 throw new IllegalArgumentException("Unknown package: " + packageName); 13336 } 13337 IBinder ksh = ks.getToken(); 13338 if (ksh instanceof KeySetHandle) { 13339 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13340 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13341 } 13342 return false; 13343 } 13344 } 13345 13346 public void getUsageStatsIfNoPackageUsageInfo() { 13347 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 13348 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 13349 if (usm == null) { 13350 throw new IllegalStateException("UsageStatsManager must be initialized"); 13351 } 13352 long now = System.currentTimeMillis(); 13353 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 13354 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 13355 String packageName = entry.getKey(); 13356 PackageParser.Package pkg = mPackages.get(packageName); 13357 if (pkg == null) { 13358 continue; 13359 } 13360 UsageStats usage = entry.getValue(); 13361 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 13362 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 13363 } 13364 } 13365 } 13366 13367 /** 13368 * Check and throw if the given before/after packages would be considered a 13369 * downgrade. 13370 */ 13371 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 13372 throws PackageManagerException { 13373 if (after.versionCode < before.mVersionCode) { 13374 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13375 "Update version code " + after.versionCode + " is older than current " 13376 + before.mVersionCode); 13377 } else if (after.versionCode == before.mVersionCode) { 13378 if (after.baseRevisionCode < before.baseRevisionCode) { 13379 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13380 "Update base revision code " + after.baseRevisionCode 13381 + " is older than current " + before.baseRevisionCode); 13382 } 13383 13384 if (!ArrayUtils.isEmpty(after.splitNames)) { 13385 for (int i = 0; i < after.splitNames.length; i++) { 13386 final String splitName = after.splitNames[i]; 13387 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 13388 if (j != -1) { 13389 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 13390 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13391 "Update split " + splitName + " revision code " 13392 + after.splitRevisionCodes[i] + " is older than current " 13393 + before.splitRevisionCodes[j]); 13394 } 13395 } 13396 } 13397 } 13398 } 13399 } 13400} 13401