PackageManagerService.java revision 8c04facdf5e76fb34c55cfe3dc9a0216322b91b8
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.InstructionSets.getAppDexInstructionSets; 59import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 60import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 61import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 62 63import android.util.ArrayMap; 64 65import com.android.internal.R; 66import com.android.internal.app.IMediaContainerService; 67import com.android.internal.app.ResolverActivity; 68import com.android.internal.content.NativeLibraryHelper; 69import com.android.internal.content.PackageHelper; 70import com.android.internal.os.IParcelFileDescriptorFactory; 71import com.android.internal.util.ArrayUtils; 72import com.android.internal.util.FastPrintWriter; 73import com.android.internal.util.FastXmlSerializer; 74import com.android.internal.util.IndentingPrintWriter; 75import com.android.server.EventLogTags; 76import com.android.server.IntentResolver; 77import com.android.server.LocalServices; 78import com.android.server.ServiceThread; 79import com.android.server.SystemConfig; 80import com.android.server.Watchdog; 81import com.android.server.pm.Settings.DatabaseVersion; 82import com.android.server.storage.DeviceStorageMonitorInternal; 83 84import org.xmlpull.v1.XmlSerializer; 85 86import android.app.ActivityManager; 87import android.app.ActivityManagerNative; 88import android.app.AppGlobals; 89import android.app.IActivityManager; 90import android.app.admin.IDevicePolicyManager; 91import android.app.backup.IBackupManager; 92import android.app.usage.UsageStats; 93import android.app.usage.UsageStatsManager; 94import android.content.BroadcastReceiver; 95import android.content.ComponentName; 96import android.content.Context; 97import android.content.IIntentReceiver; 98import android.content.Intent; 99import android.content.IntentFilter; 100import android.content.IntentSender; 101import android.content.IntentSender.SendIntentException; 102import android.content.ServiceConnection; 103import android.content.pm.ActivityInfo; 104import android.content.pm.ApplicationInfo; 105import android.content.pm.FeatureInfo; 106import android.content.pm.IPackageDataObserver; 107import android.content.pm.IPackageDeleteObserver; 108import android.content.pm.IPackageDeleteObserver2; 109import android.content.pm.IPackageInstallObserver2; 110import android.content.pm.IPackageInstaller; 111import android.content.pm.IPackageManager; 112import android.content.pm.IPackageMoveObserver; 113import android.content.pm.IPackageStatsObserver; 114import android.content.pm.InstrumentationInfo; 115import android.content.pm.KeySet; 116import android.content.pm.ManifestDigest; 117import android.content.pm.PackageCleanItem; 118import android.content.pm.PackageInfo; 119import android.content.pm.PackageInfoLite; 120import android.content.pm.PackageInstaller; 121import android.content.pm.PackageManager; 122import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 123import android.content.pm.PackageParser.ActivityIntentInfo; 124import android.content.pm.PackageParser.PackageLite; 125import android.content.pm.PackageParser.PackageParserException; 126import android.content.pm.PackageParser; 127import android.content.pm.PackageStats; 128import android.content.pm.PackageUserState; 129import android.content.pm.ParceledListSlice; 130import android.content.pm.PermissionGroupInfo; 131import android.content.pm.PermissionInfo; 132import android.content.pm.ProviderInfo; 133import android.content.pm.ResolveInfo; 134import android.content.pm.ServiceInfo; 135import android.content.pm.Signature; 136import android.content.pm.UserInfo; 137import android.content.pm.VerificationParams; 138import android.content.pm.VerifierDeviceIdentity; 139import android.content.pm.VerifierInfo; 140import android.content.res.Resources; 141import android.hardware.display.DisplayManager; 142import android.net.Uri; 143import android.os.Binder; 144import android.os.Build; 145import android.os.Bundle; 146import android.os.Environment; 147import android.os.Environment.UserEnvironment; 148import android.os.storage.IMountService; 149import android.os.storage.StorageManager; 150import android.os.Debug; 151import android.os.FileUtils; 152import android.os.Handler; 153import android.os.IBinder; 154import android.os.Looper; 155import android.os.Message; 156import android.os.Parcel; 157import android.os.ParcelFileDescriptor; 158import android.os.Process; 159import android.os.RemoteException; 160import android.os.SELinux; 161import android.os.ServiceManager; 162import android.os.SystemClock; 163import android.os.SystemProperties; 164import android.os.UserHandle; 165import android.os.UserManager; 166import android.security.KeyStore; 167import android.security.SystemKeyStore; 168import android.system.ErrnoException; 169import android.system.Os; 170import android.system.StructStat; 171import android.text.TextUtils; 172import android.text.format.DateUtils; 173import android.util.ArraySet; 174import android.util.AtomicFile; 175import android.util.DisplayMetrics; 176import android.util.EventLog; 177import android.util.ExceptionUtils; 178import android.util.Log; 179import android.util.LogPrinter; 180import android.util.PrintStreamPrinter; 181import android.util.Slog; 182import android.util.SparseArray; 183import android.util.SparseBooleanArray; 184import android.view.Display; 185 186import java.io.BufferedInputStream; 187import java.io.BufferedOutputStream; 188import java.io.BufferedReader; 189import java.io.File; 190import java.io.FileDescriptor; 191import java.io.FileNotFoundException; 192import java.io.FileOutputStream; 193import java.io.FileReader; 194import java.io.FilenameFilter; 195import java.io.IOException; 196import java.io.InputStream; 197import java.io.PrintWriter; 198import java.nio.charset.StandardCharsets; 199import java.security.NoSuchAlgorithmException; 200import java.security.PublicKey; 201import java.security.cert.CertificateEncodingException; 202import java.security.cert.CertificateException; 203import java.text.SimpleDateFormat; 204import java.util.ArrayList; 205import java.util.Arrays; 206import java.util.Collection; 207import java.util.Collections; 208import java.util.Comparator; 209import java.util.Date; 210import java.util.Iterator; 211import java.util.List; 212import java.util.Map; 213import java.util.Objects; 214import java.util.Set; 215import java.util.concurrent.atomic.AtomicBoolean; 216import java.util.concurrent.atomic.AtomicLong; 217 218import dalvik.system.DexFile; 219import dalvik.system.VMRuntime; 220 221import libcore.io.IoUtils; 222import libcore.util.EmptyArray; 223 224/** 225 * Keep track of all those .apks everywhere. 226 * 227 * This is very central to the platform's security; please run the unit 228 * tests whenever making modifications here: 229 * 230mmm frameworks/base/tests/AndroidTests 231adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 232adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 233 * 234 * {@hide} 235 */ 236public class PackageManagerService extends IPackageManager.Stub { 237 static final String TAG = "PackageManager"; 238 static final boolean DEBUG_SETTINGS = false; 239 static final boolean DEBUG_PREFERRED = false; 240 static final boolean DEBUG_UPGRADE = false; 241 private static final boolean DEBUG_INSTALL = false; 242 private static final boolean DEBUG_REMOVE = false; 243 private static final boolean DEBUG_BROADCASTS = false; 244 private static final boolean DEBUG_SHOW_INFO = false; 245 private static final boolean DEBUG_PACKAGE_INFO = false; 246 private static final boolean DEBUG_INTENT_MATCHING = false; 247 private static final boolean DEBUG_PACKAGE_SCANNING = false; 248 private static final boolean DEBUG_VERIFY = false; 249 private static final boolean DEBUG_DEXOPT = false; 250 private static final boolean DEBUG_ABI_SELECTION = false; 251 252 private static final int RADIO_UID = Process.PHONE_UID; 253 private static final int LOG_UID = Process.LOG_UID; 254 private static final int NFC_UID = Process.NFC_UID; 255 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 256 private static final int SHELL_UID = Process.SHELL_UID; 257 258 // Cap the size of permission trees that 3rd party apps can define 259 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 260 261 // Suffix used during package installation when copying/moving 262 // package apks to install directory. 263 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 264 265 static final int SCAN_NO_DEX = 1<<1; 266 static final int SCAN_FORCE_DEX = 1<<2; 267 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 268 static final int SCAN_NEW_INSTALL = 1<<4; 269 static final int SCAN_NO_PATHS = 1<<5; 270 static final int SCAN_UPDATE_TIME = 1<<6; 271 static final int SCAN_DEFER_DEX = 1<<7; 272 static final int SCAN_BOOTING = 1<<8; 273 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 274 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 275 static final int SCAN_REPLACING = 1<<11; 276 277 static final int REMOVE_CHATTY = 1<<16; 278 279 /** 280 * Timeout (in milliseconds) after which the watchdog should declare that 281 * our handler thread is wedged. The usual default for such things is one 282 * minute but we sometimes do very lengthy I/O operations on this thread, 283 * such as installing multi-gigabyte applications, so ours needs to be longer. 284 */ 285 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 286 287 /** 288 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 289 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 290 * settings entry if available, otherwise we use the hardcoded default. If it's been 291 * more than this long since the last fstrim, we force one during the boot sequence. 292 * 293 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 294 * one gets run at the next available charging+idle time. This final mandatory 295 * no-fstrim check kicks in only of the other scheduling criteria is never met. 296 */ 297 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 298 299 /** 300 * Whether verification is enabled by default. 301 */ 302 private static final boolean DEFAULT_VERIFY_ENABLE = true; 303 304 /** 305 * The default maximum time to wait for the verification agent to return in 306 * milliseconds. 307 */ 308 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 309 310 /** 311 * The default response for package verification timeout. 312 * 313 * This can be either PackageManager.VERIFICATION_ALLOW or 314 * PackageManager.VERIFICATION_REJECT. 315 */ 316 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 317 318 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 319 320 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 321 DEFAULT_CONTAINER_PACKAGE, 322 "com.android.defcontainer.DefaultContainerService"); 323 324 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 325 326 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 327 328 final ServiceThread mHandlerThread; 329 330 final PackageHandler mHandler; 331 332 /** 333 * Messages for {@link #mHandler} that need to wait for system ready before 334 * being dispatched. 335 */ 336 private ArrayList<Message> mPostSystemReadyMessages; 337 338 final int mSdkVersion = Build.VERSION.SDK_INT; 339 340 final Context mContext; 341 final boolean mFactoryTest; 342 final boolean mOnlyCore; 343 final boolean mLazyDexOpt; 344 final long mDexOptLRUThresholdInMills; 345 final DisplayMetrics mMetrics; 346 final int mDefParseFlags; 347 final String[] mSeparateProcesses; 348 final boolean mIsUpgrade; 349 350 // This is where all application persistent data goes. 351 final File mAppDataDir; 352 353 // This is where all application persistent data goes for secondary users. 354 final File mUserAppDataDir; 355 356 /** The location for ASEC container files on internal storage. */ 357 final String mAsecInternalPath; 358 359 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 360 // LOCK HELD. Can be called with mInstallLock held. 361 final Installer mInstaller; 362 363 /** Directory where installed third-party apps stored */ 364 final File mAppInstallDir; 365 366 /** 367 * Directory to which applications installed internally have their 368 * 32 bit native libraries copied. 369 */ 370 private File mAppLib32InstallDir; 371 372 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 373 // apps. 374 final File mDrmAppPrivateInstallDir; 375 376 // ---------------------------------------------------------------- 377 378 // Lock for state used when installing and doing other long running 379 // operations. Methods that must be called with this lock held have 380 // the suffix "LI". 381 final Object mInstallLock = new Object(); 382 383 // ---------------------------------------------------------------- 384 385 // Keys are String (package name), values are Package. This also serves 386 // as the lock for the global state. Methods that must be called with 387 // this lock held have the prefix "LP". 388 final ArrayMap<String, PackageParser.Package> mPackages = 389 new ArrayMap<String, PackageParser.Package>(); 390 391 // Tracks available target package names -> overlay package paths. 392 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 393 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 394 395 final Settings mSettings; 396 boolean mRestoredSettings; 397 398 // System configuration read by SystemConfig. 399 final int[] mGlobalGids; 400 final SparseArray<ArraySet<String>> mSystemPermissions; 401 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 402 403 // If mac_permissions.xml was found for seinfo labeling. 404 boolean mFoundPolicyFile; 405 406 // If a recursive restorecon of /data/data/<pkg> is needed. 407 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 408 409 public static final class SharedLibraryEntry { 410 public final String path; 411 public final String apk; 412 413 SharedLibraryEntry(String _path, String _apk) { 414 path = _path; 415 apk = _apk; 416 } 417 } 418 419 // Currently known shared libraries. 420 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 421 new ArrayMap<String, SharedLibraryEntry>(); 422 423 // All available activities, for your resolving pleasure. 424 final ActivityIntentResolver mActivities = 425 new ActivityIntentResolver(); 426 427 // All available receivers, for your resolving pleasure. 428 final ActivityIntentResolver mReceivers = 429 new ActivityIntentResolver(); 430 431 // All available services, for your resolving pleasure. 432 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 433 434 // All available providers, for your resolving pleasure. 435 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 436 437 // Mapping from provider base names (first directory in content URI codePath) 438 // to the provider information. 439 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 440 new ArrayMap<String, PackageParser.Provider>(); 441 442 // Mapping from instrumentation class names to info about them. 443 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 444 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 445 446 // Mapping from permission names to info about them. 447 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 448 new ArrayMap<String, PackageParser.PermissionGroup>(); 449 450 // Packages whose data we have transfered into another package, thus 451 // should no longer exist. 452 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 453 454 // Broadcast actions that are only available to the system. 455 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 456 457 /** List of packages waiting for verification. */ 458 final SparseArray<PackageVerificationState> mPendingVerification 459 = new SparseArray<PackageVerificationState>(); 460 461 /** Set of packages associated with each app op permission. */ 462 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 463 464 final PackageInstallerService mInstallerService; 465 466 private final PackageDexOptimizer mPackageDexOptimizer; 467 // Cache of users who need badging. 468 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 469 470 /** Token for keys in mPendingVerification. */ 471 private int mPendingVerificationToken = 0; 472 473 volatile boolean mSystemReady; 474 volatile boolean mSafeMode; 475 volatile boolean mHasSystemUidErrors; 476 477 ApplicationInfo mAndroidApplication; 478 final ActivityInfo mResolveActivity = new ActivityInfo(); 479 final ResolveInfo mResolveInfo = new ResolveInfo(); 480 ComponentName mResolveComponentName; 481 PackageParser.Package mPlatformPackage; 482 ComponentName mCustomResolverComponentName; 483 484 boolean mResolverReplaced = false; 485 486 // Set of pending broadcasts for aggregating enable/disable of components. 487 static class PendingPackageBroadcasts { 488 // for each user id, a map of <package name -> components within that package> 489 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 490 491 public PendingPackageBroadcasts() { 492 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 493 } 494 495 public ArrayList<String> get(int userId, String packageName) { 496 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 497 return packages.get(packageName); 498 } 499 500 public void put(int userId, String packageName, ArrayList<String> components) { 501 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 502 packages.put(packageName, components); 503 } 504 505 public void remove(int userId, String packageName) { 506 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 507 if (packages != null) { 508 packages.remove(packageName); 509 } 510 } 511 512 public void remove(int userId) { 513 mUidMap.remove(userId); 514 } 515 516 public int userIdCount() { 517 return mUidMap.size(); 518 } 519 520 public int userIdAt(int n) { 521 return mUidMap.keyAt(n); 522 } 523 524 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 525 return mUidMap.get(userId); 526 } 527 528 public int size() { 529 // total number of pending broadcast entries across all userIds 530 int num = 0; 531 for (int i = 0; i< mUidMap.size(); i++) { 532 num += mUidMap.valueAt(i).size(); 533 } 534 return num; 535 } 536 537 public void clear() { 538 mUidMap.clear(); 539 } 540 541 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 542 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 543 if (map == null) { 544 map = new ArrayMap<String, ArrayList<String>>(); 545 mUidMap.put(userId, map); 546 } 547 return map; 548 } 549 } 550 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 551 552 // Service Connection to remote media container service to copy 553 // package uri's from external media onto secure containers 554 // or internal storage. 555 private IMediaContainerService mContainerService = null; 556 557 static final int SEND_PENDING_BROADCAST = 1; 558 static final int MCS_BOUND = 3; 559 static final int END_COPY = 4; 560 static final int INIT_COPY = 5; 561 static final int MCS_UNBIND = 6; 562 static final int START_CLEANING_PACKAGE = 7; 563 static final int FIND_INSTALL_LOC = 8; 564 static final int POST_INSTALL = 9; 565 static final int MCS_RECONNECT = 10; 566 static final int MCS_GIVE_UP = 11; 567 static final int UPDATED_MEDIA_STATUS = 12; 568 static final int WRITE_SETTINGS = 13; 569 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 570 static final int PACKAGE_VERIFIED = 15; 571 static final int CHECK_PENDING_VERIFICATION = 16; 572 573 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 574 575 // Delay time in millisecs 576 static final int BROADCAST_DELAY = 10 * 1000; 577 578 static UserManagerService sUserManager; 579 580 // Stores a list of users whose package restrictions file needs to be updated 581 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 582 583 final private DefaultContainerConnection mDefContainerConn = 584 new DefaultContainerConnection(); 585 class DefaultContainerConnection implements ServiceConnection { 586 public void onServiceConnected(ComponentName name, IBinder service) { 587 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 588 IMediaContainerService imcs = 589 IMediaContainerService.Stub.asInterface(service); 590 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 591 } 592 593 public void onServiceDisconnected(ComponentName name) { 594 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 595 } 596 }; 597 598 // Recordkeeping of restore-after-install operations that are currently in flight 599 // between the Package Manager and the Backup Manager 600 class PostInstallData { 601 public InstallArgs args; 602 public PackageInstalledInfo res; 603 604 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 605 args = _a; 606 res = _r; 607 } 608 }; 609 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 610 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 611 612 private final String mRequiredVerifierPackage; 613 614 private final PackageUsage mPackageUsage = new PackageUsage(); 615 616 private class PackageUsage { 617 private static final int WRITE_INTERVAL 618 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 619 620 private final Object mFileLock = new Object(); 621 private final AtomicLong mLastWritten = new AtomicLong(0); 622 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 623 624 private boolean mIsHistoricalPackageUsageAvailable = true; 625 626 boolean isHistoricalPackageUsageAvailable() { 627 return mIsHistoricalPackageUsageAvailable; 628 } 629 630 void write(boolean force) { 631 if (force) { 632 writeInternal(); 633 return; 634 } 635 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 636 && !DEBUG_DEXOPT) { 637 return; 638 } 639 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 640 new Thread("PackageUsage_DiskWriter") { 641 @Override 642 public void run() { 643 try { 644 writeInternal(); 645 } finally { 646 mBackgroundWriteRunning.set(false); 647 } 648 } 649 }.start(); 650 } 651 } 652 653 private void writeInternal() { 654 synchronized (mPackages) { 655 synchronized (mFileLock) { 656 AtomicFile file = getFile(); 657 FileOutputStream f = null; 658 try { 659 f = file.startWrite(); 660 BufferedOutputStream out = new BufferedOutputStream(f); 661 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 662 StringBuilder sb = new StringBuilder(); 663 for (PackageParser.Package pkg : mPackages.values()) { 664 if (pkg.mLastPackageUsageTimeInMills == 0) { 665 continue; 666 } 667 sb.setLength(0); 668 sb.append(pkg.packageName); 669 sb.append(' '); 670 sb.append((long)pkg.mLastPackageUsageTimeInMills); 671 sb.append('\n'); 672 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 673 } 674 out.flush(); 675 file.finishWrite(f); 676 } catch (IOException e) { 677 if (f != null) { 678 file.failWrite(f); 679 } 680 Log.e(TAG, "Failed to write package usage times", e); 681 } 682 } 683 } 684 mLastWritten.set(SystemClock.elapsedRealtime()); 685 } 686 687 void readLP() { 688 synchronized (mFileLock) { 689 AtomicFile file = getFile(); 690 BufferedInputStream in = null; 691 try { 692 in = new BufferedInputStream(file.openRead()); 693 StringBuffer sb = new StringBuffer(); 694 while (true) { 695 String packageName = readToken(in, sb, ' '); 696 if (packageName == null) { 697 break; 698 } 699 String timeInMillisString = readToken(in, sb, '\n'); 700 if (timeInMillisString == null) { 701 throw new IOException("Failed to find last usage time for package " 702 + packageName); 703 } 704 PackageParser.Package pkg = mPackages.get(packageName); 705 if (pkg == null) { 706 continue; 707 } 708 long timeInMillis; 709 try { 710 timeInMillis = Long.parseLong(timeInMillisString.toString()); 711 } catch (NumberFormatException e) { 712 throw new IOException("Failed to parse " + timeInMillisString 713 + " as a long.", e); 714 } 715 pkg.mLastPackageUsageTimeInMills = timeInMillis; 716 } 717 } catch (FileNotFoundException expected) { 718 mIsHistoricalPackageUsageAvailable = false; 719 } catch (IOException e) { 720 Log.w(TAG, "Failed to read package usage times", e); 721 } finally { 722 IoUtils.closeQuietly(in); 723 } 724 } 725 mLastWritten.set(SystemClock.elapsedRealtime()); 726 } 727 728 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 729 throws IOException { 730 sb.setLength(0); 731 while (true) { 732 int ch = in.read(); 733 if (ch == -1) { 734 if (sb.length() == 0) { 735 return null; 736 } 737 throw new IOException("Unexpected EOF"); 738 } 739 if (ch == endOfToken) { 740 return sb.toString(); 741 } 742 sb.append((char)ch); 743 } 744 } 745 746 private AtomicFile getFile() { 747 File dataDir = Environment.getDataDirectory(); 748 File systemDir = new File(dataDir, "system"); 749 File fname = new File(systemDir, "package-usage.list"); 750 return new AtomicFile(fname); 751 } 752 } 753 754 class PackageHandler extends Handler { 755 private boolean mBound = false; 756 final ArrayList<HandlerParams> mPendingInstalls = 757 new ArrayList<HandlerParams>(); 758 759 private boolean connectToService() { 760 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 761 " DefaultContainerService"); 762 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 763 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 764 if (mContext.bindServiceAsUser(service, mDefContainerConn, 765 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 766 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 767 mBound = true; 768 return true; 769 } 770 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 771 return false; 772 } 773 774 private void disconnectService() { 775 mContainerService = null; 776 mBound = false; 777 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 778 mContext.unbindService(mDefContainerConn); 779 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 780 } 781 782 PackageHandler(Looper looper) { 783 super(looper); 784 } 785 786 public void handleMessage(Message msg) { 787 try { 788 doHandleMessage(msg); 789 } finally { 790 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 791 } 792 } 793 794 void doHandleMessage(Message msg) { 795 switch (msg.what) { 796 case INIT_COPY: { 797 HandlerParams params = (HandlerParams) msg.obj; 798 int idx = mPendingInstalls.size(); 799 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 800 // If a bind was already initiated we dont really 801 // need to do anything. The pending install 802 // will be processed later on. 803 if (!mBound) { 804 // If this is the only one pending we might 805 // have to bind to the service again. 806 if (!connectToService()) { 807 Slog.e(TAG, "Failed to bind to media container service"); 808 params.serviceError(); 809 return; 810 } else { 811 // Once we bind to the service, the first 812 // pending request will be processed. 813 mPendingInstalls.add(idx, params); 814 } 815 } else { 816 mPendingInstalls.add(idx, params); 817 // Already bound to the service. Just make 818 // sure we trigger off processing the first request. 819 if (idx == 0) { 820 mHandler.sendEmptyMessage(MCS_BOUND); 821 } 822 } 823 break; 824 } 825 case MCS_BOUND: { 826 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 827 if (msg.obj != null) { 828 mContainerService = (IMediaContainerService) msg.obj; 829 } 830 if (mContainerService == null) { 831 // Something seriously wrong. Bail out 832 Slog.e(TAG, "Cannot bind to media container service"); 833 for (HandlerParams params : mPendingInstalls) { 834 // Indicate service bind error 835 params.serviceError(); 836 } 837 mPendingInstalls.clear(); 838 } else if (mPendingInstalls.size() > 0) { 839 HandlerParams params = mPendingInstalls.get(0); 840 if (params != null) { 841 if (params.startCopy()) { 842 // We are done... look for more work or to 843 // go idle. 844 if (DEBUG_SD_INSTALL) Log.i(TAG, 845 "Checking for more work or unbind..."); 846 // Delete pending install 847 if (mPendingInstalls.size() > 0) { 848 mPendingInstalls.remove(0); 849 } 850 if (mPendingInstalls.size() == 0) { 851 if (mBound) { 852 if (DEBUG_SD_INSTALL) Log.i(TAG, 853 "Posting delayed MCS_UNBIND"); 854 removeMessages(MCS_UNBIND); 855 Message ubmsg = obtainMessage(MCS_UNBIND); 856 // Unbind after a little delay, to avoid 857 // continual thrashing. 858 sendMessageDelayed(ubmsg, 10000); 859 } 860 } else { 861 // There are more pending requests in queue. 862 // Just post MCS_BOUND message to trigger processing 863 // of next pending install. 864 if (DEBUG_SD_INSTALL) Log.i(TAG, 865 "Posting MCS_BOUND for next work"); 866 mHandler.sendEmptyMessage(MCS_BOUND); 867 } 868 } 869 } 870 } else { 871 // Should never happen ideally. 872 Slog.w(TAG, "Empty queue"); 873 } 874 break; 875 } 876 case MCS_RECONNECT: { 877 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 878 if (mPendingInstalls.size() > 0) { 879 if (mBound) { 880 disconnectService(); 881 } 882 if (!connectToService()) { 883 Slog.e(TAG, "Failed to bind to media container service"); 884 for (HandlerParams params : mPendingInstalls) { 885 // Indicate service bind error 886 params.serviceError(); 887 } 888 mPendingInstalls.clear(); 889 } 890 } 891 break; 892 } 893 case MCS_UNBIND: { 894 // If there is no actual work left, then time to unbind. 895 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 896 897 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 898 if (mBound) { 899 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 900 901 disconnectService(); 902 } 903 } else if (mPendingInstalls.size() > 0) { 904 // There are more pending requests in queue. 905 // Just post MCS_BOUND message to trigger processing 906 // of next pending install. 907 mHandler.sendEmptyMessage(MCS_BOUND); 908 } 909 910 break; 911 } 912 case MCS_GIVE_UP: { 913 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 914 mPendingInstalls.remove(0); 915 break; 916 } 917 case SEND_PENDING_BROADCAST: { 918 String packages[]; 919 ArrayList<String> components[]; 920 int size = 0; 921 int uids[]; 922 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 923 synchronized (mPackages) { 924 if (mPendingBroadcasts == null) { 925 return; 926 } 927 size = mPendingBroadcasts.size(); 928 if (size <= 0) { 929 // Nothing to be done. Just return 930 return; 931 } 932 packages = new String[size]; 933 components = new ArrayList[size]; 934 uids = new int[size]; 935 int i = 0; // filling out the above arrays 936 937 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 938 int packageUserId = mPendingBroadcasts.userIdAt(n); 939 Iterator<Map.Entry<String, ArrayList<String>>> it 940 = mPendingBroadcasts.packagesForUserId(packageUserId) 941 .entrySet().iterator(); 942 while (it.hasNext() && i < size) { 943 Map.Entry<String, ArrayList<String>> ent = it.next(); 944 packages[i] = ent.getKey(); 945 components[i] = ent.getValue(); 946 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 947 uids[i] = (ps != null) 948 ? UserHandle.getUid(packageUserId, ps.appId) 949 : -1; 950 i++; 951 } 952 } 953 size = i; 954 mPendingBroadcasts.clear(); 955 } 956 // Send broadcasts 957 for (int i = 0; i < size; i++) { 958 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 959 } 960 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 961 break; 962 } 963 case START_CLEANING_PACKAGE: { 964 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 965 final String packageName = (String)msg.obj; 966 final int userId = msg.arg1; 967 final boolean andCode = msg.arg2 != 0; 968 synchronized (mPackages) { 969 if (userId == UserHandle.USER_ALL) { 970 int[] users = sUserManager.getUserIds(); 971 for (int user : users) { 972 mSettings.addPackageToCleanLPw( 973 new PackageCleanItem(user, packageName, andCode)); 974 } 975 } else { 976 mSettings.addPackageToCleanLPw( 977 new PackageCleanItem(userId, packageName, andCode)); 978 } 979 } 980 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 981 startCleaningPackages(); 982 } break; 983 case POST_INSTALL: { 984 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 985 PostInstallData data = mRunningInstalls.get(msg.arg1); 986 mRunningInstalls.delete(msg.arg1); 987 boolean deleteOld = false; 988 989 if (data != null) { 990 InstallArgs args = data.args; 991 PackageInstalledInfo res = data.res; 992 993 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 994 res.removedInfo.sendBroadcast(false, true, false); 995 Bundle extras = new Bundle(1); 996 extras.putInt(Intent.EXTRA_UID, res.uid); 997 // Determine the set of users who are adding this 998 // package for the first time vs. those who are seeing 999 // an update. 1000 int[] firstUsers; 1001 int[] updateUsers = new int[0]; 1002 if (res.origUsers == null || res.origUsers.length == 0) { 1003 firstUsers = res.newUsers; 1004 } else { 1005 firstUsers = new int[0]; 1006 for (int i=0; i<res.newUsers.length; i++) { 1007 int user = res.newUsers[i]; 1008 boolean isNew = true; 1009 for (int j=0; j<res.origUsers.length; j++) { 1010 if (res.origUsers[j] == user) { 1011 isNew = false; 1012 break; 1013 } 1014 } 1015 if (isNew) { 1016 int[] newFirst = new int[firstUsers.length+1]; 1017 System.arraycopy(firstUsers, 0, newFirst, 0, 1018 firstUsers.length); 1019 newFirst[firstUsers.length] = user; 1020 firstUsers = newFirst; 1021 } else { 1022 int[] newUpdate = new int[updateUsers.length+1]; 1023 System.arraycopy(updateUsers, 0, newUpdate, 0, 1024 updateUsers.length); 1025 newUpdate[updateUsers.length] = user; 1026 updateUsers = newUpdate; 1027 } 1028 } 1029 } 1030 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1031 res.pkg.applicationInfo.packageName, 1032 extras, null, null, firstUsers); 1033 final boolean update = res.removedInfo.removedPackage != null; 1034 if (update) { 1035 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1036 } 1037 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1038 res.pkg.applicationInfo.packageName, 1039 extras, null, null, updateUsers); 1040 if (update) { 1041 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1042 res.pkg.applicationInfo.packageName, 1043 extras, null, null, updateUsers); 1044 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1045 null, null, 1046 res.pkg.applicationInfo.packageName, null, updateUsers); 1047 1048 // treat asec-hosted packages like removable media on upgrade 1049 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1050 if (DEBUG_INSTALL) { 1051 Slog.i(TAG, "upgrading pkg " + res.pkg 1052 + " is ASEC-hosted -> AVAILABLE"); 1053 } 1054 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1055 ArrayList<String> pkgList = new ArrayList<String>(1); 1056 pkgList.add(res.pkg.applicationInfo.packageName); 1057 sendResourcesChangedBroadcast(true, true, 1058 pkgList,uidArray, null); 1059 } 1060 } 1061 if (res.removedInfo.args != null) { 1062 // Remove the replaced package's older resources safely now 1063 deleteOld = true; 1064 } 1065 1066 // Log current value of "unknown sources" setting 1067 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1068 getUnknownSourcesSettings()); 1069 } 1070 // Force a gc to clear up things 1071 Runtime.getRuntime().gc(); 1072 // We delete after a gc for applications on sdcard. 1073 if (deleteOld) { 1074 synchronized (mInstallLock) { 1075 res.removedInfo.args.doPostDeleteLI(true); 1076 } 1077 } 1078 if (args.observer != null) { 1079 try { 1080 Bundle extras = extrasForInstallResult(res); 1081 args.observer.onPackageInstalled(res.name, res.returnCode, 1082 res.returnMsg, extras); 1083 } catch (RemoteException e) { 1084 Slog.i(TAG, "Observer no longer exists."); 1085 } 1086 } 1087 } else { 1088 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1089 } 1090 } break; 1091 case UPDATED_MEDIA_STATUS: { 1092 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1093 boolean reportStatus = msg.arg1 == 1; 1094 boolean doGc = msg.arg2 == 1; 1095 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1096 if (doGc) { 1097 // Force a gc to clear up stale containers. 1098 Runtime.getRuntime().gc(); 1099 } 1100 if (msg.obj != null) { 1101 @SuppressWarnings("unchecked") 1102 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1103 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1104 // Unload containers 1105 unloadAllContainers(args); 1106 } 1107 if (reportStatus) { 1108 try { 1109 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1110 PackageHelper.getMountService().finishMediaUpdate(); 1111 } catch (RemoteException e) { 1112 Log.e(TAG, "MountService not running?"); 1113 } 1114 } 1115 } break; 1116 case WRITE_SETTINGS: { 1117 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1118 synchronized (mPackages) { 1119 removeMessages(WRITE_SETTINGS); 1120 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1121 mSettings.writeLPr(); 1122 mDirtyUsers.clear(); 1123 } 1124 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1125 } break; 1126 case WRITE_PACKAGE_RESTRICTIONS: { 1127 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1128 synchronized (mPackages) { 1129 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1130 for (int userId : mDirtyUsers) { 1131 mSettings.writePackageRestrictionsLPr(userId); 1132 } 1133 mDirtyUsers.clear(); 1134 } 1135 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1136 } break; 1137 case CHECK_PENDING_VERIFICATION: { 1138 final int verificationId = msg.arg1; 1139 final PackageVerificationState state = mPendingVerification.get(verificationId); 1140 1141 if ((state != null) && !state.timeoutExtended()) { 1142 final InstallArgs args = state.getInstallArgs(); 1143 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1144 1145 Slog.i(TAG, "Verification timed out for " + originUri); 1146 mPendingVerification.remove(verificationId); 1147 1148 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1149 1150 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1151 Slog.i(TAG, "Continuing with installation of " + originUri); 1152 state.setVerifierResponse(Binder.getCallingUid(), 1153 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1154 broadcastPackageVerified(verificationId, originUri, 1155 PackageManager.VERIFICATION_ALLOW, 1156 state.getInstallArgs().getUser()); 1157 try { 1158 ret = args.copyApk(mContainerService, true); 1159 } catch (RemoteException e) { 1160 Slog.e(TAG, "Could not contact the ContainerService"); 1161 } 1162 } else { 1163 broadcastPackageVerified(verificationId, originUri, 1164 PackageManager.VERIFICATION_REJECT, 1165 state.getInstallArgs().getUser()); 1166 } 1167 1168 processPendingInstall(args, ret); 1169 mHandler.sendEmptyMessage(MCS_UNBIND); 1170 } 1171 break; 1172 } 1173 case PACKAGE_VERIFIED: { 1174 final int verificationId = msg.arg1; 1175 1176 final PackageVerificationState state = mPendingVerification.get(verificationId); 1177 if (state == null) { 1178 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1179 break; 1180 } 1181 1182 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1183 1184 state.setVerifierResponse(response.callerUid, response.code); 1185 1186 if (state.isVerificationComplete()) { 1187 mPendingVerification.remove(verificationId); 1188 1189 final InstallArgs args = state.getInstallArgs(); 1190 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1191 1192 int ret; 1193 if (state.isInstallAllowed()) { 1194 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1195 broadcastPackageVerified(verificationId, originUri, 1196 response.code, state.getInstallArgs().getUser()); 1197 try { 1198 ret = args.copyApk(mContainerService, true); 1199 } catch (RemoteException e) { 1200 Slog.e(TAG, "Could not contact the ContainerService"); 1201 } 1202 } else { 1203 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1204 } 1205 1206 processPendingInstall(args, ret); 1207 1208 mHandler.sendEmptyMessage(MCS_UNBIND); 1209 } 1210 1211 break; 1212 } 1213 } 1214 } 1215 } 1216 1217 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1218 Bundle extras = null; 1219 switch (res.returnCode) { 1220 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1221 extras = new Bundle(); 1222 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1223 res.origPermission); 1224 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1225 res.origPackage); 1226 break; 1227 } 1228 } 1229 return extras; 1230 } 1231 1232 void scheduleWriteSettingsLocked() { 1233 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1234 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1235 } 1236 } 1237 1238 void scheduleWritePackageRestrictionsLocked(int userId) { 1239 if (!sUserManager.exists(userId)) return; 1240 mDirtyUsers.add(userId); 1241 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1242 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1243 } 1244 } 1245 1246 public static final PackageManagerService main(Context context, Installer installer, 1247 boolean factoryTest, boolean onlyCore) { 1248 PackageManagerService m = new PackageManagerService(context, installer, 1249 factoryTest, onlyCore); 1250 ServiceManager.addService("package", m); 1251 return m; 1252 } 1253 1254 static String[] splitString(String str, char sep) { 1255 int count = 1; 1256 int i = 0; 1257 while ((i=str.indexOf(sep, i)) >= 0) { 1258 count++; 1259 i++; 1260 } 1261 1262 String[] res = new String[count]; 1263 i=0; 1264 count = 0; 1265 int lastI=0; 1266 while ((i=str.indexOf(sep, i)) >= 0) { 1267 res[count] = str.substring(lastI, i); 1268 count++; 1269 i++; 1270 lastI = i; 1271 } 1272 res[count] = str.substring(lastI, str.length()); 1273 return res; 1274 } 1275 1276 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1277 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1278 Context.DISPLAY_SERVICE); 1279 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1280 } 1281 1282 public PackageManagerService(Context context, Installer installer, 1283 boolean factoryTest, boolean onlyCore) { 1284 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1285 SystemClock.uptimeMillis()); 1286 1287 if (mSdkVersion <= 0) { 1288 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1289 } 1290 1291 mContext = context; 1292 mFactoryTest = factoryTest; 1293 mOnlyCore = onlyCore; 1294 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1295 mMetrics = new DisplayMetrics(); 1296 mSettings = new Settings(context); 1297 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1298 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1299 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1300 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1301 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1302 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1303 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1304 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1305 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1306 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1307 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1308 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1309 1310 // TODO: add a property to control this? 1311 long dexOptLRUThresholdInMinutes; 1312 if (mLazyDexOpt) { 1313 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1314 } else { 1315 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1316 } 1317 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1318 1319 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1320 if (separateProcesses != null && separateProcesses.length() > 0) { 1321 if ("*".equals(separateProcesses)) { 1322 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1323 mSeparateProcesses = null; 1324 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1325 } else { 1326 mDefParseFlags = 0; 1327 mSeparateProcesses = separateProcesses.split(","); 1328 Slog.w(TAG, "Running with debug.separate_processes: " 1329 + separateProcesses); 1330 } 1331 } else { 1332 mDefParseFlags = 0; 1333 mSeparateProcesses = null; 1334 } 1335 1336 mInstaller = installer; 1337 mPackageDexOptimizer = new PackageDexOptimizer(this); 1338 1339 getDefaultDisplayMetrics(context, mMetrics); 1340 1341 SystemConfig systemConfig = SystemConfig.getInstance(); 1342 mGlobalGids = systemConfig.getGlobalGids(); 1343 mSystemPermissions = systemConfig.getSystemPermissions(); 1344 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1345 1346 synchronized (mInstallLock) { 1347 // writer 1348 synchronized (mPackages) { 1349 mHandlerThread = new ServiceThread(TAG, 1350 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1351 mHandlerThread.start(); 1352 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1353 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1354 1355 File dataDir = Environment.getDataDirectory(); 1356 mAppDataDir = new File(dataDir, "data"); 1357 mAppInstallDir = new File(dataDir, "app"); 1358 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1359 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1360 mUserAppDataDir = new File(dataDir, "user"); 1361 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1362 1363 sUserManager = new UserManagerService(context, this, 1364 mInstallLock, mPackages); 1365 1366 // Propagate permission configuration in to package manager. 1367 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1368 = systemConfig.getPermissions(); 1369 for (int i=0; i<permConfig.size(); i++) { 1370 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1371 BasePermission bp = mSettings.mPermissions.get(perm.name); 1372 if (bp == null) { 1373 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1374 mSettings.mPermissions.put(perm.name, bp); 1375 } 1376 if (perm.gids != null) { 1377 bp.gids = appendInts(bp.gids, perm.gids); 1378 } 1379 } 1380 1381 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1382 for (int i=0; i<libConfig.size(); i++) { 1383 mSharedLibraries.put(libConfig.keyAt(i), 1384 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1385 } 1386 1387 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1388 1389 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1390 mSdkVersion, mOnlyCore); 1391 1392 String customResolverActivity = Resources.getSystem().getString( 1393 R.string.config_customResolverActivity); 1394 if (TextUtils.isEmpty(customResolverActivity)) { 1395 customResolverActivity = null; 1396 } else { 1397 mCustomResolverComponentName = ComponentName.unflattenFromString( 1398 customResolverActivity); 1399 } 1400 1401 long startTime = SystemClock.uptimeMillis(); 1402 1403 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1404 startTime); 1405 1406 // Set flag to monitor and not change apk file paths when 1407 // scanning install directories. 1408 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1409 1410 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1411 1412 /** 1413 * Add everything in the in the boot class path to the 1414 * list of process files because dexopt will have been run 1415 * if necessary during zygote startup. 1416 */ 1417 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1418 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1419 1420 if (bootClassPath != null) { 1421 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1422 for (String element : bootClassPathElements) { 1423 alreadyDexOpted.add(element); 1424 } 1425 } else { 1426 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1427 } 1428 1429 if (systemServerClassPath != null) { 1430 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1431 for (String element : systemServerClassPathElements) { 1432 alreadyDexOpted.add(element); 1433 } 1434 } else { 1435 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1436 } 1437 1438 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1439 final String[] dexCodeInstructionSets = 1440 getDexCodeInstructionSets( 1441 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1442 1443 /** 1444 * Ensure all external libraries have had dexopt run on them. 1445 */ 1446 if (mSharedLibraries.size() > 0) { 1447 // NOTE: For now, we're compiling these system "shared libraries" 1448 // (and framework jars) into all available architectures. It's possible 1449 // to compile them only when we come across an app that uses them (there's 1450 // already logic for that in scanPackageLI) but that adds some complexity. 1451 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1452 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1453 final String lib = libEntry.path; 1454 if (lib == null) { 1455 continue; 1456 } 1457 1458 try { 1459 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1460 dexCodeInstructionSet, 1461 false); 1462 if (dexoptRequired != DexFile.UP_TO_DATE) { 1463 alreadyDexOpted.add(lib); 1464 1465 // The list of "shared libraries" we have at this point is 1466 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1467 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1468 } else { 1469 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1470 } 1471 } 1472 } catch (FileNotFoundException e) { 1473 Slog.w(TAG, "Library not found: " + lib); 1474 } catch (IOException e) { 1475 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1476 + e.getMessage()); 1477 } 1478 } 1479 } 1480 } 1481 1482 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1483 1484 // Gross hack for now: we know this file doesn't contain any 1485 // code, so don't dexopt it to avoid the resulting log spew. 1486 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1487 1488 // Gross hack for now: we know this file is only part of 1489 // the boot class path for art, so don't dexopt it to 1490 // avoid the resulting log spew. 1491 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1492 1493 /** 1494 * And there are a number of commands implemented in Java, which 1495 * we currently need to do the dexopt on so that they can be 1496 * run from a non-root shell. 1497 */ 1498 String[] frameworkFiles = frameworkDir.list(); 1499 if (frameworkFiles != null) { 1500 // TODO: We could compile these only for the most preferred ABI. We should 1501 // first double check that the dex files for these commands are not referenced 1502 // by other system apps. 1503 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1504 for (int i=0; i<frameworkFiles.length; i++) { 1505 File libPath = new File(frameworkDir, frameworkFiles[i]); 1506 String path = libPath.getPath(); 1507 // Skip the file if we already did it. 1508 if (alreadyDexOpted.contains(path)) { 1509 continue; 1510 } 1511 // Skip the file if it is not a type we want to dexopt. 1512 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1513 continue; 1514 } 1515 try { 1516 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1517 dexCodeInstructionSet, 1518 false); 1519 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1520 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1521 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1522 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1523 } 1524 } catch (FileNotFoundException e) { 1525 Slog.w(TAG, "Jar not found: " + path); 1526 } catch (IOException e) { 1527 Slog.w(TAG, "Exception reading jar: " + path, e); 1528 } 1529 } 1530 } 1531 } 1532 1533 // Collect vendor overlay packages. 1534 // (Do this before scanning any apps.) 1535 // For security and version matching reason, only consider 1536 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1537 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1538 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1539 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1540 1541 // Find base frameworks (resource packages without code). 1542 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1543 | PackageParser.PARSE_IS_SYSTEM_DIR 1544 | PackageParser.PARSE_IS_PRIVILEGED, 1545 scanFlags | SCAN_NO_DEX, 0); 1546 1547 // Collected privileged system packages. 1548 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1549 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1550 | PackageParser.PARSE_IS_SYSTEM_DIR 1551 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1552 1553 // Collect ordinary system packages. 1554 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1555 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1556 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1557 1558 // Collect all vendor packages. 1559 File vendorAppDir = new File("/vendor/app"); 1560 try { 1561 vendorAppDir = vendorAppDir.getCanonicalFile(); 1562 } catch (IOException e) { 1563 // failed to look up canonical path, continue with original one 1564 } 1565 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1566 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1567 1568 // Collect all OEM packages. 1569 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1570 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1571 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1572 1573 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1574 mInstaller.moveFiles(); 1575 1576 // Prune any system packages that no longer exist. 1577 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1578 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1579 if (!mOnlyCore) { 1580 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1581 while (psit.hasNext()) { 1582 PackageSetting ps = psit.next(); 1583 1584 /* 1585 * If this is not a system app, it can't be a 1586 * disable system app. 1587 */ 1588 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1589 continue; 1590 } 1591 1592 /* 1593 * If the package is scanned, it's not erased. 1594 */ 1595 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1596 if (scannedPkg != null) { 1597 /* 1598 * If the system app is both scanned and in the 1599 * disabled packages list, then it must have been 1600 * added via OTA. Remove it from the currently 1601 * scanned package so the previously user-installed 1602 * application can be scanned. 1603 */ 1604 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1605 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1606 + ps.name + "; removing system app. Last known codePath=" 1607 + ps.codePathString + ", installStatus=" + ps.installStatus 1608 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1609 + scannedPkg.mVersionCode); 1610 removePackageLI(ps, true); 1611 expectingBetter.put(ps.name, ps.codePath); 1612 } 1613 1614 continue; 1615 } 1616 1617 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1618 psit.remove(); 1619 logCriticalInfo(Log.WARN, "System package " + ps.name 1620 + " no longer exists; wiping its data"); 1621 removeDataDirsLI(ps.name); 1622 } else { 1623 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1624 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1625 possiblyDeletedUpdatedSystemApps.add(ps.name); 1626 } 1627 } 1628 } 1629 } 1630 1631 //look for any incomplete package installations 1632 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1633 //clean up list 1634 for(int i = 0; i < deletePkgsList.size(); i++) { 1635 //clean up here 1636 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1637 } 1638 //delete tmp files 1639 deleteTempPackageFiles(); 1640 1641 // Remove any shared userIDs that have no associated packages 1642 mSettings.pruneSharedUsersLPw(); 1643 1644 if (!mOnlyCore) { 1645 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1646 SystemClock.uptimeMillis()); 1647 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1648 1649 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1650 scanFlags, 0); 1651 1652 /** 1653 * Remove disable package settings for any updated system 1654 * apps that were removed via an OTA. If they're not a 1655 * previously-updated app, remove them completely. 1656 * Otherwise, just revoke their system-level permissions. 1657 */ 1658 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1659 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1660 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1661 1662 String msg; 1663 if (deletedPkg == null) { 1664 msg = "Updated system package " + deletedAppName 1665 + " no longer exists; wiping its data"; 1666 removeDataDirsLI(deletedAppName); 1667 } else { 1668 msg = "Updated system app + " + deletedAppName 1669 + " no longer present; removing system privileges for " 1670 + deletedAppName; 1671 1672 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1673 1674 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1675 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1676 } 1677 logCriticalInfo(Log.WARN, msg); 1678 } 1679 1680 /** 1681 * Make sure all system apps that we expected to appear on 1682 * the userdata partition actually showed up. If they never 1683 * appeared, crawl back and revive the system version. 1684 */ 1685 for (int i = 0; i < expectingBetter.size(); i++) { 1686 final String packageName = expectingBetter.keyAt(i); 1687 if (!mPackages.containsKey(packageName)) { 1688 final File scanFile = expectingBetter.valueAt(i); 1689 1690 logCriticalInfo(Log.WARN, "Expected better " + packageName 1691 + " but never showed up; reverting to system"); 1692 1693 final int reparseFlags; 1694 if (FileUtils.contains(privilegedAppDir, scanFile)) { 1695 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1696 | PackageParser.PARSE_IS_SYSTEM_DIR 1697 | PackageParser.PARSE_IS_PRIVILEGED; 1698 } else if (FileUtils.contains(systemAppDir, scanFile)) { 1699 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1700 | PackageParser.PARSE_IS_SYSTEM_DIR; 1701 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 1702 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1703 | PackageParser.PARSE_IS_SYSTEM_DIR; 1704 } else if (FileUtils.contains(oemAppDir, scanFile)) { 1705 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1706 | PackageParser.PARSE_IS_SYSTEM_DIR; 1707 } else { 1708 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 1709 continue; 1710 } 1711 1712 mSettings.enableSystemPackageLPw(packageName); 1713 1714 try { 1715 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 1716 } catch (PackageManagerException e) { 1717 Slog.e(TAG, "Failed to parse original system package: " 1718 + e.getMessage()); 1719 } 1720 } 1721 } 1722 } 1723 1724 // Now that we know all of the shared libraries, update all clients to have 1725 // the correct library paths. 1726 updateAllSharedLibrariesLPw(); 1727 1728 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1729 // NOTE: We ignore potential failures here during a system scan (like 1730 // the rest of the commands above) because there's precious little we 1731 // can do about it. A settings error is reported, though. 1732 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1733 false /* force dexopt */, false /* defer dexopt */); 1734 } 1735 1736 // Now that we know all the packages we are keeping, 1737 // read and update their last usage times. 1738 mPackageUsage.readLP(); 1739 1740 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1741 SystemClock.uptimeMillis()); 1742 Slog.i(TAG, "Time to scan packages: " 1743 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1744 + " seconds"); 1745 1746 // If the platform SDK has changed since the last time we booted, 1747 // we need to re-grant app permission to catch any new ones that 1748 // appear. This is really a hack, and means that apps can in some 1749 // cases get permissions that the user didn't initially explicitly 1750 // allow... it would be nice to have some better way to handle 1751 // this situation. 1752 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1753 != mSdkVersion; 1754 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1755 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1756 + "; regranting permissions for internal storage"); 1757 mSettings.mInternalSdkPlatform = mSdkVersion; 1758 1759 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1760 | (regrantPermissions 1761 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1762 : 0)); 1763 1764 // If this is the first boot, and it is a normal boot, then 1765 // we need to initialize the default preferred apps. 1766 if (!mRestoredSettings && !onlyCore) { 1767 mSettings.readDefaultPreferredAppsLPw(this, 0); 1768 } 1769 1770 // If this is first boot after an OTA, and a normal boot, then 1771 // we need to clear code cache directories. 1772 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 1773 if (mIsUpgrade && !onlyCore) { 1774 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1775 for (String pkgName : mSettings.mPackages.keySet()) { 1776 deleteCodeCacheDirsLI(pkgName); 1777 } 1778 mSettings.mFingerprint = Build.FINGERPRINT; 1779 } 1780 1781 // All the changes are done during package scanning. 1782 mSettings.updateInternalDatabaseVersion(); 1783 1784 // can downgrade to reader 1785 mSettings.writeLPr(); 1786 1787 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1788 SystemClock.uptimeMillis()); 1789 1790 1791 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1792 } // synchronized (mPackages) 1793 } // synchronized (mInstallLock) 1794 1795 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1796 1797 // Now after opening every single application zip, make sure they 1798 // are all flushed. Not really needed, but keeps things nice and 1799 // tidy. 1800 Runtime.getRuntime().gc(); 1801 } 1802 1803 @Override 1804 public boolean isFirstBoot() { 1805 return !mRestoredSettings; 1806 } 1807 1808 @Override 1809 public boolean isOnlyCoreApps() { 1810 return mOnlyCore; 1811 } 1812 1813 @Override 1814 public boolean isUpgrade() { 1815 return mIsUpgrade; 1816 } 1817 1818 private String getRequiredVerifierLPr() { 1819 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1820 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1821 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1822 1823 String requiredVerifier = null; 1824 1825 final int N = receivers.size(); 1826 for (int i = 0; i < N; i++) { 1827 final ResolveInfo info = receivers.get(i); 1828 1829 if (info.activityInfo == null) { 1830 continue; 1831 } 1832 1833 final String packageName = info.activityInfo.packageName; 1834 1835 final PackageSetting ps = mSettings.mPackages.get(packageName); 1836 if (ps == null) { 1837 continue; 1838 } 1839 1840 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1841 if (!gp.grantedPermissions 1842 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1843 continue; 1844 } 1845 1846 if (requiredVerifier != null) { 1847 throw new RuntimeException("There can be only one required verifier"); 1848 } 1849 1850 requiredVerifier = packageName; 1851 } 1852 1853 return requiredVerifier; 1854 } 1855 1856 @Override 1857 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1858 throws RemoteException { 1859 try { 1860 return super.onTransact(code, data, reply, flags); 1861 } catch (RuntimeException e) { 1862 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1863 Slog.wtf(TAG, "Package Manager Crash", e); 1864 } 1865 throw e; 1866 } 1867 } 1868 1869 void cleanupInstallFailedPackage(PackageSetting ps) { 1870 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1871 1872 removeDataDirsLI(ps.name); 1873 if (ps.codePath != null) { 1874 if (ps.codePath.isDirectory()) { 1875 FileUtils.deleteContents(ps.codePath); 1876 } 1877 ps.codePath.delete(); 1878 } 1879 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1880 if (ps.resourcePath.isDirectory()) { 1881 FileUtils.deleteContents(ps.resourcePath); 1882 } 1883 ps.resourcePath.delete(); 1884 } 1885 mSettings.removePackageLPw(ps.name); 1886 } 1887 1888 static int[] appendInts(int[] cur, int[] add) { 1889 if (add == null) return cur; 1890 if (cur == null) return add; 1891 final int N = add.length; 1892 for (int i=0; i<N; i++) { 1893 cur = appendInt(cur, add[i]); 1894 } 1895 return cur; 1896 } 1897 1898 static int[] removeInts(int[] cur, int[] rem) { 1899 if (rem == null) return cur; 1900 if (cur == null) return cur; 1901 final int N = rem.length; 1902 for (int i=0; i<N; i++) { 1903 cur = removeInt(cur, rem[i]); 1904 } 1905 return cur; 1906 } 1907 1908 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1909 if (!sUserManager.exists(userId)) return null; 1910 final PackageSetting ps = (PackageSetting) p.mExtras; 1911 if (ps == null) { 1912 return null; 1913 } 1914 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1915 final PackageUserState state = ps.readUserState(userId); 1916 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1917 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1918 state, userId); 1919 } 1920 1921 @Override 1922 public boolean isPackageAvailable(String packageName, int userId) { 1923 if (!sUserManager.exists(userId)) return false; 1924 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1925 synchronized (mPackages) { 1926 PackageParser.Package p = mPackages.get(packageName); 1927 if (p != null) { 1928 final PackageSetting ps = (PackageSetting) p.mExtras; 1929 if (ps != null) { 1930 final PackageUserState state = ps.readUserState(userId); 1931 if (state != null) { 1932 return PackageParser.isAvailable(state); 1933 } 1934 } 1935 } 1936 } 1937 return false; 1938 } 1939 1940 @Override 1941 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1942 if (!sUserManager.exists(userId)) return null; 1943 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1944 // reader 1945 synchronized (mPackages) { 1946 PackageParser.Package p = mPackages.get(packageName); 1947 if (DEBUG_PACKAGE_INFO) 1948 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1949 if (p != null) { 1950 return generatePackageInfo(p, flags, userId); 1951 } 1952 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1953 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1954 } 1955 } 1956 return null; 1957 } 1958 1959 @Override 1960 public String[] currentToCanonicalPackageNames(String[] names) { 1961 String[] out = new String[names.length]; 1962 // reader 1963 synchronized (mPackages) { 1964 for (int i=names.length-1; i>=0; i--) { 1965 PackageSetting ps = mSettings.mPackages.get(names[i]); 1966 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1967 } 1968 } 1969 return out; 1970 } 1971 1972 @Override 1973 public String[] canonicalToCurrentPackageNames(String[] names) { 1974 String[] out = new String[names.length]; 1975 // reader 1976 synchronized (mPackages) { 1977 for (int i=names.length-1; i>=0; i--) { 1978 String cur = mSettings.mRenamedPackages.get(names[i]); 1979 out[i] = cur != null ? cur : names[i]; 1980 } 1981 } 1982 return out; 1983 } 1984 1985 @Override 1986 public int getPackageUid(String packageName, int userId) { 1987 if (!sUserManager.exists(userId)) return -1; 1988 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1989 // reader 1990 synchronized (mPackages) { 1991 PackageParser.Package p = mPackages.get(packageName); 1992 if(p != null) { 1993 return UserHandle.getUid(userId, p.applicationInfo.uid); 1994 } 1995 PackageSetting ps = mSettings.mPackages.get(packageName); 1996 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1997 return -1; 1998 } 1999 p = ps.pkg; 2000 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2001 } 2002 } 2003 2004 @Override 2005 public int[] getPackageGids(String packageName) { 2006 // reader 2007 synchronized (mPackages) { 2008 PackageParser.Package p = mPackages.get(packageName); 2009 if (DEBUG_PACKAGE_INFO) 2010 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2011 if (p != null) { 2012 final PackageSetting ps = (PackageSetting)p.mExtras; 2013 return ps.getGids(); 2014 } 2015 } 2016 // stupid thing to indicate an error. 2017 return new int[0]; 2018 } 2019 2020 static final PermissionInfo generatePermissionInfo( 2021 BasePermission bp, int flags) { 2022 if (bp.perm != null) { 2023 return PackageParser.generatePermissionInfo(bp.perm, flags); 2024 } 2025 PermissionInfo pi = new PermissionInfo(); 2026 pi.name = bp.name; 2027 pi.packageName = bp.sourcePackage; 2028 pi.nonLocalizedLabel = bp.name; 2029 pi.protectionLevel = bp.protectionLevel; 2030 return pi; 2031 } 2032 2033 @Override 2034 public PermissionInfo getPermissionInfo(String name, int flags) { 2035 // reader 2036 synchronized (mPackages) { 2037 final BasePermission p = mSettings.mPermissions.get(name); 2038 if (p != null) { 2039 return generatePermissionInfo(p, flags); 2040 } 2041 return null; 2042 } 2043 } 2044 2045 @Override 2046 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2047 // reader 2048 synchronized (mPackages) { 2049 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2050 for (BasePermission p : mSettings.mPermissions.values()) { 2051 if (group == null) { 2052 if (p.perm == null || p.perm.info.group == null) { 2053 out.add(generatePermissionInfo(p, flags)); 2054 } 2055 } else { 2056 if (p.perm != null && group.equals(p.perm.info.group)) { 2057 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2058 } 2059 } 2060 } 2061 2062 if (out.size() > 0) { 2063 return out; 2064 } 2065 return mPermissionGroups.containsKey(group) ? out : null; 2066 } 2067 } 2068 2069 @Override 2070 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2071 // reader 2072 synchronized (mPackages) { 2073 return PackageParser.generatePermissionGroupInfo( 2074 mPermissionGroups.get(name), flags); 2075 } 2076 } 2077 2078 @Override 2079 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2080 // reader 2081 synchronized (mPackages) { 2082 final int N = mPermissionGroups.size(); 2083 ArrayList<PermissionGroupInfo> out 2084 = new ArrayList<PermissionGroupInfo>(N); 2085 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2086 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2087 } 2088 return out; 2089 } 2090 } 2091 2092 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2093 int userId) { 2094 if (!sUserManager.exists(userId)) return null; 2095 PackageSetting ps = mSettings.mPackages.get(packageName); 2096 if (ps != null) { 2097 if (ps.pkg == null) { 2098 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2099 flags, userId); 2100 if (pInfo != null) { 2101 return pInfo.applicationInfo; 2102 } 2103 return null; 2104 } 2105 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2106 ps.readUserState(userId), userId); 2107 } 2108 return null; 2109 } 2110 2111 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2112 int userId) { 2113 if (!sUserManager.exists(userId)) return null; 2114 PackageSetting ps = mSettings.mPackages.get(packageName); 2115 if (ps != null) { 2116 PackageParser.Package pkg = ps.pkg; 2117 if (pkg == null) { 2118 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2119 return null; 2120 } 2121 // Only data remains, so we aren't worried about code paths 2122 pkg = new PackageParser.Package(packageName); 2123 pkg.applicationInfo.packageName = packageName; 2124 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2125 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2126 pkg.applicationInfo.dataDir = 2127 getDataPathForPackage(packageName, 0).getPath(); 2128 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2129 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2130 } 2131 return generatePackageInfo(pkg, flags, userId); 2132 } 2133 return null; 2134 } 2135 2136 @Override 2137 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2138 if (!sUserManager.exists(userId)) return null; 2139 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2140 // writer 2141 synchronized (mPackages) { 2142 PackageParser.Package p = mPackages.get(packageName); 2143 if (DEBUG_PACKAGE_INFO) Log.v( 2144 TAG, "getApplicationInfo " + packageName 2145 + ": " + p); 2146 if (p != null) { 2147 PackageSetting ps = mSettings.mPackages.get(packageName); 2148 if (ps == null) return null; 2149 // Note: isEnabledLP() does not apply here - always return info 2150 return PackageParser.generateApplicationInfo( 2151 p, flags, ps.readUserState(userId), userId); 2152 } 2153 if ("android".equals(packageName)||"system".equals(packageName)) { 2154 return mAndroidApplication; 2155 } 2156 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2157 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2158 } 2159 } 2160 return null; 2161 } 2162 2163 2164 @Override 2165 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2166 mContext.enforceCallingOrSelfPermission( 2167 android.Manifest.permission.CLEAR_APP_CACHE, null); 2168 // Queue up an async operation since clearing cache may take a little while. 2169 mHandler.post(new Runnable() { 2170 public void run() { 2171 mHandler.removeCallbacks(this); 2172 int retCode = -1; 2173 synchronized (mInstallLock) { 2174 retCode = mInstaller.freeCache(freeStorageSize); 2175 if (retCode < 0) { 2176 Slog.w(TAG, "Couldn't clear application caches"); 2177 } 2178 } 2179 if (observer != null) { 2180 try { 2181 observer.onRemoveCompleted(null, (retCode >= 0)); 2182 } catch (RemoteException e) { 2183 Slog.w(TAG, "RemoveException when invoking call back"); 2184 } 2185 } 2186 } 2187 }); 2188 } 2189 2190 @Override 2191 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2192 mContext.enforceCallingOrSelfPermission( 2193 android.Manifest.permission.CLEAR_APP_CACHE, null); 2194 // Queue up an async operation since clearing cache may take a little while. 2195 mHandler.post(new Runnable() { 2196 public void run() { 2197 mHandler.removeCallbacks(this); 2198 int retCode = -1; 2199 synchronized (mInstallLock) { 2200 retCode = mInstaller.freeCache(freeStorageSize); 2201 if (retCode < 0) { 2202 Slog.w(TAG, "Couldn't clear application caches"); 2203 } 2204 } 2205 if(pi != null) { 2206 try { 2207 // Callback via pending intent 2208 int code = (retCode >= 0) ? 1 : 0; 2209 pi.sendIntent(null, code, null, 2210 null, null); 2211 } catch (SendIntentException e1) { 2212 Slog.i(TAG, "Failed to send pending intent"); 2213 } 2214 } 2215 } 2216 }); 2217 } 2218 2219 void freeStorage(long freeStorageSize) throws IOException { 2220 synchronized (mInstallLock) { 2221 if (mInstaller.freeCache(freeStorageSize) < 0) { 2222 throw new IOException("Failed to free enough space"); 2223 } 2224 } 2225 } 2226 2227 @Override 2228 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2229 if (!sUserManager.exists(userId)) return null; 2230 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2231 synchronized (mPackages) { 2232 PackageParser.Activity a = mActivities.mActivities.get(component); 2233 2234 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2235 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2236 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2237 if (ps == null) return null; 2238 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2239 userId); 2240 } 2241 if (mResolveComponentName.equals(component)) { 2242 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2243 new PackageUserState(), userId); 2244 } 2245 } 2246 return null; 2247 } 2248 2249 @Override 2250 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2251 String resolvedType) { 2252 synchronized (mPackages) { 2253 PackageParser.Activity a = mActivities.mActivities.get(component); 2254 if (a == null) { 2255 return false; 2256 } 2257 for (int i=0; i<a.intents.size(); i++) { 2258 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2259 intent.getData(), intent.getCategories(), TAG) >= 0) { 2260 return true; 2261 } 2262 } 2263 return false; 2264 } 2265 } 2266 2267 @Override 2268 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2269 if (!sUserManager.exists(userId)) return null; 2270 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2271 synchronized (mPackages) { 2272 PackageParser.Activity a = mReceivers.mActivities.get(component); 2273 if (DEBUG_PACKAGE_INFO) Log.v( 2274 TAG, "getReceiverInfo " + component + ": " + a); 2275 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2276 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2277 if (ps == null) return null; 2278 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2279 userId); 2280 } 2281 } 2282 return null; 2283 } 2284 2285 @Override 2286 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2287 if (!sUserManager.exists(userId)) return null; 2288 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2289 synchronized (mPackages) { 2290 PackageParser.Service s = mServices.mServices.get(component); 2291 if (DEBUG_PACKAGE_INFO) Log.v( 2292 TAG, "getServiceInfo " + component + ": " + s); 2293 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2294 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2295 if (ps == null) return null; 2296 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2297 userId); 2298 } 2299 } 2300 return null; 2301 } 2302 2303 @Override 2304 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2305 if (!sUserManager.exists(userId)) return null; 2306 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2307 synchronized (mPackages) { 2308 PackageParser.Provider p = mProviders.mProviders.get(component); 2309 if (DEBUG_PACKAGE_INFO) Log.v( 2310 TAG, "getProviderInfo " + component + ": " + p); 2311 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2312 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2313 if (ps == null) return null; 2314 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2315 userId); 2316 } 2317 } 2318 return null; 2319 } 2320 2321 @Override 2322 public String[] getSystemSharedLibraryNames() { 2323 Set<String> libSet; 2324 synchronized (mPackages) { 2325 libSet = mSharedLibraries.keySet(); 2326 int size = libSet.size(); 2327 if (size > 0) { 2328 String[] libs = new String[size]; 2329 libSet.toArray(libs); 2330 return libs; 2331 } 2332 } 2333 return null; 2334 } 2335 2336 /** 2337 * @hide 2338 */ 2339 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2340 synchronized (mPackages) { 2341 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2342 if (lib != null && lib.apk != null) { 2343 return mPackages.get(lib.apk); 2344 } 2345 } 2346 return null; 2347 } 2348 2349 @Override 2350 public FeatureInfo[] getSystemAvailableFeatures() { 2351 Collection<FeatureInfo> featSet; 2352 synchronized (mPackages) { 2353 featSet = mAvailableFeatures.values(); 2354 int size = featSet.size(); 2355 if (size > 0) { 2356 FeatureInfo[] features = new FeatureInfo[size+1]; 2357 featSet.toArray(features); 2358 FeatureInfo fi = new FeatureInfo(); 2359 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2360 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2361 features[size] = fi; 2362 return features; 2363 } 2364 } 2365 return null; 2366 } 2367 2368 @Override 2369 public boolean hasSystemFeature(String name) { 2370 synchronized (mPackages) { 2371 return mAvailableFeatures.containsKey(name); 2372 } 2373 } 2374 2375 private void checkValidCaller(int uid, int userId) { 2376 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2377 return; 2378 2379 throw new SecurityException("Caller uid=" + uid 2380 + " is not privileged to communicate with user=" + userId); 2381 } 2382 2383 @Override 2384 public int checkPermission(String permName, String pkgName) { 2385 synchronized (mPackages) { 2386 PackageParser.Package p = mPackages.get(pkgName); 2387 if (p != null && p.mExtras != null) { 2388 PackageSetting ps = (PackageSetting)p.mExtras; 2389 if (ps.sharedUser != null) { 2390 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2391 return PackageManager.PERMISSION_GRANTED; 2392 } 2393 } else if (ps.grantedPermissions.contains(permName)) { 2394 return PackageManager.PERMISSION_GRANTED; 2395 } 2396 } 2397 } 2398 return PackageManager.PERMISSION_DENIED; 2399 } 2400 2401 @Override 2402 public int checkUidPermission(String permName, int uid) { 2403 synchronized (mPackages) { 2404 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2405 if (obj != null) { 2406 GrantedPermissions gp = (GrantedPermissions)obj; 2407 if (gp.grantedPermissions.contains(permName)) { 2408 return PackageManager.PERMISSION_GRANTED; 2409 } 2410 } else { 2411 ArraySet<String> perms = mSystemPermissions.get(uid); 2412 if (perms != null && perms.contains(permName)) { 2413 return PackageManager.PERMISSION_GRANTED; 2414 } 2415 } 2416 } 2417 return PackageManager.PERMISSION_DENIED; 2418 } 2419 2420 /** 2421 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2422 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2423 * @param checkShell TODO(yamasani): 2424 * @param message the message to log on security exception 2425 */ 2426 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2427 boolean checkShell, String message) { 2428 if (userId < 0) { 2429 throw new IllegalArgumentException("Invalid userId " + userId); 2430 } 2431 if (checkShell) { 2432 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2433 } 2434 if (userId == UserHandle.getUserId(callingUid)) return; 2435 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2436 if (requireFullPermission) { 2437 mContext.enforceCallingOrSelfPermission( 2438 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2439 } else { 2440 try { 2441 mContext.enforceCallingOrSelfPermission( 2442 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2443 } catch (SecurityException se) { 2444 mContext.enforceCallingOrSelfPermission( 2445 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2446 } 2447 } 2448 } 2449 } 2450 2451 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2452 if (callingUid == Process.SHELL_UID) { 2453 if (userHandle >= 0 2454 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2455 throw new SecurityException("Shell does not have permission to access user " 2456 + userHandle); 2457 } else if (userHandle < 0) { 2458 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2459 + Debug.getCallers(3)); 2460 } 2461 } 2462 } 2463 2464 private BasePermission findPermissionTreeLP(String permName) { 2465 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2466 if (permName.startsWith(bp.name) && 2467 permName.length() > bp.name.length() && 2468 permName.charAt(bp.name.length()) == '.') { 2469 return bp; 2470 } 2471 } 2472 return null; 2473 } 2474 2475 private BasePermission checkPermissionTreeLP(String permName) { 2476 if (permName != null) { 2477 BasePermission bp = findPermissionTreeLP(permName); 2478 if (bp != null) { 2479 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2480 return bp; 2481 } 2482 throw new SecurityException("Calling uid " 2483 + Binder.getCallingUid() 2484 + " is not allowed to add to permission tree " 2485 + bp.name + " owned by uid " + bp.uid); 2486 } 2487 } 2488 throw new SecurityException("No permission tree found for " + permName); 2489 } 2490 2491 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2492 if (s1 == null) { 2493 return s2 == null; 2494 } 2495 if (s2 == null) { 2496 return false; 2497 } 2498 if (s1.getClass() != s2.getClass()) { 2499 return false; 2500 } 2501 return s1.equals(s2); 2502 } 2503 2504 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2505 if (pi1.icon != pi2.icon) return false; 2506 if (pi1.logo != pi2.logo) return false; 2507 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2508 if (!compareStrings(pi1.name, pi2.name)) return false; 2509 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2510 // We'll take care of setting this one. 2511 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2512 // These are not currently stored in settings. 2513 //if (!compareStrings(pi1.group, pi2.group)) return false; 2514 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2515 //if (pi1.labelRes != pi2.labelRes) return false; 2516 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2517 return true; 2518 } 2519 2520 int permissionInfoFootprint(PermissionInfo info) { 2521 int size = info.name.length(); 2522 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2523 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2524 return size; 2525 } 2526 2527 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2528 int size = 0; 2529 for (BasePermission perm : mSettings.mPermissions.values()) { 2530 if (perm.uid == tree.uid) { 2531 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2532 } 2533 } 2534 return size; 2535 } 2536 2537 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2538 // We calculate the max size of permissions defined by this uid and throw 2539 // if that plus the size of 'info' would exceed our stated maximum. 2540 if (tree.uid != Process.SYSTEM_UID) { 2541 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2542 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2543 throw new SecurityException("Permission tree size cap exceeded"); 2544 } 2545 } 2546 } 2547 2548 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2549 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2550 throw new SecurityException("Label must be specified in permission"); 2551 } 2552 BasePermission tree = checkPermissionTreeLP(info.name); 2553 BasePermission bp = mSettings.mPermissions.get(info.name); 2554 boolean added = bp == null; 2555 boolean changed = true; 2556 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2557 if (added) { 2558 enforcePermissionCapLocked(info, tree); 2559 bp = new BasePermission(info.name, tree.sourcePackage, 2560 BasePermission.TYPE_DYNAMIC); 2561 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2562 throw new SecurityException( 2563 "Not allowed to modify non-dynamic permission " 2564 + info.name); 2565 } else { 2566 if (bp.protectionLevel == fixedLevel 2567 && bp.perm.owner.equals(tree.perm.owner) 2568 && bp.uid == tree.uid 2569 && comparePermissionInfos(bp.perm.info, info)) { 2570 changed = false; 2571 } 2572 } 2573 bp.protectionLevel = fixedLevel; 2574 info = new PermissionInfo(info); 2575 info.protectionLevel = fixedLevel; 2576 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2577 bp.perm.info.packageName = tree.perm.info.packageName; 2578 bp.uid = tree.uid; 2579 if (added) { 2580 mSettings.mPermissions.put(info.name, bp); 2581 } 2582 if (changed) { 2583 if (!async) { 2584 mSettings.writeLPr(); 2585 } else { 2586 scheduleWriteSettingsLocked(); 2587 } 2588 } 2589 return added; 2590 } 2591 2592 @Override 2593 public boolean addPermission(PermissionInfo info) { 2594 synchronized (mPackages) { 2595 return addPermissionLocked(info, false); 2596 } 2597 } 2598 2599 @Override 2600 public boolean addPermissionAsync(PermissionInfo info) { 2601 synchronized (mPackages) { 2602 return addPermissionLocked(info, true); 2603 } 2604 } 2605 2606 @Override 2607 public void removePermission(String name) { 2608 synchronized (mPackages) { 2609 checkPermissionTreeLP(name); 2610 BasePermission bp = mSettings.mPermissions.get(name); 2611 if (bp != null) { 2612 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2613 throw new SecurityException( 2614 "Not allowed to modify non-dynamic permission " 2615 + name); 2616 } 2617 mSettings.mPermissions.remove(name); 2618 mSettings.writeLPr(); 2619 } 2620 } 2621 } 2622 2623 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2624 int index = pkg.requestedPermissions.indexOf(bp.name); 2625 if (index == -1) { 2626 throw new SecurityException("Package " + pkg.packageName 2627 + " has not requested permission " + bp.name); 2628 } 2629 boolean isNormal = 2630 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2631 == PermissionInfo.PROTECTION_NORMAL); 2632 boolean isDangerous = 2633 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2634 == PermissionInfo.PROTECTION_DANGEROUS); 2635 boolean isDevelopment = 2636 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2637 2638 if (!isNormal && !isDangerous && !isDevelopment) { 2639 throw new SecurityException("Permission " + bp.name 2640 + " is not a changeable permission type"); 2641 } 2642 2643 if (isNormal || isDangerous) { 2644 if (pkg.requestedPermissionsRequired.get(index)) { 2645 throw new SecurityException("Can't change " + bp.name 2646 + ". It is required by the application"); 2647 } 2648 } 2649 } 2650 2651 @Override 2652 public void grantPermission(String packageName, String permissionName) { 2653 mContext.enforceCallingOrSelfPermission( 2654 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2655 synchronized (mPackages) { 2656 final PackageParser.Package pkg = mPackages.get(packageName); 2657 if (pkg == null) { 2658 throw new IllegalArgumentException("Unknown package: " + packageName); 2659 } 2660 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2661 if (bp == null) { 2662 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2663 } 2664 2665 checkGrantRevokePermissions(pkg, bp); 2666 2667 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2668 if (ps == null) { 2669 return; 2670 } 2671 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2672 if (gp.grantedPermissions.add(permissionName)) { 2673 if (ps.haveGids) { 2674 gp.gids = appendInts(gp.gids, bp.gids); 2675 } 2676 mSettings.writeLPr(); 2677 } 2678 } 2679 } 2680 2681 @Override 2682 public void revokePermission(String packageName, String permissionName) { 2683 int changedAppId = -1; 2684 2685 synchronized (mPackages) { 2686 final PackageParser.Package pkg = mPackages.get(packageName); 2687 if (pkg == null) { 2688 throw new IllegalArgumentException("Unknown package: " + packageName); 2689 } 2690 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2691 mContext.enforceCallingOrSelfPermission( 2692 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2693 } 2694 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2695 if (bp == null) { 2696 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2697 } 2698 2699 checkGrantRevokePermissions(pkg, bp); 2700 2701 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2702 if (ps == null) { 2703 return; 2704 } 2705 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2706 if (gp.grantedPermissions.remove(permissionName)) { 2707 gp.grantedPermissions.remove(permissionName); 2708 if (ps.haveGids) { 2709 gp.gids = removeInts(gp.gids, bp.gids); 2710 } 2711 mSettings.writeLPr(); 2712 changedAppId = ps.appId; 2713 } 2714 } 2715 2716 if (changedAppId >= 0) { 2717 // We changed the perm on someone, kill its processes. 2718 IActivityManager am = ActivityManagerNative.getDefault(); 2719 if (am != null) { 2720 final int callingUserId = UserHandle.getCallingUserId(); 2721 final long ident = Binder.clearCallingIdentity(); 2722 try { 2723 //XXX we should only revoke for the calling user's app permissions, 2724 // but for now we impact all users. 2725 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2726 // "revoke " + permissionName); 2727 int[] users = sUserManager.getUserIds(); 2728 for (int user : users) { 2729 am.killUid(UserHandle.getUid(user, changedAppId), 2730 "revoke " + permissionName); 2731 } 2732 } catch (RemoteException e) { 2733 } finally { 2734 Binder.restoreCallingIdentity(ident); 2735 } 2736 } 2737 } 2738 } 2739 2740 @Override 2741 public boolean isProtectedBroadcast(String actionName) { 2742 synchronized (mPackages) { 2743 return mProtectedBroadcasts.contains(actionName); 2744 } 2745 } 2746 2747 @Override 2748 public int checkSignatures(String pkg1, String pkg2) { 2749 synchronized (mPackages) { 2750 final PackageParser.Package p1 = mPackages.get(pkg1); 2751 final PackageParser.Package p2 = mPackages.get(pkg2); 2752 if (p1 == null || p1.mExtras == null 2753 || p2 == null || p2.mExtras == null) { 2754 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2755 } 2756 return compareSignatures(p1.mSignatures, p2.mSignatures); 2757 } 2758 } 2759 2760 @Override 2761 public int checkUidSignatures(int uid1, int uid2) { 2762 // Map to base uids. 2763 uid1 = UserHandle.getAppId(uid1); 2764 uid2 = UserHandle.getAppId(uid2); 2765 // reader 2766 synchronized (mPackages) { 2767 Signature[] s1; 2768 Signature[] s2; 2769 Object obj = mSettings.getUserIdLPr(uid1); 2770 if (obj != null) { 2771 if (obj instanceof SharedUserSetting) { 2772 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2773 } else if (obj instanceof PackageSetting) { 2774 s1 = ((PackageSetting)obj).signatures.mSignatures; 2775 } else { 2776 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2777 } 2778 } else { 2779 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2780 } 2781 obj = mSettings.getUserIdLPr(uid2); 2782 if (obj != null) { 2783 if (obj instanceof SharedUserSetting) { 2784 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2785 } else if (obj instanceof PackageSetting) { 2786 s2 = ((PackageSetting)obj).signatures.mSignatures; 2787 } else { 2788 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2789 } 2790 } else { 2791 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2792 } 2793 return compareSignatures(s1, s2); 2794 } 2795 } 2796 2797 /** 2798 * Compares two sets of signatures. Returns: 2799 * <br /> 2800 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2801 * <br /> 2802 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2803 * <br /> 2804 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2805 * <br /> 2806 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2807 * <br /> 2808 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2809 */ 2810 static int compareSignatures(Signature[] s1, Signature[] s2) { 2811 if (s1 == null) { 2812 return s2 == null 2813 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2814 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2815 } 2816 2817 if (s2 == null) { 2818 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2819 } 2820 2821 if (s1.length != s2.length) { 2822 return PackageManager.SIGNATURE_NO_MATCH; 2823 } 2824 2825 // Since both signature sets are of size 1, we can compare without HashSets. 2826 if (s1.length == 1) { 2827 return s1[0].equals(s2[0]) ? 2828 PackageManager.SIGNATURE_MATCH : 2829 PackageManager.SIGNATURE_NO_MATCH; 2830 } 2831 2832 ArraySet<Signature> set1 = new ArraySet<Signature>(); 2833 for (Signature sig : s1) { 2834 set1.add(sig); 2835 } 2836 ArraySet<Signature> set2 = new ArraySet<Signature>(); 2837 for (Signature sig : s2) { 2838 set2.add(sig); 2839 } 2840 // Make sure s2 contains all signatures in s1. 2841 if (set1.equals(set2)) { 2842 return PackageManager.SIGNATURE_MATCH; 2843 } 2844 return PackageManager.SIGNATURE_NO_MATCH; 2845 } 2846 2847 /** 2848 * If the database version for this type of package (internal storage or 2849 * external storage) is less than the version where package signatures 2850 * were updated, return true. 2851 */ 2852 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2853 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2854 DatabaseVersion.SIGNATURE_END_ENTITY)) 2855 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2856 DatabaseVersion.SIGNATURE_END_ENTITY)); 2857 } 2858 2859 /** 2860 * Used for backward compatibility to make sure any packages with 2861 * certificate chains get upgraded to the new style. {@code existingSigs} 2862 * will be in the old format (since they were stored on disk from before the 2863 * system upgrade) and {@code scannedSigs} will be in the newer format. 2864 */ 2865 private int compareSignaturesCompat(PackageSignatures existingSigs, 2866 PackageParser.Package scannedPkg) { 2867 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2868 return PackageManager.SIGNATURE_NO_MATCH; 2869 } 2870 2871 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 2872 for (Signature sig : existingSigs.mSignatures) { 2873 existingSet.add(sig); 2874 } 2875 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 2876 for (Signature sig : scannedPkg.mSignatures) { 2877 try { 2878 Signature[] chainSignatures = sig.getChainSignatures(); 2879 for (Signature chainSig : chainSignatures) { 2880 scannedCompatSet.add(chainSig); 2881 } 2882 } catch (CertificateEncodingException e) { 2883 scannedCompatSet.add(sig); 2884 } 2885 } 2886 /* 2887 * Make sure the expanded scanned set contains all signatures in the 2888 * existing one. 2889 */ 2890 if (scannedCompatSet.equals(existingSet)) { 2891 // Migrate the old signatures to the new scheme. 2892 existingSigs.assignSignatures(scannedPkg.mSignatures); 2893 // The new KeySets will be re-added later in the scanning process. 2894 synchronized (mPackages) { 2895 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2896 } 2897 return PackageManager.SIGNATURE_MATCH; 2898 } 2899 return PackageManager.SIGNATURE_NO_MATCH; 2900 } 2901 2902 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2903 if (isExternal(scannedPkg)) { 2904 return mSettings.isExternalDatabaseVersionOlderThan( 2905 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2906 } else { 2907 return mSettings.isInternalDatabaseVersionOlderThan( 2908 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2909 } 2910 } 2911 2912 private int compareSignaturesRecover(PackageSignatures existingSigs, 2913 PackageParser.Package scannedPkg) { 2914 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 2915 return PackageManager.SIGNATURE_NO_MATCH; 2916 } 2917 2918 String msg = null; 2919 try { 2920 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 2921 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 2922 + scannedPkg.packageName); 2923 return PackageManager.SIGNATURE_MATCH; 2924 } 2925 } catch (CertificateException e) { 2926 msg = e.getMessage(); 2927 } 2928 2929 logCriticalInfo(Log.INFO, 2930 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 2931 return PackageManager.SIGNATURE_NO_MATCH; 2932 } 2933 2934 @Override 2935 public String[] getPackagesForUid(int uid) { 2936 uid = UserHandle.getAppId(uid); 2937 // reader 2938 synchronized (mPackages) { 2939 Object obj = mSettings.getUserIdLPr(uid); 2940 if (obj instanceof SharedUserSetting) { 2941 final SharedUserSetting sus = (SharedUserSetting) obj; 2942 final int N = sus.packages.size(); 2943 final String[] res = new String[N]; 2944 final Iterator<PackageSetting> it = sus.packages.iterator(); 2945 int i = 0; 2946 while (it.hasNext()) { 2947 res[i++] = it.next().name; 2948 } 2949 return res; 2950 } else if (obj instanceof PackageSetting) { 2951 final PackageSetting ps = (PackageSetting) obj; 2952 return new String[] { ps.name }; 2953 } 2954 } 2955 return null; 2956 } 2957 2958 @Override 2959 public String getNameForUid(int uid) { 2960 // reader 2961 synchronized (mPackages) { 2962 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2963 if (obj instanceof SharedUserSetting) { 2964 final SharedUserSetting sus = (SharedUserSetting) obj; 2965 return sus.name + ":" + sus.userId; 2966 } else if (obj instanceof PackageSetting) { 2967 final PackageSetting ps = (PackageSetting) obj; 2968 return ps.name; 2969 } 2970 } 2971 return null; 2972 } 2973 2974 @Override 2975 public int getUidForSharedUser(String sharedUserName) { 2976 if(sharedUserName == null) { 2977 return -1; 2978 } 2979 // reader 2980 synchronized (mPackages) { 2981 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 2982 if (suid == null) { 2983 return -1; 2984 } 2985 return suid.userId; 2986 } 2987 } 2988 2989 @Override 2990 public int getFlagsForUid(int uid) { 2991 synchronized (mPackages) { 2992 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2993 if (obj instanceof SharedUserSetting) { 2994 final SharedUserSetting sus = (SharedUserSetting) obj; 2995 return sus.pkgFlags; 2996 } else if (obj instanceof PackageSetting) { 2997 final PackageSetting ps = (PackageSetting) obj; 2998 return ps.pkgFlags; 2999 } 3000 } 3001 return 0; 3002 } 3003 3004 @Override 3005 public int getPrivateFlagsForUid(int uid) { 3006 synchronized (mPackages) { 3007 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3008 if (obj instanceof SharedUserSetting) { 3009 final SharedUserSetting sus = (SharedUserSetting) obj; 3010 return sus.pkgPrivateFlags; 3011 } else if (obj instanceof PackageSetting) { 3012 final PackageSetting ps = (PackageSetting) obj; 3013 return ps.pkgPrivateFlags; 3014 } 3015 } 3016 return 0; 3017 } 3018 3019 @Override 3020 public boolean isUidPrivileged(int uid) { 3021 uid = UserHandle.getAppId(uid); 3022 // reader 3023 synchronized (mPackages) { 3024 Object obj = mSettings.getUserIdLPr(uid); 3025 if (obj instanceof SharedUserSetting) { 3026 final SharedUserSetting sus = (SharedUserSetting) obj; 3027 final Iterator<PackageSetting> it = sus.packages.iterator(); 3028 while (it.hasNext()) { 3029 if (it.next().isPrivileged()) { 3030 return true; 3031 } 3032 } 3033 } else if (obj instanceof PackageSetting) { 3034 final PackageSetting ps = (PackageSetting) obj; 3035 return ps.isPrivileged(); 3036 } 3037 } 3038 return false; 3039 } 3040 3041 @Override 3042 public String[] getAppOpPermissionPackages(String permissionName) { 3043 synchronized (mPackages) { 3044 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3045 if (pkgs == null) { 3046 return null; 3047 } 3048 return pkgs.toArray(new String[pkgs.size()]); 3049 } 3050 } 3051 3052 @Override 3053 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3054 int flags, int userId) { 3055 if (!sUserManager.exists(userId)) return null; 3056 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3057 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3058 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3059 } 3060 3061 @Override 3062 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3063 IntentFilter filter, int match, ComponentName activity) { 3064 final int userId = UserHandle.getCallingUserId(); 3065 if (DEBUG_PREFERRED) { 3066 Log.v(TAG, "setLastChosenActivity intent=" + intent 3067 + " resolvedType=" + resolvedType 3068 + " flags=" + flags 3069 + " filter=" + filter 3070 + " match=" + match 3071 + " activity=" + activity); 3072 filter.dump(new PrintStreamPrinter(System.out), " "); 3073 } 3074 intent.setComponent(null); 3075 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3076 // Find any earlier preferred or last chosen entries and nuke them 3077 findPreferredActivity(intent, resolvedType, 3078 flags, query, 0, false, true, false, userId); 3079 // Add the new activity as the last chosen for this filter 3080 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3081 "Setting last chosen"); 3082 } 3083 3084 @Override 3085 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3086 final int userId = UserHandle.getCallingUserId(); 3087 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3088 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3089 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3090 false, false, false, userId); 3091 } 3092 3093 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3094 int flags, List<ResolveInfo> query, int userId) { 3095 if (query != null) { 3096 final int N = query.size(); 3097 if (N == 1) { 3098 return query.get(0); 3099 } else if (N > 1) { 3100 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3101 // If there is more than one activity with the same priority, 3102 // then let the user decide between them. 3103 ResolveInfo r0 = query.get(0); 3104 ResolveInfo r1 = query.get(1); 3105 if (DEBUG_INTENT_MATCHING || debug) { 3106 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3107 + r1.activityInfo.name + "=" + r1.priority); 3108 } 3109 // If the first activity has a higher priority, or a different 3110 // default, then it is always desireable to pick it. 3111 if (r0.priority != r1.priority 3112 || r0.preferredOrder != r1.preferredOrder 3113 || r0.isDefault != r1.isDefault) { 3114 return query.get(0); 3115 } 3116 // If we have saved a preference for a preferred activity for 3117 // this Intent, use that. 3118 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3119 flags, query, r0.priority, true, false, debug, userId); 3120 if (ri != null) { 3121 return ri; 3122 } 3123 if (userId != 0) { 3124 ri = new ResolveInfo(mResolveInfo); 3125 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3126 ri.activityInfo.applicationInfo = new ApplicationInfo( 3127 ri.activityInfo.applicationInfo); 3128 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3129 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3130 return ri; 3131 } 3132 return mResolveInfo; 3133 } 3134 } 3135 return null; 3136 } 3137 3138 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3139 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3140 final int N = query.size(); 3141 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3142 .get(userId); 3143 // Get the list of persistent preferred activities that handle the intent 3144 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3145 List<PersistentPreferredActivity> pprefs = ppir != null 3146 ? ppir.queryIntent(intent, resolvedType, 3147 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3148 : null; 3149 if (pprefs != null && pprefs.size() > 0) { 3150 final int M = pprefs.size(); 3151 for (int i=0; i<M; i++) { 3152 final PersistentPreferredActivity ppa = pprefs.get(i); 3153 if (DEBUG_PREFERRED || debug) { 3154 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3155 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3156 + "\n component=" + ppa.mComponent); 3157 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3158 } 3159 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3160 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3161 if (DEBUG_PREFERRED || debug) { 3162 Slog.v(TAG, "Found persistent preferred activity:"); 3163 if (ai != null) { 3164 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3165 } else { 3166 Slog.v(TAG, " null"); 3167 } 3168 } 3169 if (ai == null) { 3170 // This previously registered persistent preferred activity 3171 // component is no longer known. Ignore it and do NOT remove it. 3172 continue; 3173 } 3174 for (int j=0; j<N; j++) { 3175 final ResolveInfo ri = query.get(j); 3176 if (!ri.activityInfo.applicationInfo.packageName 3177 .equals(ai.applicationInfo.packageName)) { 3178 continue; 3179 } 3180 if (!ri.activityInfo.name.equals(ai.name)) { 3181 continue; 3182 } 3183 // Found a persistent preference that can handle the intent. 3184 if (DEBUG_PREFERRED || debug) { 3185 Slog.v(TAG, "Returning persistent preferred activity: " + 3186 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3187 } 3188 return ri; 3189 } 3190 } 3191 } 3192 return null; 3193 } 3194 3195 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3196 List<ResolveInfo> query, int priority, boolean always, 3197 boolean removeMatches, boolean debug, int userId) { 3198 if (!sUserManager.exists(userId)) return null; 3199 // writer 3200 synchronized (mPackages) { 3201 if (intent.getSelector() != null) { 3202 intent = intent.getSelector(); 3203 } 3204 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3205 3206 // Try to find a matching persistent preferred activity. 3207 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3208 debug, userId); 3209 3210 // If a persistent preferred activity matched, use it. 3211 if (pri != null) { 3212 return pri; 3213 } 3214 3215 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3216 // Get the list of preferred activities that handle the intent 3217 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3218 List<PreferredActivity> prefs = pir != null 3219 ? pir.queryIntent(intent, resolvedType, 3220 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3221 : null; 3222 if (prefs != null && prefs.size() > 0) { 3223 boolean changed = false; 3224 try { 3225 // First figure out how good the original match set is. 3226 // We will only allow preferred activities that came 3227 // from the same match quality. 3228 int match = 0; 3229 3230 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3231 3232 final int N = query.size(); 3233 for (int j=0; j<N; j++) { 3234 final ResolveInfo ri = query.get(j); 3235 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3236 + ": 0x" + Integer.toHexString(match)); 3237 if (ri.match > match) { 3238 match = ri.match; 3239 } 3240 } 3241 3242 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3243 + Integer.toHexString(match)); 3244 3245 match &= IntentFilter.MATCH_CATEGORY_MASK; 3246 final int M = prefs.size(); 3247 for (int i=0; i<M; i++) { 3248 final PreferredActivity pa = prefs.get(i); 3249 if (DEBUG_PREFERRED || debug) { 3250 Slog.v(TAG, "Checking PreferredActivity ds=" 3251 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3252 + "\n component=" + pa.mPref.mComponent); 3253 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3254 } 3255 if (pa.mPref.mMatch != match) { 3256 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3257 + Integer.toHexString(pa.mPref.mMatch)); 3258 continue; 3259 } 3260 // If it's not an "always" type preferred activity and that's what we're 3261 // looking for, skip it. 3262 if (always && !pa.mPref.mAlways) { 3263 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3264 continue; 3265 } 3266 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3267 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3268 if (DEBUG_PREFERRED || debug) { 3269 Slog.v(TAG, "Found preferred activity:"); 3270 if (ai != null) { 3271 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3272 } else { 3273 Slog.v(TAG, " null"); 3274 } 3275 } 3276 if (ai == null) { 3277 // This previously registered preferred activity 3278 // component is no longer known. Most likely an update 3279 // to the app was installed and in the new version this 3280 // component no longer exists. Clean it up by removing 3281 // it from the preferred activities list, and skip it. 3282 Slog.w(TAG, "Removing dangling preferred activity: " 3283 + pa.mPref.mComponent); 3284 pir.removeFilter(pa); 3285 changed = true; 3286 continue; 3287 } 3288 for (int j=0; j<N; j++) { 3289 final ResolveInfo ri = query.get(j); 3290 if (!ri.activityInfo.applicationInfo.packageName 3291 .equals(ai.applicationInfo.packageName)) { 3292 continue; 3293 } 3294 if (!ri.activityInfo.name.equals(ai.name)) { 3295 continue; 3296 } 3297 3298 if (removeMatches) { 3299 pir.removeFilter(pa); 3300 changed = true; 3301 if (DEBUG_PREFERRED) { 3302 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3303 } 3304 break; 3305 } 3306 3307 // Okay we found a previously set preferred or last chosen app. 3308 // If the result set is different from when this 3309 // was created, we need to clear it and re-ask the 3310 // user their preference, if we're looking for an "always" type entry. 3311 if (always && !pa.mPref.sameSet(query)) { 3312 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3313 + intent + " type " + resolvedType); 3314 if (DEBUG_PREFERRED) { 3315 Slog.v(TAG, "Removing preferred activity since set changed " 3316 + pa.mPref.mComponent); 3317 } 3318 pir.removeFilter(pa); 3319 // Re-add the filter as a "last chosen" entry (!always) 3320 PreferredActivity lastChosen = new PreferredActivity( 3321 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3322 pir.addFilter(lastChosen); 3323 changed = true; 3324 return null; 3325 } 3326 3327 // Yay! Either the set matched or we're looking for the last chosen 3328 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3329 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3330 return ri; 3331 } 3332 } 3333 } finally { 3334 if (changed) { 3335 if (DEBUG_PREFERRED) { 3336 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3337 } 3338 scheduleWritePackageRestrictionsLocked(userId); 3339 } 3340 } 3341 } 3342 } 3343 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3344 return null; 3345 } 3346 3347 /* 3348 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3349 */ 3350 @Override 3351 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3352 int targetUserId) { 3353 mContext.enforceCallingOrSelfPermission( 3354 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3355 List<CrossProfileIntentFilter> matches = 3356 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3357 if (matches != null) { 3358 int size = matches.size(); 3359 for (int i = 0; i < size; i++) { 3360 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3361 } 3362 } 3363 return false; 3364 } 3365 3366 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3367 String resolvedType, int userId) { 3368 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3369 if (resolver != null) { 3370 return resolver.queryIntent(intent, resolvedType, false, userId); 3371 } 3372 return null; 3373 } 3374 3375 @Override 3376 public List<ResolveInfo> queryIntentActivities(Intent intent, 3377 String resolvedType, int flags, int userId) { 3378 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3379 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3380 ComponentName comp = intent.getComponent(); 3381 if (comp == null) { 3382 if (intent.getSelector() != null) { 3383 intent = intent.getSelector(); 3384 comp = intent.getComponent(); 3385 } 3386 } 3387 3388 if (comp != null) { 3389 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3390 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3391 if (ai != null) { 3392 final ResolveInfo ri = new ResolveInfo(); 3393 ri.activityInfo = ai; 3394 list.add(ri); 3395 } 3396 return list; 3397 } 3398 3399 // reader 3400 synchronized (mPackages) { 3401 final String pkgName = intent.getPackage(); 3402 if (pkgName == null) { 3403 List<CrossProfileIntentFilter> matchingFilters = 3404 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3405 // Check for results that need to skip the current profile. 3406 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3407 resolvedType, flags, userId); 3408 if (resolveInfo != null) { 3409 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3410 result.add(resolveInfo); 3411 return filterIfNotPrimaryUser(result, userId); 3412 } 3413 // Check for cross profile results. 3414 resolveInfo = queryCrossProfileIntents( 3415 matchingFilters, intent, resolvedType, flags, userId); 3416 3417 // Check for results in the current profile. 3418 List<ResolveInfo> result = mActivities.queryIntent( 3419 intent, resolvedType, flags, userId); 3420 if (resolveInfo != null) { 3421 result.add(resolveInfo); 3422 Collections.sort(result, mResolvePrioritySorter); 3423 } 3424 return filterIfNotPrimaryUser(result, userId); 3425 } 3426 final PackageParser.Package pkg = mPackages.get(pkgName); 3427 if (pkg != null) { 3428 return filterIfNotPrimaryUser( 3429 mActivities.queryIntentForPackage( 3430 intent, resolvedType, flags, pkg.activities, userId), 3431 userId); 3432 } 3433 return new ArrayList<ResolveInfo>(); 3434 } 3435 } 3436 3437 /** 3438 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3439 * 3440 * @return filtered list 3441 */ 3442 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3443 if (userId == UserHandle.USER_OWNER) { 3444 return resolveInfos; 3445 } 3446 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 3447 ResolveInfo info = resolveInfos.get(i); 3448 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 3449 resolveInfos.remove(i); 3450 } 3451 } 3452 return resolveInfos; 3453 } 3454 3455 3456 private ResolveInfo querySkipCurrentProfileIntents( 3457 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3458 int flags, int sourceUserId) { 3459 if (matchingFilters != null) { 3460 int size = matchingFilters.size(); 3461 for (int i = 0; i < size; i ++) { 3462 CrossProfileIntentFilter filter = matchingFilters.get(i); 3463 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3464 // Checking if there are activities in the target user that can handle the 3465 // intent. 3466 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3467 flags, sourceUserId); 3468 if (resolveInfo != null) { 3469 return resolveInfo; 3470 } 3471 } 3472 } 3473 } 3474 return null; 3475 } 3476 3477 // Return matching ResolveInfo if any for skip current profile intent filters. 3478 private ResolveInfo queryCrossProfileIntents( 3479 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3480 int flags, int sourceUserId) { 3481 if (matchingFilters != null) { 3482 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3483 // match the same intent. For performance reasons, it is better not to 3484 // run queryIntent twice for the same userId 3485 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3486 int size = matchingFilters.size(); 3487 for (int i = 0; i < size; i++) { 3488 CrossProfileIntentFilter filter = matchingFilters.get(i); 3489 int targetUserId = filter.getTargetUserId(); 3490 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3491 && !alreadyTriedUserIds.get(targetUserId)) { 3492 // Checking if there are activities in the target user that can handle the 3493 // intent. 3494 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3495 flags, sourceUserId); 3496 if (resolveInfo != null) return resolveInfo; 3497 alreadyTriedUserIds.put(targetUserId, true); 3498 } 3499 } 3500 } 3501 return null; 3502 } 3503 3504 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3505 String resolvedType, int flags, int sourceUserId) { 3506 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3507 resolvedType, flags, filter.getTargetUserId()); 3508 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3509 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3510 } 3511 return null; 3512 } 3513 3514 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3515 int sourceUserId, int targetUserId) { 3516 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3517 String className; 3518 if (targetUserId == UserHandle.USER_OWNER) { 3519 className = FORWARD_INTENT_TO_USER_OWNER; 3520 } else { 3521 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3522 } 3523 ComponentName forwardingActivityComponentName = new ComponentName( 3524 mAndroidApplication.packageName, className); 3525 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3526 sourceUserId); 3527 if (targetUserId == UserHandle.USER_OWNER) { 3528 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3529 forwardingResolveInfo.noResourceId = true; 3530 } 3531 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3532 forwardingResolveInfo.priority = 0; 3533 forwardingResolveInfo.preferredOrder = 0; 3534 forwardingResolveInfo.match = 0; 3535 forwardingResolveInfo.isDefault = true; 3536 forwardingResolveInfo.filter = filter; 3537 forwardingResolveInfo.targetUserId = targetUserId; 3538 return forwardingResolveInfo; 3539 } 3540 3541 @Override 3542 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3543 Intent[] specifics, String[] specificTypes, Intent intent, 3544 String resolvedType, int flags, int userId) { 3545 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3546 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3547 false, "query intent activity options"); 3548 final String resultsAction = intent.getAction(); 3549 3550 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3551 | PackageManager.GET_RESOLVED_FILTER, userId); 3552 3553 if (DEBUG_INTENT_MATCHING) { 3554 Log.v(TAG, "Query " + intent + ": " + results); 3555 } 3556 3557 int specificsPos = 0; 3558 int N; 3559 3560 // todo: note that the algorithm used here is O(N^2). This 3561 // isn't a problem in our current environment, but if we start running 3562 // into situations where we have more than 5 or 10 matches then this 3563 // should probably be changed to something smarter... 3564 3565 // First we go through and resolve each of the specific items 3566 // that were supplied, taking care of removing any corresponding 3567 // duplicate items in the generic resolve list. 3568 if (specifics != null) { 3569 for (int i=0; i<specifics.length; i++) { 3570 final Intent sintent = specifics[i]; 3571 if (sintent == null) { 3572 continue; 3573 } 3574 3575 if (DEBUG_INTENT_MATCHING) { 3576 Log.v(TAG, "Specific #" + i + ": " + sintent); 3577 } 3578 3579 String action = sintent.getAction(); 3580 if (resultsAction != null && resultsAction.equals(action)) { 3581 // If this action was explicitly requested, then don't 3582 // remove things that have it. 3583 action = null; 3584 } 3585 3586 ResolveInfo ri = null; 3587 ActivityInfo ai = null; 3588 3589 ComponentName comp = sintent.getComponent(); 3590 if (comp == null) { 3591 ri = resolveIntent( 3592 sintent, 3593 specificTypes != null ? specificTypes[i] : null, 3594 flags, userId); 3595 if (ri == null) { 3596 continue; 3597 } 3598 if (ri == mResolveInfo) { 3599 // ACK! Must do something better with this. 3600 } 3601 ai = ri.activityInfo; 3602 comp = new ComponentName(ai.applicationInfo.packageName, 3603 ai.name); 3604 } else { 3605 ai = getActivityInfo(comp, flags, userId); 3606 if (ai == null) { 3607 continue; 3608 } 3609 } 3610 3611 // Look for any generic query activities that are duplicates 3612 // of this specific one, and remove them from the results. 3613 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3614 N = results.size(); 3615 int j; 3616 for (j=specificsPos; j<N; j++) { 3617 ResolveInfo sri = results.get(j); 3618 if ((sri.activityInfo.name.equals(comp.getClassName()) 3619 && sri.activityInfo.applicationInfo.packageName.equals( 3620 comp.getPackageName())) 3621 || (action != null && sri.filter.matchAction(action))) { 3622 results.remove(j); 3623 if (DEBUG_INTENT_MATCHING) Log.v( 3624 TAG, "Removing duplicate item from " + j 3625 + " due to specific " + specificsPos); 3626 if (ri == null) { 3627 ri = sri; 3628 } 3629 j--; 3630 N--; 3631 } 3632 } 3633 3634 // Add this specific item to its proper place. 3635 if (ri == null) { 3636 ri = new ResolveInfo(); 3637 ri.activityInfo = ai; 3638 } 3639 results.add(specificsPos, ri); 3640 ri.specificIndex = i; 3641 specificsPos++; 3642 } 3643 } 3644 3645 // Now we go through the remaining generic results and remove any 3646 // duplicate actions that are found here. 3647 N = results.size(); 3648 for (int i=specificsPos; i<N-1; i++) { 3649 final ResolveInfo rii = results.get(i); 3650 if (rii.filter == null) { 3651 continue; 3652 } 3653 3654 // Iterate over all of the actions of this result's intent 3655 // filter... typically this should be just one. 3656 final Iterator<String> it = rii.filter.actionsIterator(); 3657 if (it == null) { 3658 continue; 3659 } 3660 while (it.hasNext()) { 3661 final String action = it.next(); 3662 if (resultsAction != null && resultsAction.equals(action)) { 3663 // If this action was explicitly requested, then don't 3664 // remove things that have it. 3665 continue; 3666 } 3667 for (int j=i+1; j<N; j++) { 3668 final ResolveInfo rij = results.get(j); 3669 if (rij.filter != null && rij.filter.hasAction(action)) { 3670 results.remove(j); 3671 if (DEBUG_INTENT_MATCHING) Log.v( 3672 TAG, "Removing duplicate item from " + j 3673 + " due to action " + action + " at " + i); 3674 j--; 3675 N--; 3676 } 3677 } 3678 } 3679 3680 // If the caller didn't request filter information, drop it now 3681 // so we don't have to marshall/unmarshall it. 3682 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3683 rii.filter = null; 3684 } 3685 } 3686 3687 // Filter out the caller activity if so requested. 3688 if (caller != null) { 3689 N = results.size(); 3690 for (int i=0; i<N; i++) { 3691 ActivityInfo ainfo = results.get(i).activityInfo; 3692 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3693 && caller.getClassName().equals(ainfo.name)) { 3694 results.remove(i); 3695 break; 3696 } 3697 } 3698 } 3699 3700 // If the caller didn't request filter information, 3701 // drop them now so we don't have to 3702 // marshall/unmarshall it. 3703 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3704 N = results.size(); 3705 for (int i=0; i<N; i++) { 3706 results.get(i).filter = null; 3707 } 3708 } 3709 3710 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3711 return results; 3712 } 3713 3714 @Override 3715 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3716 int userId) { 3717 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3718 ComponentName comp = intent.getComponent(); 3719 if (comp == null) { 3720 if (intent.getSelector() != null) { 3721 intent = intent.getSelector(); 3722 comp = intent.getComponent(); 3723 } 3724 } 3725 if (comp != null) { 3726 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3727 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3728 if (ai != null) { 3729 ResolveInfo ri = new ResolveInfo(); 3730 ri.activityInfo = ai; 3731 list.add(ri); 3732 } 3733 return list; 3734 } 3735 3736 // reader 3737 synchronized (mPackages) { 3738 String pkgName = intent.getPackage(); 3739 if (pkgName == null) { 3740 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3741 } 3742 final PackageParser.Package pkg = mPackages.get(pkgName); 3743 if (pkg != null) { 3744 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3745 userId); 3746 } 3747 return null; 3748 } 3749 } 3750 3751 @Override 3752 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3753 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3754 if (!sUserManager.exists(userId)) return null; 3755 if (query != null) { 3756 if (query.size() >= 1) { 3757 // If there is more than one service with the same priority, 3758 // just arbitrarily pick the first one. 3759 return query.get(0); 3760 } 3761 } 3762 return null; 3763 } 3764 3765 @Override 3766 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3767 int userId) { 3768 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3769 ComponentName comp = intent.getComponent(); 3770 if (comp == null) { 3771 if (intent.getSelector() != null) { 3772 intent = intent.getSelector(); 3773 comp = intent.getComponent(); 3774 } 3775 } 3776 if (comp != null) { 3777 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3778 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3779 if (si != null) { 3780 final ResolveInfo ri = new ResolveInfo(); 3781 ri.serviceInfo = si; 3782 list.add(ri); 3783 } 3784 return list; 3785 } 3786 3787 // reader 3788 synchronized (mPackages) { 3789 String pkgName = intent.getPackage(); 3790 if (pkgName == null) { 3791 return mServices.queryIntent(intent, resolvedType, flags, userId); 3792 } 3793 final PackageParser.Package pkg = mPackages.get(pkgName); 3794 if (pkg != null) { 3795 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3796 userId); 3797 } 3798 return null; 3799 } 3800 } 3801 3802 @Override 3803 public List<ResolveInfo> queryIntentContentProviders( 3804 Intent intent, String resolvedType, int flags, int userId) { 3805 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3806 ComponentName comp = intent.getComponent(); 3807 if (comp == null) { 3808 if (intent.getSelector() != null) { 3809 intent = intent.getSelector(); 3810 comp = intent.getComponent(); 3811 } 3812 } 3813 if (comp != null) { 3814 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3815 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3816 if (pi != null) { 3817 final ResolveInfo ri = new ResolveInfo(); 3818 ri.providerInfo = pi; 3819 list.add(ri); 3820 } 3821 return list; 3822 } 3823 3824 // reader 3825 synchronized (mPackages) { 3826 String pkgName = intent.getPackage(); 3827 if (pkgName == null) { 3828 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3829 } 3830 final PackageParser.Package pkg = mPackages.get(pkgName); 3831 if (pkg != null) { 3832 return mProviders.queryIntentForPackage( 3833 intent, resolvedType, flags, pkg.providers, userId); 3834 } 3835 return null; 3836 } 3837 } 3838 3839 @Override 3840 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3841 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3842 3843 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3844 3845 // writer 3846 synchronized (mPackages) { 3847 ArrayList<PackageInfo> list; 3848 if (listUninstalled) { 3849 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3850 for (PackageSetting ps : mSettings.mPackages.values()) { 3851 PackageInfo pi; 3852 if (ps.pkg != null) { 3853 pi = generatePackageInfo(ps.pkg, flags, userId); 3854 } else { 3855 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3856 } 3857 if (pi != null) { 3858 list.add(pi); 3859 } 3860 } 3861 } else { 3862 list = new ArrayList<PackageInfo>(mPackages.size()); 3863 for (PackageParser.Package p : mPackages.values()) { 3864 PackageInfo pi = generatePackageInfo(p, flags, userId); 3865 if (pi != null) { 3866 list.add(pi); 3867 } 3868 } 3869 } 3870 3871 return new ParceledListSlice<PackageInfo>(list); 3872 } 3873 } 3874 3875 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3876 String[] permissions, boolean[] tmp, int flags, int userId) { 3877 int numMatch = 0; 3878 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3879 for (int i=0; i<permissions.length; i++) { 3880 if (gp.grantedPermissions.contains(permissions[i])) { 3881 tmp[i] = true; 3882 numMatch++; 3883 } else { 3884 tmp[i] = false; 3885 } 3886 } 3887 if (numMatch == 0) { 3888 return; 3889 } 3890 PackageInfo pi; 3891 if (ps.pkg != null) { 3892 pi = generatePackageInfo(ps.pkg, flags, userId); 3893 } else { 3894 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3895 } 3896 // The above might return null in cases of uninstalled apps or install-state 3897 // skew across users/profiles. 3898 if (pi != null) { 3899 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3900 if (numMatch == permissions.length) { 3901 pi.requestedPermissions = permissions; 3902 } else { 3903 pi.requestedPermissions = new String[numMatch]; 3904 numMatch = 0; 3905 for (int i=0; i<permissions.length; i++) { 3906 if (tmp[i]) { 3907 pi.requestedPermissions[numMatch] = permissions[i]; 3908 numMatch++; 3909 } 3910 } 3911 } 3912 } 3913 list.add(pi); 3914 } 3915 } 3916 3917 @Override 3918 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3919 String[] permissions, 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<PackageInfo> list = new ArrayList<PackageInfo>(); 3926 boolean[] tmpBools = new boolean[permissions.length]; 3927 if (listUninstalled) { 3928 for (PackageSetting ps : mSettings.mPackages.values()) { 3929 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3930 } 3931 } else { 3932 for (PackageParser.Package pkg : mPackages.values()) { 3933 PackageSetting ps = (PackageSetting)pkg.mExtras; 3934 if (ps != null) { 3935 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3936 userId); 3937 } 3938 } 3939 } 3940 3941 return new ParceledListSlice<PackageInfo>(list); 3942 } 3943 } 3944 3945 @Override 3946 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3947 if (!sUserManager.exists(userId)) return null; 3948 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3949 3950 // writer 3951 synchronized (mPackages) { 3952 ArrayList<ApplicationInfo> list; 3953 if (listUninstalled) { 3954 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3955 for (PackageSetting ps : mSettings.mPackages.values()) { 3956 ApplicationInfo ai; 3957 if (ps.pkg != null) { 3958 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3959 ps.readUserState(userId), userId); 3960 } else { 3961 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3962 } 3963 if (ai != null) { 3964 list.add(ai); 3965 } 3966 } 3967 } else { 3968 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3969 for (PackageParser.Package p : mPackages.values()) { 3970 if (p.mExtras != null) { 3971 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3972 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3973 if (ai != null) { 3974 list.add(ai); 3975 } 3976 } 3977 } 3978 } 3979 3980 return new ParceledListSlice<ApplicationInfo>(list); 3981 } 3982 } 3983 3984 public List<ApplicationInfo> getPersistentApplications(int flags) { 3985 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3986 3987 // reader 3988 synchronized (mPackages) { 3989 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3990 final int userId = UserHandle.getCallingUserId(); 3991 while (i.hasNext()) { 3992 final PackageParser.Package p = i.next(); 3993 if (p.applicationInfo != null 3994 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3995 && (!mSafeMode || isSystemApp(p))) { 3996 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3997 if (ps != null) { 3998 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3999 ps.readUserState(userId), userId); 4000 if (ai != null) { 4001 finalList.add(ai); 4002 } 4003 } 4004 } 4005 } 4006 } 4007 4008 return finalList; 4009 } 4010 4011 @Override 4012 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4013 if (!sUserManager.exists(userId)) return null; 4014 // reader 4015 synchronized (mPackages) { 4016 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4017 PackageSetting ps = provider != null 4018 ? mSettings.mPackages.get(provider.owner.packageName) 4019 : null; 4020 return ps != null 4021 && mSettings.isEnabledLPr(provider.info, flags, userId) 4022 && (!mSafeMode || (provider.info.applicationInfo.flags 4023 &ApplicationInfo.FLAG_SYSTEM) != 0) 4024 ? PackageParser.generateProviderInfo(provider, flags, 4025 ps.readUserState(userId), userId) 4026 : null; 4027 } 4028 } 4029 4030 /** 4031 * @deprecated 4032 */ 4033 @Deprecated 4034 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4035 // reader 4036 synchronized (mPackages) { 4037 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4038 .entrySet().iterator(); 4039 final int userId = UserHandle.getCallingUserId(); 4040 while (i.hasNext()) { 4041 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4042 PackageParser.Provider p = entry.getValue(); 4043 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4044 4045 if (ps != null && p.syncable 4046 && (!mSafeMode || (p.info.applicationInfo.flags 4047 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4048 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4049 ps.readUserState(userId), userId); 4050 if (info != null) { 4051 outNames.add(entry.getKey()); 4052 outInfo.add(info); 4053 } 4054 } 4055 } 4056 } 4057 } 4058 4059 @Override 4060 public List<ProviderInfo> queryContentProviders(String processName, 4061 int uid, int flags) { 4062 ArrayList<ProviderInfo> finalList = null; 4063 // reader 4064 synchronized (mPackages) { 4065 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4066 final int userId = processName != null ? 4067 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4068 while (i.hasNext()) { 4069 final PackageParser.Provider p = i.next(); 4070 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4071 if (ps != null && p.info.authority != null 4072 && (processName == null 4073 || (p.info.processName.equals(processName) 4074 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4075 && mSettings.isEnabledLPr(p.info, flags, userId) 4076 && (!mSafeMode 4077 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4078 if (finalList == null) { 4079 finalList = new ArrayList<ProviderInfo>(3); 4080 } 4081 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4082 ps.readUserState(userId), userId); 4083 if (info != null) { 4084 finalList.add(info); 4085 } 4086 } 4087 } 4088 } 4089 4090 if (finalList != null) { 4091 Collections.sort(finalList, mProviderInitOrderSorter); 4092 } 4093 4094 return finalList; 4095 } 4096 4097 @Override 4098 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4099 int flags) { 4100 // reader 4101 synchronized (mPackages) { 4102 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4103 return PackageParser.generateInstrumentationInfo(i, flags); 4104 } 4105 } 4106 4107 @Override 4108 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4109 int flags) { 4110 ArrayList<InstrumentationInfo> finalList = 4111 new ArrayList<InstrumentationInfo>(); 4112 4113 // reader 4114 synchronized (mPackages) { 4115 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4116 while (i.hasNext()) { 4117 final PackageParser.Instrumentation p = i.next(); 4118 if (targetPackage == null 4119 || targetPackage.equals(p.info.targetPackage)) { 4120 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4121 flags); 4122 if (ii != null) { 4123 finalList.add(ii); 4124 } 4125 } 4126 } 4127 } 4128 4129 return finalList; 4130 } 4131 4132 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4133 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4134 if (overlays == null) { 4135 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4136 return; 4137 } 4138 for (PackageParser.Package opkg : overlays.values()) { 4139 // Not much to do if idmap fails: we already logged the error 4140 // and we certainly don't want to abort installation of pkg simply 4141 // because an overlay didn't fit properly. For these reasons, 4142 // ignore the return value of createIdmapForPackagePairLI. 4143 createIdmapForPackagePairLI(pkg, opkg); 4144 } 4145 } 4146 4147 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4148 PackageParser.Package opkg) { 4149 if (!opkg.mTrustedOverlay) { 4150 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4151 opkg.baseCodePath + ": overlay not trusted"); 4152 return false; 4153 } 4154 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4155 if (overlaySet == null) { 4156 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4157 opkg.baseCodePath + " but target package has no known overlays"); 4158 return false; 4159 } 4160 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4161 // TODO: generate idmap for split APKs 4162 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4163 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4164 + opkg.baseCodePath); 4165 return false; 4166 } 4167 PackageParser.Package[] overlayArray = 4168 overlaySet.values().toArray(new PackageParser.Package[0]); 4169 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4170 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4171 return p1.mOverlayPriority - p2.mOverlayPriority; 4172 } 4173 }; 4174 Arrays.sort(overlayArray, cmp); 4175 4176 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4177 int i = 0; 4178 for (PackageParser.Package p : overlayArray) { 4179 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4180 } 4181 return true; 4182 } 4183 4184 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4185 final File[] files = dir.listFiles(); 4186 if (ArrayUtils.isEmpty(files)) { 4187 Log.d(TAG, "No files in app dir " + dir); 4188 return; 4189 } 4190 4191 if (DEBUG_PACKAGE_SCANNING) { 4192 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4193 + " flags=0x" + Integer.toHexString(parseFlags)); 4194 } 4195 4196 for (File file : files) { 4197 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4198 && !PackageInstallerService.isStageName(file.getName()); 4199 if (!isPackage) { 4200 // Ignore entries which are not packages 4201 continue; 4202 } 4203 try { 4204 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4205 scanFlags, currentTime, null); 4206 } catch (PackageManagerException e) { 4207 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4208 4209 // Delete invalid userdata apps 4210 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4211 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4212 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4213 if (file.isDirectory()) { 4214 FileUtils.deleteContents(file); 4215 } 4216 file.delete(); 4217 } 4218 } 4219 } 4220 } 4221 4222 private static File getSettingsProblemFile() { 4223 File dataDir = Environment.getDataDirectory(); 4224 File systemDir = new File(dataDir, "system"); 4225 File fname = new File(systemDir, "uiderrors.txt"); 4226 return fname; 4227 } 4228 4229 static void reportSettingsProblem(int priority, String msg) { 4230 logCriticalInfo(priority, msg); 4231 } 4232 4233 static void logCriticalInfo(int priority, String msg) { 4234 Slog.println(priority, TAG, msg); 4235 EventLogTags.writePmCriticalInfo(msg); 4236 try { 4237 File fname = getSettingsProblemFile(); 4238 FileOutputStream out = new FileOutputStream(fname, true); 4239 PrintWriter pw = new FastPrintWriter(out); 4240 SimpleDateFormat formatter = new SimpleDateFormat(); 4241 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4242 pw.println(dateString + ": " + msg); 4243 pw.close(); 4244 FileUtils.setPermissions( 4245 fname.toString(), 4246 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4247 -1, -1); 4248 } catch (java.io.IOException e) { 4249 } 4250 } 4251 4252 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4253 PackageParser.Package pkg, File srcFile, int parseFlags) 4254 throws PackageManagerException { 4255 if (ps != null 4256 && ps.codePath.equals(srcFile) 4257 && ps.timeStamp == srcFile.lastModified() 4258 && !isCompatSignatureUpdateNeeded(pkg) 4259 && !isRecoverSignatureUpdateNeeded(pkg)) { 4260 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4261 if (ps.signatures.mSignatures != null 4262 && ps.signatures.mSignatures.length != 0 4263 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4264 // Optimization: reuse the existing cached certificates 4265 // if the package appears to be unchanged. 4266 pkg.mSignatures = ps.signatures.mSignatures; 4267 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4268 synchronized (mPackages) { 4269 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4270 } 4271 return; 4272 } 4273 4274 Slog.w(TAG, "PackageSetting for " + ps.name 4275 + " is missing signatures. Collecting certs again to recover them."); 4276 } else { 4277 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4278 } 4279 4280 try { 4281 pp.collectCertificates(pkg, parseFlags); 4282 pp.collectManifestDigest(pkg); 4283 } catch (PackageParserException e) { 4284 throw PackageManagerException.from(e); 4285 } 4286 } 4287 4288 /* 4289 * Scan a package and return the newly parsed package. 4290 * Returns null in case of errors and the error code is stored in mLastScanError 4291 */ 4292 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4293 long currentTime, UserHandle user) throws PackageManagerException { 4294 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4295 parseFlags |= mDefParseFlags; 4296 PackageParser pp = new PackageParser(); 4297 pp.setSeparateProcesses(mSeparateProcesses); 4298 pp.setOnlyCoreApps(mOnlyCore); 4299 pp.setDisplayMetrics(mMetrics); 4300 4301 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4302 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4303 } 4304 4305 final PackageParser.Package pkg; 4306 try { 4307 pkg = pp.parsePackage(scanFile, parseFlags); 4308 } catch (PackageParserException e) { 4309 throw PackageManagerException.from(e); 4310 } 4311 4312 PackageSetting ps = null; 4313 PackageSetting updatedPkg; 4314 // reader 4315 synchronized (mPackages) { 4316 // Look to see if we already know about this package. 4317 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4318 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4319 // This package has been renamed to its original name. Let's 4320 // use that. 4321 ps = mSettings.peekPackageLPr(oldName); 4322 } 4323 // If there was no original package, see one for the real package name. 4324 if (ps == null) { 4325 ps = mSettings.peekPackageLPr(pkg.packageName); 4326 } 4327 // Check to see if this package could be hiding/updating a system 4328 // package. Must look for it either under the original or real 4329 // package name depending on our state. 4330 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4331 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4332 } 4333 boolean updatedPkgBetter = false; 4334 // First check if this is a system package that may involve an update 4335 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4336 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4337 // it needs to drop FLAG_PRIVILEGED. 4338 if (locationIsPrivileged(scanFile)) { 4339 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4340 } else { 4341 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4342 } 4343 4344 if (ps != null && !ps.codePath.equals(scanFile)) { 4345 // The path has changed from what was last scanned... check the 4346 // version of the new path against what we have stored to determine 4347 // what to do. 4348 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4349 if (pkg.mVersionCode <= ps.versionCode) { 4350 // The system package has been updated and the code path does not match 4351 // Ignore entry. Skip it. 4352 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4353 + " ignored: updated version " + ps.versionCode 4354 + " better than this " + pkg.mVersionCode); 4355 if (!updatedPkg.codePath.equals(scanFile)) { 4356 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4357 + ps.name + " changing from " + updatedPkg.codePathString 4358 + " to " + scanFile); 4359 updatedPkg.codePath = scanFile; 4360 updatedPkg.codePathString = scanFile.toString(); 4361 updatedPkg.resourcePath = scanFile; 4362 updatedPkg.resourcePathString = scanFile.toString(); 4363 } 4364 updatedPkg.pkg = pkg; 4365 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4366 } else { 4367 // The current app on the system partition is better than 4368 // what we have updated to on the data partition; switch 4369 // back to the system partition version. 4370 // At this point, its safely assumed that package installation for 4371 // apps in system partition will go through. If not there won't be a working 4372 // version of the app 4373 // writer 4374 synchronized (mPackages) { 4375 // Just remove the loaded entries from package lists. 4376 mPackages.remove(ps.name); 4377 } 4378 4379 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4380 + " reverting from " + ps.codePathString 4381 + ": new version " + pkg.mVersionCode 4382 + " better than installed " + ps.versionCode); 4383 4384 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4385 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4386 getAppDexInstructionSets(ps)); 4387 synchronized (mInstallLock) { 4388 args.cleanUpResourcesLI(); 4389 } 4390 synchronized (mPackages) { 4391 mSettings.enableSystemPackageLPw(ps.name); 4392 } 4393 updatedPkgBetter = true; 4394 } 4395 } 4396 } 4397 4398 if (updatedPkg != null) { 4399 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4400 // initially 4401 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4402 4403 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4404 // flag set initially 4405 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4406 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4407 } 4408 } 4409 4410 // Verify certificates against what was last scanned 4411 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4412 4413 /* 4414 * A new system app appeared, but we already had a non-system one of the 4415 * same name installed earlier. 4416 */ 4417 boolean shouldHideSystemApp = false; 4418 if (updatedPkg == null && ps != null 4419 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4420 /* 4421 * Check to make sure the signatures match first. If they don't, 4422 * wipe the installed application and its data. 4423 */ 4424 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4425 != PackageManager.SIGNATURE_MATCH) { 4426 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4427 + " signatures don't match existing userdata copy; removing"); 4428 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4429 ps = null; 4430 } else { 4431 /* 4432 * If the newly-added system app is an older version than the 4433 * already installed version, hide it. It will be scanned later 4434 * and re-added like an update. 4435 */ 4436 if (pkg.mVersionCode <= ps.versionCode) { 4437 shouldHideSystemApp = true; 4438 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4439 + " but new version " + pkg.mVersionCode + " better than installed " 4440 + ps.versionCode + "; hiding system"); 4441 } else { 4442 /* 4443 * The newly found system app is a newer version that the 4444 * one previously installed. Simply remove the 4445 * already-installed application and replace it with our own 4446 * while keeping the application data. 4447 */ 4448 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4449 + " reverting from " + ps.codePathString + ": new version " 4450 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4451 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4452 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4453 getAppDexInstructionSets(ps)); 4454 synchronized (mInstallLock) { 4455 args.cleanUpResourcesLI(); 4456 } 4457 } 4458 } 4459 } 4460 4461 // The apk is forward locked (not public) if its code and resources 4462 // are kept in different files. (except for app in either system or 4463 // vendor path). 4464 // TODO grab this value from PackageSettings 4465 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4466 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4467 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4468 } 4469 } 4470 4471 // TODO: extend to support forward-locked splits 4472 String resourcePath = null; 4473 String baseResourcePath = null; 4474 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4475 if (ps != null && ps.resourcePathString != null) { 4476 resourcePath = ps.resourcePathString; 4477 baseResourcePath = ps.resourcePathString; 4478 } else { 4479 // Should not happen at all. Just log an error. 4480 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4481 } 4482 } else { 4483 resourcePath = pkg.codePath; 4484 baseResourcePath = pkg.baseCodePath; 4485 } 4486 4487 // Set application objects path explicitly. 4488 pkg.applicationInfo.setCodePath(pkg.codePath); 4489 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4490 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4491 pkg.applicationInfo.setResourcePath(resourcePath); 4492 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4493 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4494 4495 // Note that we invoke the following method only if we are about to unpack an application 4496 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4497 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4498 4499 /* 4500 * If the system app should be overridden by a previously installed 4501 * data, hide the system app now and let the /data/app scan pick it up 4502 * again. 4503 */ 4504 if (shouldHideSystemApp) { 4505 synchronized (mPackages) { 4506 /* 4507 * We have to grant systems permissions before we hide, because 4508 * grantPermissions will assume the package update is trying to 4509 * expand its permissions. 4510 */ 4511 grantPermissionsLPw(pkg, true, pkg.packageName); 4512 mSettings.disableSystemPackageLPw(pkg.packageName); 4513 } 4514 } 4515 4516 return scannedPkg; 4517 } 4518 4519 private static String fixProcessName(String defProcessName, 4520 String processName, int uid) { 4521 if (processName == null) { 4522 return defProcessName; 4523 } 4524 return processName; 4525 } 4526 4527 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4528 throws PackageManagerException { 4529 if (pkgSetting.signatures.mSignatures != null) { 4530 // Already existing package. Make sure signatures match 4531 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4532 == PackageManager.SIGNATURE_MATCH; 4533 if (!match) { 4534 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4535 == PackageManager.SIGNATURE_MATCH; 4536 } 4537 if (!match) { 4538 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 4539 == PackageManager.SIGNATURE_MATCH; 4540 } 4541 if (!match) { 4542 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4543 + pkg.packageName + " signatures do not match the " 4544 + "previously installed version; ignoring!"); 4545 } 4546 } 4547 4548 // Check for shared user signatures 4549 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4550 // Already existing package. Make sure signatures match 4551 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4552 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4553 if (!match) { 4554 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4555 == PackageManager.SIGNATURE_MATCH; 4556 } 4557 if (!match) { 4558 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 4559 == PackageManager.SIGNATURE_MATCH; 4560 } 4561 if (!match) { 4562 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4563 "Package " + pkg.packageName 4564 + " has no signatures that match those in shared user " 4565 + pkgSetting.sharedUser.name + "; ignoring!"); 4566 } 4567 } 4568 } 4569 4570 /** 4571 * Enforces that only the system UID or root's UID can call a method exposed 4572 * via Binder. 4573 * 4574 * @param message used as message if SecurityException is thrown 4575 * @throws SecurityException if the caller is not system or root 4576 */ 4577 private static final void enforceSystemOrRoot(String message) { 4578 final int uid = Binder.getCallingUid(); 4579 if (uid != Process.SYSTEM_UID && uid != 0) { 4580 throw new SecurityException(message); 4581 } 4582 } 4583 4584 @Override 4585 public void performBootDexOpt() { 4586 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4587 4588 // Before everything else, see whether we need to fstrim. 4589 try { 4590 IMountService ms = PackageHelper.getMountService(); 4591 if (ms != null) { 4592 final boolean isUpgrade = isUpgrade(); 4593 boolean doTrim = isUpgrade; 4594 if (doTrim) { 4595 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 4596 } else { 4597 final long interval = android.provider.Settings.Global.getLong( 4598 mContext.getContentResolver(), 4599 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 4600 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 4601 if (interval > 0) { 4602 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 4603 if (timeSinceLast > interval) { 4604 doTrim = true; 4605 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 4606 + "; running immediately"); 4607 } 4608 } 4609 } 4610 if (doTrim) { 4611 if (!isFirstBoot()) { 4612 try { 4613 ActivityManagerNative.getDefault().showBootMessage( 4614 mContext.getResources().getString( 4615 R.string.android_upgrading_fstrim), true); 4616 } catch (RemoteException e) { 4617 } 4618 } 4619 ms.runMaintenance(); 4620 } 4621 } else { 4622 Slog.e(TAG, "Mount service unavailable!"); 4623 } 4624 } catch (RemoteException e) { 4625 // Can't happen; MountService is local 4626 } 4627 4628 final ArraySet<PackageParser.Package> pkgs; 4629 synchronized (mPackages) { 4630 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 4631 } 4632 4633 if (pkgs != null) { 4634 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4635 // in case the device runs out of space. 4636 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4637 // Give priority to core apps. 4638 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4639 PackageParser.Package pkg = it.next(); 4640 if (pkg.coreApp) { 4641 if (DEBUG_DEXOPT) { 4642 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 4643 } 4644 sortedPkgs.add(pkg); 4645 it.remove(); 4646 } 4647 } 4648 // Give priority to system apps that listen for pre boot complete. 4649 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4650 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 4651 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4652 PackageParser.Package pkg = it.next(); 4653 if (pkgNames.contains(pkg.packageName)) { 4654 if (DEBUG_DEXOPT) { 4655 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 4656 } 4657 sortedPkgs.add(pkg); 4658 it.remove(); 4659 } 4660 } 4661 // Give priority to system apps. 4662 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4663 PackageParser.Package pkg = it.next(); 4664 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 4665 if (DEBUG_DEXOPT) { 4666 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 4667 } 4668 sortedPkgs.add(pkg); 4669 it.remove(); 4670 } 4671 } 4672 // Give priority to updated system apps. 4673 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4674 PackageParser.Package pkg = it.next(); 4675 if (isUpdatedSystemApp(pkg)) { 4676 if (DEBUG_DEXOPT) { 4677 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 4678 } 4679 sortedPkgs.add(pkg); 4680 it.remove(); 4681 } 4682 } 4683 // Give priority to apps that listen for boot complete. 4684 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4685 pkgNames = getPackageNamesForIntent(intent); 4686 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4687 PackageParser.Package pkg = it.next(); 4688 if (pkgNames.contains(pkg.packageName)) { 4689 if (DEBUG_DEXOPT) { 4690 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 4691 } 4692 sortedPkgs.add(pkg); 4693 it.remove(); 4694 } 4695 } 4696 // Filter out packages that aren't recently used. 4697 filterRecentlyUsedApps(pkgs); 4698 // Add all remaining apps. 4699 for (PackageParser.Package pkg : pkgs) { 4700 if (DEBUG_DEXOPT) { 4701 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 4702 } 4703 sortedPkgs.add(pkg); 4704 } 4705 4706 // If we want to be lazy, filter everything that wasn't recently used. 4707 if (mLazyDexOpt) { 4708 filterRecentlyUsedApps(sortedPkgs); 4709 } 4710 4711 int i = 0; 4712 int total = sortedPkgs.size(); 4713 File dataDir = Environment.getDataDirectory(); 4714 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 4715 if (lowThreshold == 0) { 4716 throw new IllegalStateException("Invalid low memory threshold"); 4717 } 4718 for (PackageParser.Package pkg : sortedPkgs) { 4719 long usableSpace = dataDir.getUsableSpace(); 4720 if (usableSpace < lowThreshold) { 4721 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 4722 break; 4723 } 4724 performBootDexOpt(pkg, ++i, total); 4725 } 4726 } 4727 } 4728 4729 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 4730 // Filter out packages that aren't recently used. 4731 // 4732 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4733 // should do a full dexopt. 4734 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4735 int total = pkgs.size(); 4736 int skipped = 0; 4737 long now = System.currentTimeMillis(); 4738 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4739 PackageParser.Package pkg = i.next(); 4740 long then = pkg.mLastPackageUsageTimeInMills; 4741 if (then + mDexOptLRUThresholdInMills < now) { 4742 if (DEBUG_DEXOPT) { 4743 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4744 ((then == 0) ? "never" : new Date(then))); 4745 } 4746 i.remove(); 4747 skipped++; 4748 } 4749 } 4750 if (DEBUG_DEXOPT) { 4751 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4752 } 4753 } 4754 } 4755 4756 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 4757 List<ResolveInfo> ris = null; 4758 try { 4759 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4760 intent, null, 0, UserHandle.USER_OWNER); 4761 } catch (RemoteException e) { 4762 } 4763 ArraySet<String> pkgNames = new ArraySet<String>(); 4764 if (ris != null) { 4765 for (ResolveInfo ri : ris) { 4766 pkgNames.add(ri.activityInfo.packageName); 4767 } 4768 } 4769 return pkgNames; 4770 } 4771 4772 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4773 if (DEBUG_DEXOPT) { 4774 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4775 } 4776 if (!isFirstBoot()) { 4777 try { 4778 ActivityManagerNative.getDefault().showBootMessage( 4779 mContext.getResources().getString(R.string.android_upgrading_apk, 4780 curr, total), true); 4781 } catch (RemoteException e) { 4782 } 4783 } 4784 PackageParser.Package p = pkg; 4785 synchronized (mInstallLock) { 4786 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 4787 false /* force dex */, false /* defer */, true /* include dependencies */); 4788 } 4789 } 4790 4791 @Override 4792 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4793 return performDexOpt(packageName, instructionSet, false); 4794 } 4795 4796 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4797 if (info.primaryCpuAbi == null) { 4798 return getPreferredInstructionSet(); 4799 } 4800 4801 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4802 } 4803 4804 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4805 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4806 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4807 if (!dexopt && !updateUsage) { 4808 // We aren't going to dexopt or update usage, so bail early. 4809 return false; 4810 } 4811 PackageParser.Package p; 4812 final String targetInstructionSet; 4813 synchronized (mPackages) { 4814 p = mPackages.get(packageName); 4815 if (p == null) { 4816 return false; 4817 } 4818 if (updateUsage) { 4819 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4820 } 4821 mPackageUsage.write(false); 4822 if (!dexopt) { 4823 // We aren't going to dexopt, so bail early. 4824 return false; 4825 } 4826 4827 targetInstructionSet = instructionSet != null ? instructionSet : 4828 getPrimaryInstructionSet(p.applicationInfo); 4829 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4830 return false; 4831 } 4832 } 4833 4834 synchronized (mInstallLock) { 4835 final String[] instructionSets = new String[] { targetInstructionSet }; 4836 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 4837 false /* forceDex */, false /* defer */, true /* inclDependencies */); 4838 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 4839 } 4840 } 4841 4842 public ArraySet<String> getPackagesThatNeedDexOpt() { 4843 ArraySet<String> pkgs = null; 4844 synchronized (mPackages) { 4845 for (PackageParser.Package p : mPackages.values()) { 4846 if (DEBUG_DEXOPT) { 4847 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4848 } 4849 if (!p.mDexOptPerformed.isEmpty()) { 4850 continue; 4851 } 4852 if (pkgs == null) { 4853 pkgs = new ArraySet<String>(); 4854 } 4855 pkgs.add(p.packageName); 4856 } 4857 } 4858 return pkgs; 4859 } 4860 4861 public void shutdown() { 4862 mPackageUsage.write(true); 4863 } 4864 4865 @Override 4866 public void forceDexOpt(String packageName) { 4867 enforceSystemOrRoot("forceDexOpt"); 4868 4869 PackageParser.Package pkg; 4870 synchronized (mPackages) { 4871 pkg = mPackages.get(packageName); 4872 if (pkg == null) { 4873 throw new IllegalArgumentException("Missing package: " + packageName); 4874 } 4875 } 4876 4877 synchronized (mInstallLock) { 4878 final String[] instructionSets = new String[] { 4879 getPrimaryInstructionSet(pkg.applicationInfo) }; 4880 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 4881 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 4882 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 4883 throw new IllegalStateException("Failed to dexopt: " + res); 4884 } 4885 } 4886 } 4887 4888 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4889 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4890 Slog.w(TAG, "Unable to update from " + oldPkg.name 4891 + " to " + newPkg.packageName 4892 + ": old package not in system partition"); 4893 return false; 4894 } else if (mPackages.get(oldPkg.name) != null) { 4895 Slog.w(TAG, "Unable to update from " + oldPkg.name 4896 + " to " + newPkg.packageName 4897 + ": old package still exists"); 4898 return false; 4899 } 4900 return true; 4901 } 4902 4903 private File getDataPathForPackage(String packageName, int userId) { 4904 /* 4905 * Until we fully support multiple users, return the directory we 4906 * previously would have. The PackageManagerTests will need to be 4907 * revised when this is changed back.. 4908 */ 4909 if (userId == 0) { 4910 return new File(mAppDataDir, packageName); 4911 } else { 4912 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4913 + File.separator + packageName); 4914 } 4915 } 4916 4917 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4918 int[] users = sUserManager.getUserIds(); 4919 int res = mInstaller.install(packageName, uid, uid, seinfo); 4920 if (res < 0) { 4921 return res; 4922 } 4923 for (int user : users) { 4924 if (user != 0) { 4925 res = mInstaller.createUserData(packageName, 4926 UserHandle.getUid(user, uid), user, seinfo); 4927 if (res < 0) { 4928 return res; 4929 } 4930 } 4931 } 4932 return res; 4933 } 4934 4935 private int removeDataDirsLI(String packageName) { 4936 int[] users = sUserManager.getUserIds(); 4937 int res = 0; 4938 for (int user : users) { 4939 int resInner = mInstaller.remove(packageName, user); 4940 if (resInner < 0) { 4941 res = resInner; 4942 } 4943 } 4944 4945 return res; 4946 } 4947 4948 private int deleteCodeCacheDirsLI(String packageName) { 4949 int[] users = sUserManager.getUserIds(); 4950 int res = 0; 4951 for (int user : users) { 4952 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4953 if (resInner < 0) { 4954 res = resInner; 4955 } 4956 } 4957 return res; 4958 } 4959 4960 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4961 PackageParser.Package changingLib) { 4962 if (file.path != null) { 4963 usesLibraryFiles.add(file.path); 4964 return; 4965 } 4966 PackageParser.Package p = mPackages.get(file.apk); 4967 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4968 // If we are doing this while in the middle of updating a library apk, 4969 // then we need to make sure to use that new apk for determining the 4970 // dependencies here. (We haven't yet finished committing the new apk 4971 // to the package manager state.) 4972 if (p == null || p.packageName.equals(changingLib.packageName)) { 4973 p = changingLib; 4974 } 4975 } 4976 if (p != null) { 4977 usesLibraryFiles.addAll(p.getAllCodePaths()); 4978 } 4979 } 4980 4981 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4982 PackageParser.Package changingLib) throws PackageManagerException { 4983 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4984 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4985 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4986 for (int i=0; i<N; i++) { 4987 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4988 if (file == null) { 4989 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4990 "Package " + pkg.packageName + " requires unavailable shared library " 4991 + pkg.usesLibraries.get(i) + "; failing!"); 4992 } 4993 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4994 } 4995 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4996 for (int i=0; i<N; i++) { 4997 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4998 if (file == null) { 4999 Slog.w(TAG, "Package " + pkg.packageName 5000 + " desires unavailable shared library " 5001 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5002 } else { 5003 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5004 } 5005 } 5006 N = usesLibraryFiles.size(); 5007 if (N > 0) { 5008 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5009 } else { 5010 pkg.usesLibraryFiles = null; 5011 } 5012 } 5013 } 5014 5015 private static boolean hasString(List<String> list, List<String> which) { 5016 if (list == null) { 5017 return false; 5018 } 5019 for (int i=list.size()-1; i>=0; i--) { 5020 for (int j=which.size()-1; j>=0; j--) { 5021 if (which.get(j).equals(list.get(i))) { 5022 return true; 5023 } 5024 } 5025 } 5026 return false; 5027 } 5028 5029 private void updateAllSharedLibrariesLPw() { 5030 for (PackageParser.Package pkg : mPackages.values()) { 5031 try { 5032 updateSharedLibrariesLPw(pkg, null); 5033 } catch (PackageManagerException e) { 5034 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5035 } 5036 } 5037 } 5038 5039 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5040 PackageParser.Package changingPkg) { 5041 ArrayList<PackageParser.Package> res = null; 5042 for (PackageParser.Package pkg : mPackages.values()) { 5043 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5044 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5045 if (res == null) { 5046 res = new ArrayList<PackageParser.Package>(); 5047 } 5048 res.add(pkg); 5049 try { 5050 updateSharedLibrariesLPw(pkg, changingPkg); 5051 } catch (PackageManagerException e) { 5052 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5053 } 5054 } 5055 } 5056 return res; 5057 } 5058 5059 /** 5060 * Derive the value of the {@code cpuAbiOverride} based on the provided 5061 * value and an optional stored value from the package settings. 5062 */ 5063 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5064 String cpuAbiOverride = null; 5065 5066 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5067 cpuAbiOverride = null; 5068 } else if (abiOverride != null) { 5069 cpuAbiOverride = abiOverride; 5070 } else if (settings != null) { 5071 cpuAbiOverride = settings.cpuAbiOverrideString; 5072 } 5073 5074 return cpuAbiOverride; 5075 } 5076 5077 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5078 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5079 boolean success = false; 5080 try { 5081 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5082 currentTime, user); 5083 success = true; 5084 return res; 5085 } finally { 5086 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5087 removeDataDirsLI(pkg.packageName); 5088 } 5089 } 5090 } 5091 5092 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5093 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5094 final File scanFile = new File(pkg.codePath); 5095 if (pkg.applicationInfo.getCodePath() == null || 5096 pkg.applicationInfo.getResourcePath() == null) { 5097 // Bail out. The resource and code paths haven't been set. 5098 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5099 "Code and resource paths haven't been set correctly"); 5100 } 5101 5102 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5103 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5104 } else { 5105 // Only allow system apps to be flagged as core apps. 5106 pkg.coreApp = false; 5107 } 5108 5109 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5110 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5111 } 5112 5113 if (mCustomResolverComponentName != null && 5114 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5115 setUpCustomResolverActivity(pkg); 5116 } 5117 5118 if (pkg.packageName.equals("android")) { 5119 synchronized (mPackages) { 5120 if (mAndroidApplication != null) { 5121 Slog.w(TAG, "*************************************************"); 5122 Slog.w(TAG, "Core android package being redefined. Skipping."); 5123 Slog.w(TAG, " file=" + scanFile); 5124 Slog.w(TAG, "*************************************************"); 5125 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5126 "Core android package being redefined. Skipping."); 5127 } 5128 5129 // Set up information for our fall-back user intent resolution activity. 5130 mPlatformPackage = pkg; 5131 pkg.mVersionCode = mSdkVersion; 5132 mAndroidApplication = pkg.applicationInfo; 5133 5134 if (!mResolverReplaced) { 5135 mResolveActivity.applicationInfo = mAndroidApplication; 5136 mResolveActivity.name = ResolverActivity.class.getName(); 5137 mResolveActivity.packageName = mAndroidApplication.packageName; 5138 mResolveActivity.processName = "system:ui"; 5139 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5140 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5141 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5142 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5143 mResolveActivity.exported = true; 5144 mResolveActivity.enabled = true; 5145 mResolveInfo.activityInfo = mResolveActivity; 5146 mResolveInfo.priority = 0; 5147 mResolveInfo.preferredOrder = 0; 5148 mResolveInfo.match = 0; 5149 mResolveComponentName = new ComponentName( 5150 mAndroidApplication.packageName, mResolveActivity.name); 5151 } 5152 } 5153 } 5154 5155 if (DEBUG_PACKAGE_SCANNING) { 5156 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5157 Log.d(TAG, "Scanning package " + pkg.packageName); 5158 } 5159 5160 if (mPackages.containsKey(pkg.packageName) 5161 || mSharedLibraries.containsKey(pkg.packageName)) { 5162 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5163 "Application package " + pkg.packageName 5164 + " already installed. Skipping duplicate."); 5165 } 5166 5167 // Initialize package source and resource directories 5168 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5169 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5170 5171 SharedUserSetting suid = null; 5172 PackageSetting pkgSetting = null; 5173 5174 if (!isSystemApp(pkg)) { 5175 // Only system apps can use these features. 5176 pkg.mOriginalPackages = null; 5177 pkg.mRealPackage = null; 5178 pkg.mAdoptPermissions = null; 5179 } 5180 5181 // writer 5182 synchronized (mPackages) { 5183 if (pkg.mSharedUserId != null) { 5184 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5185 if (suid == null) { 5186 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5187 "Creating application package " + pkg.packageName 5188 + " for shared user failed"); 5189 } 5190 if (DEBUG_PACKAGE_SCANNING) { 5191 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5192 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5193 + "): packages=" + suid.packages); 5194 } 5195 } 5196 5197 // Check if we are renaming from an original package name. 5198 PackageSetting origPackage = null; 5199 String realName = null; 5200 if (pkg.mOriginalPackages != null) { 5201 // This package may need to be renamed to a previously 5202 // installed name. Let's check on that... 5203 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5204 if (pkg.mOriginalPackages.contains(renamed)) { 5205 // This package had originally been installed as the 5206 // original name, and we have already taken care of 5207 // transitioning to the new one. Just update the new 5208 // one to continue using the old name. 5209 realName = pkg.mRealPackage; 5210 if (!pkg.packageName.equals(renamed)) { 5211 // Callers into this function may have already taken 5212 // care of renaming the package; only do it here if 5213 // it is not already done. 5214 pkg.setPackageName(renamed); 5215 } 5216 5217 } else { 5218 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5219 if ((origPackage = mSettings.peekPackageLPr( 5220 pkg.mOriginalPackages.get(i))) != null) { 5221 // We do have the package already installed under its 5222 // original name... should we use it? 5223 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5224 // New package is not compatible with original. 5225 origPackage = null; 5226 continue; 5227 } else if (origPackage.sharedUser != null) { 5228 // Make sure uid is compatible between packages. 5229 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5230 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5231 + " to " + pkg.packageName + ": old uid " 5232 + origPackage.sharedUser.name 5233 + " differs from " + pkg.mSharedUserId); 5234 origPackage = null; 5235 continue; 5236 } 5237 } else { 5238 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5239 + pkg.packageName + " to old name " + origPackage.name); 5240 } 5241 break; 5242 } 5243 } 5244 } 5245 } 5246 5247 if (mTransferedPackages.contains(pkg.packageName)) { 5248 Slog.w(TAG, "Package " + pkg.packageName 5249 + " was transferred to another, but its .apk remains"); 5250 } 5251 5252 // Just create the setting, don't add it yet. For already existing packages 5253 // the PkgSetting exists already and doesn't have to be created. 5254 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5255 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5256 pkg.applicationInfo.primaryCpuAbi, 5257 pkg.applicationInfo.secondaryCpuAbi, 5258 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5259 user, false); 5260 if (pkgSetting == null) { 5261 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5262 "Creating application package " + pkg.packageName + " failed"); 5263 } 5264 5265 if (pkgSetting.origPackage != null) { 5266 // If we are first transitioning from an original package, 5267 // fix up the new package's name now. We need to do this after 5268 // looking up the package under its new name, so getPackageLP 5269 // can take care of fiddling things correctly. 5270 pkg.setPackageName(origPackage.name); 5271 5272 // File a report about this. 5273 String msg = "New package " + pkgSetting.realName 5274 + " renamed to replace old package " + pkgSetting.name; 5275 reportSettingsProblem(Log.WARN, msg); 5276 5277 // Make a note of it. 5278 mTransferedPackages.add(origPackage.name); 5279 5280 // No longer need to retain this. 5281 pkgSetting.origPackage = null; 5282 } 5283 5284 if (realName != null) { 5285 // Make a note of it. 5286 mTransferedPackages.add(pkg.packageName); 5287 } 5288 5289 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5290 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5291 } 5292 5293 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5294 // Check all shared libraries and map to their actual file path. 5295 // We only do this here for apps not on a system dir, because those 5296 // are the only ones that can fail an install due to this. We 5297 // will take care of the system apps by updating all of their 5298 // library paths after the scan is done. 5299 updateSharedLibrariesLPw(pkg, null); 5300 } 5301 5302 if (mFoundPolicyFile) { 5303 SELinuxMMAC.assignSeinfoValue(pkg); 5304 } 5305 5306 pkg.applicationInfo.uid = pkgSetting.appId; 5307 pkg.mExtras = pkgSetting; 5308 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5309 try { 5310 verifySignaturesLP(pkgSetting, pkg); 5311 // We just determined the app is signed correctly, so bring 5312 // over the latest parsed certs. 5313 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5314 } catch (PackageManagerException e) { 5315 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5316 throw e; 5317 } 5318 // The signature has changed, but this package is in the system 5319 // image... let's recover! 5320 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5321 // However... if this package is part of a shared user, but it 5322 // doesn't match the signature of the shared user, let's fail. 5323 // What this means is that you can't change the signatures 5324 // associated with an overall shared user, which doesn't seem all 5325 // that unreasonable. 5326 if (pkgSetting.sharedUser != null) { 5327 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5328 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5329 throw new PackageManagerException( 5330 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5331 "Signature mismatch for shared user : " 5332 + pkgSetting.sharedUser); 5333 } 5334 } 5335 // File a report about this. 5336 String msg = "System package " + pkg.packageName 5337 + " signature changed; retaining data."; 5338 reportSettingsProblem(Log.WARN, msg); 5339 } 5340 } else { 5341 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5342 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5343 + pkg.packageName + " upgrade keys do not match the " 5344 + "previously installed version"); 5345 } else { 5346 // We just determined the app is signed correctly, so bring 5347 // over the latest parsed certs. 5348 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5349 } 5350 } 5351 // Verify that this new package doesn't have any content providers 5352 // that conflict with existing packages. Only do this if the 5353 // package isn't already installed, since we don't want to break 5354 // things that are installed. 5355 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5356 final int N = pkg.providers.size(); 5357 int i; 5358 for (i=0; i<N; i++) { 5359 PackageParser.Provider p = pkg.providers.get(i); 5360 if (p.info.authority != null) { 5361 String names[] = p.info.authority.split(";"); 5362 for (int j = 0; j < names.length; j++) { 5363 if (mProvidersByAuthority.containsKey(names[j])) { 5364 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5365 final String otherPackageName = 5366 ((other != null && other.getComponentName() != null) ? 5367 other.getComponentName().getPackageName() : "?"); 5368 throw new PackageManagerException( 5369 INSTALL_FAILED_CONFLICTING_PROVIDER, 5370 "Can't install because provider name " + names[j] 5371 + " (in package " + pkg.applicationInfo.packageName 5372 + ") is already used by " + otherPackageName); 5373 } 5374 } 5375 } 5376 } 5377 } 5378 5379 if (pkg.mAdoptPermissions != null) { 5380 // This package wants to adopt ownership of permissions from 5381 // another package. 5382 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5383 final String origName = pkg.mAdoptPermissions.get(i); 5384 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5385 if (orig != null) { 5386 if (verifyPackageUpdateLPr(orig, pkg)) { 5387 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5388 + pkg.packageName); 5389 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5390 } 5391 } 5392 } 5393 } 5394 } 5395 5396 final String pkgName = pkg.packageName; 5397 5398 final long scanFileTime = scanFile.lastModified(); 5399 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5400 pkg.applicationInfo.processName = fixProcessName( 5401 pkg.applicationInfo.packageName, 5402 pkg.applicationInfo.processName, 5403 pkg.applicationInfo.uid); 5404 5405 File dataPath; 5406 if (mPlatformPackage == pkg) { 5407 // The system package is special. 5408 dataPath = new File(Environment.getDataDirectory(), "system"); 5409 5410 pkg.applicationInfo.dataDir = dataPath.getPath(); 5411 5412 } else { 5413 // This is a normal package, need to make its data directory. 5414 dataPath = getDataPathForPackage(pkg.packageName, 0); 5415 5416 boolean uidError = false; 5417 if (dataPath.exists()) { 5418 int currentUid = 0; 5419 try { 5420 StructStat stat = Os.stat(dataPath.getPath()); 5421 currentUid = stat.st_uid; 5422 } catch (ErrnoException e) { 5423 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5424 } 5425 5426 // If we have mismatched owners for the data path, we have a problem. 5427 if (currentUid != pkg.applicationInfo.uid) { 5428 boolean recovered = false; 5429 if (currentUid == 0) { 5430 // The directory somehow became owned by root. Wow. 5431 // This is probably because the system was stopped while 5432 // installd was in the middle of messing with its libs 5433 // directory. Ask installd to fix that. 5434 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5435 pkg.applicationInfo.uid); 5436 if (ret >= 0) { 5437 recovered = true; 5438 String msg = "Package " + pkg.packageName 5439 + " unexpectedly changed to uid 0; recovered to " + 5440 + pkg.applicationInfo.uid; 5441 reportSettingsProblem(Log.WARN, msg); 5442 } 5443 } 5444 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5445 || (scanFlags&SCAN_BOOTING) != 0)) { 5446 // If this is a system app, we can at least delete its 5447 // current data so the application will still work. 5448 int ret = removeDataDirsLI(pkgName); 5449 if (ret >= 0) { 5450 // TODO: Kill the processes first 5451 // Old data gone! 5452 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5453 ? "System package " : "Third party package "; 5454 String msg = prefix + pkg.packageName 5455 + " has changed from uid: " 5456 + currentUid + " to " 5457 + pkg.applicationInfo.uid + "; old data erased"; 5458 reportSettingsProblem(Log.WARN, msg); 5459 recovered = true; 5460 5461 // And now re-install the app. 5462 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5463 pkg.applicationInfo.seinfo); 5464 if (ret == -1) { 5465 // Ack should not happen! 5466 msg = prefix + pkg.packageName 5467 + " could not have data directory re-created after delete."; 5468 reportSettingsProblem(Log.WARN, msg); 5469 throw new PackageManagerException( 5470 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5471 } 5472 } 5473 if (!recovered) { 5474 mHasSystemUidErrors = true; 5475 } 5476 } else if (!recovered) { 5477 // If we allow this install to proceed, we will be broken. 5478 // Abort, abort! 5479 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5480 "scanPackageLI"); 5481 } 5482 if (!recovered) { 5483 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5484 + pkg.applicationInfo.uid + "/fs_" 5485 + currentUid; 5486 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5487 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5488 String msg = "Package " + pkg.packageName 5489 + " has mismatched uid: " 5490 + currentUid + " on disk, " 5491 + pkg.applicationInfo.uid + " in settings"; 5492 // writer 5493 synchronized (mPackages) { 5494 mSettings.mReadMessages.append(msg); 5495 mSettings.mReadMessages.append('\n'); 5496 uidError = true; 5497 if (!pkgSetting.uidError) { 5498 reportSettingsProblem(Log.ERROR, msg); 5499 } 5500 } 5501 } 5502 } 5503 pkg.applicationInfo.dataDir = dataPath.getPath(); 5504 if (mShouldRestoreconData) { 5505 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5506 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5507 pkg.applicationInfo.uid); 5508 } 5509 } else { 5510 if (DEBUG_PACKAGE_SCANNING) { 5511 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5512 Log.v(TAG, "Want this data dir: " + dataPath); 5513 } 5514 //invoke installer to do the actual installation 5515 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5516 pkg.applicationInfo.seinfo); 5517 if (ret < 0) { 5518 // Error from installer 5519 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5520 "Unable to create data dirs [errorCode=" + ret + "]"); 5521 } 5522 5523 if (dataPath.exists()) { 5524 pkg.applicationInfo.dataDir = dataPath.getPath(); 5525 } else { 5526 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5527 pkg.applicationInfo.dataDir = null; 5528 } 5529 } 5530 5531 pkgSetting.uidError = uidError; 5532 } 5533 5534 final String path = scanFile.getPath(); 5535 final String codePath = pkg.applicationInfo.getCodePath(); 5536 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5537 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5538 setBundledAppAbisAndRoots(pkg, pkgSetting); 5539 5540 // If we haven't found any native libraries for the app, check if it has 5541 // renderscript code. We'll need to force the app to 32 bit if it has 5542 // renderscript bitcode. 5543 if (pkg.applicationInfo.primaryCpuAbi == null 5544 && pkg.applicationInfo.secondaryCpuAbi == null 5545 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5546 NativeLibraryHelper.Handle handle = null; 5547 try { 5548 handle = NativeLibraryHelper.Handle.create(scanFile); 5549 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5550 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5551 } 5552 } catch (IOException ioe) { 5553 Slog.w(TAG, "Error scanning system app : " + ioe); 5554 } finally { 5555 IoUtils.closeQuietly(handle); 5556 } 5557 } 5558 5559 setNativeLibraryPaths(pkg); 5560 } else { 5561 // TODO: We can probably be smarter about this stuff. For installed apps, 5562 // we can calculate this information at install time once and for all. For 5563 // system apps, we can probably assume that this information doesn't change 5564 // after the first boot scan. As things stand, we do lots of unnecessary work. 5565 5566 // Give ourselves some initial paths; we'll come back for another 5567 // pass once we've determined ABI below. 5568 setNativeLibraryPaths(pkg); 5569 5570 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 5571 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5572 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5573 5574 NativeLibraryHelper.Handle handle = null; 5575 try { 5576 handle = NativeLibraryHelper.Handle.create(scanFile); 5577 // TODO(multiArch): This can be null for apps that didn't go through the 5578 // usual installation process. We can calculate it again, like we 5579 // do during install time. 5580 // 5581 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5582 // unnecessary. 5583 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5584 5585 // Null out the abis so that they can be recalculated. 5586 pkg.applicationInfo.primaryCpuAbi = null; 5587 pkg.applicationInfo.secondaryCpuAbi = null; 5588 if (isMultiArch(pkg.applicationInfo)) { 5589 // Warn if we've set an abiOverride for multi-lib packages.. 5590 // By definition, we need to copy both 32 and 64 bit libraries for 5591 // such packages. 5592 if (pkg.cpuAbiOverride != null 5593 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5594 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5595 } 5596 5597 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5598 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5599 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5600 if (isAsec) { 5601 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5602 } else { 5603 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5604 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5605 useIsaSpecificSubdirs); 5606 } 5607 } 5608 5609 maybeThrowExceptionForMultiArchCopy( 5610 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5611 5612 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5613 if (isAsec) { 5614 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5615 } else { 5616 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5617 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5618 useIsaSpecificSubdirs); 5619 } 5620 } 5621 5622 maybeThrowExceptionForMultiArchCopy( 5623 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5624 5625 if (abi64 >= 0) { 5626 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5627 } 5628 5629 if (abi32 >= 0) { 5630 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5631 if (abi64 >= 0) { 5632 pkg.applicationInfo.secondaryCpuAbi = abi; 5633 } else { 5634 pkg.applicationInfo.primaryCpuAbi = abi; 5635 } 5636 } 5637 } else { 5638 String[] abiList = (cpuAbiOverride != null) ? 5639 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5640 5641 // Enable gross and lame hacks for apps that are built with old 5642 // SDK tools. We must scan their APKs for renderscript bitcode and 5643 // not launch them if it's present. Don't bother checking on devices 5644 // that don't have 64 bit support. 5645 boolean needsRenderScriptOverride = false; 5646 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5647 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5648 abiList = Build.SUPPORTED_32_BIT_ABIS; 5649 needsRenderScriptOverride = true; 5650 } 5651 5652 final int copyRet; 5653 if (isAsec) { 5654 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5655 } else { 5656 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5657 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5658 } 5659 5660 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5661 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5662 "Error unpackaging native libs for app, errorCode=" + copyRet); 5663 } 5664 5665 if (copyRet >= 0) { 5666 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5667 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5668 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5669 } else if (needsRenderScriptOverride) { 5670 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5671 } 5672 } 5673 } catch (IOException ioe) { 5674 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5675 } finally { 5676 IoUtils.closeQuietly(handle); 5677 } 5678 5679 // Now that we've calculated the ABIs and determined if it's an internal app, 5680 // we will go ahead and populate the nativeLibraryPath. 5681 setNativeLibraryPaths(pkg); 5682 5683 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5684 final int[] userIds = sUserManager.getUserIds(); 5685 synchronized (mInstallLock) { 5686 // Create a native library symlink only if we have native libraries 5687 // and if the native libraries are 32 bit libraries. We do not provide 5688 // this symlink for 64 bit libraries. 5689 if (pkg.applicationInfo.primaryCpuAbi != null && 5690 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5691 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5692 for (int userId : userIds) { 5693 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5694 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5695 "Failed linking native library dir (user=" + userId + ")"); 5696 } 5697 } 5698 } 5699 } 5700 } 5701 5702 // This is a special case for the "system" package, where the ABI is 5703 // dictated by the zygote configuration (and init.rc). We should keep track 5704 // of this ABI so that we can deal with "normal" applications that run under 5705 // the same UID correctly. 5706 if (mPlatformPackage == pkg) { 5707 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5708 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5709 } 5710 5711 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5712 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5713 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5714 // Copy the derived override back to the parsed package, so that we can 5715 // update the package settings accordingly. 5716 pkg.cpuAbiOverride = cpuAbiOverride; 5717 5718 if (DEBUG_ABI_SELECTION) { 5719 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5720 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5721 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5722 } 5723 5724 // Push the derived path down into PackageSettings so we know what to 5725 // clean up at uninstall time. 5726 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5727 5728 if (DEBUG_ABI_SELECTION) { 5729 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5730 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5731 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5732 } 5733 5734 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5735 // We don't do this here during boot because we can do it all 5736 // at once after scanning all existing packages. 5737 // 5738 // We also do this *before* we perform dexopt on this package, so that 5739 // we can avoid redundant dexopts, and also to make sure we've got the 5740 // code and package path correct. 5741 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5742 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5743 } 5744 5745 if ((scanFlags & SCAN_NO_DEX) == 0) { 5746 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 5747 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 5748 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5749 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5750 } 5751 } 5752 5753 if (mFactoryTest && pkg.requestedPermissions.contains( 5754 android.Manifest.permission.FACTORY_TEST)) { 5755 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5756 } 5757 5758 ArrayList<PackageParser.Package> clientLibPkgs = null; 5759 5760 // writer 5761 synchronized (mPackages) { 5762 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5763 // Only system apps can add new shared libraries. 5764 if (pkg.libraryNames != null) { 5765 for (int i=0; i<pkg.libraryNames.size(); i++) { 5766 String name = pkg.libraryNames.get(i); 5767 boolean allowed = false; 5768 if (isUpdatedSystemApp(pkg)) { 5769 // New library entries can only be added through the 5770 // system image. This is important to get rid of a lot 5771 // of nasty edge cases: for example if we allowed a non- 5772 // system update of the app to add a library, then uninstalling 5773 // the update would make the library go away, and assumptions 5774 // we made such as through app install filtering would now 5775 // have allowed apps on the device which aren't compatible 5776 // with it. Better to just have the restriction here, be 5777 // conservative, and create many fewer cases that can negatively 5778 // impact the user experience. 5779 final PackageSetting sysPs = mSettings 5780 .getDisabledSystemPkgLPr(pkg.packageName); 5781 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5782 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5783 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5784 allowed = true; 5785 allowed = true; 5786 break; 5787 } 5788 } 5789 } 5790 } else { 5791 allowed = true; 5792 } 5793 if (allowed) { 5794 if (!mSharedLibraries.containsKey(name)) { 5795 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5796 } else if (!name.equals(pkg.packageName)) { 5797 Slog.w(TAG, "Package " + pkg.packageName + " library " 5798 + name + " already exists; skipping"); 5799 } 5800 } else { 5801 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5802 + name + " that is not declared on system image; skipping"); 5803 } 5804 } 5805 if ((scanFlags&SCAN_BOOTING) == 0) { 5806 // If we are not booting, we need to update any applications 5807 // that are clients of our shared library. If we are booting, 5808 // this will all be done once the scan is complete. 5809 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5810 } 5811 } 5812 } 5813 } 5814 5815 // We also need to dexopt any apps that are dependent on this library. Note that 5816 // if these fail, we should abort the install since installing the library will 5817 // result in some apps being broken. 5818 if (clientLibPkgs != null) { 5819 if ((scanFlags & SCAN_NO_DEX) == 0) { 5820 for (int i = 0; i < clientLibPkgs.size(); i++) { 5821 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5822 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 5823 null /* instruction sets */, forceDex, 5824 (scanFlags & SCAN_DEFER_DEX) != 0, false); 5825 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5826 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5827 "scanPackageLI failed to dexopt clientLibPkgs"); 5828 } 5829 } 5830 } 5831 } 5832 5833 // Request the ActivityManager to kill the process(only for existing packages) 5834 // so that we do not end up in a confused state while the user is still using the older 5835 // version of the application while the new one gets installed. 5836 if ((scanFlags & SCAN_REPLACING) != 0) { 5837 killApplication(pkg.applicationInfo.packageName, 5838 pkg.applicationInfo.uid, "update pkg"); 5839 } 5840 5841 // Also need to kill any apps that are dependent on the library. 5842 if (clientLibPkgs != null) { 5843 for (int i=0; i<clientLibPkgs.size(); i++) { 5844 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5845 killApplication(clientPkg.applicationInfo.packageName, 5846 clientPkg.applicationInfo.uid, "update lib"); 5847 } 5848 } 5849 5850 // writer 5851 synchronized (mPackages) { 5852 // We don't expect installation to fail beyond this point 5853 5854 // Add the new setting to mSettings 5855 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5856 // Add the new setting to mPackages 5857 mPackages.put(pkg.applicationInfo.packageName, pkg); 5858 // Make sure we don't accidentally delete its data. 5859 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5860 while (iter.hasNext()) { 5861 PackageCleanItem item = iter.next(); 5862 if (pkgName.equals(item.packageName)) { 5863 iter.remove(); 5864 } 5865 } 5866 5867 // Take care of first install / last update times. 5868 if (currentTime != 0) { 5869 if (pkgSetting.firstInstallTime == 0) { 5870 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5871 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5872 pkgSetting.lastUpdateTime = currentTime; 5873 } 5874 } else if (pkgSetting.firstInstallTime == 0) { 5875 // We need *something*. Take time time stamp of the file. 5876 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5877 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5878 if (scanFileTime != pkgSetting.timeStamp) { 5879 // A package on the system image has changed; consider this 5880 // to be an update. 5881 pkgSetting.lastUpdateTime = scanFileTime; 5882 } 5883 } 5884 5885 // Add the package's KeySets to the global KeySetManagerService 5886 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5887 try { 5888 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5889 if (pkg.mKeySetMapping != null) { 5890 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 5891 if (pkg.mUpgradeKeySets != null) { 5892 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 5893 } 5894 } 5895 } catch (NullPointerException e) { 5896 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5897 } catch (IllegalArgumentException e) { 5898 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5899 } 5900 5901 int N = pkg.providers.size(); 5902 StringBuilder r = null; 5903 int i; 5904 for (i=0; i<N; i++) { 5905 PackageParser.Provider p = pkg.providers.get(i); 5906 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5907 p.info.processName, pkg.applicationInfo.uid); 5908 mProviders.addProvider(p); 5909 p.syncable = p.info.isSyncable; 5910 if (p.info.authority != null) { 5911 String names[] = p.info.authority.split(";"); 5912 p.info.authority = null; 5913 for (int j = 0; j < names.length; j++) { 5914 if (j == 1 && p.syncable) { 5915 // We only want the first authority for a provider to possibly be 5916 // syncable, so if we already added this provider using a different 5917 // authority clear the syncable flag. We copy the provider before 5918 // changing it because the mProviders object contains a reference 5919 // to a provider that we don't want to change. 5920 // Only do this for the second authority since the resulting provider 5921 // object can be the same for all future authorities for this provider. 5922 p = new PackageParser.Provider(p); 5923 p.syncable = false; 5924 } 5925 if (!mProvidersByAuthority.containsKey(names[j])) { 5926 mProvidersByAuthority.put(names[j], p); 5927 if (p.info.authority == null) { 5928 p.info.authority = names[j]; 5929 } else { 5930 p.info.authority = p.info.authority + ";" + names[j]; 5931 } 5932 if (DEBUG_PACKAGE_SCANNING) { 5933 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5934 Log.d(TAG, "Registered content provider: " + names[j] 5935 + ", className = " + p.info.name + ", isSyncable = " 5936 + p.info.isSyncable); 5937 } 5938 } else { 5939 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5940 Slog.w(TAG, "Skipping provider name " + names[j] + 5941 " (in package " + pkg.applicationInfo.packageName + 5942 "): name already used by " 5943 + ((other != null && other.getComponentName() != null) 5944 ? other.getComponentName().getPackageName() : "?")); 5945 } 5946 } 5947 } 5948 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5949 if (r == null) { 5950 r = new StringBuilder(256); 5951 } else { 5952 r.append(' '); 5953 } 5954 r.append(p.info.name); 5955 } 5956 } 5957 if (r != null) { 5958 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5959 } 5960 5961 N = pkg.services.size(); 5962 r = null; 5963 for (i=0; i<N; i++) { 5964 PackageParser.Service s = pkg.services.get(i); 5965 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5966 s.info.processName, pkg.applicationInfo.uid); 5967 mServices.addService(s); 5968 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5969 if (r == null) { 5970 r = new StringBuilder(256); 5971 } else { 5972 r.append(' '); 5973 } 5974 r.append(s.info.name); 5975 } 5976 } 5977 if (r != null) { 5978 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5979 } 5980 5981 N = pkg.receivers.size(); 5982 r = null; 5983 for (i=0; i<N; i++) { 5984 PackageParser.Activity a = pkg.receivers.get(i); 5985 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5986 a.info.processName, pkg.applicationInfo.uid); 5987 mReceivers.addActivity(a, "receiver"); 5988 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5989 if (r == null) { 5990 r = new StringBuilder(256); 5991 } else { 5992 r.append(' '); 5993 } 5994 r.append(a.info.name); 5995 } 5996 } 5997 if (r != null) { 5998 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5999 } 6000 6001 N = pkg.activities.size(); 6002 r = null; 6003 for (i=0; i<N; i++) { 6004 PackageParser.Activity a = pkg.activities.get(i); 6005 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6006 a.info.processName, pkg.applicationInfo.uid); 6007 mActivities.addActivity(a, "activity"); 6008 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6009 if (r == null) { 6010 r = new StringBuilder(256); 6011 } else { 6012 r.append(' '); 6013 } 6014 r.append(a.info.name); 6015 } 6016 } 6017 if (r != null) { 6018 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6019 } 6020 6021 N = pkg.permissionGroups.size(); 6022 r = null; 6023 for (i=0; i<N; i++) { 6024 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6025 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6026 if (cur == null) { 6027 mPermissionGroups.put(pg.info.name, pg); 6028 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6029 if (r == null) { 6030 r = new StringBuilder(256); 6031 } else { 6032 r.append(' '); 6033 } 6034 r.append(pg.info.name); 6035 } 6036 } else { 6037 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6038 + pg.info.packageName + " ignored: original from " 6039 + cur.info.packageName); 6040 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6041 if (r == null) { 6042 r = new StringBuilder(256); 6043 } else { 6044 r.append(' '); 6045 } 6046 r.append("DUP:"); 6047 r.append(pg.info.name); 6048 } 6049 } 6050 } 6051 if (r != null) { 6052 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6053 } 6054 6055 N = pkg.permissions.size(); 6056 r = null; 6057 for (i=0; i<N; i++) { 6058 PackageParser.Permission p = pkg.permissions.get(i); 6059 ArrayMap<String, BasePermission> permissionMap = 6060 p.tree ? mSettings.mPermissionTrees 6061 : mSettings.mPermissions; 6062 p.group = mPermissionGroups.get(p.info.group); 6063 if (p.info.group == null || p.group != null) { 6064 BasePermission bp = permissionMap.get(p.info.name); 6065 6066 // Allow system apps to redefine non-system permissions 6067 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6068 final boolean currentOwnerIsSystem = (bp.perm != null 6069 && isSystemApp(bp.perm.owner)); 6070 if (isSystemApp(p.owner)) { 6071 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6072 // It's a built-in permission and no owner, take ownership now 6073 bp.packageSetting = pkgSetting; 6074 bp.perm = p; 6075 bp.uid = pkg.applicationInfo.uid; 6076 bp.sourcePackage = p.info.packageName; 6077 } else if (!currentOwnerIsSystem) { 6078 String msg = "New decl " + p.owner + " of permission " 6079 + p.info.name + " is system; overriding " + bp.sourcePackage; 6080 reportSettingsProblem(Log.WARN, msg); 6081 bp = null; 6082 } 6083 } 6084 } 6085 6086 if (bp == null) { 6087 bp = new BasePermission(p.info.name, p.info.packageName, 6088 BasePermission.TYPE_NORMAL); 6089 permissionMap.put(p.info.name, bp); 6090 } 6091 6092 if (bp.perm == null) { 6093 if (bp.sourcePackage == null 6094 || bp.sourcePackage.equals(p.info.packageName)) { 6095 BasePermission tree = findPermissionTreeLP(p.info.name); 6096 if (tree == null 6097 || tree.sourcePackage.equals(p.info.packageName)) { 6098 bp.packageSetting = pkgSetting; 6099 bp.perm = p; 6100 bp.uid = pkg.applicationInfo.uid; 6101 bp.sourcePackage = p.info.packageName; 6102 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6103 if (r == null) { 6104 r = new StringBuilder(256); 6105 } else { 6106 r.append(' '); 6107 } 6108 r.append(p.info.name); 6109 } 6110 } else { 6111 Slog.w(TAG, "Permission " + p.info.name + " from package " 6112 + p.info.packageName + " ignored: base tree " 6113 + tree.name + " is from package " 6114 + tree.sourcePackage); 6115 } 6116 } else { 6117 Slog.w(TAG, "Permission " + p.info.name + " from package " 6118 + p.info.packageName + " ignored: original from " 6119 + bp.sourcePackage); 6120 } 6121 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6122 if (r == null) { 6123 r = new StringBuilder(256); 6124 } else { 6125 r.append(' '); 6126 } 6127 r.append("DUP:"); 6128 r.append(p.info.name); 6129 } 6130 if (bp.perm == p) { 6131 bp.protectionLevel = p.info.protectionLevel; 6132 } 6133 } else { 6134 Slog.w(TAG, "Permission " + p.info.name + " from package " 6135 + p.info.packageName + " ignored: no group " 6136 + p.group); 6137 } 6138 } 6139 if (r != null) { 6140 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6141 } 6142 6143 N = pkg.instrumentation.size(); 6144 r = null; 6145 for (i=0; i<N; i++) { 6146 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6147 a.info.packageName = pkg.applicationInfo.packageName; 6148 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6149 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6150 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6151 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6152 a.info.dataDir = pkg.applicationInfo.dataDir; 6153 6154 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6155 // need other information about the application, like the ABI and what not ? 6156 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6157 mInstrumentation.put(a.getComponentName(), a); 6158 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6159 if (r == null) { 6160 r = new StringBuilder(256); 6161 } else { 6162 r.append(' '); 6163 } 6164 r.append(a.info.name); 6165 } 6166 } 6167 if (r != null) { 6168 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6169 } 6170 6171 if (pkg.protectedBroadcasts != null) { 6172 N = pkg.protectedBroadcasts.size(); 6173 for (i=0; i<N; i++) { 6174 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6175 } 6176 } 6177 6178 pkgSetting.setTimeStamp(scanFileTime); 6179 6180 // Create idmap files for pairs of (packages, overlay packages). 6181 // Note: "android", ie framework-res.apk, is handled by native layers. 6182 if (pkg.mOverlayTarget != null) { 6183 // This is an overlay package. 6184 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6185 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6186 mOverlays.put(pkg.mOverlayTarget, 6187 new ArrayMap<String, PackageParser.Package>()); 6188 } 6189 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6190 map.put(pkg.packageName, pkg); 6191 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6192 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6193 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6194 "scanPackageLI failed to createIdmap"); 6195 } 6196 } 6197 } else if (mOverlays.containsKey(pkg.packageName) && 6198 !pkg.packageName.equals("android")) { 6199 // This is a regular package, with one or more known overlay packages. 6200 createIdmapsForPackageLI(pkg); 6201 } 6202 } 6203 6204 return pkg; 6205 } 6206 6207 /** 6208 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6209 * i.e, so that all packages can be run inside a single process if required. 6210 * 6211 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6212 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6213 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6214 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6215 * updating a package that belongs to a shared user. 6216 * 6217 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6218 * adds unnecessary complexity. 6219 */ 6220 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6221 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6222 String requiredInstructionSet = null; 6223 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6224 requiredInstructionSet = VMRuntime.getInstructionSet( 6225 scannedPackage.applicationInfo.primaryCpuAbi); 6226 } 6227 6228 PackageSetting requirer = null; 6229 for (PackageSetting ps : packagesForUser) { 6230 // If packagesForUser contains scannedPackage, we skip it. This will happen 6231 // when scannedPackage is an update of an existing package. Without this check, 6232 // we will never be able to change the ABI of any package belonging to a shared 6233 // user, even if it's compatible with other packages. 6234 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6235 if (ps.primaryCpuAbiString == null) { 6236 continue; 6237 } 6238 6239 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6240 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6241 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6242 // this but there's not much we can do. 6243 String errorMessage = "Instruction set mismatch, " 6244 + ((requirer == null) ? "[caller]" : requirer) 6245 + " requires " + requiredInstructionSet + " whereas " + ps 6246 + " requires " + instructionSet; 6247 Slog.w(TAG, errorMessage); 6248 } 6249 6250 if (requiredInstructionSet == null) { 6251 requiredInstructionSet = instructionSet; 6252 requirer = ps; 6253 } 6254 } 6255 } 6256 6257 if (requiredInstructionSet != null) { 6258 String adjustedAbi; 6259 if (requirer != null) { 6260 // requirer != null implies that either scannedPackage was null or that scannedPackage 6261 // did not require an ABI, in which case we have to adjust scannedPackage to match 6262 // the ABI of the set (which is the same as requirer's ABI) 6263 adjustedAbi = requirer.primaryCpuAbiString; 6264 if (scannedPackage != null) { 6265 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6266 } 6267 } else { 6268 // requirer == null implies that we're updating all ABIs in the set to 6269 // match scannedPackage. 6270 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6271 } 6272 6273 for (PackageSetting ps : packagesForUser) { 6274 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6275 if (ps.primaryCpuAbiString != null) { 6276 continue; 6277 } 6278 6279 ps.primaryCpuAbiString = adjustedAbi; 6280 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6281 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6282 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6283 6284 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6285 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6286 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6287 ps.primaryCpuAbiString = null; 6288 ps.pkg.applicationInfo.primaryCpuAbi = null; 6289 return; 6290 } else { 6291 mInstaller.rmdex(ps.codePathString, 6292 getDexCodeInstructionSet(getPreferredInstructionSet())); 6293 } 6294 } 6295 } 6296 } 6297 } 6298 } 6299 6300 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6301 synchronized (mPackages) { 6302 mResolverReplaced = true; 6303 // Set up information for custom user intent resolution activity. 6304 mResolveActivity.applicationInfo = pkg.applicationInfo; 6305 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6306 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6307 mResolveActivity.processName = pkg.applicationInfo.packageName; 6308 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6309 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6310 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6311 mResolveActivity.theme = 0; 6312 mResolveActivity.exported = true; 6313 mResolveActivity.enabled = true; 6314 mResolveInfo.activityInfo = mResolveActivity; 6315 mResolveInfo.priority = 0; 6316 mResolveInfo.preferredOrder = 0; 6317 mResolveInfo.match = 0; 6318 mResolveComponentName = mCustomResolverComponentName; 6319 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6320 mResolveComponentName); 6321 } 6322 } 6323 6324 private static String calculateBundledApkRoot(final String codePathString) { 6325 final File codePath = new File(codePathString); 6326 final File codeRoot; 6327 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6328 codeRoot = Environment.getRootDirectory(); 6329 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6330 codeRoot = Environment.getOemDirectory(); 6331 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6332 codeRoot = Environment.getVendorDirectory(); 6333 } else { 6334 // Unrecognized code path; take its top real segment as the apk root: 6335 // e.g. /something/app/blah.apk => /something 6336 try { 6337 File f = codePath.getCanonicalFile(); 6338 File parent = f.getParentFile(); // non-null because codePath is a file 6339 File tmp; 6340 while ((tmp = parent.getParentFile()) != null) { 6341 f = parent; 6342 parent = tmp; 6343 } 6344 codeRoot = f; 6345 Slog.w(TAG, "Unrecognized code path " 6346 + codePath + " - using " + codeRoot); 6347 } catch (IOException e) { 6348 // Can't canonicalize the code path -- shenanigans? 6349 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6350 return Environment.getRootDirectory().getPath(); 6351 } 6352 } 6353 return codeRoot.getPath(); 6354 } 6355 6356 /** 6357 * Derive and set the location of native libraries for the given package, 6358 * which varies depending on where and how the package was installed. 6359 */ 6360 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6361 final ApplicationInfo info = pkg.applicationInfo; 6362 final String codePath = pkg.codePath; 6363 final File codeFile = new File(codePath); 6364 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6365 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6366 6367 info.nativeLibraryRootDir = null; 6368 info.nativeLibraryRootRequiresIsa = false; 6369 info.nativeLibraryDir = null; 6370 info.secondaryNativeLibraryDir = null; 6371 6372 if (isApkFile(codeFile)) { 6373 // Monolithic install 6374 if (bundledApp) { 6375 // If "/system/lib64/apkname" exists, assume that is the per-package 6376 // native library directory to use; otherwise use "/system/lib/apkname". 6377 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6378 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6379 getPrimaryInstructionSet(info)); 6380 6381 // This is a bundled system app so choose the path based on the ABI. 6382 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6383 // is just the default path. 6384 final String apkName = deriveCodePathName(codePath); 6385 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6386 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6387 apkName).getAbsolutePath(); 6388 6389 if (info.secondaryCpuAbi != null) { 6390 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6391 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6392 secondaryLibDir, apkName).getAbsolutePath(); 6393 } 6394 } else if (asecApp) { 6395 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6396 .getAbsolutePath(); 6397 } else { 6398 final String apkName = deriveCodePathName(codePath); 6399 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6400 .getAbsolutePath(); 6401 } 6402 6403 info.nativeLibraryRootRequiresIsa = false; 6404 info.nativeLibraryDir = info.nativeLibraryRootDir; 6405 } else { 6406 // Cluster install 6407 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6408 info.nativeLibraryRootRequiresIsa = true; 6409 6410 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6411 getPrimaryInstructionSet(info)).getAbsolutePath(); 6412 6413 if (info.secondaryCpuAbi != null) { 6414 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6415 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6416 } 6417 } 6418 } 6419 6420 /** 6421 * Calculate the abis and roots for a bundled app. These can uniquely 6422 * be determined from the contents of the system partition, i.e whether 6423 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6424 * of this information, and instead assume that the system was built 6425 * sensibly. 6426 */ 6427 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6428 PackageSetting pkgSetting) { 6429 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6430 6431 // If "/system/lib64/apkname" exists, assume that is the per-package 6432 // native library directory to use; otherwise use "/system/lib/apkname". 6433 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6434 setBundledAppAbi(pkg, apkRoot, apkName); 6435 // pkgSetting might be null during rescan following uninstall of updates 6436 // to a bundled app, so accommodate that possibility. The settings in 6437 // that case will be established later from the parsed package. 6438 // 6439 // If the settings aren't null, sync them up with what we've just derived. 6440 // note that apkRoot isn't stored in the package settings. 6441 if (pkgSetting != null) { 6442 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6443 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6444 } 6445 } 6446 6447 /** 6448 * Deduces the ABI of a bundled app and sets the relevant fields on the 6449 * parsed pkg object. 6450 * 6451 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6452 * under which system libraries are installed. 6453 * @param apkName the name of the installed package. 6454 */ 6455 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6456 final File codeFile = new File(pkg.codePath); 6457 6458 final boolean has64BitLibs; 6459 final boolean has32BitLibs; 6460 if (isApkFile(codeFile)) { 6461 // Monolithic install 6462 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6463 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6464 } else { 6465 // Cluster install 6466 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6467 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6468 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6469 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6470 has64BitLibs = (new File(rootDir, isa)).exists(); 6471 } else { 6472 has64BitLibs = false; 6473 } 6474 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6475 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6476 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6477 has32BitLibs = (new File(rootDir, isa)).exists(); 6478 } else { 6479 has32BitLibs = false; 6480 } 6481 } 6482 6483 if (has64BitLibs && !has32BitLibs) { 6484 // The package has 64 bit libs, but not 32 bit libs. Its primary 6485 // ABI should be 64 bit. We can safely assume here that the bundled 6486 // native libraries correspond to the most preferred ABI in the list. 6487 6488 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6489 pkg.applicationInfo.secondaryCpuAbi = null; 6490 } else if (has32BitLibs && !has64BitLibs) { 6491 // The package has 32 bit libs but not 64 bit libs. Its primary 6492 // ABI should be 32 bit. 6493 6494 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6495 pkg.applicationInfo.secondaryCpuAbi = null; 6496 } else if (has32BitLibs && has64BitLibs) { 6497 // The application has both 64 and 32 bit bundled libraries. We check 6498 // here that the app declares multiArch support, and warn if it doesn't. 6499 // 6500 // We will be lenient here and record both ABIs. The primary will be the 6501 // ABI that's higher on the list, i.e, a device that's configured to prefer 6502 // 64 bit apps will see a 64 bit primary ABI, 6503 6504 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6505 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6506 } 6507 6508 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6509 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6510 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6511 } else { 6512 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6513 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6514 } 6515 } else { 6516 pkg.applicationInfo.primaryCpuAbi = null; 6517 pkg.applicationInfo.secondaryCpuAbi = null; 6518 } 6519 } 6520 6521 private void killApplication(String pkgName, int appId, String reason) { 6522 // Request the ActivityManager to kill the process(only for existing packages) 6523 // so that we do not end up in a confused state while the user is still using the older 6524 // version of the application while the new one gets installed. 6525 IActivityManager am = ActivityManagerNative.getDefault(); 6526 if (am != null) { 6527 try { 6528 am.killApplicationWithAppId(pkgName, appId, reason); 6529 } catch (RemoteException e) { 6530 } 6531 } 6532 } 6533 6534 void removePackageLI(PackageSetting ps, boolean chatty) { 6535 if (DEBUG_INSTALL) { 6536 if (chatty) 6537 Log.d(TAG, "Removing package " + ps.name); 6538 } 6539 6540 // writer 6541 synchronized (mPackages) { 6542 mPackages.remove(ps.name); 6543 final PackageParser.Package pkg = ps.pkg; 6544 if (pkg != null) { 6545 cleanPackageDataStructuresLILPw(pkg, chatty); 6546 } 6547 } 6548 } 6549 6550 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6551 if (DEBUG_INSTALL) { 6552 if (chatty) 6553 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6554 } 6555 6556 // writer 6557 synchronized (mPackages) { 6558 mPackages.remove(pkg.applicationInfo.packageName); 6559 cleanPackageDataStructuresLILPw(pkg, chatty); 6560 } 6561 } 6562 6563 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6564 int N = pkg.providers.size(); 6565 StringBuilder r = null; 6566 int i; 6567 for (i=0; i<N; i++) { 6568 PackageParser.Provider p = pkg.providers.get(i); 6569 mProviders.removeProvider(p); 6570 if (p.info.authority == null) { 6571 6572 /* There was another ContentProvider with this authority when 6573 * this app was installed so this authority is null, 6574 * Ignore it as we don't have to unregister the provider. 6575 */ 6576 continue; 6577 } 6578 String names[] = p.info.authority.split(";"); 6579 for (int j = 0; j < names.length; j++) { 6580 if (mProvidersByAuthority.get(names[j]) == p) { 6581 mProvidersByAuthority.remove(names[j]); 6582 if (DEBUG_REMOVE) { 6583 if (chatty) 6584 Log.d(TAG, "Unregistered content provider: " + names[j] 6585 + ", className = " + p.info.name + ", isSyncable = " 6586 + p.info.isSyncable); 6587 } 6588 } 6589 } 6590 if (DEBUG_REMOVE && chatty) { 6591 if (r == null) { 6592 r = new StringBuilder(256); 6593 } else { 6594 r.append(' '); 6595 } 6596 r.append(p.info.name); 6597 } 6598 } 6599 if (r != null) { 6600 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6601 } 6602 6603 N = pkg.services.size(); 6604 r = null; 6605 for (i=0; i<N; i++) { 6606 PackageParser.Service s = pkg.services.get(i); 6607 mServices.removeService(s); 6608 if (chatty) { 6609 if (r == null) { 6610 r = new StringBuilder(256); 6611 } else { 6612 r.append(' '); 6613 } 6614 r.append(s.info.name); 6615 } 6616 } 6617 if (r != null) { 6618 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6619 } 6620 6621 N = pkg.receivers.size(); 6622 r = null; 6623 for (i=0; i<N; i++) { 6624 PackageParser.Activity a = pkg.receivers.get(i); 6625 mReceivers.removeActivity(a, "receiver"); 6626 if (DEBUG_REMOVE && chatty) { 6627 if (r == null) { 6628 r = new StringBuilder(256); 6629 } else { 6630 r.append(' '); 6631 } 6632 r.append(a.info.name); 6633 } 6634 } 6635 if (r != null) { 6636 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6637 } 6638 6639 N = pkg.activities.size(); 6640 r = null; 6641 for (i=0; i<N; i++) { 6642 PackageParser.Activity a = pkg.activities.get(i); 6643 mActivities.removeActivity(a, "activity"); 6644 if (DEBUG_REMOVE && chatty) { 6645 if (r == null) { 6646 r = new StringBuilder(256); 6647 } else { 6648 r.append(' '); 6649 } 6650 r.append(a.info.name); 6651 } 6652 } 6653 if (r != null) { 6654 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6655 } 6656 6657 N = pkg.permissions.size(); 6658 r = null; 6659 for (i=0; i<N; i++) { 6660 PackageParser.Permission p = pkg.permissions.get(i); 6661 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6662 if (bp == null) { 6663 bp = mSettings.mPermissionTrees.get(p.info.name); 6664 } 6665 if (bp != null && bp.perm == p) { 6666 bp.perm = null; 6667 if (DEBUG_REMOVE && chatty) { 6668 if (r == null) { 6669 r = new StringBuilder(256); 6670 } else { 6671 r.append(' '); 6672 } 6673 r.append(p.info.name); 6674 } 6675 } 6676 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6677 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6678 if (appOpPerms != null) { 6679 appOpPerms.remove(pkg.packageName); 6680 } 6681 } 6682 } 6683 if (r != null) { 6684 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6685 } 6686 6687 N = pkg.requestedPermissions.size(); 6688 r = null; 6689 for (i=0; i<N; i++) { 6690 String perm = pkg.requestedPermissions.get(i); 6691 BasePermission bp = mSettings.mPermissions.get(perm); 6692 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6693 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6694 if (appOpPerms != null) { 6695 appOpPerms.remove(pkg.packageName); 6696 if (appOpPerms.isEmpty()) { 6697 mAppOpPermissionPackages.remove(perm); 6698 } 6699 } 6700 } 6701 } 6702 if (r != null) { 6703 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6704 } 6705 6706 N = pkg.instrumentation.size(); 6707 r = null; 6708 for (i=0; i<N; i++) { 6709 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6710 mInstrumentation.remove(a.getComponentName()); 6711 if (DEBUG_REMOVE && chatty) { 6712 if (r == null) { 6713 r = new StringBuilder(256); 6714 } else { 6715 r.append(' '); 6716 } 6717 r.append(a.info.name); 6718 } 6719 } 6720 if (r != null) { 6721 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6722 } 6723 6724 r = null; 6725 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6726 // Only system apps can hold shared libraries. 6727 if (pkg.libraryNames != null) { 6728 for (i=0; i<pkg.libraryNames.size(); i++) { 6729 String name = pkg.libraryNames.get(i); 6730 SharedLibraryEntry cur = mSharedLibraries.get(name); 6731 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6732 mSharedLibraries.remove(name); 6733 if (DEBUG_REMOVE && chatty) { 6734 if (r == null) { 6735 r = new StringBuilder(256); 6736 } else { 6737 r.append(' '); 6738 } 6739 r.append(name); 6740 } 6741 } 6742 } 6743 } 6744 } 6745 if (r != null) { 6746 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6747 } 6748 } 6749 6750 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6751 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6752 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6753 return true; 6754 } 6755 } 6756 return false; 6757 } 6758 6759 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6760 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6761 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6762 6763 private void updatePermissionsLPw(String changingPkg, 6764 PackageParser.Package pkgInfo, int flags) { 6765 // Make sure there are no dangling permission trees. 6766 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6767 while (it.hasNext()) { 6768 final BasePermission bp = it.next(); 6769 if (bp.packageSetting == null) { 6770 // We may not yet have parsed the package, so just see if 6771 // we still know about its settings. 6772 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6773 } 6774 if (bp.packageSetting == null) { 6775 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6776 + " from package " + bp.sourcePackage); 6777 it.remove(); 6778 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6779 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6780 Slog.i(TAG, "Removing old permission tree: " + bp.name 6781 + " from package " + bp.sourcePackage); 6782 flags |= UPDATE_PERMISSIONS_ALL; 6783 it.remove(); 6784 } 6785 } 6786 } 6787 6788 // Make sure all dynamic permissions have been assigned to a package, 6789 // and make sure there are no dangling permissions. 6790 it = mSettings.mPermissions.values().iterator(); 6791 while (it.hasNext()) { 6792 final BasePermission bp = it.next(); 6793 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6794 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6795 + bp.name + " pkg=" + bp.sourcePackage 6796 + " info=" + bp.pendingInfo); 6797 if (bp.packageSetting == null && bp.pendingInfo != null) { 6798 final BasePermission tree = findPermissionTreeLP(bp.name); 6799 if (tree != null && tree.perm != null) { 6800 bp.packageSetting = tree.packageSetting; 6801 bp.perm = new PackageParser.Permission(tree.perm.owner, 6802 new PermissionInfo(bp.pendingInfo)); 6803 bp.perm.info.packageName = tree.perm.info.packageName; 6804 bp.perm.info.name = bp.name; 6805 bp.uid = tree.uid; 6806 } 6807 } 6808 } 6809 if (bp.packageSetting == null) { 6810 // We may not yet have parsed the package, so just see if 6811 // we still know about its settings. 6812 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6813 } 6814 if (bp.packageSetting == null) { 6815 Slog.w(TAG, "Removing dangling permission: " + bp.name 6816 + " from package " + bp.sourcePackage); 6817 it.remove(); 6818 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6819 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6820 Slog.i(TAG, "Removing old permission: " + bp.name 6821 + " from package " + bp.sourcePackage); 6822 flags |= UPDATE_PERMISSIONS_ALL; 6823 it.remove(); 6824 } 6825 } 6826 } 6827 6828 // Now update the permissions for all packages, in particular 6829 // replace the granted permissions of the system packages. 6830 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6831 for (PackageParser.Package pkg : mPackages.values()) { 6832 if (pkg != pkgInfo) { 6833 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6834 changingPkg); 6835 } 6836 } 6837 } 6838 6839 if (pkgInfo != null) { 6840 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6841 } 6842 } 6843 6844 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6845 String packageOfInterest) { 6846 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6847 if (ps == null) { 6848 return; 6849 } 6850 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6851 ArraySet<String> origPermissions = gp.grantedPermissions; 6852 boolean changedPermission = false; 6853 6854 if (replace) { 6855 ps.permissionsFixed = false; 6856 if (gp == ps) { 6857 origPermissions = new ArraySet<String>(gp.grantedPermissions); 6858 gp.grantedPermissions.clear(); 6859 gp.gids = mGlobalGids; 6860 } 6861 } 6862 6863 if (gp.gids == null) { 6864 gp.gids = mGlobalGids; 6865 } 6866 6867 final int N = pkg.requestedPermissions.size(); 6868 for (int i=0; i<N; i++) { 6869 final String name = pkg.requestedPermissions.get(i); 6870 final boolean required = pkg.requestedPermissionsRequired.get(i); 6871 final BasePermission bp = mSettings.mPermissions.get(name); 6872 if (DEBUG_INSTALL) { 6873 if (gp != ps) { 6874 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6875 } 6876 } 6877 6878 if (bp == null || bp.packageSetting == null) { 6879 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6880 Slog.w(TAG, "Unknown permission " + name 6881 + " in package " + pkg.packageName); 6882 } 6883 continue; 6884 } 6885 6886 final String perm = bp.name; 6887 boolean allowed; 6888 boolean allowedSig = false; 6889 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6890 // Keep track of app op permissions. 6891 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6892 if (pkgs == null) { 6893 pkgs = new ArraySet<>(); 6894 mAppOpPermissionPackages.put(bp.name, pkgs); 6895 } 6896 pkgs.add(pkg.packageName); 6897 } 6898 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6899 if (level == PermissionInfo.PROTECTION_NORMAL 6900 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6901 // We grant a normal or dangerous permission if any of the following 6902 // are true: 6903 // 1) The permission is required 6904 // 2) The permission is optional, but was granted in the past 6905 // 3) The permission is optional, but was requested by an 6906 // app in /system (not /data) 6907 // 6908 // Otherwise, reject the permission. 6909 allowed = (required || origPermissions.contains(perm) 6910 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6911 } else if (bp.packageSetting == null) { 6912 // This permission is invalid; skip it. 6913 allowed = false; 6914 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6915 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6916 if (allowed) { 6917 allowedSig = true; 6918 } 6919 } else { 6920 allowed = false; 6921 } 6922 if (DEBUG_INSTALL) { 6923 if (gp != ps) { 6924 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6925 } 6926 } 6927 if (allowed) { 6928 if (!isSystemApp(ps) && ps.permissionsFixed) { 6929 // If this is an existing, non-system package, then 6930 // we can't add any new permissions to it. 6931 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6932 // Except... if this is a permission that was added 6933 // to the platform (note: need to only do this when 6934 // updating the platform). 6935 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6936 } 6937 } 6938 if (allowed) { 6939 if (!gp.grantedPermissions.contains(perm)) { 6940 changedPermission = true; 6941 gp.grantedPermissions.add(perm); 6942 gp.gids = appendInts(gp.gids, bp.gids); 6943 } else if (!ps.haveGids) { 6944 gp.gids = appendInts(gp.gids, bp.gids); 6945 } 6946 } else { 6947 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6948 Slog.w(TAG, "Not granting permission " + perm 6949 + " to package " + pkg.packageName 6950 + " because it was previously installed without"); 6951 } 6952 } 6953 } else { 6954 if (gp.grantedPermissions.remove(perm)) { 6955 changedPermission = true; 6956 gp.gids = removeInts(gp.gids, bp.gids); 6957 Slog.i(TAG, "Un-granting permission " + perm 6958 + " from package " + pkg.packageName 6959 + " (protectionLevel=" + bp.protectionLevel 6960 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6961 + ")"); 6962 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6963 // Don't print warning for app op permissions, since it is fine for them 6964 // not to be granted, there is a UI for the user to decide. 6965 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6966 Slog.w(TAG, "Not granting permission " + perm 6967 + " to package " + pkg.packageName 6968 + " (protectionLevel=" + bp.protectionLevel 6969 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6970 + ")"); 6971 } 6972 } 6973 } 6974 } 6975 6976 if ((changedPermission || replace) && !ps.permissionsFixed && 6977 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6978 // This is the first that we have heard about this package, so the 6979 // permissions we have now selected are fixed until explicitly 6980 // changed. 6981 ps.permissionsFixed = true; 6982 } 6983 ps.haveGids = true; 6984 } 6985 6986 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6987 boolean allowed = false; 6988 final int NP = PackageParser.NEW_PERMISSIONS.length; 6989 for (int ip=0; ip<NP; ip++) { 6990 final PackageParser.NewPermissionInfo npi 6991 = PackageParser.NEW_PERMISSIONS[ip]; 6992 if (npi.name.equals(perm) 6993 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6994 allowed = true; 6995 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6996 + pkg.packageName); 6997 break; 6998 } 6999 } 7000 return allowed; 7001 } 7002 7003 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7004 BasePermission bp, ArraySet<String> origPermissions) { 7005 boolean allowed; 7006 allowed = (compareSignatures( 7007 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7008 == PackageManager.SIGNATURE_MATCH) 7009 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7010 == PackageManager.SIGNATURE_MATCH); 7011 if (!allowed && (bp.protectionLevel 7012 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7013 if (isSystemApp(pkg)) { 7014 // For updated system applications, a system permission 7015 // is granted only if it had been defined by the original application. 7016 if (isUpdatedSystemApp(pkg)) { 7017 final PackageSetting sysPs = mSettings 7018 .getDisabledSystemPkgLPr(pkg.packageName); 7019 final GrantedPermissions origGp = sysPs.sharedUser != null 7020 ? sysPs.sharedUser : sysPs; 7021 7022 if (origGp.grantedPermissions.contains(perm)) { 7023 // If the original was granted this permission, we take 7024 // that grant decision as read and propagate it to the 7025 // update. 7026 if (sysPs.isPrivileged()) { 7027 allowed = true; 7028 } 7029 } else { 7030 // The system apk may have been updated with an older 7031 // version of the one on the data partition, but which 7032 // granted a new system permission that it didn't have 7033 // before. In this case we do want to allow the app to 7034 // now get the new permission if the ancestral apk is 7035 // privileged to get it. 7036 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7037 for (int j=0; 7038 j<sysPs.pkg.requestedPermissions.size(); j++) { 7039 if (perm.equals( 7040 sysPs.pkg.requestedPermissions.get(j))) { 7041 allowed = true; 7042 break; 7043 } 7044 } 7045 } 7046 } 7047 } else { 7048 allowed = isPrivilegedApp(pkg); 7049 } 7050 } 7051 } 7052 if (!allowed && (bp.protectionLevel 7053 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7054 // For development permissions, a development permission 7055 // is granted only if it was already granted. 7056 allowed = origPermissions.contains(perm); 7057 } 7058 return allowed; 7059 } 7060 7061 final class ActivityIntentResolver 7062 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7063 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7064 boolean defaultOnly, int userId) { 7065 if (!sUserManager.exists(userId)) return null; 7066 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7067 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7068 } 7069 7070 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7071 int userId) { 7072 if (!sUserManager.exists(userId)) return null; 7073 mFlags = flags; 7074 return super.queryIntent(intent, resolvedType, 7075 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7076 } 7077 7078 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7079 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7080 if (!sUserManager.exists(userId)) return null; 7081 if (packageActivities == null) { 7082 return null; 7083 } 7084 mFlags = flags; 7085 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7086 final int N = packageActivities.size(); 7087 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7088 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7089 7090 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7091 for (int i = 0; i < N; ++i) { 7092 intentFilters = packageActivities.get(i).intents; 7093 if (intentFilters != null && intentFilters.size() > 0) { 7094 PackageParser.ActivityIntentInfo[] array = 7095 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7096 intentFilters.toArray(array); 7097 listCut.add(array); 7098 } 7099 } 7100 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7101 } 7102 7103 public final void addActivity(PackageParser.Activity a, String type) { 7104 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7105 mActivities.put(a.getComponentName(), a); 7106 if (DEBUG_SHOW_INFO) 7107 Log.v( 7108 TAG, " " + type + " " + 7109 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7110 if (DEBUG_SHOW_INFO) 7111 Log.v(TAG, " Class=" + a.info.name); 7112 final int NI = a.intents.size(); 7113 for (int j=0; j<NI; j++) { 7114 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7115 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7116 intent.setPriority(0); 7117 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7118 + a.className + " with priority > 0, forcing to 0"); 7119 } 7120 if (DEBUG_SHOW_INFO) { 7121 Log.v(TAG, " IntentFilter:"); 7122 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7123 } 7124 if (!intent.debugCheck()) { 7125 Log.w(TAG, "==> For Activity " + a.info.name); 7126 } 7127 addFilter(intent); 7128 } 7129 } 7130 7131 public final void removeActivity(PackageParser.Activity a, String type) { 7132 mActivities.remove(a.getComponentName()); 7133 if (DEBUG_SHOW_INFO) { 7134 Log.v(TAG, " " + type + " " 7135 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7136 : a.info.name) + ":"); 7137 Log.v(TAG, " Class=" + a.info.name); 7138 } 7139 final int NI = a.intents.size(); 7140 for (int j=0; j<NI; j++) { 7141 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7142 if (DEBUG_SHOW_INFO) { 7143 Log.v(TAG, " IntentFilter:"); 7144 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7145 } 7146 removeFilter(intent); 7147 } 7148 } 7149 7150 @Override 7151 protected boolean allowFilterResult( 7152 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7153 ActivityInfo filterAi = filter.activity.info; 7154 for (int i=dest.size()-1; i>=0; i--) { 7155 ActivityInfo destAi = dest.get(i).activityInfo; 7156 if (destAi.name == filterAi.name 7157 && destAi.packageName == filterAi.packageName) { 7158 return false; 7159 } 7160 } 7161 return true; 7162 } 7163 7164 @Override 7165 protected ActivityIntentInfo[] newArray(int size) { 7166 return new ActivityIntentInfo[size]; 7167 } 7168 7169 @Override 7170 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7171 if (!sUserManager.exists(userId)) return true; 7172 PackageParser.Package p = filter.activity.owner; 7173 if (p != null) { 7174 PackageSetting ps = (PackageSetting)p.mExtras; 7175 if (ps != null) { 7176 // System apps are never considered stopped for purposes of 7177 // filtering, because there may be no way for the user to 7178 // actually re-launch them. 7179 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7180 && ps.getStopped(userId); 7181 } 7182 } 7183 return false; 7184 } 7185 7186 @Override 7187 protected boolean isPackageForFilter(String packageName, 7188 PackageParser.ActivityIntentInfo info) { 7189 return packageName.equals(info.activity.owner.packageName); 7190 } 7191 7192 @Override 7193 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7194 int match, int userId) { 7195 if (!sUserManager.exists(userId)) return null; 7196 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7197 return null; 7198 } 7199 final PackageParser.Activity activity = info.activity; 7200 if (mSafeMode && (activity.info.applicationInfo.flags 7201 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7202 return null; 7203 } 7204 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7205 if (ps == null) { 7206 return null; 7207 } 7208 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7209 ps.readUserState(userId), userId); 7210 if (ai == null) { 7211 return null; 7212 } 7213 final ResolveInfo res = new ResolveInfo(); 7214 res.activityInfo = ai; 7215 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7216 res.filter = info; 7217 } 7218 res.priority = info.getPriority(); 7219 res.preferredOrder = activity.owner.mPreferredOrder; 7220 //System.out.println("Result: " + res.activityInfo.className + 7221 // " = " + res.priority); 7222 res.match = match; 7223 res.isDefault = info.hasDefault; 7224 res.labelRes = info.labelRes; 7225 res.nonLocalizedLabel = info.nonLocalizedLabel; 7226 if (userNeedsBadging(userId)) { 7227 res.noResourceId = true; 7228 } else { 7229 res.icon = info.icon; 7230 } 7231 res.system = isSystemApp(res.activityInfo.applicationInfo); 7232 return res; 7233 } 7234 7235 @Override 7236 protected void sortResults(List<ResolveInfo> results) { 7237 Collections.sort(results, mResolvePrioritySorter); 7238 } 7239 7240 @Override 7241 protected void dumpFilter(PrintWriter out, String prefix, 7242 PackageParser.ActivityIntentInfo filter) { 7243 out.print(prefix); out.print( 7244 Integer.toHexString(System.identityHashCode(filter.activity))); 7245 out.print(' '); 7246 filter.activity.printComponentShortName(out); 7247 out.print(" filter "); 7248 out.println(Integer.toHexString(System.identityHashCode(filter))); 7249 } 7250 7251 @Override 7252 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7253 return filter.activity; 7254 } 7255 7256 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7257 PackageParser.Activity activity = (PackageParser.Activity)label; 7258 out.print(prefix); out.print( 7259 Integer.toHexString(System.identityHashCode(activity))); 7260 out.print(' '); 7261 activity.printComponentShortName(out); 7262 if (count > 1) { 7263 out.print(" ("); out.print(count); out.print(" filters)"); 7264 } 7265 out.println(); 7266 } 7267 7268// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7269// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7270// final List<ResolveInfo> retList = Lists.newArrayList(); 7271// while (i.hasNext()) { 7272// final ResolveInfo resolveInfo = i.next(); 7273// if (isEnabledLP(resolveInfo.activityInfo)) { 7274// retList.add(resolveInfo); 7275// } 7276// } 7277// return retList; 7278// } 7279 7280 // Keys are String (activity class name), values are Activity. 7281 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7282 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7283 private int mFlags; 7284 } 7285 7286 private final class ServiceIntentResolver 7287 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7288 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7289 boolean defaultOnly, int userId) { 7290 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7291 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7292 } 7293 7294 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7295 int userId) { 7296 if (!sUserManager.exists(userId)) return null; 7297 mFlags = flags; 7298 return super.queryIntent(intent, resolvedType, 7299 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7300 } 7301 7302 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7303 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7304 if (!sUserManager.exists(userId)) return null; 7305 if (packageServices == null) { 7306 return null; 7307 } 7308 mFlags = flags; 7309 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7310 final int N = packageServices.size(); 7311 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7312 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7313 7314 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7315 for (int i = 0; i < N; ++i) { 7316 intentFilters = packageServices.get(i).intents; 7317 if (intentFilters != null && intentFilters.size() > 0) { 7318 PackageParser.ServiceIntentInfo[] array = 7319 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7320 intentFilters.toArray(array); 7321 listCut.add(array); 7322 } 7323 } 7324 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7325 } 7326 7327 public final void addService(PackageParser.Service s) { 7328 mServices.put(s.getComponentName(), s); 7329 if (DEBUG_SHOW_INFO) { 7330 Log.v(TAG, " " 7331 + (s.info.nonLocalizedLabel != null 7332 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7333 Log.v(TAG, " Class=" + s.info.name); 7334 } 7335 final int NI = s.intents.size(); 7336 int j; 7337 for (j=0; j<NI; j++) { 7338 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7339 if (DEBUG_SHOW_INFO) { 7340 Log.v(TAG, " IntentFilter:"); 7341 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7342 } 7343 if (!intent.debugCheck()) { 7344 Log.w(TAG, "==> For Service " + s.info.name); 7345 } 7346 addFilter(intent); 7347 } 7348 } 7349 7350 public final void removeService(PackageParser.Service s) { 7351 mServices.remove(s.getComponentName()); 7352 if (DEBUG_SHOW_INFO) { 7353 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7354 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7355 Log.v(TAG, " Class=" + s.info.name); 7356 } 7357 final int NI = s.intents.size(); 7358 int j; 7359 for (j=0; j<NI; j++) { 7360 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7361 if (DEBUG_SHOW_INFO) { 7362 Log.v(TAG, " IntentFilter:"); 7363 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7364 } 7365 removeFilter(intent); 7366 } 7367 } 7368 7369 @Override 7370 protected boolean allowFilterResult( 7371 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7372 ServiceInfo filterSi = filter.service.info; 7373 for (int i=dest.size()-1; i>=0; i--) { 7374 ServiceInfo destAi = dest.get(i).serviceInfo; 7375 if (destAi.name == filterSi.name 7376 && destAi.packageName == filterSi.packageName) { 7377 return false; 7378 } 7379 } 7380 return true; 7381 } 7382 7383 @Override 7384 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7385 return new PackageParser.ServiceIntentInfo[size]; 7386 } 7387 7388 @Override 7389 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7390 if (!sUserManager.exists(userId)) return true; 7391 PackageParser.Package p = filter.service.owner; 7392 if (p != null) { 7393 PackageSetting ps = (PackageSetting)p.mExtras; 7394 if (ps != null) { 7395 // System apps are never considered stopped for purposes of 7396 // filtering, because there may be no way for the user to 7397 // actually re-launch them. 7398 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7399 && ps.getStopped(userId); 7400 } 7401 } 7402 return false; 7403 } 7404 7405 @Override 7406 protected boolean isPackageForFilter(String packageName, 7407 PackageParser.ServiceIntentInfo info) { 7408 return packageName.equals(info.service.owner.packageName); 7409 } 7410 7411 @Override 7412 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7413 int match, int userId) { 7414 if (!sUserManager.exists(userId)) return null; 7415 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7416 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7417 return null; 7418 } 7419 final PackageParser.Service service = info.service; 7420 if (mSafeMode && (service.info.applicationInfo.flags 7421 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7422 return null; 7423 } 7424 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7425 if (ps == null) { 7426 return null; 7427 } 7428 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7429 ps.readUserState(userId), userId); 7430 if (si == null) { 7431 return null; 7432 } 7433 final ResolveInfo res = new ResolveInfo(); 7434 res.serviceInfo = si; 7435 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7436 res.filter = filter; 7437 } 7438 res.priority = info.getPriority(); 7439 res.preferredOrder = service.owner.mPreferredOrder; 7440 //System.out.println("Result: " + res.activityInfo.className + 7441 // " = " + res.priority); 7442 res.match = match; 7443 res.isDefault = info.hasDefault; 7444 res.labelRes = info.labelRes; 7445 res.nonLocalizedLabel = info.nonLocalizedLabel; 7446 res.icon = info.icon; 7447 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7448 return res; 7449 } 7450 7451 @Override 7452 protected void sortResults(List<ResolveInfo> results) { 7453 Collections.sort(results, mResolvePrioritySorter); 7454 } 7455 7456 @Override 7457 protected void dumpFilter(PrintWriter out, String prefix, 7458 PackageParser.ServiceIntentInfo filter) { 7459 out.print(prefix); out.print( 7460 Integer.toHexString(System.identityHashCode(filter.service))); 7461 out.print(' '); 7462 filter.service.printComponentShortName(out); 7463 out.print(" filter "); 7464 out.println(Integer.toHexString(System.identityHashCode(filter))); 7465 } 7466 7467 @Override 7468 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 7469 return filter.service; 7470 } 7471 7472 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7473 PackageParser.Service service = (PackageParser.Service)label; 7474 out.print(prefix); out.print( 7475 Integer.toHexString(System.identityHashCode(service))); 7476 out.print(' '); 7477 service.printComponentShortName(out); 7478 if (count > 1) { 7479 out.print(" ("); out.print(count); out.print(" filters)"); 7480 } 7481 out.println(); 7482 } 7483 7484// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7485// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7486// final List<ResolveInfo> retList = Lists.newArrayList(); 7487// while (i.hasNext()) { 7488// final ResolveInfo resolveInfo = (ResolveInfo) i; 7489// if (isEnabledLP(resolveInfo.serviceInfo)) { 7490// retList.add(resolveInfo); 7491// } 7492// } 7493// return retList; 7494// } 7495 7496 // Keys are String (activity class name), values are Activity. 7497 private final ArrayMap<ComponentName, PackageParser.Service> mServices 7498 = new ArrayMap<ComponentName, PackageParser.Service>(); 7499 private int mFlags; 7500 }; 7501 7502 private final class ProviderIntentResolver 7503 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7504 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7505 boolean defaultOnly, int userId) { 7506 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7507 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7508 } 7509 7510 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7511 int userId) { 7512 if (!sUserManager.exists(userId)) 7513 return null; 7514 mFlags = flags; 7515 return super.queryIntent(intent, resolvedType, 7516 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7517 } 7518 7519 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7520 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7521 if (!sUserManager.exists(userId)) 7522 return null; 7523 if (packageProviders == null) { 7524 return null; 7525 } 7526 mFlags = flags; 7527 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7528 final int N = packageProviders.size(); 7529 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7530 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7531 7532 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7533 for (int i = 0; i < N; ++i) { 7534 intentFilters = packageProviders.get(i).intents; 7535 if (intentFilters != null && intentFilters.size() > 0) { 7536 PackageParser.ProviderIntentInfo[] array = 7537 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7538 intentFilters.toArray(array); 7539 listCut.add(array); 7540 } 7541 } 7542 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7543 } 7544 7545 public final void addProvider(PackageParser.Provider p) { 7546 if (mProviders.containsKey(p.getComponentName())) { 7547 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7548 return; 7549 } 7550 7551 mProviders.put(p.getComponentName(), p); 7552 if (DEBUG_SHOW_INFO) { 7553 Log.v(TAG, " " 7554 + (p.info.nonLocalizedLabel != null 7555 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7556 Log.v(TAG, " Class=" + p.info.name); 7557 } 7558 final int NI = p.intents.size(); 7559 int j; 7560 for (j = 0; j < NI; j++) { 7561 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7562 if (DEBUG_SHOW_INFO) { 7563 Log.v(TAG, " IntentFilter:"); 7564 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7565 } 7566 if (!intent.debugCheck()) { 7567 Log.w(TAG, "==> For Provider " + p.info.name); 7568 } 7569 addFilter(intent); 7570 } 7571 } 7572 7573 public final void removeProvider(PackageParser.Provider p) { 7574 mProviders.remove(p.getComponentName()); 7575 if (DEBUG_SHOW_INFO) { 7576 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7577 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7578 Log.v(TAG, " Class=" + p.info.name); 7579 } 7580 final int NI = p.intents.size(); 7581 int j; 7582 for (j = 0; j < NI; j++) { 7583 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7584 if (DEBUG_SHOW_INFO) { 7585 Log.v(TAG, " IntentFilter:"); 7586 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7587 } 7588 removeFilter(intent); 7589 } 7590 } 7591 7592 @Override 7593 protected boolean allowFilterResult( 7594 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7595 ProviderInfo filterPi = filter.provider.info; 7596 for (int i = dest.size() - 1; i >= 0; i--) { 7597 ProviderInfo destPi = dest.get(i).providerInfo; 7598 if (destPi.name == filterPi.name 7599 && destPi.packageName == filterPi.packageName) { 7600 return false; 7601 } 7602 } 7603 return true; 7604 } 7605 7606 @Override 7607 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7608 return new PackageParser.ProviderIntentInfo[size]; 7609 } 7610 7611 @Override 7612 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7613 if (!sUserManager.exists(userId)) 7614 return true; 7615 PackageParser.Package p = filter.provider.owner; 7616 if (p != null) { 7617 PackageSetting ps = (PackageSetting) p.mExtras; 7618 if (ps != null) { 7619 // System apps are never considered stopped for purposes of 7620 // filtering, because there may be no way for the user to 7621 // actually re-launch them. 7622 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7623 && ps.getStopped(userId); 7624 } 7625 } 7626 return false; 7627 } 7628 7629 @Override 7630 protected boolean isPackageForFilter(String packageName, 7631 PackageParser.ProviderIntentInfo info) { 7632 return packageName.equals(info.provider.owner.packageName); 7633 } 7634 7635 @Override 7636 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7637 int match, int userId) { 7638 if (!sUserManager.exists(userId)) 7639 return null; 7640 final PackageParser.ProviderIntentInfo info = filter; 7641 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7642 return null; 7643 } 7644 final PackageParser.Provider provider = info.provider; 7645 if (mSafeMode && (provider.info.applicationInfo.flags 7646 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7647 return null; 7648 } 7649 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7650 if (ps == null) { 7651 return null; 7652 } 7653 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7654 ps.readUserState(userId), userId); 7655 if (pi == null) { 7656 return null; 7657 } 7658 final ResolveInfo res = new ResolveInfo(); 7659 res.providerInfo = pi; 7660 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7661 res.filter = filter; 7662 } 7663 res.priority = info.getPriority(); 7664 res.preferredOrder = provider.owner.mPreferredOrder; 7665 res.match = match; 7666 res.isDefault = info.hasDefault; 7667 res.labelRes = info.labelRes; 7668 res.nonLocalizedLabel = info.nonLocalizedLabel; 7669 res.icon = info.icon; 7670 res.system = isSystemApp(res.providerInfo.applicationInfo); 7671 return res; 7672 } 7673 7674 @Override 7675 protected void sortResults(List<ResolveInfo> results) { 7676 Collections.sort(results, mResolvePrioritySorter); 7677 } 7678 7679 @Override 7680 protected void dumpFilter(PrintWriter out, String prefix, 7681 PackageParser.ProviderIntentInfo filter) { 7682 out.print(prefix); 7683 out.print( 7684 Integer.toHexString(System.identityHashCode(filter.provider))); 7685 out.print(' '); 7686 filter.provider.printComponentShortName(out); 7687 out.print(" filter "); 7688 out.println(Integer.toHexString(System.identityHashCode(filter))); 7689 } 7690 7691 @Override 7692 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 7693 return filter.provider; 7694 } 7695 7696 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7697 PackageParser.Provider provider = (PackageParser.Provider)label; 7698 out.print(prefix); out.print( 7699 Integer.toHexString(System.identityHashCode(provider))); 7700 out.print(' '); 7701 provider.printComponentShortName(out); 7702 if (count > 1) { 7703 out.print(" ("); out.print(count); out.print(" filters)"); 7704 } 7705 out.println(); 7706 } 7707 7708 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 7709 = new ArrayMap<ComponentName, PackageParser.Provider>(); 7710 private int mFlags; 7711 }; 7712 7713 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7714 new Comparator<ResolveInfo>() { 7715 public int compare(ResolveInfo r1, ResolveInfo r2) { 7716 int v1 = r1.priority; 7717 int v2 = r2.priority; 7718 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7719 if (v1 != v2) { 7720 return (v1 > v2) ? -1 : 1; 7721 } 7722 v1 = r1.preferredOrder; 7723 v2 = r2.preferredOrder; 7724 if (v1 != v2) { 7725 return (v1 > v2) ? -1 : 1; 7726 } 7727 if (r1.isDefault != r2.isDefault) { 7728 return r1.isDefault ? -1 : 1; 7729 } 7730 v1 = r1.match; 7731 v2 = r2.match; 7732 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7733 if (v1 != v2) { 7734 return (v1 > v2) ? -1 : 1; 7735 } 7736 if (r1.system != r2.system) { 7737 return r1.system ? -1 : 1; 7738 } 7739 return 0; 7740 } 7741 }; 7742 7743 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7744 new Comparator<ProviderInfo>() { 7745 public int compare(ProviderInfo p1, ProviderInfo p2) { 7746 final int v1 = p1.initOrder; 7747 final int v2 = p2.initOrder; 7748 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7749 } 7750 }; 7751 7752 static final void sendPackageBroadcast(String action, String pkg, 7753 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7754 int[] userIds) { 7755 IActivityManager am = ActivityManagerNative.getDefault(); 7756 if (am != null) { 7757 try { 7758 if (userIds == null) { 7759 userIds = am.getRunningUserIds(); 7760 } 7761 for (int id : userIds) { 7762 final Intent intent = new Intent(action, 7763 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7764 if (extras != null) { 7765 intent.putExtras(extras); 7766 } 7767 if (targetPkg != null) { 7768 intent.setPackage(targetPkg); 7769 } 7770 // Modify the UID when posting to other users 7771 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7772 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7773 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7774 intent.putExtra(Intent.EXTRA_UID, uid); 7775 } 7776 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7777 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7778 if (DEBUG_BROADCASTS) { 7779 RuntimeException here = new RuntimeException("here"); 7780 here.fillInStackTrace(); 7781 Slog.d(TAG, "Sending to user " + id + ": " 7782 + intent.toShortString(false, true, false, false) 7783 + " " + intent.getExtras(), here); 7784 } 7785 am.broadcastIntent(null, intent, null, finishedReceiver, 7786 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7787 finishedReceiver != null, false, id); 7788 } 7789 } catch (RemoteException ex) { 7790 } 7791 } 7792 } 7793 7794 /** 7795 * Check if the external storage media is available. This is true if there 7796 * is a mounted external storage medium or if the external storage is 7797 * emulated. 7798 */ 7799 private boolean isExternalMediaAvailable() { 7800 return mMediaMounted || Environment.isExternalStorageEmulated(); 7801 } 7802 7803 @Override 7804 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7805 // writer 7806 synchronized (mPackages) { 7807 if (!isExternalMediaAvailable()) { 7808 // If the external storage is no longer mounted at this point, 7809 // the caller may not have been able to delete all of this 7810 // packages files and can not delete any more. Bail. 7811 return null; 7812 } 7813 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7814 if (lastPackage != null) { 7815 pkgs.remove(lastPackage); 7816 } 7817 if (pkgs.size() > 0) { 7818 return pkgs.get(0); 7819 } 7820 } 7821 return null; 7822 } 7823 7824 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7825 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7826 userId, andCode ? 1 : 0, packageName); 7827 if (mSystemReady) { 7828 msg.sendToTarget(); 7829 } else { 7830 if (mPostSystemReadyMessages == null) { 7831 mPostSystemReadyMessages = new ArrayList<>(); 7832 } 7833 mPostSystemReadyMessages.add(msg); 7834 } 7835 } 7836 7837 void startCleaningPackages() { 7838 // reader 7839 synchronized (mPackages) { 7840 if (!isExternalMediaAvailable()) { 7841 return; 7842 } 7843 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7844 return; 7845 } 7846 } 7847 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7848 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7849 IActivityManager am = ActivityManagerNative.getDefault(); 7850 if (am != null) { 7851 try { 7852 am.startService(null, intent, null, UserHandle.USER_OWNER); 7853 } catch (RemoteException e) { 7854 } 7855 } 7856 } 7857 7858 @Override 7859 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7860 int installFlags, String installerPackageName, VerificationParams verificationParams, 7861 String packageAbiOverride) { 7862 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7863 packageAbiOverride, UserHandle.getCallingUserId()); 7864 } 7865 7866 @Override 7867 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7868 int installFlags, String installerPackageName, VerificationParams verificationParams, 7869 String packageAbiOverride, int userId) { 7870 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 7871 7872 final int callingUid = Binder.getCallingUid(); 7873 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 7874 7875 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7876 try { 7877 if (observer != null) { 7878 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7879 } 7880 } catch (RemoteException re) { 7881 } 7882 return; 7883 } 7884 7885 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 7886 installFlags |= PackageManager.INSTALL_FROM_ADB; 7887 7888 } else { 7889 // Caller holds INSTALL_PACKAGES permission, so we're less strict 7890 // about installerPackageName. 7891 7892 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 7893 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 7894 } 7895 7896 UserHandle user; 7897 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7898 user = UserHandle.ALL; 7899 } else { 7900 user = new UserHandle(userId); 7901 } 7902 7903 verificationParams.setInstallerUid(callingUid); 7904 7905 final File originFile = new File(originPath); 7906 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7907 7908 final Message msg = mHandler.obtainMessage(INIT_COPY); 7909 msg.obj = new InstallParams(origin, observer, installFlags, 7910 installerPackageName, verificationParams, user, packageAbiOverride); 7911 mHandler.sendMessage(msg); 7912 } 7913 7914 void installStage(String packageName, File stagedDir, String stagedCid, 7915 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7916 String installerPackageName, int installerUid, UserHandle user) { 7917 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7918 params.referrerUri, installerUid, null); 7919 7920 final OriginInfo origin; 7921 if (stagedDir != null) { 7922 origin = OriginInfo.fromStagedFile(stagedDir); 7923 } else { 7924 origin = OriginInfo.fromStagedContainer(stagedCid); 7925 } 7926 7927 final Message msg = mHandler.obtainMessage(INIT_COPY); 7928 msg.obj = new InstallParams(origin, observer, params.installFlags, 7929 installerPackageName, verifParams, user, params.abiOverride); 7930 mHandler.sendMessage(msg); 7931 } 7932 7933 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7934 Bundle extras = new Bundle(1); 7935 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7936 7937 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7938 packageName, extras, null, null, new int[] {userId}); 7939 try { 7940 IActivityManager am = ActivityManagerNative.getDefault(); 7941 final boolean isSystem = 7942 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7943 if (isSystem && am.isUserRunning(userId, false)) { 7944 // The just-installed/enabled app is bundled on the system, so presumed 7945 // to be able to run automatically without needing an explicit launch. 7946 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7947 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7948 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7949 .setPackage(packageName); 7950 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7951 android.app.AppOpsManager.OP_NONE, false, false, userId); 7952 } 7953 } catch (RemoteException e) { 7954 // shouldn't happen 7955 Slog.w(TAG, "Unable to bootstrap installed package", e); 7956 } 7957 } 7958 7959 @Override 7960 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7961 int userId) { 7962 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7963 PackageSetting pkgSetting; 7964 final int uid = Binder.getCallingUid(); 7965 enforceCrossUserPermission(uid, userId, true, true, 7966 "setApplicationHiddenSetting for user " + userId); 7967 7968 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7969 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7970 return false; 7971 } 7972 7973 long callingId = Binder.clearCallingIdentity(); 7974 try { 7975 boolean sendAdded = false; 7976 boolean sendRemoved = false; 7977 // writer 7978 synchronized (mPackages) { 7979 pkgSetting = mSettings.mPackages.get(packageName); 7980 if (pkgSetting == null) { 7981 return false; 7982 } 7983 if (pkgSetting.getHidden(userId) != hidden) { 7984 pkgSetting.setHidden(hidden, userId); 7985 mSettings.writePackageRestrictionsLPr(userId); 7986 if (hidden) { 7987 sendRemoved = true; 7988 } else { 7989 sendAdded = true; 7990 } 7991 } 7992 } 7993 if (sendAdded) { 7994 sendPackageAddedForUser(packageName, pkgSetting, userId); 7995 return true; 7996 } 7997 if (sendRemoved) { 7998 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7999 "hiding pkg"); 8000 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8001 } 8002 } finally { 8003 Binder.restoreCallingIdentity(callingId); 8004 } 8005 return false; 8006 } 8007 8008 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8009 int userId) { 8010 final PackageRemovedInfo info = new PackageRemovedInfo(); 8011 info.removedPackage = packageName; 8012 info.removedUsers = new int[] {userId}; 8013 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8014 info.sendBroadcast(false, false, false); 8015 } 8016 8017 /** 8018 * Returns true if application is not found or there was an error. Otherwise it returns 8019 * the hidden state of the package for the given user. 8020 */ 8021 @Override 8022 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8023 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8024 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8025 false, "getApplicationHidden for user " + userId); 8026 PackageSetting pkgSetting; 8027 long callingId = Binder.clearCallingIdentity(); 8028 try { 8029 // writer 8030 synchronized (mPackages) { 8031 pkgSetting = mSettings.mPackages.get(packageName); 8032 if (pkgSetting == null) { 8033 return true; 8034 } 8035 return pkgSetting.getHidden(userId); 8036 } 8037 } finally { 8038 Binder.restoreCallingIdentity(callingId); 8039 } 8040 } 8041 8042 /** 8043 * @hide 8044 */ 8045 @Override 8046 public int installExistingPackageAsUser(String packageName, int userId) { 8047 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8048 null); 8049 PackageSetting pkgSetting; 8050 final int uid = Binder.getCallingUid(); 8051 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8052 + userId); 8053 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8054 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8055 } 8056 8057 long callingId = Binder.clearCallingIdentity(); 8058 try { 8059 boolean sendAdded = false; 8060 Bundle extras = new Bundle(1); 8061 8062 // writer 8063 synchronized (mPackages) { 8064 pkgSetting = mSettings.mPackages.get(packageName); 8065 if (pkgSetting == null) { 8066 return PackageManager.INSTALL_FAILED_INVALID_URI; 8067 } 8068 if (!pkgSetting.getInstalled(userId)) { 8069 pkgSetting.setInstalled(true, userId); 8070 pkgSetting.setHidden(false, userId); 8071 mSettings.writePackageRestrictionsLPr(userId); 8072 sendAdded = true; 8073 } 8074 } 8075 8076 if (sendAdded) { 8077 sendPackageAddedForUser(packageName, pkgSetting, userId); 8078 } 8079 } finally { 8080 Binder.restoreCallingIdentity(callingId); 8081 } 8082 8083 return PackageManager.INSTALL_SUCCEEDED; 8084 } 8085 8086 boolean isUserRestricted(int userId, String restrictionKey) { 8087 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8088 if (restrictions.getBoolean(restrictionKey, false)) { 8089 Log.w(TAG, "User is restricted: " + restrictionKey); 8090 return true; 8091 } 8092 return false; 8093 } 8094 8095 @Override 8096 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8097 mContext.enforceCallingOrSelfPermission( 8098 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8099 "Only package verification agents can verify applications"); 8100 8101 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8102 final PackageVerificationResponse response = new PackageVerificationResponse( 8103 verificationCode, Binder.getCallingUid()); 8104 msg.arg1 = id; 8105 msg.obj = response; 8106 mHandler.sendMessage(msg); 8107 } 8108 8109 @Override 8110 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8111 long millisecondsToDelay) { 8112 mContext.enforceCallingOrSelfPermission( 8113 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8114 "Only package verification agents can extend verification timeouts"); 8115 8116 final PackageVerificationState state = mPendingVerification.get(id); 8117 final PackageVerificationResponse response = new PackageVerificationResponse( 8118 verificationCodeAtTimeout, Binder.getCallingUid()); 8119 8120 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8121 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8122 } 8123 if (millisecondsToDelay < 0) { 8124 millisecondsToDelay = 0; 8125 } 8126 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8127 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8128 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8129 } 8130 8131 if ((state != null) && !state.timeoutExtended()) { 8132 state.extendTimeout(); 8133 8134 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8135 msg.arg1 = id; 8136 msg.obj = response; 8137 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8138 } 8139 } 8140 8141 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8142 int verificationCode, UserHandle user) { 8143 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8144 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8145 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8146 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8147 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8148 8149 mContext.sendBroadcastAsUser(intent, user, 8150 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8151 } 8152 8153 private ComponentName matchComponentForVerifier(String packageName, 8154 List<ResolveInfo> receivers) { 8155 ActivityInfo targetReceiver = null; 8156 8157 final int NR = receivers.size(); 8158 for (int i = 0; i < NR; i++) { 8159 final ResolveInfo info = receivers.get(i); 8160 if (info.activityInfo == null) { 8161 continue; 8162 } 8163 8164 if (packageName.equals(info.activityInfo.packageName)) { 8165 targetReceiver = info.activityInfo; 8166 break; 8167 } 8168 } 8169 8170 if (targetReceiver == null) { 8171 return null; 8172 } 8173 8174 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8175 } 8176 8177 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8178 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8179 if (pkgInfo.verifiers.length == 0) { 8180 return null; 8181 } 8182 8183 final int N = pkgInfo.verifiers.length; 8184 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8185 for (int i = 0; i < N; i++) { 8186 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8187 8188 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8189 receivers); 8190 if (comp == null) { 8191 continue; 8192 } 8193 8194 final int verifierUid = getUidForVerifier(verifierInfo); 8195 if (verifierUid == -1) { 8196 continue; 8197 } 8198 8199 if (DEBUG_VERIFY) { 8200 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8201 + " with the correct signature"); 8202 } 8203 sufficientVerifiers.add(comp); 8204 verificationState.addSufficientVerifier(verifierUid); 8205 } 8206 8207 return sufficientVerifiers; 8208 } 8209 8210 private int getUidForVerifier(VerifierInfo verifierInfo) { 8211 synchronized (mPackages) { 8212 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8213 if (pkg == null) { 8214 return -1; 8215 } else if (pkg.mSignatures.length != 1) { 8216 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8217 + " has more than one signature; ignoring"); 8218 return -1; 8219 } 8220 8221 /* 8222 * If the public key of the package's signature does not match 8223 * our expected public key, then this is a different package and 8224 * we should skip. 8225 */ 8226 8227 final byte[] expectedPublicKey; 8228 try { 8229 final Signature verifierSig = pkg.mSignatures[0]; 8230 final PublicKey publicKey = verifierSig.getPublicKey(); 8231 expectedPublicKey = publicKey.getEncoded(); 8232 } catch (CertificateException e) { 8233 return -1; 8234 } 8235 8236 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8237 8238 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8239 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8240 + " does not have the expected public key; ignoring"); 8241 return -1; 8242 } 8243 8244 return pkg.applicationInfo.uid; 8245 } 8246 } 8247 8248 @Override 8249 public void finishPackageInstall(int token) { 8250 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8251 8252 if (DEBUG_INSTALL) { 8253 Slog.v(TAG, "BM finishing package install for " + token); 8254 } 8255 8256 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8257 mHandler.sendMessage(msg); 8258 } 8259 8260 /** 8261 * Get the verification agent timeout. 8262 * 8263 * @return verification timeout in milliseconds 8264 */ 8265 private long getVerificationTimeout() { 8266 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8267 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8268 DEFAULT_VERIFICATION_TIMEOUT); 8269 } 8270 8271 /** 8272 * Get the default verification agent response code. 8273 * 8274 * @return default verification response code 8275 */ 8276 private int getDefaultVerificationResponse() { 8277 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8278 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8279 DEFAULT_VERIFICATION_RESPONSE); 8280 } 8281 8282 /** 8283 * Check whether or not package verification has been enabled. 8284 * 8285 * @return true if verification should be performed 8286 */ 8287 private boolean isVerificationEnabled(int userId, int installFlags) { 8288 if (!DEFAULT_VERIFY_ENABLE) { 8289 return false; 8290 } 8291 8292 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8293 8294 // Check if installing from ADB 8295 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8296 // Do not run verification in a test harness environment 8297 if (ActivityManager.isRunningInTestHarness()) { 8298 return false; 8299 } 8300 if (ensureVerifyAppsEnabled) { 8301 return true; 8302 } 8303 // Check if the developer does not want package verification for ADB installs 8304 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8305 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8306 return false; 8307 } 8308 } 8309 8310 if (ensureVerifyAppsEnabled) { 8311 return true; 8312 } 8313 8314 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8315 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8316 } 8317 8318 /** 8319 * Get the "allow unknown sources" setting. 8320 * 8321 * @return the current "allow unknown sources" setting 8322 */ 8323 private int getUnknownSourcesSettings() { 8324 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8325 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8326 -1); 8327 } 8328 8329 @Override 8330 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8331 final int uid = Binder.getCallingUid(); 8332 // writer 8333 synchronized (mPackages) { 8334 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8335 if (targetPackageSetting == null) { 8336 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8337 } 8338 8339 PackageSetting installerPackageSetting; 8340 if (installerPackageName != null) { 8341 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8342 if (installerPackageSetting == null) { 8343 throw new IllegalArgumentException("Unknown installer package: " 8344 + installerPackageName); 8345 } 8346 } else { 8347 installerPackageSetting = null; 8348 } 8349 8350 Signature[] callerSignature; 8351 Object obj = mSettings.getUserIdLPr(uid); 8352 if (obj != null) { 8353 if (obj instanceof SharedUserSetting) { 8354 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8355 } else if (obj instanceof PackageSetting) { 8356 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8357 } else { 8358 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8359 } 8360 } else { 8361 throw new SecurityException("Unknown calling uid " + uid); 8362 } 8363 8364 // Verify: can't set installerPackageName to a package that is 8365 // not signed with the same cert as the caller. 8366 if (installerPackageSetting != null) { 8367 if (compareSignatures(callerSignature, 8368 installerPackageSetting.signatures.mSignatures) 8369 != PackageManager.SIGNATURE_MATCH) { 8370 throw new SecurityException( 8371 "Caller does not have same cert as new installer package " 8372 + installerPackageName); 8373 } 8374 } 8375 8376 // Verify: if target already has an installer package, it must 8377 // be signed with the same cert as the caller. 8378 if (targetPackageSetting.installerPackageName != null) { 8379 PackageSetting setting = mSettings.mPackages.get( 8380 targetPackageSetting.installerPackageName); 8381 // If the currently set package isn't valid, then it's always 8382 // okay to change it. 8383 if (setting != null) { 8384 if (compareSignatures(callerSignature, 8385 setting.signatures.mSignatures) 8386 != PackageManager.SIGNATURE_MATCH) { 8387 throw new SecurityException( 8388 "Caller does not have same cert as old installer package " 8389 + targetPackageSetting.installerPackageName); 8390 } 8391 } 8392 } 8393 8394 // Okay! 8395 targetPackageSetting.installerPackageName = installerPackageName; 8396 scheduleWriteSettingsLocked(); 8397 } 8398 } 8399 8400 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8401 // Queue up an async operation since the package installation may take a little while. 8402 mHandler.post(new Runnable() { 8403 public void run() { 8404 mHandler.removeCallbacks(this); 8405 // Result object to be returned 8406 PackageInstalledInfo res = new PackageInstalledInfo(); 8407 res.returnCode = currentStatus; 8408 res.uid = -1; 8409 res.pkg = null; 8410 res.removedInfo = new PackageRemovedInfo(); 8411 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8412 args.doPreInstall(res.returnCode); 8413 synchronized (mInstallLock) { 8414 installPackageLI(args, res); 8415 } 8416 args.doPostInstall(res.returnCode, res.uid); 8417 } 8418 8419 // A restore should be performed at this point if (a) the install 8420 // succeeded, (b) the operation is not an update, and (c) the new 8421 // package has not opted out of backup participation. 8422 final boolean update = res.removedInfo.removedPackage != null; 8423 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8424 boolean doRestore = !update 8425 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8426 8427 // Set up the post-install work request bookkeeping. This will be used 8428 // and cleaned up by the post-install event handling regardless of whether 8429 // there's a restore pass performed. Token values are >= 1. 8430 int token; 8431 if (mNextInstallToken < 0) mNextInstallToken = 1; 8432 token = mNextInstallToken++; 8433 8434 PostInstallData data = new PostInstallData(args, res); 8435 mRunningInstalls.put(token, data); 8436 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8437 8438 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8439 // Pass responsibility to the Backup Manager. It will perform a 8440 // restore if appropriate, then pass responsibility back to the 8441 // Package Manager to run the post-install observer callbacks 8442 // and broadcasts. 8443 IBackupManager bm = IBackupManager.Stub.asInterface( 8444 ServiceManager.getService(Context.BACKUP_SERVICE)); 8445 if (bm != null) { 8446 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8447 + " to BM for possible restore"); 8448 try { 8449 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 8450 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8451 } else { 8452 doRestore = false; 8453 } 8454 } catch (RemoteException e) { 8455 // can't happen; the backup manager is local 8456 } catch (Exception e) { 8457 Slog.e(TAG, "Exception trying to enqueue restore", e); 8458 doRestore = false; 8459 } 8460 } else { 8461 Slog.e(TAG, "Backup Manager not found!"); 8462 doRestore = false; 8463 } 8464 } 8465 8466 if (!doRestore) { 8467 // No restore possible, or the Backup Manager was mysteriously not 8468 // available -- just fire the post-install work request directly. 8469 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8470 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8471 mHandler.sendMessage(msg); 8472 } 8473 } 8474 }); 8475 } 8476 8477 private abstract class HandlerParams { 8478 private static final int MAX_RETRIES = 4; 8479 8480 /** 8481 * Number of times startCopy() has been attempted and had a non-fatal 8482 * error. 8483 */ 8484 private int mRetries = 0; 8485 8486 /** User handle for the user requesting the information or installation. */ 8487 private final UserHandle mUser; 8488 8489 HandlerParams(UserHandle user) { 8490 mUser = user; 8491 } 8492 8493 UserHandle getUser() { 8494 return mUser; 8495 } 8496 8497 final boolean startCopy() { 8498 boolean res; 8499 try { 8500 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8501 8502 if (++mRetries > MAX_RETRIES) { 8503 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8504 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8505 handleServiceError(); 8506 return false; 8507 } else { 8508 handleStartCopy(); 8509 res = true; 8510 } 8511 } catch (RemoteException e) { 8512 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8513 mHandler.sendEmptyMessage(MCS_RECONNECT); 8514 res = false; 8515 } 8516 handleReturnCode(); 8517 return res; 8518 } 8519 8520 final void serviceError() { 8521 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8522 handleServiceError(); 8523 handleReturnCode(); 8524 } 8525 8526 abstract void handleStartCopy() throws RemoteException; 8527 abstract void handleServiceError(); 8528 abstract void handleReturnCode(); 8529 } 8530 8531 class MeasureParams extends HandlerParams { 8532 private final PackageStats mStats; 8533 private boolean mSuccess; 8534 8535 private final IPackageStatsObserver mObserver; 8536 8537 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8538 super(new UserHandle(stats.userHandle)); 8539 mObserver = observer; 8540 mStats = stats; 8541 } 8542 8543 @Override 8544 public String toString() { 8545 return "MeasureParams{" 8546 + Integer.toHexString(System.identityHashCode(this)) 8547 + " " + mStats.packageName + "}"; 8548 } 8549 8550 @Override 8551 void handleStartCopy() throws RemoteException { 8552 synchronized (mInstallLock) { 8553 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8554 } 8555 8556 if (mSuccess) { 8557 final boolean mounted; 8558 if (Environment.isExternalStorageEmulated()) { 8559 mounted = true; 8560 } else { 8561 final String status = Environment.getExternalStorageState(); 8562 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8563 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8564 } 8565 8566 if (mounted) { 8567 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8568 8569 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8570 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8571 8572 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8573 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8574 8575 // Always subtract cache size, since it's a subdirectory 8576 mStats.externalDataSize -= mStats.externalCacheSize; 8577 8578 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8579 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8580 8581 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8582 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8583 } 8584 } 8585 } 8586 8587 @Override 8588 void handleReturnCode() { 8589 if (mObserver != null) { 8590 try { 8591 mObserver.onGetStatsCompleted(mStats, mSuccess); 8592 } catch (RemoteException e) { 8593 Slog.i(TAG, "Observer no longer exists."); 8594 } 8595 } 8596 } 8597 8598 @Override 8599 void handleServiceError() { 8600 Slog.e(TAG, "Could not measure application " + mStats.packageName 8601 + " external storage"); 8602 } 8603 } 8604 8605 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8606 throws RemoteException { 8607 long result = 0; 8608 for (File path : paths) { 8609 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8610 } 8611 return result; 8612 } 8613 8614 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8615 for (File path : paths) { 8616 try { 8617 mcs.clearDirectory(path.getAbsolutePath()); 8618 } catch (RemoteException e) { 8619 } 8620 } 8621 } 8622 8623 static class OriginInfo { 8624 /** 8625 * Location where install is coming from, before it has been 8626 * copied/renamed into place. This could be a single monolithic APK 8627 * file, or a cluster directory. This location may be untrusted. 8628 */ 8629 final File file; 8630 final String cid; 8631 8632 /** 8633 * Flag indicating that {@link #file} or {@link #cid} has already been 8634 * staged, meaning downstream users don't need to defensively copy the 8635 * contents. 8636 */ 8637 final boolean staged; 8638 8639 /** 8640 * Flag indicating that {@link #file} or {@link #cid} is an already 8641 * installed app that is being moved. 8642 */ 8643 final boolean existing; 8644 8645 final String resolvedPath; 8646 final File resolvedFile; 8647 8648 static OriginInfo fromNothing() { 8649 return new OriginInfo(null, null, false, false); 8650 } 8651 8652 static OriginInfo fromUntrustedFile(File file) { 8653 return new OriginInfo(file, null, false, false); 8654 } 8655 8656 static OriginInfo fromExistingFile(File file) { 8657 return new OriginInfo(file, null, false, true); 8658 } 8659 8660 static OriginInfo fromStagedFile(File file) { 8661 return new OriginInfo(file, null, true, false); 8662 } 8663 8664 static OriginInfo fromStagedContainer(String cid) { 8665 return new OriginInfo(null, cid, true, false); 8666 } 8667 8668 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8669 this.file = file; 8670 this.cid = cid; 8671 this.staged = staged; 8672 this.existing = existing; 8673 8674 if (cid != null) { 8675 resolvedPath = PackageHelper.getSdDir(cid); 8676 resolvedFile = new File(resolvedPath); 8677 } else if (file != null) { 8678 resolvedPath = file.getAbsolutePath(); 8679 resolvedFile = file; 8680 } else { 8681 resolvedPath = null; 8682 resolvedFile = null; 8683 } 8684 } 8685 } 8686 8687 class InstallParams extends HandlerParams { 8688 final OriginInfo origin; 8689 final IPackageInstallObserver2 observer; 8690 int installFlags; 8691 final String installerPackageName; 8692 final VerificationParams verificationParams; 8693 private InstallArgs mArgs; 8694 private int mRet; 8695 final String packageAbiOverride; 8696 8697 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8698 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8699 String packageAbiOverride) { 8700 super(user); 8701 this.origin = origin; 8702 this.observer = observer; 8703 this.installFlags = installFlags; 8704 this.installerPackageName = installerPackageName; 8705 this.verificationParams = verificationParams; 8706 this.packageAbiOverride = packageAbiOverride; 8707 } 8708 8709 @Override 8710 public String toString() { 8711 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8712 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8713 } 8714 8715 public ManifestDigest getManifestDigest() { 8716 if (verificationParams == null) { 8717 return null; 8718 } 8719 return verificationParams.getManifestDigest(); 8720 } 8721 8722 private int installLocationPolicy(PackageInfoLite pkgLite) { 8723 String packageName = pkgLite.packageName; 8724 int installLocation = pkgLite.installLocation; 8725 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8726 // reader 8727 synchronized (mPackages) { 8728 PackageParser.Package pkg = mPackages.get(packageName); 8729 if (pkg != null) { 8730 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8731 // Check for downgrading. 8732 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8733 try { 8734 checkDowngrade(pkg, pkgLite); 8735 } catch (PackageManagerException e) { 8736 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 8737 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8738 } 8739 } 8740 // Check for updated system application. 8741 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8742 if (onSd) { 8743 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8744 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8745 } 8746 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8747 } else { 8748 if (onSd) { 8749 // Install flag overrides everything. 8750 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8751 } 8752 // If current upgrade specifies particular preference 8753 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8754 // Application explicitly specified internal. 8755 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8756 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8757 // App explictly prefers external. Let policy decide 8758 } else { 8759 // Prefer previous location 8760 if (isExternal(pkg)) { 8761 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8762 } 8763 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8764 } 8765 } 8766 } else { 8767 // Invalid install. Return error code 8768 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8769 } 8770 } 8771 } 8772 // All the special cases have been taken care of. 8773 // Return result based on recommended install location. 8774 if (onSd) { 8775 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8776 } 8777 return pkgLite.recommendedInstallLocation; 8778 } 8779 8780 /* 8781 * Invoke remote method to get package information and install 8782 * location values. Override install location based on default 8783 * policy if needed and then create install arguments based 8784 * on the install location. 8785 */ 8786 public void handleStartCopy() throws RemoteException { 8787 int ret = PackageManager.INSTALL_SUCCEEDED; 8788 8789 // If we're already staged, we've firmly committed to an install location 8790 if (origin.staged) { 8791 if (origin.file != null) { 8792 installFlags |= PackageManager.INSTALL_INTERNAL; 8793 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8794 } else if (origin.cid != null) { 8795 installFlags |= PackageManager.INSTALL_EXTERNAL; 8796 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8797 } else { 8798 throw new IllegalStateException("Invalid stage location"); 8799 } 8800 } 8801 8802 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8803 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8804 8805 PackageInfoLite pkgLite = null; 8806 8807 if (onInt && onSd) { 8808 // Check if both bits are set. 8809 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8810 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8811 } else { 8812 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8813 packageAbiOverride); 8814 8815 /* 8816 * If we have too little free space, try to free cache 8817 * before giving up. 8818 */ 8819 if (!origin.staged && pkgLite.recommendedInstallLocation 8820 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8821 // TODO: focus freeing disk space on the target device 8822 final StorageManager storage = StorageManager.from(mContext); 8823 final long lowThreshold = storage.getStorageLowBytes( 8824 Environment.getDataDirectory()); 8825 8826 final long sizeBytes = mContainerService.calculateInstalledSize( 8827 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8828 8829 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8830 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8831 installFlags, packageAbiOverride); 8832 } 8833 8834 /* 8835 * The cache free must have deleted the file we 8836 * downloaded to install. 8837 * 8838 * TODO: fix the "freeCache" call to not delete 8839 * the file we care about. 8840 */ 8841 if (pkgLite.recommendedInstallLocation 8842 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8843 pkgLite.recommendedInstallLocation 8844 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8845 } 8846 } 8847 } 8848 8849 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8850 int loc = pkgLite.recommendedInstallLocation; 8851 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8852 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8853 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8854 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8855 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8856 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8857 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8858 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8859 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8860 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8861 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8862 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8863 } else { 8864 // Override with defaults if needed. 8865 loc = installLocationPolicy(pkgLite); 8866 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8867 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8868 } else if (!onSd && !onInt) { 8869 // Override install location with flags 8870 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8871 // Set the flag to install on external media. 8872 installFlags |= PackageManager.INSTALL_EXTERNAL; 8873 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8874 } else { 8875 // Make sure the flag for installing on external 8876 // media is unset 8877 installFlags |= PackageManager.INSTALL_INTERNAL; 8878 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8879 } 8880 } 8881 } 8882 } 8883 8884 final InstallArgs args = createInstallArgs(this); 8885 mArgs = args; 8886 8887 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8888 /* 8889 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8890 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8891 */ 8892 int userIdentifier = getUser().getIdentifier(); 8893 if (userIdentifier == UserHandle.USER_ALL 8894 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8895 userIdentifier = UserHandle.USER_OWNER; 8896 } 8897 8898 /* 8899 * Determine if we have any installed package verifiers. If we 8900 * do, then we'll defer to them to verify the packages. 8901 */ 8902 final int requiredUid = mRequiredVerifierPackage == null ? -1 8903 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8904 if (!origin.existing && requiredUid != -1 8905 && isVerificationEnabled(userIdentifier, installFlags)) { 8906 final Intent verification = new Intent( 8907 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8908 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 8909 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8910 PACKAGE_MIME_TYPE); 8911 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8912 8913 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8914 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8915 0 /* TODO: Which userId? */); 8916 8917 if (DEBUG_VERIFY) { 8918 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8919 + verification.toString() + " with " + pkgLite.verifiers.length 8920 + " optional verifiers"); 8921 } 8922 8923 final int verificationId = mPendingVerificationToken++; 8924 8925 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8926 8927 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8928 installerPackageName); 8929 8930 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8931 installFlags); 8932 8933 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8934 pkgLite.packageName); 8935 8936 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8937 pkgLite.versionCode); 8938 8939 if (verificationParams != null) { 8940 if (verificationParams.getVerificationURI() != null) { 8941 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8942 verificationParams.getVerificationURI()); 8943 } 8944 if (verificationParams.getOriginatingURI() != null) { 8945 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8946 verificationParams.getOriginatingURI()); 8947 } 8948 if (verificationParams.getReferrer() != null) { 8949 verification.putExtra(Intent.EXTRA_REFERRER, 8950 verificationParams.getReferrer()); 8951 } 8952 if (verificationParams.getOriginatingUid() >= 0) { 8953 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8954 verificationParams.getOriginatingUid()); 8955 } 8956 if (verificationParams.getInstallerUid() >= 0) { 8957 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8958 verificationParams.getInstallerUid()); 8959 } 8960 } 8961 8962 final PackageVerificationState verificationState = new PackageVerificationState( 8963 requiredUid, args); 8964 8965 mPendingVerification.append(verificationId, verificationState); 8966 8967 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8968 receivers, verificationState); 8969 8970 /* 8971 * If any sufficient verifiers were listed in the package 8972 * manifest, attempt to ask them. 8973 */ 8974 if (sufficientVerifiers != null) { 8975 final int N = sufficientVerifiers.size(); 8976 if (N == 0) { 8977 Slog.i(TAG, "Additional verifiers required, but none installed."); 8978 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8979 } else { 8980 for (int i = 0; i < N; i++) { 8981 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8982 8983 final Intent sufficientIntent = new Intent(verification); 8984 sufficientIntent.setComponent(verifierComponent); 8985 8986 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8987 } 8988 } 8989 } 8990 8991 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8992 mRequiredVerifierPackage, receivers); 8993 if (ret == PackageManager.INSTALL_SUCCEEDED 8994 && mRequiredVerifierPackage != null) { 8995 /* 8996 * Send the intent to the required verification agent, 8997 * but only start the verification timeout after the 8998 * target BroadcastReceivers have run. 8999 */ 9000 verification.setComponent(requiredVerifierComponent); 9001 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9002 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9003 new BroadcastReceiver() { 9004 @Override 9005 public void onReceive(Context context, Intent intent) { 9006 final Message msg = mHandler 9007 .obtainMessage(CHECK_PENDING_VERIFICATION); 9008 msg.arg1 = verificationId; 9009 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9010 } 9011 }, null, 0, null, null); 9012 9013 /* 9014 * We don't want the copy to proceed until verification 9015 * succeeds, so null out this field. 9016 */ 9017 mArgs = null; 9018 } 9019 } else { 9020 /* 9021 * No package verification is enabled, so immediately start 9022 * the remote call to initiate copy using temporary file. 9023 */ 9024 ret = args.copyApk(mContainerService, true); 9025 } 9026 } 9027 9028 mRet = ret; 9029 } 9030 9031 @Override 9032 void handleReturnCode() { 9033 // If mArgs is null, then MCS couldn't be reached. When it 9034 // reconnects, it will try again to install. At that point, this 9035 // will succeed. 9036 if (mArgs != null) { 9037 processPendingInstall(mArgs, mRet); 9038 } 9039 } 9040 9041 @Override 9042 void handleServiceError() { 9043 mArgs = createInstallArgs(this); 9044 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9045 } 9046 9047 public boolean isForwardLocked() { 9048 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9049 } 9050 } 9051 9052 /** 9053 * Used during creation of InstallArgs 9054 * 9055 * @param installFlags package installation flags 9056 * @return true if should be installed on external storage 9057 */ 9058 private static boolean installOnSd(int installFlags) { 9059 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9060 return false; 9061 } 9062 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9063 return true; 9064 } 9065 return false; 9066 } 9067 9068 /** 9069 * Used during creation of InstallArgs 9070 * 9071 * @param installFlags package installation flags 9072 * @return true if should be installed as forward locked 9073 */ 9074 private static boolean installForwardLocked(int installFlags) { 9075 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9076 } 9077 9078 private InstallArgs createInstallArgs(InstallParams params) { 9079 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9080 return new AsecInstallArgs(params); 9081 } else { 9082 return new FileInstallArgs(params); 9083 } 9084 } 9085 9086 /** 9087 * Create args that describe an existing installed package. Typically used 9088 * when cleaning up old installs, or used as a move source. 9089 */ 9090 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9091 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9092 final boolean isInAsec; 9093 if (installOnSd(installFlags)) { 9094 /* Apps on SD card are always in ASEC containers. */ 9095 isInAsec = true; 9096 } else if (installForwardLocked(installFlags) 9097 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9098 /* 9099 * Forward-locked apps are only in ASEC containers if they're the 9100 * new style 9101 */ 9102 isInAsec = true; 9103 } else { 9104 isInAsec = false; 9105 } 9106 9107 if (isInAsec) { 9108 return new AsecInstallArgs(codePath, instructionSets, 9109 installOnSd(installFlags), installForwardLocked(installFlags)); 9110 } else { 9111 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9112 instructionSets); 9113 } 9114 } 9115 9116 static abstract class InstallArgs { 9117 /** @see InstallParams#origin */ 9118 final OriginInfo origin; 9119 9120 final IPackageInstallObserver2 observer; 9121 // Always refers to PackageManager flags only 9122 final int installFlags; 9123 final String installerPackageName; 9124 final ManifestDigest manifestDigest; 9125 final UserHandle user; 9126 final String abiOverride; 9127 9128 // The list of instruction sets supported by this app. This is currently 9129 // only used during the rmdex() phase to clean up resources. We can get rid of this 9130 // if we move dex files under the common app path. 9131 /* nullable */ String[] instructionSets; 9132 9133 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9134 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9135 String[] instructionSets, String abiOverride) { 9136 this.origin = origin; 9137 this.installFlags = installFlags; 9138 this.observer = observer; 9139 this.installerPackageName = installerPackageName; 9140 this.manifestDigest = manifestDigest; 9141 this.user = user; 9142 this.instructionSets = instructionSets; 9143 this.abiOverride = abiOverride; 9144 } 9145 9146 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9147 abstract int doPreInstall(int status); 9148 9149 /** 9150 * Rename package into final resting place. All paths on the given 9151 * scanned package should be updated to reflect the rename. 9152 */ 9153 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9154 abstract int doPostInstall(int status, int uid); 9155 9156 /** @see PackageSettingBase#codePathString */ 9157 abstract String getCodePath(); 9158 /** @see PackageSettingBase#resourcePathString */ 9159 abstract String getResourcePath(); 9160 abstract String getLegacyNativeLibraryPath(); 9161 9162 // Need installer lock especially for dex file removal. 9163 abstract void cleanUpResourcesLI(); 9164 abstract boolean doPostDeleteLI(boolean delete); 9165 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9166 9167 /** 9168 * Called before the source arguments are copied. This is used mostly 9169 * for MoveParams when it needs to read the source file to put it in the 9170 * destination. 9171 */ 9172 int doPreCopy() { 9173 return PackageManager.INSTALL_SUCCEEDED; 9174 } 9175 9176 /** 9177 * Called after the source arguments are copied. This is used mostly for 9178 * MoveParams when it needs to read the source file to put it in the 9179 * destination. 9180 * 9181 * @return 9182 */ 9183 int doPostCopy(int uid) { 9184 return PackageManager.INSTALL_SUCCEEDED; 9185 } 9186 9187 protected boolean isFwdLocked() { 9188 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9189 } 9190 9191 protected boolean isExternal() { 9192 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9193 } 9194 9195 UserHandle getUser() { 9196 return user; 9197 } 9198 } 9199 9200 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9201 if (!allCodePaths.isEmpty()) { 9202 if (instructionSets == null) { 9203 throw new IllegalStateException("instructionSet == null"); 9204 } 9205 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9206 for (String codePath : allCodePaths) { 9207 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9208 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9209 if (retCode < 0) { 9210 Slog.w(TAG, "Couldn't remove dex file for package: " 9211 + " at location " + codePath + ", retcode=" + retCode); 9212 // we don't consider this to be a failure of the core package deletion 9213 } 9214 } 9215 } 9216 } 9217 } 9218 9219 /** 9220 * Logic to handle installation of non-ASEC applications, including copying 9221 * and renaming logic. 9222 */ 9223 class FileInstallArgs extends InstallArgs { 9224 private File codeFile; 9225 private File resourceFile; 9226 private File legacyNativeLibraryPath; 9227 9228 // Example topology: 9229 // /data/app/com.example/base.apk 9230 // /data/app/com.example/split_foo.apk 9231 // /data/app/com.example/lib/arm/libfoo.so 9232 // /data/app/com.example/lib/arm64/libfoo.so 9233 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9234 9235 /** New install */ 9236 FileInstallArgs(InstallParams params) { 9237 super(params.origin, params.observer, params.installFlags, 9238 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9239 null /* instruction sets */, params.packageAbiOverride); 9240 if (isFwdLocked()) { 9241 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9242 } 9243 } 9244 9245 /** Existing install */ 9246 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9247 String[] instructionSets) { 9248 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9249 this.codeFile = (codePath != null) ? new File(codePath) : null; 9250 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9251 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9252 new File(legacyNativeLibraryPath) : null; 9253 } 9254 9255 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9256 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9257 isFwdLocked(), abiOverride); 9258 9259 final StorageManager storage = StorageManager.from(mContext); 9260 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9261 } 9262 9263 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9264 if (origin.staged) { 9265 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9266 codeFile = origin.file; 9267 resourceFile = origin.file; 9268 return PackageManager.INSTALL_SUCCEEDED; 9269 } 9270 9271 try { 9272 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9273 codeFile = tempDir; 9274 resourceFile = tempDir; 9275 } catch (IOException e) { 9276 Slog.w(TAG, "Failed to create copy file: " + e); 9277 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9278 } 9279 9280 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9281 @Override 9282 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9283 if (!FileUtils.isValidExtFilename(name)) { 9284 throw new IllegalArgumentException("Invalid filename: " + name); 9285 } 9286 try { 9287 final File file = new File(codeFile, name); 9288 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9289 O_RDWR | O_CREAT, 0644); 9290 Os.chmod(file.getAbsolutePath(), 0644); 9291 return new ParcelFileDescriptor(fd); 9292 } catch (ErrnoException e) { 9293 throw new RemoteException("Failed to open: " + e.getMessage()); 9294 } 9295 } 9296 }; 9297 9298 int ret = PackageManager.INSTALL_SUCCEEDED; 9299 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9300 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9301 Slog.e(TAG, "Failed to copy package"); 9302 return ret; 9303 } 9304 9305 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9306 NativeLibraryHelper.Handle handle = null; 9307 try { 9308 handle = NativeLibraryHelper.Handle.create(codeFile); 9309 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9310 abiOverride); 9311 } catch (IOException e) { 9312 Slog.e(TAG, "Copying native libraries failed", e); 9313 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9314 } finally { 9315 IoUtils.closeQuietly(handle); 9316 } 9317 9318 return ret; 9319 } 9320 9321 int doPreInstall(int status) { 9322 if (status != PackageManager.INSTALL_SUCCEEDED) { 9323 cleanUp(); 9324 } 9325 return status; 9326 } 9327 9328 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9329 if (status != PackageManager.INSTALL_SUCCEEDED) { 9330 cleanUp(); 9331 return false; 9332 } else { 9333 final File beforeCodeFile = codeFile; 9334 final File afterCodeFile = getNextCodePath(pkg.packageName); 9335 9336 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9337 try { 9338 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9339 } catch (ErrnoException e) { 9340 Slog.d(TAG, "Failed to rename", e); 9341 return false; 9342 } 9343 9344 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9345 Slog.d(TAG, "Failed to restorecon"); 9346 return false; 9347 } 9348 9349 // Reflect the rename internally 9350 codeFile = afterCodeFile; 9351 resourceFile = afterCodeFile; 9352 9353 // Reflect the rename in scanned details 9354 pkg.codePath = afterCodeFile.getAbsolutePath(); 9355 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9356 pkg.baseCodePath); 9357 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9358 pkg.splitCodePaths); 9359 9360 // Reflect the rename in app info 9361 pkg.applicationInfo.setCodePath(pkg.codePath); 9362 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9363 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9364 pkg.applicationInfo.setResourcePath(pkg.codePath); 9365 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9366 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9367 9368 return true; 9369 } 9370 } 9371 9372 int doPostInstall(int status, int uid) { 9373 if (status != PackageManager.INSTALL_SUCCEEDED) { 9374 cleanUp(); 9375 } 9376 return status; 9377 } 9378 9379 @Override 9380 String getCodePath() { 9381 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9382 } 9383 9384 @Override 9385 String getResourcePath() { 9386 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9387 } 9388 9389 @Override 9390 String getLegacyNativeLibraryPath() { 9391 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9392 } 9393 9394 private boolean cleanUp() { 9395 if (codeFile == null || !codeFile.exists()) { 9396 return false; 9397 } 9398 9399 if (codeFile.isDirectory()) { 9400 FileUtils.deleteContents(codeFile); 9401 } 9402 codeFile.delete(); 9403 9404 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9405 resourceFile.delete(); 9406 } 9407 9408 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9409 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9410 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9411 } 9412 legacyNativeLibraryPath.delete(); 9413 } 9414 9415 return true; 9416 } 9417 9418 void cleanUpResourcesLI() { 9419 // Try enumerating all code paths before deleting 9420 List<String> allCodePaths = Collections.EMPTY_LIST; 9421 if (codeFile != null && codeFile.exists()) { 9422 try { 9423 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9424 allCodePaths = pkg.getAllCodePaths(); 9425 } catch (PackageParserException e) { 9426 // Ignored; we tried our best 9427 } 9428 } 9429 9430 cleanUp(); 9431 removeDexFiles(allCodePaths, instructionSets); 9432 } 9433 9434 boolean doPostDeleteLI(boolean delete) { 9435 // XXX err, shouldn't we respect the delete flag? 9436 cleanUpResourcesLI(); 9437 return true; 9438 } 9439 } 9440 9441 private boolean isAsecExternal(String cid) { 9442 final String asecPath = PackageHelper.getSdFilesystem(cid); 9443 return !asecPath.startsWith(mAsecInternalPath); 9444 } 9445 9446 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9447 PackageManagerException { 9448 if (copyRet < 0) { 9449 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9450 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9451 throw new PackageManagerException(copyRet, message); 9452 } 9453 } 9454 } 9455 9456 /** 9457 * Extract the MountService "container ID" from the full code path of an 9458 * .apk. 9459 */ 9460 static String cidFromCodePath(String fullCodePath) { 9461 int eidx = fullCodePath.lastIndexOf("/"); 9462 String subStr1 = fullCodePath.substring(0, eidx); 9463 int sidx = subStr1.lastIndexOf("/"); 9464 return subStr1.substring(sidx+1, eidx); 9465 } 9466 9467 /** 9468 * Logic to handle installation of ASEC applications, including copying and 9469 * renaming logic. 9470 */ 9471 class AsecInstallArgs extends InstallArgs { 9472 static final String RES_FILE_NAME = "pkg.apk"; 9473 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9474 9475 String cid; 9476 String packagePath; 9477 String resourcePath; 9478 String legacyNativeLibraryDir; 9479 9480 /** New install */ 9481 AsecInstallArgs(InstallParams params) { 9482 super(params.origin, params.observer, params.installFlags, 9483 params.installerPackageName, params.getManifestDigest(), 9484 params.getUser(), null /* instruction sets */, 9485 params.packageAbiOverride); 9486 } 9487 9488 /** Existing install */ 9489 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9490 boolean isExternal, boolean isForwardLocked) { 9491 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9492 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9493 instructionSets, null); 9494 // Hackily pretend we're still looking at a full code path 9495 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9496 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9497 } 9498 9499 // Extract cid from fullCodePath 9500 int eidx = fullCodePath.lastIndexOf("/"); 9501 String subStr1 = fullCodePath.substring(0, eidx); 9502 int sidx = subStr1.lastIndexOf("/"); 9503 cid = subStr1.substring(sidx+1, eidx); 9504 setMountPath(subStr1); 9505 } 9506 9507 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9508 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9509 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9510 instructionSets, null); 9511 this.cid = cid; 9512 setMountPath(PackageHelper.getSdDir(cid)); 9513 } 9514 9515 void createCopyFile() { 9516 cid = mInstallerService.allocateExternalStageCidLegacy(); 9517 } 9518 9519 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9520 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9521 abiOverride); 9522 9523 final File target; 9524 if (isExternal()) { 9525 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9526 } else { 9527 target = Environment.getDataDirectory(); 9528 } 9529 9530 final StorageManager storage = StorageManager.from(mContext); 9531 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9532 } 9533 9534 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9535 if (origin.staged) { 9536 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9537 cid = origin.cid; 9538 setMountPath(PackageHelper.getSdDir(cid)); 9539 return PackageManager.INSTALL_SUCCEEDED; 9540 } 9541 9542 if (temp) { 9543 createCopyFile(); 9544 } else { 9545 /* 9546 * Pre-emptively destroy the container since it's destroyed if 9547 * copying fails due to it existing anyway. 9548 */ 9549 PackageHelper.destroySdDir(cid); 9550 } 9551 9552 final String newMountPath = imcs.copyPackageToContainer( 9553 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9554 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9555 9556 if (newMountPath != null) { 9557 setMountPath(newMountPath); 9558 return PackageManager.INSTALL_SUCCEEDED; 9559 } else { 9560 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9561 } 9562 } 9563 9564 @Override 9565 String getCodePath() { 9566 return packagePath; 9567 } 9568 9569 @Override 9570 String getResourcePath() { 9571 return resourcePath; 9572 } 9573 9574 @Override 9575 String getLegacyNativeLibraryPath() { 9576 return legacyNativeLibraryDir; 9577 } 9578 9579 int doPreInstall(int status) { 9580 if (status != PackageManager.INSTALL_SUCCEEDED) { 9581 // Destroy container 9582 PackageHelper.destroySdDir(cid); 9583 } else { 9584 boolean mounted = PackageHelper.isContainerMounted(cid); 9585 if (!mounted) { 9586 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9587 Process.SYSTEM_UID); 9588 if (newMountPath != null) { 9589 setMountPath(newMountPath); 9590 } else { 9591 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9592 } 9593 } 9594 } 9595 return status; 9596 } 9597 9598 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9599 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9600 String newMountPath = null; 9601 if (PackageHelper.isContainerMounted(cid)) { 9602 // Unmount the container 9603 if (!PackageHelper.unMountSdDir(cid)) { 9604 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9605 return false; 9606 } 9607 } 9608 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9609 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9610 " which might be stale. Will try to clean up."); 9611 // Clean up the stale container and proceed to recreate. 9612 if (!PackageHelper.destroySdDir(newCacheId)) { 9613 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9614 return false; 9615 } 9616 // Successfully cleaned up stale container. Try to rename again. 9617 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9618 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9619 + " inspite of cleaning it up."); 9620 return false; 9621 } 9622 } 9623 if (!PackageHelper.isContainerMounted(newCacheId)) { 9624 Slog.w(TAG, "Mounting container " + newCacheId); 9625 newMountPath = PackageHelper.mountSdDir(newCacheId, 9626 getEncryptKey(), Process.SYSTEM_UID); 9627 } else { 9628 newMountPath = PackageHelper.getSdDir(newCacheId); 9629 } 9630 if (newMountPath == null) { 9631 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9632 return false; 9633 } 9634 Log.i(TAG, "Succesfully renamed " + cid + 9635 " to " + newCacheId + 9636 " at new path: " + newMountPath); 9637 cid = newCacheId; 9638 9639 final File beforeCodeFile = new File(packagePath); 9640 setMountPath(newMountPath); 9641 final File afterCodeFile = new File(packagePath); 9642 9643 // Reflect the rename in scanned details 9644 pkg.codePath = afterCodeFile.getAbsolutePath(); 9645 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9646 pkg.baseCodePath); 9647 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9648 pkg.splitCodePaths); 9649 9650 // Reflect the rename in app info 9651 pkg.applicationInfo.setCodePath(pkg.codePath); 9652 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9653 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9654 pkg.applicationInfo.setResourcePath(pkg.codePath); 9655 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9656 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9657 9658 return true; 9659 } 9660 9661 private void setMountPath(String mountPath) { 9662 final File mountFile = new File(mountPath); 9663 9664 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9665 if (monolithicFile.exists()) { 9666 packagePath = monolithicFile.getAbsolutePath(); 9667 if (isFwdLocked()) { 9668 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9669 } else { 9670 resourcePath = packagePath; 9671 } 9672 } else { 9673 packagePath = mountFile.getAbsolutePath(); 9674 resourcePath = packagePath; 9675 } 9676 9677 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9678 } 9679 9680 int doPostInstall(int status, int uid) { 9681 if (status != PackageManager.INSTALL_SUCCEEDED) { 9682 cleanUp(); 9683 } else { 9684 final int groupOwner; 9685 final String protectedFile; 9686 if (isFwdLocked()) { 9687 groupOwner = UserHandle.getSharedAppGid(uid); 9688 protectedFile = RES_FILE_NAME; 9689 } else { 9690 groupOwner = -1; 9691 protectedFile = null; 9692 } 9693 9694 if (uid < Process.FIRST_APPLICATION_UID 9695 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9696 Slog.e(TAG, "Failed to finalize " + cid); 9697 PackageHelper.destroySdDir(cid); 9698 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9699 } 9700 9701 boolean mounted = PackageHelper.isContainerMounted(cid); 9702 if (!mounted) { 9703 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9704 } 9705 } 9706 return status; 9707 } 9708 9709 private void cleanUp() { 9710 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9711 9712 // Destroy secure container 9713 PackageHelper.destroySdDir(cid); 9714 } 9715 9716 private List<String> getAllCodePaths() { 9717 final File codeFile = new File(getCodePath()); 9718 if (codeFile != null && codeFile.exists()) { 9719 try { 9720 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9721 return pkg.getAllCodePaths(); 9722 } catch (PackageParserException e) { 9723 // Ignored; we tried our best 9724 } 9725 } 9726 return Collections.EMPTY_LIST; 9727 } 9728 9729 void cleanUpResourcesLI() { 9730 // Enumerate all code paths before deleting 9731 cleanUpResourcesLI(getAllCodePaths()); 9732 } 9733 9734 private void cleanUpResourcesLI(List<String> allCodePaths) { 9735 cleanUp(); 9736 removeDexFiles(allCodePaths, instructionSets); 9737 } 9738 9739 9740 9741 String getPackageName() { 9742 return getAsecPackageName(cid); 9743 } 9744 9745 boolean doPostDeleteLI(boolean delete) { 9746 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9747 final List<String> allCodePaths = getAllCodePaths(); 9748 boolean mounted = PackageHelper.isContainerMounted(cid); 9749 if (mounted) { 9750 // Unmount first 9751 if (PackageHelper.unMountSdDir(cid)) { 9752 mounted = false; 9753 } 9754 } 9755 if (!mounted && delete) { 9756 cleanUpResourcesLI(allCodePaths); 9757 } 9758 return !mounted; 9759 } 9760 9761 @Override 9762 int doPreCopy() { 9763 if (isFwdLocked()) { 9764 if (!PackageHelper.fixSdPermissions(cid, 9765 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9766 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9767 } 9768 } 9769 9770 return PackageManager.INSTALL_SUCCEEDED; 9771 } 9772 9773 @Override 9774 int doPostCopy(int uid) { 9775 if (isFwdLocked()) { 9776 if (uid < Process.FIRST_APPLICATION_UID 9777 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9778 RES_FILE_NAME)) { 9779 Slog.e(TAG, "Failed to finalize " + cid); 9780 PackageHelper.destroySdDir(cid); 9781 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9782 } 9783 } 9784 9785 return PackageManager.INSTALL_SUCCEEDED; 9786 } 9787 } 9788 9789 static String getAsecPackageName(String packageCid) { 9790 int idx = packageCid.lastIndexOf("-"); 9791 if (idx == -1) { 9792 return packageCid; 9793 } 9794 return packageCid.substring(0, idx); 9795 } 9796 9797 // Utility method used to create code paths based on package name and available index. 9798 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9799 String idxStr = ""; 9800 int idx = 1; 9801 // Fall back to default value of idx=1 if prefix is not 9802 // part of oldCodePath 9803 if (oldCodePath != null) { 9804 String subStr = oldCodePath; 9805 // Drop the suffix right away 9806 if (suffix != null && subStr.endsWith(suffix)) { 9807 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9808 } 9809 // If oldCodePath already contains prefix find out the 9810 // ending index to either increment or decrement. 9811 int sidx = subStr.lastIndexOf(prefix); 9812 if (sidx != -1) { 9813 subStr = subStr.substring(sidx + prefix.length()); 9814 if (subStr != null) { 9815 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9816 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9817 } 9818 try { 9819 idx = Integer.parseInt(subStr); 9820 if (idx <= 1) { 9821 idx++; 9822 } else { 9823 idx--; 9824 } 9825 } catch(NumberFormatException e) { 9826 } 9827 } 9828 } 9829 } 9830 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9831 return prefix + idxStr; 9832 } 9833 9834 private File getNextCodePath(String packageName) { 9835 int suffix = 1; 9836 File result; 9837 do { 9838 result = new File(mAppInstallDir, packageName + "-" + suffix); 9839 suffix++; 9840 } while (result.exists()); 9841 return result; 9842 } 9843 9844 // Utility method used to ignore ADD/REMOVE events 9845 // by directory observer. 9846 private static boolean ignoreCodePath(String fullPathStr) { 9847 String apkName = deriveCodePathName(fullPathStr); 9848 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9849 if (idx != -1 && ((idx+1) < apkName.length())) { 9850 // Make sure the package ends with a numeral 9851 String version = apkName.substring(idx+1); 9852 try { 9853 Integer.parseInt(version); 9854 return true; 9855 } catch (NumberFormatException e) {} 9856 } 9857 return false; 9858 } 9859 9860 // Utility method that returns the relative package path with respect 9861 // to the installation directory. Like say for /data/data/com.test-1.apk 9862 // string com.test-1 is returned. 9863 static String deriveCodePathName(String codePath) { 9864 if (codePath == null) { 9865 return null; 9866 } 9867 final File codeFile = new File(codePath); 9868 final String name = codeFile.getName(); 9869 if (codeFile.isDirectory()) { 9870 return name; 9871 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9872 final int lastDot = name.lastIndexOf('.'); 9873 return name.substring(0, lastDot); 9874 } else { 9875 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9876 return null; 9877 } 9878 } 9879 9880 class PackageInstalledInfo { 9881 String name; 9882 int uid; 9883 // The set of users that originally had this package installed. 9884 int[] origUsers; 9885 // The set of users that now have this package installed. 9886 int[] newUsers; 9887 PackageParser.Package pkg; 9888 int returnCode; 9889 String returnMsg; 9890 PackageRemovedInfo removedInfo; 9891 9892 public void setError(int code, String msg) { 9893 returnCode = code; 9894 returnMsg = msg; 9895 Slog.w(TAG, msg); 9896 } 9897 9898 public void setError(String msg, PackageParserException e) { 9899 returnCode = e.error; 9900 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9901 Slog.w(TAG, msg, e); 9902 } 9903 9904 public void setError(String msg, PackageManagerException e) { 9905 returnCode = e.error; 9906 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9907 Slog.w(TAG, msg, e); 9908 } 9909 9910 // In some error cases we want to convey more info back to the observer 9911 String origPackage; 9912 String origPermission; 9913 } 9914 9915 /* 9916 * Install a non-existing package. 9917 */ 9918 private void installNewPackageLI(PackageParser.Package pkg, 9919 int parseFlags, int scanFlags, UserHandle user, 9920 String installerPackageName, PackageInstalledInfo res) { 9921 // Remember this for later, in case we need to rollback this install 9922 String pkgName = pkg.packageName; 9923 9924 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9925 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9926 synchronized(mPackages) { 9927 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9928 // A package with the same name is already installed, though 9929 // it has been renamed to an older name. The package we 9930 // are trying to install should be installed as an update to 9931 // the existing one, but that has not been requested, so bail. 9932 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9933 + " without first uninstalling package running as " 9934 + mSettings.mRenamedPackages.get(pkgName)); 9935 return; 9936 } 9937 if (mPackages.containsKey(pkgName)) { 9938 // Don't allow installation over an existing package with the same name. 9939 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9940 + " without first uninstalling."); 9941 return; 9942 } 9943 } 9944 9945 try { 9946 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9947 System.currentTimeMillis(), user); 9948 9949 updateSettingsLI(newPackage, installerPackageName, null, null, res, user); 9950 // delete the partially installed application. the data directory will have to be 9951 // restored if it was already existing 9952 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9953 // remove package from internal structures. Note that we want deletePackageX to 9954 // delete the package data and cache directories that it created in 9955 // scanPackageLocked, unless those directories existed before we even tried to 9956 // install. 9957 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9958 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9959 res.removedInfo, true); 9960 } 9961 9962 } catch (PackageManagerException e) { 9963 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9964 } 9965 } 9966 9967 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9968 // Upgrade keysets are being used. Determine if new package has a superset of the 9969 // required keys. 9970 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9971 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9972 for (int i = 0; i < upgradeKeySets.length; i++) { 9973 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9974 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9975 return true; 9976 } 9977 } 9978 return false; 9979 } 9980 9981 private void replacePackageLI(PackageParser.Package pkg, 9982 int parseFlags, int scanFlags, UserHandle user, 9983 String installerPackageName, PackageInstalledInfo res) { 9984 PackageParser.Package oldPackage; 9985 String pkgName = pkg.packageName; 9986 int[] allUsers; 9987 boolean[] perUserInstalled; 9988 9989 // First find the old package info and check signatures 9990 synchronized(mPackages) { 9991 oldPackage = mPackages.get(pkgName); 9992 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9993 PackageSetting ps = mSettings.mPackages.get(pkgName); 9994 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9995 // default to original signature matching 9996 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9997 != PackageManager.SIGNATURE_MATCH) { 9998 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9999 "New package has a different signature: " + pkgName); 10000 return; 10001 } 10002 } else { 10003 if(!checkUpgradeKeySetLP(ps, pkg)) { 10004 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10005 "New package not signed by keys specified by upgrade-keysets: " 10006 + pkgName); 10007 return; 10008 } 10009 } 10010 10011 // In case of rollback, remember per-user/profile install state 10012 allUsers = sUserManager.getUserIds(); 10013 perUserInstalled = new boolean[allUsers.length]; 10014 for (int i = 0; i < allUsers.length; i++) { 10015 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10016 } 10017 } 10018 10019 boolean sysPkg = (isSystemApp(oldPackage)); 10020 if (sysPkg) { 10021 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10022 user, allUsers, perUserInstalled, installerPackageName, res); 10023 } else { 10024 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10025 user, allUsers, perUserInstalled, installerPackageName, res); 10026 } 10027 } 10028 10029 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10030 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10031 int[] allUsers, boolean[] perUserInstalled, 10032 String installerPackageName, PackageInstalledInfo res) { 10033 String pkgName = deletedPackage.packageName; 10034 boolean deletedPkg = true; 10035 boolean updatedSettings = false; 10036 10037 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10038 + deletedPackage); 10039 long origUpdateTime; 10040 if (pkg.mExtras != null) { 10041 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10042 } else { 10043 origUpdateTime = 0; 10044 } 10045 10046 // First delete the existing package while retaining the data directory 10047 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10048 res.removedInfo, true)) { 10049 // If the existing package wasn't successfully deleted 10050 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10051 deletedPkg = false; 10052 } else { 10053 // Successfully deleted the old package; proceed with replace. 10054 10055 // If deleted package lived in a container, give users a chance to 10056 // relinquish resources before killing. 10057 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10058 if (DEBUG_INSTALL) { 10059 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10060 } 10061 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10062 final ArrayList<String> pkgList = new ArrayList<String>(1); 10063 pkgList.add(deletedPackage.applicationInfo.packageName); 10064 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10065 } 10066 10067 deleteCodeCacheDirsLI(pkgName); 10068 try { 10069 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10070 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10071 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res, 10072 user); 10073 updatedSettings = true; 10074 } catch (PackageManagerException e) { 10075 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10076 } 10077 } 10078 10079 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10080 // remove package from internal structures. Note that we want deletePackageX to 10081 // delete the package data and cache directories that it created in 10082 // scanPackageLocked, unless those directories existed before we even tried to 10083 // install. 10084 if(updatedSettings) { 10085 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10086 deletePackageLI( 10087 pkgName, null, true, allUsers, perUserInstalled, 10088 PackageManager.DELETE_KEEP_DATA, 10089 res.removedInfo, true); 10090 } 10091 // Since we failed to install the new package we need to restore the old 10092 // package that we deleted. 10093 if (deletedPkg) { 10094 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10095 File restoreFile = new File(deletedPackage.codePath); 10096 // Parse old package 10097 boolean oldOnSd = isExternal(deletedPackage); 10098 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10099 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10100 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10101 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10102 try { 10103 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10104 } catch (PackageManagerException e) { 10105 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10106 + e.getMessage()); 10107 return; 10108 } 10109 // Restore of old package succeeded. Update permissions. 10110 // writer 10111 synchronized (mPackages) { 10112 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10113 UPDATE_PERMISSIONS_ALL); 10114 // can downgrade to reader 10115 mSettings.writeLPr(); 10116 } 10117 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10118 } 10119 } 10120 } 10121 10122 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10123 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10124 int[] allUsers, boolean[] perUserInstalled, 10125 String installerPackageName, PackageInstalledInfo res) { 10126 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10127 + ", old=" + deletedPackage); 10128 boolean disabledSystem = false; 10129 boolean updatedSettings = false; 10130 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10131 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10132 != 0) { 10133 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10134 } 10135 String packageName = deletedPackage.packageName; 10136 if (packageName == null) { 10137 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10138 "Attempt to delete null packageName."); 10139 return; 10140 } 10141 PackageParser.Package oldPkg; 10142 PackageSetting oldPkgSetting; 10143 // reader 10144 synchronized (mPackages) { 10145 oldPkg = mPackages.get(packageName); 10146 oldPkgSetting = mSettings.mPackages.get(packageName); 10147 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10148 (oldPkgSetting == null)) { 10149 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10150 "Couldn't find package:" + packageName + " information"); 10151 return; 10152 } 10153 } 10154 10155 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10156 10157 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10158 res.removedInfo.removedPackage = packageName; 10159 // Remove existing system package 10160 removePackageLI(oldPkgSetting, true); 10161 // writer 10162 synchronized (mPackages) { 10163 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10164 if (!disabledSystem && deletedPackage != null) { 10165 // We didn't need to disable the .apk as a current system package, 10166 // which means we are replacing another update that is already 10167 // installed. We need to make sure to delete the older one's .apk. 10168 res.removedInfo.args = createInstallArgsForExisting(0, 10169 deletedPackage.applicationInfo.getCodePath(), 10170 deletedPackage.applicationInfo.getResourcePath(), 10171 deletedPackage.applicationInfo.nativeLibraryRootDir, 10172 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10173 } else { 10174 res.removedInfo.args = null; 10175 } 10176 } 10177 10178 // Successfully disabled the old package. Now proceed with re-installation 10179 deleteCodeCacheDirsLI(packageName); 10180 10181 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10182 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10183 10184 PackageParser.Package newPackage = null; 10185 try { 10186 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10187 if (newPackage.mExtras != null) { 10188 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10189 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10190 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10191 10192 // is the update attempting to change shared user? that isn't going to work... 10193 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10194 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10195 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10196 + " to " + newPkgSetting.sharedUser); 10197 updatedSettings = true; 10198 } 10199 } 10200 10201 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10202 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res, 10203 user); 10204 updatedSettings = true; 10205 } 10206 10207 } catch (PackageManagerException e) { 10208 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10209 } 10210 10211 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10212 // Re installation failed. Restore old information 10213 // Remove new pkg information 10214 if (newPackage != null) { 10215 removeInstalledPackageLI(newPackage, true); 10216 } 10217 // Add back the old system package 10218 try { 10219 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10220 } catch (PackageManagerException e) { 10221 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10222 } 10223 // Restore the old system information in Settings 10224 synchronized (mPackages) { 10225 if (disabledSystem) { 10226 mSettings.enableSystemPackageLPw(packageName); 10227 } 10228 if (updatedSettings) { 10229 mSettings.setInstallerPackageName(packageName, 10230 oldPkgSetting.installerPackageName); 10231 } 10232 mSettings.writeLPr(); 10233 } 10234 } 10235 } 10236 10237 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10238 int[] allUsers, boolean[] perUserInstalled, 10239 PackageInstalledInfo res, UserHandle user) { 10240 String pkgName = newPackage.packageName; 10241 synchronized (mPackages) { 10242 //write settings. the installStatus will be incomplete at this stage. 10243 //note that the new package setting would have already been 10244 //added to mPackages. It hasn't been persisted yet. 10245 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10246 mSettings.writeLPr(); 10247 } 10248 10249 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10250 10251 synchronized (mPackages) { 10252 updatePermissionsLPw(newPackage.packageName, newPackage, 10253 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10254 ? UPDATE_PERMISSIONS_ALL : 0)); 10255 // For system-bundled packages, we assume that installing an upgraded version 10256 // of the package implies that the user actually wants to run that new code, 10257 // so we enable the package. 10258 PackageSetting ps = mSettings.mPackages.get(pkgName); 10259 if (ps != null) { 10260 if (isSystemApp(newPackage)) { 10261 // NB: implicit assumption that system package upgrades apply to all users 10262 if (DEBUG_INSTALL) { 10263 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10264 } 10265 if (res.origUsers != null) { 10266 for (int userHandle : res.origUsers) { 10267 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10268 userHandle, installerPackageName); 10269 } 10270 } 10271 // Also convey the prior install/uninstall state 10272 if (allUsers != null && perUserInstalled != null) { 10273 for (int i = 0; i < allUsers.length; i++) { 10274 if (DEBUG_INSTALL) { 10275 Slog.d(TAG, " user " + allUsers[i] 10276 + " => " + perUserInstalled[i]); 10277 } 10278 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10279 } 10280 // these install state changes will be persisted in the 10281 // upcoming call to mSettings.writeLPr(). 10282 } 10283 } 10284 // It's implied that when a user requests installation, they want the app to be 10285 // installed and enabled. 10286 int userId = user.getIdentifier(); 10287 if (userId != UserHandle.USER_ALL) { 10288 ps.setInstalled(true, userId); 10289 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 10290 } 10291 } 10292 res.name = pkgName; 10293 res.uid = newPackage.applicationInfo.uid; 10294 res.pkg = newPackage; 10295 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10296 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10297 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10298 //to update install status 10299 mSettings.writeLPr(); 10300 } 10301 } 10302 10303 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10304 final int installFlags = args.installFlags; 10305 String installerPackageName = args.installerPackageName; 10306 File tmpPackageFile = new File(args.getCodePath()); 10307 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10308 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10309 boolean replace = false; 10310 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10311 // Result object to be returned 10312 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10313 10314 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10315 // Retrieve PackageSettings and parse package 10316 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10317 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10318 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10319 PackageParser pp = new PackageParser(); 10320 pp.setSeparateProcesses(mSeparateProcesses); 10321 pp.setDisplayMetrics(mMetrics); 10322 10323 final PackageParser.Package pkg; 10324 try { 10325 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10326 } catch (PackageParserException e) { 10327 res.setError("Failed parse during installPackageLI", e); 10328 return; 10329 } 10330 10331 // Mark that we have an install time CPU ABI override. 10332 pkg.cpuAbiOverride = args.abiOverride; 10333 10334 String pkgName = res.name = pkg.packageName; 10335 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10336 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10337 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10338 return; 10339 } 10340 } 10341 10342 try { 10343 pp.collectCertificates(pkg, parseFlags); 10344 pp.collectManifestDigest(pkg); 10345 } catch (PackageParserException e) { 10346 res.setError("Failed collect during installPackageLI", e); 10347 return; 10348 } 10349 10350 /* If the installer passed in a manifest digest, compare it now. */ 10351 if (args.manifestDigest != null) { 10352 if (DEBUG_INSTALL) { 10353 final String parsedManifest = pkg.manifestDigest == null ? "null" 10354 : pkg.manifestDigest.toString(); 10355 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10356 + parsedManifest); 10357 } 10358 10359 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10360 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10361 return; 10362 } 10363 } else if (DEBUG_INSTALL) { 10364 final String parsedManifest = pkg.manifestDigest == null 10365 ? "null" : pkg.manifestDigest.toString(); 10366 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10367 } 10368 10369 // Get rid of all references to package scan path via parser. 10370 pp = null; 10371 String oldCodePath = null; 10372 boolean systemApp = false; 10373 synchronized (mPackages) { 10374 // Check if installing already existing package 10375 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10376 String oldName = mSettings.mRenamedPackages.get(pkgName); 10377 if (pkg.mOriginalPackages != null 10378 && pkg.mOriginalPackages.contains(oldName) 10379 && mPackages.containsKey(oldName)) { 10380 // This package is derived from an original package, 10381 // and this device has been updating from that original 10382 // name. We must continue using the original name, so 10383 // rename the new package here. 10384 pkg.setPackageName(oldName); 10385 pkgName = pkg.packageName; 10386 replace = true; 10387 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10388 + oldName + " pkgName=" + pkgName); 10389 } else if (mPackages.containsKey(pkgName)) { 10390 // This package, under its official name, already exists 10391 // on the device; we should replace it. 10392 replace = true; 10393 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10394 } 10395 } 10396 10397 PackageSetting ps = mSettings.mPackages.get(pkgName); 10398 if (ps != null) { 10399 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10400 10401 // Quick sanity check that we're signed correctly if updating; 10402 // we'll check this again later when scanning, but we want to 10403 // bail early here before tripping over redefined permissions. 10404 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10405 try { 10406 verifySignaturesLP(ps, pkg); 10407 } catch (PackageManagerException e) { 10408 res.setError(e.error, e.getMessage()); 10409 return; 10410 } 10411 } else { 10412 if (!checkUpgradeKeySetLP(ps, pkg)) { 10413 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 10414 + pkg.packageName + " upgrade keys do not match the " 10415 + "previously installed version"); 10416 return; 10417 } 10418 } 10419 10420 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10421 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10422 systemApp = (ps.pkg.applicationInfo.flags & 10423 ApplicationInfo.FLAG_SYSTEM) != 0; 10424 } 10425 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10426 } 10427 10428 // Check whether the newly-scanned package wants to define an already-defined perm 10429 int N = pkg.permissions.size(); 10430 for (int i = N-1; i >= 0; i--) { 10431 PackageParser.Permission perm = pkg.permissions.get(i); 10432 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10433 if (bp != null) { 10434 // If the defining package is signed with our cert, it's okay. This 10435 // also includes the "updating the same package" case, of course. 10436 // "updating same package" could also involve key-rotation. 10437 final boolean sigsOk; 10438 if (!bp.sourcePackage.equals(pkg.packageName) 10439 || !(bp.packageSetting instanceof PackageSetting) 10440 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10441 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10442 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10443 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10444 } else { 10445 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10446 } 10447 if (!sigsOk) { 10448 // If the owning package is the system itself, we log but allow 10449 // install to proceed; we fail the install on all other permission 10450 // redefinitions. 10451 if (!bp.sourcePackage.equals("android")) { 10452 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10453 + pkg.packageName + " attempting to redeclare permission " 10454 + perm.info.name + " already owned by " + bp.sourcePackage); 10455 res.origPermission = perm.info.name; 10456 res.origPackage = bp.sourcePackage; 10457 return; 10458 } else { 10459 Slog.w(TAG, "Package " + pkg.packageName 10460 + " attempting to redeclare system permission " 10461 + perm.info.name + "; ignoring new declaration"); 10462 pkg.permissions.remove(i); 10463 } 10464 } 10465 } 10466 } 10467 10468 } 10469 10470 if (systemApp && onSd) { 10471 // Disable updates to system apps on sdcard 10472 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10473 "Cannot install updates to system apps on sdcard"); 10474 return; 10475 } 10476 10477 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10478 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10479 return; 10480 } 10481 10482 if (replace) { 10483 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10484 installerPackageName, res); 10485 } else { 10486 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10487 args.user, installerPackageName, res); 10488 } 10489 synchronized (mPackages) { 10490 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10491 if (ps != null) { 10492 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10493 } 10494 } 10495 } 10496 10497 private static boolean isMultiArch(PackageSetting ps) { 10498 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10499 } 10500 10501 private static boolean isMultiArch(ApplicationInfo info) { 10502 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10503 } 10504 10505 private static boolean isExternal(PackageParser.Package pkg) { 10506 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10507 } 10508 10509 private static boolean isExternal(PackageSetting ps) { 10510 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10511 } 10512 10513 private static boolean isExternal(ApplicationInfo info) { 10514 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10515 } 10516 10517 private static boolean isSystemApp(PackageParser.Package pkg) { 10518 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10519 } 10520 10521 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10522 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 10523 } 10524 10525 private static boolean isSystemApp(ApplicationInfo info) { 10526 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10527 } 10528 10529 private static boolean isSystemApp(PackageSetting ps) { 10530 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10531 } 10532 10533 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10534 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10535 } 10536 10537 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10538 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10539 } 10540 10541 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10542 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10543 } 10544 10545 private int packageFlagsToInstallFlags(PackageSetting ps) { 10546 int installFlags = 0; 10547 if (isExternal(ps)) { 10548 installFlags |= PackageManager.INSTALL_EXTERNAL; 10549 } 10550 if (ps.isForwardLocked()) { 10551 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10552 } 10553 return installFlags; 10554 } 10555 10556 private void deleteTempPackageFiles() { 10557 final FilenameFilter filter = new FilenameFilter() { 10558 public boolean accept(File dir, String name) { 10559 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10560 } 10561 }; 10562 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10563 file.delete(); 10564 } 10565 } 10566 10567 @Override 10568 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10569 int flags) { 10570 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10571 flags); 10572 } 10573 10574 @Override 10575 public void deletePackage(final String packageName, 10576 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10577 mContext.enforceCallingOrSelfPermission( 10578 android.Manifest.permission.DELETE_PACKAGES, null); 10579 final int uid = Binder.getCallingUid(); 10580 if (UserHandle.getUserId(uid) != userId) { 10581 mContext.enforceCallingPermission( 10582 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10583 "deletePackage for user " + userId); 10584 } 10585 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10586 try { 10587 observer.onPackageDeleted(packageName, 10588 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10589 } catch (RemoteException re) { 10590 } 10591 return; 10592 } 10593 10594 boolean uninstallBlocked = false; 10595 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10596 int[] users = sUserManager.getUserIds(); 10597 for (int i = 0; i < users.length; ++i) { 10598 if (getBlockUninstallForUser(packageName, users[i])) { 10599 uninstallBlocked = true; 10600 break; 10601 } 10602 } 10603 } else { 10604 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10605 } 10606 if (uninstallBlocked) { 10607 try { 10608 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10609 null); 10610 } catch (RemoteException re) { 10611 } 10612 return; 10613 } 10614 10615 if (DEBUG_REMOVE) { 10616 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10617 } 10618 // Queue up an async operation since the package deletion may take a little while. 10619 mHandler.post(new Runnable() { 10620 public void run() { 10621 mHandler.removeCallbacks(this); 10622 final int returnCode = deletePackageX(packageName, userId, flags); 10623 if (observer != null) { 10624 try { 10625 observer.onPackageDeleted(packageName, returnCode, null); 10626 } catch (RemoteException e) { 10627 Log.i(TAG, "Observer no longer exists."); 10628 } //end catch 10629 } //end if 10630 } //end run 10631 }); 10632 } 10633 10634 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10635 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10636 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10637 try { 10638 if (dpm != null) { 10639 if (dpm.isDeviceOwner(packageName)) { 10640 return true; 10641 } 10642 int[] users; 10643 if (userId == UserHandle.USER_ALL) { 10644 users = sUserManager.getUserIds(); 10645 } else { 10646 users = new int[]{userId}; 10647 } 10648 for (int i = 0; i < users.length; ++i) { 10649 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10650 return true; 10651 } 10652 } 10653 } 10654 } catch (RemoteException e) { 10655 } 10656 return false; 10657 } 10658 10659 /** 10660 * This method is an internal method that could be get invoked either 10661 * to delete an installed package or to clean up a failed installation. 10662 * After deleting an installed package, a broadcast is sent to notify any 10663 * listeners that the package has been installed. For cleaning up a failed 10664 * installation, the broadcast is not necessary since the package's 10665 * installation wouldn't have sent the initial broadcast either 10666 * The key steps in deleting a package are 10667 * deleting the package information in internal structures like mPackages, 10668 * deleting the packages base directories through installd 10669 * updating mSettings to reflect current status 10670 * persisting settings for later use 10671 * sending a broadcast if necessary 10672 */ 10673 private int deletePackageX(String packageName, int userId, int flags) { 10674 final PackageRemovedInfo info = new PackageRemovedInfo(); 10675 final boolean res; 10676 10677 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10678 ? UserHandle.ALL : new UserHandle(userId); 10679 10680 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10681 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10682 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10683 } 10684 10685 boolean removedForAllUsers = false; 10686 boolean systemUpdate = false; 10687 10688 // for the uninstall-updates case and restricted profiles, remember the per- 10689 // userhandle installed state 10690 int[] allUsers; 10691 boolean[] perUserInstalled; 10692 synchronized (mPackages) { 10693 PackageSetting ps = mSettings.mPackages.get(packageName); 10694 allUsers = sUserManager.getUserIds(); 10695 perUserInstalled = new boolean[allUsers.length]; 10696 for (int i = 0; i < allUsers.length; i++) { 10697 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10698 } 10699 } 10700 10701 synchronized (mInstallLock) { 10702 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10703 res = deletePackageLI(packageName, removeForUser, 10704 true, allUsers, perUserInstalled, 10705 flags | REMOVE_CHATTY, info, true); 10706 systemUpdate = info.isRemovedPackageSystemUpdate; 10707 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10708 removedForAllUsers = true; 10709 } 10710 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10711 + " removedForAllUsers=" + removedForAllUsers); 10712 } 10713 10714 if (res) { 10715 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10716 10717 // If the removed package was a system update, the old system package 10718 // was re-enabled; we need to broadcast this information 10719 if (systemUpdate) { 10720 Bundle extras = new Bundle(1); 10721 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10722 ? info.removedAppId : info.uid); 10723 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10724 10725 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10726 extras, null, null, null); 10727 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10728 extras, null, null, null); 10729 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10730 null, packageName, null, null); 10731 } 10732 } 10733 // Force a gc here. 10734 Runtime.getRuntime().gc(); 10735 // Delete the resources here after sending the broadcast to let 10736 // other processes clean up before deleting resources. 10737 if (info.args != null) { 10738 synchronized (mInstallLock) { 10739 info.args.doPostDeleteLI(true); 10740 } 10741 } 10742 10743 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10744 } 10745 10746 static class PackageRemovedInfo { 10747 String removedPackage; 10748 int uid = -1; 10749 int removedAppId = -1; 10750 int[] removedUsers = null; 10751 boolean isRemovedPackageSystemUpdate = false; 10752 // Clean up resources deleted packages. 10753 InstallArgs args = null; 10754 10755 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10756 Bundle extras = new Bundle(1); 10757 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10758 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10759 if (replacing) { 10760 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10761 } 10762 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10763 if (removedPackage != null) { 10764 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10765 extras, null, null, removedUsers); 10766 if (fullRemove && !replacing) { 10767 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10768 extras, null, null, removedUsers); 10769 } 10770 } 10771 if (removedAppId >= 0) { 10772 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10773 removedUsers); 10774 } 10775 } 10776 } 10777 10778 /* 10779 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10780 * flag is not set, the data directory is removed as well. 10781 * make sure this flag is set for partially installed apps. If not its meaningless to 10782 * delete a partially installed application. 10783 */ 10784 private void removePackageDataLI(PackageSetting ps, 10785 int[] allUserHandles, boolean[] perUserInstalled, 10786 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10787 String packageName = ps.name; 10788 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10789 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10790 // Retrieve object to delete permissions for shared user later on 10791 final PackageSetting deletedPs; 10792 // reader 10793 synchronized (mPackages) { 10794 deletedPs = mSettings.mPackages.get(packageName); 10795 if (outInfo != null) { 10796 outInfo.removedPackage = packageName; 10797 outInfo.removedUsers = deletedPs != null 10798 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10799 : null; 10800 } 10801 } 10802 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10803 removeDataDirsLI(packageName); 10804 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10805 } 10806 // writer 10807 synchronized (mPackages) { 10808 if (deletedPs != null) { 10809 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10810 if (outInfo != null) { 10811 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10812 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10813 } 10814 if (deletedPs != null) { 10815 updatePermissionsLPw(deletedPs.name, null, 0); 10816 if (deletedPs.sharedUser != null) { 10817 // remove permissions associated with package 10818 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10819 } 10820 } 10821 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10822 } 10823 // make sure to preserve per-user disabled state if this removal was just 10824 // a downgrade of a system app to the factory package 10825 if (allUserHandles != null && perUserInstalled != null) { 10826 if (DEBUG_REMOVE) { 10827 Slog.d(TAG, "Propagating install state across downgrade"); 10828 } 10829 for (int i = 0; i < allUserHandles.length; i++) { 10830 if (DEBUG_REMOVE) { 10831 Slog.d(TAG, " user " + allUserHandles[i] 10832 + " => " + perUserInstalled[i]); 10833 } 10834 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10835 } 10836 } 10837 } 10838 // can downgrade to reader 10839 if (writeSettings) { 10840 // Save settings now 10841 mSettings.writeLPr(); 10842 } 10843 } 10844 if (outInfo != null) { 10845 // A user ID was deleted here. Go through all users and remove it 10846 // from KeyStore. 10847 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10848 } 10849 } 10850 10851 static boolean locationIsPrivileged(File path) { 10852 try { 10853 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10854 .getCanonicalPath(); 10855 return path.getCanonicalPath().startsWith(privilegedAppDir); 10856 } catch (IOException e) { 10857 Slog.e(TAG, "Unable to access code path " + path); 10858 } 10859 return false; 10860 } 10861 10862 /* 10863 * Tries to delete system package. 10864 */ 10865 private boolean deleteSystemPackageLI(PackageSetting newPs, 10866 int[] allUserHandles, boolean[] perUserInstalled, 10867 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10868 final boolean applyUserRestrictions 10869 = (allUserHandles != null) && (perUserInstalled != null); 10870 PackageSetting disabledPs = null; 10871 // Confirm if the system package has been updated 10872 // An updated system app can be deleted. This will also have to restore 10873 // the system pkg from system partition 10874 // reader 10875 synchronized (mPackages) { 10876 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10877 } 10878 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10879 + " disabledPs=" + disabledPs); 10880 if (disabledPs == null) { 10881 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10882 return false; 10883 } else if (DEBUG_REMOVE) { 10884 Slog.d(TAG, "Deleting system pkg from data partition"); 10885 } 10886 if (DEBUG_REMOVE) { 10887 if (applyUserRestrictions) { 10888 Slog.d(TAG, "Remembering install states:"); 10889 for (int i = 0; i < allUserHandles.length; i++) { 10890 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10891 } 10892 } 10893 } 10894 // Delete the updated package 10895 outInfo.isRemovedPackageSystemUpdate = true; 10896 if (disabledPs.versionCode < newPs.versionCode) { 10897 // Delete data for downgrades 10898 flags &= ~PackageManager.DELETE_KEEP_DATA; 10899 } else { 10900 // Preserve data by setting flag 10901 flags |= PackageManager.DELETE_KEEP_DATA; 10902 } 10903 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10904 allUserHandles, perUserInstalled, outInfo, writeSettings); 10905 if (!ret) { 10906 return false; 10907 } 10908 // writer 10909 synchronized (mPackages) { 10910 // Reinstate the old system package 10911 mSettings.enableSystemPackageLPw(newPs.name); 10912 // Remove any native libraries from the upgraded package. 10913 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10914 } 10915 // Install the system package 10916 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10917 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10918 if (locationIsPrivileged(disabledPs.codePath)) { 10919 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10920 } 10921 10922 final PackageParser.Package newPkg; 10923 try { 10924 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10925 } catch (PackageManagerException e) { 10926 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10927 return false; 10928 } 10929 10930 // writer 10931 synchronized (mPackages) { 10932 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10933 updatePermissionsLPw(newPkg.packageName, newPkg, 10934 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10935 if (applyUserRestrictions) { 10936 if (DEBUG_REMOVE) { 10937 Slog.d(TAG, "Propagating install state across reinstall"); 10938 } 10939 for (int i = 0; i < allUserHandles.length; i++) { 10940 if (DEBUG_REMOVE) { 10941 Slog.d(TAG, " user " + allUserHandles[i] 10942 + " => " + perUserInstalled[i]); 10943 } 10944 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10945 } 10946 // Regardless of writeSettings we need to ensure that this restriction 10947 // state propagation is persisted 10948 mSettings.writeAllUsersPackageRestrictionsLPr(); 10949 } 10950 // can downgrade to reader here 10951 if (writeSettings) { 10952 mSettings.writeLPr(); 10953 } 10954 } 10955 return true; 10956 } 10957 10958 private boolean deleteInstalledPackageLI(PackageSetting ps, 10959 boolean deleteCodeAndResources, int flags, 10960 int[] allUserHandles, boolean[] perUserInstalled, 10961 PackageRemovedInfo outInfo, boolean writeSettings) { 10962 if (outInfo != null) { 10963 outInfo.uid = ps.appId; 10964 } 10965 10966 // Delete package data from internal structures and also remove data if flag is set 10967 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10968 10969 // Delete application code and resources 10970 if (deleteCodeAndResources && (outInfo != null)) { 10971 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10972 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10973 getAppDexInstructionSets(ps)); 10974 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10975 } 10976 return true; 10977 } 10978 10979 @Override 10980 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10981 int userId) { 10982 mContext.enforceCallingOrSelfPermission( 10983 android.Manifest.permission.DELETE_PACKAGES, null); 10984 synchronized (mPackages) { 10985 PackageSetting ps = mSettings.mPackages.get(packageName); 10986 if (ps == null) { 10987 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10988 return false; 10989 } 10990 if (!ps.getInstalled(userId)) { 10991 // Can't block uninstall for an app that is not installed or enabled. 10992 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10993 return false; 10994 } 10995 ps.setBlockUninstall(blockUninstall, userId); 10996 mSettings.writePackageRestrictionsLPr(userId); 10997 } 10998 return true; 10999 } 11000 11001 @Override 11002 public boolean getBlockUninstallForUser(String packageName, int userId) { 11003 synchronized (mPackages) { 11004 PackageSetting ps = mSettings.mPackages.get(packageName); 11005 if (ps == null) { 11006 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11007 return false; 11008 } 11009 return ps.getBlockUninstall(userId); 11010 } 11011 } 11012 11013 /* 11014 * This method handles package deletion in general 11015 */ 11016 private boolean deletePackageLI(String packageName, UserHandle user, 11017 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11018 int flags, PackageRemovedInfo outInfo, 11019 boolean writeSettings) { 11020 if (packageName == null) { 11021 Slog.w(TAG, "Attempt to delete null packageName."); 11022 return false; 11023 } 11024 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11025 PackageSetting ps; 11026 boolean dataOnly = false; 11027 int removeUser = -1; 11028 int appId = -1; 11029 synchronized (mPackages) { 11030 ps = mSettings.mPackages.get(packageName); 11031 if (ps == null) { 11032 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11033 return false; 11034 } 11035 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11036 && user.getIdentifier() != UserHandle.USER_ALL) { 11037 // The caller is asking that the package only be deleted for a single 11038 // user. To do this, we just mark its uninstalled state and delete 11039 // its data. If this is a system app, we only allow this to happen if 11040 // they have set the special DELETE_SYSTEM_APP which requests different 11041 // semantics than normal for uninstalling system apps. 11042 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11043 ps.setUserState(user.getIdentifier(), 11044 COMPONENT_ENABLED_STATE_DEFAULT, 11045 false, //installed 11046 true, //stopped 11047 true, //notLaunched 11048 false, //hidden 11049 null, null, null, 11050 false // blockUninstall 11051 ); 11052 if (!isSystemApp(ps)) { 11053 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11054 // Other user still have this package installed, so all 11055 // we need to do is clear this user's data and save that 11056 // it is uninstalled. 11057 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11058 removeUser = user.getIdentifier(); 11059 appId = ps.appId; 11060 mSettings.writePackageRestrictionsLPr(removeUser); 11061 } else { 11062 // We need to set it back to 'installed' so the uninstall 11063 // broadcasts will be sent correctly. 11064 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11065 ps.setInstalled(true, user.getIdentifier()); 11066 } 11067 } else { 11068 // This is a system app, so we assume that the 11069 // other users still have this package installed, so all 11070 // we need to do is clear this user's data and save that 11071 // it is uninstalled. 11072 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11073 removeUser = user.getIdentifier(); 11074 appId = ps.appId; 11075 mSettings.writePackageRestrictionsLPr(removeUser); 11076 } 11077 } 11078 } 11079 11080 if (removeUser >= 0) { 11081 // From above, we determined that we are deleting this only 11082 // for a single user. Continue the work here. 11083 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11084 if (outInfo != null) { 11085 outInfo.removedPackage = packageName; 11086 outInfo.removedAppId = appId; 11087 outInfo.removedUsers = new int[] {removeUser}; 11088 } 11089 mInstaller.clearUserData(packageName, removeUser); 11090 removeKeystoreDataIfNeeded(removeUser, appId); 11091 schedulePackageCleaning(packageName, removeUser, false); 11092 return true; 11093 } 11094 11095 if (dataOnly) { 11096 // Delete application data first 11097 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11098 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11099 return true; 11100 } 11101 11102 boolean ret = false; 11103 if (isSystemApp(ps)) { 11104 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11105 // When an updated system application is deleted we delete the existing resources as well and 11106 // fall back to existing code in system partition 11107 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11108 flags, outInfo, writeSettings); 11109 } else { 11110 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11111 // Kill application pre-emptively especially for apps on sd. 11112 killApplication(packageName, ps.appId, "uninstall pkg"); 11113 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11114 allUserHandles, perUserInstalled, 11115 outInfo, writeSettings); 11116 } 11117 11118 return ret; 11119 } 11120 11121 private final class ClearStorageConnection implements ServiceConnection { 11122 IMediaContainerService mContainerService; 11123 11124 @Override 11125 public void onServiceConnected(ComponentName name, IBinder service) { 11126 synchronized (this) { 11127 mContainerService = IMediaContainerService.Stub.asInterface(service); 11128 notifyAll(); 11129 } 11130 } 11131 11132 @Override 11133 public void onServiceDisconnected(ComponentName name) { 11134 } 11135 } 11136 11137 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11138 final boolean mounted; 11139 if (Environment.isExternalStorageEmulated()) { 11140 mounted = true; 11141 } else { 11142 final String status = Environment.getExternalStorageState(); 11143 11144 mounted = status.equals(Environment.MEDIA_MOUNTED) 11145 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11146 } 11147 11148 if (!mounted) { 11149 return; 11150 } 11151 11152 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11153 int[] users; 11154 if (userId == UserHandle.USER_ALL) { 11155 users = sUserManager.getUserIds(); 11156 } else { 11157 users = new int[] { userId }; 11158 } 11159 final ClearStorageConnection conn = new ClearStorageConnection(); 11160 if (mContext.bindServiceAsUser( 11161 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11162 try { 11163 for (int curUser : users) { 11164 long timeout = SystemClock.uptimeMillis() + 5000; 11165 synchronized (conn) { 11166 long now = SystemClock.uptimeMillis(); 11167 while (conn.mContainerService == null && now < timeout) { 11168 try { 11169 conn.wait(timeout - now); 11170 } catch (InterruptedException e) { 11171 } 11172 } 11173 } 11174 if (conn.mContainerService == null) { 11175 return; 11176 } 11177 11178 final UserEnvironment userEnv = new UserEnvironment(curUser); 11179 clearDirectory(conn.mContainerService, 11180 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11181 if (allData) { 11182 clearDirectory(conn.mContainerService, 11183 userEnv.buildExternalStorageAppDataDirs(packageName)); 11184 clearDirectory(conn.mContainerService, 11185 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11186 } 11187 } 11188 } finally { 11189 mContext.unbindService(conn); 11190 } 11191 } 11192 } 11193 11194 @Override 11195 public void clearApplicationUserData(final String packageName, 11196 final IPackageDataObserver observer, final int userId) { 11197 mContext.enforceCallingOrSelfPermission( 11198 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11199 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11200 // Queue up an async operation since the package deletion may take a little while. 11201 mHandler.post(new Runnable() { 11202 public void run() { 11203 mHandler.removeCallbacks(this); 11204 final boolean succeeded; 11205 synchronized (mInstallLock) { 11206 succeeded = clearApplicationUserDataLI(packageName, userId); 11207 } 11208 clearExternalStorageDataSync(packageName, userId, true); 11209 if (succeeded) { 11210 // invoke DeviceStorageMonitor's update method to clear any notifications 11211 DeviceStorageMonitorInternal 11212 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11213 if (dsm != null) { 11214 dsm.checkMemory(); 11215 } 11216 } 11217 if(observer != null) { 11218 try { 11219 observer.onRemoveCompleted(packageName, succeeded); 11220 } catch (RemoteException e) { 11221 Log.i(TAG, "Observer no longer exists."); 11222 } 11223 } //end if observer 11224 } //end run 11225 }); 11226 } 11227 11228 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11229 if (packageName == null) { 11230 Slog.w(TAG, "Attempt to delete null packageName."); 11231 return false; 11232 } 11233 11234 // Try finding details about the requested package 11235 PackageParser.Package pkg; 11236 synchronized (mPackages) { 11237 pkg = mPackages.get(packageName); 11238 if (pkg == null) { 11239 final PackageSetting ps = mSettings.mPackages.get(packageName); 11240 if (ps != null) { 11241 pkg = ps.pkg; 11242 } 11243 } 11244 } 11245 11246 if (pkg == null) { 11247 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11248 } 11249 11250 // Always delete data directories for package, even if we found no other 11251 // record of app. This helps users recover from UID mismatches without 11252 // resorting to a full data wipe. 11253 int retCode = mInstaller.clearUserData(packageName, userId); 11254 if (retCode < 0) { 11255 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11256 return false; 11257 } 11258 11259 if (pkg == null) { 11260 return false; 11261 } 11262 11263 if (pkg != null && pkg.applicationInfo != null) { 11264 final int appId = pkg.applicationInfo.uid; 11265 removeKeystoreDataIfNeeded(userId, appId); 11266 } 11267 11268 // Create a native library symlink only if we have native libraries 11269 // and if the native libraries are 32 bit libraries. We do not provide 11270 // this symlink for 64 bit libraries. 11271 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11272 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11273 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11274 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11275 Slog.w(TAG, "Failed linking native library dir"); 11276 return false; 11277 } 11278 } 11279 11280 return true; 11281 } 11282 11283 /** 11284 * Remove entries from the keystore daemon. Will only remove it if the 11285 * {@code appId} is valid. 11286 */ 11287 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11288 if (appId < 0) { 11289 return; 11290 } 11291 11292 final KeyStore keyStore = KeyStore.getInstance(); 11293 if (keyStore != null) { 11294 if (userId == UserHandle.USER_ALL) { 11295 for (final int individual : sUserManager.getUserIds()) { 11296 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11297 } 11298 } else { 11299 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11300 } 11301 } else { 11302 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11303 } 11304 } 11305 11306 @Override 11307 public void deleteApplicationCacheFiles(final String packageName, 11308 final IPackageDataObserver observer) { 11309 mContext.enforceCallingOrSelfPermission( 11310 android.Manifest.permission.DELETE_CACHE_FILES, null); 11311 // Queue up an async operation since the package deletion may take a little while. 11312 final int userId = UserHandle.getCallingUserId(); 11313 mHandler.post(new Runnable() { 11314 public void run() { 11315 mHandler.removeCallbacks(this); 11316 final boolean succeded; 11317 synchronized (mInstallLock) { 11318 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11319 } 11320 clearExternalStorageDataSync(packageName, userId, false); 11321 if(observer != null) { 11322 try { 11323 observer.onRemoveCompleted(packageName, succeded); 11324 } catch (RemoteException e) { 11325 Log.i(TAG, "Observer no longer exists."); 11326 } 11327 } //end if observer 11328 } //end run 11329 }); 11330 } 11331 11332 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11333 if (packageName == null) { 11334 Slog.w(TAG, "Attempt to delete null packageName."); 11335 return false; 11336 } 11337 PackageParser.Package p; 11338 synchronized (mPackages) { 11339 p = mPackages.get(packageName); 11340 } 11341 if (p == null) { 11342 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11343 return false; 11344 } 11345 final ApplicationInfo applicationInfo = p.applicationInfo; 11346 if (applicationInfo == null) { 11347 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11348 return false; 11349 } 11350 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11351 if (retCode < 0) { 11352 Slog.w(TAG, "Couldn't remove cache files for package: " 11353 + packageName + " u" + userId); 11354 return false; 11355 } 11356 return true; 11357 } 11358 11359 @Override 11360 public void getPackageSizeInfo(final String packageName, int userHandle, 11361 final IPackageStatsObserver observer) { 11362 mContext.enforceCallingOrSelfPermission( 11363 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11364 if (packageName == null) { 11365 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11366 } 11367 11368 PackageStats stats = new PackageStats(packageName, userHandle); 11369 11370 /* 11371 * Queue up an async operation since the package measurement may take a 11372 * little while. 11373 */ 11374 Message msg = mHandler.obtainMessage(INIT_COPY); 11375 msg.obj = new MeasureParams(stats, observer); 11376 mHandler.sendMessage(msg); 11377 } 11378 11379 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11380 PackageStats pStats) { 11381 if (packageName == null) { 11382 Slog.w(TAG, "Attempt to get size of null packageName."); 11383 return false; 11384 } 11385 PackageParser.Package p; 11386 boolean dataOnly = false; 11387 String libDirRoot = null; 11388 String asecPath = null; 11389 PackageSetting ps = null; 11390 synchronized (mPackages) { 11391 p = mPackages.get(packageName); 11392 ps = mSettings.mPackages.get(packageName); 11393 if(p == null) { 11394 dataOnly = true; 11395 if((ps == null) || (ps.pkg == null)) { 11396 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11397 return false; 11398 } 11399 p = ps.pkg; 11400 } 11401 if (ps != null) { 11402 libDirRoot = ps.legacyNativeLibraryPathString; 11403 } 11404 if (p != null && (isExternal(p) || p.isForwardLocked())) { 11405 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11406 if (secureContainerId != null) { 11407 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11408 } 11409 } 11410 } 11411 String publicSrcDir = null; 11412 if(!dataOnly) { 11413 final ApplicationInfo applicationInfo = p.applicationInfo; 11414 if (applicationInfo == null) { 11415 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11416 return false; 11417 } 11418 if (p.isForwardLocked()) { 11419 publicSrcDir = applicationInfo.getBaseResourcePath(); 11420 } 11421 } 11422 // TODO: extend to measure size of split APKs 11423 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11424 // not just the first level. 11425 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11426 // just the primary. 11427 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11428 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11429 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11430 if (res < 0) { 11431 return false; 11432 } 11433 11434 // Fix-up for forward-locked applications in ASEC containers. 11435 if (!isExternal(p)) { 11436 pStats.codeSize += pStats.externalCodeSize; 11437 pStats.externalCodeSize = 0L; 11438 } 11439 11440 return true; 11441 } 11442 11443 11444 @Override 11445 public void addPackageToPreferred(String packageName) { 11446 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11447 } 11448 11449 @Override 11450 public void removePackageFromPreferred(String packageName) { 11451 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11452 } 11453 11454 @Override 11455 public List<PackageInfo> getPreferredPackages(int flags) { 11456 return new ArrayList<PackageInfo>(); 11457 } 11458 11459 private int getUidTargetSdkVersionLockedLPr(int uid) { 11460 Object obj = mSettings.getUserIdLPr(uid); 11461 if (obj instanceof SharedUserSetting) { 11462 final SharedUserSetting sus = (SharedUserSetting) obj; 11463 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11464 final Iterator<PackageSetting> it = sus.packages.iterator(); 11465 while (it.hasNext()) { 11466 final PackageSetting ps = it.next(); 11467 if (ps.pkg != null) { 11468 int v = ps.pkg.applicationInfo.targetSdkVersion; 11469 if (v < vers) vers = v; 11470 } 11471 } 11472 return vers; 11473 } else if (obj instanceof PackageSetting) { 11474 final PackageSetting ps = (PackageSetting) obj; 11475 if (ps.pkg != null) { 11476 return ps.pkg.applicationInfo.targetSdkVersion; 11477 } 11478 } 11479 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11480 } 11481 11482 @Override 11483 public void addPreferredActivity(IntentFilter filter, int match, 11484 ComponentName[] set, ComponentName activity, int userId) { 11485 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11486 "Adding preferred"); 11487 } 11488 11489 private void addPreferredActivityInternal(IntentFilter filter, int match, 11490 ComponentName[] set, ComponentName activity, boolean always, int userId, 11491 String opname) { 11492 // writer 11493 int callingUid = Binder.getCallingUid(); 11494 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11495 if (filter.countActions() == 0) { 11496 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11497 return; 11498 } 11499 synchronized (mPackages) { 11500 if (mContext.checkCallingOrSelfPermission( 11501 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11502 != PackageManager.PERMISSION_GRANTED) { 11503 if (getUidTargetSdkVersionLockedLPr(callingUid) 11504 < Build.VERSION_CODES.FROYO) { 11505 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11506 + callingUid); 11507 return; 11508 } 11509 mContext.enforceCallingOrSelfPermission( 11510 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11511 } 11512 11513 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11514 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11515 + userId + ":"); 11516 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11517 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11518 scheduleWritePackageRestrictionsLocked(userId); 11519 } 11520 } 11521 11522 @Override 11523 public void replacePreferredActivity(IntentFilter filter, int match, 11524 ComponentName[] set, ComponentName activity, int userId) { 11525 if (filter.countActions() != 1) { 11526 throw new IllegalArgumentException( 11527 "replacePreferredActivity expects filter to have only 1 action."); 11528 } 11529 if (filter.countDataAuthorities() != 0 11530 || filter.countDataPaths() != 0 11531 || filter.countDataSchemes() > 1 11532 || filter.countDataTypes() != 0) { 11533 throw new IllegalArgumentException( 11534 "replacePreferredActivity expects filter to have no data authorities, " + 11535 "paths, or types; and at most one scheme."); 11536 } 11537 11538 final int callingUid = Binder.getCallingUid(); 11539 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11540 synchronized (mPackages) { 11541 if (mContext.checkCallingOrSelfPermission( 11542 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11543 != PackageManager.PERMISSION_GRANTED) { 11544 if (getUidTargetSdkVersionLockedLPr(callingUid) 11545 < Build.VERSION_CODES.FROYO) { 11546 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11547 + Binder.getCallingUid()); 11548 return; 11549 } 11550 mContext.enforceCallingOrSelfPermission( 11551 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11552 } 11553 11554 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11555 if (pir != null) { 11556 // Get all of the existing entries that exactly match this filter. 11557 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11558 if (existing != null && existing.size() == 1) { 11559 PreferredActivity cur = existing.get(0); 11560 if (DEBUG_PREFERRED) { 11561 Slog.i(TAG, "Checking replace of preferred:"); 11562 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11563 if (!cur.mPref.mAlways) { 11564 Slog.i(TAG, " -- CUR; not mAlways!"); 11565 } else { 11566 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11567 Slog.i(TAG, " -- CUR: mSet=" 11568 + Arrays.toString(cur.mPref.mSetComponents)); 11569 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11570 Slog.i(TAG, " -- NEW: mMatch=" 11571 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11572 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11573 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11574 } 11575 } 11576 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11577 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11578 && cur.mPref.sameSet(set)) { 11579 // Setting the preferred activity to what it happens to be already 11580 if (DEBUG_PREFERRED) { 11581 Slog.i(TAG, "Replacing with same preferred activity " 11582 + cur.mPref.mShortComponent + " for user " 11583 + userId + ":"); 11584 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11585 } 11586 return; 11587 } 11588 } 11589 11590 if (existing != null) { 11591 if (DEBUG_PREFERRED) { 11592 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11593 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11594 } 11595 for (int i = 0; i < existing.size(); i++) { 11596 PreferredActivity pa = existing.get(i); 11597 if (DEBUG_PREFERRED) { 11598 Slog.i(TAG, "Removing existing preferred activity " 11599 + pa.mPref.mComponent + ":"); 11600 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11601 } 11602 pir.removeFilter(pa); 11603 } 11604 } 11605 } 11606 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11607 "Replacing preferred"); 11608 } 11609 } 11610 11611 @Override 11612 public void clearPackagePreferredActivities(String packageName) { 11613 final int uid = Binder.getCallingUid(); 11614 // writer 11615 synchronized (mPackages) { 11616 PackageParser.Package pkg = mPackages.get(packageName); 11617 if (pkg == null || pkg.applicationInfo.uid != uid) { 11618 if (mContext.checkCallingOrSelfPermission( 11619 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11620 != PackageManager.PERMISSION_GRANTED) { 11621 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11622 < Build.VERSION_CODES.FROYO) { 11623 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11624 + Binder.getCallingUid()); 11625 return; 11626 } 11627 mContext.enforceCallingOrSelfPermission( 11628 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11629 } 11630 } 11631 11632 int user = UserHandle.getCallingUserId(); 11633 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11634 scheduleWritePackageRestrictionsLocked(user); 11635 } 11636 } 11637 } 11638 11639 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11640 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11641 ArrayList<PreferredActivity> removed = null; 11642 boolean changed = false; 11643 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11644 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11645 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11646 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11647 continue; 11648 } 11649 Iterator<PreferredActivity> it = pir.filterIterator(); 11650 while (it.hasNext()) { 11651 PreferredActivity pa = it.next(); 11652 // Mark entry for removal only if it matches the package name 11653 // and the entry is of type "always". 11654 if (packageName == null || 11655 (pa.mPref.mComponent.getPackageName().equals(packageName) 11656 && pa.mPref.mAlways)) { 11657 if (removed == null) { 11658 removed = new ArrayList<PreferredActivity>(); 11659 } 11660 removed.add(pa); 11661 } 11662 } 11663 if (removed != null) { 11664 for (int j=0; j<removed.size(); j++) { 11665 PreferredActivity pa = removed.get(j); 11666 pir.removeFilter(pa); 11667 } 11668 changed = true; 11669 } 11670 } 11671 return changed; 11672 } 11673 11674 @Override 11675 public void resetPreferredActivities(int userId) { 11676 /* TODO: Actually use userId. Why is it being passed in? */ 11677 mContext.enforceCallingOrSelfPermission( 11678 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11679 // writer 11680 synchronized (mPackages) { 11681 int user = UserHandle.getCallingUserId(); 11682 clearPackagePreferredActivitiesLPw(null, user); 11683 mSettings.readDefaultPreferredAppsLPw(this, user); 11684 scheduleWritePackageRestrictionsLocked(user); 11685 } 11686 } 11687 11688 @Override 11689 public int getPreferredActivities(List<IntentFilter> outFilters, 11690 List<ComponentName> outActivities, String packageName) { 11691 11692 int num = 0; 11693 final int userId = UserHandle.getCallingUserId(); 11694 // reader 11695 synchronized (mPackages) { 11696 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11697 if (pir != null) { 11698 final Iterator<PreferredActivity> it = pir.filterIterator(); 11699 while (it.hasNext()) { 11700 final PreferredActivity pa = it.next(); 11701 if (packageName == null 11702 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11703 && pa.mPref.mAlways)) { 11704 if (outFilters != null) { 11705 outFilters.add(new IntentFilter(pa)); 11706 } 11707 if (outActivities != null) { 11708 outActivities.add(pa.mPref.mComponent); 11709 } 11710 } 11711 } 11712 } 11713 } 11714 11715 return num; 11716 } 11717 11718 @Override 11719 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11720 int userId) { 11721 int callingUid = Binder.getCallingUid(); 11722 if (callingUid != Process.SYSTEM_UID) { 11723 throw new SecurityException( 11724 "addPersistentPreferredActivity can only be run by the system"); 11725 } 11726 if (filter.countActions() == 0) { 11727 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11728 return; 11729 } 11730 synchronized (mPackages) { 11731 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11732 " :"); 11733 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11734 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11735 new PersistentPreferredActivity(filter, activity)); 11736 scheduleWritePackageRestrictionsLocked(userId); 11737 } 11738 } 11739 11740 @Override 11741 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11742 int callingUid = Binder.getCallingUid(); 11743 if (callingUid != Process.SYSTEM_UID) { 11744 throw new SecurityException( 11745 "clearPackagePersistentPreferredActivities can only be run by the system"); 11746 } 11747 ArrayList<PersistentPreferredActivity> removed = null; 11748 boolean changed = false; 11749 synchronized (mPackages) { 11750 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11751 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11752 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11753 .valueAt(i); 11754 if (userId != thisUserId) { 11755 continue; 11756 } 11757 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11758 while (it.hasNext()) { 11759 PersistentPreferredActivity ppa = it.next(); 11760 // Mark entry for removal only if it matches the package name. 11761 if (ppa.mComponent.getPackageName().equals(packageName)) { 11762 if (removed == null) { 11763 removed = new ArrayList<PersistentPreferredActivity>(); 11764 } 11765 removed.add(ppa); 11766 } 11767 } 11768 if (removed != null) { 11769 for (int j=0; j<removed.size(); j++) { 11770 PersistentPreferredActivity ppa = removed.get(j); 11771 ppir.removeFilter(ppa); 11772 } 11773 changed = true; 11774 } 11775 } 11776 11777 if (changed) { 11778 scheduleWritePackageRestrictionsLocked(userId); 11779 } 11780 } 11781 } 11782 11783 @Override 11784 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11785 int sourceUserId, int targetUserId, int flags) { 11786 mContext.enforceCallingOrSelfPermission( 11787 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11788 int callingUid = Binder.getCallingUid(); 11789 enforceOwnerRights(ownerPackage, callingUid); 11790 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11791 if (intentFilter.countActions() == 0) { 11792 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11793 return; 11794 } 11795 synchronized (mPackages) { 11796 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 11797 ownerPackage, targetUserId, flags); 11798 CrossProfileIntentResolver resolver = 11799 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11800 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 11801 // We have all those whose filter is equal. Now checking if the rest is equal as well. 11802 if (existing != null) { 11803 int size = existing.size(); 11804 for (int i = 0; i < size; i++) { 11805 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 11806 return; 11807 } 11808 } 11809 } 11810 resolver.addFilter(newFilter); 11811 scheduleWritePackageRestrictionsLocked(sourceUserId); 11812 } 11813 } 11814 11815 @Override 11816 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 11817 mContext.enforceCallingOrSelfPermission( 11818 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11819 int callingUid = Binder.getCallingUid(); 11820 enforceOwnerRights(ownerPackage, callingUid); 11821 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11822 synchronized (mPackages) { 11823 CrossProfileIntentResolver resolver = 11824 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11825 ArraySet<CrossProfileIntentFilter> set = 11826 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 11827 for (CrossProfileIntentFilter filter : set) { 11828 if (filter.getOwnerPackage().equals(ownerPackage)) { 11829 resolver.removeFilter(filter); 11830 } 11831 } 11832 scheduleWritePackageRestrictionsLocked(sourceUserId); 11833 } 11834 } 11835 11836 // Enforcing that callingUid is owning pkg on userId 11837 private void enforceOwnerRights(String pkg, int callingUid) { 11838 // The system owns everything. 11839 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11840 return; 11841 } 11842 int callingUserId = UserHandle.getUserId(callingUid); 11843 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11844 if (pi == null) { 11845 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11846 + callingUserId); 11847 } 11848 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11849 throw new SecurityException("Calling uid " + callingUid 11850 + " does not own package " + pkg); 11851 } 11852 } 11853 11854 @Override 11855 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11856 Intent intent = new Intent(Intent.ACTION_MAIN); 11857 intent.addCategory(Intent.CATEGORY_HOME); 11858 11859 final int callingUserId = UserHandle.getCallingUserId(); 11860 List<ResolveInfo> list = queryIntentActivities(intent, null, 11861 PackageManager.GET_META_DATA, callingUserId); 11862 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11863 true, false, false, callingUserId); 11864 11865 allHomeCandidates.clear(); 11866 if (list != null) { 11867 for (ResolveInfo ri : list) { 11868 allHomeCandidates.add(ri); 11869 } 11870 } 11871 return (preferred == null || preferred.activityInfo == null) 11872 ? null 11873 : new ComponentName(preferred.activityInfo.packageName, 11874 preferred.activityInfo.name); 11875 } 11876 11877 @Override 11878 public void setApplicationEnabledSetting(String appPackageName, 11879 int newState, int flags, int userId, String callingPackage) { 11880 if (!sUserManager.exists(userId)) return; 11881 if (callingPackage == null) { 11882 callingPackage = Integer.toString(Binder.getCallingUid()); 11883 } 11884 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11885 } 11886 11887 @Override 11888 public void setComponentEnabledSetting(ComponentName componentName, 11889 int newState, int flags, int userId) { 11890 if (!sUserManager.exists(userId)) return; 11891 setEnabledSetting(componentName.getPackageName(), 11892 componentName.getClassName(), newState, flags, userId, null); 11893 } 11894 11895 private void setEnabledSetting(final String packageName, String className, int newState, 11896 final int flags, int userId, String callingPackage) { 11897 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11898 || newState == COMPONENT_ENABLED_STATE_ENABLED 11899 || newState == COMPONENT_ENABLED_STATE_DISABLED 11900 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11901 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11902 throw new IllegalArgumentException("Invalid new component state: " 11903 + newState); 11904 } 11905 PackageSetting pkgSetting; 11906 final int uid = Binder.getCallingUid(); 11907 final int permission = mContext.checkCallingOrSelfPermission( 11908 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11909 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 11910 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11911 boolean sendNow = false; 11912 boolean isApp = (className == null); 11913 String componentName = isApp ? packageName : className; 11914 int packageUid = -1; 11915 ArrayList<String> components; 11916 11917 // writer 11918 synchronized (mPackages) { 11919 pkgSetting = mSettings.mPackages.get(packageName); 11920 if (pkgSetting == null) { 11921 if (className == null) { 11922 throw new IllegalArgumentException( 11923 "Unknown package: " + packageName); 11924 } 11925 throw new IllegalArgumentException( 11926 "Unknown component: " + packageName 11927 + "/" + className); 11928 } 11929 // Allow root and verify that userId is not being specified by a different user 11930 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11931 throw new SecurityException( 11932 "Permission Denial: attempt to change component state from pid=" 11933 + Binder.getCallingPid() 11934 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11935 } 11936 if (className == null) { 11937 // We're dealing with an application/package level state change 11938 if (pkgSetting.getEnabled(userId) == newState) { 11939 // Nothing to do 11940 return; 11941 } 11942 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11943 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11944 // Don't care about who enables an app. 11945 callingPackage = null; 11946 } 11947 pkgSetting.setEnabled(newState, userId, callingPackage); 11948 // pkgSetting.pkg.mSetEnabled = newState; 11949 } else { 11950 // We're dealing with a component level state change 11951 // First, verify that this is a valid class name. 11952 PackageParser.Package pkg = pkgSetting.pkg; 11953 if (pkg == null || !pkg.hasComponentClassName(className)) { 11954 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11955 throw new IllegalArgumentException("Component class " + className 11956 + " does not exist in " + packageName); 11957 } else { 11958 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11959 + className + " does not exist in " + packageName); 11960 } 11961 } 11962 switch (newState) { 11963 case COMPONENT_ENABLED_STATE_ENABLED: 11964 if (!pkgSetting.enableComponentLPw(className, userId)) { 11965 return; 11966 } 11967 break; 11968 case COMPONENT_ENABLED_STATE_DISABLED: 11969 if (!pkgSetting.disableComponentLPw(className, userId)) { 11970 return; 11971 } 11972 break; 11973 case COMPONENT_ENABLED_STATE_DEFAULT: 11974 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11975 return; 11976 } 11977 break; 11978 default: 11979 Slog.e(TAG, "Invalid new component state: " + newState); 11980 return; 11981 } 11982 } 11983 scheduleWritePackageRestrictionsLocked(userId); 11984 components = mPendingBroadcasts.get(userId, packageName); 11985 final boolean newPackage = components == null; 11986 if (newPackage) { 11987 components = new ArrayList<String>(); 11988 } 11989 if (!components.contains(componentName)) { 11990 components.add(componentName); 11991 } 11992 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11993 sendNow = true; 11994 // Purge entry from pending broadcast list if another one exists already 11995 // since we are sending one right away. 11996 mPendingBroadcasts.remove(userId, packageName); 11997 } else { 11998 if (newPackage) { 11999 mPendingBroadcasts.put(userId, packageName, components); 12000 } 12001 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12002 // Schedule a message 12003 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12004 } 12005 } 12006 } 12007 12008 long callingId = Binder.clearCallingIdentity(); 12009 try { 12010 if (sendNow) { 12011 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12012 sendPackageChangedBroadcast(packageName, 12013 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12014 } 12015 } finally { 12016 Binder.restoreCallingIdentity(callingId); 12017 } 12018 } 12019 12020 private void sendPackageChangedBroadcast(String packageName, 12021 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12022 if (DEBUG_INSTALL) 12023 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12024 + componentNames); 12025 Bundle extras = new Bundle(4); 12026 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12027 String nameList[] = new String[componentNames.size()]; 12028 componentNames.toArray(nameList); 12029 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12030 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12031 extras.putInt(Intent.EXTRA_UID, packageUid); 12032 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12033 new int[] {UserHandle.getUserId(packageUid)}); 12034 } 12035 12036 @Override 12037 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12038 if (!sUserManager.exists(userId)) return; 12039 final int uid = Binder.getCallingUid(); 12040 final int permission = mContext.checkCallingOrSelfPermission( 12041 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12042 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12043 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12044 // writer 12045 synchronized (mPackages) { 12046 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12047 uid, userId)) { 12048 scheduleWritePackageRestrictionsLocked(userId); 12049 } 12050 } 12051 } 12052 12053 @Override 12054 public String getInstallerPackageName(String packageName) { 12055 // reader 12056 synchronized (mPackages) { 12057 return mSettings.getInstallerPackageNameLPr(packageName); 12058 } 12059 } 12060 12061 @Override 12062 public int getApplicationEnabledSetting(String packageName, int userId) { 12063 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12064 int uid = Binder.getCallingUid(); 12065 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12066 // reader 12067 synchronized (mPackages) { 12068 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12069 } 12070 } 12071 12072 @Override 12073 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12074 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12075 int uid = Binder.getCallingUid(); 12076 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12077 // reader 12078 synchronized (mPackages) { 12079 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12080 } 12081 } 12082 12083 @Override 12084 public void enterSafeMode() { 12085 enforceSystemOrRoot("Only the system can request entering safe mode"); 12086 12087 if (!mSystemReady) { 12088 mSafeMode = true; 12089 } 12090 } 12091 12092 @Override 12093 public void systemReady() { 12094 mSystemReady = true; 12095 12096 // Read the compatibilty setting when the system is ready. 12097 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12098 mContext.getContentResolver(), 12099 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12100 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12101 if (DEBUG_SETTINGS) { 12102 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12103 } 12104 12105 synchronized (mPackages) { 12106 // Verify that all of the preferred activity components actually 12107 // exist. It is possible for applications to be updated and at 12108 // that point remove a previously declared activity component that 12109 // had been set as a preferred activity. We try to clean this up 12110 // the next time we encounter that preferred activity, but it is 12111 // possible for the user flow to never be able to return to that 12112 // situation so here we do a sanity check to make sure we haven't 12113 // left any junk around. 12114 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12115 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12116 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12117 removed.clear(); 12118 for (PreferredActivity pa : pir.filterSet()) { 12119 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12120 removed.add(pa); 12121 } 12122 } 12123 if (removed.size() > 0) { 12124 for (int r=0; r<removed.size(); r++) { 12125 PreferredActivity pa = removed.get(r); 12126 Slog.w(TAG, "Removing dangling preferred activity: " 12127 + pa.mPref.mComponent); 12128 pir.removeFilter(pa); 12129 } 12130 mSettings.writePackageRestrictionsLPr( 12131 mSettings.mPreferredActivities.keyAt(i)); 12132 } 12133 } 12134 } 12135 sUserManager.systemReady(); 12136 12137 // Kick off any messages waiting for system ready 12138 if (mPostSystemReadyMessages != null) { 12139 for (Message msg : mPostSystemReadyMessages) { 12140 msg.sendToTarget(); 12141 } 12142 mPostSystemReadyMessages = null; 12143 } 12144 } 12145 12146 @Override 12147 public boolean isSafeMode() { 12148 return mSafeMode; 12149 } 12150 12151 @Override 12152 public boolean hasSystemUidErrors() { 12153 return mHasSystemUidErrors; 12154 } 12155 12156 static String arrayToString(int[] array) { 12157 StringBuffer buf = new StringBuffer(128); 12158 buf.append('['); 12159 if (array != null) { 12160 for (int i=0; i<array.length; i++) { 12161 if (i > 0) buf.append(", "); 12162 buf.append(array[i]); 12163 } 12164 } 12165 buf.append(']'); 12166 return buf.toString(); 12167 } 12168 12169 static class DumpState { 12170 public static final int DUMP_LIBS = 1 << 0; 12171 public static final int DUMP_FEATURES = 1 << 1; 12172 public static final int DUMP_RESOLVERS = 1 << 2; 12173 public static final int DUMP_PERMISSIONS = 1 << 3; 12174 public static final int DUMP_PACKAGES = 1 << 4; 12175 public static final int DUMP_SHARED_USERS = 1 << 5; 12176 public static final int DUMP_MESSAGES = 1 << 6; 12177 public static final int DUMP_PROVIDERS = 1 << 7; 12178 public static final int DUMP_VERIFIERS = 1 << 8; 12179 public static final int DUMP_PREFERRED = 1 << 9; 12180 public static final int DUMP_PREFERRED_XML = 1 << 10; 12181 public static final int DUMP_KEYSETS = 1 << 11; 12182 public static final int DUMP_VERSION = 1 << 12; 12183 public static final int DUMP_INSTALLS = 1 << 13; 12184 12185 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12186 12187 private int mTypes; 12188 12189 private int mOptions; 12190 12191 private boolean mTitlePrinted; 12192 12193 private SharedUserSetting mSharedUser; 12194 12195 public boolean isDumping(int type) { 12196 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12197 return true; 12198 } 12199 12200 return (mTypes & type) != 0; 12201 } 12202 12203 public void setDump(int type) { 12204 mTypes |= type; 12205 } 12206 12207 public boolean isOptionEnabled(int option) { 12208 return (mOptions & option) != 0; 12209 } 12210 12211 public void setOptionEnabled(int option) { 12212 mOptions |= option; 12213 } 12214 12215 public boolean onTitlePrinted() { 12216 final boolean printed = mTitlePrinted; 12217 mTitlePrinted = true; 12218 return printed; 12219 } 12220 12221 public boolean getTitlePrinted() { 12222 return mTitlePrinted; 12223 } 12224 12225 public void setTitlePrinted(boolean enabled) { 12226 mTitlePrinted = enabled; 12227 } 12228 12229 public SharedUserSetting getSharedUser() { 12230 return mSharedUser; 12231 } 12232 12233 public void setSharedUser(SharedUserSetting user) { 12234 mSharedUser = user; 12235 } 12236 } 12237 12238 @Override 12239 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12240 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12241 != PackageManager.PERMISSION_GRANTED) { 12242 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12243 + Binder.getCallingPid() 12244 + ", uid=" + Binder.getCallingUid() 12245 + " without permission " 12246 + android.Manifest.permission.DUMP); 12247 return; 12248 } 12249 12250 DumpState dumpState = new DumpState(); 12251 boolean fullPreferred = false; 12252 boolean checkin = false; 12253 12254 String packageName = null; 12255 12256 int opti = 0; 12257 while (opti < args.length) { 12258 String opt = args[opti]; 12259 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12260 break; 12261 } 12262 opti++; 12263 12264 if ("-a".equals(opt)) { 12265 // Right now we only know how to print all. 12266 } else if ("-h".equals(opt)) { 12267 pw.println("Package manager dump options:"); 12268 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12269 pw.println(" --checkin: dump for a checkin"); 12270 pw.println(" -f: print details of intent filters"); 12271 pw.println(" -h: print this help"); 12272 pw.println(" cmd may be one of:"); 12273 pw.println(" l[ibraries]: list known shared libraries"); 12274 pw.println(" f[ibraries]: list device features"); 12275 pw.println(" k[eysets]: print known keysets"); 12276 pw.println(" r[esolvers]: dump intent resolvers"); 12277 pw.println(" perm[issions]: dump permissions"); 12278 pw.println(" pref[erred]: print preferred package settings"); 12279 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12280 pw.println(" prov[iders]: dump content providers"); 12281 pw.println(" p[ackages]: dump installed packages"); 12282 pw.println(" s[hared-users]: dump shared user IDs"); 12283 pw.println(" m[essages]: print collected runtime messages"); 12284 pw.println(" v[erifiers]: print package verifier info"); 12285 pw.println(" version: print database version info"); 12286 pw.println(" write: write current settings now"); 12287 pw.println(" <package.name>: info about given package"); 12288 pw.println(" installs: details about install sessions"); 12289 return; 12290 } else if ("--checkin".equals(opt)) { 12291 checkin = true; 12292 } else if ("-f".equals(opt)) { 12293 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12294 } else { 12295 pw.println("Unknown argument: " + opt + "; use -h for help"); 12296 } 12297 } 12298 12299 // Is the caller requesting to dump a particular piece of data? 12300 if (opti < args.length) { 12301 String cmd = args[opti]; 12302 opti++; 12303 // Is this a package name? 12304 if ("android".equals(cmd) || cmd.contains(".")) { 12305 packageName = cmd; 12306 // When dumping a single package, we always dump all of its 12307 // filter information since the amount of data will be reasonable. 12308 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12309 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12310 dumpState.setDump(DumpState.DUMP_LIBS); 12311 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12312 dumpState.setDump(DumpState.DUMP_FEATURES); 12313 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12314 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12315 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12316 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12317 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12318 dumpState.setDump(DumpState.DUMP_PREFERRED); 12319 } else if ("preferred-xml".equals(cmd)) { 12320 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12321 if (opti < args.length && "--full".equals(args[opti])) { 12322 fullPreferred = true; 12323 opti++; 12324 } 12325 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12326 dumpState.setDump(DumpState.DUMP_PACKAGES); 12327 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12328 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12329 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12330 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12331 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12332 dumpState.setDump(DumpState.DUMP_MESSAGES); 12333 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12334 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12335 } else if ("version".equals(cmd)) { 12336 dumpState.setDump(DumpState.DUMP_VERSION); 12337 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12338 dumpState.setDump(DumpState.DUMP_KEYSETS); 12339 } else if ("installs".equals(cmd)) { 12340 dumpState.setDump(DumpState.DUMP_INSTALLS); 12341 } else if ("write".equals(cmd)) { 12342 synchronized (mPackages) { 12343 mSettings.writeLPr(); 12344 pw.println("Settings written."); 12345 return; 12346 } 12347 } 12348 } 12349 12350 if (checkin) { 12351 pw.println("vers,1"); 12352 } 12353 12354 // reader 12355 synchronized (mPackages) { 12356 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12357 if (!checkin) { 12358 if (dumpState.onTitlePrinted()) 12359 pw.println(); 12360 pw.println("Database versions:"); 12361 pw.print(" SDK Version:"); 12362 pw.print(" internal="); 12363 pw.print(mSettings.mInternalSdkPlatform); 12364 pw.print(" external="); 12365 pw.println(mSettings.mExternalSdkPlatform); 12366 pw.print(" DB Version:"); 12367 pw.print(" internal="); 12368 pw.print(mSettings.mInternalDatabaseVersion); 12369 pw.print(" external="); 12370 pw.println(mSettings.mExternalDatabaseVersion); 12371 } 12372 } 12373 12374 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12375 if (!checkin) { 12376 if (dumpState.onTitlePrinted()) 12377 pw.println(); 12378 pw.println("Verifiers:"); 12379 pw.print(" Required: "); 12380 pw.print(mRequiredVerifierPackage); 12381 pw.print(" (uid="); 12382 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12383 pw.println(")"); 12384 } else if (mRequiredVerifierPackage != null) { 12385 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12386 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12387 } 12388 } 12389 12390 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12391 boolean printedHeader = false; 12392 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12393 while (it.hasNext()) { 12394 String name = it.next(); 12395 SharedLibraryEntry ent = mSharedLibraries.get(name); 12396 if (!checkin) { 12397 if (!printedHeader) { 12398 if (dumpState.onTitlePrinted()) 12399 pw.println(); 12400 pw.println("Libraries:"); 12401 printedHeader = true; 12402 } 12403 pw.print(" "); 12404 } else { 12405 pw.print("lib,"); 12406 } 12407 pw.print(name); 12408 if (!checkin) { 12409 pw.print(" -> "); 12410 } 12411 if (ent.path != null) { 12412 if (!checkin) { 12413 pw.print("(jar) "); 12414 pw.print(ent.path); 12415 } else { 12416 pw.print(",jar,"); 12417 pw.print(ent.path); 12418 } 12419 } else { 12420 if (!checkin) { 12421 pw.print("(apk) "); 12422 pw.print(ent.apk); 12423 } else { 12424 pw.print(",apk,"); 12425 pw.print(ent.apk); 12426 } 12427 } 12428 pw.println(); 12429 } 12430 } 12431 12432 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12433 if (dumpState.onTitlePrinted()) 12434 pw.println(); 12435 if (!checkin) { 12436 pw.println("Features:"); 12437 } 12438 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12439 while (it.hasNext()) { 12440 String name = it.next(); 12441 if (!checkin) { 12442 pw.print(" "); 12443 } else { 12444 pw.print("feat,"); 12445 } 12446 pw.println(name); 12447 } 12448 } 12449 12450 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12451 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12452 : "Activity Resolver Table:", " ", packageName, 12453 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12454 dumpState.setTitlePrinted(true); 12455 } 12456 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12457 : "Receiver Resolver Table:", " ", packageName, 12458 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12459 dumpState.setTitlePrinted(true); 12460 } 12461 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12462 : "Service Resolver Table:", " ", packageName, 12463 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12464 dumpState.setTitlePrinted(true); 12465 } 12466 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12467 : "Provider Resolver Table:", " ", packageName, 12468 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12469 dumpState.setTitlePrinted(true); 12470 } 12471 } 12472 12473 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12474 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12475 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12476 int user = mSettings.mPreferredActivities.keyAt(i); 12477 if (pir.dump(pw, 12478 dumpState.getTitlePrinted() 12479 ? "\nPreferred Activities User " + user + ":" 12480 : "Preferred Activities User " + user + ":", " ", 12481 packageName, true, false)) { 12482 dumpState.setTitlePrinted(true); 12483 } 12484 } 12485 } 12486 12487 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12488 pw.flush(); 12489 FileOutputStream fout = new FileOutputStream(fd); 12490 BufferedOutputStream str = new BufferedOutputStream(fout); 12491 XmlSerializer serializer = new FastXmlSerializer(); 12492 try { 12493 serializer.setOutput(str, "utf-8"); 12494 serializer.startDocument(null, true); 12495 serializer.setFeature( 12496 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12497 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12498 serializer.endDocument(); 12499 serializer.flush(); 12500 } catch (IllegalArgumentException e) { 12501 pw.println("Failed writing: " + e); 12502 } catch (IllegalStateException e) { 12503 pw.println("Failed writing: " + e); 12504 } catch (IOException e) { 12505 pw.println("Failed writing: " + e); 12506 } 12507 } 12508 12509 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12510 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12511 if (packageName == null) { 12512 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12513 if (iperm == 0) { 12514 if (dumpState.onTitlePrinted()) 12515 pw.println(); 12516 pw.println("AppOp Permissions:"); 12517 } 12518 pw.print(" AppOp Permission "); 12519 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12520 pw.println(":"); 12521 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12522 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12523 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12524 } 12525 } 12526 } 12527 } 12528 12529 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12530 boolean printedSomething = false; 12531 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12532 if (packageName != null && !packageName.equals(p.info.packageName)) { 12533 continue; 12534 } 12535 if (!printedSomething) { 12536 if (dumpState.onTitlePrinted()) 12537 pw.println(); 12538 pw.println("Registered ContentProviders:"); 12539 printedSomething = true; 12540 } 12541 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12542 pw.print(" "); pw.println(p.toString()); 12543 } 12544 printedSomething = false; 12545 for (Map.Entry<String, PackageParser.Provider> entry : 12546 mProvidersByAuthority.entrySet()) { 12547 PackageParser.Provider p = entry.getValue(); 12548 if (packageName != null && !packageName.equals(p.info.packageName)) { 12549 continue; 12550 } 12551 if (!printedSomething) { 12552 if (dumpState.onTitlePrinted()) 12553 pw.println(); 12554 pw.println("ContentProvider Authorities:"); 12555 printedSomething = true; 12556 } 12557 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12558 pw.print(" "); pw.println(p.toString()); 12559 if (p.info != null && p.info.applicationInfo != null) { 12560 final String appInfo = p.info.applicationInfo.toString(); 12561 pw.print(" applicationInfo="); pw.println(appInfo); 12562 } 12563 } 12564 } 12565 12566 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12567 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12568 } 12569 12570 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12571 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12572 } 12573 12574 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12575 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 12576 } 12577 12578 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12579 // XXX should handle packageName != null by dumping only install data that 12580 // the given package is involved with. 12581 if (dumpState.onTitlePrinted()) pw.println(); 12582 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12583 } 12584 12585 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12586 if (dumpState.onTitlePrinted()) pw.println(); 12587 mSettings.dumpReadMessagesLPr(pw, dumpState); 12588 12589 pw.println(); 12590 pw.println("Package warning 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.println(line); 12598 } 12599 } catch (IOException ignored) { 12600 } finally { 12601 IoUtils.closeQuietly(in); 12602 } 12603 } 12604 12605 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12606 BufferedReader in = null; 12607 String line = null; 12608 try { 12609 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12610 while ((line = in.readLine()) != null) { 12611 if (line.contains("ignored: updated version")) continue; 12612 pw.print("msg,"); 12613 pw.println(line); 12614 } 12615 } catch (IOException ignored) { 12616 } finally { 12617 IoUtils.closeQuietly(in); 12618 } 12619 } 12620 } 12621 } 12622 12623 // ------- apps on sdcard specific code ------- 12624 static final boolean DEBUG_SD_INSTALL = false; 12625 12626 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12627 12628 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12629 12630 private boolean mMediaMounted = false; 12631 12632 static String getEncryptKey() { 12633 try { 12634 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12635 SD_ENCRYPTION_KEYSTORE_NAME); 12636 if (sdEncKey == null) { 12637 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12638 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12639 if (sdEncKey == null) { 12640 Slog.e(TAG, "Failed to create encryption keys"); 12641 return null; 12642 } 12643 } 12644 return sdEncKey; 12645 } catch (NoSuchAlgorithmException nsae) { 12646 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12647 return null; 12648 } catch (IOException ioe) { 12649 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12650 return null; 12651 } 12652 } 12653 12654 /* 12655 * Update media status on PackageManager. 12656 */ 12657 @Override 12658 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12659 int callingUid = Binder.getCallingUid(); 12660 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12661 throw new SecurityException("Media status can only be updated by the system"); 12662 } 12663 // reader; this apparently protects mMediaMounted, but should probably 12664 // be a different lock in that case. 12665 synchronized (mPackages) { 12666 Log.i(TAG, "Updating external media status from " 12667 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12668 + (mediaStatus ? "mounted" : "unmounted")); 12669 if (DEBUG_SD_INSTALL) 12670 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12671 + ", mMediaMounted=" + mMediaMounted); 12672 if (mediaStatus == mMediaMounted) { 12673 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12674 : 0, -1); 12675 mHandler.sendMessage(msg); 12676 return; 12677 } 12678 mMediaMounted = mediaStatus; 12679 } 12680 // Queue up an async operation since the package installation may take a 12681 // little while. 12682 mHandler.post(new Runnable() { 12683 public void run() { 12684 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12685 } 12686 }); 12687 } 12688 12689 /** 12690 * Called by MountService when the initial ASECs to scan are available. 12691 * Should block until all the ASEC containers are finished being scanned. 12692 */ 12693 public void scanAvailableAsecs() { 12694 updateExternalMediaStatusInner(true, false, false); 12695 if (mShouldRestoreconData) { 12696 SELinuxMMAC.setRestoreconDone(); 12697 mShouldRestoreconData = false; 12698 } 12699 } 12700 12701 /* 12702 * Collect information of applications on external media, map them against 12703 * existing containers and update information based on current mount status. 12704 * Please note that we always have to report status if reportStatus has been 12705 * set to true especially when unloading packages. 12706 */ 12707 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12708 boolean externalStorage) { 12709 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12710 int[] uidArr = EmptyArray.INT; 12711 12712 final String[] list = PackageHelper.getSecureContainerList(); 12713 if (ArrayUtils.isEmpty(list)) { 12714 Log.i(TAG, "No secure containers found"); 12715 } else { 12716 // Process list of secure containers and categorize them 12717 // as active or stale based on their package internal state. 12718 12719 // reader 12720 synchronized (mPackages) { 12721 for (String cid : list) { 12722 // Leave stages untouched for now; installer service owns them 12723 if (PackageInstallerService.isStageName(cid)) continue; 12724 12725 if (DEBUG_SD_INSTALL) 12726 Log.i(TAG, "Processing container " + cid); 12727 String pkgName = getAsecPackageName(cid); 12728 if (pkgName == null) { 12729 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12730 continue; 12731 } 12732 if (DEBUG_SD_INSTALL) 12733 Log.i(TAG, "Looking for pkg : " + pkgName); 12734 12735 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12736 if (ps == null) { 12737 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12738 continue; 12739 } 12740 12741 /* 12742 * Skip packages that are not external if we're unmounting 12743 * external storage. 12744 */ 12745 if (externalStorage && !isMounted && !isExternal(ps)) { 12746 continue; 12747 } 12748 12749 final AsecInstallArgs args = new AsecInstallArgs(cid, 12750 getAppDexInstructionSets(ps), ps.isForwardLocked()); 12751 // The package status is changed only if the code path 12752 // matches between settings and the container id. 12753 if (ps.codePathString != null 12754 && ps.codePathString.startsWith(args.getCodePath())) { 12755 if (DEBUG_SD_INSTALL) { 12756 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12757 + " at code path: " + ps.codePathString); 12758 } 12759 12760 // We do have a valid package installed on sdcard 12761 processCids.put(args, ps.codePathString); 12762 final int uid = ps.appId; 12763 if (uid != -1) { 12764 uidArr = ArrayUtils.appendInt(uidArr, uid); 12765 } 12766 } else { 12767 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12768 + ps.codePathString); 12769 } 12770 } 12771 } 12772 12773 Arrays.sort(uidArr); 12774 } 12775 12776 // Process packages with valid entries. 12777 if (isMounted) { 12778 if (DEBUG_SD_INSTALL) 12779 Log.i(TAG, "Loading packages"); 12780 loadMediaPackages(processCids, uidArr); 12781 startCleaningPackages(); 12782 mInstallerService.onSecureContainersAvailable(); 12783 } else { 12784 if (DEBUG_SD_INSTALL) 12785 Log.i(TAG, "Unloading packages"); 12786 unloadMediaPackages(processCids, uidArr, reportStatus); 12787 } 12788 } 12789 12790 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12791 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12792 int size = pkgList.size(); 12793 if (size > 0) { 12794 // Send broadcasts here 12795 Bundle extras = new Bundle(); 12796 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12797 .toArray(new String[size])); 12798 if (uidArr != null) { 12799 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12800 } 12801 if (replacing) { 12802 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12803 } 12804 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12805 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12806 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12807 } 12808 } 12809 12810 /* 12811 * Look at potentially valid container ids from processCids If package 12812 * information doesn't match the one on record or package scanning fails, 12813 * the cid is added to list of removeCids. We currently don't delete stale 12814 * containers. 12815 */ 12816 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12817 ArrayList<String> pkgList = new ArrayList<String>(); 12818 Set<AsecInstallArgs> keys = processCids.keySet(); 12819 12820 for (AsecInstallArgs args : keys) { 12821 String codePath = processCids.get(args); 12822 if (DEBUG_SD_INSTALL) 12823 Log.i(TAG, "Loading container : " + args.cid); 12824 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12825 try { 12826 // Make sure there are no container errors first. 12827 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12828 Slog.e(TAG, "Failed to mount cid : " + args.cid 12829 + " when installing from sdcard"); 12830 continue; 12831 } 12832 // Check code path here. 12833 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12834 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12835 + " does not match one in settings " + codePath); 12836 continue; 12837 } 12838 // Parse package 12839 int parseFlags = mDefParseFlags; 12840 if (args.isExternal()) { 12841 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12842 } 12843 if (args.isFwdLocked()) { 12844 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12845 } 12846 12847 synchronized (mInstallLock) { 12848 PackageParser.Package pkg = null; 12849 try { 12850 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12851 } catch (PackageManagerException e) { 12852 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12853 } 12854 // Scan the package 12855 if (pkg != null) { 12856 /* 12857 * TODO why is the lock being held? doPostInstall is 12858 * called in other places without the lock. This needs 12859 * to be straightened out. 12860 */ 12861 // writer 12862 synchronized (mPackages) { 12863 retCode = PackageManager.INSTALL_SUCCEEDED; 12864 pkgList.add(pkg.packageName); 12865 // Post process args 12866 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12867 pkg.applicationInfo.uid); 12868 } 12869 } else { 12870 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12871 } 12872 } 12873 12874 } finally { 12875 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12876 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12877 } 12878 } 12879 } 12880 // writer 12881 synchronized (mPackages) { 12882 // If the platform SDK has changed since the last time we booted, 12883 // we need to re-grant app permission to catch any new ones that 12884 // appear. This is really a hack, and means that apps can in some 12885 // cases get permissions that the user didn't initially explicitly 12886 // allow... it would be nice to have some better way to handle 12887 // this situation. 12888 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12889 if (regrantPermissions) 12890 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12891 + mSdkVersion + "; regranting permissions for external storage"); 12892 mSettings.mExternalSdkPlatform = mSdkVersion; 12893 12894 // Make sure group IDs have been assigned, and any permission 12895 // changes in other apps are accounted for 12896 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12897 | (regrantPermissions 12898 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12899 : 0)); 12900 12901 mSettings.updateExternalDatabaseVersion(); 12902 12903 // can downgrade to reader 12904 // Persist settings 12905 mSettings.writeLPr(); 12906 } 12907 // Send a broadcast to let everyone know we are done processing 12908 if (pkgList.size() > 0) { 12909 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12910 } 12911 } 12912 12913 /* 12914 * Utility method to unload a list of specified containers 12915 */ 12916 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12917 // Just unmount all valid containers. 12918 for (AsecInstallArgs arg : cidArgs) { 12919 synchronized (mInstallLock) { 12920 arg.doPostDeleteLI(false); 12921 } 12922 } 12923 } 12924 12925 /* 12926 * Unload packages mounted on external media. This involves deleting package 12927 * data from internal structures, sending broadcasts about diabled packages, 12928 * gc'ing to free up references, unmounting all secure containers 12929 * corresponding to packages on external media, and posting a 12930 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12931 * that we always have to post this message if status has been requested no 12932 * matter what. 12933 */ 12934 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12935 final boolean reportStatus) { 12936 if (DEBUG_SD_INSTALL) 12937 Log.i(TAG, "unloading media packages"); 12938 ArrayList<String> pkgList = new ArrayList<String>(); 12939 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12940 final Set<AsecInstallArgs> keys = processCids.keySet(); 12941 for (AsecInstallArgs args : keys) { 12942 String pkgName = args.getPackageName(); 12943 if (DEBUG_SD_INSTALL) 12944 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12945 // Delete package internally 12946 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12947 synchronized (mInstallLock) { 12948 boolean res = deletePackageLI(pkgName, null, false, null, null, 12949 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12950 if (res) { 12951 pkgList.add(pkgName); 12952 } else { 12953 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12954 failedList.add(args); 12955 } 12956 } 12957 } 12958 12959 // reader 12960 synchronized (mPackages) { 12961 // We didn't update the settings after removing each package; 12962 // write them now for all packages. 12963 mSettings.writeLPr(); 12964 } 12965 12966 // We have to absolutely send UPDATED_MEDIA_STATUS only 12967 // after confirming that all the receivers processed the ordered 12968 // broadcast when packages get disabled, force a gc to clean things up. 12969 // and unload all the containers. 12970 if (pkgList.size() > 0) { 12971 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12972 new IIntentReceiver.Stub() { 12973 public void performReceive(Intent intent, int resultCode, String data, 12974 Bundle extras, boolean ordered, boolean sticky, 12975 int sendingUser) throws RemoteException { 12976 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12977 reportStatus ? 1 : 0, 1, keys); 12978 mHandler.sendMessage(msg); 12979 } 12980 }); 12981 } else { 12982 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12983 keys); 12984 mHandler.sendMessage(msg); 12985 } 12986 } 12987 12988 /** Binder call */ 12989 @Override 12990 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12991 final int flags) { 12992 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12993 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12994 int returnCode = PackageManager.MOVE_SUCCEEDED; 12995 int currInstallFlags = 0; 12996 int newInstallFlags = 0; 12997 12998 File codeFile = null; 12999 String installerPackageName = null; 13000 String packageAbiOverride = null; 13001 13002 // reader 13003 synchronized (mPackages) { 13004 final PackageParser.Package pkg = mPackages.get(packageName); 13005 final PackageSetting ps = mSettings.mPackages.get(packageName); 13006 if (pkg == null || ps == null) { 13007 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13008 } else { 13009 // Disable moving fwd locked apps and system packages 13010 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13011 Slog.w(TAG, "Cannot move system application"); 13012 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13013 } else if (pkg.mOperationPending) { 13014 Slog.w(TAG, "Attempt to move package which has pending operations"); 13015 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13016 } else { 13017 // Find install location first 13018 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13019 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13020 Slog.w(TAG, "Ambigous flags specified for move location."); 13021 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13022 } else { 13023 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13024 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13025 currInstallFlags = isExternal(pkg) 13026 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13027 13028 if (newInstallFlags == currInstallFlags) { 13029 Slog.w(TAG, "No move required. Trying to move to same location"); 13030 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13031 } else { 13032 if (pkg.isForwardLocked()) { 13033 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13034 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13035 } 13036 } 13037 } 13038 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13039 pkg.mOperationPending = true; 13040 } 13041 } 13042 13043 codeFile = new File(pkg.codePath); 13044 installerPackageName = ps.installerPackageName; 13045 packageAbiOverride = ps.cpuAbiOverrideString; 13046 } 13047 } 13048 13049 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13050 try { 13051 observer.packageMoved(packageName, returnCode); 13052 } catch (RemoteException ignored) { 13053 } 13054 return; 13055 } 13056 13057 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13058 @Override 13059 public void onUserActionRequired(Intent intent) throws RemoteException { 13060 throw new IllegalStateException(); 13061 } 13062 13063 @Override 13064 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13065 Bundle extras) throws RemoteException { 13066 Slog.d(TAG, "Install result for move: " 13067 + PackageManager.installStatusToString(returnCode, msg)); 13068 13069 // We usually have a new package now after the install, but if 13070 // we failed we need to clear the pending flag on the original 13071 // package object. 13072 synchronized (mPackages) { 13073 final PackageParser.Package pkg = mPackages.get(packageName); 13074 if (pkg != null) { 13075 pkg.mOperationPending = false; 13076 } 13077 } 13078 13079 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13080 switch (status) { 13081 case PackageInstaller.STATUS_SUCCESS: 13082 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13083 break; 13084 case PackageInstaller.STATUS_FAILURE_STORAGE: 13085 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13086 break; 13087 default: 13088 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13089 break; 13090 } 13091 } 13092 }; 13093 13094 // Treat a move like reinstalling an existing app, which ensures that we 13095 // process everythign uniformly, like unpacking native libraries. 13096 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13097 13098 final Message msg = mHandler.obtainMessage(INIT_COPY); 13099 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13100 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13101 installerPackageName, null, user, packageAbiOverride); 13102 mHandler.sendMessage(msg); 13103 } 13104 13105 @Override 13106 public boolean setInstallLocation(int loc) { 13107 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13108 null); 13109 if (getInstallLocation() == loc) { 13110 return true; 13111 } 13112 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13113 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13114 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13115 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13116 return true; 13117 } 13118 return false; 13119 } 13120 13121 @Override 13122 public int getInstallLocation() { 13123 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13124 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13125 PackageHelper.APP_INSTALL_AUTO); 13126 } 13127 13128 /** Called by UserManagerService */ 13129 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13130 mDirtyUsers.remove(userHandle); 13131 mSettings.removeUserLPw(userHandle); 13132 mPendingBroadcasts.remove(userHandle); 13133 if (mInstaller != null) { 13134 // Technically, we shouldn't be doing this with the package lock 13135 // held. However, this is very rare, and there is already so much 13136 // other disk I/O going on, that we'll let it slide for now. 13137 mInstaller.removeUserDataDirs(userHandle); 13138 } 13139 mUserNeedsBadging.delete(userHandle); 13140 removeUnusedPackagesLILPw(userManager, userHandle); 13141 } 13142 13143 /** 13144 * We're removing userHandle and would like to remove any downloaded packages 13145 * that are no longer in use by any other user. 13146 * @param userHandle the user being removed 13147 */ 13148 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13149 final boolean DEBUG_CLEAN_APKS = false; 13150 int [] users = userManager.getUserIdsLPr(); 13151 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13152 while (psit.hasNext()) { 13153 PackageSetting ps = psit.next(); 13154 if (ps.pkg == null) { 13155 continue; 13156 } 13157 final String packageName = ps.pkg.packageName; 13158 // Skip over if system app 13159 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13160 continue; 13161 } 13162 if (DEBUG_CLEAN_APKS) { 13163 Slog.i(TAG, "Checking package " + packageName); 13164 } 13165 boolean keep = false; 13166 for (int i = 0; i < users.length; i++) { 13167 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13168 keep = true; 13169 if (DEBUG_CLEAN_APKS) { 13170 Slog.i(TAG, " Keeping package " + packageName + " for user " 13171 + users[i]); 13172 } 13173 break; 13174 } 13175 } 13176 if (!keep) { 13177 if (DEBUG_CLEAN_APKS) { 13178 Slog.i(TAG, " Removing package " + packageName); 13179 } 13180 mHandler.post(new Runnable() { 13181 public void run() { 13182 deletePackageX(packageName, userHandle, 0); 13183 } //end run 13184 }); 13185 } 13186 } 13187 } 13188 13189 /** Called by UserManagerService */ 13190 void createNewUserLILPw(int userHandle, File path) { 13191 if (mInstaller != null) { 13192 mInstaller.createUserConfig(userHandle); 13193 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13194 } 13195 } 13196 13197 @Override 13198 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13199 mContext.enforceCallingOrSelfPermission( 13200 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13201 "Only package verification agents can read the verifier device identity"); 13202 13203 synchronized (mPackages) { 13204 return mSettings.getVerifierDeviceIdentityLPw(); 13205 } 13206 } 13207 13208 @Override 13209 public void setPermissionEnforced(String permission, boolean enforced) { 13210 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13211 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13212 synchronized (mPackages) { 13213 if (mSettings.mReadExternalStorageEnforced == null 13214 || mSettings.mReadExternalStorageEnforced != enforced) { 13215 mSettings.mReadExternalStorageEnforced = enforced; 13216 mSettings.writeLPr(); 13217 } 13218 } 13219 // kill any non-foreground processes so we restart them and 13220 // grant/revoke the GID. 13221 final IActivityManager am = ActivityManagerNative.getDefault(); 13222 if (am != null) { 13223 final long token = Binder.clearCallingIdentity(); 13224 try { 13225 am.killProcessesBelowForeground("setPermissionEnforcement"); 13226 } catch (RemoteException e) { 13227 } finally { 13228 Binder.restoreCallingIdentity(token); 13229 } 13230 } 13231 } else { 13232 throw new IllegalArgumentException("No selective enforcement for " + permission); 13233 } 13234 } 13235 13236 @Override 13237 @Deprecated 13238 public boolean isPermissionEnforced(String permission) { 13239 return true; 13240 } 13241 13242 @Override 13243 public boolean isStorageLow() { 13244 final long token = Binder.clearCallingIdentity(); 13245 try { 13246 final DeviceStorageMonitorInternal 13247 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13248 if (dsm != null) { 13249 return dsm.isMemoryLow(); 13250 } else { 13251 return false; 13252 } 13253 } finally { 13254 Binder.restoreCallingIdentity(token); 13255 } 13256 } 13257 13258 @Override 13259 public IPackageInstaller getPackageInstaller() { 13260 return mInstallerService; 13261 } 13262 13263 private boolean userNeedsBadging(int userId) { 13264 int index = mUserNeedsBadging.indexOfKey(userId); 13265 if (index < 0) { 13266 final UserInfo userInfo; 13267 final long token = Binder.clearCallingIdentity(); 13268 try { 13269 userInfo = sUserManager.getUserInfo(userId); 13270 } finally { 13271 Binder.restoreCallingIdentity(token); 13272 } 13273 final boolean b; 13274 if (userInfo != null && userInfo.isManagedProfile()) { 13275 b = true; 13276 } else { 13277 b = false; 13278 } 13279 mUserNeedsBadging.put(userId, b); 13280 return b; 13281 } 13282 return mUserNeedsBadging.valueAt(index); 13283 } 13284 13285 @Override 13286 public KeySet getKeySetByAlias(String packageName, String alias) { 13287 if (packageName == null || alias == null) { 13288 return null; 13289 } 13290 synchronized(mPackages) { 13291 final PackageParser.Package pkg = mPackages.get(packageName); 13292 if (pkg == null) { 13293 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13294 throw new IllegalArgumentException("Unknown package: " + packageName); 13295 } 13296 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13297 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13298 } 13299 } 13300 13301 @Override 13302 public KeySet getSigningKeySet(String packageName) { 13303 if (packageName == null) { 13304 return null; 13305 } 13306 synchronized(mPackages) { 13307 final PackageParser.Package pkg = mPackages.get(packageName); 13308 if (pkg == null) { 13309 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13310 throw new IllegalArgumentException("Unknown package: " + packageName); 13311 } 13312 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13313 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13314 throw new SecurityException("May not access signing KeySet of other apps."); 13315 } 13316 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13317 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13318 } 13319 } 13320 13321 @Override 13322 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13323 if (packageName == null || ks == null) { 13324 return false; 13325 } 13326 synchronized(mPackages) { 13327 final PackageParser.Package pkg = mPackages.get(packageName); 13328 if (pkg == null) { 13329 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13330 throw new IllegalArgumentException("Unknown package: " + packageName); 13331 } 13332 IBinder ksh = ks.getToken(); 13333 if (ksh instanceof KeySetHandle) { 13334 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13335 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13336 } 13337 return false; 13338 } 13339 } 13340 13341 @Override 13342 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13343 if (packageName == null || ks == null) { 13344 return false; 13345 } 13346 synchronized(mPackages) { 13347 final PackageParser.Package pkg = mPackages.get(packageName); 13348 if (pkg == null) { 13349 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13350 throw new IllegalArgumentException("Unknown package: " + packageName); 13351 } 13352 IBinder ksh = ks.getToken(); 13353 if (ksh instanceof KeySetHandle) { 13354 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13355 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13356 } 13357 return false; 13358 } 13359 } 13360 13361 public void getUsageStatsIfNoPackageUsageInfo() { 13362 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 13363 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 13364 if (usm == null) { 13365 throw new IllegalStateException("UsageStatsManager must be initialized"); 13366 } 13367 long now = System.currentTimeMillis(); 13368 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 13369 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 13370 String packageName = entry.getKey(); 13371 PackageParser.Package pkg = mPackages.get(packageName); 13372 if (pkg == null) { 13373 continue; 13374 } 13375 UsageStats usage = entry.getValue(); 13376 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 13377 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 13378 } 13379 } 13380 } 13381 13382 /** 13383 * Check and throw if the given before/after packages would be considered a 13384 * downgrade. 13385 */ 13386 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 13387 throws PackageManagerException { 13388 if (after.versionCode < before.mVersionCode) { 13389 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13390 "Update version code " + after.versionCode + " is older than current " 13391 + before.mVersionCode); 13392 } else if (after.versionCode == before.mVersionCode) { 13393 if (after.baseRevisionCode < before.baseRevisionCode) { 13394 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13395 "Update base revision code " + after.baseRevisionCode 13396 + " is older than current " + before.baseRevisionCode); 13397 } 13398 13399 if (!ArrayUtils.isEmpty(after.splitNames)) { 13400 for (int i = 0; i < after.splitNames.length; i++) { 13401 final String splitName = after.splitNames[i]; 13402 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 13403 if (j != -1) { 13404 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 13405 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13406 "Update split " + splitName + " revision code " 13407 + after.splitRevisionCodes[i] + " is older than current " 13408 + before.splitRevisionCodes[j]); 13409 } 13410 } 13411 } 13412 } 13413 } 13414 } 13415} 13416