PackageManagerService.java revision 77e46d214db035f150e8522fad03edec913939e8
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; 62import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 63 64import android.util.ArrayMap; 65 66import com.android.internal.R; 67import com.android.internal.app.IMediaContainerService; 68import com.android.internal.app.ResolverActivity; 69import com.android.internal.content.NativeLibraryHelper; 70import com.android.internal.content.PackageHelper; 71import com.android.internal.os.IParcelFileDescriptorFactory; 72import com.android.internal.util.ArrayUtils; 73import com.android.internal.util.FastPrintWriter; 74import com.android.internal.util.FastXmlSerializer; 75import com.android.internal.util.IndentingPrintWriter; 76import com.android.server.EventLogTags; 77import com.android.server.IntentResolver; 78import com.android.server.LocalServices; 79import com.android.server.ServiceThread; 80import com.android.server.SystemConfig; 81import com.android.server.Watchdog; 82import com.android.server.pm.Settings.DatabaseVersion; 83import com.android.server.storage.DeviceStorageMonitorInternal; 84 85import org.xmlpull.v1.XmlSerializer; 86 87import android.app.ActivityManager; 88import android.app.ActivityManagerNative; 89import android.app.AppGlobals; 90import android.app.IActivityManager; 91import android.app.admin.IDevicePolicyManager; 92import android.app.backup.IBackupManager; 93import android.app.usage.UsageStats; 94import android.app.usage.UsageStatsManager; 95import android.content.BroadcastReceiver; 96import android.content.ComponentName; 97import android.content.Context; 98import android.content.IIntentReceiver; 99import android.content.Intent; 100import android.content.IntentFilter; 101import android.content.IntentSender; 102import android.content.IntentSender.SendIntentException; 103import android.content.ServiceConnection; 104import android.content.pm.ActivityInfo; 105import android.content.pm.ApplicationInfo; 106import android.content.pm.FeatureInfo; 107import android.content.pm.IPackageDataObserver; 108import android.content.pm.IPackageDeleteObserver; 109import android.content.pm.IPackageDeleteObserver2; 110import android.content.pm.IPackageInstallObserver2; 111import android.content.pm.IPackageInstaller; 112import android.content.pm.IPackageManager; 113import android.content.pm.IPackageMoveObserver; 114import android.content.pm.IPackageStatsObserver; 115import android.content.pm.InstrumentationInfo; 116import android.content.pm.KeySet; 117import android.content.pm.ManifestDigest; 118import android.content.pm.PackageCleanItem; 119import android.content.pm.PackageInfo; 120import android.content.pm.PackageInfoLite; 121import android.content.pm.PackageInstaller; 122import android.content.pm.PackageManager; 123import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 124import android.content.pm.PackageParser.ActivityIntentInfo; 125import android.content.pm.PackageParser.PackageLite; 126import android.content.pm.PackageParser.PackageParserException; 127import android.content.pm.PackageParser; 128import android.content.pm.PackageStats; 129import android.content.pm.PackageUserState; 130import android.content.pm.ParceledListSlice; 131import android.content.pm.PermissionGroupInfo; 132import android.content.pm.PermissionInfo; 133import android.content.pm.ProviderInfo; 134import android.content.pm.ResolveInfo; 135import android.content.pm.ServiceInfo; 136import android.content.pm.Signature; 137import android.content.pm.UserInfo; 138import android.content.pm.VerificationParams; 139import android.content.pm.VerifierDeviceIdentity; 140import android.content.pm.VerifierInfo; 141import android.content.res.Resources; 142import android.hardware.display.DisplayManager; 143import android.net.Uri; 144import android.os.Binder; 145import android.os.Build; 146import android.os.Bundle; 147import android.os.Environment; 148import android.os.Environment.UserEnvironment; 149import android.os.storage.IMountService; 150import android.os.storage.StorageManager; 151import android.os.Debug; 152import android.os.FileUtils; 153import android.os.Handler; 154import android.os.IBinder; 155import android.os.Looper; 156import android.os.Message; 157import android.os.Parcel; 158import android.os.ParcelFileDescriptor; 159import android.os.Process; 160import android.os.RemoteException; 161import android.os.SELinux; 162import android.os.ServiceManager; 163import android.os.SystemClock; 164import android.os.SystemProperties; 165import android.os.UserHandle; 166import android.os.UserManager; 167import android.security.KeyStore; 168import android.security.SystemKeyStore; 169import android.system.ErrnoException; 170import android.system.Os; 171import android.system.StructStat; 172import android.text.TextUtils; 173import android.text.format.DateUtils; 174import android.util.ArraySet; 175import android.util.AtomicFile; 176import android.util.DisplayMetrics; 177import android.util.EventLog; 178import android.util.ExceptionUtils; 179import android.util.Log; 180import android.util.LogPrinter; 181import android.util.PrintStreamPrinter; 182import android.util.Slog; 183import android.util.SparseArray; 184import android.util.SparseBooleanArray; 185import android.view.Display; 186 187import java.io.BufferedInputStream; 188import java.io.BufferedOutputStream; 189import java.io.BufferedReader; 190import java.io.File; 191import java.io.FileDescriptor; 192import java.io.FileNotFoundException; 193import java.io.FileOutputStream; 194import java.io.FileReader; 195import java.io.FilenameFilter; 196import java.io.IOException; 197import java.io.InputStream; 198import java.io.PrintWriter; 199import java.nio.charset.StandardCharsets; 200import java.security.NoSuchAlgorithmException; 201import java.security.PublicKey; 202import java.security.cert.CertificateEncodingException; 203import java.security.cert.CertificateException; 204import java.text.SimpleDateFormat; 205import java.util.ArrayList; 206import java.util.Arrays; 207import java.util.Collection; 208import java.util.Collections; 209import java.util.Comparator; 210import java.util.Date; 211import java.util.Iterator; 212import java.util.List; 213import java.util.Map; 214import java.util.Objects; 215import java.util.Set; 216import java.util.concurrent.atomic.AtomicBoolean; 217import java.util.concurrent.atomic.AtomicLong; 218 219import dalvik.system.DexFile; 220import dalvik.system.VMRuntime; 221 222import libcore.io.IoUtils; 223import libcore.util.EmptyArray; 224 225/** 226 * Keep track of all those .apks everywhere. 227 * 228 * This is very central to the platform's security; please run the unit 229 * tests whenever making modifications here: 230 * 231mmm frameworks/base/tests/AndroidTests 232adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 233adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 234 * 235 * {@hide} 236 */ 237public class PackageManagerService extends IPackageManager.Stub { 238 static final String TAG = "PackageManager"; 239 static final boolean DEBUG_SETTINGS = false; 240 static final boolean DEBUG_PREFERRED = false; 241 static final boolean DEBUG_UPGRADE = false; 242 private static final boolean DEBUG_INSTALL = false; 243 private static final boolean DEBUG_REMOVE = false; 244 private static final boolean DEBUG_BROADCASTS = false; 245 private static final boolean DEBUG_SHOW_INFO = false; 246 private static final boolean DEBUG_PACKAGE_INFO = false; 247 private static final boolean DEBUG_INTENT_MATCHING = false; 248 private static final boolean DEBUG_PACKAGE_SCANNING = false; 249 private static final boolean DEBUG_VERIFY = false; 250 private static final boolean DEBUG_DEXOPT = false; 251 private static final boolean DEBUG_ABI_SELECTION = false; 252 253 private static final int RADIO_UID = Process.PHONE_UID; 254 private static final int LOG_UID = Process.LOG_UID; 255 private static final int NFC_UID = Process.NFC_UID; 256 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 257 private static final int SHELL_UID = Process.SHELL_UID; 258 259 // Cap the size of permission trees that 3rd party apps can define 260 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 261 262 // Suffix used during package installation when copying/moving 263 // package apks to install directory. 264 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 265 266 static final int SCAN_NO_DEX = 1<<1; 267 static final int SCAN_FORCE_DEX = 1<<2; 268 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 269 static final int SCAN_NEW_INSTALL = 1<<4; 270 static final int SCAN_NO_PATHS = 1<<5; 271 static final int SCAN_UPDATE_TIME = 1<<6; 272 static final int SCAN_DEFER_DEX = 1<<7; 273 static final int SCAN_BOOTING = 1<<8; 274 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 275 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 276 static final int SCAN_REPLACING = 1<<11; 277 static final int SCAN_REQUIRE_KNOWN = 1<<12; 278 279 static final int REMOVE_CHATTY = 1<<16; 280 281 /** 282 * Timeout (in milliseconds) after which the watchdog should declare that 283 * our handler thread is wedged. The usual default for such things is one 284 * minute but we sometimes do very lengthy I/O operations on this thread, 285 * such as installing multi-gigabyte applications, so ours needs to be longer. 286 */ 287 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 288 289 /** 290 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 291 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 292 * settings entry if available, otherwise we use the hardcoded default. If it's been 293 * more than this long since the last fstrim, we force one during the boot sequence. 294 * 295 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 296 * one gets run at the next available charging+idle time. This final mandatory 297 * no-fstrim check kicks in only of the other scheduling criteria is never met. 298 */ 299 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 300 301 /** 302 * Whether verification is enabled by default. 303 */ 304 private static final boolean DEFAULT_VERIFY_ENABLE = true; 305 306 /** 307 * The default maximum time to wait for the verification agent to return in 308 * milliseconds. 309 */ 310 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 311 312 /** 313 * The default response for package verification timeout. 314 * 315 * This can be either PackageManager.VERIFICATION_ALLOW or 316 * PackageManager.VERIFICATION_REJECT. 317 */ 318 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 319 320 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 321 322 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 323 DEFAULT_CONTAINER_PACKAGE, 324 "com.android.defcontainer.DefaultContainerService"); 325 326 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 327 328 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 329 330 final ServiceThread mHandlerThread; 331 332 final PackageHandler mHandler; 333 334 /** 335 * Messages for {@link #mHandler} that need to wait for system ready before 336 * being dispatched. 337 */ 338 private ArrayList<Message> mPostSystemReadyMessages; 339 340 final int mSdkVersion = Build.VERSION.SDK_INT; 341 342 final Context mContext; 343 final boolean mFactoryTest; 344 final boolean mOnlyCore; 345 final boolean mLazyDexOpt; 346 final long mDexOptLRUThresholdInMills; 347 final DisplayMetrics mMetrics; 348 final int mDefParseFlags; 349 final String[] mSeparateProcesses; 350 final boolean mIsUpgrade; 351 352 // This is where all application persistent data goes. 353 final File mAppDataDir; 354 355 // This is where all application persistent data goes for secondary users. 356 final File mUserAppDataDir; 357 358 /** The location for ASEC container files on internal storage. */ 359 final String mAsecInternalPath; 360 361 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 362 // LOCK HELD. Can be called with mInstallLock held. 363 final Installer mInstaller; 364 365 /** Directory where installed third-party apps stored */ 366 final File mAppInstallDir; 367 368 /** 369 * Directory to which applications installed internally have their 370 * 32 bit native libraries copied. 371 */ 372 private File mAppLib32InstallDir; 373 374 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 375 // apps. 376 final File mDrmAppPrivateInstallDir; 377 378 // ---------------------------------------------------------------- 379 380 // Lock for state used when installing and doing other long running 381 // operations. Methods that must be called with this lock held have 382 // the suffix "LI". 383 final Object mInstallLock = new Object(); 384 385 // ---------------------------------------------------------------- 386 387 // Keys are String (package name), values are Package. This also serves 388 // as the lock for the global state. Methods that must be called with 389 // this lock held have the prefix "LP". 390 final ArrayMap<String, PackageParser.Package> mPackages = 391 new ArrayMap<String, PackageParser.Package>(); 392 393 // Tracks available target package names -> overlay package paths. 394 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 395 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 396 397 final Settings mSettings; 398 boolean mRestoredSettings; 399 400 // System configuration read by SystemConfig. 401 final int[] mGlobalGids; 402 final SparseArray<ArraySet<String>> mSystemPermissions; 403 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 404 405 // If mac_permissions.xml was found for seinfo labeling. 406 boolean mFoundPolicyFile; 407 408 // If a recursive restorecon of /data/data/<pkg> is needed. 409 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 410 411 public static final class SharedLibraryEntry { 412 public final String path; 413 public final String apk; 414 415 SharedLibraryEntry(String _path, String _apk) { 416 path = _path; 417 apk = _apk; 418 } 419 } 420 421 // Currently known shared libraries. 422 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 423 new ArrayMap<String, SharedLibraryEntry>(); 424 425 // All available activities, for your resolving pleasure. 426 final ActivityIntentResolver mActivities = 427 new ActivityIntentResolver(); 428 429 // All available receivers, for your resolving pleasure. 430 final ActivityIntentResolver mReceivers = 431 new ActivityIntentResolver(); 432 433 // All available services, for your resolving pleasure. 434 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 435 436 // All available providers, for your resolving pleasure. 437 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 438 439 // Mapping from provider base names (first directory in content URI codePath) 440 // to the provider information. 441 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 442 new ArrayMap<String, PackageParser.Provider>(); 443 444 // Mapping from instrumentation class names to info about them. 445 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 446 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 447 448 // Mapping from permission names to info about them. 449 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 450 new ArrayMap<String, PackageParser.PermissionGroup>(); 451 452 // Packages whose data we have transfered into another package, thus 453 // should no longer exist. 454 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 455 456 // Broadcast actions that are only available to the system. 457 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 458 459 /** List of packages waiting for verification. */ 460 final SparseArray<PackageVerificationState> mPendingVerification 461 = new SparseArray<PackageVerificationState>(); 462 463 /** Set of packages associated with each app op permission. */ 464 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 465 466 final PackageInstallerService mInstallerService; 467 468 private final PackageDexOptimizer mPackageDexOptimizer; 469 // Cache of users who need badging. 470 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 471 472 /** Token for keys in mPendingVerification. */ 473 private int mPendingVerificationToken = 0; 474 475 volatile boolean mSystemReady; 476 volatile boolean mSafeMode; 477 volatile boolean mHasSystemUidErrors; 478 479 ApplicationInfo mAndroidApplication; 480 final ActivityInfo mResolveActivity = new ActivityInfo(); 481 final ResolveInfo mResolveInfo = new ResolveInfo(); 482 ComponentName mResolveComponentName; 483 PackageParser.Package mPlatformPackage; 484 ComponentName mCustomResolverComponentName; 485 486 boolean mResolverReplaced = false; 487 488 // Set of pending broadcasts for aggregating enable/disable of components. 489 static class PendingPackageBroadcasts { 490 // for each user id, a map of <package name -> components within that package> 491 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 492 493 public PendingPackageBroadcasts() { 494 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 495 } 496 497 public ArrayList<String> get(int userId, String packageName) { 498 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 499 return packages.get(packageName); 500 } 501 502 public void put(int userId, String packageName, ArrayList<String> components) { 503 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 504 packages.put(packageName, components); 505 } 506 507 public void remove(int userId, String packageName) { 508 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 509 if (packages != null) { 510 packages.remove(packageName); 511 } 512 } 513 514 public void remove(int userId) { 515 mUidMap.remove(userId); 516 } 517 518 public int userIdCount() { 519 return mUidMap.size(); 520 } 521 522 public int userIdAt(int n) { 523 return mUidMap.keyAt(n); 524 } 525 526 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 527 return mUidMap.get(userId); 528 } 529 530 public int size() { 531 // total number of pending broadcast entries across all userIds 532 int num = 0; 533 for (int i = 0; i< mUidMap.size(); i++) { 534 num += mUidMap.valueAt(i).size(); 535 } 536 return num; 537 } 538 539 public void clear() { 540 mUidMap.clear(); 541 } 542 543 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 544 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 545 if (map == null) { 546 map = new ArrayMap<String, ArrayList<String>>(); 547 mUidMap.put(userId, map); 548 } 549 return map; 550 } 551 } 552 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 553 554 // Service Connection to remote media container service to copy 555 // package uri's from external media onto secure containers 556 // or internal storage. 557 private IMediaContainerService mContainerService = null; 558 559 static final int SEND_PENDING_BROADCAST = 1; 560 static final int MCS_BOUND = 3; 561 static final int END_COPY = 4; 562 static final int INIT_COPY = 5; 563 static final int MCS_UNBIND = 6; 564 static final int START_CLEANING_PACKAGE = 7; 565 static final int FIND_INSTALL_LOC = 8; 566 static final int POST_INSTALL = 9; 567 static final int MCS_RECONNECT = 10; 568 static final int MCS_GIVE_UP = 11; 569 static final int UPDATED_MEDIA_STATUS = 12; 570 static final int WRITE_SETTINGS = 13; 571 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 572 static final int PACKAGE_VERIFIED = 15; 573 static final int CHECK_PENDING_VERIFICATION = 16; 574 575 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 576 577 // Delay time in millisecs 578 static final int BROADCAST_DELAY = 10 * 1000; 579 580 static UserManagerService sUserManager; 581 582 // Stores a list of users whose package restrictions file needs to be updated 583 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 584 585 final private DefaultContainerConnection mDefContainerConn = 586 new DefaultContainerConnection(); 587 class DefaultContainerConnection implements ServiceConnection { 588 public void onServiceConnected(ComponentName name, IBinder service) { 589 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 590 IMediaContainerService imcs = 591 IMediaContainerService.Stub.asInterface(service); 592 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 593 } 594 595 public void onServiceDisconnected(ComponentName name) { 596 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 597 } 598 }; 599 600 // Recordkeeping of restore-after-install operations that are currently in flight 601 // between the Package Manager and the Backup Manager 602 class PostInstallData { 603 public InstallArgs args; 604 public PackageInstalledInfo res; 605 606 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 607 args = _a; 608 res = _r; 609 } 610 }; 611 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 612 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 613 614 private final String mRequiredVerifierPackage; 615 616 private final PackageUsage mPackageUsage = new PackageUsage(); 617 618 private class PackageUsage { 619 private static final int WRITE_INTERVAL 620 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 621 622 private final Object mFileLock = new Object(); 623 private final AtomicLong mLastWritten = new AtomicLong(0); 624 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 625 626 private boolean mIsHistoricalPackageUsageAvailable = true; 627 628 boolean isHistoricalPackageUsageAvailable() { 629 return mIsHistoricalPackageUsageAvailable; 630 } 631 632 void write(boolean force) { 633 if (force) { 634 writeInternal(); 635 return; 636 } 637 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 638 && !DEBUG_DEXOPT) { 639 return; 640 } 641 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 642 new Thread("PackageUsage_DiskWriter") { 643 @Override 644 public void run() { 645 try { 646 writeInternal(); 647 } finally { 648 mBackgroundWriteRunning.set(false); 649 } 650 } 651 }.start(); 652 } 653 } 654 655 private void writeInternal() { 656 synchronized (mPackages) { 657 synchronized (mFileLock) { 658 AtomicFile file = getFile(); 659 FileOutputStream f = null; 660 try { 661 f = file.startWrite(); 662 BufferedOutputStream out = new BufferedOutputStream(f); 663 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 664 StringBuilder sb = new StringBuilder(); 665 for (PackageParser.Package pkg : mPackages.values()) { 666 if (pkg.mLastPackageUsageTimeInMills == 0) { 667 continue; 668 } 669 sb.setLength(0); 670 sb.append(pkg.packageName); 671 sb.append(' '); 672 sb.append((long)pkg.mLastPackageUsageTimeInMills); 673 sb.append('\n'); 674 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 675 } 676 out.flush(); 677 file.finishWrite(f); 678 } catch (IOException e) { 679 if (f != null) { 680 file.failWrite(f); 681 } 682 Log.e(TAG, "Failed to write package usage times", e); 683 } 684 } 685 } 686 mLastWritten.set(SystemClock.elapsedRealtime()); 687 } 688 689 void readLP() { 690 synchronized (mFileLock) { 691 AtomicFile file = getFile(); 692 BufferedInputStream in = null; 693 try { 694 in = new BufferedInputStream(file.openRead()); 695 StringBuffer sb = new StringBuffer(); 696 while (true) { 697 String packageName = readToken(in, sb, ' '); 698 if (packageName == null) { 699 break; 700 } 701 String timeInMillisString = readToken(in, sb, '\n'); 702 if (timeInMillisString == null) { 703 throw new IOException("Failed to find last usage time for package " 704 + packageName); 705 } 706 PackageParser.Package pkg = mPackages.get(packageName); 707 if (pkg == null) { 708 continue; 709 } 710 long timeInMillis; 711 try { 712 timeInMillis = Long.parseLong(timeInMillisString.toString()); 713 } catch (NumberFormatException e) { 714 throw new IOException("Failed to parse " + timeInMillisString 715 + " as a long.", e); 716 } 717 pkg.mLastPackageUsageTimeInMills = timeInMillis; 718 } 719 } catch (FileNotFoundException expected) { 720 mIsHistoricalPackageUsageAvailable = false; 721 } catch (IOException e) { 722 Log.w(TAG, "Failed to read package usage times", e); 723 } finally { 724 IoUtils.closeQuietly(in); 725 } 726 } 727 mLastWritten.set(SystemClock.elapsedRealtime()); 728 } 729 730 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 731 throws IOException { 732 sb.setLength(0); 733 while (true) { 734 int ch = in.read(); 735 if (ch == -1) { 736 if (sb.length() == 0) { 737 return null; 738 } 739 throw new IOException("Unexpected EOF"); 740 } 741 if (ch == endOfToken) { 742 return sb.toString(); 743 } 744 sb.append((char)ch); 745 } 746 } 747 748 private AtomicFile getFile() { 749 File dataDir = Environment.getDataDirectory(); 750 File systemDir = new File(dataDir, "system"); 751 File fname = new File(systemDir, "package-usage.list"); 752 return new AtomicFile(fname); 753 } 754 } 755 756 class PackageHandler extends Handler { 757 private boolean mBound = false; 758 final ArrayList<HandlerParams> mPendingInstalls = 759 new ArrayList<HandlerParams>(); 760 761 private boolean connectToService() { 762 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 763 " DefaultContainerService"); 764 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 765 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 766 if (mContext.bindServiceAsUser(service, mDefContainerConn, 767 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 768 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 769 mBound = true; 770 return true; 771 } 772 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 773 return false; 774 } 775 776 private void disconnectService() { 777 mContainerService = null; 778 mBound = false; 779 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 780 mContext.unbindService(mDefContainerConn); 781 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 782 } 783 784 PackageHandler(Looper looper) { 785 super(looper); 786 } 787 788 public void handleMessage(Message msg) { 789 try { 790 doHandleMessage(msg); 791 } finally { 792 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 793 } 794 } 795 796 void doHandleMessage(Message msg) { 797 switch (msg.what) { 798 case INIT_COPY: { 799 HandlerParams params = (HandlerParams) msg.obj; 800 int idx = mPendingInstalls.size(); 801 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 802 // If a bind was already initiated we dont really 803 // need to do anything. The pending install 804 // will be processed later on. 805 if (!mBound) { 806 // If this is the only one pending we might 807 // have to bind to the service again. 808 if (!connectToService()) { 809 Slog.e(TAG, "Failed to bind to media container service"); 810 params.serviceError(); 811 return; 812 } else { 813 // Once we bind to the service, the first 814 // pending request will be processed. 815 mPendingInstalls.add(idx, params); 816 } 817 } else { 818 mPendingInstalls.add(idx, params); 819 // Already bound to the service. Just make 820 // sure we trigger off processing the first request. 821 if (idx == 0) { 822 mHandler.sendEmptyMessage(MCS_BOUND); 823 } 824 } 825 break; 826 } 827 case MCS_BOUND: { 828 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 829 if (msg.obj != null) { 830 mContainerService = (IMediaContainerService) msg.obj; 831 } 832 if (mContainerService == null) { 833 // Something seriously wrong. Bail out 834 Slog.e(TAG, "Cannot bind to media container service"); 835 for (HandlerParams params : mPendingInstalls) { 836 // Indicate service bind error 837 params.serviceError(); 838 } 839 mPendingInstalls.clear(); 840 } else if (mPendingInstalls.size() > 0) { 841 HandlerParams params = mPendingInstalls.get(0); 842 if (params != null) { 843 if (params.startCopy()) { 844 // We are done... look for more work or to 845 // go idle. 846 if (DEBUG_SD_INSTALL) Log.i(TAG, 847 "Checking for more work or unbind..."); 848 // Delete pending install 849 if (mPendingInstalls.size() > 0) { 850 mPendingInstalls.remove(0); 851 } 852 if (mPendingInstalls.size() == 0) { 853 if (mBound) { 854 if (DEBUG_SD_INSTALL) Log.i(TAG, 855 "Posting delayed MCS_UNBIND"); 856 removeMessages(MCS_UNBIND); 857 Message ubmsg = obtainMessage(MCS_UNBIND); 858 // Unbind after a little delay, to avoid 859 // continual thrashing. 860 sendMessageDelayed(ubmsg, 10000); 861 } 862 } else { 863 // There are more pending requests in queue. 864 // Just post MCS_BOUND message to trigger processing 865 // of next pending install. 866 if (DEBUG_SD_INSTALL) Log.i(TAG, 867 "Posting MCS_BOUND for next work"); 868 mHandler.sendEmptyMessage(MCS_BOUND); 869 } 870 } 871 } 872 } else { 873 // Should never happen ideally. 874 Slog.w(TAG, "Empty queue"); 875 } 876 break; 877 } 878 case MCS_RECONNECT: { 879 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 880 if (mPendingInstalls.size() > 0) { 881 if (mBound) { 882 disconnectService(); 883 } 884 if (!connectToService()) { 885 Slog.e(TAG, "Failed to bind to media container service"); 886 for (HandlerParams params : mPendingInstalls) { 887 // Indicate service bind error 888 params.serviceError(); 889 } 890 mPendingInstalls.clear(); 891 } 892 } 893 break; 894 } 895 case MCS_UNBIND: { 896 // If there is no actual work left, then time to unbind. 897 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 898 899 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 900 if (mBound) { 901 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 902 903 disconnectService(); 904 } 905 } else if (mPendingInstalls.size() > 0) { 906 // There are more pending requests in queue. 907 // Just post MCS_BOUND message to trigger processing 908 // of next pending install. 909 mHandler.sendEmptyMessage(MCS_BOUND); 910 } 911 912 break; 913 } 914 case MCS_GIVE_UP: { 915 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 916 mPendingInstalls.remove(0); 917 break; 918 } 919 case SEND_PENDING_BROADCAST: { 920 String packages[]; 921 ArrayList<String> components[]; 922 int size = 0; 923 int uids[]; 924 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 925 synchronized (mPackages) { 926 if (mPendingBroadcasts == null) { 927 return; 928 } 929 size = mPendingBroadcasts.size(); 930 if (size <= 0) { 931 // Nothing to be done. Just return 932 return; 933 } 934 packages = new String[size]; 935 components = new ArrayList[size]; 936 uids = new int[size]; 937 int i = 0; // filling out the above arrays 938 939 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 940 int packageUserId = mPendingBroadcasts.userIdAt(n); 941 Iterator<Map.Entry<String, ArrayList<String>>> it 942 = mPendingBroadcasts.packagesForUserId(packageUserId) 943 .entrySet().iterator(); 944 while (it.hasNext() && i < size) { 945 Map.Entry<String, ArrayList<String>> ent = it.next(); 946 packages[i] = ent.getKey(); 947 components[i] = ent.getValue(); 948 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 949 uids[i] = (ps != null) 950 ? UserHandle.getUid(packageUserId, ps.appId) 951 : -1; 952 i++; 953 } 954 } 955 size = i; 956 mPendingBroadcasts.clear(); 957 } 958 // Send broadcasts 959 for (int i = 0; i < size; i++) { 960 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 961 } 962 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 963 break; 964 } 965 case START_CLEANING_PACKAGE: { 966 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 967 final String packageName = (String)msg.obj; 968 final int userId = msg.arg1; 969 final boolean andCode = msg.arg2 != 0; 970 synchronized (mPackages) { 971 if (userId == UserHandle.USER_ALL) { 972 int[] users = sUserManager.getUserIds(); 973 for (int user : users) { 974 mSettings.addPackageToCleanLPw( 975 new PackageCleanItem(user, packageName, andCode)); 976 } 977 } else { 978 mSettings.addPackageToCleanLPw( 979 new PackageCleanItem(userId, packageName, andCode)); 980 } 981 } 982 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 983 startCleaningPackages(); 984 } break; 985 case POST_INSTALL: { 986 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 987 PostInstallData data = mRunningInstalls.get(msg.arg1); 988 mRunningInstalls.delete(msg.arg1); 989 boolean deleteOld = false; 990 991 if (data != null) { 992 InstallArgs args = data.args; 993 PackageInstalledInfo res = data.res; 994 995 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 996 res.removedInfo.sendBroadcast(false, true, false); 997 Bundle extras = new Bundle(1); 998 extras.putInt(Intent.EXTRA_UID, res.uid); 999 // Determine the set of users who are adding this 1000 // package for the first time vs. those who are seeing 1001 // an update. 1002 int[] firstUsers; 1003 int[] updateUsers = new int[0]; 1004 if (res.origUsers == null || res.origUsers.length == 0) { 1005 firstUsers = res.newUsers; 1006 } else { 1007 firstUsers = new int[0]; 1008 for (int i=0; i<res.newUsers.length; i++) { 1009 int user = res.newUsers[i]; 1010 boolean isNew = true; 1011 for (int j=0; j<res.origUsers.length; j++) { 1012 if (res.origUsers[j] == user) { 1013 isNew = false; 1014 break; 1015 } 1016 } 1017 if (isNew) { 1018 int[] newFirst = new int[firstUsers.length+1]; 1019 System.arraycopy(firstUsers, 0, newFirst, 0, 1020 firstUsers.length); 1021 newFirst[firstUsers.length] = user; 1022 firstUsers = newFirst; 1023 } else { 1024 int[] newUpdate = new int[updateUsers.length+1]; 1025 System.arraycopy(updateUsers, 0, newUpdate, 0, 1026 updateUsers.length); 1027 newUpdate[updateUsers.length] = user; 1028 updateUsers = newUpdate; 1029 } 1030 } 1031 } 1032 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1033 res.pkg.applicationInfo.packageName, 1034 extras, null, null, firstUsers); 1035 final boolean update = res.removedInfo.removedPackage != null; 1036 if (update) { 1037 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1038 } 1039 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1040 res.pkg.applicationInfo.packageName, 1041 extras, null, null, updateUsers); 1042 if (update) { 1043 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1044 res.pkg.applicationInfo.packageName, 1045 extras, null, null, updateUsers); 1046 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1047 null, null, 1048 res.pkg.applicationInfo.packageName, null, updateUsers); 1049 1050 // treat asec-hosted packages like removable media on upgrade 1051 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1052 if (DEBUG_INSTALL) { 1053 Slog.i(TAG, "upgrading pkg " + res.pkg 1054 + " is ASEC-hosted -> AVAILABLE"); 1055 } 1056 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1057 ArrayList<String> pkgList = new ArrayList<String>(1); 1058 pkgList.add(res.pkg.applicationInfo.packageName); 1059 sendResourcesChangedBroadcast(true, true, 1060 pkgList,uidArray, null); 1061 } 1062 } 1063 if (res.removedInfo.args != null) { 1064 // Remove the replaced package's older resources safely now 1065 deleteOld = true; 1066 } 1067 1068 // Log current value of "unknown sources" setting 1069 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1070 getUnknownSourcesSettings()); 1071 } 1072 // Force a gc to clear up things 1073 Runtime.getRuntime().gc(); 1074 // We delete after a gc for applications on sdcard. 1075 if (deleteOld) { 1076 synchronized (mInstallLock) { 1077 res.removedInfo.args.doPostDeleteLI(true); 1078 } 1079 } 1080 if (args.observer != null) { 1081 try { 1082 Bundle extras = extrasForInstallResult(res); 1083 args.observer.onPackageInstalled(res.name, res.returnCode, 1084 res.returnMsg, extras); 1085 } catch (RemoteException e) { 1086 Slog.i(TAG, "Observer no longer exists."); 1087 } 1088 } 1089 } else { 1090 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1091 } 1092 } break; 1093 case UPDATED_MEDIA_STATUS: { 1094 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1095 boolean reportStatus = msg.arg1 == 1; 1096 boolean doGc = msg.arg2 == 1; 1097 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1098 if (doGc) { 1099 // Force a gc to clear up stale containers. 1100 Runtime.getRuntime().gc(); 1101 } 1102 if (msg.obj != null) { 1103 @SuppressWarnings("unchecked") 1104 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1105 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1106 // Unload containers 1107 unloadAllContainers(args); 1108 } 1109 if (reportStatus) { 1110 try { 1111 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1112 PackageHelper.getMountService().finishMediaUpdate(); 1113 } catch (RemoteException e) { 1114 Log.e(TAG, "MountService not running?"); 1115 } 1116 } 1117 } break; 1118 case WRITE_SETTINGS: { 1119 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1120 synchronized (mPackages) { 1121 removeMessages(WRITE_SETTINGS); 1122 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1123 mSettings.writeLPr(); 1124 mDirtyUsers.clear(); 1125 } 1126 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1127 } break; 1128 case WRITE_PACKAGE_RESTRICTIONS: { 1129 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1130 synchronized (mPackages) { 1131 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1132 for (int userId : mDirtyUsers) { 1133 mSettings.writePackageRestrictionsLPr(userId); 1134 } 1135 mDirtyUsers.clear(); 1136 } 1137 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1138 } break; 1139 case CHECK_PENDING_VERIFICATION: { 1140 final int verificationId = msg.arg1; 1141 final PackageVerificationState state = mPendingVerification.get(verificationId); 1142 1143 if ((state != null) && !state.timeoutExtended()) { 1144 final InstallArgs args = state.getInstallArgs(); 1145 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1146 1147 Slog.i(TAG, "Verification timed out for " + originUri); 1148 mPendingVerification.remove(verificationId); 1149 1150 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1151 1152 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1153 Slog.i(TAG, "Continuing with installation of " + originUri); 1154 state.setVerifierResponse(Binder.getCallingUid(), 1155 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1156 broadcastPackageVerified(verificationId, originUri, 1157 PackageManager.VERIFICATION_ALLOW, 1158 state.getInstallArgs().getUser()); 1159 try { 1160 ret = args.copyApk(mContainerService, true); 1161 } catch (RemoteException e) { 1162 Slog.e(TAG, "Could not contact the ContainerService"); 1163 } 1164 } else { 1165 broadcastPackageVerified(verificationId, originUri, 1166 PackageManager.VERIFICATION_REJECT, 1167 state.getInstallArgs().getUser()); 1168 } 1169 1170 processPendingInstall(args, ret); 1171 mHandler.sendEmptyMessage(MCS_UNBIND); 1172 } 1173 break; 1174 } 1175 case PACKAGE_VERIFIED: { 1176 final int verificationId = msg.arg1; 1177 1178 final PackageVerificationState state = mPendingVerification.get(verificationId); 1179 if (state == null) { 1180 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1181 break; 1182 } 1183 1184 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1185 1186 state.setVerifierResponse(response.callerUid, response.code); 1187 1188 if (state.isVerificationComplete()) { 1189 mPendingVerification.remove(verificationId); 1190 1191 final InstallArgs args = state.getInstallArgs(); 1192 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1193 1194 int ret; 1195 if (state.isInstallAllowed()) { 1196 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1197 broadcastPackageVerified(verificationId, originUri, 1198 response.code, state.getInstallArgs().getUser()); 1199 try { 1200 ret = args.copyApk(mContainerService, true); 1201 } catch (RemoteException e) { 1202 Slog.e(TAG, "Could not contact the ContainerService"); 1203 } 1204 } else { 1205 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1206 } 1207 1208 processPendingInstall(args, ret); 1209 1210 mHandler.sendEmptyMessage(MCS_UNBIND); 1211 } 1212 1213 break; 1214 } 1215 } 1216 } 1217 } 1218 1219 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1220 Bundle extras = null; 1221 switch (res.returnCode) { 1222 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1223 extras = new Bundle(); 1224 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1225 res.origPermission); 1226 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1227 res.origPackage); 1228 break; 1229 } 1230 } 1231 return extras; 1232 } 1233 1234 void scheduleWriteSettingsLocked() { 1235 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1236 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1237 } 1238 } 1239 1240 void scheduleWritePackageRestrictionsLocked(int userId) { 1241 if (!sUserManager.exists(userId)) return; 1242 mDirtyUsers.add(userId); 1243 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1244 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1245 } 1246 } 1247 1248 public static final PackageManagerService main(Context context, Installer installer, 1249 boolean factoryTest, boolean onlyCore) { 1250 PackageManagerService m = new PackageManagerService(context, installer, 1251 factoryTest, onlyCore); 1252 ServiceManager.addService("package", m); 1253 return m; 1254 } 1255 1256 static String[] splitString(String str, char sep) { 1257 int count = 1; 1258 int i = 0; 1259 while ((i=str.indexOf(sep, i)) >= 0) { 1260 count++; 1261 i++; 1262 } 1263 1264 String[] res = new String[count]; 1265 i=0; 1266 count = 0; 1267 int lastI=0; 1268 while ((i=str.indexOf(sep, i)) >= 0) { 1269 res[count] = str.substring(lastI, i); 1270 count++; 1271 i++; 1272 lastI = i; 1273 } 1274 res[count] = str.substring(lastI, str.length()); 1275 return res; 1276 } 1277 1278 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1279 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1280 Context.DISPLAY_SERVICE); 1281 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1282 } 1283 1284 public PackageManagerService(Context context, Installer installer, 1285 boolean factoryTest, boolean onlyCore) { 1286 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1287 SystemClock.uptimeMillis()); 1288 1289 if (mSdkVersion <= 0) { 1290 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1291 } 1292 1293 mContext = context; 1294 mFactoryTest = factoryTest; 1295 mOnlyCore = onlyCore; 1296 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1297 mMetrics = new DisplayMetrics(); 1298 mSettings = new Settings(context); 1299 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1300 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1301 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1302 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1303 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1304 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1305 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1306 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1307 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1308 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1309 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1310 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1311 1312 // TODO: add a property to control this? 1313 long dexOptLRUThresholdInMinutes; 1314 if (mLazyDexOpt) { 1315 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1316 } else { 1317 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1318 } 1319 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1320 1321 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1322 if (separateProcesses != null && separateProcesses.length() > 0) { 1323 if ("*".equals(separateProcesses)) { 1324 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1325 mSeparateProcesses = null; 1326 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1327 } else { 1328 mDefParseFlags = 0; 1329 mSeparateProcesses = separateProcesses.split(","); 1330 Slog.w(TAG, "Running with debug.separate_processes: " 1331 + separateProcesses); 1332 } 1333 } else { 1334 mDefParseFlags = 0; 1335 mSeparateProcesses = null; 1336 } 1337 1338 mInstaller = installer; 1339 mPackageDexOptimizer = new PackageDexOptimizer(this); 1340 1341 getDefaultDisplayMetrics(context, mMetrics); 1342 1343 SystemConfig systemConfig = SystemConfig.getInstance(); 1344 mGlobalGids = systemConfig.getGlobalGids(); 1345 mSystemPermissions = systemConfig.getSystemPermissions(); 1346 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1347 1348 synchronized (mInstallLock) { 1349 // writer 1350 synchronized (mPackages) { 1351 mHandlerThread = new ServiceThread(TAG, 1352 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1353 mHandlerThread.start(); 1354 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1355 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1356 1357 File dataDir = Environment.getDataDirectory(); 1358 mAppDataDir = new File(dataDir, "data"); 1359 mAppInstallDir = new File(dataDir, "app"); 1360 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1361 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1362 mUserAppDataDir = new File(dataDir, "user"); 1363 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1364 1365 sUserManager = new UserManagerService(context, this, 1366 mInstallLock, mPackages); 1367 1368 // Propagate permission configuration in to package manager. 1369 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1370 = systemConfig.getPermissions(); 1371 for (int i=0; i<permConfig.size(); i++) { 1372 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1373 BasePermission bp = mSettings.mPermissions.get(perm.name); 1374 if (bp == null) { 1375 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1376 mSettings.mPermissions.put(perm.name, bp); 1377 } 1378 if (perm.gids != null) { 1379 bp.gids = appendInts(bp.gids, perm.gids); 1380 } 1381 } 1382 1383 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1384 for (int i=0; i<libConfig.size(); i++) { 1385 mSharedLibraries.put(libConfig.keyAt(i), 1386 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1387 } 1388 1389 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1390 1391 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1392 mSdkVersion, mOnlyCore); 1393 1394 String customResolverActivity = Resources.getSystem().getString( 1395 R.string.config_customResolverActivity); 1396 if (TextUtils.isEmpty(customResolverActivity)) { 1397 customResolverActivity = null; 1398 } else { 1399 mCustomResolverComponentName = ComponentName.unflattenFromString( 1400 customResolverActivity); 1401 } 1402 1403 long startTime = SystemClock.uptimeMillis(); 1404 1405 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1406 startTime); 1407 1408 // Set flag to monitor and not change apk file paths when 1409 // scanning install directories. 1410 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1411 1412 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1413 1414 /** 1415 * Add everything in the in the boot class path to the 1416 * list of process files because dexopt will have been run 1417 * if necessary during zygote startup. 1418 */ 1419 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1420 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1421 1422 if (bootClassPath != null) { 1423 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1424 for (String element : bootClassPathElements) { 1425 alreadyDexOpted.add(element); 1426 } 1427 } else { 1428 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1429 } 1430 1431 if (systemServerClassPath != null) { 1432 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1433 for (String element : systemServerClassPathElements) { 1434 alreadyDexOpted.add(element); 1435 } 1436 } else { 1437 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1438 } 1439 1440 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1441 final String[] dexCodeInstructionSets = 1442 getDexCodeInstructionSets( 1443 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1444 1445 /** 1446 * Ensure all external libraries have had dexopt run on them. 1447 */ 1448 if (mSharedLibraries.size() > 0) { 1449 // NOTE: For now, we're compiling these system "shared libraries" 1450 // (and framework jars) into all available architectures. It's possible 1451 // to compile them only when we come across an app that uses them (there's 1452 // already logic for that in scanPackageLI) but that adds some complexity. 1453 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1454 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1455 final String lib = libEntry.path; 1456 if (lib == null) { 1457 continue; 1458 } 1459 1460 try { 1461 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1462 dexCodeInstructionSet, 1463 false); 1464 if (dexoptRequired != DexFile.UP_TO_DATE) { 1465 alreadyDexOpted.add(lib); 1466 1467 // The list of "shared libraries" we have at this point is 1468 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1469 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1470 } else { 1471 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1472 } 1473 } 1474 } catch (FileNotFoundException e) { 1475 Slog.w(TAG, "Library not found: " + lib); 1476 } catch (IOException e) { 1477 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1478 + e.getMessage()); 1479 } 1480 } 1481 } 1482 } 1483 1484 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1485 1486 // Gross hack for now: we know this file doesn't contain any 1487 // code, so don't dexopt it to avoid the resulting log spew. 1488 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1489 1490 // Gross hack for now: we know this file is only part of 1491 // the boot class path for art, so don't dexopt it to 1492 // avoid the resulting log spew. 1493 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1494 1495 /** 1496 * And there are a number of commands implemented in Java, which 1497 * we currently need to do the dexopt on so that they can be 1498 * run from a non-root shell. 1499 */ 1500 String[] frameworkFiles = frameworkDir.list(); 1501 if (frameworkFiles != null) { 1502 // TODO: We could compile these only for the most preferred ABI. We should 1503 // first double check that the dex files for these commands are not referenced 1504 // by other system apps. 1505 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1506 for (int i=0; i<frameworkFiles.length; i++) { 1507 File libPath = new File(frameworkDir, frameworkFiles[i]); 1508 String path = libPath.getPath(); 1509 // Skip the file if we already did it. 1510 if (alreadyDexOpted.contains(path)) { 1511 continue; 1512 } 1513 // Skip the file if it is not a type we want to dexopt. 1514 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1515 continue; 1516 } 1517 try { 1518 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1519 dexCodeInstructionSet, 1520 false); 1521 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1522 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1523 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1524 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1525 } 1526 } catch (FileNotFoundException e) { 1527 Slog.w(TAG, "Jar not found: " + path); 1528 } catch (IOException e) { 1529 Slog.w(TAG, "Exception reading jar: " + path, e); 1530 } 1531 } 1532 } 1533 } 1534 1535 // Collect vendor overlay packages. 1536 // (Do this before scanning any apps.) 1537 // For security and version matching reason, only consider 1538 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1539 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1540 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1541 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1542 1543 // Find base frameworks (resource packages without code). 1544 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1545 | PackageParser.PARSE_IS_SYSTEM_DIR 1546 | PackageParser.PARSE_IS_PRIVILEGED, 1547 scanFlags | SCAN_NO_DEX, 0); 1548 1549 // Collected privileged system packages. 1550 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1551 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1552 | PackageParser.PARSE_IS_SYSTEM_DIR 1553 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1554 1555 // Collect ordinary system packages. 1556 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1557 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1558 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1559 1560 // Collect all vendor packages. 1561 File vendorAppDir = new File("/vendor/app"); 1562 try { 1563 vendorAppDir = vendorAppDir.getCanonicalFile(); 1564 } catch (IOException e) { 1565 // failed to look up canonical path, continue with original one 1566 } 1567 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1568 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1569 1570 // Collect all OEM packages. 1571 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1572 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1573 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1574 1575 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1576 mInstaller.moveFiles(); 1577 1578 // Prune any system packages that no longer exist. 1579 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1580 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1581 if (!mOnlyCore) { 1582 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1583 while (psit.hasNext()) { 1584 PackageSetting ps = psit.next(); 1585 1586 /* 1587 * If this is not a system app, it can't be a 1588 * disable system app. 1589 */ 1590 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1591 continue; 1592 } 1593 1594 /* 1595 * If the package is scanned, it's not erased. 1596 */ 1597 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1598 if (scannedPkg != null) { 1599 /* 1600 * If the system app is both scanned and in the 1601 * disabled packages list, then it must have been 1602 * added via OTA. Remove it from the currently 1603 * scanned package so the previously user-installed 1604 * application can be scanned. 1605 */ 1606 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1607 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1608 + ps.name + "; removing system app. Last known codePath=" 1609 + ps.codePathString + ", installStatus=" + ps.installStatus 1610 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1611 + scannedPkg.mVersionCode); 1612 removePackageLI(ps, true); 1613 expectingBetter.put(ps.name, ps.codePath); 1614 } 1615 1616 continue; 1617 } 1618 1619 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1620 psit.remove(); 1621 logCriticalInfo(Log.WARN, "System package " + ps.name 1622 + " no longer exists; wiping its data"); 1623 removeDataDirsLI(ps.name); 1624 } else { 1625 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1626 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1627 possiblyDeletedUpdatedSystemApps.add(ps.name); 1628 } 1629 } 1630 } 1631 } 1632 1633 //look for any incomplete package installations 1634 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1635 //clean up list 1636 for(int i = 0; i < deletePkgsList.size(); i++) { 1637 //clean up here 1638 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1639 } 1640 //delete tmp files 1641 deleteTempPackageFiles(); 1642 1643 // Remove any shared userIDs that have no associated packages 1644 mSettings.pruneSharedUsersLPw(); 1645 1646 if (!mOnlyCore) { 1647 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1648 SystemClock.uptimeMillis()); 1649 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 1650 1651 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1652 scanFlags | SCAN_REQUIRE_KNOWN, 0); 1653 1654 /** 1655 * Remove disable package settings for any updated system 1656 * apps that were removed via an OTA. If they're not a 1657 * previously-updated app, remove them completely. 1658 * Otherwise, just revoke their system-level permissions. 1659 */ 1660 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1661 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1662 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1663 1664 String msg; 1665 if (deletedPkg == null) { 1666 msg = "Updated system package " + deletedAppName 1667 + " no longer exists; wiping its data"; 1668 removeDataDirsLI(deletedAppName); 1669 } else { 1670 msg = "Updated system app + " + deletedAppName 1671 + " no longer present; removing system privileges for " 1672 + deletedAppName; 1673 1674 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1675 1676 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1677 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1678 } 1679 logCriticalInfo(Log.WARN, msg); 1680 } 1681 1682 /** 1683 * Make sure all system apps that we expected to appear on 1684 * the userdata partition actually showed up. If they never 1685 * appeared, crawl back and revive the system version. 1686 */ 1687 for (int i = 0; i < expectingBetter.size(); i++) { 1688 final String packageName = expectingBetter.keyAt(i); 1689 if (!mPackages.containsKey(packageName)) { 1690 final File scanFile = expectingBetter.valueAt(i); 1691 1692 logCriticalInfo(Log.WARN, "Expected better " + packageName 1693 + " but never showed up; reverting to system"); 1694 1695 final int reparseFlags; 1696 if (FileUtils.contains(privilegedAppDir, scanFile)) { 1697 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1698 | PackageParser.PARSE_IS_SYSTEM_DIR 1699 | PackageParser.PARSE_IS_PRIVILEGED; 1700 } else if (FileUtils.contains(systemAppDir, scanFile)) { 1701 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1702 | PackageParser.PARSE_IS_SYSTEM_DIR; 1703 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 1704 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1705 | PackageParser.PARSE_IS_SYSTEM_DIR; 1706 } else if (FileUtils.contains(oemAppDir, scanFile)) { 1707 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1708 | PackageParser.PARSE_IS_SYSTEM_DIR; 1709 } else { 1710 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 1711 continue; 1712 } 1713 1714 mSettings.enableSystemPackageLPw(packageName); 1715 1716 try { 1717 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 1718 } catch (PackageManagerException e) { 1719 Slog.e(TAG, "Failed to parse original system package: " 1720 + e.getMessage()); 1721 } 1722 } 1723 } 1724 } 1725 1726 // Now that we know all of the shared libraries, update all clients to have 1727 // the correct library paths. 1728 updateAllSharedLibrariesLPw(); 1729 1730 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1731 // NOTE: We ignore potential failures here during a system scan (like 1732 // the rest of the commands above) because there's precious little we 1733 // can do about it. A settings error is reported, though. 1734 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1735 false /* force dexopt */, false /* defer dexopt */); 1736 } 1737 1738 // Now that we know all the packages we are keeping, 1739 // read and update their last usage times. 1740 mPackageUsage.readLP(); 1741 1742 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1743 SystemClock.uptimeMillis()); 1744 Slog.i(TAG, "Time to scan packages: " 1745 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1746 + " seconds"); 1747 1748 // If the platform SDK has changed since the last time we booted, 1749 // we need to re-grant app permission to catch any new ones that 1750 // appear. This is really a hack, and means that apps can in some 1751 // cases get permissions that the user didn't initially explicitly 1752 // allow... it would be nice to have some better way to handle 1753 // this situation. 1754 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1755 != mSdkVersion; 1756 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1757 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1758 + "; regranting permissions for internal storage"); 1759 mSettings.mInternalSdkPlatform = mSdkVersion; 1760 1761 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1762 | (regrantPermissions 1763 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1764 : 0)); 1765 1766 // If this is the first boot, and it is a normal boot, then 1767 // we need to initialize the default preferred apps. 1768 if (!mRestoredSettings && !onlyCore) { 1769 mSettings.readDefaultPreferredAppsLPw(this, 0); 1770 } 1771 1772 // If this is first boot after an OTA, and a normal boot, then 1773 // we need to clear code cache directories. 1774 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 1775 if (mIsUpgrade && !onlyCore) { 1776 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1777 for (String pkgName : mSettings.mPackages.keySet()) { 1778 deleteCodeCacheDirsLI(pkgName); 1779 } 1780 mSettings.mFingerprint = Build.FINGERPRINT; 1781 } 1782 1783 // All the changes are done during package scanning. 1784 mSettings.updateInternalDatabaseVersion(); 1785 1786 // can downgrade to reader 1787 mSettings.writeLPr(); 1788 1789 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1790 SystemClock.uptimeMillis()); 1791 1792 1793 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1794 } // synchronized (mPackages) 1795 } // synchronized (mInstallLock) 1796 1797 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1798 1799 // Now after opening every single application zip, make sure they 1800 // are all flushed. Not really needed, but keeps things nice and 1801 // tidy. 1802 Runtime.getRuntime().gc(); 1803 } 1804 1805 @Override 1806 public boolean isFirstBoot() { 1807 return !mRestoredSettings; 1808 } 1809 1810 @Override 1811 public boolean isOnlyCoreApps() { 1812 return mOnlyCore; 1813 } 1814 1815 @Override 1816 public boolean isUpgrade() { 1817 return mIsUpgrade; 1818 } 1819 1820 private String getRequiredVerifierLPr() { 1821 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1822 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1823 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1824 1825 String requiredVerifier = null; 1826 1827 final int N = receivers.size(); 1828 for (int i = 0; i < N; i++) { 1829 final ResolveInfo info = receivers.get(i); 1830 1831 if (info.activityInfo == null) { 1832 continue; 1833 } 1834 1835 final String packageName = info.activityInfo.packageName; 1836 1837 final PackageSetting ps = mSettings.mPackages.get(packageName); 1838 if (ps == null) { 1839 continue; 1840 } 1841 1842 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1843 if (!gp.grantedPermissions 1844 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1845 continue; 1846 } 1847 1848 if (requiredVerifier != null) { 1849 throw new RuntimeException("There can be only one required verifier"); 1850 } 1851 1852 requiredVerifier = packageName; 1853 } 1854 1855 return requiredVerifier; 1856 } 1857 1858 @Override 1859 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1860 throws RemoteException { 1861 try { 1862 return super.onTransact(code, data, reply, flags); 1863 } catch (RuntimeException e) { 1864 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1865 Slog.wtf(TAG, "Package Manager Crash", e); 1866 } 1867 throw e; 1868 } 1869 } 1870 1871 void cleanupInstallFailedPackage(PackageSetting ps) { 1872 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1873 1874 removeDataDirsLI(ps.name); 1875 if (ps.codePath != null) { 1876 if (ps.codePath.isDirectory()) { 1877 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 1878 } else { 1879 ps.codePath.delete(); 1880 } 1881 } 1882 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1883 if (ps.resourcePath.isDirectory()) { 1884 FileUtils.deleteContents(ps.resourcePath); 1885 } 1886 ps.resourcePath.delete(); 1887 } 1888 mSettings.removePackageLPw(ps.name); 1889 } 1890 1891 static int[] appendInts(int[] cur, int[] add) { 1892 if (add == null) return cur; 1893 if (cur == null) return add; 1894 final int N = add.length; 1895 for (int i=0; i<N; i++) { 1896 cur = appendInt(cur, add[i]); 1897 } 1898 return cur; 1899 } 1900 1901 static int[] removeInts(int[] cur, int[] rem) { 1902 if (rem == null) return cur; 1903 if (cur == null) return cur; 1904 final int N = rem.length; 1905 for (int i=0; i<N; i++) { 1906 cur = removeInt(cur, rem[i]); 1907 } 1908 return cur; 1909 } 1910 1911 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1912 if (!sUserManager.exists(userId)) return null; 1913 final PackageSetting ps = (PackageSetting) p.mExtras; 1914 if (ps == null) { 1915 return null; 1916 } 1917 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1918 final PackageUserState state = ps.readUserState(userId); 1919 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1920 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1921 state, userId); 1922 } 1923 1924 @Override 1925 public boolean isPackageAvailable(String packageName, int userId) { 1926 if (!sUserManager.exists(userId)) return false; 1927 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1928 synchronized (mPackages) { 1929 PackageParser.Package p = mPackages.get(packageName); 1930 if (p != null) { 1931 final PackageSetting ps = (PackageSetting) p.mExtras; 1932 if (ps != null) { 1933 final PackageUserState state = ps.readUserState(userId); 1934 if (state != null) { 1935 return PackageParser.isAvailable(state); 1936 } 1937 } 1938 } 1939 } 1940 return false; 1941 } 1942 1943 @Override 1944 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1945 if (!sUserManager.exists(userId)) return null; 1946 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1947 // reader 1948 synchronized (mPackages) { 1949 PackageParser.Package p = mPackages.get(packageName); 1950 if (DEBUG_PACKAGE_INFO) 1951 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1952 if (p != null) { 1953 return generatePackageInfo(p, flags, userId); 1954 } 1955 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1956 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1957 } 1958 } 1959 return null; 1960 } 1961 1962 @Override 1963 public String[] currentToCanonicalPackageNames(String[] names) { 1964 String[] out = new String[names.length]; 1965 // reader 1966 synchronized (mPackages) { 1967 for (int i=names.length-1; i>=0; i--) { 1968 PackageSetting ps = mSettings.mPackages.get(names[i]); 1969 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1970 } 1971 } 1972 return out; 1973 } 1974 1975 @Override 1976 public String[] canonicalToCurrentPackageNames(String[] names) { 1977 String[] out = new String[names.length]; 1978 // reader 1979 synchronized (mPackages) { 1980 for (int i=names.length-1; i>=0; i--) { 1981 String cur = mSettings.mRenamedPackages.get(names[i]); 1982 out[i] = cur != null ? cur : names[i]; 1983 } 1984 } 1985 return out; 1986 } 1987 1988 @Override 1989 public int getPackageUid(String packageName, int userId) { 1990 if (!sUserManager.exists(userId)) return -1; 1991 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1992 // reader 1993 synchronized (mPackages) { 1994 PackageParser.Package p = mPackages.get(packageName); 1995 if(p != null) { 1996 return UserHandle.getUid(userId, p.applicationInfo.uid); 1997 } 1998 PackageSetting ps = mSettings.mPackages.get(packageName); 1999 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2000 return -1; 2001 } 2002 p = ps.pkg; 2003 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2004 } 2005 } 2006 2007 @Override 2008 public int[] getPackageGids(String packageName) { 2009 // reader 2010 synchronized (mPackages) { 2011 PackageParser.Package p = mPackages.get(packageName); 2012 if (DEBUG_PACKAGE_INFO) 2013 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2014 if (p != null) { 2015 final PackageSetting ps = (PackageSetting)p.mExtras; 2016 return ps.getGids(); 2017 } 2018 } 2019 // stupid thing to indicate an error. 2020 return new int[0]; 2021 } 2022 2023 static final PermissionInfo generatePermissionInfo( 2024 BasePermission bp, int flags) { 2025 if (bp.perm != null) { 2026 return PackageParser.generatePermissionInfo(bp.perm, flags); 2027 } 2028 PermissionInfo pi = new PermissionInfo(); 2029 pi.name = bp.name; 2030 pi.packageName = bp.sourcePackage; 2031 pi.nonLocalizedLabel = bp.name; 2032 pi.protectionLevel = bp.protectionLevel; 2033 return pi; 2034 } 2035 2036 @Override 2037 public PermissionInfo getPermissionInfo(String name, int flags) { 2038 // reader 2039 synchronized (mPackages) { 2040 final BasePermission p = mSettings.mPermissions.get(name); 2041 if (p != null) { 2042 return generatePermissionInfo(p, flags); 2043 } 2044 return null; 2045 } 2046 } 2047 2048 @Override 2049 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2050 // reader 2051 synchronized (mPackages) { 2052 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2053 for (BasePermission p : mSettings.mPermissions.values()) { 2054 if (group == null) { 2055 if (p.perm == null || p.perm.info.group == null) { 2056 out.add(generatePermissionInfo(p, flags)); 2057 } 2058 } else { 2059 if (p.perm != null && group.equals(p.perm.info.group)) { 2060 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2061 } 2062 } 2063 } 2064 2065 if (out.size() > 0) { 2066 return out; 2067 } 2068 return mPermissionGroups.containsKey(group) ? out : null; 2069 } 2070 } 2071 2072 @Override 2073 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2074 // reader 2075 synchronized (mPackages) { 2076 return PackageParser.generatePermissionGroupInfo( 2077 mPermissionGroups.get(name), flags); 2078 } 2079 } 2080 2081 @Override 2082 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2083 // reader 2084 synchronized (mPackages) { 2085 final int N = mPermissionGroups.size(); 2086 ArrayList<PermissionGroupInfo> out 2087 = new ArrayList<PermissionGroupInfo>(N); 2088 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2089 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2090 } 2091 return out; 2092 } 2093 } 2094 2095 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2096 int userId) { 2097 if (!sUserManager.exists(userId)) return null; 2098 PackageSetting ps = mSettings.mPackages.get(packageName); 2099 if (ps != null) { 2100 if (ps.pkg == null) { 2101 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2102 flags, userId); 2103 if (pInfo != null) { 2104 return pInfo.applicationInfo; 2105 } 2106 return null; 2107 } 2108 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2109 ps.readUserState(userId), userId); 2110 } 2111 return null; 2112 } 2113 2114 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2115 int userId) { 2116 if (!sUserManager.exists(userId)) return null; 2117 PackageSetting ps = mSettings.mPackages.get(packageName); 2118 if (ps != null) { 2119 PackageParser.Package pkg = ps.pkg; 2120 if (pkg == null) { 2121 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2122 return null; 2123 } 2124 // Only data remains, so we aren't worried about code paths 2125 pkg = new PackageParser.Package(packageName); 2126 pkg.applicationInfo.packageName = packageName; 2127 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2128 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2129 pkg.applicationInfo.dataDir = 2130 getDataPathForPackage(packageName, 0).getPath(); 2131 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2132 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2133 } 2134 return generatePackageInfo(pkg, flags, userId); 2135 } 2136 return null; 2137 } 2138 2139 @Override 2140 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2141 if (!sUserManager.exists(userId)) return null; 2142 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2143 // writer 2144 synchronized (mPackages) { 2145 PackageParser.Package p = mPackages.get(packageName); 2146 if (DEBUG_PACKAGE_INFO) Log.v( 2147 TAG, "getApplicationInfo " + packageName 2148 + ": " + p); 2149 if (p != null) { 2150 PackageSetting ps = mSettings.mPackages.get(packageName); 2151 if (ps == null) return null; 2152 // Note: isEnabledLP() does not apply here - always return info 2153 return PackageParser.generateApplicationInfo( 2154 p, flags, ps.readUserState(userId), userId); 2155 } 2156 if ("android".equals(packageName)||"system".equals(packageName)) { 2157 return mAndroidApplication; 2158 } 2159 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2160 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2161 } 2162 } 2163 return null; 2164 } 2165 2166 2167 @Override 2168 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2169 mContext.enforceCallingOrSelfPermission( 2170 android.Manifest.permission.CLEAR_APP_CACHE, null); 2171 // Queue up an async operation since clearing cache may take a little while. 2172 mHandler.post(new Runnable() { 2173 public void run() { 2174 mHandler.removeCallbacks(this); 2175 int retCode = -1; 2176 synchronized (mInstallLock) { 2177 retCode = mInstaller.freeCache(freeStorageSize); 2178 if (retCode < 0) { 2179 Slog.w(TAG, "Couldn't clear application caches"); 2180 } 2181 } 2182 if (observer != null) { 2183 try { 2184 observer.onRemoveCompleted(null, (retCode >= 0)); 2185 } catch (RemoteException e) { 2186 Slog.w(TAG, "RemoveException when invoking call back"); 2187 } 2188 } 2189 } 2190 }); 2191 } 2192 2193 @Override 2194 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2195 mContext.enforceCallingOrSelfPermission( 2196 android.Manifest.permission.CLEAR_APP_CACHE, null); 2197 // Queue up an async operation since clearing cache may take a little while. 2198 mHandler.post(new Runnable() { 2199 public void run() { 2200 mHandler.removeCallbacks(this); 2201 int retCode = -1; 2202 synchronized (mInstallLock) { 2203 retCode = mInstaller.freeCache(freeStorageSize); 2204 if (retCode < 0) { 2205 Slog.w(TAG, "Couldn't clear application caches"); 2206 } 2207 } 2208 if(pi != null) { 2209 try { 2210 // Callback via pending intent 2211 int code = (retCode >= 0) ? 1 : 0; 2212 pi.sendIntent(null, code, null, 2213 null, null); 2214 } catch (SendIntentException e1) { 2215 Slog.i(TAG, "Failed to send pending intent"); 2216 } 2217 } 2218 } 2219 }); 2220 } 2221 2222 void freeStorage(long freeStorageSize) throws IOException { 2223 synchronized (mInstallLock) { 2224 if (mInstaller.freeCache(freeStorageSize) < 0) { 2225 throw new IOException("Failed to free enough space"); 2226 } 2227 } 2228 } 2229 2230 @Override 2231 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2232 if (!sUserManager.exists(userId)) return null; 2233 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2234 synchronized (mPackages) { 2235 PackageParser.Activity a = mActivities.mActivities.get(component); 2236 2237 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2238 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2239 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2240 if (ps == null) return null; 2241 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2242 userId); 2243 } 2244 if (mResolveComponentName.equals(component)) { 2245 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2246 new PackageUserState(), userId); 2247 } 2248 } 2249 return null; 2250 } 2251 2252 @Override 2253 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2254 String resolvedType) { 2255 synchronized (mPackages) { 2256 PackageParser.Activity a = mActivities.mActivities.get(component); 2257 if (a == null) { 2258 return false; 2259 } 2260 for (int i=0; i<a.intents.size(); i++) { 2261 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2262 intent.getData(), intent.getCategories(), TAG) >= 0) { 2263 return true; 2264 } 2265 } 2266 return false; 2267 } 2268 } 2269 2270 @Override 2271 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2272 if (!sUserManager.exists(userId)) return null; 2273 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2274 synchronized (mPackages) { 2275 PackageParser.Activity a = mReceivers.mActivities.get(component); 2276 if (DEBUG_PACKAGE_INFO) Log.v( 2277 TAG, "getReceiverInfo " + component + ": " + a); 2278 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2279 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2280 if (ps == null) return null; 2281 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2282 userId); 2283 } 2284 } 2285 return null; 2286 } 2287 2288 @Override 2289 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2290 if (!sUserManager.exists(userId)) return null; 2291 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2292 synchronized (mPackages) { 2293 PackageParser.Service s = mServices.mServices.get(component); 2294 if (DEBUG_PACKAGE_INFO) Log.v( 2295 TAG, "getServiceInfo " + component + ": " + s); 2296 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2297 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2298 if (ps == null) return null; 2299 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2300 userId); 2301 } 2302 } 2303 return null; 2304 } 2305 2306 @Override 2307 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2308 if (!sUserManager.exists(userId)) return null; 2309 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2310 synchronized (mPackages) { 2311 PackageParser.Provider p = mProviders.mProviders.get(component); 2312 if (DEBUG_PACKAGE_INFO) Log.v( 2313 TAG, "getProviderInfo " + component + ": " + p); 2314 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2315 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2316 if (ps == null) return null; 2317 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2318 userId); 2319 } 2320 } 2321 return null; 2322 } 2323 2324 @Override 2325 public String[] getSystemSharedLibraryNames() { 2326 Set<String> libSet; 2327 synchronized (mPackages) { 2328 libSet = mSharedLibraries.keySet(); 2329 int size = libSet.size(); 2330 if (size > 0) { 2331 String[] libs = new String[size]; 2332 libSet.toArray(libs); 2333 return libs; 2334 } 2335 } 2336 return null; 2337 } 2338 2339 /** 2340 * @hide 2341 */ 2342 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2343 synchronized (mPackages) { 2344 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2345 if (lib != null && lib.apk != null) { 2346 return mPackages.get(lib.apk); 2347 } 2348 } 2349 return null; 2350 } 2351 2352 @Override 2353 public FeatureInfo[] getSystemAvailableFeatures() { 2354 Collection<FeatureInfo> featSet; 2355 synchronized (mPackages) { 2356 featSet = mAvailableFeatures.values(); 2357 int size = featSet.size(); 2358 if (size > 0) { 2359 FeatureInfo[] features = new FeatureInfo[size+1]; 2360 featSet.toArray(features); 2361 FeatureInfo fi = new FeatureInfo(); 2362 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2363 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2364 features[size] = fi; 2365 return features; 2366 } 2367 } 2368 return null; 2369 } 2370 2371 @Override 2372 public boolean hasSystemFeature(String name) { 2373 synchronized (mPackages) { 2374 return mAvailableFeatures.containsKey(name); 2375 } 2376 } 2377 2378 private void checkValidCaller(int uid, int userId) { 2379 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2380 return; 2381 2382 throw new SecurityException("Caller uid=" + uid 2383 + " is not privileged to communicate with user=" + userId); 2384 } 2385 2386 @Override 2387 public int checkPermission(String permName, String pkgName) { 2388 synchronized (mPackages) { 2389 PackageParser.Package p = mPackages.get(pkgName); 2390 if (p != null && p.mExtras != null) { 2391 PackageSetting ps = (PackageSetting)p.mExtras; 2392 if (ps.sharedUser != null) { 2393 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2394 return PackageManager.PERMISSION_GRANTED; 2395 } 2396 } else if (ps.grantedPermissions.contains(permName)) { 2397 return PackageManager.PERMISSION_GRANTED; 2398 } 2399 } 2400 } 2401 return PackageManager.PERMISSION_DENIED; 2402 } 2403 2404 @Override 2405 public int checkUidPermission(String permName, int uid) { 2406 synchronized (mPackages) { 2407 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2408 if (obj != null) { 2409 GrantedPermissions gp = (GrantedPermissions)obj; 2410 if (gp.grantedPermissions.contains(permName)) { 2411 return PackageManager.PERMISSION_GRANTED; 2412 } 2413 } else { 2414 ArraySet<String> perms = mSystemPermissions.get(uid); 2415 if (perms != null && perms.contains(permName)) { 2416 return PackageManager.PERMISSION_GRANTED; 2417 } 2418 } 2419 } 2420 return PackageManager.PERMISSION_DENIED; 2421 } 2422 2423 /** 2424 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2425 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2426 * @param checkShell TODO(yamasani): 2427 * @param message the message to log on security exception 2428 */ 2429 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2430 boolean checkShell, String message) { 2431 if (userId < 0) { 2432 throw new IllegalArgumentException("Invalid userId " + userId); 2433 } 2434 if (checkShell) { 2435 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2436 } 2437 if (userId == UserHandle.getUserId(callingUid)) return; 2438 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2439 if (requireFullPermission) { 2440 mContext.enforceCallingOrSelfPermission( 2441 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2442 } else { 2443 try { 2444 mContext.enforceCallingOrSelfPermission( 2445 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2446 } catch (SecurityException se) { 2447 mContext.enforceCallingOrSelfPermission( 2448 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2449 } 2450 } 2451 } 2452 } 2453 2454 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2455 if (callingUid == Process.SHELL_UID) { 2456 if (userHandle >= 0 2457 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2458 throw new SecurityException("Shell does not have permission to access user " 2459 + userHandle); 2460 } else if (userHandle < 0) { 2461 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2462 + Debug.getCallers(3)); 2463 } 2464 } 2465 } 2466 2467 private BasePermission findPermissionTreeLP(String permName) { 2468 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2469 if (permName.startsWith(bp.name) && 2470 permName.length() > bp.name.length() && 2471 permName.charAt(bp.name.length()) == '.') { 2472 return bp; 2473 } 2474 } 2475 return null; 2476 } 2477 2478 private BasePermission checkPermissionTreeLP(String permName) { 2479 if (permName != null) { 2480 BasePermission bp = findPermissionTreeLP(permName); 2481 if (bp != null) { 2482 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2483 return bp; 2484 } 2485 throw new SecurityException("Calling uid " 2486 + Binder.getCallingUid() 2487 + " is not allowed to add to permission tree " 2488 + bp.name + " owned by uid " + bp.uid); 2489 } 2490 } 2491 throw new SecurityException("No permission tree found for " + permName); 2492 } 2493 2494 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2495 if (s1 == null) { 2496 return s2 == null; 2497 } 2498 if (s2 == null) { 2499 return false; 2500 } 2501 if (s1.getClass() != s2.getClass()) { 2502 return false; 2503 } 2504 return s1.equals(s2); 2505 } 2506 2507 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2508 if (pi1.icon != pi2.icon) return false; 2509 if (pi1.logo != pi2.logo) return false; 2510 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2511 if (!compareStrings(pi1.name, pi2.name)) return false; 2512 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2513 // We'll take care of setting this one. 2514 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2515 // These are not currently stored in settings. 2516 //if (!compareStrings(pi1.group, pi2.group)) return false; 2517 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2518 //if (pi1.labelRes != pi2.labelRes) return false; 2519 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2520 return true; 2521 } 2522 2523 int permissionInfoFootprint(PermissionInfo info) { 2524 int size = info.name.length(); 2525 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2526 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2527 return size; 2528 } 2529 2530 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2531 int size = 0; 2532 for (BasePermission perm : mSettings.mPermissions.values()) { 2533 if (perm.uid == tree.uid) { 2534 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2535 } 2536 } 2537 return size; 2538 } 2539 2540 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2541 // We calculate the max size of permissions defined by this uid and throw 2542 // if that plus the size of 'info' would exceed our stated maximum. 2543 if (tree.uid != Process.SYSTEM_UID) { 2544 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2545 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2546 throw new SecurityException("Permission tree size cap exceeded"); 2547 } 2548 } 2549 } 2550 2551 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2552 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2553 throw new SecurityException("Label must be specified in permission"); 2554 } 2555 BasePermission tree = checkPermissionTreeLP(info.name); 2556 BasePermission bp = mSettings.mPermissions.get(info.name); 2557 boolean added = bp == null; 2558 boolean changed = true; 2559 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2560 if (added) { 2561 enforcePermissionCapLocked(info, tree); 2562 bp = new BasePermission(info.name, tree.sourcePackage, 2563 BasePermission.TYPE_DYNAMIC); 2564 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2565 throw new SecurityException( 2566 "Not allowed to modify non-dynamic permission " 2567 + info.name); 2568 } else { 2569 if (bp.protectionLevel == fixedLevel 2570 && bp.perm.owner.equals(tree.perm.owner) 2571 && bp.uid == tree.uid 2572 && comparePermissionInfos(bp.perm.info, info)) { 2573 changed = false; 2574 } 2575 } 2576 bp.protectionLevel = fixedLevel; 2577 info = new PermissionInfo(info); 2578 info.protectionLevel = fixedLevel; 2579 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2580 bp.perm.info.packageName = tree.perm.info.packageName; 2581 bp.uid = tree.uid; 2582 if (added) { 2583 mSettings.mPermissions.put(info.name, bp); 2584 } 2585 if (changed) { 2586 if (!async) { 2587 mSettings.writeLPr(); 2588 } else { 2589 scheduleWriteSettingsLocked(); 2590 } 2591 } 2592 return added; 2593 } 2594 2595 @Override 2596 public boolean addPermission(PermissionInfo info) { 2597 synchronized (mPackages) { 2598 return addPermissionLocked(info, false); 2599 } 2600 } 2601 2602 @Override 2603 public boolean addPermissionAsync(PermissionInfo info) { 2604 synchronized (mPackages) { 2605 return addPermissionLocked(info, true); 2606 } 2607 } 2608 2609 @Override 2610 public void removePermission(String name) { 2611 synchronized (mPackages) { 2612 checkPermissionTreeLP(name); 2613 BasePermission bp = mSettings.mPermissions.get(name); 2614 if (bp != null) { 2615 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2616 throw new SecurityException( 2617 "Not allowed to modify non-dynamic permission " 2618 + name); 2619 } 2620 mSettings.mPermissions.remove(name); 2621 mSettings.writeLPr(); 2622 } 2623 } 2624 } 2625 2626 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2627 int index = pkg.requestedPermissions.indexOf(bp.name); 2628 if (index == -1) { 2629 throw new SecurityException("Package " + pkg.packageName 2630 + " has not requested permission " + bp.name); 2631 } 2632 boolean isNormal = 2633 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2634 == PermissionInfo.PROTECTION_NORMAL); 2635 boolean isDangerous = 2636 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2637 == PermissionInfo.PROTECTION_DANGEROUS); 2638 boolean isDevelopment = 2639 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2640 2641 if (!isNormal && !isDangerous && !isDevelopment) { 2642 throw new SecurityException("Permission " + bp.name 2643 + " is not a changeable permission type"); 2644 } 2645 2646 if (isNormal || isDangerous) { 2647 if (pkg.requestedPermissionsRequired.get(index)) { 2648 throw new SecurityException("Can't change " + bp.name 2649 + ". It is required by the application"); 2650 } 2651 } 2652 } 2653 2654 @Override 2655 public void grantPermission(String packageName, String permissionName) { 2656 mContext.enforceCallingOrSelfPermission( 2657 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2658 synchronized (mPackages) { 2659 final PackageParser.Package pkg = mPackages.get(packageName); 2660 if (pkg == null) { 2661 throw new IllegalArgumentException("Unknown package: " + packageName); 2662 } 2663 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2664 if (bp == null) { 2665 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2666 } 2667 2668 checkGrantRevokePermissions(pkg, bp); 2669 2670 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2671 if (ps == null) { 2672 return; 2673 } 2674 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2675 if (gp.grantedPermissions.add(permissionName)) { 2676 if (ps.haveGids) { 2677 gp.gids = appendInts(gp.gids, bp.gids); 2678 } 2679 mSettings.writeLPr(); 2680 } 2681 } 2682 } 2683 2684 @Override 2685 public void revokePermission(String packageName, String permissionName) { 2686 int changedAppId = -1; 2687 2688 synchronized (mPackages) { 2689 final PackageParser.Package pkg = mPackages.get(packageName); 2690 if (pkg == null) { 2691 throw new IllegalArgumentException("Unknown package: " + packageName); 2692 } 2693 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2694 mContext.enforceCallingOrSelfPermission( 2695 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2696 } 2697 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2698 if (bp == null) { 2699 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2700 } 2701 2702 checkGrantRevokePermissions(pkg, bp); 2703 2704 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2705 if (ps == null) { 2706 return; 2707 } 2708 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2709 if (gp.grantedPermissions.remove(permissionName)) { 2710 gp.grantedPermissions.remove(permissionName); 2711 if (ps.haveGids) { 2712 gp.gids = removeInts(gp.gids, bp.gids); 2713 } 2714 mSettings.writeLPr(); 2715 changedAppId = ps.appId; 2716 } 2717 } 2718 2719 if (changedAppId >= 0) { 2720 // We changed the perm on someone, kill its processes. 2721 IActivityManager am = ActivityManagerNative.getDefault(); 2722 if (am != null) { 2723 final int callingUserId = UserHandle.getCallingUserId(); 2724 final long ident = Binder.clearCallingIdentity(); 2725 try { 2726 //XXX we should only revoke for the calling user's app permissions, 2727 // but for now we impact all users. 2728 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2729 // "revoke " + permissionName); 2730 int[] users = sUserManager.getUserIds(); 2731 for (int user : users) { 2732 am.killUid(UserHandle.getUid(user, changedAppId), 2733 "revoke " + permissionName); 2734 } 2735 } catch (RemoteException e) { 2736 } finally { 2737 Binder.restoreCallingIdentity(ident); 2738 } 2739 } 2740 } 2741 } 2742 2743 @Override 2744 public boolean isProtectedBroadcast(String actionName) { 2745 synchronized (mPackages) { 2746 return mProtectedBroadcasts.contains(actionName); 2747 } 2748 } 2749 2750 @Override 2751 public int checkSignatures(String pkg1, String pkg2) { 2752 synchronized (mPackages) { 2753 final PackageParser.Package p1 = mPackages.get(pkg1); 2754 final PackageParser.Package p2 = mPackages.get(pkg2); 2755 if (p1 == null || p1.mExtras == null 2756 || p2 == null || p2.mExtras == null) { 2757 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2758 } 2759 return compareSignatures(p1.mSignatures, p2.mSignatures); 2760 } 2761 } 2762 2763 @Override 2764 public int checkUidSignatures(int uid1, int uid2) { 2765 // Map to base uids. 2766 uid1 = UserHandle.getAppId(uid1); 2767 uid2 = UserHandle.getAppId(uid2); 2768 // reader 2769 synchronized (mPackages) { 2770 Signature[] s1; 2771 Signature[] s2; 2772 Object obj = mSettings.getUserIdLPr(uid1); 2773 if (obj != null) { 2774 if (obj instanceof SharedUserSetting) { 2775 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2776 } else if (obj instanceof PackageSetting) { 2777 s1 = ((PackageSetting)obj).signatures.mSignatures; 2778 } else { 2779 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2780 } 2781 } else { 2782 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2783 } 2784 obj = mSettings.getUserIdLPr(uid2); 2785 if (obj != null) { 2786 if (obj instanceof SharedUserSetting) { 2787 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2788 } else if (obj instanceof PackageSetting) { 2789 s2 = ((PackageSetting)obj).signatures.mSignatures; 2790 } else { 2791 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2792 } 2793 } else { 2794 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2795 } 2796 return compareSignatures(s1, s2); 2797 } 2798 } 2799 2800 /** 2801 * Compares two sets of signatures. Returns: 2802 * <br /> 2803 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2804 * <br /> 2805 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2806 * <br /> 2807 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2808 * <br /> 2809 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2810 * <br /> 2811 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2812 */ 2813 static int compareSignatures(Signature[] s1, Signature[] s2) { 2814 if (s1 == null) { 2815 return s2 == null 2816 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2817 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2818 } 2819 2820 if (s2 == null) { 2821 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2822 } 2823 2824 if (s1.length != s2.length) { 2825 return PackageManager.SIGNATURE_NO_MATCH; 2826 } 2827 2828 // Since both signature sets are of size 1, we can compare without HashSets. 2829 if (s1.length == 1) { 2830 return s1[0].equals(s2[0]) ? 2831 PackageManager.SIGNATURE_MATCH : 2832 PackageManager.SIGNATURE_NO_MATCH; 2833 } 2834 2835 ArraySet<Signature> set1 = new ArraySet<Signature>(); 2836 for (Signature sig : s1) { 2837 set1.add(sig); 2838 } 2839 ArraySet<Signature> set2 = new ArraySet<Signature>(); 2840 for (Signature sig : s2) { 2841 set2.add(sig); 2842 } 2843 // Make sure s2 contains all signatures in s1. 2844 if (set1.equals(set2)) { 2845 return PackageManager.SIGNATURE_MATCH; 2846 } 2847 return PackageManager.SIGNATURE_NO_MATCH; 2848 } 2849 2850 /** 2851 * If the database version for this type of package (internal storage or 2852 * external storage) is less than the version where package signatures 2853 * were updated, return true. 2854 */ 2855 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2856 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2857 DatabaseVersion.SIGNATURE_END_ENTITY)) 2858 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2859 DatabaseVersion.SIGNATURE_END_ENTITY)); 2860 } 2861 2862 /** 2863 * Used for backward compatibility to make sure any packages with 2864 * certificate chains get upgraded to the new style. {@code existingSigs} 2865 * will be in the old format (since they were stored on disk from before the 2866 * system upgrade) and {@code scannedSigs} will be in the newer format. 2867 */ 2868 private int compareSignaturesCompat(PackageSignatures existingSigs, 2869 PackageParser.Package scannedPkg) { 2870 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2871 return PackageManager.SIGNATURE_NO_MATCH; 2872 } 2873 2874 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 2875 for (Signature sig : existingSigs.mSignatures) { 2876 existingSet.add(sig); 2877 } 2878 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 2879 for (Signature sig : scannedPkg.mSignatures) { 2880 try { 2881 Signature[] chainSignatures = sig.getChainSignatures(); 2882 for (Signature chainSig : chainSignatures) { 2883 scannedCompatSet.add(chainSig); 2884 } 2885 } catch (CertificateEncodingException e) { 2886 scannedCompatSet.add(sig); 2887 } 2888 } 2889 /* 2890 * Make sure the expanded scanned set contains all signatures in the 2891 * existing one. 2892 */ 2893 if (scannedCompatSet.equals(existingSet)) { 2894 // Migrate the old signatures to the new scheme. 2895 existingSigs.assignSignatures(scannedPkg.mSignatures); 2896 // The new KeySets will be re-added later in the scanning process. 2897 synchronized (mPackages) { 2898 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2899 } 2900 return PackageManager.SIGNATURE_MATCH; 2901 } 2902 return PackageManager.SIGNATURE_NO_MATCH; 2903 } 2904 2905 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2906 if (isExternal(scannedPkg)) { 2907 return mSettings.isExternalDatabaseVersionOlderThan( 2908 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2909 } else { 2910 return mSettings.isInternalDatabaseVersionOlderThan( 2911 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2912 } 2913 } 2914 2915 private int compareSignaturesRecover(PackageSignatures existingSigs, 2916 PackageParser.Package scannedPkg) { 2917 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 2918 return PackageManager.SIGNATURE_NO_MATCH; 2919 } 2920 2921 String msg = null; 2922 try { 2923 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 2924 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 2925 + scannedPkg.packageName); 2926 return PackageManager.SIGNATURE_MATCH; 2927 } 2928 } catch (CertificateException e) { 2929 msg = e.getMessage(); 2930 } 2931 2932 logCriticalInfo(Log.INFO, 2933 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 2934 return PackageManager.SIGNATURE_NO_MATCH; 2935 } 2936 2937 @Override 2938 public String[] getPackagesForUid(int uid) { 2939 uid = UserHandle.getAppId(uid); 2940 // reader 2941 synchronized (mPackages) { 2942 Object obj = mSettings.getUserIdLPr(uid); 2943 if (obj instanceof SharedUserSetting) { 2944 final SharedUserSetting sus = (SharedUserSetting) obj; 2945 final int N = sus.packages.size(); 2946 final String[] res = new String[N]; 2947 final Iterator<PackageSetting> it = sus.packages.iterator(); 2948 int i = 0; 2949 while (it.hasNext()) { 2950 res[i++] = it.next().name; 2951 } 2952 return res; 2953 } else if (obj instanceof PackageSetting) { 2954 final PackageSetting ps = (PackageSetting) obj; 2955 return new String[] { ps.name }; 2956 } 2957 } 2958 return null; 2959 } 2960 2961 @Override 2962 public String getNameForUid(int uid) { 2963 // reader 2964 synchronized (mPackages) { 2965 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2966 if (obj instanceof SharedUserSetting) { 2967 final SharedUserSetting sus = (SharedUserSetting) obj; 2968 return sus.name + ":" + sus.userId; 2969 } else if (obj instanceof PackageSetting) { 2970 final PackageSetting ps = (PackageSetting) obj; 2971 return ps.name; 2972 } 2973 } 2974 return null; 2975 } 2976 2977 @Override 2978 public int getUidForSharedUser(String sharedUserName) { 2979 if(sharedUserName == null) { 2980 return -1; 2981 } 2982 // reader 2983 synchronized (mPackages) { 2984 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 2985 if (suid == null) { 2986 return -1; 2987 } 2988 return suid.userId; 2989 } 2990 } 2991 2992 @Override 2993 public int getFlagsForUid(int uid) { 2994 synchronized (mPackages) { 2995 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2996 if (obj instanceof SharedUserSetting) { 2997 final SharedUserSetting sus = (SharedUserSetting) obj; 2998 return sus.pkgFlags; 2999 } else if (obj instanceof PackageSetting) { 3000 final PackageSetting ps = (PackageSetting) obj; 3001 return ps.pkgFlags; 3002 } 3003 } 3004 return 0; 3005 } 3006 3007 @Override 3008 public int getPrivateFlagsForUid(int uid) { 3009 synchronized (mPackages) { 3010 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3011 if (obj instanceof SharedUserSetting) { 3012 final SharedUserSetting sus = (SharedUserSetting) obj; 3013 return sus.pkgPrivateFlags; 3014 } else if (obj instanceof PackageSetting) { 3015 final PackageSetting ps = (PackageSetting) obj; 3016 return ps.pkgPrivateFlags; 3017 } 3018 } 3019 return 0; 3020 } 3021 3022 @Override 3023 public boolean isUidPrivileged(int uid) { 3024 uid = UserHandle.getAppId(uid); 3025 // reader 3026 synchronized (mPackages) { 3027 Object obj = mSettings.getUserIdLPr(uid); 3028 if (obj instanceof SharedUserSetting) { 3029 final SharedUserSetting sus = (SharedUserSetting) obj; 3030 final Iterator<PackageSetting> it = sus.packages.iterator(); 3031 while (it.hasNext()) { 3032 if (it.next().isPrivileged()) { 3033 return true; 3034 } 3035 } 3036 } else if (obj instanceof PackageSetting) { 3037 final PackageSetting ps = (PackageSetting) obj; 3038 return ps.isPrivileged(); 3039 } 3040 } 3041 return false; 3042 } 3043 3044 @Override 3045 public String[] getAppOpPermissionPackages(String permissionName) { 3046 synchronized (mPackages) { 3047 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3048 if (pkgs == null) { 3049 return null; 3050 } 3051 return pkgs.toArray(new String[pkgs.size()]); 3052 } 3053 } 3054 3055 @Override 3056 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3057 int flags, int userId) { 3058 if (!sUserManager.exists(userId)) return null; 3059 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3060 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3061 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3062 } 3063 3064 @Override 3065 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3066 IntentFilter filter, int match, ComponentName activity) { 3067 final int userId = UserHandle.getCallingUserId(); 3068 if (DEBUG_PREFERRED) { 3069 Log.v(TAG, "setLastChosenActivity intent=" + intent 3070 + " resolvedType=" + resolvedType 3071 + " flags=" + flags 3072 + " filter=" + filter 3073 + " match=" + match 3074 + " activity=" + activity); 3075 filter.dump(new PrintStreamPrinter(System.out), " "); 3076 } 3077 intent.setComponent(null); 3078 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3079 // Find any earlier preferred or last chosen entries and nuke them 3080 findPreferredActivity(intent, resolvedType, 3081 flags, query, 0, false, true, false, userId); 3082 // Add the new activity as the last chosen for this filter 3083 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3084 "Setting last chosen"); 3085 } 3086 3087 @Override 3088 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3089 final int userId = UserHandle.getCallingUserId(); 3090 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3091 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3092 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3093 false, false, false, userId); 3094 } 3095 3096 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3097 int flags, List<ResolveInfo> query, int userId) { 3098 if (query != null) { 3099 final int N = query.size(); 3100 if (N == 1) { 3101 return query.get(0); 3102 } else if (N > 1) { 3103 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3104 // If there is more than one activity with the same priority, 3105 // then let the user decide between them. 3106 ResolveInfo r0 = query.get(0); 3107 ResolveInfo r1 = query.get(1); 3108 if (DEBUG_INTENT_MATCHING || debug) { 3109 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3110 + r1.activityInfo.name + "=" + r1.priority); 3111 } 3112 // If the first activity has a higher priority, or a different 3113 // default, then it is always desireable to pick it. 3114 if (r0.priority != r1.priority 3115 || r0.preferredOrder != r1.preferredOrder 3116 || r0.isDefault != r1.isDefault) { 3117 return query.get(0); 3118 } 3119 // If we have saved a preference for a preferred activity for 3120 // this Intent, use that. 3121 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3122 flags, query, r0.priority, true, false, debug, userId); 3123 if (ri != null) { 3124 return ri; 3125 } 3126 if (userId != 0) { 3127 ri = new ResolveInfo(mResolveInfo); 3128 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3129 ri.activityInfo.applicationInfo = new ApplicationInfo( 3130 ri.activityInfo.applicationInfo); 3131 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3132 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3133 return ri; 3134 } 3135 return mResolveInfo; 3136 } 3137 } 3138 return null; 3139 } 3140 3141 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3142 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3143 final int N = query.size(); 3144 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3145 .get(userId); 3146 // Get the list of persistent preferred activities that handle the intent 3147 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3148 List<PersistentPreferredActivity> pprefs = ppir != null 3149 ? ppir.queryIntent(intent, resolvedType, 3150 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3151 : null; 3152 if (pprefs != null && pprefs.size() > 0) { 3153 final int M = pprefs.size(); 3154 for (int i=0; i<M; i++) { 3155 final PersistentPreferredActivity ppa = pprefs.get(i); 3156 if (DEBUG_PREFERRED || debug) { 3157 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3158 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3159 + "\n component=" + ppa.mComponent); 3160 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3161 } 3162 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3163 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3164 if (DEBUG_PREFERRED || debug) { 3165 Slog.v(TAG, "Found persistent preferred activity:"); 3166 if (ai != null) { 3167 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3168 } else { 3169 Slog.v(TAG, " null"); 3170 } 3171 } 3172 if (ai == null) { 3173 // This previously registered persistent preferred activity 3174 // component is no longer known. Ignore it and do NOT remove it. 3175 continue; 3176 } 3177 for (int j=0; j<N; j++) { 3178 final ResolveInfo ri = query.get(j); 3179 if (!ri.activityInfo.applicationInfo.packageName 3180 .equals(ai.applicationInfo.packageName)) { 3181 continue; 3182 } 3183 if (!ri.activityInfo.name.equals(ai.name)) { 3184 continue; 3185 } 3186 // Found a persistent preference that can handle the intent. 3187 if (DEBUG_PREFERRED || debug) { 3188 Slog.v(TAG, "Returning persistent preferred activity: " + 3189 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3190 } 3191 return ri; 3192 } 3193 } 3194 } 3195 return null; 3196 } 3197 3198 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3199 List<ResolveInfo> query, int priority, boolean always, 3200 boolean removeMatches, boolean debug, int userId) { 3201 if (!sUserManager.exists(userId)) return null; 3202 // writer 3203 synchronized (mPackages) { 3204 if (intent.getSelector() != null) { 3205 intent = intent.getSelector(); 3206 } 3207 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3208 3209 // Try to find a matching persistent preferred activity. 3210 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3211 debug, userId); 3212 3213 // If a persistent preferred activity matched, use it. 3214 if (pri != null) { 3215 return pri; 3216 } 3217 3218 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3219 // Get the list of preferred activities that handle the intent 3220 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3221 List<PreferredActivity> prefs = pir != null 3222 ? pir.queryIntent(intent, resolvedType, 3223 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3224 : null; 3225 if (prefs != null && prefs.size() > 0) { 3226 boolean changed = false; 3227 try { 3228 // First figure out how good the original match set is. 3229 // We will only allow preferred activities that came 3230 // from the same match quality. 3231 int match = 0; 3232 3233 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3234 3235 final int N = query.size(); 3236 for (int j=0; j<N; j++) { 3237 final ResolveInfo ri = query.get(j); 3238 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3239 + ": 0x" + Integer.toHexString(match)); 3240 if (ri.match > match) { 3241 match = ri.match; 3242 } 3243 } 3244 3245 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3246 + Integer.toHexString(match)); 3247 3248 match &= IntentFilter.MATCH_CATEGORY_MASK; 3249 final int M = prefs.size(); 3250 for (int i=0; i<M; i++) { 3251 final PreferredActivity pa = prefs.get(i); 3252 if (DEBUG_PREFERRED || debug) { 3253 Slog.v(TAG, "Checking PreferredActivity ds=" 3254 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3255 + "\n component=" + pa.mPref.mComponent); 3256 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3257 } 3258 if (pa.mPref.mMatch != match) { 3259 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3260 + Integer.toHexString(pa.mPref.mMatch)); 3261 continue; 3262 } 3263 // If it's not an "always" type preferred activity and that's what we're 3264 // looking for, skip it. 3265 if (always && !pa.mPref.mAlways) { 3266 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3267 continue; 3268 } 3269 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3270 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3271 if (DEBUG_PREFERRED || debug) { 3272 Slog.v(TAG, "Found preferred activity:"); 3273 if (ai != null) { 3274 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3275 } else { 3276 Slog.v(TAG, " null"); 3277 } 3278 } 3279 if (ai == null) { 3280 // This previously registered preferred activity 3281 // component is no longer known. Most likely an update 3282 // to the app was installed and in the new version this 3283 // component no longer exists. Clean it up by removing 3284 // it from the preferred activities list, and skip it. 3285 Slog.w(TAG, "Removing dangling preferred activity: " 3286 + pa.mPref.mComponent); 3287 pir.removeFilter(pa); 3288 changed = true; 3289 continue; 3290 } 3291 for (int j=0; j<N; j++) { 3292 final ResolveInfo ri = query.get(j); 3293 if (!ri.activityInfo.applicationInfo.packageName 3294 .equals(ai.applicationInfo.packageName)) { 3295 continue; 3296 } 3297 if (!ri.activityInfo.name.equals(ai.name)) { 3298 continue; 3299 } 3300 3301 if (removeMatches) { 3302 pir.removeFilter(pa); 3303 changed = true; 3304 if (DEBUG_PREFERRED) { 3305 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3306 } 3307 break; 3308 } 3309 3310 // Okay we found a previously set preferred or last chosen app. 3311 // If the result set is different from when this 3312 // was created, we need to clear it and re-ask the 3313 // user their preference, if we're looking for an "always" type entry. 3314 if (always && !pa.mPref.sameSet(query)) { 3315 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3316 + intent + " type " + resolvedType); 3317 if (DEBUG_PREFERRED) { 3318 Slog.v(TAG, "Removing preferred activity since set changed " 3319 + pa.mPref.mComponent); 3320 } 3321 pir.removeFilter(pa); 3322 // Re-add the filter as a "last chosen" entry (!always) 3323 PreferredActivity lastChosen = new PreferredActivity( 3324 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3325 pir.addFilter(lastChosen); 3326 changed = true; 3327 return null; 3328 } 3329 3330 // Yay! Either the set matched or we're looking for the last chosen 3331 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3332 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3333 return ri; 3334 } 3335 } 3336 } finally { 3337 if (changed) { 3338 if (DEBUG_PREFERRED) { 3339 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3340 } 3341 scheduleWritePackageRestrictionsLocked(userId); 3342 } 3343 } 3344 } 3345 } 3346 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3347 return null; 3348 } 3349 3350 /* 3351 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3352 */ 3353 @Override 3354 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3355 int targetUserId) { 3356 mContext.enforceCallingOrSelfPermission( 3357 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3358 List<CrossProfileIntentFilter> matches = 3359 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3360 if (matches != null) { 3361 int size = matches.size(); 3362 for (int i = 0; i < size; i++) { 3363 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3364 } 3365 } 3366 return false; 3367 } 3368 3369 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3370 String resolvedType, int userId) { 3371 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3372 if (resolver != null) { 3373 return resolver.queryIntent(intent, resolvedType, false, userId); 3374 } 3375 return null; 3376 } 3377 3378 @Override 3379 public List<ResolveInfo> queryIntentActivities(Intent intent, 3380 String resolvedType, int flags, int userId) { 3381 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3382 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3383 ComponentName comp = intent.getComponent(); 3384 if (comp == null) { 3385 if (intent.getSelector() != null) { 3386 intent = intent.getSelector(); 3387 comp = intent.getComponent(); 3388 } 3389 } 3390 3391 if (comp != null) { 3392 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3393 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3394 if (ai != null) { 3395 final ResolveInfo ri = new ResolveInfo(); 3396 ri.activityInfo = ai; 3397 list.add(ri); 3398 } 3399 return list; 3400 } 3401 3402 // reader 3403 synchronized (mPackages) { 3404 final String pkgName = intent.getPackage(); 3405 if (pkgName == null) { 3406 List<CrossProfileIntentFilter> matchingFilters = 3407 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3408 // Check for results that need to skip the current profile. 3409 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3410 resolvedType, flags, userId); 3411 if (resolveInfo != null) { 3412 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3413 result.add(resolveInfo); 3414 return result; 3415 } 3416 // Check for cross profile results. 3417 resolveInfo = queryCrossProfileIntents( 3418 matchingFilters, intent, resolvedType, flags, userId); 3419 3420 // Check for results in the current profile. 3421 List<ResolveInfo> result = mActivities.queryIntent( 3422 intent, resolvedType, flags, userId); 3423 if (resolveInfo != null) { 3424 result.add(resolveInfo); 3425 Collections.sort(result, mResolvePrioritySorter); 3426 } 3427 return result; 3428 } 3429 final PackageParser.Package pkg = mPackages.get(pkgName); 3430 if (pkg != null) { 3431 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3432 pkg.activities, userId); 3433 } 3434 return new ArrayList<ResolveInfo>(); 3435 } 3436 } 3437 3438 private ResolveInfo querySkipCurrentProfileIntents( 3439 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3440 int flags, int sourceUserId) { 3441 if (matchingFilters != null) { 3442 int size = matchingFilters.size(); 3443 for (int i = 0; i < size; i ++) { 3444 CrossProfileIntentFilter filter = matchingFilters.get(i); 3445 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3446 // Checking if there are activities in the target user that can handle the 3447 // intent. 3448 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3449 flags, sourceUserId); 3450 if (resolveInfo != null) { 3451 return resolveInfo; 3452 } 3453 } 3454 } 3455 } 3456 return null; 3457 } 3458 3459 // Return matching ResolveInfo if any for skip current profile intent filters. 3460 private ResolveInfo queryCrossProfileIntents( 3461 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3462 int flags, int sourceUserId) { 3463 if (matchingFilters != null) { 3464 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3465 // match the same intent. For performance reasons, it is better not to 3466 // run queryIntent twice for the same userId 3467 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3468 int size = matchingFilters.size(); 3469 for (int i = 0; i < size; i++) { 3470 CrossProfileIntentFilter filter = matchingFilters.get(i); 3471 int targetUserId = filter.getTargetUserId(); 3472 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3473 && !alreadyTriedUserIds.get(targetUserId)) { 3474 // Checking if there are activities in the target user that can handle the 3475 // intent. 3476 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3477 flags, sourceUserId); 3478 if (resolveInfo != null) return resolveInfo; 3479 alreadyTriedUserIds.put(targetUserId, true); 3480 } 3481 } 3482 } 3483 return null; 3484 } 3485 3486 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3487 String resolvedType, int flags, int sourceUserId) { 3488 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3489 resolvedType, flags, filter.getTargetUserId()); 3490 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3491 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3492 } 3493 return null; 3494 } 3495 3496 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3497 int sourceUserId, int targetUserId) { 3498 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3499 String className; 3500 if (targetUserId == UserHandle.USER_OWNER) { 3501 className = FORWARD_INTENT_TO_USER_OWNER; 3502 } else { 3503 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3504 } 3505 ComponentName forwardingActivityComponentName = new ComponentName( 3506 mAndroidApplication.packageName, className); 3507 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3508 sourceUserId); 3509 if (targetUserId == UserHandle.USER_OWNER) { 3510 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3511 forwardingResolveInfo.noResourceId = true; 3512 } 3513 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3514 forwardingResolveInfo.priority = 0; 3515 forwardingResolveInfo.preferredOrder = 0; 3516 forwardingResolveInfo.match = 0; 3517 forwardingResolveInfo.isDefault = true; 3518 forwardingResolveInfo.filter = filter; 3519 forwardingResolveInfo.targetUserId = targetUserId; 3520 return forwardingResolveInfo; 3521 } 3522 3523 @Override 3524 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3525 Intent[] specifics, String[] specificTypes, Intent intent, 3526 String resolvedType, int flags, int userId) { 3527 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3528 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3529 false, "query intent activity options"); 3530 final String resultsAction = intent.getAction(); 3531 3532 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3533 | PackageManager.GET_RESOLVED_FILTER, userId); 3534 3535 if (DEBUG_INTENT_MATCHING) { 3536 Log.v(TAG, "Query " + intent + ": " + results); 3537 } 3538 3539 int specificsPos = 0; 3540 int N; 3541 3542 // todo: note that the algorithm used here is O(N^2). This 3543 // isn't a problem in our current environment, but if we start running 3544 // into situations where we have more than 5 or 10 matches then this 3545 // should probably be changed to something smarter... 3546 3547 // First we go through and resolve each of the specific items 3548 // that were supplied, taking care of removing any corresponding 3549 // duplicate items in the generic resolve list. 3550 if (specifics != null) { 3551 for (int i=0; i<specifics.length; i++) { 3552 final Intent sintent = specifics[i]; 3553 if (sintent == null) { 3554 continue; 3555 } 3556 3557 if (DEBUG_INTENT_MATCHING) { 3558 Log.v(TAG, "Specific #" + i + ": " + sintent); 3559 } 3560 3561 String action = sintent.getAction(); 3562 if (resultsAction != null && resultsAction.equals(action)) { 3563 // If this action was explicitly requested, then don't 3564 // remove things that have it. 3565 action = null; 3566 } 3567 3568 ResolveInfo ri = null; 3569 ActivityInfo ai = null; 3570 3571 ComponentName comp = sintent.getComponent(); 3572 if (comp == null) { 3573 ri = resolveIntent( 3574 sintent, 3575 specificTypes != null ? specificTypes[i] : null, 3576 flags, userId); 3577 if (ri == null) { 3578 continue; 3579 } 3580 if (ri == mResolveInfo) { 3581 // ACK! Must do something better with this. 3582 } 3583 ai = ri.activityInfo; 3584 comp = new ComponentName(ai.applicationInfo.packageName, 3585 ai.name); 3586 } else { 3587 ai = getActivityInfo(comp, flags, userId); 3588 if (ai == null) { 3589 continue; 3590 } 3591 } 3592 3593 // Look for any generic query activities that are duplicates 3594 // of this specific one, and remove them from the results. 3595 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3596 N = results.size(); 3597 int j; 3598 for (j=specificsPos; j<N; j++) { 3599 ResolveInfo sri = results.get(j); 3600 if ((sri.activityInfo.name.equals(comp.getClassName()) 3601 && sri.activityInfo.applicationInfo.packageName.equals( 3602 comp.getPackageName())) 3603 || (action != null && sri.filter.matchAction(action))) { 3604 results.remove(j); 3605 if (DEBUG_INTENT_MATCHING) Log.v( 3606 TAG, "Removing duplicate item from " + j 3607 + " due to specific " + specificsPos); 3608 if (ri == null) { 3609 ri = sri; 3610 } 3611 j--; 3612 N--; 3613 } 3614 } 3615 3616 // Add this specific item to its proper place. 3617 if (ri == null) { 3618 ri = new ResolveInfo(); 3619 ri.activityInfo = ai; 3620 } 3621 results.add(specificsPos, ri); 3622 ri.specificIndex = i; 3623 specificsPos++; 3624 } 3625 } 3626 3627 // Now we go through the remaining generic results and remove any 3628 // duplicate actions that are found here. 3629 N = results.size(); 3630 for (int i=specificsPos; i<N-1; i++) { 3631 final ResolveInfo rii = results.get(i); 3632 if (rii.filter == null) { 3633 continue; 3634 } 3635 3636 // Iterate over all of the actions of this result's intent 3637 // filter... typically this should be just one. 3638 final Iterator<String> it = rii.filter.actionsIterator(); 3639 if (it == null) { 3640 continue; 3641 } 3642 while (it.hasNext()) { 3643 final String action = it.next(); 3644 if (resultsAction != null && resultsAction.equals(action)) { 3645 // If this action was explicitly requested, then don't 3646 // remove things that have it. 3647 continue; 3648 } 3649 for (int j=i+1; j<N; j++) { 3650 final ResolveInfo rij = results.get(j); 3651 if (rij.filter != null && rij.filter.hasAction(action)) { 3652 results.remove(j); 3653 if (DEBUG_INTENT_MATCHING) Log.v( 3654 TAG, "Removing duplicate item from " + j 3655 + " due to action " + action + " at " + i); 3656 j--; 3657 N--; 3658 } 3659 } 3660 } 3661 3662 // If the caller didn't request filter information, drop it now 3663 // so we don't have to marshall/unmarshall it. 3664 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3665 rii.filter = null; 3666 } 3667 } 3668 3669 // Filter out the caller activity if so requested. 3670 if (caller != null) { 3671 N = results.size(); 3672 for (int i=0; i<N; i++) { 3673 ActivityInfo ainfo = results.get(i).activityInfo; 3674 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3675 && caller.getClassName().equals(ainfo.name)) { 3676 results.remove(i); 3677 break; 3678 } 3679 } 3680 } 3681 3682 // If the caller didn't request filter information, 3683 // drop them now so we don't have to 3684 // marshall/unmarshall it. 3685 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3686 N = results.size(); 3687 for (int i=0; i<N; i++) { 3688 results.get(i).filter = null; 3689 } 3690 } 3691 3692 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3693 return results; 3694 } 3695 3696 @Override 3697 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3698 int userId) { 3699 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3700 ComponentName comp = intent.getComponent(); 3701 if (comp == null) { 3702 if (intent.getSelector() != null) { 3703 intent = intent.getSelector(); 3704 comp = intent.getComponent(); 3705 } 3706 } 3707 if (comp != null) { 3708 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3709 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3710 if (ai != null) { 3711 ResolveInfo ri = new ResolveInfo(); 3712 ri.activityInfo = ai; 3713 list.add(ri); 3714 } 3715 return list; 3716 } 3717 3718 // reader 3719 synchronized (mPackages) { 3720 String pkgName = intent.getPackage(); 3721 if (pkgName == null) { 3722 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3723 } 3724 final PackageParser.Package pkg = mPackages.get(pkgName); 3725 if (pkg != null) { 3726 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3727 userId); 3728 } 3729 return null; 3730 } 3731 } 3732 3733 @Override 3734 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3735 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3736 if (!sUserManager.exists(userId)) return null; 3737 if (query != null) { 3738 if (query.size() >= 1) { 3739 // If there is more than one service with the same priority, 3740 // just arbitrarily pick the first one. 3741 return query.get(0); 3742 } 3743 } 3744 return null; 3745 } 3746 3747 @Override 3748 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3749 int userId) { 3750 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3751 ComponentName comp = intent.getComponent(); 3752 if (comp == null) { 3753 if (intent.getSelector() != null) { 3754 intent = intent.getSelector(); 3755 comp = intent.getComponent(); 3756 } 3757 } 3758 if (comp != null) { 3759 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3760 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3761 if (si != null) { 3762 final ResolveInfo ri = new ResolveInfo(); 3763 ri.serviceInfo = si; 3764 list.add(ri); 3765 } 3766 return list; 3767 } 3768 3769 // reader 3770 synchronized (mPackages) { 3771 String pkgName = intent.getPackage(); 3772 if (pkgName == null) { 3773 return mServices.queryIntent(intent, resolvedType, flags, userId); 3774 } 3775 final PackageParser.Package pkg = mPackages.get(pkgName); 3776 if (pkg != null) { 3777 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3778 userId); 3779 } 3780 return null; 3781 } 3782 } 3783 3784 @Override 3785 public List<ResolveInfo> queryIntentContentProviders( 3786 Intent intent, String resolvedType, int flags, int userId) { 3787 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3788 ComponentName comp = intent.getComponent(); 3789 if (comp == null) { 3790 if (intent.getSelector() != null) { 3791 intent = intent.getSelector(); 3792 comp = intent.getComponent(); 3793 } 3794 } 3795 if (comp != null) { 3796 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3797 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3798 if (pi != null) { 3799 final ResolveInfo ri = new ResolveInfo(); 3800 ri.providerInfo = pi; 3801 list.add(ri); 3802 } 3803 return list; 3804 } 3805 3806 // reader 3807 synchronized (mPackages) { 3808 String pkgName = intent.getPackage(); 3809 if (pkgName == null) { 3810 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3811 } 3812 final PackageParser.Package pkg = mPackages.get(pkgName); 3813 if (pkg != null) { 3814 return mProviders.queryIntentForPackage( 3815 intent, resolvedType, flags, pkg.providers, userId); 3816 } 3817 return null; 3818 } 3819 } 3820 3821 @Override 3822 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3823 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3824 3825 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3826 3827 // writer 3828 synchronized (mPackages) { 3829 ArrayList<PackageInfo> list; 3830 if (listUninstalled) { 3831 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3832 for (PackageSetting ps : mSettings.mPackages.values()) { 3833 PackageInfo pi; 3834 if (ps.pkg != null) { 3835 pi = generatePackageInfo(ps.pkg, flags, userId); 3836 } else { 3837 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3838 } 3839 if (pi != null) { 3840 list.add(pi); 3841 } 3842 } 3843 } else { 3844 list = new ArrayList<PackageInfo>(mPackages.size()); 3845 for (PackageParser.Package p : mPackages.values()) { 3846 PackageInfo pi = generatePackageInfo(p, flags, userId); 3847 if (pi != null) { 3848 list.add(pi); 3849 } 3850 } 3851 } 3852 3853 return new ParceledListSlice<PackageInfo>(list); 3854 } 3855 } 3856 3857 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3858 String[] permissions, boolean[] tmp, int flags, int userId) { 3859 int numMatch = 0; 3860 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3861 for (int i=0; i<permissions.length; i++) { 3862 if (gp.grantedPermissions.contains(permissions[i])) { 3863 tmp[i] = true; 3864 numMatch++; 3865 } else { 3866 tmp[i] = false; 3867 } 3868 } 3869 if (numMatch == 0) { 3870 return; 3871 } 3872 PackageInfo pi; 3873 if (ps.pkg != null) { 3874 pi = generatePackageInfo(ps.pkg, flags, userId); 3875 } else { 3876 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3877 } 3878 // The above might return null in cases of uninstalled apps or install-state 3879 // skew across users/profiles. 3880 if (pi != null) { 3881 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3882 if (numMatch == permissions.length) { 3883 pi.requestedPermissions = permissions; 3884 } else { 3885 pi.requestedPermissions = new String[numMatch]; 3886 numMatch = 0; 3887 for (int i=0; i<permissions.length; i++) { 3888 if (tmp[i]) { 3889 pi.requestedPermissions[numMatch] = permissions[i]; 3890 numMatch++; 3891 } 3892 } 3893 } 3894 } 3895 list.add(pi); 3896 } 3897 } 3898 3899 @Override 3900 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3901 String[] permissions, int flags, int userId) { 3902 if (!sUserManager.exists(userId)) return null; 3903 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3904 3905 // writer 3906 synchronized (mPackages) { 3907 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3908 boolean[] tmpBools = new boolean[permissions.length]; 3909 if (listUninstalled) { 3910 for (PackageSetting ps : mSettings.mPackages.values()) { 3911 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3912 } 3913 } else { 3914 for (PackageParser.Package pkg : mPackages.values()) { 3915 PackageSetting ps = (PackageSetting)pkg.mExtras; 3916 if (ps != null) { 3917 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3918 userId); 3919 } 3920 } 3921 } 3922 3923 return new ParceledListSlice<PackageInfo>(list); 3924 } 3925 } 3926 3927 @Override 3928 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3929 if (!sUserManager.exists(userId)) return null; 3930 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3931 3932 // writer 3933 synchronized (mPackages) { 3934 ArrayList<ApplicationInfo> list; 3935 if (listUninstalled) { 3936 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3937 for (PackageSetting ps : mSettings.mPackages.values()) { 3938 ApplicationInfo ai; 3939 if (ps.pkg != null) { 3940 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3941 ps.readUserState(userId), userId); 3942 } else { 3943 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3944 } 3945 if (ai != null) { 3946 list.add(ai); 3947 } 3948 } 3949 } else { 3950 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3951 for (PackageParser.Package p : mPackages.values()) { 3952 if (p.mExtras != null) { 3953 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3954 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3955 if (ai != null) { 3956 list.add(ai); 3957 } 3958 } 3959 } 3960 } 3961 3962 return new ParceledListSlice<ApplicationInfo>(list); 3963 } 3964 } 3965 3966 public List<ApplicationInfo> getPersistentApplications(int flags) { 3967 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3968 3969 // reader 3970 synchronized (mPackages) { 3971 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3972 final int userId = UserHandle.getCallingUserId(); 3973 while (i.hasNext()) { 3974 final PackageParser.Package p = i.next(); 3975 if (p.applicationInfo != null 3976 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3977 && (!mSafeMode || isSystemApp(p))) { 3978 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3979 if (ps != null) { 3980 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3981 ps.readUserState(userId), userId); 3982 if (ai != null) { 3983 finalList.add(ai); 3984 } 3985 } 3986 } 3987 } 3988 } 3989 3990 return finalList; 3991 } 3992 3993 @Override 3994 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3995 if (!sUserManager.exists(userId)) return null; 3996 // reader 3997 synchronized (mPackages) { 3998 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3999 PackageSetting ps = provider != null 4000 ? mSettings.mPackages.get(provider.owner.packageName) 4001 : null; 4002 return ps != null 4003 && mSettings.isEnabledLPr(provider.info, flags, userId) 4004 && (!mSafeMode || (provider.info.applicationInfo.flags 4005 &ApplicationInfo.FLAG_SYSTEM) != 0) 4006 ? PackageParser.generateProviderInfo(provider, flags, 4007 ps.readUserState(userId), userId) 4008 : null; 4009 } 4010 } 4011 4012 /** 4013 * @deprecated 4014 */ 4015 @Deprecated 4016 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4017 // reader 4018 synchronized (mPackages) { 4019 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4020 .entrySet().iterator(); 4021 final int userId = UserHandle.getCallingUserId(); 4022 while (i.hasNext()) { 4023 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4024 PackageParser.Provider p = entry.getValue(); 4025 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4026 4027 if (ps != null && p.syncable 4028 && (!mSafeMode || (p.info.applicationInfo.flags 4029 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4030 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4031 ps.readUserState(userId), userId); 4032 if (info != null) { 4033 outNames.add(entry.getKey()); 4034 outInfo.add(info); 4035 } 4036 } 4037 } 4038 } 4039 } 4040 4041 @Override 4042 public List<ProviderInfo> queryContentProviders(String processName, 4043 int uid, int flags) { 4044 ArrayList<ProviderInfo> finalList = null; 4045 // reader 4046 synchronized (mPackages) { 4047 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4048 final int userId = processName != null ? 4049 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4050 while (i.hasNext()) { 4051 final PackageParser.Provider p = i.next(); 4052 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4053 if (ps != null && p.info.authority != null 4054 && (processName == null 4055 || (p.info.processName.equals(processName) 4056 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4057 && mSettings.isEnabledLPr(p.info, flags, userId) 4058 && (!mSafeMode 4059 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4060 if (finalList == null) { 4061 finalList = new ArrayList<ProviderInfo>(3); 4062 } 4063 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4064 ps.readUserState(userId), userId); 4065 if (info != null) { 4066 finalList.add(info); 4067 } 4068 } 4069 } 4070 } 4071 4072 if (finalList != null) { 4073 Collections.sort(finalList, mProviderInitOrderSorter); 4074 } 4075 4076 return finalList; 4077 } 4078 4079 @Override 4080 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4081 int flags) { 4082 // reader 4083 synchronized (mPackages) { 4084 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4085 return PackageParser.generateInstrumentationInfo(i, flags); 4086 } 4087 } 4088 4089 @Override 4090 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4091 int flags) { 4092 ArrayList<InstrumentationInfo> finalList = 4093 new ArrayList<InstrumentationInfo>(); 4094 4095 // reader 4096 synchronized (mPackages) { 4097 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4098 while (i.hasNext()) { 4099 final PackageParser.Instrumentation p = i.next(); 4100 if (targetPackage == null 4101 || targetPackage.equals(p.info.targetPackage)) { 4102 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4103 flags); 4104 if (ii != null) { 4105 finalList.add(ii); 4106 } 4107 } 4108 } 4109 } 4110 4111 return finalList; 4112 } 4113 4114 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4115 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4116 if (overlays == null) { 4117 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4118 return; 4119 } 4120 for (PackageParser.Package opkg : overlays.values()) { 4121 // Not much to do if idmap fails: we already logged the error 4122 // and we certainly don't want to abort installation of pkg simply 4123 // because an overlay didn't fit properly. For these reasons, 4124 // ignore the return value of createIdmapForPackagePairLI. 4125 createIdmapForPackagePairLI(pkg, opkg); 4126 } 4127 } 4128 4129 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4130 PackageParser.Package opkg) { 4131 if (!opkg.mTrustedOverlay) { 4132 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4133 opkg.baseCodePath + ": overlay not trusted"); 4134 return false; 4135 } 4136 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4137 if (overlaySet == null) { 4138 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4139 opkg.baseCodePath + " but target package has no known overlays"); 4140 return false; 4141 } 4142 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4143 // TODO: generate idmap for split APKs 4144 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4145 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4146 + opkg.baseCodePath); 4147 return false; 4148 } 4149 PackageParser.Package[] overlayArray = 4150 overlaySet.values().toArray(new PackageParser.Package[0]); 4151 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4152 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4153 return p1.mOverlayPriority - p2.mOverlayPriority; 4154 } 4155 }; 4156 Arrays.sort(overlayArray, cmp); 4157 4158 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4159 int i = 0; 4160 for (PackageParser.Package p : overlayArray) { 4161 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4162 } 4163 return true; 4164 } 4165 4166 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4167 final File[] files = dir.listFiles(); 4168 if (ArrayUtils.isEmpty(files)) { 4169 Log.d(TAG, "No files in app dir " + dir); 4170 return; 4171 } 4172 4173 if (DEBUG_PACKAGE_SCANNING) { 4174 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4175 + " flags=0x" + Integer.toHexString(parseFlags)); 4176 } 4177 4178 for (File file : files) { 4179 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4180 && !PackageInstallerService.isStageName(file.getName()); 4181 if (!isPackage) { 4182 // Ignore entries which are not packages 4183 continue; 4184 } 4185 try { 4186 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4187 scanFlags, currentTime, null); 4188 } catch (PackageManagerException e) { 4189 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4190 4191 // Delete invalid userdata apps 4192 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4193 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4194 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4195 if (file.isDirectory()) { 4196 mInstaller.rmPackageDir(file.getAbsolutePath()); 4197 } else { 4198 file.delete(); 4199 } 4200 } 4201 } 4202 } 4203 } 4204 4205 private static File getSettingsProblemFile() { 4206 File dataDir = Environment.getDataDirectory(); 4207 File systemDir = new File(dataDir, "system"); 4208 File fname = new File(systemDir, "uiderrors.txt"); 4209 return fname; 4210 } 4211 4212 static void reportSettingsProblem(int priority, String msg) { 4213 logCriticalInfo(priority, msg); 4214 } 4215 4216 static void logCriticalInfo(int priority, String msg) { 4217 Slog.println(priority, TAG, msg); 4218 EventLogTags.writePmCriticalInfo(msg); 4219 try { 4220 File fname = getSettingsProblemFile(); 4221 FileOutputStream out = new FileOutputStream(fname, true); 4222 PrintWriter pw = new FastPrintWriter(out); 4223 SimpleDateFormat formatter = new SimpleDateFormat(); 4224 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4225 pw.println(dateString + ": " + msg); 4226 pw.close(); 4227 FileUtils.setPermissions( 4228 fname.toString(), 4229 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4230 -1, -1); 4231 } catch (java.io.IOException e) { 4232 } 4233 } 4234 4235 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4236 PackageParser.Package pkg, File srcFile, int parseFlags) 4237 throws PackageManagerException { 4238 if (ps != null 4239 && ps.codePath.equals(srcFile) 4240 && ps.timeStamp == srcFile.lastModified() 4241 && !isCompatSignatureUpdateNeeded(pkg) 4242 && !isRecoverSignatureUpdateNeeded(pkg)) { 4243 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4244 if (ps.signatures.mSignatures != null 4245 && ps.signatures.mSignatures.length != 0 4246 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4247 // Optimization: reuse the existing cached certificates 4248 // if the package appears to be unchanged. 4249 pkg.mSignatures = ps.signatures.mSignatures; 4250 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4251 synchronized (mPackages) { 4252 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4253 } 4254 return; 4255 } 4256 4257 Slog.w(TAG, "PackageSetting for " + ps.name 4258 + " is missing signatures. Collecting certs again to recover them."); 4259 } else { 4260 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4261 } 4262 4263 try { 4264 pp.collectCertificates(pkg, parseFlags); 4265 pp.collectManifestDigest(pkg); 4266 } catch (PackageParserException e) { 4267 throw PackageManagerException.from(e); 4268 } 4269 } 4270 4271 /* 4272 * Scan a package and return the newly parsed package. 4273 * Returns null in case of errors and the error code is stored in mLastScanError 4274 */ 4275 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4276 long currentTime, UserHandle user) throws PackageManagerException { 4277 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4278 parseFlags |= mDefParseFlags; 4279 PackageParser pp = new PackageParser(); 4280 pp.setSeparateProcesses(mSeparateProcesses); 4281 pp.setOnlyCoreApps(mOnlyCore); 4282 pp.setDisplayMetrics(mMetrics); 4283 4284 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4285 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4286 } 4287 4288 final PackageParser.Package pkg; 4289 try { 4290 pkg = pp.parsePackage(scanFile, parseFlags); 4291 } catch (PackageParserException e) { 4292 throw PackageManagerException.from(e); 4293 } 4294 4295 PackageSetting ps = null; 4296 PackageSetting updatedPkg; 4297 // reader 4298 synchronized (mPackages) { 4299 // Look to see if we already know about this package. 4300 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4301 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4302 // This package has been renamed to its original name. Let's 4303 // use that. 4304 ps = mSettings.peekPackageLPr(oldName); 4305 } 4306 // If there was no original package, see one for the real package name. 4307 if (ps == null) { 4308 ps = mSettings.peekPackageLPr(pkg.packageName); 4309 } 4310 // Check to see if this package could be hiding/updating a system 4311 // package. Must look for it either under the original or real 4312 // package name depending on our state. 4313 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4314 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4315 } 4316 boolean updatedPkgBetter = false; 4317 // First check if this is a system package that may involve an update 4318 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4319 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4320 // it needs to drop FLAG_PRIVILEGED. 4321 if (locationIsPrivileged(scanFile)) { 4322 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4323 } else { 4324 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4325 } 4326 4327 if (ps != null && !ps.codePath.equals(scanFile)) { 4328 // The path has changed from what was last scanned... check the 4329 // version of the new path against what we have stored to determine 4330 // what to do. 4331 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4332 if (pkg.mVersionCode <= ps.versionCode) { 4333 // The system package has been updated and the code path does not match 4334 // Ignore entry. Skip it. 4335 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4336 + " ignored: updated version " + ps.versionCode 4337 + " better than this " + pkg.mVersionCode); 4338 if (!updatedPkg.codePath.equals(scanFile)) { 4339 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4340 + ps.name + " changing from " + updatedPkg.codePathString 4341 + " to " + scanFile); 4342 updatedPkg.codePath = scanFile; 4343 updatedPkg.codePathString = scanFile.toString(); 4344 updatedPkg.resourcePath = scanFile; 4345 updatedPkg.resourcePathString = scanFile.toString(); 4346 } 4347 updatedPkg.pkg = pkg; 4348 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4349 } else { 4350 // The current app on the system partition is better than 4351 // what we have updated to on the data partition; switch 4352 // back to the system partition version. 4353 // At this point, its safely assumed that package installation for 4354 // apps in system partition will go through. If not there won't be a working 4355 // version of the app 4356 // writer 4357 synchronized (mPackages) { 4358 // Just remove the loaded entries from package lists. 4359 mPackages.remove(ps.name); 4360 } 4361 4362 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4363 + " reverting from " + ps.codePathString 4364 + ": new version " + pkg.mVersionCode 4365 + " better than installed " + ps.versionCode); 4366 4367 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4368 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4369 getAppDexInstructionSets(ps)); 4370 synchronized (mInstallLock) { 4371 args.cleanUpResourcesLI(); 4372 } 4373 synchronized (mPackages) { 4374 mSettings.enableSystemPackageLPw(ps.name); 4375 } 4376 updatedPkgBetter = true; 4377 } 4378 } 4379 } 4380 4381 if (updatedPkg != null) { 4382 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4383 // initially 4384 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4385 4386 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4387 // flag set initially 4388 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4389 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4390 } 4391 } 4392 4393 // Verify certificates against what was last scanned 4394 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4395 4396 /* 4397 * A new system app appeared, but we already had a non-system one of the 4398 * same name installed earlier. 4399 */ 4400 boolean shouldHideSystemApp = false; 4401 if (updatedPkg == null && ps != null 4402 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4403 /* 4404 * Check to make sure the signatures match first. If they don't, 4405 * wipe the installed application and its data. 4406 */ 4407 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4408 != PackageManager.SIGNATURE_MATCH) { 4409 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4410 + " signatures don't match existing userdata copy; removing"); 4411 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4412 ps = null; 4413 } else { 4414 /* 4415 * If the newly-added system app is an older version than the 4416 * already installed version, hide it. It will be scanned later 4417 * and re-added like an update. 4418 */ 4419 if (pkg.mVersionCode <= ps.versionCode) { 4420 shouldHideSystemApp = true; 4421 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4422 + " but new version " + pkg.mVersionCode + " better than installed " 4423 + ps.versionCode + "; hiding system"); 4424 } else { 4425 /* 4426 * The newly found system app is a newer version that the 4427 * one previously installed. Simply remove the 4428 * already-installed application and replace it with our own 4429 * while keeping the application data. 4430 */ 4431 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4432 + " reverting from " + ps.codePathString + ": new version " 4433 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4434 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4435 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4436 getAppDexInstructionSets(ps)); 4437 synchronized (mInstallLock) { 4438 args.cleanUpResourcesLI(); 4439 } 4440 } 4441 } 4442 } 4443 4444 // The apk is forward locked (not public) if its code and resources 4445 // are kept in different files. (except for app in either system or 4446 // vendor path). 4447 // TODO grab this value from PackageSettings 4448 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4449 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4450 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4451 } 4452 } 4453 4454 // TODO: extend to support forward-locked splits 4455 String resourcePath = null; 4456 String baseResourcePath = null; 4457 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4458 if (ps != null && ps.resourcePathString != null) { 4459 resourcePath = ps.resourcePathString; 4460 baseResourcePath = ps.resourcePathString; 4461 } else { 4462 // Should not happen at all. Just log an error. 4463 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4464 } 4465 } else { 4466 resourcePath = pkg.codePath; 4467 baseResourcePath = pkg.baseCodePath; 4468 } 4469 4470 // Set application objects path explicitly. 4471 pkg.applicationInfo.setCodePath(pkg.codePath); 4472 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4473 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4474 pkg.applicationInfo.setResourcePath(resourcePath); 4475 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4476 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4477 4478 // Note that we invoke the following method only if we are about to unpack an application 4479 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4480 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4481 4482 /* 4483 * If the system app should be overridden by a previously installed 4484 * data, hide the system app now and let the /data/app scan pick it up 4485 * again. 4486 */ 4487 if (shouldHideSystemApp) { 4488 synchronized (mPackages) { 4489 /* 4490 * We have to grant systems permissions before we hide, because 4491 * grantPermissions will assume the package update is trying to 4492 * expand its permissions. 4493 */ 4494 grantPermissionsLPw(pkg, true, pkg.packageName); 4495 mSettings.disableSystemPackageLPw(pkg.packageName); 4496 } 4497 } 4498 4499 return scannedPkg; 4500 } 4501 4502 private static String fixProcessName(String defProcessName, 4503 String processName, int uid) { 4504 if (processName == null) { 4505 return defProcessName; 4506 } 4507 return processName; 4508 } 4509 4510 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4511 throws PackageManagerException { 4512 if (pkgSetting.signatures.mSignatures != null) { 4513 // Already existing package. Make sure signatures match 4514 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4515 == PackageManager.SIGNATURE_MATCH; 4516 if (!match) { 4517 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4518 == PackageManager.SIGNATURE_MATCH; 4519 } 4520 if (!match) { 4521 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 4522 == PackageManager.SIGNATURE_MATCH; 4523 } 4524 if (!match) { 4525 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4526 + pkg.packageName + " signatures do not match the " 4527 + "previously installed version; ignoring!"); 4528 } 4529 } 4530 4531 // Check for shared user signatures 4532 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4533 // Already existing package. Make sure signatures match 4534 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4535 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4536 if (!match) { 4537 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4538 == PackageManager.SIGNATURE_MATCH; 4539 } 4540 if (!match) { 4541 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 4542 == PackageManager.SIGNATURE_MATCH; 4543 } 4544 if (!match) { 4545 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4546 "Package " + pkg.packageName 4547 + " has no signatures that match those in shared user " 4548 + pkgSetting.sharedUser.name + "; ignoring!"); 4549 } 4550 } 4551 } 4552 4553 /** 4554 * Enforces that only the system UID or root's UID can call a method exposed 4555 * via Binder. 4556 * 4557 * @param message used as message if SecurityException is thrown 4558 * @throws SecurityException if the caller is not system or root 4559 */ 4560 private static final void enforceSystemOrRoot(String message) { 4561 final int uid = Binder.getCallingUid(); 4562 if (uid != Process.SYSTEM_UID && uid != 0) { 4563 throw new SecurityException(message); 4564 } 4565 } 4566 4567 @Override 4568 public void performBootDexOpt() { 4569 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4570 4571 // Before everything else, see whether we need to fstrim. 4572 try { 4573 IMountService ms = PackageHelper.getMountService(); 4574 if (ms != null) { 4575 final boolean isUpgrade = isUpgrade(); 4576 boolean doTrim = isUpgrade; 4577 if (doTrim) { 4578 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 4579 } else { 4580 final long interval = android.provider.Settings.Global.getLong( 4581 mContext.getContentResolver(), 4582 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 4583 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 4584 if (interval > 0) { 4585 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 4586 if (timeSinceLast > interval) { 4587 doTrim = true; 4588 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 4589 + "; running immediately"); 4590 } 4591 } 4592 } 4593 if (doTrim) { 4594 if (!isFirstBoot()) { 4595 try { 4596 ActivityManagerNative.getDefault().showBootMessage( 4597 mContext.getResources().getString( 4598 R.string.android_upgrading_fstrim), true); 4599 } catch (RemoteException e) { 4600 } 4601 } 4602 ms.runMaintenance(); 4603 } 4604 } else { 4605 Slog.e(TAG, "Mount service unavailable!"); 4606 } 4607 } catch (RemoteException e) { 4608 // Can't happen; MountService is local 4609 } 4610 4611 final ArraySet<PackageParser.Package> pkgs; 4612 synchronized (mPackages) { 4613 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 4614 } 4615 4616 if (pkgs != null) { 4617 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4618 // in case the device runs out of space. 4619 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4620 // Give priority to core apps. 4621 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4622 PackageParser.Package pkg = it.next(); 4623 if (pkg.coreApp) { 4624 if (DEBUG_DEXOPT) { 4625 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 4626 } 4627 sortedPkgs.add(pkg); 4628 it.remove(); 4629 } 4630 } 4631 // Give priority to system apps that listen for pre boot complete. 4632 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4633 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 4634 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4635 PackageParser.Package pkg = it.next(); 4636 if (pkgNames.contains(pkg.packageName)) { 4637 if (DEBUG_DEXOPT) { 4638 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 4639 } 4640 sortedPkgs.add(pkg); 4641 it.remove(); 4642 } 4643 } 4644 // Give priority to system apps. 4645 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4646 PackageParser.Package pkg = it.next(); 4647 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 4648 if (DEBUG_DEXOPT) { 4649 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 4650 } 4651 sortedPkgs.add(pkg); 4652 it.remove(); 4653 } 4654 } 4655 // Give priority to updated system apps. 4656 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4657 PackageParser.Package pkg = it.next(); 4658 if (pkg.isUpdatedSystemApp()) { 4659 if (DEBUG_DEXOPT) { 4660 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 4661 } 4662 sortedPkgs.add(pkg); 4663 it.remove(); 4664 } 4665 } 4666 // Give priority to apps that listen for boot complete. 4667 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4668 pkgNames = getPackageNamesForIntent(intent); 4669 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4670 PackageParser.Package pkg = it.next(); 4671 if (pkgNames.contains(pkg.packageName)) { 4672 if (DEBUG_DEXOPT) { 4673 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 4674 } 4675 sortedPkgs.add(pkg); 4676 it.remove(); 4677 } 4678 } 4679 // Filter out packages that aren't recently used. 4680 filterRecentlyUsedApps(pkgs); 4681 // Add all remaining apps. 4682 for (PackageParser.Package pkg : pkgs) { 4683 if (DEBUG_DEXOPT) { 4684 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 4685 } 4686 sortedPkgs.add(pkg); 4687 } 4688 4689 // If we want to be lazy, filter everything that wasn't recently used. 4690 if (mLazyDexOpt) { 4691 filterRecentlyUsedApps(sortedPkgs); 4692 } 4693 4694 int i = 0; 4695 int total = sortedPkgs.size(); 4696 File dataDir = Environment.getDataDirectory(); 4697 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 4698 if (lowThreshold == 0) { 4699 throw new IllegalStateException("Invalid low memory threshold"); 4700 } 4701 for (PackageParser.Package pkg : sortedPkgs) { 4702 long usableSpace = dataDir.getUsableSpace(); 4703 if (usableSpace < lowThreshold) { 4704 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 4705 break; 4706 } 4707 performBootDexOpt(pkg, ++i, total); 4708 } 4709 } 4710 } 4711 4712 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 4713 // Filter out packages that aren't recently used. 4714 // 4715 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4716 // should do a full dexopt. 4717 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4718 int total = pkgs.size(); 4719 int skipped = 0; 4720 long now = System.currentTimeMillis(); 4721 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4722 PackageParser.Package pkg = i.next(); 4723 long then = pkg.mLastPackageUsageTimeInMills; 4724 if (then + mDexOptLRUThresholdInMills < now) { 4725 if (DEBUG_DEXOPT) { 4726 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4727 ((then == 0) ? "never" : new Date(then))); 4728 } 4729 i.remove(); 4730 skipped++; 4731 } 4732 } 4733 if (DEBUG_DEXOPT) { 4734 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4735 } 4736 } 4737 } 4738 4739 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 4740 List<ResolveInfo> ris = null; 4741 try { 4742 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4743 intent, null, 0, UserHandle.USER_OWNER); 4744 } catch (RemoteException e) { 4745 } 4746 ArraySet<String> pkgNames = new ArraySet<String>(); 4747 if (ris != null) { 4748 for (ResolveInfo ri : ris) { 4749 pkgNames.add(ri.activityInfo.packageName); 4750 } 4751 } 4752 return pkgNames; 4753 } 4754 4755 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4756 if (DEBUG_DEXOPT) { 4757 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4758 } 4759 if (!isFirstBoot()) { 4760 try { 4761 ActivityManagerNative.getDefault().showBootMessage( 4762 mContext.getResources().getString(R.string.android_upgrading_apk, 4763 curr, total), true); 4764 } catch (RemoteException e) { 4765 } 4766 } 4767 PackageParser.Package p = pkg; 4768 synchronized (mInstallLock) { 4769 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 4770 false /* force dex */, false /* defer */, true /* include dependencies */); 4771 } 4772 } 4773 4774 @Override 4775 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4776 return performDexOpt(packageName, instructionSet, false); 4777 } 4778 4779 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4780 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4781 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4782 if (!dexopt && !updateUsage) { 4783 // We aren't going to dexopt or update usage, so bail early. 4784 return false; 4785 } 4786 PackageParser.Package p; 4787 final String targetInstructionSet; 4788 synchronized (mPackages) { 4789 p = mPackages.get(packageName); 4790 if (p == null) { 4791 return false; 4792 } 4793 if (updateUsage) { 4794 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4795 } 4796 mPackageUsage.write(false); 4797 if (!dexopt) { 4798 // We aren't going to dexopt, so bail early. 4799 return false; 4800 } 4801 4802 targetInstructionSet = instructionSet != null ? instructionSet : 4803 getPrimaryInstructionSet(p.applicationInfo); 4804 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4805 return false; 4806 } 4807 } 4808 4809 synchronized (mInstallLock) { 4810 final String[] instructionSets = new String[] { targetInstructionSet }; 4811 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 4812 false /* forceDex */, false /* defer */, true /* inclDependencies */); 4813 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 4814 } 4815 } 4816 4817 public ArraySet<String> getPackagesThatNeedDexOpt() { 4818 ArraySet<String> pkgs = null; 4819 synchronized (mPackages) { 4820 for (PackageParser.Package p : mPackages.values()) { 4821 if (DEBUG_DEXOPT) { 4822 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4823 } 4824 if (!p.mDexOptPerformed.isEmpty()) { 4825 continue; 4826 } 4827 if (pkgs == null) { 4828 pkgs = new ArraySet<String>(); 4829 } 4830 pkgs.add(p.packageName); 4831 } 4832 } 4833 return pkgs; 4834 } 4835 4836 public void shutdown() { 4837 mPackageUsage.write(true); 4838 } 4839 4840 @Override 4841 public void forceDexOpt(String packageName) { 4842 enforceSystemOrRoot("forceDexOpt"); 4843 4844 PackageParser.Package pkg; 4845 synchronized (mPackages) { 4846 pkg = mPackages.get(packageName); 4847 if (pkg == null) { 4848 throw new IllegalArgumentException("Missing package: " + packageName); 4849 } 4850 } 4851 4852 synchronized (mInstallLock) { 4853 final String[] instructionSets = new String[] { 4854 getPrimaryInstructionSet(pkg.applicationInfo) }; 4855 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 4856 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 4857 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 4858 throw new IllegalStateException("Failed to dexopt: " + res); 4859 } 4860 } 4861 } 4862 4863 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4864 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4865 Slog.w(TAG, "Unable to update from " + oldPkg.name 4866 + " to " + newPkg.packageName 4867 + ": old package not in system partition"); 4868 return false; 4869 } else if (mPackages.get(oldPkg.name) != null) { 4870 Slog.w(TAG, "Unable to update from " + oldPkg.name 4871 + " to " + newPkg.packageName 4872 + ": old package still exists"); 4873 return false; 4874 } 4875 return true; 4876 } 4877 4878 private File getDataPathForPackage(String packageName, int userId) { 4879 /* 4880 * Until we fully support multiple users, return the directory we 4881 * previously would have. The PackageManagerTests will need to be 4882 * revised when this is changed back.. 4883 */ 4884 if (userId == 0) { 4885 return new File(mAppDataDir, packageName); 4886 } else { 4887 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4888 + File.separator + packageName); 4889 } 4890 } 4891 4892 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4893 int[] users = sUserManager.getUserIds(); 4894 int res = mInstaller.install(packageName, uid, uid, seinfo); 4895 if (res < 0) { 4896 return res; 4897 } 4898 for (int user : users) { 4899 if (user != 0) { 4900 res = mInstaller.createUserData(packageName, 4901 UserHandle.getUid(user, uid), user, seinfo); 4902 if (res < 0) { 4903 return res; 4904 } 4905 } 4906 } 4907 return res; 4908 } 4909 4910 private int removeDataDirsLI(String packageName) { 4911 int[] users = sUserManager.getUserIds(); 4912 int res = 0; 4913 for (int user : users) { 4914 int resInner = mInstaller.remove(packageName, user); 4915 if (resInner < 0) { 4916 res = resInner; 4917 } 4918 } 4919 4920 return res; 4921 } 4922 4923 private int deleteCodeCacheDirsLI(String packageName) { 4924 int[] users = sUserManager.getUserIds(); 4925 int res = 0; 4926 for (int user : users) { 4927 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4928 if (resInner < 0) { 4929 res = resInner; 4930 } 4931 } 4932 return res; 4933 } 4934 4935 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4936 PackageParser.Package changingLib) { 4937 if (file.path != null) { 4938 usesLibraryFiles.add(file.path); 4939 return; 4940 } 4941 PackageParser.Package p = mPackages.get(file.apk); 4942 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4943 // If we are doing this while in the middle of updating a library apk, 4944 // then we need to make sure to use that new apk for determining the 4945 // dependencies here. (We haven't yet finished committing the new apk 4946 // to the package manager state.) 4947 if (p == null || p.packageName.equals(changingLib.packageName)) { 4948 p = changingLib; 4949 } 4950 } 4951 if (p != null) { 4952 usesLibraryFiles.addAll(p.getAllCodePaths()); 4953 } 4954 } 4955 4956 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4957 PackageParser.Package changingLib) throws PackageManagerException { 4958 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4959 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4960 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4961 for (int i=0; i<N; i++) { 4962 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4963 if (file == null) { 4964 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4965 "Package " + pkg.packageName + " requires unavailable shared library " 4966 + pkg.usesLibraries.get(i) + "; failing!"); 4967 } 4968 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4969 } 4970 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4971 for (int i=0; i<N; i++) { 4972 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4973 if (file == null) { 4974 Slog.w(TAG, "Package " + pkg.packageName 4975 + " desires unavailable shared library " 4976 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4977 } else { 4978 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4979 } 4980 } 4981 N = usesLibraryFiles.size(); 4982 if (N > 0) { 4983 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4984 } else { 4985 pkg.usesLibraryFiles = null; 4986 } 4987 } 4988 } 4989 4990 private static boolean hasString(List<String> list, List<String> which) { 4991 if (list == null) { 4992 return false; 4993 } 4994 for (int i=list.size()-1; i>=0; i--) { 4995 for (int j=which.size()-1; j>=0; j--) { 4996 if (which.get(j).equals(list.get(i))) { 4997 return true; 4998 } 4999 } 5000 } 5001 return false; 5002 } 5003 5004 private void updateAllSharedLibrariesLPw() { 5005 for (PackageParser.Package pkg : mPackages.values()) { 5006 try { 5007 updateSharedLibrariesLPw(pkg, null); 5008 } catch (PackageManagerException e) { 5009 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5010 } 5011 } 5012 } 5013 5014 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5015 PackageParser.Package changingPkg) { 5016 ArrayList<PackageParser.Package> res = null; 5017 for (PackageParser.Package pkg : mPackages.values()) { 5018 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5019 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5020 if (res == null) { 5021 res = new ArrayList<PackageParser.Package>(); 5022 } 5023 res.add(pkg); 5024 try { 5025 updateSharedLibrariesLPw(pkg, changingPkg); 5026 } catch (PackageManagerException e) { 5027 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5028 } 5029 } 5030 } 5031 return res; 5032 } 5033 5034 /** 5035 * Derive the value of the {@code cpuAbiOverride} based on the provided 5036 * value and an optional stored value from the package settings. 5037 */ 5038 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5039 String cpuAbiOverride = null; 5040 5041 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5042 cpuAbiOverride = null; 5043 } else if (abiOverride != null) { 5044 cpuAbiOverride = abiOverride; 5045 } else if (settings != null) { 5046 cpuAbiOverride = settings.cpuAbiOverrideString; 5047 } 5048 5049 return cpuAbiOverride; 5050 } 5051 5052 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5053 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5054 boolean success = false; 5055 try { 5056 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5057 currentTime, user); 5058 success = true; 5059 return res; 5060 } finally { 5061 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5062 removeDataDirsLI(pkg.packageName); 5063 } 5064 } 5065 } 5066 5067 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5068 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5069 final File scanFile = new File(pkg.codePath); 5070 if (pkg.applicationInfo.getCodePath() == null || 5071 pkg.applicationInfo.getResourcePath() == null) { 5072 // Bail out. The resource and code paths haven't been set. 5073 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5074 "Code and resource paths haven't been set correctly"); 5075 } 5076 5077 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5078 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5079 } else { 5080 // Only allow system apps to be flagged as core apps. 5081 pkg.coreApp = false; 5082 } 5083 5084 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5085 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5086 } 5087 5088 if (mCustomResolverComponentName != null && 5089 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5090 setUpCustomResolverActivity(pkg); 5091 } 5092 5093 if (pkg.packageName.equals("android")) { 5094 synchronized (mPackages) { 5095 if (mAndroidApplication != null) { 5096 Slog.w(TAG, "*************************************************"); 5097 Slog.w(TAG, "Core android package being redefined. Skipping."); 5098 Slog.w(TAG, " file=" + scanFile); 5099 Slog.w(TAG, "*************************************************"); 5100 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5101 "Core android package being redefined. Skipping."); 5102 } 5103 5104 // Set up information for our fall-back user intent resolution activity. 5105 mPlatformPackage = pkg; 5106 pkg.mVersionCode = mSdkVersion; 5107 mAndroidApplication = pkg.applicationInfo; 5108 5109 if (!mResolverReplaced) { 5110 mResolveActivity.applicationInfo = mAndroidApplication; 5111 mResolveActivity.name = ResolverActivity.class.getName(); 5112 mResolveActivity.packageName = mAndroidApplication.packageName; 5113 mResolveActivity.processName = "system:ui"; 5114 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5115 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5116 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5117 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5118 mResolveActivity.exported = true; 5119 mResolveActivity.enabled = true; 5120 mResolveInfo.activityInfo = mResolveActivity; 5121 mResolveInfo.priority = 0; 5122 mResolveInfo.preferredOrder = 0; 5123 mResolveInfo.match = 0; 5124 mResolveComponentName = new ComponentName( 5125 mAndroidApplication.packageName, mResolveActivity.name); 5126 } 5127 } 5128 } 5129 5130 if (DEBUG_PACKAGE_SCANNING) { 5131 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5132 Log.d(TAG, "Scanning package " + pkg.packageName); 5133 } 5134 5135 if (mPackages.containsKey(pkg.packageName) 5136 || mSharedLibraries.containsKey(pkg.packageName)) { 5137 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5138 "Application package " + pkg.packageName 5139 + " already installed. Skipping duplicate."); 5140 } 5141 5142 // If we're only installing presumed-existing packages, require that the 5143 // scanned APK is both already known and at the path previously established 5144 // for it. Previously unknown packages we pick up normally, but if we have an 5145 // a priori expectation about this package's install presence, enforce it. 5146 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5147 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5148 if (known != null) { 5149 if (DEBUG_PACKAGE_SCANNING) { 5150 Log.d(TAG, "Examining " + pkg.codePath 5151 + " and requiring known paths " + known.codePathString 5152 + " & " + known.resourcePathString); 5153 } 5154 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5155 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5156 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5157 "Application package " + pkg.packageName 5158 + " found at " + pkg.applicationInfo.getCodePath() 5159 + " but expected at " + known.codePathString + "; ignoring."); 5160 } 5161 } 5162 } 5163 5164 // Initialize package source and resource directories 5165 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5166 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5167 5168 SharedUserSetting suid = null; 5169 PackageSetting pkgSetting = null; 5170 5171 if (!isSystemApp(pkg)) { 5172 // Only system apps can use these features. 5173 pkg.mOriginalPackages = null; 5174 pkg.mRealPackage = null; 5175 pkg.mAdoptPermissions = null; 5176 } 5177 5178 // writer 5179 synchronized (mPackages) { 5180 if (pkg.mSharedUserId != null) { 5181 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5182 if (suid == null) { 5183 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5184 "Creating application package " + pkg.packageName 5185 + " for shared user failed"); 5186 } 5187 if (DEBUG_PACKAGE_SCANNING) { 5188 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5189 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5190 + "): packages=" + suid.packages); 5191 } 5192 } 5193 5194 // Check if we are renaming from an original package name. 5195 PackageSetting origPackage = null; 5196 String realName = null; 5197 if (pkg.mOriginalPackages != null) { 5198 // This package may need to be renamed to a previously 5199 // installed name. Let's check on that... 5200 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5201 if (pkg.mOriginalPackages.contains(renamed)) { 5202 // This package had originally been installed as the 5203 // original name, and we have already taken care of 5204 // transitioning to the new one. Just update the new 5205 // one to continue using the old name. 5206 realName = pkg.mRealPackage; 5207 if (!pkg.packageName.equals(renamed)) { 5208 // Callers into this function may have already taken 5209 // care of renaming the package; only do it here if 5210 // it is not already done. 5211 pkg.setPackageName(renamed); 5212 } 5213 5214 } else { 5215 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5216 if ((origPackage = mSettings.peekPackageLPr( 5217 pkg.mOriginalPackages.get(i))) != null) { 5218 // We do have the package already installed under its 5219 // original name... should we use it? 5220 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5221 // New package is not compatible with original. 5222 origPackage = null; 5223 continue; 5224 } else if (origPackage.sharedUser != null) { 5225 // Make sure uid is compatible between packages. 5226 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5227 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5228 + " to " + pkg.packageName + ": old uid " 5229 + origPackage.sharedUser.name 5230 + " differs from " + pkg.mSharedUserId); 5231 origPackage = null; 5232 continue; 5233 } 5234 } else { 5235 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5236 + pkg.packageName + " to old name " + origPackage.name); 5237 } 5238 break; 5239 } 5240 } 5241 } 5242 } 5243 5244 if (mTransferedPackages.contains(pkg.packageName)) { 5245 Slog.w(TAG, "Package " + pkg.packageName 5246 + " was transferred to another, but its .apk remains"); 5247 } 5248 5249 // Just create the setting, don't add it yet. For already existing packages 5250 // the PkgSetting exists already and doesn't have to be created. 5251 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5252 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5253 pkg.applicationInfo.primaryCpuAbi, 5254 pkg.applicationInfo.secondaryCpuAbi, 5255 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5256 user, false); 5257 if (pkgSetting == null) { 5258 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5259 "Creating application package " + pkg.packageName + " failed"); 5260 } 5261 5262 if (pkgSetting.origPackage != null) { 5263 // If we are first transitioning from an original package, 5264 // fix up the new package's name now. We need to do this after 5265 // looking up the package under its new name, so getPackageLP 5266 // can take care of fiddling things correctly. 5267 pkg.setPackageName(origPackage.name); 5268 5269 // File a report about this. 5270 String msg = "New package " + pkgSetting.realName 5271 + " renamed to replace old package " + pkgSetting.name; 5272 reportSettingsProblem(Log.WARN, msg); 5273 5274 // Make a note of it. 5275 mTransferedPackages.add(origPackage.name); 5276 5277 // No longer need to retain this. 5278 pkgSetting.origPackage = null; 5279 } 5280 5281 if (realName != null) { 5282 // Make a note of it. 5283 mTransferedPackages.add(pkg.packageName); 5284 } 5285 5286 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5287 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5288 } 5289 5290 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5291 // Check all shared libraries and map to their actual file path. 5292 // We only do this here for apps not on a system dir, because those 5293 // are the only ones that can fail an install due to this. We 5294 // will take care of the system apps by updating all of their 5295 // library paths after the scan is done. 5296 updateSharedLibrariesLPw(pkg, null); 5297 } 5298 5299 if (mFoundPolicyFile) { 5300 SELinuxMMAC.assignSeinfoValue(pkg); 5301 } 5302 5303 pkg.applicationInfo.uid = pkgSetting.appId; 5304 pkg.mExtras = pkgSetting; 5305 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5306 try { 5307 verifySignaturesLP(pkgSetting, pkg); 5308 // We just determined the app is signed correctly, so bring 5309 // over the latest parsed certs. 5310 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5311 } catch (PackageManagerException e) { 5312 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5313 throw e; 5314 } 5315 // The signature has changed, but this package is in the system 5316 // image... let's recover! 5317 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5318 // However... if this package is part of a shared user, but it 5319 // doesn't match the signature of the shared user, let's fail. 5320 // What this means is that you can't change the signatures 5321 // associated with an overall shared user, which doesn't seem all 5322 // that unreasonable. 5323 if (pkgSetting.sharedUser != null) { 5324 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5325 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5326 throw new PackageManagerException( 5327 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5328 "Signature mismatch for shared user : " 5329 + pkgSetting.sharedUser); 5330 } 5331 } 5332 // File a report about this. 5333 String msg = "System package " + pkg.packageName 5334 + " signature changed; retaining data."; 5335 reportSettingsProblem(Log.WARN, msg); 5336 } 5337 } else { 5338 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5339 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5340 + pkg.packageName + " upgrade keys do not match the " 5341 + "previously installed version"); 5342 } else { 5343 // We just determined the app is signed correctly, so bring 5344 // over the latest parsed certs. 5345 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5346 } 5347 } 5348 // Verify that this new package doesn't have any content providers 5349 // that conflict with existing packages. Only do this if the 5350 // package isn't already installed, since we don't want to break 5351 // things that are installed. 5352 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5353 final int N = pkg.providers.size(); 5354 int i; 5355 for (i=0; i<N; i++) { 5356 PackageParser.Provider p = pkg.providers.get(i); 5357 if (p.info.authority != null) { 5358 String names[] = p.info.authority.split(";"); 5359 for (int j = 0; j < names.length; j++) { 5360 if (mProvidersByAuthority.containsKey(names[j])) { 5361 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5362 final String otherPackageName = 5363 ((other != null && other.getComponentName() != null) ? 5364 other.getComponentName().getPackageName() : "?"); 5365 throw new PackageManagerException( 5366 INSTALL_FAILED_CONFLICTING_PROVIDER, 5367 "Can't install because provider name " + names[j] 5368 + " (in package " + pkg.applicationInfo.packageName 5369 + ") is already used by " + otherPackageName); 5370 } 5371 } 5372 } 5373 } 5374 } 5375 5376 if (pkg.mAdoptPermissions != null) { 5377 // This package wants to adopt ownership of permissions from 5378 // another package. 5379 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5380 final String origName = pkg.mAdoptPermissions.get(i); 5381 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5382 if (orig != null) { 5383 if (verifyPackageUpdateLPr(orig, pkg)) { 5384 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5385 + pkg.packageName); 5386 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5387 } 5388 } 5389 } 5390 } 5391 } 5392 5393 final String pkgName = pkg.packageName; 5394 5395 final long scanFileTime = scanFile.lastModified(); 5396 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5397 pkg.applicationInfo.processName = fixProcessName( 5398 pkg.applicationInfo.packageName, 5399 pkg.applicationInfo.processName, 5400 pkg.applicationInfo.uid); 5401 5402 File dataPath; 5403 if (mPlatformPackage == pkg) { 5404 // The system package is special. 5405 dataPath = new File(Environment.getDataDirectory(), "system"); 5406 5407 pkg.applicationInfo.dataDir = dataPath.getPath(); 5408 5409 } else { 5410 // This is a normal package, need to make its data directory. 5411 dataPath = getDataPathForPackage(pkg.packageName, 0); 5412 5413 boolean uidError = false; 5414 if (dataPath.exists()) { 5415 int currentUid = 0; 5416 try { 5417 StructStat stat = Os.stat(dataPath.getPath()); 5418 currentUid = stat.st_uid; 5419 } catch (ErrnoException e) { 5420 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5421 } 5422 5423 // If we have mismatched owners for the data path, we have a problem. 5424 if (currentUid != pkg.applicationInfo.uid) { 5425 boolean recovered = false; 5426 if (currentUid == 0) { 5427 // The directory somehow became owned by root. Wow. 5428 // This is probably because the system was stopped while 5429 // installd was in the middle of messing with its libs 5430 // directory. Ask installd to fix that. 5431 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5432 pkg.applicationInfo.uid); 5433 if (ret >= 0) { 5434 recovered = true; 5435 String msg = "Package " + pkg.packageName 5436 + " unexpectedly changed to uid 0; recovered to " + 5437 + pkg.applicationInfo.uid; 5438 reportSettingsProblem(Log.WARN, msg); 5439 } 5440 } 5441 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5442 || (scanFlags&SCAN_BOOTING) != 0)) { 5443 // If this is a system app, we can at least delete its 5444 // current data so the application will still work. 5445 int ret = removeDataDirsLI(pkgName); 5446 if (ret >= 0) { 5447 // TODO: Kill the processes first 5448 // Old data gone! 5449 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5450 ? "System package " : "Third party package "; 5451 String msg = prefix + pkg.packageName 5452 + " has changed from uid: " 5453 + currentUid + " to " 5454 + pkg.applicationInfo.uid + "; old data erased"; 5455 reportSettingsProblem(Log.WARN, msg); 5456 recovered = true; 5457 5458 // And now re-install the app. 5459 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5460 pkg.applicationInfo.seinfo); 5461 if (ret == -1) { 5462 // Ack should not happen! 5463 msg = prefix + pkg.packageName 5464 + " could not have data directory re-created after delete."; 5465 reportSettingsProblem(Log.WARN, msg); 5466 throw new PackageManagerException( 5467 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5468 } 5469 } 5470 if (!recovered) { 5471 mHasSystemUidErrors = true; 5472 } 5473 } else if (!recovered) { 5474 // If we allow this install to proceed, we will be broken. 5475 // Abort, abort! 5476 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5477 "scanPackageLI"); 5478 } 5479 if (!recovered) { 5480 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5481 + pkg.applicationInfo.uid + "/fs_" 5482 + currentUid; 5483 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5484 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5485 String msg = "Package " + pkg.packageName 5486 + " has mismatched uid: " 5487 + currentUid + " on disk, " 5488 + pkg.applicationInfo.uid + " in settings"; 5489 // writer 5490 synchronized (mPackages) { 5491 mSettings.mReadMessages.append(msg); 5492 mSettings.mReadMessages.append('\n'); 5493 uidError = true; 5494 if (!pkgSetting.uidError) { 5495 reportSettingsProblem(Log.ERROR, msg); 5496 } 5497 } 5498 } 5499 } 5500 pkg.applicationInfo.dataDir = dataPath.getPath(); 5501 if (mShouldRestoreconData) { 5502 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5503 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5504 pkg.applicationInfo.uid); 5505 } 5506 } else { 5507 if (DEBUG_PACKAGE_SCANNING) { 5508 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5509 Log.v(TAG, "Want this data dir: " + dataPath); 5510 } 5511 //invoke installer to do the actual installation 5512 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5513 pkg.applicationInfo.seinfo); 5514 if (ret < 0) { 5515 // Error from installer 5516 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5517 "Unable to create data dirs [errorCode=" + ret + "]"); 5518 } 5519 5520 if (dataPath.exists()) { 5521 pkg.applicationInfo.dataDir = dataPath.getPath(); 5522 } else { 5523 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5524 pkg.applicationInfo.dataDir = null; 5525 } 5526 } 5527 5528 pkgSetting.uidError = uidError; 5529 } 5530 5531 final String path = scanFile.getPath(); 5532 final String codePath = pkg.applicationInfo.getCodePath(); 5533 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5534 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5535 setBundledAppAbisAndRoots(pkg, pkgSetting); 5536 5537 // If we haven't found any native libraries for the app, check if it has 5538 // renderscript code. We'll need to force the app to 32 bit if it has 5539 // renderscript bitcode. 5540 if (pkg.applicationInfo.primaryCpuAbi == null 5541 && pkg.applicationInfo.secondaryCpuAbi == null 5542 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5543 NativeLibraryHelper.Handle handle = null; 5544 try { 5545 handle = NativeLibraryHelper.Handle.create(scanFile); 5546 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5547 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5548 } 5549 } catch (IOException ioe) { 5550 Slog.w(TAG, "Error scanning system app : " + ioe); 5551 } finally { 5552 IoUtils.closeQuietly(handle); 5553 } 5554 } 5555 5556 setNativeLibraryPaths(pkg); 5557 } else { 5558 // TODO: We can probably be smarter about this stuff. For installed apps, 5559 // we can calculate this information at install time once and for all. For 5560 // system apps, we can probably assume that this information doesn't change 5561 // after the first boot scan. As things stand, we do lots of unnecessary work. 5562 5563 // Give ourselves some initial paths; we'll come back for another 5564 // pass once we've determined ABI below. 5565 setNativeLibraryPaths(pkg); 5566 5567 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 5568 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5569 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5570 5571 NativeLibraryHelper.Handle handle = null; 5572 try { 5573 handle = NativeLibraryHelper.Handle.create(scanFile); 5574 // TODO(multiArch): This can be null for apps that didn't go through the 5575 // usual installation process. We can calculate it again, like we 5576 // do during install time. 5577 // 5578 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5579 // unnecessary. 5580 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5581 5582 // Null out the abis so that they can be recalculated. 5583 pkg.applicationInfo.primaryCpuAbi = null; 5584 pkg.applicationInfo.secondaryCpuAbi = null; 5585 if (isMultiArch(pkg.applicationInfo)) { 5586 // Warn if we've set an abiOverride for multi-lib packages.. 5587 // By definition, we need to copy both 32 and 64 bit libraries for 5588 // such packages. 5589 if (pkg.cpuAbiOverride != null 5590 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5591 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5592 } 5593 5594 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5595 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5596 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5597 if (isAsec) { 5598 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5599 } else { 5600 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5601 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5602 useIsaSpecificSubdirs); 5603 } 5604 } 5605 5606 maybeThrowExceptionForMultiArchCopy( 5607 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5608 5609 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5610 if (isAsec) { 5611 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5612 } else { 5613 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5614 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5615 useIsaSpecificSubdirs); 5616 } 5617 } 5618 5619 maybeThrowExceptionForMultiArchCopy( 5620 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5621 5622 if (abi64 >= 0) { 5623 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5624 } 5625 5626 if (abi32 >= 0) { 5627 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5628 if (abi64 >= 0) { 5629 pkg.applicationInfo.secondaryCpuAbi = abi; 5630 } else { 5631 pkg.applicationInfo.primaryCpuAbi = abi; 5632 } 5633 } 5634 } else { 5635 String[] abiList = (cpuAbiOverride != null) ? 5636 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5637 5638 // Enable gross and lame hacks for apps that are built with old 5639 // SDK tools. We must scan their APKs for renderscript bitcode and 5640 // not launch them if it's present. Don't bother checking on devices 5641 // that don't have 64 bit support. 5642 boolean needsRenderScriptOverride = false; 5643 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5644 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5645 abiList = Build.SUPPORTED_32_BIT_ABIS; 5646 needsRenderScriptOverride = true; 5647 } 5648 5649 final int copyRet; 5650 if (isAsec) { 5651 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5652 } else { 5653 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5654 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5655 } 5656 5657 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5658 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5659 "Error unpackaging native libs for app, errorCode=" + copyRet); 5660 } 5661 5662 if (copyRet >= 0) { 5663 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5664 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5665 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5666 } else if (needsRenderScriptOverride) { 5667 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5668 } 5669 } 5670 } catch (IOException ioe) { 5671 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5672 } finally { 5673 IoUtils.closeQuietly(handle); 5674 } 5675 5676 // Now that we've calculated the ABIs and determined if it's an internal app, 5677 // we will go ahead and populate the nativeLibraryPath. 5678 setNativeLibraryPaths(pkg); 5679 5680 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5681 final int[] userIds = sUserManager.getUserIds(); 5682 synchronized (mInstallLock) { 5683 // Create a native library symlink only if we have native libraries 5684 // and if the native libraries are 32 bit libraries. We do not provide 5685 // this symlink for 64 bit libraries. 5686 if (pkg.applicationInfo.primaryCpuAbi != null && 5687 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5688 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5689 for (int userId : userIds) { 5690 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5691 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5692 "Failed linking native library dir (user=" + userId + ")"); 5693 } 5694 } 5695 } 5696 } 5697 } 5698 5699 // This is a special case for the "system" package, where the ABI is 5700 // dictated by the zygote configuration (and init.rc). We should keep track 5701 // of this ABI so that we can deal with "normal" applications that run under 5702 // the same UID correctly. 5703 if (mPlatformPackage == pkg) { 5704 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5705 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5706 } 5707 5708 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5709 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5710 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5711 // Copy the derived override back to the parsed package, so that we can 5712 // update the package settings accordingly. 5713 pkg.cpuAbiOverride = cpuAbiOverride; 5714 5715 if (DEBUG_ABI_SELECTION) { 5716 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5717 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5718 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5719 } 5720 5721 // Push the derived path down into PackageSettings so we know what to 5722 // clean up at uninstall time. 5723 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5724 5725 if (DEBUG_ABI_SELECTION) { 5726 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5727 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5728 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5729 } 5730 5731 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5732 // We don't do this here during boot because we can do it all 5733 // at once after scanning all existing packages. 5734 // 5735 // We also do this *before* we perform dexopt on this package, so that 5736 // we can avoid redundant dexopts, and also to make sure we've got the 5737 // code and package path correct. 5738 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5739 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5740 } 5741 5742 if ((scanFlags & SCAN_NO_DEX) == 0) { 5743 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 5744 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 5745 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5746 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5747 } 5748 } 5749 if (mFactoryTest && pkg.requestedPermissions.contains( 5750 android.Manifest.permission.FACTORY_TEST)) { 5751 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5752 } 5753 5754 ArrayList<PackageParser.Package> clientLibPkgs = null; 5755 5756 // writer 5757 synchronized (mPackages) { 5758 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5759 // Only system apps can add new shared libraries. 5760 if (pkg.libraryNames != null) { 5761 for (int i=0; i<pkg.libraryNames.size(); i++) { 5762 String name = pkg.libraryNames.get(i); 5763 boolean allowed = false; 5764 if (pkg.isUpdatedSystemApp()) { 5765 // New library entries can only be added through the 5766 // system image. This is important to get rid of a lot 5767 // of nasty edge cases: for example if we allowed a non- 5768 // system update of the app to add a library, then uninstalling 5769 // the update would make the library go away, and assumptions 5770 // we made such as through app install filtering would now 5771 // have allowed apps on the device which aren't compatible 5772 // with it. Better to just have the restriction here, be 5773 // conservative, and create many fewer cases that can negatively 5774 // impact the user experience. 5775 final PackageSetting sysPs = mSettings 5776 .getDisabledSystemPkgLPr(pkg.packageName); 5777 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5778 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5779 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5780 allowed = true; 5781 allowed = true; 5782 break; 5783 } 5784 } 5785 } 5786 } else { 5787 allowed = true; 5788 } 5789 if (allowed) { 5790 if (!mSharedLibraries.containsKey(name)) { 5791 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5792 } else if (!name.equals(pkg.packageName)) { 5793 Slog.w(TAG, "Package " + pkg.packageName + " library " 5794 + name + " already exists; skipping"); 5795 } 5796 } else { 5797 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5798 + name + " that is not declared on system image; skipping"); 5799 } 5800 } 5801 if ((scanFlags&SCAN_BOOTING) == 0) { 5802 // If we are not booting, we need to update any applications 5803 // that are clients of our shared library. If we are booting, 5804 // this will all be done once the scan is complete. 5805 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5806 } 5807 } 5808 } 5809 } 5810 5811 // We also need to dexopt any apps that are dependent on this library. Note that 5812 // if these fail, we should abort the install since installing the library will 5813 // result in some apps being broken. 5814 if (clientLibPkgs != null) { 5815 if ((scanFlags & SCAN_NO_DEX) == 0) { 5816 for (int i = 0; i < clientLibPkgs.size(); i++) { 5817 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5818 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 5819 null /* instruction sets */, forceDex, 5820 (scanFlags & SCAN_DEFER_DEX) != 0, false); 5821 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5822 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5823 "scanPackageLI failed to dexopt clientLibPkgs"); 5824 } 5825 } 5826 } 5827 } 5828 5829 // Request the ActivityManager to kill the process(only for existing packages) 5830 // so that we do not end up in a confused state while the user is still using the older 5831 // version of the application while the new one gets installed. 5832 if ((scanFlags & SCAN_REPLACING) != 0) { 5833 killApplication(pkg.applicationInfo.packageName, 5834 pkg.applicationInfo.uid, "update pkg"); 5835 } 5836 5837 // Also need to kill any apps that are dependent on the library. 5838 if (clientLibPkgs != null) { 5839 for (int i=0; i<clientLibPkgs.size(); i++) { 5840 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5841 killApplication(clientPkg.applicationInfo.packageName, 5842 clientPkg.applicationInfo.uid, "update lib"); 5843 } 5844 } 5845 5846 // writer 5847 synchronized (mPackages) { 5848 // We don't expect installation to fail beyond this point 5849 5850 // Add the new setting to mSettings 5851 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5852 // Add the new setting to mPackages 5853 mPackages.put(pkg.applicationInfo.packageName, pkg); 5854 // Make sure we don't accidentally delete its data. 5855 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5856 while (iter.hasNext()) { 5857 PackageCleanItem item = iter.next(); 5858 if (pkgName.equals(item.packageName)) { 5859 iter.remove(); 5860 } 5861 } 5862 5863 // Take care of first install / last update times. 5864 if (currentTime != 0) { 5865 if (pkgSetting.firstInstallTime == 0) { 5866 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5867 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5868 pkgSetting.lastUpdateTime = currentTime; 5869 } 5870 } else if (pkgSetting.firstInstallTime == 0) { 5871 // We need *something*. Take time time stamp of the file. 5872 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5873 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5874 if (scanFileTime != pkgSetting.timeStamp) { 5875 // A package on the system image has changed; consider this 5876 // to be an update. 5877 pkgSetting.lastUpdateTime = scanFileTime; 5878 } 5879 } 5880 5881 // Add the package's KeySets to the global KeySetManagerService 5882 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5883 try { 5884 // Old KeySetData no longer valid. 5885 ksms.removeAppKeySetDataLPw(pkg.packageName); 5886 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5887 if (pkg.mKeySetMapping != null) { 5888 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5889 pkg.mKeySetMapping.entrySet()) { 5890 if (entry.getValue() != null) { 5891 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5892 entry.getValue(), entry.getKey()); 5893 } 5894 } 5895 if (pkg.mUpgradeKeySets != null) { 5896 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5897 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5898 } 5899 } 5900 } 5901 } catch (NullPointerException e) { 5902 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5903 } catch (IllegalArgumentException e) { 5904 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5905 } 5906 5907 int N = pkg.providers.size(); 5908 StringBuilder r = null; 5909 int i; 5910 for (i=0; i<N; i++) { 5911 PackageParser.Provider p = pkg.providers.get(i); 5912 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5913 p.info.processName, pkg.applicationInfo.uid); 5914 mProviders.addProvider(p); 5915 p.syncable = p.info.isSyncable; 5916 if (p.info.authority != null) { 5917 String names[] = p.info.authority.split(";"); 5918 p.info.authority = null; 5919 for (int j = 0; j < names.length; j++) { 5920 if (j == 1 && p.syncable) { 5921 // We only want the first authority for a provider to possibly be 5922 // syncable, so if we already added this provider using a different 5923 // authority clear the syncable flag. We copy the provider before 5924 // changing it because the mProviders object contains a reference 5925 // to a provider that we don't want to change. 5926 // Only do this for the second authority since the resulting provider 5927 // object can be the same for all future authorities for this provider. 5928 p = new PackageParser.Provider(p); 5929 p.syncable = false; 5930 } 5931 if (!mProvidersByAuthority.containsKey(names[j])) { 5932 mProvidersByAuthority.put(names[j], p); 5933 if (p.info.authority == null) { 5934 p.info.authority = names[j]; 5935 } else { 5936 p.info.authority = p.info.authority + ";" + names[j]; 5937 } 5938 if (DEBUG_PACKAGE_SCANNING) { 5939 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5940 Log.d(TAG, "Registered content provider: " + names[j] 5941 + ", className = " + p.info.name + ", isSyncable = " 5942 + p.info.isSyncable); 5943 } 5944 } else { 5945 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5946 Slog.w(TAG, "Skipping provider name " + names[j] + 5947 " (in package " + pkg.applicationInfo.packageName + 5948 "): name already used by " 5949 + ((other != null && other.getComponentName() != null) 5950 ? other.getComponentName().getPackageName() : "?")); 5951 } 5952 } 5953 } 5954 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5955 if (r == null) { 5956 r = new StringBuilder(256); 5957 } else { 5958 r.append(' '); 5959 } 5960 r.append(p.info.name); 5961 } 5962 } 5963 if (r != null) { 5964 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5965 } 5966 5967 N = pkg.services.size(); 5968 r = null; 5969 for (i=0; i<N; i++) { 5970 PackageParser.Service s = pkg.services.get(i); 5971 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5972 s.info.processName, pkg.applicationInfo.uid); 5973 mServices.addService(s); 5974 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5975 if (r == null) { 5976 r = new StringBuilder(256); 5977 } else { 5978 r.append(' '); 5979 } 5980 r.append(s.info.name); 5981 } 5982 } 5983 if (r != null) { 5984 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5985 } 5986 5987 N = pkg.receivers.size(); 5988 r = null; 5989 for (i=0; i<N; i++) { 5990 PackageParser.Activity a = pkg.receivers.get(i); 5991 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5992 a.info.processName, pkg.applicationInfo.uid); 5993 mReceivers.addActivity(a, "receiver"); 5994 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5995 if (r == null) { 5996 r = new StringBuilder(256); 5997 } else { 5998 r.append(' '); 5999 } 6000 r.append(a.info.name); 6001 } 6002 } 6003 if (r != null) { 6004 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6005 } 6006 6007 N = pkg.activities.size(); 6008 r = null; 6009 for (i=0; i<N; i++) { 6010 PackageParser.Activity a = pkg.activities.get(i); 6011 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6012 a.info.processName, pkg.applicationInfo.uid); 6013 mActivities.addActivity(a, "activity"); 6014 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6015 if (r == null) { 6016 r = new StringBuilder(256); 6017 } else { 6018 r.append(' '); 6019 } 6020 r.append(a.info.name); 6021 } 6022 } 6023 if (r != null) { 6024 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6025 } 6026 6027 N = pkg.permissionGroups.size(); 6028 r = null; 6029 for (i=0; i<N; i++) { 6030 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6031 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6032 if (cur == null) { 6033 mPermissionGroups.put(pg.info.name, pg); 6034 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6035 if (r == null) { 6036 r = new StringBuilder(256); 6037 } else { 6038 r.append(' '); 6039 } 6040 r.append(pg.info.name); 6041 } 6042 } else { 6043 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6044 + pg.info.packageName + " ignored: original from " 6045 + cur.info.packageName); 6046 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6047 if (r == null) { 6048 r = new StringBuilder(256); 6049 } else { 6050 r.append(' '); 6051 } 6052 r.append("DUP:"); 6053 r.append(pg.info.name); 6054 } 6055 } 6056 } 6057 if (r != null) { 6058 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6059 } 6060 6061 N = pkg.permissions.size(); 6062 r = null; 6063 for (i=0; i<N; i++) { 6064 PackageParser.Permission p = pkg.permissions.get(i); 6065 ArrayMap<String, BasePermission> permissionMap = 6066 p.tree ? mSettings.mPermissionTrees 6067 : mSettings.mPermissions; 6068 p.group = mPermissionGroups.get(p.info.group); 6069 if (p.info.group == null || p.group != null) { 6070 BasePermission bp = permissionMap.get(p.info.name); 6071 6072 // Allow system apps to redefine non-system permissions 6073 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6074 final boolean currentOwnerIsSystem = (bp.perm != null 6075 && isSystemApp(bp.perm.owner)); 6076 if (isSystemApp(p.owner)) { 6077 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6078 // It's a built-in permission and no owner, take ownership now 6079 bp.packageSetting = pkgSetting; 6080 bp.perm = p; 6081 bp.uid = pkg.applicationInfo.uid; 6082 bp.sourcePackage = p.info.packageName; 6083 } else if (!currentOwnerIsSystem) { 6084 String msg = "New decl " + p.owner + " of permission " 6085 + p.info.name + " is system; overriding " + bp.sourcePackage; 6086 reportSettingsProblem(Log.WARN, msg); 6087 bp = null; 6088 } 6089 } 6090 } 6091 6092 if (bp == null) { 6093 bp = new BasePermission(p.info.name, p.info.packageName, 6094 BasePermission.TYPE_NORMAL); 6095 permissionMap.put(p.info.name, bp); 6096 } 6097 6098 if (bp.perm == null) { 6099 if (bp.sourcePackage == null 6100 || bp.sourcePackage.equals(p.info.packageName)) { 6101 BasePermission tree = findPermissionTreeLP(p.info.name); 6102 if (tree == null 6103 || tree.sourcePackage.equals(p.info.packageName)) { 6104 bp.packageSetting = pkgSetting; 6105 bp.perm = p; 6106 bp.uid = pkg.applicationInfo.uid; 6107 bp.sourcePackage = p.info.packageName; 6108 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6109 if (r == null) { 6110 r = new StringBuilder(256); 6111 } else { 6112 r.append(' '); 6113 } 6114 r.append(p.info.name); 6115 } 6116 } else { 6117 Slog.w(TAG, "Permission " + p.info.name + " from package " 6118 + p.info.packageName + " ignored: base tree " 6119 + tree.name + " is from package " 6120 + tree.sourcePackage); 6121 } 6122 } else { 6123 Slog.w(TAG, "Permission " + p.info.name + " from package " 6124 + p.info.packageName + " ignored: original from " 6125 + bp.sourcePackage); 6126 } 6127 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6128 if (r == null) { 6129 r = new StringBuilder(256); 6130 } else { 6131 r.append(' '); 6132 } 6133 r.append("DUP:"); 6134 r.append(p.info.name); 6135 } 6136 if (bp.perm == p) { 6137 bp.protectionLevel = p.info.protectionLevel; 6138 } 6139 } else { 6140 Slog.w(TAG, "Permission " + p.info.name + " from package " 6141 + p.info.packageName + " ignored: no group " 6142 + p.group); 6143 } 6144 } 6145 if (r != null) { 6146 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6147 } 6148 6149 N = pkg.instrumentation.size(); 6150 r = null; 6151 for (i=0; i<N; i++) { 6152 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6153 a.info.packageName = pkg.applicationInfo.packageName; 6154 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6155 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6156 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6157 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6158 a.info.dataDir = pkg.applicationInfo.dataDir; 6159 6160 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6161 // need other information about the application, like the ABI and what not ? 6162 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6163 mInstrumentation.put(a.getComponentName(), a); 6164 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6165 if (r == null) { 6166 r = new StringBuilder(256); 6167 } else { 6168 r.append(' '); 6169 } 6170 r.append(a.info.name); 6171 } 6172 } 6173 if (r != null) { 6174 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6175 } 6176 6177 if (pkg.protectedBroadcasts != null) { 6178 N = pkg.protectedBroadcasts.size(); 6179 for (i=0; i<N; i++) { 6180 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6181 } 6182 } 6183 6184 pkgSetting.setTimeStamp(scanFileTime); 6185 6186 // Create idmap files for pairs of (packages, overlay packages). 6187 // Note: "android", ie framework-res.apk, is handled by native layers. 6188 if (pkg.mOverlayTarget != null) { 6189 // This is an overlay package. 6190 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6191 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6192 mOverlays.put(pkg.mOverlayTarget, 6193 new ArrayMap<String, PackageParser.Package>()); 6194 } 6195 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6196 map.put(pkg.packageName, pkg); 6197 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6198 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6199 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6200 "scanPackageLI failed to createIdmap"); 6201 } 6202 } 6203 } else if (mOverlays.containsKey(pkg.packageName) && 6204 !pkg.packageName.equals("android")) { 6205 // This is a regular package, with one or more known overlay packages. 6206 createIdmapsForPackageLI(pkg); 6207 } 6208 } 6209 6210 return pkg; 6211 } 6212 6213 /** 6214 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6215 * i.e, so that all packages can be run inside a single process if required. 6216 * 6217 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6218 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6219 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6220 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6221 * updating a package that belongs to a shared user. 6222 * 6223 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6224 * adds unnecessary complexity. 6225 */ 6226 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6227 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6228 String requiredInstructionSet = null; 6229 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6230 requiredInstructionSet = VMRuntime.getInstructionSet( 6231 scannedPackage.applicationInfo.primaryCpuAbi); 6232 } 6233 6234 PackageSetting requirer = null; 6235 for (PackageSetting ps : packagesForUser) { 6236 // If packagesForUser contains scannedPackage, we skip it. This will happen 6237 // when scannedPackage is an update of an existing package. Without this check, 6238 // we will never be able to change the ABI of any package belonging to a shared 6239 // user, even if it's compatible with other packages. 6240 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6241 if (ps.primaryCpuAbiString == null) { 6242 continue; 6243 } 6244 6245 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6246 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6247 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6248 // this but there's not much we can do. 6249 String errorMessage = "Instruction set mismatch, " 6250 + ((requirer == null) ? "[caller]" : requirer) 6251 + " requires " + requiredInstructionSet + " whereas " + ps 6252 + " requires " + instructionSet; 6253 Slog.w(TAG, errorMessage); 6254 } 6255 6256 if (requiredInstructionSet == null) { 6257 requiredInstructionSet = instructionSet; 6258 requirer = ps; 6259 } 6260 } 6261 } 6262 6263 if (requiredInstructionSet != null) { 6264 String adjustedAbi; 6265 if (requirer != null) { 6266 // requirer != null implies that either scannedPackage was null or that scannedPackage 6267 // did not require an ABI, in which case we have to adjust scannedPackage to match 6268 // the ABI of the set (which is the same as requirer's ABI) 6269 adjustedAbi = requirer.primaryCpuAbiString; 6270 if (scannedPackage != null) { 6271 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6272 } 6273 } else { 6274 // requirer == null implies that we're updating all ABIs in the set to 6275 // match scannedPackage. 6276 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6277 } 6278 6279 for (PackageSetting ps : packagesForUser) { 6280 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6281 if (ps.primaryCpuAbiString != null) { 6282 continue; 6283 } 6284 6285 ps.primaryCpuAbiString = adjustedAbi; 6286 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6287 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6288 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6289 6290 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6291 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6292 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6293 ps.primaryCpuAbiString = null; 6294 ps.pkg.applicationInfo.primaryCpuAbi = null; 6295 return; 6296 } else { 6297 mInstaller.rmdex(ps.codePathString, 6298 getDexCodeInstructionSet(getPreferredInstructionSet())); 6299 } 6300 } 6301 } 6302 } 6303 } 6304 } 6305 6306 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6307 synchronized (mPackages) { 6308 mResolverReplaced = true; 6309 // Set up information for custom user intent resolution activity. 6310 mResolveActivity.applicationInfo = pkg.applicationInfo; 6311 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6312 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6313 mResolveActivity.processName = pkg.applicationInfo.packageName; 6314 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6315 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6316 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6317 mResolveActivity.theme = 0; 6318 mResolveActivity.exported = true; 6319 mResolveActivity.enabled = true; 6320 mResolveInfo.activityInfo = mResolveActivity; 6321 mResolveInfo.priority = 0; 6322 mResolveInfo.preferredOrder = 0; 6323 mResolveInfo.match = 0; 6324 mResolveComponentName = mCustomResolverComponentName; 6325 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6326 mResolveComponentName); 6327 } 6328 } 6329 6330 private static String calculateBundledApkRoot(final String codePathString) { 6331 final File codePath = new File(codePathString); 6332 final File codeRoot; 6333 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6334 codeRoot = Environment.getRootDirectory(); 6335 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6336 codeRoot = Environment.getOemDirectory(); 6337 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6338 codeRoot = Environment.getVendorDirectory(); 6339 } else { 6340 // Unrecognized code path; take its top real segment as the apk root: 6341 // e.g. /something/app/blah.apk => /something 6342 try { 6343 File f = codePath.getCanonicalFile(); 6344 File parent = f.getParentFile(); // non-null because codePath is a file 6345 File tmp; 6346 while ((tmp = parent.getParentFile()) != null) { 6347 f = parent; 6348 parent = tmp; 6349 } 6350 codeRoot = f; 6351 Slog.w(TAG, "Unrecognized code path " 6352 + codePath + " - using " + codeRoot); 6353 } catch (IOException e) { 6354 // Can't canonicalize the code path -- shenanigans? 6355 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6356 return Environment.getRootDirectory().getPath(); 6357 } 6358 } 6359 return codeRoot.getPath(); 6360 } 6361 6362 /** 6363 * Derive and set the location of native libraries for the given package, 6364 * which varies depending on where and how the package was installed. 6365 */ 6366 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6367 final ApplicationInfo info = pkg.applicationInfo; 6368 final String codePath = pkg.codePath; 6369 final File codeFile = new File(codePath); 6370 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 6371 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6372 6373 info.nativeLibraryRootDir = null; 6374 info.nativeLibraryRootRequiresIsa = false; 6375 info.nativeLibraryDir = null; 6376 info.secondaryNativeLibraryDir = null; 6377 6378 if (isApkFile(codeFile)) { 6379 // Monolithic install 6380 if (bundledApp) { 6381 // If "/system/lib64/apkname" exists, assume that is the per-package 6382 // native library directory to use; otherwise use "/system/lib/apkname". 6383 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6384 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6385 getPrimaryInstructionSet(info)); 6386 6387 // This is a bundled system app so choose the path based on the ABI. 6388 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6389 // is just the default path. 6390 final String apkName = deriveCodePathName(codePath); 6391 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6392 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6393 apkName).getAbsolutePath(); 6394 6395 if (info.secondaryCpuAbi != null) { 6396 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6397 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6398 secondaryLibDir, apkName).getAbsolutePath(); 6399 } 6400 } else if (asecApp) { 6401 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6402 .getAbsolutePath(); 6403 } else { 6404 final String apkName = deriveCodePathName(codePath); 6405 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6406 .getAbsolutePath(); 6407 } 6408 6409 info.nativeLibraryRootRequiresIsa = false; 6410 info.nativeLibraryDir = info.nativeLibraryRootDir; 6411 } else { 6412 // Cluster install 6413 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6414 info.nativeLibraryRootRequiresIsa = true; 6415 6416 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6417 getPrimaryInstructionSet(info)).getAbsolutePath(); 6418 6419 if (info.secondaryCpuAbi != null) { 6420 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6421 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6422 } 6423 } 6424 } 6425 6426 /** 6427 * Calculate the abis and roots for a bundled app. These can uniquely 6428 * be determined from the contents of the system partition, i.e whether 6429 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6430 * of this information, and instead assume that the system was built 6431 * sensibly. 6432 */ 6433 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6434 PackageSetting pkgSetting) { 6435 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6436 6437 // If "/system/lib64/apkname" exists, assume that is the per-package 6438 // native library directory to use; otherwise use "/system/lib/apkname". 6439 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6440 setBundledAppAbi(pkg, apkRoot, apkName); 6441 // pkgSetting might be null during rescan following uninstall of updates 6442 // to a bundled app, so accommodate that possibility. The settings in 6443 // that case will be established later from the parsed package. 6444 // 6445 // If the settings aren't null, sync them up with what we've just derived. 6446 // note that apkRoot isn't stored in the package settings. 6447 if (pkgSetting != null) { 6448 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6449 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6450 } 6451 } 6452 6453 /** 6454 * Deduces the ABI of a bundled app and sets the relevant fields on the 6455 * parsed pkg object. 6456 * 6457 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6458 * under which system libraries are installed. 6459 * @param apkName the name of the installed package. 6460 */ 6461 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6462 final File codeFile = new File(pkg.codePath); 6463 6464 final boolean has64BitLibs; 6465 final boolean has32BitLibs; 6466 if (isApkFile(codeFile)) { 6467 // Monolithic install 6468 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6469 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6470 } else { 6471 // Cluster install 6472 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6473 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6474 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6475 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6476 has64BitLibs = (new File(rootDir, isa)).exists(); 6477 } else { 6478 has64BitLibs = false; 6479 } 6480 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6481 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6482 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6483 has32BitLibs = (new File(rootDir, isa)).exists(); 6484 } else { 6485 has32BitLibs = false; 6486 } 6487 } 6488 6489 if (has64BitLibs && !has32BitLibs) { 6490 // The package has 64 bit libs, but not 32 bit libs. Its primary 6491 // ABI should be 64 bit. We can safely assume here that the bundled 6492 // native libraries correspond to the most preferred ABI in the list. 6493 6494 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6495 pkg.applicationInfo.secondaryCpuAbi = null; 6496 } else if (has32BitLibs && !has64BitLibs) { 6497 // The package has 32 bit libs but not 64 bit libs. Its primary 6498 // ABI should be 32 bit. 6499 6500 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6501 pkg.applicationInfo.secondaryCpuAbi = null; 6502 } else if (has32BitLibs && has64BitLibs) { 6503 // The application has both 64 and 32 bit bundled libraries. We check 6504 // here that the app declares multiArch support, and warn if it doesn't. 6505 // 6506 // We will be lenient here and record both ABIs. The primary will be the 6507 // ABI that's higher on the list, i.e, a device that's configured to prefer 6508 // 64 bit apps will see a 64 bit primary ABI, 6509 6510 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6511 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6512 } 6513 6514 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6515 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6516 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6517 } else { 6518 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6519 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6520 } 6521 } else { 6522 pkg.applicationInfo.primaryCpuAbi = null; 6523 pkg.applicationInfo.secondaryCpuAbi = null; 6524 } 6525 } 6526 6527 private void killApplication(String pkgName, int appId, String reason) { 6528 // Request the ActivityManager to kill the process(only for existing packages) 6529 // so that we do not end up in a confused state while the user is still using the older 6530 // version of the application while the new one gets installed. 6531 IActivityManager am = ActivityManagerNative.getDefault(); 6532 if (am != null) { 6533 try { 6534 am.killApplicationWithAppId(pkgName, appId, reason); 6535 } catch (RemoteException e) { 6536 } 6537 } 6538 } 6539 6540 void removePackageLI(PackageSetting ps, boolean chatty) { 6541 if (DEBUG_INSTALL) { 6542 if (chatty) 6543 Log.d(TAG, "Removing package " + ps.name); 6544 } 6545 6546 // writer 6547 synchronized (mPackages) { 6548 mPackages.remove(ps.name); 6549 final PackageParser.Package pkg = ps.pkg; 6550 if (pkg != null) { 6551 cleanPackageDataStructuresLILPw(pkg, chatty); 6552 } 6553 } 6554 } 6555 6556 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6557 if (DEBUG_INSTALL) { 6558 if (chatty) 6559 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6560 } 6561 6562 // writer 6563 synchronized (mPackages) { 6564 mPackages.remove(pkg.applicationInfo.packageName); 6565 cleanPackageDataStructuresLILPw(pkg, chatty); 6566 } 6567 } 6568 6569 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6570 int N = pkg.providers.size(); 6571 StringBuilder r = null; 6572 int i; 6573 for (i=0; i<N; i++) { 6574 PackageParser.Provider p = pkg.providers.get(i); 6575 mProviders.removeProvider(p); 6576 if (p.info.authority == null) { 6577 6578 /* There was another ContentProvider with this authority when 6579 * this app was installed so this authority is null, 6580 * Ignore it as we don't have to unregister the provider. 6581 */ 6582 continue; 6583 } 6584 String names[] = p.info.authority.split(";"); 6585 for (int j = 0; j < names.length; j++) { 6586 if (mProvidersByAuthority.get(names[j]) == p) { 6587 mProvidersByAuthority.remove(names[j]); 6588 if (DEBUG_REMOVE) { 6589 if (chatty) 6590 Log.d(TAG, "Unregistered content provider: " + names[j] 6591 + ", className = " + p.info.name + ", isSyncable = " 6592 + p.info.isSyncable); 6593 } 6594 } 6595 } 6596 if (DEBUG_REMOVE && chatty) { 6597 if (r == null) { 6598 r = new StringBuilder(256); 6599 } else { 6600 r.append(' '); 6601 } 6602 r.append(p.info.name); 6603 } 6604 } 6605 if (r != null) { 6606 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6607 } 6608 6609 N = pkg.services.size(); 6610 r = null; 6611 for (i=0; i<N; i++) { 6612 PackageParser.Service s = pkg.services.get(i); 6613 mServices.removeService(s); 6614 if (chatty) { 6615 if (r == null) { 6616 r = new StringBuilder(256); 6617 } else { 6618 r.append(' '); 6619 } 6620 r.append(s.info.name); 6621 } 6622 } 6623 if (r != null) { 6624 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6625 } 6626 6627 N = pkg.receivers.size(); 6628 r = null; 6629 for (i=0; i<N; i++) { 6630 PackageParser.Activity a = pkg.receivers.get(i); 6631 mReceivers.removeActivity(a, "receiver"); 6632 if (DEBUG_REMOVE && chatty) { 6633 if (r == null) { 6634 r = new StringBuilder(256); 6635 } else { 6636 r.append(' '); 6637 } 6638 r.append(a.info.name); 6639 } 6640 } 6641 if (r != null) { 6642 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6643 } 6644 6645 N = pkg.activities.size(); 6646 r = null; 6647 for (i=0; i<N; i++) { 6648 PackageParser.Activity a = pkg.activities.get(i); 6649 mActivities.removeActivity(a, "activity"); 6650 if (DEBUG_REMOVE && chatty) { 6651 if (r == null) { 6652 r = new StringBuilder(256); 6653 } else { 6654 r.append(' '); 6655 } 6656 r.append(a.info.name); 6657 } 6658 } 6659 if (r != null) { 6660 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6661 } 6662 6663 N = pkg.permissions.size(); 6664 r = null; 6665 for (i=0; i<N; i++) { 6666 PackageParser.Permission p = pkg.permissions.get(i); 6667 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6668 if (bp == null) { 6669 bp = mSettings.mPermissionTrees.get(p.info.name); 6670 } 6671 if (bp != null && bp.perm == p) { 6672 bp.perm = null; 6673 if (DEBUG_REMOVE && chatty) { 6674 if (r == null) { 6675 r = new StringBuilder(256); 6676 } else { 6677 r.append(' '); 6678 } 6679 r.append(p.info.name); 6680 } 6681 } 6682 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6683 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6684 if (appOpPerms != null) { 6685 appOpPerms.remove(pkg.packageName); 6686 } 6687 } 6688 } 6689 if (r != null) { 6690 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6691 } 6692 6693 N = pkg.requestedPermissions.size(); 6694 r = null; 6695 for (i=0; i<N; i++) { 6696 String perm = pkg.requestedPermissions.get(i); 6697 BasePermission bp = mSettings.mPermissions.get(perm); 6698 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6699 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6700 if (appOpPerms != null) { 6701 appOpPerms.remove(pkg.packageName); 6702 if (appOpPerms.isEmpty()) { 6703 mAppOpPermissionPackages.remove(perm); 6704 } 6705 } 6706 } 6707 } 6708 if (r != null) { 6709 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6710 } 6711 6712 N = pkg.instrumentation.size(); 6713 r = null; 6714 for (i=0; i<N; i++) { 6715 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6716 mInstrumentation.remove(a.getComponentName()); 6717 if (DEBUG_REMOVE && chatty) { 6718 if (r == null) { 6719 r = new StringBuilder(256); 6720 } else { 6721 r.append(' '); 6722 } 6723 r.append(a.info.name); 6724 } 6725 } 6726 if (r != null) { 6727 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6728 } 6729 6730 r = null; 6731 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6732 // Only system apps can hold shared libraries. 6733 if (pkg.libraryNames != null) { 6734 for (i=0; i<pkg.libraryNames.size(); i++) { 6735 String name = pkg.libraryNames.get(i); 6736 SharedLibraryEntry cur = mSharedLibraries.get(name); 6737 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6738 mSharedLibraries.remove(name); 6739 if (DEBUG_REMOVE && chatty) { 6740 if (r == null) { 6741 r = new StringBuilder(256); 6742 } else { 6743 r.append(' '); 6744 } 6745 r.append(name); 6746 } 6747 } 6748 } 6749 } 6750 } 6751 if (r != null) { 6752 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6753 } 6754 } 6755 6756 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6757 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6758 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6759 return true; 6760 } 6761 } 6762 return false; 6763 } 6764 6765 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6766 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6767 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6768 6769 private void updatePermissionsLPw(String changingPkg, 6770 PackageParser.Package pkgInfo, int flags) { 6771 // Make sure there are no dangling permission trees. 6772 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6773 while (it.hasNext()) { 6774 final BasePermission bp = it.next(); 6775 if (bp.packageSetting == null) { 6776 // We may not yet have parsed the package, so just see if 6777 // we still know about its settings. 6778 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6779 } 6780 if (bp.packageSetting == null) { 6781 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6782 + " from package " + bp.sourcePackage); 6783 it.remove(); 6784 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6785 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6786 Slog.i(TAG, "Removing old permission tree: " + bp.name 6787 + " from package " + bp.sourcePackage); 6788 flags |= UPDATE_PERMISSIONS_ALL; 6789 it.remove(); 6790 } 6791 } 6792 } 6793 6794 // Make sure all dynamic permissions have been assigned to a package, 6795 // and make sure there are no dangling permissions. 6796 it = mSettings.mPermissions.values().iterator(); 6797 while (it.hasNext()) { 6798 final BasePermission bp = it.next(); 6799 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6800 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6801 + bp.name + " pkg=" + bp.sourcePackage 6802 + " info=" + bp.pendingInfo); 6803 if (bp.packageSetting == null && bp.pendingInfo != null) { 6804 final BasePermission tree = findPermissionTreeLP(bp.name); 6805 if (tree != null && tree.perm != null) { 6806 bp.packageSetting = tree.packageSetting; 6807 bp.perm = new PackageParser.Permission(tree.perm.owner, 6808 new PermissionInfo(bp.pendingInfo)); 6809 bp.perm.info.packageName = tree.perm.info.packageName; 6810 bp.perm.info.name = bp.name; 6811 bp.uid = tree.uid; 6812 } 6813 } 6814 } 6815 if (bp.packageSetting == null) { 6816 // We may not yet have parsed the package, so just see if 6817 // we still know about its settings. 6818 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6819 } 6820 if (bp.packageSetting == null) { 6821 Slog.w(TAG, "Removing dangling permission: " + bp.name 6822 + " from package " + bp.sourcePackage); 6823 it.remove(); 6824 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6825 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6826 Slog.i(TAG, "Removing old permission: " + bp.name 6827 + " from package " + bp.sourcePackage); 6828 flags |= UPDATE_PERMISSIONS_ALL; 6829 it.remove(); 6830 } 6831 } 6832 } 6833 6834 // Now update the permissions for all packages, in particular 6835 // replace the granted permissions of the system packages. 6836 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6837 for (PackageParser.Package pkg : mPackages.values()) { 6838 if (pkg != pkgInfo) { 6839 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6840 changingPkg); 6841 } 6842 } 6843 } 6844 6845 if (pkgInfo != null) { 6846 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6847 } 6848 } 6849 6850 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6851 String packageOfInterest) { 6852 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6853 if (ps == null) { 6854 return; 6855 } 6856 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6857 ArraySet<String> origPermissions = gp.grantedPermissions; 6858 boolean changedPermission = false; 6859 6860 if (replace) { 6861 ps.permissionsFixed = false; 6862 if (gp == ps) { 6863 origPermissions = new ArraySet<String>(gp.grantedPermissions); 6864 gp.grantedPermissions.clear(); 6865 gp.gids = mGlobalGids; 6866 } 6867 } 6868 6869 if (gp.gids == null) { 6870 gp.gids = mGlobalGids; 6871 } 6872 6873 final int N = pkg.requestedPermissions.size(); 6874 for (int i=0; i<N; i++) { 6875 final String name = pkg.requestedPermissions.get(i); 6876 final boolean required = pkg.requestedPermissionsRequired.get(i); 6877 final BasePermission bp = mSettings.mPermissions.get(name); 6878 if (DEBUG_INSTALL) { 6879 if (gp != ps) { 6880 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6881 } 6882 } 6883 6884 if (bp == null || bp.packageSetting == null) { 6885 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6886 Slog.w(TAG, "Unknown permission " + name 6887 + " in package " + pkg.packageName); 6888 } 6889 continue; 6890 } 6891 6892 final String perm = bp.name; 6893 boolean allowed; 6894 boolean allowedSig = false; 6895 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6896 // Keep track of app op permissions. 6897 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6898 if (pkgs == null) { 6899 pkgs = new ArraySet<>(); 6900 mAppOpPermissionPackages.put(bp.name, pkgs); 6901 } 6902 pkgs.add(pkg.packageName); 6903 } 6904 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6905 if (level == PermissionInfo.PROTECTION_NORMAL 6906 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6907 // We grant a normal or dangerous permission if any of the following 6908 // are true: 6909 // 1) The permission is required 6910 // 2) The permission is optional, but was granted in the past 6911 // 3) The permission is optional, but was requested by an 6912 // app in /system (not /data) 6913 // 6914 // Otherwise, reject the permission. 6915 allowed = (required || origPermissions.contains(perm) 6916 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6917 } else if (bp.packageSetting == null) { 6918 // This permission is invalid; skip it. 6919 allowed = false; 6920 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6921 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6922 if (allowed) { 6923 allowedSig = true; 6924 } 6925 } else { 6926 allowed = false; 6927 } 6928 if (DEBUG_INSTALL) { 6929 if (gp != ps) { 6930 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6931 } 6932 } 6933 if (allowed) { 6934 if (!isSystemApp(ps) && ps.permissionsFixed) { 6935 // If this is an existing, non-system package, then 6936 // we can't add any new permissions to it. 6937 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6938 // Except... if this is a permission that was added 6939 // to the platform (note: need to only do this when 6940 // updating the platform). 6941 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6942 } 6943 } 6944 if (allowed) { 6945 if (!gp.grantedPermissions.contains(perm)) { 6946 changedPermission = true; 6947 gp.grantedPermissions.add(perm); 6948 gp.gids = appendInts(gp.gids, bp.gids); 6949 } else if (!ps.haveGids) { 6950 gp.gids = appendInts(gp.gids, bp.gids); 6951 } 6952 } else { 6953 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6954 Slog.w(TAG, "Not granting permission " + perm 6955 + " to package " + pkg.packageName 6956 + " because it was previously installed without"); 6957 } 6958 } 6959 } else { 6960 if (gp.grantedPermissions.remove(perm)) { 6961 changedPermission = true; 6962 gp.gids = removeInts(gp.gids, bp.gids); 6963 Slog.i(TAG, "Un-granting permission " + perm 6964 + " from package " + pkg.packageName 6965 + " (protectionLevel=" + bp.protectionLevel 6966 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6967 + ")"); 6968 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6969 // Don't print warning for app op permissions, since it is fine for them 6970 // not to be granted, there is a UI for the user to decide. 6971 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6972 Slog.w(TAG, "Not granting permission " + perm 6973 + " to package " + pkg.packageName 6974 + " (protectionLevel=" + bp.protectionLevel 6975 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6976 + ")"); 6977 } 6978 } 6979 } 6980 } 6981 6982 if ((changedPermission || replace) && !ps.permissionsFixed && 6983 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6984 // This is the first that we have heard about this package, so the 6985 // permissions we have now selected are fixed until explicitly 6986 // changed. 6987 ps.permissionsFixed = true; 6988 } 6989 ps.haveGids = true; 6990 } 6991 6992 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6993 boolean allowed = false; 6994 final int NP = PackageParser.NEW_PERMISSIONS.length; 6995 for (int ip=0; ip<NP; ip++) { 6996 final PackageParser.NewPermissionInfo npi 6997 = PackageParser.NEW_PERMISSIONS[ip]; 6998 if (npi.name.equals(perm) 6999 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7000 allowed = true; 7001 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7002 + pkg.packageName); 7003 break; 7004 } 7005 } 7006 return allowed; 7007 } 7008 7009 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7010 BasePermission bp, ArraySet<String> origPermissions) { 7011 boolean allowed; 7012 allowed = (compareSignatures( 7013 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7014 == PackageManager.SIGNATURE_MATCH) 7015 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7016 == PackageManager.SIGNATURE_MATCH); 7017 if (!allowed && (bp.protectionLevel 7018 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7019 if (isSystemApp(pkg)) { 7020 // For updated system applications, a system permission 7021 // is granted only if it had been defined by the original application. 7022 if (pkg.isUpdatedSystemApp()) { 7023 final PackageSetting sysPs = mSettings 7024 .getDisabledSystemPkgLPr(pkg.packageName); 7025 final GrantedPermissions origGp = sysPs.sharedUser != null 7026 ? sysPs.sharedUser : sysPs; 7027 7028 if (origGp.grantedPermissions.contains(perm)) { 7029 // If the original was granted this permission, we take 7030 // that grant decision as read and propagate it to the 7031 // update. 7032 if (sysPs.isPrivileged()) { 7033 allowed = true; 7034 } 7035 } else { 7036 // The system apk may have been updated with an older 7037 // version of the one on the data partition, but which 7038 // granted a new system permission that it didn't have 7039 // before. In this case we do want to allow the app to 7040 // now get the new permission if the ancestral apk is 7041 // privileged to get it. 7042 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7043 for (int j=0; 7044 j<sysPs.pkg.requestedPermissions.size(); j++) { 7045 if (perm.equals( 7046 sysPs.pkg.requestedPermissions.get(j))) { 7047 allowed = true; 7048 break; 7049 } 7050 } 7051 } 7052 } 7053 } else { 7054 allowed = isPrivilegedApp(pkg); 7055 } 7056 } 7057 } 7058 if (!allowed && (bp.protectionLevel 7059 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7060 // For development permissions, a development permission 7061 // is granted only if it was already granted. 7062 allowed = origPermissions.contains(perm); 7063 } 7064 return allowed; 7065 } 7066 7067 final class ActivityIntentResolver 7068 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7069 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7070 boolean defaultOnly, int userId) { 7071 if (!sUserManager.exists(userId)) return null; 7072 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7073 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7074 } 7075 7076 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7077 int userId) { 7078 if (!sUserManager.exists(userId)) return null; 7079 mFlags = flags; 7080 return super.queryIntent(intent, resolvedType, 7081 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7082 } 7083 7084 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7085 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7086 if (!sUserManager.exists(userId)) return null; 7087 if (packageActivities == null) { 7088 return null; 7089 } 7090 mFlags = flags; 7091 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7092 final int N = packageActivities.size(); 7093 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7094 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7095 7096 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7097 for (int i = 0; i < N; ++i) { 7098 intentFilters = packageActivities.get(i).intents; 7099 if (intentFilters != null && intentFilters.size() > 0) { 7100 PackageParser.ActivityIntentInfo[] array = 7101 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7102 intentFilters.toArray(array); 7103 listCut.add(array); 7104 } 7105 } 7106 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7107 } 7108 7109 public final void addActivity(PackageParser.Activity a, String type) { 7110 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7111 mActivities.put(a.getComponentName(), a); 7112 if (DEBUG_SHOW_INFO) 7113 Log.v( 7114 TAG, " " + type + " " + 7115 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7116 if (DEBUG_SHOW_INFO) 7117 Log.v(TAG, " Class=" + a.info.name); 7118 final int NI = a.intents.size(); 7119 for (int j=0; j<NI; j++) { 7120 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7121 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7122 intent.setPriority(0); 7123 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7124 + a.className + " with priority > 0, forcing to 0"); 7125 } 7126 if (DEBUG_SHOW_INFO) { 7127 Log.v(TAG, " IntentFilter:"); 7128 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7129 } 7130 if (!intent.debugCheck()) { 7131 Log.w(TAG, "==> For Activity " + a.info.name); 7132 } 7133 addFilter(intent); 7134 } 7135 } 7136 7137 public final void removeActivity(PackageParser.Activity a, String type) { 7138 mActivities.remove(a.getComponentName()); 7139 if (DEBUG_SHOW_INFO) { 7140 Log.v(TAG, " " + type + " " 7141 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7142 : a.info.name) + ":"); 7143 Log.v(TAG, " Class=" + a.info.name); 7144 } 7145 final int NI = a.intents.size(); 7146 for (int j=0; j<NI; j++) { 7147 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7148 if (DEBUG_SHOW_INFO) { 7149 Log.v(TAG, " IntentFilter:"); 7150 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7151 } 7152 removeFilter(intent); 7153 } 7154 } 7155 7156 @Override 7157 protected boolean allowFilterResult( 7158 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7159 ActivityInfo filterAi = filter.activity.info; 7160 for (int i=dest.size()-1; i>=0; i--) { 7161 ActivityInfo destAi = dest.get(i).activityInfo; 7162 if (destAi.name == filterAi.name 7163 && destAi.packageName == filterAi.packageName) { 7164 return false; 7165 } 7166 } 7167 return true; 7168 } 7169 7170 @Override 7171 protected ActivityIntentInfo[] newArray(int size) { 7172 return new ActivityIntentInfo[size]; 7173 } 7174 7175 @Override 7176 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7177 if (!sUserManager.exists(userId)) return true; 7178 PackageParser.Package p = filter.activity.owner; 7179 if (p != null) { 7180 PackageSetting ps = (PackageSetting)p.mExtras; 7181 if (ps != null) { 7182 // System apps are never considered stopped for purposes of 7183 // filtering, because there may be no way for the user to 7184 // actually re-launch them. 7185 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7186 && ps.getStopped(userId); 7187 } 7188 } 7189 return false; 7190 } 7191 7192 @Override 7193 protected boolean isPackageForFilter(String packageName, 7194 PackageParser.ActivityIntentInfo info) { 7195 return packageName.equals(info.activity.owner.packageName); 7196 } 7197 7198 @Override 7199 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7200 int match, int userId) { 7201 if (!sUserManager.exists(userId)) return null; 7202 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7203 return null; 7204 } 7205 final PackageParser.Activity activity = info.activity; 7206 if (mSafeMode && (activity.info.applicationInfo.flags 7207 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7208 return null; 7209 } 7210 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7211 if (ps == null) { 7212 return null; 7213 } 7214 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7215 ps.readUserState(userId), userId); 7216 if (ai == null) { 7217 return null; 7218 } 7219 final ResolveInfo res = new ResolveInfo(); 7220 res.activityInfo = ai; 7221 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7222 res.filter = info; 7223 } 7224 res.priority = info.getPriority(); 7225 res.preferredOrder = activity.owner.mPreferredOrder; 7226 //System.out.println("Result: " + res.activityInfo.className + 7227 // " = " + res.priority); 7228 res.match = match; 7229 res.isDefault = info.hasDefault; 7230 res.labelRes = info.labelRes; 7231 res.nonLocalizedLabel = info.nonLocalizedLabel; 7232 if (userNeedsBadging(userId)) { 7233 res.noResourceId = true; 7234 } else { 7235 res.icon = info.icon; 7236 } 7237 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7238 return res; 7239 } 7240 7241 @Override 7242 protected void sortResults(List<ResolveInfo> results) { 7243 Collections.sort(results, mResolvePrioritySorter); 7244 } 7245 7246 @Override 7247 protected void dumpFilter(PrintWriter out, String prefix, 7248 PackageParser.ActivityIntentInfo filter) { 7249 out.print(prefix); out.print( 7250 Integer.toHexString(System.identityHashCode(filter.activity))); 7251 out.print(' '); 7252 filter.activity.printComponentShortName(out); 7253 out.print(" filter "); 7254 out.println(Integer.toHexString(System.identityHashCode(filter))); 7255 } 7256 7257 @Override 7258 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7259 return filter.activity; 7260 } 7261 7262 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7263 PackageParser.Activity activity = (PackageParser.Activity)label; 7264 out.print(prefix); out.print( 7265 Integer.toHexString(System.identityHashCode(activity))); 7266 out.print(' '); 7267 activity.printComponentShortName(out); 7268 if (count > 1) { 7269 out.print(" ("); out.print(count); out.print(" filters)"); 7270 } 7271 out.println(); 7272 } 7273 7274// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7275// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7276// final List<ResolveInfo> retList = Lists.newArrayList(); 7277// while (i.hasNext()) { 7278// final ResolveInfo resolveInfo = i.next(); 7279// if (isEnabledLP(resolveInfo.activityInfo)) { 7280// retList.add(resolveInfo); 7281// } 7282// } 7283// return retList; 7284// } 7285 7286 // Keys are String (activity class name), values are Activity. 7287 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7288 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7289 private int mFlags; 7290 } 7291 7292 private final class ServiceIntentResolver 7293 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7294 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7295 boolean defaultOnly, int userId) { 7296 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7297 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7298 } 7299 7300 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7301 int userId) { 7302 if (!sUserManager.exists(userId)) return null; 7303 mFlags = flags; 7304 return super.queryIntent(intent, resolvedType, 7305 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7306 } 7307 7308 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7309 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7310 if (!sUserManager.exists(userId)) return null; 7311 if (packageServices == null) { 7312 return null; 7313 } 7314 mFlags = flags; 7315 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7316 final int N = packageServices.size(); 7317 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7318 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7319 7320 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7321 for (int i = 0; i < N; ++i) { 7322 intentFilters = packageServices.get(i).intents; 7323 if (intentFilters != null && intentFilters.size() > 0) { 7324 PackageParser.ServiceIntentInfo[] array = 7325 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7326 intentFilters.toArray(array); 7327 listCut.add(array); 7328 } 7329 } 7330 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7331 } 7332 7333 public final void addService(PackageParser.Service s) { 7334 mServices.put(s.getComponentName(), s); 7335 if (DEBUG_SHOW_INFO) { 7336 Log.v(TAG, " " 7337 + (s.info.nonLocalizedLabel != null 7338 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7339 Log.v(TAG, " Class=" + s.info.name); 7340 } 7341 final int NI = s.intents.size(); 7342 int j; 7343 for (j=0; j<NI; j++) { 7344 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7345 if (DEBUG_SHOW_INFO) { 7346 Log.v(TAG, " IntentFilter:"); 7347 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7348 } 7349 if (!intent.debugCheck()) { 7350 Log.w(TAG, "==> For Service " + s.info.name); 7351 } 7352 addFilter(intent); 7353 } 7354 } 7355 7356 public final void removeService(PackageParser.Service s) { 7357 mServices.remove(s.getComponentName()); 7358 if (DEBUG_SHOW_INFO) { 7359 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7360 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7361 Log.v(TAG, " Class=" + s.info.name); 7362 } 7363 final int NI = s.intents.size(); 7364 int j; 7365 for (j=0; j<NI; j++) { 7366 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7367 if (DEBUG_SHOW_INFO) { 7368 Log.v(TAG, " IntentFilter:"); 7369 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7370 } 7371 removeFilter(intent); 7372 } 7373 } 7374 7375 @Override 7376 protected boolean allowFilterResult( 7377 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7378 ServiceInfo filterSi = filter.service.info; 7379 for (int i=dest.size()-1; i>=0; i--) { 7380 ServiceInfo destAi = dest.get(i).serviceInfo; 7381 if (destAi.name == filterSi.name 7382 && destAi.packageName == filterSi.packageName) { 7383 return false; 7384 } 7385 } 7386 return true; 7387 } 7388 7389 @Override 7390 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7391 return new PackageParser.ServiceIntentInfo[size]; 7392 } 7393 7394 @Override 7395 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7396 if (!sUserManager.exists(userId)) return true; 7397 PackageParser.Package p = filter.service.owner; 7398 if (p != null) { 7399 PackageSetting ps = (PackageSetting)p.mExtras; 7400 if (ps != null) { 7401 // System apps are never considered stopped for purposes of 7402 // filtering, because there may be no way for the user to 7403 // actually re-launch them. 7404 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7405 && ps.getStopped(userId); 7406 } 7407 } 7408 return false; 7409 } 7410 7411 @Override 7412 protected boolean isPackageForFilter(String packageName, 7413 PackageParser.ServiceIntentInfo info) { 7414 return packageName.equals(info.service.owner.packageName); 7415 } 7416 7417 @Override 7418 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7419 int match, int userId) { 7420 if (!sUserManager.exists(userId)) return null; 7421 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7422 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7423 return null; 7424 } 7425 final PackageParser.Service service = info.service; 7426 if (mSafeMode && (service.info.applicationInfo.flags 7427 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7428 return null; 7429 } 7430 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7431 if (ps == null) { 7432 return null; 7433 } 7434 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7435 ps.readUserState(userId), userId); 7436 if (si == null) { 7437 return null; 7438 } 7439 final ResolveInfo res = new ResolveInfo(); 7440 res.serviceInfo = si; 7441 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7442 res.filter = filter; 7443 } 7444 res.priority = info.getPriority(); 7445 res.preferredOrder = service.owner.mPreferredOrder; 7446 //System.out.println("Result: " + res.activityInfo.className + 7447 // " = " + res.priority); 7448 res.match = match; 7449 res.isDefault = info.hasDefault; 7450 res.labelRes = info.labelRes; 7451 res.nonLocalizedLabel = info.nonLocalizedLabel; 7452 res.icon = info.icon; 7453 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 7454 return res; 7455 } 7456 7457 @Override 7458 protected void sortResults(List<ResolveInfo> results) { 7459 Collections.sort(results, mResolvePrioritySorter); 7460 } 7461 7462 @Override 7463 protected void dumpFilter(PrintWriter out, String prefix, 7464 PackageParser.ServiceIntentInfo filter) { 7465 out.print(prefix); out.print( 7466 Integer.toHexString(System.identityHashCode(filter.service))); 7467 out.print(' '); 7468 filter.service.printComponentShortName(out); 7469 out.print(" filter "); 7470 out.println(Integer.toHexString(System.identityHashCode(filter))); 7471 } 7472 7473 @Override 7474 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 7475 return filter.service; 7476 } 7477 7478 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7479 PackageParser.Service service = (PackageParser.Service)label; 7480 out.print(prefix); out.print( 7481 Integer.toHexString(System.identityHashCode(service))); 7482 out.print(' '); 7483 service.printComponentShortName(out); 7484 if (count > 1) { 7485 out.print(" ("); out.print(count); out.print(" filters)"); 7486 } 7487 out.println(); 7488 } 7489 7490// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7491// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7492// final List<ResolveInfo> retList = Lists.newArrayList(); 7493// while (i.hasNext()) { 7494// final ResolveInfo resolveInfo = (ResolveInfo) i; 7495// if (isEnabledLP(resolveInfo.serviceInfo)) { 7496// retList.add(resolveInfo); 7497// } 7498// } 7499// return retList; 7500// } 7501 7502 // Keys are String (activity class name), values are Activity. 7503 private final ArrayMap<ComponentName, PackageParser.Service> mServices 7504 = new ArrayMap<ComponentName, PackageParser.Service>(); 7505 private int mFlags; 7506 }; 7507 7508 private final class ProviderIntentResolver 7509 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7510 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7511 boolean defaultOnly, int userId) { 7512 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7513 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7514 } 7515 7516 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7517 int userId) { 7518 if (!sUserManager.exists(userId)) 7519 return null; 7520 mFlags = flags; 7521 return super.queryIntent(intent, resolvedType, 7522 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7523 } 7524 7525 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7526 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7527 if (!sUserManager.exists(userId)) 7528 return null; 7529 if (packageProviders == null) { 7530 return null; 7531 } 7532 mFlags = flags; 7533 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7534 final int N = packageProviders.size(); 7535 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7536 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7537 7538 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7539 for (int i = 0; i < N; ++i) { 7540 intentFilters = packageProviders.get(i).intents; 7541 if (intentFilters != null && intentFilters.size() > 0) { 7542 PackageParser.ProviderIntentInfo[] array = 7543 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7544 intentFilters.toArray(array); 7545 listCut.add(array); 7546 } 7547 } 7548 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7549 } 7550 7551 public final void addProvider(PackageParser.Provider p) { 7552 if (mProviders.containsKey(p.getComponentName())) { 7553 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7554 return; 7555 } 7556 7557 mProviders.put(p.getComponentName(), p); 7558 if (DEBUG_SHOW_INFO) { 7559 Log.v(TAG, " " 7560 + (p.info.nonLocalizedLabel != null 7561 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7562 Log.v(TAG, " Class=" + p.info.name); 7563 } 7564 final int NI = p.intents.size(); 7565 int j; 7566 for (j = 0; j < NI; j++) { 7567 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7568 if (DEBUG_SHOW_INFO) { 7569 Log.v(TAG, " IntentFilter:"); 7570 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7571 } 7572 if (!intent.debugCheck()) { 7573 Log.w(TAG, "==> For Provider " + p.info.name); 7574 } 7575 addFilter(intent); 7576 } 7577 } 7578 7579 public final void removeProvider(PackageParser.Provider p) { 7580 mProviders.remove(p.getComponentName()); 7581 if (DEBUG_SHOW_INFO) { 7582 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7583 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7584 Log.v(TAG, " Class=" + p.info.name); 7585 } 7586 final int NI = p.intents.size(); 7587 int j; 7588 for (j = 0; j < NI; j++) { 7589 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7590 if (DEBUG_SHOW_INFO) { 7591 Log.v(TAG, " IntentFilter:"); 7592 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7593 } 7594 removeFilter(intent); 7595 } 7596 } 7597 7598 @Override 7599 protected boolean allowFilterResult( 7600 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7601 ProviderInfo filterPi = filter.provider.info; 7602 for (int i = dest.size() - 1; i >= 0; i--) { 7603 ProviderInfo destPi = dest.get(i).providerInfo; 7604 if (destPi.name == filterPi.name 7605 && destPi.packageName == filterPi.packageName) { 7606 return false; 7607 } 7608 } 7609 return true; 7610 } 7611 7612 @Override 7613 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7614 return new PackageParser.ProviderIntentInfo[size]; 7615 } 7616 7617 @Override 7618 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7619 if (!sUserManager.exists(userId)) 7620 return true; 7621 PackageParser.Package p = filter.provider.owner; 7622 if (p != null) { 7623 PackageSetting ps = (PackageSetting) p.mExtras; 7624 if (ps != null) { 7625 // System apps are never considered stopped for purposes of 7626 // filtering, because there may be no way for the user to 7627 // actually re-launch them. 7628 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7629 && ps.getStopped(userId); 7630 } 7631 } 7632 return false; 7633 } 7634 7635 @Override 7636 protected boolean isPackageForFilter(String packageName, 7637 PackageParser.ProviderIntentInfo info) { 7638 return packageName.equals(info.provider.owner.packageName); 7639 } 7640 7641 @Override 7642 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7643 int match, int userId) { 7644 if (!sUserManager.exists(userId)) 7645 return null; 7646 final PackageParser.ProviderIntentInfo info = filter; 7647 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7648 return null; 7649 } 7650 final PackageParser.Provider provider = info.provider; 7651 if (mSafeMode && (provider.info.applicationInfo.flags 7652 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7653 return null; 7654 } 7655 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7656 if (ps == null) { 7657 return null; 7658 } 7659 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7660 ps.readUserState(userId), userId); 7661 if (pi == null) { 7662 return null; 7663 } 7664 final ResolveInfo res = new ResolveInfo(); 7665 res.providerInfo = pi; 7666 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7667 res.filter = filter; 7668 } 7669 res.priority = info.getPriority(); 7670 res.preferredOrder = provider.owner.mPreferredOrder; 7671 res.match = match; 7672 res.isDefault = info.hasDefault; 7673 res.labelRes = info.labelRes; 7674 res.nonLocalizedLabel = info.nonLocalizedLabel; 7675 res.icon = info.icon; 7676 res.system = res.providerInfo.applicationInfo.isSystemApp(); 7677 return res; 7678 } 7679 7680 @Override 7681 protected void sortResults(List<ResolveInfo> results) { 7682 Collections.sort(results, mResolvePrioritySorter); 7683 } 7684 7685 @Override 7686 protected void dumpFilter(PrintWriter out, String prefix, 7687 PackageParser.ProviderIntentInfo filter) { 7688 out.print(prefix); 7689 out.print( 7690 Integer.toHexString(System.identityHashCode(filter.provider))); 7691 out.print(' '); 7692 filter.provider.printComponentShortName(out); 7693 out.print(" filter "); 7694 out.println(Integer.toHexString(System.identityHashCode(filter))); 7695 } 7696 7697 @Override 7698 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 7699 return filter.provider; 7700 } 7701 7702 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7703 PackageParser.Provider provider = (PackageParser.Provider)label; 7704 out.print(prefix); out.print( 7705 Integer.toHexString(System.identityHashCode(provider))); 7706 out.print(' '); 7707 provider.printComponentShortName(out); 7708 if (count > 1) { 7709 out.print(" ("); out.print(count); out.print(" filters)"); 7710 } 7711 out.println(); 7712 } 7713 7714 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 7715 = new ArrayMap<ComponentName, PackageParser.Provider>(); 7716 private int mFlags; 7717 }; 7718 7719 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7720 new Comparator<ResolveInfo>() { 7721 public int compare(ResolveInfo r1, ResolveInfo r2) { 7722 int v1 = r1.priority; 7723 int v2 = r2.priority; 7724 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7725 if (v1 != v2) { 7726 return (v1 > v2) ? -1 : 1; 7727 } 7728 v1 = r1.preferredOrder; 7729 v2 = r2.preferredOrder; 7730 if (v1 != v2) { 7731 return (v1 > v2) ? -1 : 1; 7732 } 7733 if (r1.isDefault != r2.isDefault) { 7734 return r1.isDefault ? -1 : 1; 7735 } 7736 v1 = r1.match; 7737 v2 = r2.match; 7738 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7739 if (v1 != v2) { 7740 return (v1 > v2) ? -1 : 1; 7741 } 7742 if (r1.system != r2.system) { 7743 return r1.system ? -1 : 1; 7744 } 7745 return 0; 7746 } 7747 }; 7748 7749 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7750 new Comparator<ProviderInfo>() { 7751 public int compare(ProviderInfo p1, ProviderInfo p2) { 7752 final int v1 = p1.initOrder; 7753 final int v2 = p2.initOrder; 7754 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7755 } 7756 }; 7757 7758 static final void sendPackageBroadcast(String action, String pkg, 7759 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7760 int[] userIds) { 7761 IActivityManager am = ActivityManagerNative.getDefault(); 7762 if (am != null) { 7763 try { 7764 if (userIds == null) { 7765 userIds = am.getRunningUserIds(); 7766 } 7767 for (int id : userIds) { 7768 final Intent intent = new Intent(action, 7769 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7770 if (extras != null) { 7771 intent.putExtras(extras); 7772 } 7773 if (targetPkg != null) { 7774 intent.setPackage(targetPkg); 7775 } 7776 // Modify the UID when posting to other users 7777 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7778 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7779 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7780 intent.putExtra(Intent.EXTRA_UID, uid); 7781 } 7782 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7783 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7784 if (DEBUG_BROADCASTS) { 7785 RuntimeException here = new RuntimeException("here"); 7786 here.fillInStackTrace(); 7787 Slog.d(TAG, "Sending to user " + id + ": " 7788 + intent.toShortString(false, true, false, false) 7789 + " " + intent.getExtras(), here); 7790 } 7791 am.broadcastIntent(null, intent, null, finishedReceiver, 7792 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7793 finishedReceiver != null, false, id); 7794 } 7795 } catch (RemoteException ex) { 7796 } 7797 } 7798 } 7799 7800 /** 7801 * Check if the external storage media is available. This is true if there 7802 * is a mounted external storage medium or if the external storage is 7803 * emulated. 7804 */ 7805 private boolean isExternalMediaAvailable() { 7806 return mMediaMounted || Environment.isExternalStorageEmulated(); 7807 } 7808 7809 @Override 7810 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7811 // writer 7812 synchronized (mPackages) { 7813 if (!isExternalMediaAvailable()) { 7814 // If the external storage is no longer mounted at this point, 7815 // the caller may not have been able to delete all of this 7816 // packages files and can not delete any more. Bail. 7817 return null; 7818 } 7819 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7820 if (lastPackage != null) { 7821 pkgs.remove(lastPackage); 7822 } 7823 if (pkgs.size() > 0) { 7824 return pkgs.get(0); 7825 } 7826 } 7827 return null; 7828 } 7829 7830 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7831 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7832 userId, andCode ? 1 : 0, packageName); 7833 if (mSystemReady) { 7834 msg.sendToTarget(); 7835 } else { 7836 if (mPostSystemReadyMessages == null) { 7837 mPostSystemReadyMessages = new ArrayList<>(); 7838 } 7839 mPostSystemReadyMessages.add(msg); 7840 } 7841 } 7842 7843 void startCleaningPackages() { 7844 // reader 7845 synchronized (mPackages) { 7846 if (!isExternalMediaAvailable()) { 7847 return; 7848 } 7849 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7850 return; 7851 } 7852 } 7853 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7854 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7855 IActivityManager am = ActivityManagerNative.getDefault(); 7856 if (am != null) { 7857 try { 7858 am.startService(null, intent, null, UserHandle.USER_OWNER); 7859 } catch (RemoteException e) { 7860 } 7861 } 7862 } 7863 7864 @Override 7865 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7866 int installFlags, String installerPackageName, VerificationParams verificationParams, 7867 String packageAbiOverride) { 7868 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7869 packageAbiOverride, UserHandle.getCallingUserId()); 7870 } 7871 7872 @Override 7873 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7874 int installFlags, String installerPackageName, VerificationParams verificationParams, 7875 String packageAbiOverride, int userId) { 7876 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 7877 7878 final int callingUid = Binder.getCallingUid(); 7879 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 7880 7881 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7882 try { 7883 if (observer != null) { 7884 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7885 } 7886 } catch (RemoteException re) { 7887 } 7888 return; 7889 } 7890 7891 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 7892 installFlags |= PackageManager.INSTALL_FROM_ADB; 7893 7894 } else { 7895 // Caller holds INSTALL_PACKAGES permission, so we're less strict 7896 // about installerPackageName. 7897 7898 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 7899 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 7900 } 7901 7902 UserHandle user; 7903 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7904 user = UserHandle.ALL; 7905 } else { 7906 user = new UserHandle(userId); 7907 } 7908 7909 verificationParams.setInstallerUid(callingUid); 7910 7911 final File originFile = new File(originPath); 7912 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7913 7914 final Message msg = mHandler.obtainMessage(INIT_COPY); 7915 msg.obj = new InstallParams(origin, observer, installFlags, 7916 installerPackageName, verificationParams, user, packageAbiOverride); 7917 mHandler.sendMessage(msg); 7918 } 7919 7920 void installStage(String packageName, File stagedDir, String stagedCid, 7921 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7922 String installerPackageName, int installerUid, UserHandle user) { 7923 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7924 params.referrerUri, installerUid, null); 7925 7926 final OriginInfo origin; 7927 if (stagedDir != null) { 7928 origin = OriginInfo.fromStagedFile(stagedDir); 7929 } else { 7930 origin = OriginInfo.fromStagedContainer(stagedCid); 7931 } 7932 7933 final Message msg = mHandler.obtainMessage(INIT_COPY); 7934 msg.obj = new InstallParams(origin, observer, params.installFlags, 7935 installerPackageName, verifParams, user, params.abiOverride); 7936 mHandler.sendMessage(msg); 7937 } 7938 7939 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7940 Bundle extras = new Bundle(1); 7941 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7942 7943 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7944 packageName, extras, null, null, new int[] {userId}); 7945 try { 7946 IActivityManager am = ActivityManagerNative.getDefault(); 7947 final boolean isSystem = 7948 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7949 if (isSystem && am.isUserRunning(userId, false)) { 7950 // The just-installed/enabled app is bundled on the system, so presumed 7951 // to be able to run automatically without needing an explicit launch. 7952 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7953 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7954 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7955 .setPackage(packageName); 7956 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7957 android.app.AppOpsManager.OP_NONE, false, false, userId); 7958 } 7959 } catch (RemoteException e) { 7960 // shouldn't happen 7961 Slog.w(TAG, "Unable to bootstrap installed package", e); 7962 } 7963 } 7964 7965 @Override 7966 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7967 int userId) { 7968 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7969 PackageSetting pkgSetting; 7970 final int uid = Binder.getCallingUid(); 7971 enforceCrossUserPermission(uid, userId, true, true, 7972 "setApplicationHiddenSetting for user " + userId); 7973 7974 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7975 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7976 return false; 7977 } 7978 7979 long callingId = Binder.clearCallingIdentity(); 7980 try { 7981 boolean sendAdded = false; 7982 boolean sendRemoved = false; 7983 // writer 7984 synchronized (mPackages) { 7985 pkgSetting = mSettings.mPackages.get(packageName); 7986 if (pkgSetting == null) { 7987 return false; 7988 } 7989 if (pkgSetting.getHidden(userId) != hidden) { 7990 pkgSetting.setHidden(hidden, userId); 7991 mSettings.writePackageRestrictionsLPr(userId); 7992 if (hidden) { 7993 sendRemoved = true; 7994 } else { 7995 sendAdded = true; 7996 } 7997 } 7998 } 7999 if (sendAdded) { 8000 sendPackageAddedForUser(packageName, pkgSetting, userId); 8001 return true; 8002 } 8003 if (sendRemoved) { 8004 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8005 "hiding pkg"); 8006 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8007 } 8008 } finally { 8009 Binder.restoreCallingIdentity(callingId); 8010 } 8011 return false; 8012 } 8013 8014 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8015 int userId) { 8016 final PackageRemovedInfo info = new PackageRemovedInfo(); 8017 info.removedPackage = packageName; 8018 info.removedUsers = new int[] {userId}; 8019 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8020 info.sendBroadcast(false, false, false); 8021 } 8022 8023 /** 8024 * Returns true if application is not found or there was an error. Otherwise it returns 8025 * the hidden state of the package for the given user. 8026 */ 8027 @Override 8028 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8029 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8030 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8031 false, "getApplicationHidden for user " + userId); 8032 PackageSetting pkgSetting; 8033 long callingId = Binder.clearCallingIdentity(); 8034 try { 8035 // writer 8036 synchronized (mPackages) { 8037 pkgSetting = mSettings.mPackages.get(packageName); 8038 if (pkgSetting == null) { 8039 return true; 8040 } 8041 return pkgSetting.getHidden(userId); 8042 } 8043 } finally { 8044 Binder.restoreCallingIdentity(callingId); 8045 } 8046 } 8047 8048 /** 8049 * @hide 8050 */ 8051 @Override 8052 public int installExistingPackageAsUser(String packageName, int userId) { 8053 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8054 null); 8055 PackageSetting pkgSetting; 8056 final int uid = Binder.getCallingUid(); 8057 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8058 + userId); 8059 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8060 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8061 } 8062 8063 long callingId = Binder.clearCallingIdentity(); 8064 try { 8065 boolean sendAdded = false; 8066 Bundle extras = new Bundle(1); 8067 8068 // writer 8069 synchronized (mPackages) { 8070 pkgSetting = mSettings.mPackages.get(packageName); 8071 if (pkgSetting == null) { 8072 return PackageManager.INSTALL_FAILED_INVALID_URI; 8073 } 8074 if (!pkgSetting.getInstalled(userId)) { 8075 pkgSetting.setInstalled(true, userId); 8076 pkgSetting.setHidden(false, userId); 8077 mSettings.writePackageRestrictionsLPr(userId); 8078 sendAdded = true; 8079 } 8080 } 8081 8082 if (sendAdded) { 8083 sendPackageAddedForUser(packageName, pkgSetting, userId); 8084 } 8085 } finally { 8086 Binder.restoreCallingIdentity(callingId); 8087 } 8088 8089 return PackageManager.INSTALL_SUCCEEDED; 8090 } 8091 8092 boolean isUserRestricted(int userId, String restrictionKey) { 8093 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8094 if (restrictions.getBoolean(restrictionKey, false)) { 8095 Log.w(TAG, "User is restricted: " + restrictionKey); 8096 return true; 8097 } 8098 return false; 8099 } 8100 8101 @Override 8102 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8103 mContext.enforceCallingOrSelfPermission( 8104 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8105 "Only package verification agents can verify applications"); 8106 8107 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8108 final PackageVerificationResponse response = new PackageVerificationResponse( 8109 verificationCode, Binder.getCallingUid()); 8110 msg.arg1 = id; 8111 msg.obj = response; 8112 mHandler.sendMessage(msg); 8113 } 8114 8115 @Override 8116 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8117 long millisecondsToDelay) { 8118 mContext.enforceCallingOrSelfPermission( 8119 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8120 "Only package verification agents can extend verification timeouts"); 8121 8122 final PackageVerificationState state = mPendingVerification.get(id); 8123 final PackageVerificationResponse response = new PackageVerificationResponse( 8124 verificationCodeAtTimeout, Binder.getCallingUid()); 8125 8126 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8127 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8128 } 8129 if (millisecondsToDelay < 0) { 8130 millisecondsToDelay = 0; 8131 } 8132 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8133 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8134 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8135 } 8136 8137 if ((state != null) && !state.timeoutExtended()) { 8138 state.extendTimeout(); 8139 8140 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8141 msg.arg1 = id; 8142 msg.obj = response; 8143 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8144 } 8145 } 8146 8147 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8148 int verificationCode, UserHandle user) { 8149 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8150 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8151 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8152 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8153 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8154 8155 mContext.sendBroadcastAsUser(intent, user, 8156 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8157 } 8158 8159 private ComponentName matchComponentForVerifier(String packageName, 8160 List<ResolveInfo> receivers) { 8161 ActivityInfo targetReceiver = null; 8162 8163 final int NR = receivers.size(); 8164 for (int i = 0; i < NR; i++) { 8165 final ResolveInfo info = receivers.get(i); 8166 if (info.activityInfo == null) { 8167 continue; 8168 } 8169 8170 if (packageName.equals(info.activityInfo.packageName)) { 8171 targetReceiver = info.activityInfo; 8172 break; 8173 } 8174 } 8175 8176 if (targetReceiver == null) { 8177 return null; 8178 } 8179 8180 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8181 } 8182 8183 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8184 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8185 if (pkgInfo.verifiers.length == 0) { 8186 return null; 8187 } 8188 8189 final int N = pkgInfo.verifiers.length; 8190 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8191 for (int i = 0; i < N; i++) { 8192 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8193 8194 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8195 receivers); 8196 if (comp == null) { 8197 continue; 8198 } 8199 8200 final int verifierUid = getUidForVerifier(verifierInfo); 8201 if (verifierUid == -1) { 8202 continue; 8203 } 8204 8205 if (DEBUG_VERIFY) { 8206 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8207 + " with the correct signature"); 8208 } 8209 sufficientVerifiers.add(comp); 8210 verificationState.addSufficientVerifier(verifierUid); 8211 } 8212 8213 return sufficientVerifiers; 8214 } 8215 8216 private int getUidForVerifier(VerifierInfo verifierInfo) { 8217 synchronized (mPackages) { 8218 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8219 if (pkg == null) { 8220 return -1; 8221 } else if (pkg.mSignatures.length != 1) { 8222 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8223 + " has more than one signature; ignoring"); 8224 return -1; 8225 } 8226 8227 /* 8228 * If the public key of the package's signature does not match 8229 * our expected public key, then this is a different package and 8230 * we should skip. 8231 */ 8232 8233 final byte[] expectedPublicKey; 8234 try { 8235 final Signature verifierSig = pkg.mSignatures[0]; 8236 final PublicKey publicKey = verifierSig.getPublicKey(); 8237 expectedPublicKey = publicKey.getEncoded(); 8238 } catch (CertificateException e) { 8239 return -1; 8240 } 8241 8242 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8243 8244 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8245 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8246 + " does not have the expected public key; ignoring"); 8247 return -1; 8248 } 8249 8250 return pkg.applicationInfo.uid; 8251 } 8252 } 8253 8254 @Override 8255 public void finishPackageInstall(int token) { 8256 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8257 8258 if (DEBUG_INSTALL) { 8259 Slog.v(TAG, "BM finishing package install for " + token); 8260 } 8261 8262 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8263 mHandler.sendMessage(msg); 8264 } 8265 8266 /** 8267 * Get the verification agent timeout. 8268 * 8269 * @return verification timeout in milliseconds 8270 */ 8271 private long getVerificationTimeout() { 8272 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8273 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8274 DEFAULT_VERIFICATION_TIMEOUT); 8275 } 8276 8277 /** 8278 * Get the default verification agent response code. 8279 * 8280 * @return default verification response code 8281 */ 8282 private int getDefaultVerificationResponse() { 8283 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8284 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8285 DEFAULT_VERIFICATION_RESPONSE); 8286 } 8287 8288 /** 8289 * Check whether or not package verification has been enabled. 8290 * 8291 * @return true if verification should be performed 8292 */ 8293 private boolean isVerificationEnabled(int userId, int installFlags) { 8294 if (!DEFAULT_VERIFY_ENABLE) { 8295 return false; 8296 } 8297 8298 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8299 8300 // Check if installing from ADB 8301 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8302 // Do not run verification in a test harness environment 8303 if (ActivityManager.isRunningInTestHarness()) { 8304 return false; 8305 } 8306 if (ensureVerifyAppsEnabled) { 8307 return true; 8308 } 8309 // Check if the developer does not want package verification for ADB installs 8310 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8311 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8312 return false; 8313 } 8314 } 8315 8316 if (ensureVerifyAppsEnabled) { 8317 return true; 8318 } 8319 8320 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8321 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8322 } 8323 8324 /** 8325 * Get the "allow unknown sources" setting. 8326 * 8327 * @return the current "allow unknown sources" setting 8328 */ 8329 private int getUnknownSourcesSettings() { 8330 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8331 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8332 -1); 8333 } 8334 8335 @Override 8336 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8337 final int uid = Binder.getCallingUid(); 8338 // writer 8339 synchronized (mPackages) { 8340 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8341 if (targetPackageSetting == null) { 8342 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8343 } 8344 8345 PackageSetting installerPackageSetting; 8346 if (installerPackageName != null) { 8347 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8348 if (installerPackageSetting == null) { 8349 throw new IllegalArgumentException("Unknown installer package: " 8350 + installerPackageName); 8351 } 8352 } else { 8353 installerPackageSetting = null; 8354 } 8355 8356 Signature[] callerSignature; 8357 Object obj = mSettings.getUserIdLPr(uid); 8358 if (obj != null) { 8359 if (obj instanceof SharedUserSetting) { 8360 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8361 } else if (obj instanceof PackageSetting) { 8362 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8363 } else { 8364 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8365 } 8366 } else { 8367 throw new SecurityException("Unknown calling uid " + uid); 8368 } 8369 8370 // Verify: can't set installerPackageName to a package that is 8371 // not signed with the same cert as the caller. 8372 if (installerPackageSetting != null) { 8373 if (compareSignatures(callerSignature, 8374 installerPackageSetting.signatures.mSignatures) 8375 != PackageManager.SIGNATURE_MATCH) { 8376 throw new SecurityException( 8377 "Caller does not have same cert as new installer package " 8378 + installerPackageName); 8379 } 8380 } 8381 8382 // Verify: if target already has an installer package, it must 8383 // be signed with the same cert as the caller. 8384 if (targetPackageSetting.installerPackageName != null) { 8385 PackageSetting setting = mSettings.mPackages.get( 8386 targetPackageSetting.installerPackageName); 8387 // If the currently set package isn't valid, then it's always 8388 // okay to change it. 8389 if (setting != null) { 8390 if (compareSignatures(callerSignature, 8391 setting.signatures.mSignatures) 8392 != PackageManager.SIGNATURE_MATCH) { 8393 throw new SecurityException( 8394 "Caller does not have same cert as old installer package " 8395 + targetPackageSetting.installerPackageName); 8396 } 8397 } 8398 } 8399 8400 // Okay! 8401 targetPackageSetting.installerPackageName = installerPackageName; 8402 scheduleWriteSettingsLocked(); 8403 } 8404 } 8405 8406 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8407 // Queue up an async operation since the package installation may take a little while. 8408 mHandler.post(new Runnable() { 8409 public void run() { 8410 mHandler.removeCallbacks(this); 8411 // Result object to be returned 8412 PackageInstalledInfo res = new PackageInstalledInfo(); 8413 res.returnCode = currentStatus; 8414 res.uid = -1; 8415 res.pkg = null; 8416 res.removedInfo = new PackageRemovedInfo(); 8417 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8418 args.doPreInstall(res.returnCode); 8419 synchronized (mInstallLock) { 8420 installPackageLI(args, res); 8421 } 8422 args.doPostInstall(res.returnCode, res.uid); 8423 } 8424 8425 // A restore should be performed at this point if (a) the install 8426 // succeeded, (b) the operation is not an update, and (c) the new 8427 // package has not opted out of backup participation. 8428 final boolean update = res.removedInfo.removedPackage != null; 8429 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8430 boolean doRestore = !update 8431 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8432 8433 // Set up the post-install work request bookkeeping. This will be used 8434 // and cleaned up by the post-install event handling regardless of whether 8435 // there's a restore pass performed. Token values are >= 1. 8436 int token; 8437 if (mNextInstallToken < 0) mNextInstallToken = 1; 8438 token = mNextInstallToken++; 8439 8440 PostInstallData data = new PostInstallData(args, res); 8441 mRunningInstalls.put(token, data); 8442 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8443 8444 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8445 // Pass responsibility to the Backup Manager. It will perform a 8446 // restore if appropriate, then pass responsibility back to the 8447 // Package Manager to run the post-install observer callbacks 8448 // and broadcasts. 8449 IBackupManager bm = IBackupManager.Stub.asInterface( 8450 ServiceManager.getService(Context.BACKUP_SERVICE)); 8451 if (bm != null) { 8452 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8453 + " to BM for possible restore"); 8454 try { 8455 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 8456 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8457 } else { 8458 doRestore = false; 8459 } 8460 } catch (RemoteException e) { 8461 // can't happen; the backup manager is local 8462 } catch (Exception e) { 8463 Slog.e(TAG, "Exception trying to enqueue restore", e); 8464 doRestore = false; 8465 } 8466 } else { 8467 Slog.e(TAG, "Backup Manager not found!"); 8468 doRestore = false; 8469 } 8470 } 8471 8472 if (!doRestore) { 8473 // No restore possible, or the Backup Manager was mysteriously not 8474 // available -- just fire the post-install work request directly. 8475 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8476 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8477 mHandler.sendMessage(msg); 8478 } 8479 } 8480 }); 8481 } 8482 8483 private abstract class HandlerParams { 8484 private static final int MAX_RETRIES = 4; 8485 8486 /** 8487 * Number of times startCopy() has been attempted and had a non-fatal 8488 * error. 8489 */ 8490 private int mRetries = 0; 8491 8492 /** User handle for the user requesting the information or installation. */ 8493 private final UserHandle mUser; 8494 8495 HandlerParams(UserHandle user) { 8496 mUser = user; 8497 } 8498 8499 UserHandle getUser() { 8500 return mUser; 8501 } 8502 8503 final boolean startCopy() { 8504 boolean res; 8505 try { 8506 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8507 8508 if (++mRetries > MAX_RETRIES) { 8509 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8510 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8511 handleServiceError(); 8512 return false; 8513 } else { 8514 handleStartCopy(); 8515 res = true; 8516 } 8517 } catch (RemoteException e) { 8518 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8519 mHandler.sendEmptyMessage(MCS_RECONNECT); 8520 res = false; 8521 } 8522 handleReturnCode(); 8523 return res; 8524 } 8525 8526 final void serviceError() { 8527 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8528 handleServiceError(); 8529 handleReturnCode(); 8530 } 8531 8532 abstract void handleStartCopy() throws RemoteException; 8533 abstract void handleServiceError(); 8534 abstract void handleReturnCode(); 8535 } 8536 8537 class MeasureParams extends HandlerParams { 8538 private final PackageStats mStats; 8539 private boolean mSuccess; 8540 8541 private final IPackageStatsObserver mObserver; 8542 8543 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8544 super(new UserHandle(stats.userHandle)); 8545 mObserver = observer; 8546 mStats = stats; 8547 } 8548 8549 @Override 8550 public String toString() { 8551 return "MeasureParams{" 8552 + Integer.toHexString(System.identityHashCode(this)) 8553 + " " + mStats.packageName + "}"; 8554 } 8555 8556 @Override 8557 void handleStartCopy() throws RemoteException { 8558 synchronized (mInstallLock) { 8559 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8560 } 8561 8562 if (mSuccess) { 8563 final boolean mounted; 8564 if (Environment.isExternalStorageEmulated()) { 8565 mounted = true; 8566 } else { 8567 final String status = Environment.getExternalStorageState(); 8568 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8569 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8570 } 8571 8572 if (mounted) { 8573 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8574 8575 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8576 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8577 8578 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8579 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8580 8581 // Always subtract cache size, since it's a subdirectory 8582 mStats.externalDataSize -= mStats.externalCacheSize; 8583 8584 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8585 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8586 8587 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8588 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8589 } 8590 } 8591 } 8592 8593 @Override 8594 void handleReturnCode() { 8595 if (mObserver != null) { 8596 try { 8597 mObserver.onGetStatsCompleted(mStats, mSuccess); 8598 } catch (RemoteException e) { 8599 Slog.i(TAG, "Observer no longer exists."); 8600 } 8601 } 8602 } 8603 8604 @Override 8605 void handleServiceError() { 8606 Slog.e(TAG, "Could not measure application " + mStats.packageName 8607 + " external storage"); 8608 } 8609 } 8610 8611 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8612 throws RemoteException { 8613 long result = 0; 8614 for (File path : paths) { 8615 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8616 } 8617 return result; 8618 } 8619 8620 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8621 for (File path : paths) { 8622 try { 8623 mcs.clearDirectory(path.getAbsolutePath()); 8624 } catch (RemoteException e) { 8625 } 8626 } 8627 } 8628 8629 static class OriginInfo { 8630 /** 8631 * Location where install is coming from, before it has been 8632 * copied/renamed into place. This could be a single monolithic APK 8633 * file, or a cluster directory. This location may be untrusted. 8634 */ 8635 final File file; 8636 final String cid; 8637 8638 /** 8639 * Flag indicating that {@link #file} or {@link #cid} has already been 8640 * staged, meaning downstream users don't need to defensively copy the 8641 * contents. 8642 */ 8643 final boolean staged; 8644 8645 /** 8646 * Flag indicating that {@link #file} or {@link #cid} is an already 8647 * installed app that is being moved. 8648 */ 8649 final boolean existing; 8650 8651 final String resolvedPath; 8652 final File resolvedFile; 8653 8654 static OriginInfo fromNothing() { 8655 return new OriginInfo(null, null, false, false); 8656 } 8657 8658 static OriginInfo fromUntrustedFile(File file) { 8659 return new OriginInfo(file, null, false, false); 8660 } 8661 8662 static OriginInfo fromExistingFile(File file) { 8663 return new OriginInfo(file, null, false, true); 8664 } 8665 8666 static OriginInfo fromStagedFile(File file) { 8667 return new OriginInfo(file, null, true, false); 8668 } 8669 8670 static OriginInfo fromStagedContainer(String cid) { 8671 return new OriginInfo(null, cid, true, false); 8672 } 8673 8674 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8675 this.file = file; 8676 this.cid = cid; 8677 this.staged = staged; 8678 this.existing = existing; 8679 8680 if (cid != null) { 8681 resolvedPath = PackageHelper.getSdDir(cid); 8682 resolvedFile = new File(resolvedPath); 8683 } else if (file != null) { 8684 resolvedPath = file.getAbsolutePath(); 8685 resolvedFile = file; 8686 } else { 8687 resolvedPath = null; 8688 resolvedFile = null; 8689 } 8690 } 8691 } 8692 8693 class InstallParams extends HandlerParams { 8694 final OriginInfo origin; 8695 final IPackageInstallObserver2 observer; 8696 int installFlags; 8697 final String installerPackageName; 8698 final VerificationParams verificationParams; 8699 private InstallArgs mArgs; 8700 private int mRet; 8701 final String packageAbiOverride; 8702 8703 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8704 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8705 String packageAbiOverride) { 8706 super(user); 8707 this.origin = origin; 8708 this.observer = observer; 8709 this.installFlags = installFlags; 8710 this.installerPackageName = installerPackageName; 8711 this.verificationParams = verificationParams; 8712 this.packageAbiOverride = packageAbiOverride; 8713 } 8714 8715 @Override 8716 public String toString() { 8717 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8718 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8719 } 8720 8721 public ManifestDigest getManifestDigest() { 8722 if (verificationParams == null) { 8723 return null; 8724 } 8725 return verificationParams.getManifestDigest(); 8726 } 8727 8728 private int installLocationPolicy(PackageInfoLite pkgLite) { 8729 String packageName = pkgLite.packageName; 8730 int installLocation = pkgLite.installLocation; 8731 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8732 // reader 8733 synchronized (mPackages) { 8734 PackageParser.Package pkg = mPackages.get(packageName); 8735 if (pkg != null) { 8736 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8737 // Check for downgrading. 8738 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8739 try { 8740 checkDowngrade(pkg, pkgLite); 8741 } catch (PackageManagerException e) { 8742 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 8743 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8744 } 8745 } 8746 // Check for updated system application. 8747 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8748 if (onSd) { 8749 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8750 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8751 } 8752 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8753 } else { 8754 if (onSd) { 8755 // Install flag overrides everything. 8756 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8757 } 8758 // If current upgrade specifies particular preference 8759 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8760 // Application explicitly specified internal. 8761 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8762 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8763 // App explictly prefers external. Let policy decide 8764 } else { 8765 // Prefer previous location 8766 if (isExternal(pkg)) { 8767 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8768 } 8769 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8770 } 8771 } 8772 } else { 8773 // Invalid install. Return error code 8774 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8775 } 8776 } 8777 } 8778 // All the special cases have been taken care of. 8779 // Return result based on recommended install location. 8780 if (onSd) { 8781 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8782 } 8783 return pkgLite.recommendedInstallLocation; 8784 } 8785 8786 /* 8787 * Invoke remote method to get package information and install 8788 * location values. Override install location based on default 8789 * policy if needed and then create install arguments based 8790 * on the install location. 8791 */ 8792 public void handleStartCopy() throws RemoteException { 8793 int ret = PackageManager.INSTALL_SUCCEEDED; 8794 8795 // If we're already staged, we've firmly committed to an install location 8796 if (origin.staged) { 8797 if (origin.file != null) { 8798 installFlags |= PackageManager.INSTALL_INTERNAL; 8799 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8800 } else if (origin.cid != null) { 8801 installFlags |= PackageManager.INSTALL_EXTERNAL; 8802 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8803 } else { 8804 throw new IllegalStateException("Invalid stage location"); 8805 } 8806 } 8807 8808 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8809 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8810 8811 PackageInfoLite pkgLite = null; 8812 8813 if (onInt && onSd) { 8814 // Check if both bits are set. 8815 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8816 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8817 } else { 8818 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8819 packageAbiOverride); 8820 8821 /* 8822 * If we have too little free space, try to free cache 8823 * before giving up. 8824 */ 8825 if (!origin.staged && pkgLite.recommendedInstallLocation 8826 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8827 // TODO: focus freeing disk space on the target device 8828 final StorageManager storage = StorageManager.from(mContext); 8829 final long lowThreshold = storage.getStorageLowBytes( 8830 Environment.getDataDirectory()); 8831 8832 final long sizeBytes = mContainerService.calculateInstalledSize( 8833 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8834 8835 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8836 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8837 installFlags, packageAbiOverride); 8838 } 8839 8840 /* 8841 * The cache free must have deleted the file we 8842 * downloaded to install. 8843 * 8844 * TODO: fix the "freeCache" call to not delete 8845 * the file we care about. 8846 */ 8847 if (pkgLite.recommendedInstallLocation 8848 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8849 pkgLite.recommendedInstallLocation 8850 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8851 } 8852 } 8853 } 8854 8855 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8856 int loc = pkgLite.recommendedInstallLocation; 8857 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8858 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8859 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8860 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8861 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8862 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8863 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8864 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8865 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8866 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8867 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8868 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8869 } else { 8870 // Override with defaults if needed. 8871 loc = installLocationPolicy(pkgLite); 8872 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8873 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8874 } else if (!onSd && !onInt) { 8875 // Override install location with flags 8876 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8877 // Set the flag to install on external media. 8878 installFlags |= PackageManager.INSTALL_EXTERNAL; 8879 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8880 } else { 8881 // Make sure the flag for installing on external 8882 // media is unset 8883 installFlags |= PackageManager.INSTALL_INTERNAL; 8884 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8885 } 8886 } 8887 } 8888 } 8889 8890 final InstallArgs args = createInstallArgs(this); 8891 mArgs = args; 8892 8893 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8894 /* 8895 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8896 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8897 */ 8898 int userIdentifier = getUser().getIdentifier(); 8899 if (userIdentifier == UserHandle.USER_ALL 8900 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8901 userIdentifier = UserHandle.USER_OWNER; 8902 } 8903 8904 /* 8905 * Determine if we have any installed package verifiers. If we 8906 * do, then we'll defer to them to verify the packages. 8907 */ 8908 final int requiredUid = mRequiredVerifierPackage == null ? -1 8909 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8910 if (!origin.existing && requiredUid != -1 8911 && isVerificationEnabled(userIdentifier, installFlags)) { 8912 final Intent verification = new Intent( 8913 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8914 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 8915 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8916 PACKAGE_MIME_TYPE); 8917 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8918 8919 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8920 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8921 0 /* TODO: Which userId? */); 8922 8923 if (DEBUG_VERIFY) { 8924 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8925 + verification.toString() + " with " + pkgLite.verifiers.length 8926 + " optional verifiers"); 8927 } 8928 8929 final int verificationId = mPendingVerificationToken++; 8930 8931 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8932 8933 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8934 installerPackageName); 8935 8936 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8937 installFlags); 8938 8939 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8940 pkgLite.packageName); 8941 8942 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8943 pkgLite.versionCode); 8944 8945 if (verificationParams != null) { 8946 if (verificationParams.getVerificationURI() != null) { 8947 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8948 verificationParams.getVerificationURI()); 8949 } 8950 if (verificationParams.getOriginatingURI() != null) { 8951 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8952 verificationParams.getOriginatingURI()); 8953 } 8954 if (verificationParams.getReferrer() != null) { 8955 verification.putExtra(Intent.EXTRA_REFERRER, 8956 verificationParams.getReferrer()); 8957 } 8958 if (verificationParams.getOriginatingUid() >= 0) { 8959 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8960 verificationParams.getOriginatingUid()); 8961 } 8962 if (verificationParams.getInstallerUid() >= 0) { 8963 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8964 verificationParams.getInstallerUid()); 8965 } 8966 } 8967 8968 final PackageVerificationState verificationState = new PackageVerificationState( 8969 requiredUid, args); 8970 8971 mPendingVerification.append(verificationId, verificationState); 8972 8973 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8974 receivers, verificationState); 8975 8976 /* 8977 * If any sufficient verifiers were listed in the package 8978 * manifest, attempt to ask them. 8979 */ 8980 if (sufficientVerifiers != null) { 8981 final int N = sufficientVerifiers.size(); 8982 if (N == 0) { 8983 Slog.i(TAG, "Additional verifiers required, but none installed."); 8984 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8985 } else { 8986 for (int i = 0; i < N; i++) { 8987 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8988 8989 final Intent sufficientIntent = new Intent(verification); 8990 sufficientIntent.setComponent(verifierComponent); 8991 8992 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8993 } 8994 } 8995 } 8996 8997 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8998 mRequiredVerifierPackage, receivers); 8999 if (ret == PackageManager.INSTALL_SUCCEEDED 9000 && mRequiredVerifierPackage != null) { 9001 /* 9002 * Send the intent to the required verification agent, 9003 * but only start the verification timeout after the 9004 * target BroadcastReceivers have run. 9005 */ 9006 verification.setComponent(requiredVerifierComponent); 9007 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9008 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9009 new BroadcastReceiver() { 9010 @Override 9011 public void onReceive(Context context, Intent intent) { 9012 final Message msg = mHandler 9013 .obtainMessage(CHECK_PENDING_VERIFICATION); 9014 msg.arg1 = verificationId; 9015 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9016 } 9017 }, null, 0, null, null); 9018 9019 /* 9020 * We don't want the copy to proceed until verification 9021 * succeeds, so null out this field. 9022 */ 9023 mArgs = null; 9024 } 9025 } else { 9026 /* 9027 * No package verification is enabled, so immediately start 9028 * the remote call to initiate copy using temporary file. 9029 */ 9030 ret = args.copyApk(mContainerService, true); 9031 } 9032 } 9033 9034 mRet = ret; 9035 } 9036 9037 @Override 9038 void handleReturnCode() { 9039 // If mArgs is null, then MCS couldn't be reached. When it 9040 // reconnects, it will try again to install. At that point, this 9041 // will succeed. 9042 if (mArgs != null) { 9043 processPendingInstall(mArgs, mRet); 9044 } 9045 } 9046 9047 @Override 9048 void handleServiceError() { 9049 mArgs = createInstallArgs(this); 9050 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9051 } 9052 9053 public boolean isForwardLocked() { 9054 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9055 } 9056 } 9057 9058 /** 9059 * Used during creation of InstallArgs 9060 * 9061 * @param installFlags package installation flags 9062 * @return true if should be installed on external storage 9063 */ 9064 private static boolean installOnSd(int installFlags) { 9065 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9066 return false; 9067 } 9068 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9069 return true; 9070 } 9071 return false; 9072 } 9073 9074 /** 9075 * Used during creation of InstallArgs 9076 * 9077 * @param installFlags package installation flags 9078 * @return true if should be installed as forward locked 9079 */ 9080 private static boolean installForwardLocked(int installFlags) { 9081 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9082 } 9083 9084 private InstallArgs createInstallArgs(InstallParams params) { 9085 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9086 return new AsecInstallArgs(params); 9087 } else { 9088 return new FileInstallArgs(params); 9089 } 9090 } 9091 9092 /** 9093 * Create args that describe an existing installed package. Typically used 9094 * when cleaning up old installs, or used as a move source. 9095 */ 9096 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9097 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9098 final boolean isInAsec; 9099 if (installOnSd(installFlags)) { 9100 /* Apps on SD card are always in ASEC containers. */ 9101 isInAsec = true; 9102 } else if (installForwardLocked(installFlags) 9103 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9104 /* 9105 * Forward-locked apps are only in ASEC containers if they're the 9106 * new style 9107 */ 9108 isInAsec = true; 9109 } else { 9110 isInAsec = false; 9111 } 9112 9113 if (isInAsec) { 9114 return new AsecInstallArgs(codePath, instructionSets, 9115 installOnSd(installFlags), installForwardLocked(installFlags)); 9116 } else { 9117 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9118 instructionSets); 9119 } 9120 } 9121 9122 static abstract class InstallArgs { 9123 /** @see InstallParams#origin */ 9124 final OriginInfo origin; 9125 9126 final IPackageInstallObserver2 observer; 9127 // Always refers to PackageManager flags only 9128 final int installFlags; 9129 final String installerPackageName; 9130 final ManifestDigest manifestDigest; 9131 final UserHandle user; 9132 final String abiOverride; 9133 9134 // The list of instruction sets supported by this app. This is currently 9135 // only used during the rmdex() phase to clean up resources. We can get rid of this 9136 // if we move dex files under the common app path. 9137 /* nullable */ String[] instructionSets; 9138 9139 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9140 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9141 String[] instructionSets, String abiOverride) { 9142 this.origin = origin; 9143 this.installFlags = installFlags; 9144 this.observer = observer; 9145 this.installerPackageName = installerPackageName; 9146 this.manifestDigest = manifestDigest; 9147 this.user = user; 9148 this.instructionSets = instructionSets; 9149 this.abiOverride = abiOverride; 9150 } 9151 9152 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9153 abstract int doPreInstall(int status); 9154 9155 /** 9156 * Rename package into final resting place. All paths on the given 9157 * scanned package should be updated to reflect the rename. 9158 */ 9159 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9160 abstract int doPostInstall(int status, int uid); 9161 9162 /** @see PackageSettingBase#codePathString */ 9163 abstract String getCodePath(); 9164 /** @see PackageSettingBase#resourcePathString */ 9165 abstract String getResourcePath(); 9166 abstract String getLegacyNativeLibraryPath(); 9167 9168 // Need installer lock especially for dex file removal. 9169 abstract void cleanUpResourcesLI(); 9170 abstract boolean doPostDeleteLI(boolean delete); 9171 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9172 9173 /** 9174 * Called before the source arguments are copied. This is used mostly 9175 * for MoveParams when it needs to read the source file to put it in the 9176 * destination. 9177 */ 9178 int doPreCopy() { 9179 return PackageManager.INSTALL_SUCCEEDED; 9180 } 9181 9182 /** 9183 * Called after the source arguments are copied. This is used mostly for 9184 * MoveParams when it needs to read the source file to put it in the 9185 * destination. 9186 * 9187 * @return 9188 */ 9189 int doPostCopy(int uid) { 9190 return PackageManager.INSTALL_SUCCEEDED; 9191 } 9192 9193 protected boolean isFwdLocked() { 9194 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9195 } 9196 9197 protected boolean isExternal() { 9198 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9199 } 9200 9201 UserHandle getUser() { 9202 return user; 9203 } 9204 } 9205 9206 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9207 if (!allCodePaths.isEmpty()) { 9208 if (instructionSets == null) { 9209 throw new IllegalStateException("instructionSet == null"); 9210 } 9211 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9212 for (String codePath : allCodePaths) { 9213 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9214 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9215 if (retCode < 0) { 9216 Slog.w(TAG, "Couldn't remove dex file for package: " 9217 + " at location " + codePath + ", retcode=" + retCode); 9218 // we don't consider this to be a failure of the core package deletion 9219 } 9220 } 9221 } 9222 } 9223 } 9224 9225 /** 9226 * Logic to handle installation of non-ASEC applications, including copying 9227 * and renaming logic. 9228 */ 9229 class FileInstallArgs extends InstallArgs { 9230 private File codeFile; 9231 private File resourceFile; 9232 private File legacyNativeLibraryPath; 9233 9234 // Example topology: 9235 // /data/app/com.example/base.apk 9236 // /data/app/com.example/split_foo.apk 9237 // /data/app/com.example/lib/arm/libfoo.so 9238 // /data/app/com.example/lib/arm64/libfoo.so 9239 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9240 9241 /** New install */ 9242 FileInstallArgs(InstallParams params) { 9243 super(params.origin, params.observer, params.installFlags, 9244 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9245 null /* instruction sets */, params.packageAbiOverride); 9246 if (isFwdLocked()) { 9247 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9248 } 9249 } 9250 9251 /** Existing install */ 9252 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9253 String[] instructionSets) { 9254 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9255 this.codeFile = (codePath != null) ? new File(codePath) : null; 9256 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9257 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9258 new File(legacyNativeLibraryPath) : null; 9259 } 9260 9261 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9262 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9263 isFwdLocked(), abiOverride); 9264 9265 final StorageManager storage = StorageManager.from(mContext); 9266 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9267 } 9268 9269 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9270 if (origin.staged) { 9271 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9272 codeFile = origin.file; 9273 resourceFile = origin.file; 9274 return PackageManager.INSTALL_SUCCEEDED; 9275 } 9276 9277 try { 9278 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9279 codeFile = tempDir; 9280 resourceFile = tempDir; 9281 } catch (IOException e) { 9282 Slog.w(TAG, "Failed to create copy file: " + e); 9283 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9284 } 9285 9286 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9287 @Override 9288 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9289 if (!FileUtils.isValidExtFilename(name)) { 9290 throw new IllegalArgumentException("Invalid filename: " + name); 9291 } 9292 try { 9293 final File file = new File(codeFile, name); 9294 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9295 O_RDWR | O_CREAT, 0644); 9296 Os.chmod(file.getAbsolutePath(), 0644); 9297 return new ParcelFileDescriptor(fd); 9298 } catch (ErrnoException e) { 9299 throw new RemoteException("Failed to open: " + e.getMessage()); 9300 } 9301 } 9302 }; 9303 9304 int ret = PackageManager.INSTALL_SUCCEEDED; 9305 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9306 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9307 Slog.e(TAG, "Failed to copy package"); 9308 return ret; 9309 } 9310 9311 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9312 NativeLibraryHelper.Handle handle = null; 9313 try { 9314 handle = NativeLibraryHelper.Handle.create(codeFile); 9315 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9316 abiOverride); 9317 } catch (IOException e) { 9318 Slog.e(TAG, "Copying native libraries failed", e); 9319 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9320 } finally { 9321 IoUtils.closeQuietly(handle); 9322 } 9323 9324 return ret; 9325 } 9326 9327 int doPreInstall(int status) { 9328 if (status != PackageManager.INSTALL_SUCCEEDED) { 9329 cleanUp(); 9330 } 9331 return status; 9332 } 9333 9334 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9335 if (status != PackageManager.INSTALL_SUCCEEDED) { 9336 cleanUp(); 9337 return false; 9338 } else { 9339 final File beforeCodeFile = codeFile; 9340 final File afterCodeFile = getNextCodePath(pkg.packageName); 9341 9342 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9343 try { 9344 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9345 } catch (ErrnoException e) { 9346 Slog.d(TAG, "Failed to rename", e); 9347 return false; 9348 } 9349 9350 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9351 Slog.d(TAG, "Failed to restorecon"); 9352 return false; 9353 } 9354 9355 // Reflect the rename internally 9356 codeFile = afterCodeFile; 9357 resourceFile = afterCodeFile; 9358 9359 // Reflect the rename in scanned details 9360 pkg.codePath = afterCodeFile.getAbsolutePath(); 9361 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9362 pkg.baseCodePath); 9363 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9364 pkg.splitCodePaths); 9365 9366 // Reflect the rename in app info 9367 pkg.applicationInfo.setCodePath(pkg.codePath); 9368 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9369 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9370 pkg.applicationInfo.setResourcePath(pkg.codePath); 9371 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9372 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9373 9374 return true; 9375 } 9376 } 9377 9378 int doPostInstall(int status, int uid) { 9379 if (status != PackageManager.INSTALL_SUCCEEDED) { 9380 cleanUp(); 9381 } 9382 return status; 9383 } 9384 9385 @Override 9386 String getCodePath() { 9387 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9388 } 9389 9390 @Override 9391 String getResourcePath() { 9392 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9393 } 9394 9395 @Override 9396 String getLegacyNativeLibraryPath() { 9397 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9398 } 9399 9400 private boolean cleanUp() { 9401 if (codeFile == null || !codeFile.exists()) { 9402 return false; 9403 } 9404 9405 if (codeFile.isDirectory()) { 9406 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 9407 } else { 9408 codeFile.delete(); 9409 } 9410 9411 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9412 resourceFile.delete(); 9413 } 9414 9415 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9416 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9417 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9418 } 9419 legacyNativeLibraryPath.delete(); 9420 } 9421 9422 return true; 9423 } 9424 9425 void cleanUpResourcesLI() { 9426 // Try enumerating all code paths before deleting 9427 List<String> allCodePaths = Collections.EMPTY_LIST; 9428 if (codeFile != null && codeFile.exists()) { 9429 try { 9430 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9431 allCodePaths = pkg.getAllCodePaths(); 9432 } catch (PackageParserException e) { 9433 // Ignored; we tried our best 9434 } 9435 } 9436 9437 cleanUp(); 9438 removeDexFiles(allCodePaths, instructionSets); 9439 } 9440 9441 boolean doPostDeleteLI(boolean delete) { 9442 // XXX err, shouldn't we respect the delete flag? 9443 cleanUpResourcesLI(); 9444 return true; 9445 } 9446 } 9447 9448 private boolean isAsecExternal(String cid) { 9449 final String asecPath = PackageHelper.getSdFilesystem(cid); 9450 return !asecPath.startsWith(mAsecInternalPath); 9451 } 9452 9453 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9454 PackageManagerException { 9455 if (copyRet < 0) { 9456 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9457 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9458 throw new PackageManagerException(copyRet, message); 9459 } 9460 } 9461 } 9462 9463 /** 9464 * Extract the MountService "container ID" from the full code path of an 9465 * .apk. 9466 */ 9467 static String cidFromCodePath(String fullCodePath) { 9468 int eidx = fullCodePath.lastIndexOf("/"); 9469 String subStr1 = fullCodePath.substring(0, eidx); 9470 int sidx = subStr1.lastIndexOf("/"); 9471 return subStr1.substring(sidx+1, eidx); 9472 } 9473 9474 /** 9475 * Logic to handle installation of ASEC applications, including copying and 9476 * renaming logic. 9477 */ 9478 class AsecInstallArgs extends InstallArgs { 9479 static final String RES_FILE_NAME = "pkg.apk"; 9480 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9481 9482 String cid; 9483 String packagePath; 9484 String resourcePath; 9485 String legacyNativeLibraryDir; 9486 9487 /** New install */ 9488 AsecInstallArgs(InstallParams params) { 9489 super(params.origin, params.observer, params.installFlags, 9490 params.installerPackageName, params.getManifestDigest(), 9491 params.getUser(), null /* instruction sets */, 9492 params.packageAbiOverride); 9493 } 9494 9495 /** Existing install */ 9496 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9497 boolean isExternal, boolean isForwardLocked) { 9498 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9499 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9500 instructionSets, null); 9501 // Hackily pretend we're still looking at a full code path 9502 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9503 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9504 } 9505 9506 // Extract cid from fullCodePath 9507 int eidx = fullCodePath.lastIndexOf("/"); 9508 String subStr1 = fullCodePath.substring(0, eidx); 9509 int sidx = subStr1.lastIndexOf("/"); 9510 cid = subStr1.substring(sidx+1, eidx); 9511 setMountPath(subStr1); 9512 } 9513 9514 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9515 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9516 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9517 instructionSets, null); 9518 this.cid = cid; 9519 setMountPath(PackageHelper.getSdDir(cid)); 9520 } 9521 9522 void createCopyFile() { 9523 cid = mInstallerService.allocateExternalStageCidLegacy(); 9524 } 9525 9526 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9527 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9528 abiOverride); 9529 9530 final File target; 9531 if (isExternal()) { 9532 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9533 } else { 9534 target = Environment.getDataDirectory(); 9535 } 9536 9537 final StorageManager storage = StorageManager.from(mContext); 9538 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9539 } 9540 9541 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9542 if (origin.staged) { 9543 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9544 cid = origin.cid; 9545 setMountPath(PackageHelper.getSdDir(cid)); 9546 return PackageManager.INSTALL_SUCCEEDED; 9547 } 9548 9549 if (temp) { 9550 createCopyFile(); 9551 } else { 9552 /* 9553 * Pre-emptively destroy the container since it's destroyed if 9554 * copying fails due to it existing anyway. 9555 */ 9556 PackageHelper.destroySdDir(cid); 9557 } 9558 9559 final String newMountPath = imcs.copyPackageToContainer( 9560 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9561 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9562 9563 if (newMountPath != null) { 9564 setMountPath(newMountPath); 9565 return PackageManager.INSTALL_SUCCEEDED; 9566 } else { 9567 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9568 } 9569 } 9570 9571 @Override 9572 String getCodePath() { 9573 return packagePath; 9574 } 9575 9576 @Override 9577 String getResourcePath() { 9578 return resourcePath; 9579 } 9580 9581 @Override 9582 String getLegacyNativeLibraryPath() { 9583 return legacyNativeLibraryDir; 9584 } 9585 9586 int doPreInstall(int status) { 9587 if (status != PackageManager.INSTALL_SUCCEEDED) { 9588 // Destroy container 9589 PackageHelper.destroySdDir(cid); 9590 } else { 9591 boolean mounted = PackageHelper.isContainerMounted(cid); 9592 if (!mounted) { 9593 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9594 Process.SYSTEM_UID); 9595 if (newMountPath != null) { 9596 setMountPath(newMountPath); 9597 } else { 9598 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9599 } 9600 } 9601 } 9602 return status; 9603 } 9604 9605 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9606 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9607 String newMountPath = null; 9608 if (PackageHelper.isContainerMounted(cid)) { 9609 // Unmount the container 9610 if (!PackageHelper.unMountSdDir(cid)) { 9611 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9612 return false; 9613 } 9614 } 9615 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9616 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9617 " which might be stale. Will try to clean up."); 9618 // Clean up the stale container and proceed to recreate. 9619 if (!PackageHelper.destroySdDir(newCacheId)) { 9620 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9621 return false; 9622 } 9623 // Successfully cleaned up stale container. Try to rename again. 9624 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9625 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9626 + " inspite of cleaning it up."); 9627 return false; 9628 } 9629 } 9630 if (!PackageHelper.isContainerMounted(newCacheId)) { 9631 Slog.w(TAG, "Mounting container " + newCacheId); 9632 newMountPath = PackageHelper.mountSdDir(newCacheId, 9633 getEncryptKey(), Process.SYSTEM_UID); 9634 } else { 9635 newMountPath = PackageHelper.getSdDir(newCacheId); 9636 } 9637 if (newMountPath == null) { 9638 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9639 return false; 9640 } 9641 Log.i(TAG, "Succesfully renamed " + cid + 9642 " to " + newCacheId + 9643 " at new path: " + newMountPath); 9644 cid = newCacheId; 9645 9646 final File beforeCodeFile = new File(packagePath); 9647 setMountPath(newMountPath); 9648 final File afterCodeFile = new File(packagePath); 9649 9650 // Reflect the rename in scanned details 9651 pkg.codePath = afterCodeFile.getAbsolutePath(); 9652 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9653 pkg.baseCodePath); 9654 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9655 pkg.splitCodePaths); 9656 9657 // Reflect the rename in app info 9658 pkg.applicationInfo.setCodePath(pkg.codePath); 9659 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9660 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9661 pkg.applicationInfo.setResourcePath(pkg.codePath); 9662 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9663 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9664 9665 return true; 9666 } 9667 9668 private void setMountPath(String mountPath) { 9669 final File mountFile = new File(mountPath); 9670 9671 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9672 if (monolithicFile.exists()) { 9673 packagePath = monolithicFile.getAbsolutePath(); 9674 if (isFwdLocked()) { 9675 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9676 } else { 9677 resourcePath = packagePath; 9678 } 9679 } else { 9680 packagePath = mountFile.getAbsolutePath(); 9681 resourcePath = packagePath; 9682 } 9683 9684 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9685 } 9686 9687 int doPostInstall(int status, int uid) { 9688 if (status != PackageManager.INSTALL_SUCCEEDED) { 9689 cleanUp(); 9690 } else { 9691 final int groupOwner; 9692 final String protectedFile; 9693 if (isFwdLocked()) { 9694 groupOwner = UserHandle.getSharedAppGid(uid); 9695 protectedFile = RES_FILE_NAME; 9696 } else { 9697 groupOwner = -1; 9698 protectedFile = null; 9699 } 9700 9701 if (uid < Process.FIRST_APPLICATION_UID 9702 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9703 Slog.e(TAG, "Failed to finalize " + cid); 9704 PackageHelper.destroySdDir(cid); 9705 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9706 } 9707 9708 boolean mounted = PackageHelper.isContainerMounted(cid); 9709 if (!mounted) { 9710 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9711 } 9712 } 9713 return status; 9714 } 9715 9716 private void cleanUp() { 9717 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9718 9719 // Destroy secure container 9720 PackageHelper.destroySdDir(cid); 9721 } 9722 9723 private List<String> getAllCodePaths() { 9724 final File codeFile = new File(getCodePath()); 9725 if (codeFile != null && codeFile.exists()) { 9726 try { 9727 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9728 return pkg.getAllCodePaths(); 9729 } catch (PackageParserException e) { 9730 // Ignored; we tried our best 9731 } 9732 } 9733 return Collections.EMPTY_LIST; 9734 } 9735 9736 void cleanUpResourcesLI() { 9737 // Enumerate all code paths before deleting 9738 cleanUpResourcesLI(getAllCodePaths()); 9739 } 9740 9741 private void cleanUpResourcesLI(List<String> allCodePaths) { 9742 cleanUp(); 9743 removeDexFiles(allCodePaths, instructionSets); 9744 } 9745 9746 9747 9748 String getPackageName() { 9749 return getAsecPackageName(cid); 9750 } 9751 9752 boolean doPostDeleteLI(boolean delete) { 9753 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9754 final List<String> allCodePaths = getAllCodePaths(); 9755 boolean mounted = PackageHelper.isContainerMounted(cid); 9756 if (mounted) { 9757 // Unmount first 9758 if (PackageHelper.unMountSdDir(cid)) { 9759 mounted = false; 9760 } 9761 } 9762 if (!mounted && delete) { 9763 cleanUpResourcesLI(allCodePaths); 9764 } 9765 return !mounted; 9766 } 9767 9768 @Override 9769 int doPreCopy() { 9770 if (isFwdLocked()) { 9771 if (!PackageHelper.fixSdPermissions(cid, 9772 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9773 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9774 } 9775 } 9776 9777 return PackageManager.INSTALL_SUCCEEDED; 9778 } 9779 9780 @Override 9781 int doPostCopy(int uid) { 9782 if (isFwdLocked()) { 9783 if (uid < Process.FIRST_APPLICATION_UID 9784 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9785 RES_FILE_NAME)) { 9786 Slog.e(TAG, "Failed to finalize " + cid); 9787 PackageHelper.destroySdDir(cid); 9788 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9789 } 9790 } 9791 9792 return PackageManager.INSTALL_SUCCEEDED; 9793 } 9794 } 9795 9796 static String getAsecPackageName(String packageCid) { 9797 int idx = packageCid.lastIndexOf("-"); 9798 if (idx == -1) { 9799 return packageCid; 9800 } 9801 return packageCid.substring(0, idx); 9802 } 9803 9804 // Utility method used to create code paths based on package name and available index. 9805 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9806 String idxStr = ""; 9807 int idx = 1; 9808 // Fall back to default value of idx=1 if prefix is not 9809 // part of oldCodePath 9810 if (oldCodePath != null) { 9811 String subStr = oldCodePath; 9812 // Drop the suffix right away 9813 if (suffix != null && subStr.endsWith(suffix)) { 9814 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9815 } 9816 // If oldCodePath already contains prefix find out the 9817 // ending index to either increment or decrement. 9818 int sidx = subStr.lastIndexOf(prefix); 9819 if (sidx != -1) { 9820 subStr = subStr.substring(sidx + prefix.length()); 9821 if (subStr != null) { 9822 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9823 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9824 } 9825 try { 9826 idx = Integer.parseInt(subStr); 9827 if (idx <= 1) { 9828 idx++; 9829 } else { 9830 idx--; 9831 } 9832 } catch(NumberFormatException e) { 9833 } 9834 } 9835 } 9836 } 9837 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9838 return prefix + idxStr; 9839 } 9840 9841 private File getNextCodePath(String packageName) { 9842 int suffix = 1; 9843 File result; 9844 do { 9845 result = new File(mAppInstallDir, packageName + "-" + suffix); 9846 suffix++; 9847 } while (result.exists()); 9848 return result; 9849 } 9850 9851 // Utility method that returns the relative package path with respect 9852 // to the installation directory. Like say for /data/data/com.test-1.apk 9853 // string com.test-1 is returned. 9854 static String deriveCodePathName(String codePath) { 9855 if (codePath == null) { 9856 return null; 9857 } 9858 final File codeFile = new File(codePath); 9859 final String name = codeFile.getName(); 9860 if (codeFile.isDirectory()) { 9861 return name; 9862 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9863 final int lastDot = name.lastIndexOf('.'); 9864 return name.substring(0, lastDot); 9865 } else { 9866 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9867 return null; 9868 } 9869 } 9870 9871 class PackageInstalledInfo { 9872 String name; 9873 int uid; 9874 // The set of users that originally had this package installed. 9875 int[] origUsers; 9876 // The set of users that now have this package installed. 9877 int[] newUsers; 9878 PackageParser.Package pkg; 9879 int returnCode; 9880 String returnMsg; 9881 PackageRemovedInfo removedInfo; 9882 9883 public void setError(int code, String msg) { 9884 returnCode = code; 9885 returnMsg = msg; 9886 Slog.w(TAG, msg); 9887 } 9888 9889 public void setError(String msg, PackageParserException e) { 9890 returnCode = e.error; 9891 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9892 Slog.w(TAG, msg, e); 9893 } 9894 9895 public void setError(String msg, PackageManagerException e) { 9896 returnCode = e.error; 9897 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9898 Slog.w(TAG, msg, e); 9899 } 9900 9901 // In some error cases we want to convey more info back to the observer 9902 String origPackage; 9903 String origPermission; 9904 } 9905 9906 /* 9907 * Install a non-existing package. 9908 */ 9909 private void installNewPackageLI(PackageParser.Package pkg, 9910 int parseFlags, int scanFlags, UserHandle user, 9911 String installerPackageName, PackageInstalledInfo res) { 9912 // Remember this for later, in case we need to rollback this install 9913 String pkgName = pkg.packageName; 9914 9915 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9916 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9917 synchronized(mPackages) { 9918 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9919 // A package with the same name is already installed, though 9920 // it has been renamed to an older name. The package we 9921 // are trying to install should be installed as an update to 9922 // the existing one, but that has not been requested, so bail. 9923 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9924 + " without first uninstalling package running as " 9925 + mSettings.mRenamedPackages.get(pkgName)); 9926 return; 9927 } 9928 if (mPackages.containsKey(pkgName)) { 9929 // Don't allow installation over an existing package with the same name. 9930 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9931 + " without first uninstalling."); 9932 return; 9933 } 9934 } 9935 9936 try { 9937 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9938 System.currentTimeMillis(), user); 9939 9940 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9941 // delete the partially installed application. the data directory will have to be 9942 // restored if it was already existing 9943 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9944 // remove package from internal structures. Note that we want deletePackageX to 9945 // delete the package data and cache directories that it created in 9946 // scanPackageLocked, unless those directories existed before we even tried to 9947 // install. 9948 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9949 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9950 res.removedInfo, true); 9951 } 9952 9953 } catch (PackageManagerException e) { 9954 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9955 } 9956 } 9957 9958 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9959 // Upgrade keysets are being used. Determine if new package has a superset of the 9960 // required keys. 9961 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9962 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9963 for (int i = 0; i < upgradeKeySets.length; i++) { 9964 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9965 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9966 return true; 9967 } 9968 } 9969 return false; 9970 } 9971 9972 private void replacePackageLI(PackageParser.Package pkg, 9973 int parseFlags, int scanFlags, UserHandle user, 9974 String installerPackageName, PackageInstalledInfo res) { 9975 PackageParser.Package oldPackage; 9976 String pkgName = pkg.packageName; 9977 int[] allUsers; 9978 boolean[] perUserInstalled; 9979 9980 // First find the old package info and check signatures 9981 synchronized(mPackages) { 9982 oldPackage = mPackages.get(pkgName); 9983 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9984 PackageSetting ps = mSettings.mPackages.get(pkgName); 9985 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9986 // default to original signature matching 9987 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9988 != PackageManager.SIGNATURE_MATCH) { 9989 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9990 "New package has a different signature: " + pkgName); 9991 return; 9992 } 9993 } else { 9994 if(!checkUpgradeKeySetLP(ps, pkg)) { 9995 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9996 "New package not signed by keys specified by upgrade-keysets: " 9997 + pkgName); 9998 return; 9999 } 10000 } 10001 10002 // In case of rollback, remember per-user/profile install state 10003 allUsers = sUserManager.getUserIds(); 10004 perUserInstalled = new boolean[allUsers.length]; 10005 for (int i = 0; i < allUsers.length; i++) { 10006 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10007 } 10008 } 10009 10010 boolean sysPkg = (isSystemApp(oldPackage)); 10011 if (sysPkg) { 10012 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10013 user, allUsers, perUserInstalled, installerPackageName, res); 10014 } else { 10015 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10016 user, allUsers, perUserInstalled, installerPackageName, res); 10017 } 10018 } 10019 10020 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10021 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10022 int[] allUsers, boolean[] perUserInstalled, 10023 String installerPackageName, PackageInstalledInfo res) { 10024 String pkgName = deletedPackage.packageName; 10025 boolean deletedPkg = true; 10026 boolean updatedSettings = false; 10027 10028 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10029 + deletedPackage); 10030 long origUpdateTime; 10031 if (pkg.mExtras != null) { 10032 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10033 } else { 10034 origUpdateTime = 0; 10035 } 10036 10037 // First delete the existing package while retaining the data directory 10038 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10039 res.removedInfo, true)) { 10040 // If the existing package wasn't successfully deleted 10041 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10042 deletedPkg = false; 10043 } else { 10044 // Successfully deleted the old package; proceed with replace. 10045 10046 // If deleted package lived in a container, give users a chance to 10047 // relinquish resources before killing. 10048 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10049 if (DEBUG_INSTALL) { 10050 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10051 } 10052 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10053 final ArrayList<String> pkgList = new ArrayList<String>(1); 10054 pkgList.add(deletedPackage.applicationInfo.packageName); 10055 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10056 } 10057 10058 deleteCodeCacheDirsLI(pkgName); 10059 try { 10060 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10061 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10062 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10063 updatedSettings = true; 10064 } catch (PackageManagerException e) { 10065 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10066 } 10067 } 10068 10069 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10070 // remove package from internal structures. Note that we want deletePackageX to 10071 // delete the package data and cache directories that it created in 10072 // scanPackageLocked, unless those directories existed before we even tried to 10073 // install. 10074 if(updatedSettings) { 10075 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10076 deletePackageLI( 10077 pkgName, null, true, allUsers, perUserInstalled, 10078 PackageManager.DELETE_KEEP_DATA, 10079 res.removedInfo, true); 10080 } 10081 // Since we failed to install the new package we need to restore the old 10082 // package that we deleted. 10083 if (deletedPkg) { 10084 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10085 File restoreFile = new File(deletedPackage.codePath); 10086 // Parse old package 10087 boolean oldOnSd = isExternal(deletedPackage); 10088 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10089 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10090 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10091 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10092 try { 10093 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10094 } catch (PackageManagerException e) { 10095 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10096 + e.getMessage()); 10097 return; 10098 } 10099 // Restore of old package succeeded. Update permissions. 10100 // writer 10101 synchronized (mPackages) { 10102 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10103 UPDATE_PERMISSIONS_ALL); 10104 // can downgrade to reader 10105 mSettings.writeLPr(); 10106 } 10107 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10108 } 10109 } 10110 } 10111 10112 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10113 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10114 int[] allUsers, boolean[] perUserInstalled, 10115 String installerPackageName, PackageInstalledInfo res) { 10116 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10117 + ", old=" + deletedPackage); 10118 boolean disabledSystem = false; 10119 boolean updatedSettings = false; 10120 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10121 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10122 != 0) { 10123 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10124 } 10125 String packageName = deletedPackage.packageName; 10126 if (packageName == null) { 10127 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10128 "Attempt to delete null packageName."); 10129 return; 10130 } 10131 PackageParser.Package oldPkg; 10132 PackageSetting oldPkgSetting; 10133 // reader 10134 synchronized (mPackages) { 10135 oldPkg = mPackages.get(packageName); 10136 oldPkgSetting = mSettings.mPackages.get(packageName); 10137 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10138 (oldPkgSetting == null)) { 10139 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10140 "Couldn't find package:" + packageName + " information"); 10141 return; 10142 } 10143 } 10144 10145 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10146 10147 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10148 res.removedInfo.removedPackage = packageName; 10149 // Remove existing system package 10150 removePackageLI(oldPkgSetting, true); 10151 // writer 10152 synchronized (mPackages) { 10153 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10154 if (!disabledSystem && deletedPackage != null) { 10155 // We didn't need to disable the .apk as a current system package, 10156 // which means we are replacing another update that is already 10157 // installed. We need to make sure to delete the older one's .apk. 10158 res.removedInfo.args = createInstallArgsForExisting(0, 10159 deletedPackage.applicationInfo.getCodePath(), 10160 deletedPackage.applicationInfo.getResourcePath(), 10161 deletedPackage.applicationInfo.nativeLibraryRootDir, 10162 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10163 } else { 10164 res.removedInfo.args = null; 10165 } 10166 } 10167 10168 // Successfully disabled the old package. Now proceed with re-installation 10169 deleteCodeCacheDirsLI(packageName); 10170 10171 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10172 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10173 10174 PackageParser.Package newPackage = null; 10175 try { 10176 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10177 if (newPackage.mExtras != null) { 10178 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10179 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10180 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10181 10182 // is the update attempting to change shared user? that isn't going to work... 10183 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10184 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10185 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10186 + " to " + newPkgSetting.sharedUser); 10187 updatedSettings = true; 10188 } 10189 } 10190 10191 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10192 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10193 updatedSettings = true; 10194 } 10195 10196 } catch (PackageManagerException e) { 10197 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10198 } 10199 10200 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10201 // Re installation failed. Restore old information 10202 // Remove new pkg information 10203 if (newPackage != null) { 10204 removeInstalledPackageLI(newPackage, true); 10205 } 10206 // Add back the old system package 10207 try { 10208 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10209 } catch (PackageManagerException e) { 10210 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10211 } 10212 // Restore the old system information in Settings 10213 synchronized (mPackages) { 10214 if (disabledSystem) { 10215 mSettings.enableSystemPackageLPw(packageName); 10216 } 10217 if (updatedSettings) { 10218 mSettings.setInstallerPackageName(packageName, 10219 oldPkgSetting.installerPackageName); 10220 } 10221 mSettings.writeLPr(); 10222 } 10223 } 10224 } 10225 10226 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10227 int[] allUsers, boolean[] perUserInstalled, 10228 PackageInstalledInfo res) { 10229 String pkgName = newPackage.packageName; 10230 synchronized (mPackages) { 10231 //write settings. the installStatus will be incomplete at this stage. 10232 //note that the new package setting would have already been 10233 //added to mPackages. It hasn't been persisted yet. 10234 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10235 mSettings.writeLPr(); 10236 } 10237 10238 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10239 10240 synchronized (mPackages) { 10241 updatePermissionsLPw(newPackage.packageName, newPackage, 10242 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10243 ? UPDATE_PERMISSIONS_ALL : 0)); 10244 // For system-bundled packages, we assume that installing an upgraded version 10245 // of the package implies that the user actually wants to run that new code, 10246 // so we enable the package. 10247 if (isSystemApp(newPackage)) { 10248 // NB: implicit assumption that system package upgrades apply to all users 10249 if (DEBUG_INSTALL) { 10250 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10251 } 10252 PackageSetting ps = mSettings.mPackages.get(pkgName); 10253 if (ps != null) { 10254 if (res.origUsers != null) { 10255 for (int userHandle : res.origUsers) { 10256 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10257 userHandle, installerPackageName); 10258 } 10259 } 10260 // Also convey the prior install/uninstall state 10261 if (allUsers != null && perUserInstalled != null) { 10262 for (int i = 0; i < allUsers.length; i++) { 10263 if (DEBUG_INSTALL) { 10264 Slog.d(TAG, " user " + allUsers[i] 10265 + " => " + perUserInstalled[i]); 10266 } 10267 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10268 } 10269 // these install state changes will be persisted in the 10270 // upcoming call to mSettings.writeLPr(). 10271 } 10272 } 10273 } 10274 res.name = pkgName; 10275 res.uid = newPackage.applicationInfo.uid; 10276 res.pkg = newPackage; 10277 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10278 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10279 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10280 //to update install status 10281 mSettings.writeLPr(); 10282 } 10283 } 10284 10285 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10286 final int installFlags = args.installFlags; 10287 String installerPackageName = args.installerPackageName; 10288 File tmpPackageFile = new File(args.getCodePath()); 10289 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10290 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10291 boolean replace = false; 10292 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10293 // Result object to be returned 10294 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10295 10296 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10297 // Retrieve PackageSettings and parse package 10298 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10299 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10300 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10301 PackageParser pp = new PackageParser(); 10302 pp.setSeparateProcesses(mSeparateProcesses); 10303 pp.setDisplayMetrics(mMetrics); 10304 10305 final PackageParser.Package pkg; 10306 try { 10307 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10308 } catch (PackageParserException e) { 10309 res.setError("Failed parse during installPackageLI", e); 10310 return; 10311 } 10312 10313 // Mark that we have an install time CPU ABI override. 10314 pkg.cpuAbiOverride = args.abiOverride; 10315 10316 String pkgName = res.name = pkg.packageName; 10317 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10318 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10319 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10320 return; 10321 } 10322 } 10323 10324 try { 10325 pp.collectCertificates(pkg, parseFlags); 10326 pp.collectManifestDigest(pkg); 10327 } catch (PackageParserException e) { 10328 res.setError("Failed collect during installPackageLI", e); 10329 return; 10330 } 10331 10332 /* If the installer passed in a manifest digest, compare it now. */ 10333 if (args.manifestDigest != null) { 10334 if (DEBUG_INSTALL) { 10335 final String parsedManifest = pkg.manifestDigest == null ? "null" 10336 : pkg.manifestDigest.toString(); 10337 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10338 + parsedManifest); 10339 } 10340 10341 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10342 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10343 return; 10344 } 10345 } else if (DEBUG_INSTALL) { 10346 final String parsedManifest = pkg.manifestDigest == null 10347 ? "null" : pkg.manifestDigest.toString(); 10348 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10349 } 10350 10351 // Get rid of all references to package scan path via parser. 10352 pp = null; 10353 String oldCodePath = null; 10354 boolean systemApp = false; 10355 synchronized (mPackages) { 10356 // Check if installing already existing package 10357 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10358 String oldName = mSettings.mRenamedPackages.get(pkgName); 10359 if (pkg.mOriginalPackages != null 10360 && pkg.mOriginalPackages.contains(oldName) 10361 && mPackages.containsKey(oldName)) { 10362 // This package is derived from an original package, 10363 // and this device has been updating from that original 10364 // name. We must continue using the original name, so 10365 // rename the new package here. 10366 pkg.setPackageName(oldName); 10367 pkgName = pkg.packageName; 10368 replace = true; 10369 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10370 + oldName + " pkgName=" + pkgName); 10371 } else if (mPackages.containsKey(pkgName)) { 10372 // This package, under its official name, already exists 10373 // on the device; we should replace it. 10374 replace = true; 10375 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10376 } 10377 } 10378 10379 PackageSetting ps = mSettings.mPackages.get(pkgName); 10380 if (ps != null) { 10381 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10382 10383 // Quick sanity check that we're signed correctly if updating; 10384 // we'll check this again later when scanning, but we want to 10385 // bail early here before tripping over redefined permissions. 10386 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10387 try { 10388 verifySignaturesLP(ps, pkg); 10389 } catch (PackageManagerException e) { 10390 res.setError(e.error, e.getMessage()); 10391 return; 10392 } 10393 } else { 10394 if (!checkUpgradeKeySetLP(ps, pkg)) { 10395 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 10396 + pkg.packageName + " upgrade keys do not match the " 10397 + "previously installed version"); 10398 return; 10399 } 10400 } 10401 10402 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10403 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10404 systemApp = (ps.pkg.applicationInfo.flags & 10405 ApplicationInfo.FLAG_SYSTEM) != 0; 10406 } 10407 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10408 } 10409 10410 // Check whether the newly-scanned package wants to define an already-defined perm 10411 int N = pkg.permissions.size(); 10412 for (int i = N-1; i >= 0; i--) { 10413 PackageParser.Permission perm = pkg.permissions.get(i); 10414 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10415 if (bp != null) { 10416 // If the defining package is signed with our cert, it's okay. This 10417 // also includes the "updating the same package" case, of course. 10418 // "updating same package" could also involve key-rotation. 10419 final boolean sigsOk; 10420 if (!bp.sourcePackage.equals(pkg.packageName) 10421 || !(bp.packageSetting instanceof PackageSetting) 10422 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10423 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10424 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10425 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10426 } else { 10427 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10428 } 10429 if (!sigsOk) { 10430 // If the owning package is the system itself, we log but allow 10431 // install to proceed; we fail the install on all other permission 10432 // redefinitions. 10433 if (!bp.sourcePackage.equals("android")) { 10434 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10435 + pkg.packageName + " attempting to redeclare permission " 10436 + perm.info.name + " already owned by " + bp.sourcePackage); 10437 res.origPermission = perm.info.name; 10438 res.origPackage = bp.sourcePackage; 10439 return; 10440 } else { 10441 Slog.w(TAG, "Package " + pkg.packageName 10442 + " attempting to redeclare system permission " 10443 + perm.info.name + "; ignoring new declaration"); 10444 pkg.permissions.remove(i); 10445 } 10446 } 10447 } 10448 } 10449 10450 } 10451 10452 if (systemApp && onSd) { 10453 // Disable updates to system apps on sdcard 10454 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10455 "Cannot install updates to system apps on sdcard"); 10456 return; 10457 } 10458 10459 // Run dexopt before old package gets removed, to minimize time when app is not available 10460 int result = mPackageDexOptimizer 10461 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 10462 false /* defer */, false /* inclDependencies */); 10463 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 10464 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 10465 return; 10466 } 10467 10468 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10469 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10470 return; 10471 } 10472 10473 // Call with SCAN_NO_DEX, since dexopt has already been made 10474 if (replace) { 10475 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING | SCAN_NO_DEX, args.user, 10476 installerPackageName, res); 10477 } else { 10478 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES 10479 | SCAN_NO_DEX, args.user, installerPackageName, res); 10480 } 10481 synchronized (mPackages) { 10482 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10483 if (ps != null) { 10484 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10485 } 10486 } 10487 } 10488 10489 private static boolean isMultiArch(PackageSetting ps) { 10490 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10491 } 10492 10493 private static boolean isMultiArch(ApplicationInfo info) { 10494 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10495 } 10496 10497 private static boolean isExternal(PackageParser.Package pkg) { 10498 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10499 } 10500 10501 private static boolean isExternal(PackageSetting ps) { 10502 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10503 } 10504 10505 private static boolean isExternal(ApplicationInfo info) { 10506 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10507 } 10508 10509 private static boolean isSystemApp(PackageParser.Package pkg) { 10510 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10511 } 10512 10513 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10514 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 10515 } 10516 10517 private static boolean isSystemApp(PackageSetting ps) { 10518 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10519 } 10520 10521 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10522 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10523 } 10524 10525 private int packageFlagsToInstallFlags(PackageSetting ps) { 10526 int installFlags = 0; 10527 if (isExternal(ps)) { 10528 installFlags |= PackageManager.INSTALL_EXTERNAL; 10529 } 10530 if (ps.isForwardLocked()) { 10531 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10532 } 10533 return installFlags; 10534 } 10535 10536 private void deleteTempPackageFiles() { 10537 final FilenameFilter filter = new FilenameFilter() { 10538 public boolean accept(File dir, String name) { 10539 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10540 } 10541 }; 10542 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10543 file.delete(); 10544 } 10545 } 10546 10547 @Override 10548 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10549 int flags) { 10550 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10551 flags); 10552 } 10553 10554 @Override 10555 public void deletePackage(final String packageName, 10556 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10557 mContext.enforceCallingOrSelfPermission( 10558 android.Manifest.permission.DELETE_PACKAGES, null); 10559 final int uid = Binder.getCallingUid(); 10560 if (UserHandle.getUserId(uid) != userId) { 10561 mContext.enforceCallingPermission( 10562 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10563 "deletePackage for user " + userId); 10564 } 10565 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10566 try { 10567 observer.onPackageDeleted(packageName, 10568 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10569 } catch (RemoteException re) { 10570 } 10571 return; 10572 } 10573 10574 boolean uninstallBlocked = false; 10575 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10576 int[] users = sUserManager.getUserIds(); 10577 for (int i = 0; i < users.length; ++i) { 10578 if (getBlockUninstallForUser(packageName, users[i])) { 10579 uninstallBlocked = true; 10580 break; 10581 } 10582 } 10583 } else { 10584 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10585 } 10586 if (uninstallBlocked) { 10587 try { 10588 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10589 null); 10590 } catch (RemoteException re) { 10591 } 10592 return; 10593 } 10594 10595 if (DEBUG_REMOVE) { 10596 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10597 } 10598 // Queue up an async operation since the package deletion may take a little while. 10599 mHandler.post(new Runnable() { 10600 public void run() { 10601 mHandler.removeCallbacks(this); 10602 final int returnCode = deletePackageX(packageName, userId, flags); 10603 if (observer != null) { 10604 try { 10605 observer.onPackageDeleted(packageName, returnCode, null); 10606 } catch (RemoteException e) { 10607 Log.i(TAG, "Observer no longer exists."); 10608 } //end catch 10609 } //end if 10610 } //end run 10611 }); 10612 } 10613 10614 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10615 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10616 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10617 try { 10618 if (dpm != null) { 10619 if (dpm.isDeviceOwner(packageName)) { 10620 return true; 10621 } 10622 int[] users; 10623 if (userId == UserHandle.USER_ALL) { 10624 users = sUserManager.getUserIds(); 10625 } else { 10626 users = new int[]{userId}; 10627 } 10628 for (int i = 0; i < users.length; ++i) { 10629 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10630 return true; 10631 } 10632 } 10633 } 10634 } catch (RemoteException e) { 10635 } 10636 return false; 10637 } 10638 10639 /** 10640 * This method is an internal method that could be get invoked either 10641 * to delete an installed package or to clean up a failed installation. 10642 * After deleting an installed package, a broadcast is sent to notify any 10643 * listeners that the package has been installed. For cleaning up a failed 10644 * installation, the broadcast is not necessary since the package's 10645 * installation wouldn't have sent the initial broadcast either 10646 * The key steps in deleting a package are 10647 * deleting the package information in internal structures like mPackages, 10648 * deleting the packages base directories through installd 10649 * updating mSettings to reflect current status 10650 * persisting settings for later use 10651 * sending a broadcast if necessary 10652 */ 10653 private int deletePackageX(String packageName, int userId, int flags) { 10654 final PackageRemovedInfo info = new PackageRemovedInfo(); 10655 final boolean res; 10656 10657 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10658 ? UserHandle.ALL : new UserHandle(userId); 10659 10660 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10661 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10662 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10663 } 10664 10665 boolean removedForAllUsers = false; 10666 boolean systemUpdate = false; 10667 10668 // for the uninstall-updates case and restricted profiles, remember the per- 10669 // userhandle installed state 10670 int[] allUsers; 10671 boolean[] perUserInstalled; 10672 synchronized (mPackages) { 10673 PackageSetting ps = mSettings.mPackages.get(packageName); 10674 allUsers = sUserManager.getUserIds(); 10675 perUserInstalled = new boolean[allUsers.length]; 10676 for (int i = 0; i < allUsers.length; i++) { 10677 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10678 } 10679 } 10680 10681 synchronized (mInstallLock) { 10682 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10683 res = deletePackageLI(packageName, removeForUser, 10684 true, allUsers, perUserInstalled, 10685 flags | REMOVE_CHATTY, info, true); 10686 systemUpdate = info.isRemovedPackageSystemUpdate; 10687 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10688 removedForAllUsers = true; 10689 } 10690 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10691 + " removedForAllUsers=" + removedForAllUsers); 10692 } 10693 10694 if (res) { 10695 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10696 10697 // If the removed package was a system update, the old system package 10698 // was re-enabled; we need to broadcast this information 10699 if (systemUpdate) { 10700 Bundle extras = new Bundle(1); 10701 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10702 ? info.removedAppId : info.uid); 10703 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10704 10705 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10706 extras, null, null, null); 10707 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10708 extras, null, null, null); 10709 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10710 null, packageName, null, null); 10711 } 10712 } 10713 // Force a gc here. 10714 Runtime.getRuntime().gc(); 10715 // Delete the resources here after sending the broadcast to let 10716 // other processes clean up before deleting resources. 10717 if (info.args != null) { 10718 synchronized (mInstallLock) { 10719 info.args.doPostDeleteLI(true); 10720 } 10721 } 10722 10723 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10724 } 10725 10726 static class PackageRemovedInfo { 10727 String removedPackage; 10728 int uid = -1; 10729 int removedAppId = -1; 10730 int[] removedUsers = null; 10731 boolean isRemovedPackageSystemUpdate = false; 10732 // Clean up resources deleted packages. 10733 InstallArgs args = null; 10734 10735 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10736 Bundle extras = new Bundle(1); 10737 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10738 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10739 if (replacing) { 10740 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10741 } 10742 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10743 if (removedPackage != null) { 10744 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10745 extras, null, null, removedUsers); 10746 if (fullRemove && !replacing) { 10747 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10748 extras, null, null, removedUsers); 10749 } 10750 } 10751 if (removedAppId >= 0) { 10752 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10753 removedUsers); 10754 } 10755 } 10756 } 10757 10758 /* 10759 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10760 * flag is not set, the data directory is removed as well. 10761 * make sure this flag is set for partially installed apps. If not its meaningless to 10762 * delete a partially installed application. 10763 */ 10764 private void removePackageDataLI(PackageSetting ps, 10765 int[] allUserHandles, boolean[] perUserInstalled, 10766 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10767 String packageName = ps.name; 10768 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10769 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10770 // Retrieve object to delete permissions for shared user later on 10771 final PackageSetting deletedPs; 10772 // reader 10773 synchronized (mPackages) { 10774 deletedPs = mSettings.mPackages.get(packageName); 10775 if (outInfo != null) { 10776 outInfo.removedPackage = packageName; 10777 outInfo.removedUsers = deletedPs != null 10778 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10779 : null; 10780 } 10781 } 10782 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10783 removeDataDirsLI(packageName); 10784 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10785 } 10786 // writer 10787 synchronized (mPackages) { 10788 if (deletedPs != null) { 10789 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10790 if (outInfo != null) { 10791 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10792 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10793 } 10794 if (deletedPs != null) { 10795 updatePermissionsLPw(deletedPs.name, null, 0); 10796 if (deletedPs.sharedUser != null) { 10797 // remove permissions associated with package 10798 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10799 } 10800 } 10801 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10802 } 10803 // make sure to preserve per-user disabled state if this removal was just 10804 // a downgrade of a system app to the factory package 10805 if (allUserHandles != null && perUserInstalled != null) { 10806 if (DEBUG_REMOVE) { 10807 Slog.d(TAG, "Propagating install state across downgrade"); 10808 } 10809 for (int i = 0; i < allUserHandles.length; i++) { 10810 if (DEBUG_REMOVE) { 10811 Slog.d(TAG, " user " + allUserHandles[i] 10812 + " => " + perUserInstalled[i]); 10813 } 10814 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10815 } 10816 } 10817 } 10818 // can downgrade to reader 10819 if (writeSettings) { 10820 // Save settings now 10821 mSettings.writeLPr(); 10822 } 10823 } 10824 if (outInfo != null) { 10825 // A user ID was deleted here. Go through all users and remove it 10826 // from KeyStore. 10827 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10828 } 10829 } 10830 10831 static boolean locationIsPrivileged(File path) { 10832 try { 10833 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10834 .getCanonicalPath(); 10835 return path.getCanonicalPath().startsWith(privilegedAppDir); 10836 } catch (IOException e) { 10837 Slog.e(TAG, "Unable to access code path " + path); 10838 } 10839 return false; 10840 } 10841 10842 /* 10843 * Tries to delete system package. 10844 */ 10845 private boolean deleteSystemPackageLI(PackageSetting newPs, 10846 int[] allUserHandles, boolean[] perUserInstalled, 10847 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10848 final boolean applyUserRestrictions 10849 = (allUserHandles != null) && (perUserInstalled != null); 10850 PackageSetting disabledPs = null; 10851 // Confirm if the system package has been updated 10852 // An updated system app can be deleted. This will also have to restore 10853 // the system pkg from system partition 10854 // reader 10855 synchronized (mPackages) { 10856 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10857 } 10858 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10859 + " disabledPs=" + disabledPs); 10860 if (disabledPs == null) { 10861 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10862 return false; 10863 } else if (DEBUG_REMOVE) { 10864 Slog.d(TAG, "Deleting system pkg from data partition"); 10865 } 10866 if (DEBUG_REMOVE) { 10867 if (applyUserRestrictions) { 10868 Slog.d(TAG, "Remembering install states:"); 10869 for (int i = 0; i < allUserHandles.length; i++) { 10870 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10871 } 10872 } 10873 } 10874 // Delete the updated package 10875 outInfo.isRemovedPackageSystemUpdate = true; 10876 if (disabledPs.versionCode < newPs.versionCode) { 10877 // Delete data for downgrades 10878 flags &= ~PackageManager.DELETE_KEEP_DATA; 10879 } else { 10880 // Preserve data by setting flag 10881 flags |= PackageManager.DELETE_KEEP_DATA; 10882 } 10883 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10884 allUserHandles, perUserInstalled, outInfo, writeSettings); 10885 if (!ret) { 10886 return false; 10887 } 10888 // writer 10889 synchronized (mPackages) { 10890 // Reinstate the old system package 10891 mSettings.enableSystemPackageLPw(newPs.name); 10892 // Remove any native libraries from the upgraded package. 10893 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10894 } 10895 // Install the system package 10896 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10897 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10898 if (locationIsPrivileged(disabledPs.codePath)) { 10899 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10900 } 10901 10902 final PackageParser.Package newPkg; 10903 try { 10904 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10905 } catch (PackageManagerException e) { 10906 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10907 return false; 10908 } 10909 10910 // writer 10911 synchronized (mPackages) { 10912 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10913 updatePermissionsLPw(newPkg.packageName, newPkg, 10914 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10915 if (applyUserRestrictions) { 10916 if (DEBUG_REMOVE) { 10917 Slog.d(TAG, "Propagating install state across reinstall"); 10918 } 10919 for (int i = 0; i < allUserHandles.length; i++) { 10920 if (DEBUG_REMOVE) { 10921 Slog.d(TAG, " user " + allUserHandles[i] 10922 + " => " + perUserInstalled[i]); 10923 } 10924 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10925 } 10926 // Regardless of writeSettings we need to ensure that this restriction 10927 // state propagation is persisted 10928 mSettings.writeAllUsersPackageRestrictionsLPr(); 10929 } 10930 // can downgrade to reader here 10931 if (writeSettings) { 10932 mSettings.writeLPr(); 10933 } 10934 } 10935 return true; 10936 } 10937 10938 private boolean deleteInstalledPackageLI(PackageSetting ps, 10939 boolean deleteCodeAndResources, int flags, 10940 int[] allUserHandles, boolean[] perUserInstalled, 10941 PackageRemovedInfo outInfo, boolean writeSettings) { 10942 if (outInfo != null) { 10943 outInfo.uid = ps.appId; 10944 } 10945 10946 // Delete package data from internal structures and also remove data if flag is set 10947 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10948 10949 // Delete application code and resources 10950 if (deleteCodeAndResources && (outInfo != null)) { 10951 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10952 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10953 getAppDexInstructionSets(ps)); 10954 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10955 } 10956 return true; 10957 } 10958 10959 @Override 10960 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10961 int userId) { 10962 mContext.enforceCallingOrSelfPermission( 10963 android.Manifest.permission.DELETE_PACKAGES, null); 10964 synchronized (mPackages) { 10965 PackageSetting ps = mSettings.mPackages.get(packageName); 10966 if (ps == null) { 10967 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10968 return false; 10969 } 10970 if (!ps.getInstalled(userId)) { 10971 // Can't block uninstall for an app that is not installed or enabled. 10972 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10973 return false; 10974 } 10975 ps.setBlockUninstall(blockUninstall, userId); 10976 mSettings.writePackageRestrictionsLPr(userId); 10977 } 10978 return true; 10979 } 10980 10981 @Override 10982 public boolean getBlockUninstallForUser(String packageName, int userId) { 10983 synchronized (mPackages) { 10984 PackageSetting ps = mSettings.mPackages.get(packageName); 10985 if (ps == null) { 10986 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10987 return false; 10988 } 10989 return ps.getBlockUninstall(userId); 10990 } 10991 } 10992 10993 /* 10994 * This method handles package deletion in general 10995 */ 10996 private boolean deletePackageLI(String packageName, UserHandle user, 10997 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10998 int flags, PackageRemovedInfo outInfo, 10999 boolean writeSettings) { 11000 if (packageName == null) { 11001 Slog.w(TAG, "Attempt to delete null packageName."); 11002 return false; 11003 } 11004 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11005 PackageSetting ps; 11006 boolean dataOnly = false; 11007 int removeUser = -1; 11008 int appId = -1; 11009 synchronized (mPackages) { 11010 ps = mSettings.mPackages.get(packageName); 11011 if (ps == null) { 11012 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11013 return false; 11014 } 11015 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11016 && user.getIdentifier() != UserHandle.USER_ALL) { 11017 // The caller is asking that the package only be deleted for a single 11018 // user. To do this, we just mark its uninstalled state and delete 11019 // its data. If this is a system app, we only allow this to happen if 11020 // they have set the special DELETE_SYSTEM_APP which requests different 11021 // semantics than normal for uninstalling system apps. 11022 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11023 ps.setUserState(user.getIdentifier(), 11024 COMPONENT_ENABLED_STATE_DEFAULT, 11025 false, //installed 11026 true, //stopped 11027 true, //notLaunched 11028 false, //hidden 11029 null, null, null, 11030 false // blockUninstall 11031 ); 11032 if (!isSystemApp(ps)) { 11033 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11034 // Other user still have this package installed, so all 11035 // we need to do is clear this user's data and save that 11036 // it is uninstalled. 11037 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11038 removeUser = user.getIdentifier(); 11039 appId = ps.appId; 11040 mSettings.writePackageRestrictionsLPr(removeUser); 11041 } else { 11042 // We need to set it back to 'installed' so the uninstall 11043 // broadcasts will be sent correctly. 11044 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11045 ps.setInstalled(true, user.getIdentifier()); 11046 } 11047 } else { 11048 // This is a system app, so we assume that the 11049 // other users still have this package installed, so all 11050 // we need to do is clear this user's data and save that 11051 // it is uninstalled. 11052 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11053 removeUser = user.getIdentifier(); 11054 appId = ps.appId; 11055 mSettings.writePackageRestrictionsLPr(removeUser); 11056 } 11057 } 11058 } 11059 11060 if (removeUser >= 0) { 11061 // From above, we determined that we are deleting this only 11062 // for a single user. Continue the work here. 11063 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11064 if (outInfo != null) { 11065 outInfo.removedPackage = packageName; 11066 outInfo.removedAppId = appId; 11067 outInfo.removedUsers = new int[] {removeUser}; 11068 } 11069 mInstaller.clearUserData(packageName, removeUser); 11070 removeKeystoreDataIfNeeded(removeUser, appId); 11071 schedulePackageCleaning(packageName, removeUser, false); 11072 return true; 11073 } 11074 11075 if (dataOnly) { 11076 // Delete application data first 11077 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11078 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11079 return true; 11080 } 11081 11082 boolean ret = false; 11083 if (isSystemApp(ps)) { 11084 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11085 // When an updated system application is deleted we delete the existing resources as well and 11086 // fall back to existing code in system partition 11087 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11088 flags, outInfo, writeSettings); 11089 } else { 11090 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11091 // Kill application pre-emptively especially for apps on sd. 11092 killApplication(packageName, ps.appId, "uninstall pkg"); 11093 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11094 allUserHandles, perUserInstalled, 11095 outInfo, writeSettings); 11096 } 11097 11098 return ret; 11099 } 11100 11101 private final class ClearStorageConnection implements ServiceConnection { 11102 IMediaContainerService mContainerService; 11103 11104 @Override 11105 public void onServiceConnected(ComponentName name, IBinder service) { 11106 synchronized (this) { 11107 mContainerService = IMediaContainerService.Stub.asInterface(service); 11108 notifyAll(); 11109 } 11110 } 11111 11112 @Override 11113 public void onServiceDisconnected(ComponentName name) { 11114 } 11115 } 11116 11117 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11118 final boolean mounted; 11119 if (Environment.isExternalStorageEmulated()) { 11120 mounted = true; 11121 } else { 11122 final String status = Environment.getExternalStorageState(); 11123 11124 mounted = status.equals(Environment.MEDIA_MOUNTED) 11125 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11126 } 11127 11128 if (!mounted) { 11129 return; 11130 } 11131 11132 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11133 int[] users; 11134 if (userId == UserHandle.USER_ALL) { 11135 users = sUserManager.getUserIds(); 11136 } else { 11137 users = new int[] { userId }; 11138 } 11139 final ClearStorageConnection conn = new ClearStorageConnection(); 11140 if (mContext.bindServiceAsUser( 11141 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11142 try { 11143 for (int curUser : users) { 11144 long timeout = SystemClock.uptimeMillis() + 5000; 11145 synchronized (conn) { 11146 long now = SystemClock.uptimeMillis(); 11147 while (conn.mContainerService == null && now < timeout) { 11148 try { 11149 conn.wait(timeout - now); 11150 } catch (InterruptedException e) { 11151 } 11152 } 11153 } 11154 if (conn.mContainerService == null) { 11155 return; 11156 } 11157 11158 final UserEnvironment userEnv = new UserEnvironment(curUser); 11159 clearDirectory(conn.mContainerService, 11160 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11161 if (allData) { 11162 clearDirectory(conn.mContainerService, 11163 userEnv.buildExternalStorageAppDataDirs(packageName)); 11164 clearDirectory(conn.mContainerService, 11165 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11166 } 11167 } 11168 } finally { 11169 mContext.unbindService(conn); 11170 } 11171 } 11172 } 11173 11174 @Override 11175 public void clearApplicationUserData(final String packageName, 11176 final IPackageDataObserver observer, final int userId) { 11177 mContext.enforceCallingOrSelfPermission( 11178 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11179 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11180 // Queue up an async operation since the package deletion may take a little while. 11181 mHandler.post(new Runnable() { 11182 public void run() { 11183 mHandler.removeCallbacks(this); 11184 final boolean succeeded; 11185 synchronized (mInstallLock) { 11186 succeeded = clearApplicationUserDataLI(packageName, userId); 11187 } 11188 clearExternalStorageDataSync(packageName, userId, true); 11189 if (succeeded) { 11190 // invoke DeviceStorageMonitor's update method to clear any notifications 11191 DeviceStorageMonitorInternal 11192 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11193 if (dsm != null) { 11194 dsm.checkMemory(); 11195 } 11196 } 11197 if(observer != null) { 11198 try { 11199 observer.onRemoveCompleted(packageName, succeeded); 11200 } catch (RemoteException e) { 11201 Log.i(TAG, "Observer no longer exists."); 11202 } 11203 } //end if observer 11204 } //end run 11205 }); 11206 } 11207 11208 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11209 if (packageName == null) { 11210 Slog.w(TAG, "Attempt to delete null packageName."); 11211 return false; 11212 } 11213 11214 // Try finding details about the requested package 11215 PackageParser.Package pkg; 11216 synchronized (mPackages) { 11217 pkg = mPackages.get(packageName); 11218 if (pkg == null) { 11219 final PackageSetting ps = mSettings.mPackages.get(packageName); 11220 if (ps != null) { 11221 pkg = ps.pkg; 11222 } 11223 } 11224 } 11225 11226 if (pkg == null) { 11227 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11228 } 11229 11230 // Always delete data directories for package, even if we found no other 11231 // record of app. This helps users recover from UID mismatches without 11232 // resorting to a full data wipe. 11233 int retCode = mInstaller.clearUserData(packageName, userId); 11234 if (retCode < 0) { 11235 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11236 return false; 11237 } 11238 11239 if (pkg == null) { 11240 return false; 11241 } 11242 11243 if (pkg != null && pkg.applicationInfo != null) { 11244 final int appId = pkg.applicationInfo.uid; 11245 removeKeystoreDataIfNeeded(userId, appId); 11246 } 11247 11248 // Create a native library symlink only if we have native libraries 11249 // and if the native libraries are 32 bit libraries. We do not provide 11250 // this symlink for 64 bit libraries. 11251 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11252 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11253 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11254 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11255 Slog.w(TAG, "Failed linking native library dir"); 11256 return false; 11257 } 11258 } 11259 11260 return true; 11261 } 11262 11263 /** 11264 * Remove entries from the keystore daemon. Will only remove it if the 11265 * {@code appId} is valid. 11266 */ 11267 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11268 if (appId < 0) { 11269 return; 11270 } 11271 11272 final KeyStore keyStore = KeyStore.getInstance(); 11273 if (keyStore != null) { 11274 if (userId == UserHandle.USER_ALL) { 11275 for (final int individual : sUserManager.getUserIds()) { 11276 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11277 } 11278 } else { 11279 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11280 } 11281 } else { 11282 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11283 } 11284 } 11285 11286 @Override 11287 public void deleteApplicationCacheFiles(final String packageName, 11288 final IPackageDataObserver observer) { 11289 mContext.enforceCallingOrSelfPermission( 11290 android.Manifest.permission.DELETE_CACHE_FILES, null); 11291 // Queue up an async operation since the package deletion may take a little while. 11292 final int userId = UserHandle.getCallingUserId(); 11293 mHandler.post(new Runnable() { 11294 public void run() { 11295 mHandler.removeCallbacks(this); 11296 final boolean succeded; 11297 synchronized (mInstallLock) { 11298 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11299 } 11300 clearExternalStorageDataSync(packageName, userId, false); 11301 if(observer != null) { 11302 try { 11303 observer.onRemoveCompleted(packageName, succeded); 11304 } catch (RemoteException e) { 11305 Log.i(TAG, "Observer no longer exists."); 11306 } 11307 } //end if observer 11308 } //end run 11309 }); 11310 } 11311 11312 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11313 if (packageName == null) { 11314 Slog.w(TAG, "Attempt to delete null packageName."); 11315 return false; 11316 } 11317 PackageParser.Package p; 11318 synchronized (mPackages) { 11319 p = mPackages.get(packageName); 11320 } 11321 if (p == null) { 11322 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11323 return false; 11324 } 11325 final ApplicationInfo applicationInfo = p.applicationInfo; 11326 if (applicationInfo == null) { 11327 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11328 return false; 11329 } 11330 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11331 if (retCode < 0) { 11332 Slog.w(TAG, "Couldn't remove cache files for package: " 11333 + packageName + " u" + userId); 11334 return false; 11335 } 11336 return true; 11337 } 11338 11339 @Override 11340 public void getPackageSizeInfo(final String packageName, int userHandle, 11341 final IPackageStatsObserver observer) { 11342 mContext.enforceCallingOrSelfPermission( 11343 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11344 if (packageName == null) { 11345 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11346 } 11347 11348 PackageStats stats = new PackageStats(packageName, userHandle); 11349 11350 /* 11351 * Queue up an async operation since the package measurement may take a 11352 * little while. 11353 */ 11354 Message msg = mHandler.obtainMessage(INIT_COPY); 11355 msg.obj = new MeasureParams(stats, observer); 11356 mHandler.sendMessage(msg); 11357 } 11358 11359 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11360 PackageStats pStats) { 11361 if (packageName == null) { 11362 Slog.w(TAG, "Attempt to get size of null packageName."); 11363 return false; 11364 } 11365 PackageParser.Package p; 11366 boolean dataOnly = false; 11367 String libDirRoot = null; 11368 String asecPath = null; 11369 PackageSetting ps = null; 11370 synchronized (mPackages) { 11371 p = mPackages.get(packageName); 11372 ps = mSettings.mPackages.get(packageName); 11373 if(p == null) { 11374 dataOnly = true; 11375 if((ps == null) || (ps.pkg == null)) { 11376 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11377 return false; 11378 } 11379 p = ps.pkg; 11380 } 11381 if (ps != null) { 11382 libDirRoot = ps.legacyNativeLibraryPathString; 11383 } 11384 if (p != null && (isExternal(p) || p.isForwardLocked())) { 11385 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11386 if (secureContainerId != null) { 11387 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11388 } 11389 } 11390 } 11391 String publicSrcDir = null; 11392 if(!dataOnly) { 11393 final ApplicationInfo applicationInfo = p.applicationInfo; 11394 if (applicationInfo == null) { 11395 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11396 return false; 11397 } 11398 if (p.isForwardLocked()) { 11399 publicSrcDir = applicationInfo.getBaseResourcePath(); 11400 } 11401 } 11402 // TODO: extend to measure size of split APKs 11403 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11404 // not just the first level. 11405 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11406 // just the primary. 11407 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11408 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11409 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11410 if (res < 0) { 11411 return false; 11412 } 11413 11414 // Fix-up for forward-locked applications in ASEC containers. 11415 if (!isExternal(p)) { 11416 pStats.codeSize += pStats.externalCodeSize; 11417 pStats.externalCodeSize = 0L; 11418 } 11419 11420 return true; 11421 } 11422 11423 11424 @Override 11425 public void addPackageToPreferred(String packageName) { 11426 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11427 } 11428 11429 @Override 11430 public void removePackageFromPreferred(String packageName) { 11431 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11432 } 11433 11434 @Override 11435 public List<PackageInfo> getPreferredPackages(int flags) { 11436 return new ArrayList<PackageInfo>(); 11437 } 11438 11439 private int getUidTargetSdkVersionLockedLPr(int uid) { 11440 Object obj = mSettings.getUserIdLPr(uid); 11441 if (obj instanceof SharedUserSetting) { 11442 final SharedUserSetting sus = (SharedUserSetting) obj; 11443 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11444 final Iterator<PackageSetting> it = sus.packages.iterator(); 11445 while (it.hasNext()) { 11446 final PackageSetting ps = it.next(); 11447 if (ps.pkg != null) { 11448 int v = ps.pkg.applicationInfo.targetSdkVersion; 11449 if (v < vers) vers = v; 11450 } 11451 } 11452 return vers; 11453 } else if (obj instanceof PackageSetting) { 11454 final PackageSetting ps = (PackageSetting) obj; 11455 if (ps.pkg != null) { 11456 return ps.pkg.applicationInfo.targetSdkVersion; 11457 } 11458 } 11459 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11460 } 11461 11462 @Override 11463 public void addPreferredActivity(IntentFilter filter, int match, 11464 ComponentName[] set, ComponentName activity, int userId) { 11465 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11466 "Adding preferred"); 11467 } 11468 11469 private void addPreferredActivityInternal(IntentFilter filter, int match, 11470 ComponentName[] set, ComponentName activity, boolean always, int userId, 11471 String opname) { 11472 // writer 11473 int callingUid = Binder.getCallingUid(); 11474 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11475 if (filter.countActions() == 0) { 11476 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11477 return; 11478 } 11479 synchronized (mPackages) { 11480 if (mContext.checkCallingOrSelfPermission( 11481 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11482 != PackageManager.PERMISSION_GRANTED) { 11483 if (getUidTargetSdkVersionLockedLPr(callingUid) 11484 < Build.VERSION_CODES.FROYO) { 11485 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11486 + callingUid); 11487 return; 11488 } 11489 mContext.enforceCallingOrSelfPermission( 11490 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11491 } 11492 11493 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11494 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11495 + userId + ":"); 11496 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11497 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11498 scheduleWritePackageRestrictionsLocked(userId); 11499 } 11500 } 11501 11502 @Override 11503 public void replacePreferredActivity(IntentFilter filter, int match, 11504 ComponentName[] set, ComponentName activity, int userId) { 11505 if (filter.countActions() != 1) { 11506 throw new IllegalArgumentException( 11507 "replacePreferredActivity expects filter to have only 1 action."); 11508 } 11509 if (filter.countDataAuthorities() != 0 11510 || filter.countDataPaths() != 0 11511 || filter.countDataSchemes() > 1 11512 || filter.countDataTypes() != 0) { 11513 throw new IllegalArgumentException( 11514 "replacePreferredActivity expects filter to have no data authorities, " + 11515 "paths, or types; and at most one scheme."); 11516 } 11517 11518 final int callingUid = Binder.getCallingUid(); 11519 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11520 synchronized (mPackages) { 11521 if (mContext.checkCallingOrSelfPermission( 11522 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11523 != PackageManager.PERMISSION_GRANTED) { 11524 if (getUidTargetSdkVersionLockedLPr(callingUid) 11525 < Build.VERSION_CODES.FROYO) { 11526 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11527 + Binder.getCallingUid()); 11528 return; 11529 } 11530 mContext.enforceCallingOrSelfPermission( 11531 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11532 } 11533 11534 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11535 if (pir != null) { 11536 // Get all of the existing entries that exactly match this filter. 11537 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11538 if (existing != null && existing.size() == 1) { 11539 PreferredActivity cur = existing.get(0); 11540 if (DEBUG_PREFERRED) { 11541 Slog.i(TAG, "Checking replace of preferred:"); 11542 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11543 if (!cur.mPref.mAlways) { 11544 Slog.i(TAG, " -- CUR; not mAlways!"); 11545 } else { 11546 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11547 Slog.i(TAG, " -- CUR: mSet=" 11548 + Arrays.toString(cur.mPref.mSetComponents)); 11549 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11550 Slog.i(TAG, " -- NEW: mMatch=" 11551 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11552 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11553 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11554 } 11555 } 11556 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11557 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11558 && cur.mPref.sameSet(set)) { 11559 // Setting the preferred activity to what it happens to be already 11560 if (DEBUG_PREFERRED) { 11561 Slog.i(TAG, "Replacing with same preferred activity " 11562 + cur.mPref.mShortComponent + " for user " 11563 + userId + ":"); 11564 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11565 } 11566 return; 11567 } 11568 } 11569 11570 if (existing != null) { 11571 if (DEBUG_PREFERRED) { 11572 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11573 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11574 } 11575 for (int i = 0; i < existing.size(); i++) { 11576 PreferredActivity pa = existing.get(i); 11577 if (DEBUG_PREFERRED) { 11578 Slog.i(TAG, "Removing existing preferred activity " 11579 + pa.mPref.mComponent + ":"); 11580 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11581 } 11582 pir.removeFilter(pa); 11583 } 11584 } 11585 } 11586 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11587 "Replacing preferred"); 11588 } 11589 } 11590 11591 @Override 11592 public void clearPackagePreferredActivities(String packageName) { 11593 final int uid = Binder.getCallingUid(); 11594 // writer 11595 synchronized (mPackages) { 11596 PackageParser.Package pkg = mPackages.get(packageName); 11597 if (pkg == null || pkg.applicationInfo.uid != uid) { 11598 if (mContext.checkCallingOrSelfPermission( 11599 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11600 != PackageManager.PERMISSION_GRANTED) { 11601 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11602 < Build.VERSION_CODES.FROYO) { 11603 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11604 + Binder.getCallingUid()); 11605 return; 11606 } 11607 mContext.enforceCallingOrSelfPermission( 11608 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11609 } 11610 } 11611 11612 int user = UserHandle.getCallingUserId(); 11613 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11614 scheduleWritePackageRestrictionsLocked(user); 11615 } 11616 } 11617 } 11618 11619 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11620 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11621 ArrayList<PreferredActivity> removed = null; 11622 boolean changed = false; 11623 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11624 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11625 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11626 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11627 continue; 11628 } 11629 Iterator<PreferredActivity> it = pir.filterIterator(); 11630 while (it.hasNext()) { 11631 PreferredActivity pa = it.next(); 11632 // Mark entry for removal only if it matches the package name 11633 // and the entry is of type "always". 11634 if (packageName == null || 11635 (pa.mPref.mComponent.getPackageName().equals(packageName) 11636 && pa.mPref.mAlways)) { 11637 if (removed == null) { 11638 removed = new ArrayList<PreferredActivity>(); 11639 } 11640 removed.add(pa); 11641 } 11642 } 11643 if (removed != null) { 11644 for (int j=0; j<removed.size(); j++) { 11645 PreferredActivity pa = removed.get(j); 11646 pir.removeFilter(pa); 11647 } 11648 changed = true; 11649 } 11650 } 11651 return changed; 11652 } 11653 11654 @Override 11655 public void resetPreferredActivities(int userId) { 11656 /* TODO: Actually use userId. Why is it being passed in? */ 11657 mContext.enforceCallingOrSelfPermission( 11658 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11659 // writer 11660 synchronized (mPackages) { 11661 int user = UserHandle.getCallingUserId(); 11662 clearPackagePreferredActivitiesLPw(null, user); 11663 mSettings.readDefaultPreferredAppsLPw(this, user); 11664 scheduleWritePackageRestrictionsLocked(user); 11665 } 11666 } 11667 11668 @Override 11669 public int getPreferredActivities(List<IntentFilter> outFilters, 11670 List<ComponentName> outActivities, String packageName) { 11671 11672 int num = 0; 11673 final int userId = UserHandle.getCallingUserId(); 11674 // reader 11675 synchronized (mPackages) { 11676 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11677 if (pir != null) { 11678 final Iterator<PreferredActivity> it = pir.filterIterator(); 11679 while (it.hasNext()) { 11680 final PreferredActivity pa = it.next(); 11681 if (packageName == null 11682 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11683 && pa.mPref.mAlways)) { 11684 if (outFilters != null) { 11685 outFilters.add(new IntentFilter(pa)); 11686 } 11687 if (outActivities != null) { 11688 outActivities.add(pa.mPref.mComponent); 11689 } 11690 } 11691 } 11692 } 11693 } 11694 11695 return num; 11696 } 11697 11698 @Override 11699 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11700 int userId) { 11701 int callingUid = Binder.getCallingUid(); 11702 if (callingUid != Process.SYSTEM_UID) { 11703 throw new SecurityException( 11704 "addPersistentPreferredActivity can only be run by the system"); 11705 } 11706 if (filter.countActions() == 0) { 11707 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11708 return; 11709 } 11710 synchronized (mPackages) { 11711 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11712 " :"); 11713 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11714 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11715 new PersistentPreferredActivity(filter, activity)); 11716 scheduleWritePackageRestrictionsLocked(userId); 11717 } 11718 } 11719 11720 @Override 11721 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11722 int callingUid = Binder.getCallingUid(); 11723 if (callingUid != Process.SYSTEM_UID) { 11724 throw new SecurityException( 11725 "clearPackagePersistentPreferredActivities can only be run by the system"); 11726 } 11727 ArrayList<PersistentPreferredActivity> removed = null; 11728 boolean changed = false; 11729 synchronized (mPackages) { 11730 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11731 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11732 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11733 .valueAt(i); 11734 if (userId != thisUserId) { 11735 continue; 11736 } 11737 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11738 while (it.hasNext()) { 11739 PersistentPreferredActivity ppa = it.next(); 11740 // Mark entry for removal only if it matches the package name. 11741 if (ppa.mComponent.getPackageName().equals(packageName)) { 11742 if (removed == null) { 11743 removed = new ArrayList<PersistentPreferredActivity>(); 11744 } 11745 removed.add(ppa); 11746 } 11747 } 11748 if (removed != null) { 11749 for (int j=0; j<removed.size(); j++) { 11750 PersistentPreferredActivity ppa = removed.get(j); 11751 ppir.removeFilter(ppa); 11752 } 11753 changed = true; 11754 } 11755 } 11756 11757 if (changed) { 11758 scheduleWritePackageRestrictionsLocked(userId); 11759 } 11760 } 11761 } 11762 11763 @Override 11764 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11765 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11766 mContext.enforceCallingOrSelfPermission( 11767 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11768 int callingUid = Binder.getCallingUid(); 11769 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11770 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11771 if (intentFilter.countActions() == 0) { 11772 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11773 return; 11774 } 11775 synchronized (mPackages) { 11776 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 11777 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11778 CrossProfileIntentResolver resolver = 11779 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11780 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 11781 // We have all those whose filter is equal. Now checking if the rest is equal as well. 11782 if (existing != null) { 11783 int size = existing.size(); 11784 for (int i = 0; i < size; i++) { 11785 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 11786 return; 11787 } 11788 } 11789 } 11790 resolver.addFilter(newFilter); 11791 scheduleWritePackageRestrictionsLocked(sourceUserId); 11792 } 11793 } 11794 11795 @Override 11796 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11797 int ownerUserId) { 11798 mContext.enforceCallingOrSelfPermission( 11799 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11800 int callingUid = Binder.getCallingUid(); 11801 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11802 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11803 int callingUserId = UserHandle.getUserId(callingUid); 11804 synchronized (mPackages) { 11805 CrossProfileIntentResolver resolver = 11806 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11807 ArraySet<CrossProfileIntentFilter> set = 11808 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 11809 for (CrossProfileIntentFilter filter : set) { 11810 if (filter.getOwnerPackage().equals(ownerPackage) 11811 && filter.getOwnerUserId() == callingUserId) { 11812 resolver.removeFilter(filter); 11813 } 11814 } 11815 scheduleWritePackageRestrictionsLocked(sourceUserId); 11816 } 11817 } 11818 11819 // Enforcing that callingUid is owning pkg on userId 11820 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11821 // The system owns everything. 11822 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11823 return; 11824 } 11825 int callingUserId = UserHandle.getUserId(callingUid); 11826 if (callingUserId != userId) { 11827 throw new SecurityException("calling uid " + callingUid 11828 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11829 + callingUserId); 11830 } 11831 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11832 if (pi == null) { 11833 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11834 + callingUserId); 11835 } 11836 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11837 throw new SecurityException("Calling uid " + callingUid 11838 + " does not own package " + pkg); 11839 } 11840 } 11841 11842 @Override 11843 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11844 Intent intent = new Intent(Intent.ACTION_MAIN); 11845 intent.addCategory(Intent.CATEGORY_HOME); 11846 11847 final int callingUserId = UserHandle.getCallingUserId(); 11848 List<ResolveInfo> list = queryIntentActivities(intent, null, 11849 PackageManager.GET_META_DATA, callingUserId); 11850 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11851 true, false, false, callingUserId); 11852 11853 allHomeCandidates.clear(); 11854 if (list != null) { 11855 for (ResolveInfo ri : list) { 11856 allHomeCandidates.add(ri); 11857 } 11858 } 11859 return (preferred == null || preferred.activityInfo == null) 11860 ? null 11861 : new ComponentName(preferred.activityInfo.packageName, 11862 preferred.activityInfo.name); 11863 } 11864 11865 @Override 11866 public void setApplicationEnabledSetting(String appPackageName, 11867 int newState, int flags, int userId, String callingPackage) { 11868 if (!sUserManager.exists(userId)) return; 11869 if (callingPackage == null) { 11870 callingPackage = Integer.toString(Binder.getCallingUid()); 11871 } 11872 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11873 } 11874 11875 @Override 11876 public void setComponentEnabledSetting(ComponentName componentName, 11877 int newState, int flags, int userId) { 11878 if (!sUserManager.exists(userId)) return; 11879 setEnabledSetting(componentName.getPackageName(), 11880 componentName.getClassName(), newState, flags, userId, null); 11881 } 11882 11883 private void setEnabledSetting(final String packageName, String className, int newState, 11884 final int flags, int userId, String callingPackage) { 11885 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11886 || newState == COMPONENT_ENABLED_STATE_ENABLED 11887 || newState == COMPONENT_ENABLED_STATE_DISABLED 11888 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11889 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11890 throw new IllegalArgumentException("Invalid new component state: " 11891 + newState); 11892 } 11893 PackageSetting pkgSetting; 11894 final int uid = Binder.getCallingUid(); 11895 final int permission = mContext.checkCallingOrSelfPermission( 11896 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11897 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 11898 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11899 boolean sendNow = false; 11900 boolean isApp = (className == null); 11901 String componentName = isApp ? packageName : className; 11902 int packageUid = -1; 11903 ArrayList<String> components; 11904 11905 // writer 11906 synchronized (mPackages) { 11907 pkgSetting = mSettings.mPackages.get(packageName); 11908 if (pkgSetting == null) { 11909 if (className == null) { 11910 throw new IllegalArgumentException( 11911 "Unknown package: " + packageName); 11912 } 11913 throw new IllegalArgumentException( 11914 "Unknown component: " + packageName 11915 + "/" + className); 11916 } 11917 // Allow root and verify that userId is not being specified by a different user 11918 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11919 throw new SecurityException( 11920 "Permission Denial: attempt to change component state from pid=" 11921 + Binder.getCallingPid() 11922 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11923 } 11924 if (className == null) { 11925 // We're dealing with an application/package level state change 11926 if (pkgSetting.getEnabled(userId) == newState) { 11927 // Nothing to do 11928 return; 11929 } 11930 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11931 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11932 // Don't care about who enables an app. 11933 callingPackage = null; 11934 } 11935 pkgSetting.setEnabled(newState, userId, callingPackage); 11936 // pkgSetting.pkg.mSetEnabled = newState; 11937 } else { 11938 // We're dealing with a component level state change 11939 // First, verify that this is a valid class name. 11940 PackageParser.Package pkg = pkgSetting.pkg; 11941 if (pkg == null || !pkg.hasComponentClassName(className)) { 11942 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11943 throw new IllegalArgumentException("Component class " + className 11944 + " does not exist in " + packageName); 11945 } else { 11946 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11947 + className + " does not exist in " + packageName); 11948 } 11949 } 11950 switch (newState) { 11951 case COMPONENT_ENABLED_STATE_ENABLED: 11952 if (!pkgSetting.enableComponentLPw(className, userId)) { 11953 return; 11954 } 11955 break; 11956 case COMPONENT_ENABLED_STATE_DISABLED: 11957 if (!pkgSetting.disableComponentLPw(className, userId)) { 11958 return; 11959 } 11960 break; 11961 case COMPONENT_ENABLED_STATE_DEFAULT: 11962 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11963 return; 11964 } 11965 break; 11966 default: 11967 Slog.e(TAG, "Invalid new component state: " + newState); 11968 return; 11969 } 11970 } 11971 mSettings.writePackageRestrictionsLPr(userId); 11972 components = mPendingBroadcasts.get(userId, packageName); 11973 final boolean newPackage = components == null; 11974 if (newPackage) { 11975 components = new ArrayList<String>(); 11976 } 11977 if (!components.contains(componentName)) { 11978 components.add(componentName); 11979 } 11980 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11981 sendNow = true; 11982 // Purge entry from pending broadcast list if another one exists already 11983 // since we are sending one right away. 11984 mPendingBroadcasts.remove(userId, packageName); 11985 } else { 11986 if (newPackage) { 11987 mPendingBroadcasts.put(userId, packageName, components); 11988 } 11989 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11990 // Schedule a message 11991 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11992 } 11993 } 11994 } 11995 11996 long callingId = Binder.clearCallingIdentity(); 11997 try { 11998 if (sendNow) { 11999 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12000 sendPackageChangedBroadcast(packageName, 12001 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12002 } 12003 } finally { 12004 Binder.restoreCallingIdentity(callingId); 12005 } 12006 } 12007 12008 private void sendPackageChangedBroadcast(String packageName, 12009 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12010 if (DEBUG_INSTALL) 12011 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12012 + componentNames); 12013 Bundle extras = new Bundle(4); 12014 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12015 String nameList[] = new String[componentNames.size()]; 12016 componentNames.toArray(nameList); 12017 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12018 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12019 extras.putInt(Intent.EXTRA_UID, packageUid); 12020 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12021 new int[] {UserHandle.getUserId(packageUid)}); 12022 } 12023 12024 @Override 12025 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12026 if (!sUserManager.exists(userId)) return; 12027 final int uid = Binder.getCallingUid(); 12028 final int permission = mContext.checkCallingOrSelfPermission( 12029 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12030 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12031 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12032 // writer 12033 synchronized (mPackages) { 12034 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12035 uid, userId)) { 12036 scheduleWritePackageRestrictionsLocked(userId); 12037 } 12038 } 12039 } 12040 12041 @Override 12042 public String getInstallerPackageName(String packageName) { 12043 // reader 12044 synchronized (mPackages) { 12045 return mSettings.getInstallerPackageNameLPr(packageName); 12046 } 12047 } 12048 12049 @Override 12050 public int getApplicationEnabledSetting(String packageName, int userId) { 12051 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12052 int uid = Binder.getCallingUid(); 12053 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12054 // reader 12055 synchronized (mPackages) { 12056 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12057 } 12058 } 12059 12060 @Override 12061 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12062 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12063 int uid = Binder.getCallingUid(); 12064 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12065 // reader 12066 synchronized (mPackages) { 12067 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12068 } 12069 } 12070 12071 @Override 12072 public void enterSafeMode() { 12073 enforceSystemOrRoot("Only the system can request entering safe mode"); 12074 12075 if (!mSystemReady) { 12076 mSafeMode = true; 12077 } 12078 } 12079 12080 @Override 12081 public void systemReady() { 12082 mSystemReady = true; 12083 12084 // Read the compatibilty setting when the system is ready. 12085 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12086 mContext.getContentResolver(), 12087 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12088 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12089 if (DEBUG_SETTINGS) { 12090 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12091 } 12092 12093 synchronized (mPackages) { 12094 // Verify that all of the preferred activity components actually 12095 // exist. It is possible for applications to be updated and at 12096 // that point remove a previously declared activity component that 12097 // had been set as a preferred activity. We try to clean this up 12098 // the next time we encounter that preferred activity, but it is 12099 // possible for the user flow to never be able to return to that 12100 // situation so here we do a sanity check to make sure we haven't 12101 // left any junk around. 12102 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12103 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12104 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12105 removed.clear(); 12106 for (PreferredActivity pa : pir.filterSet()) { 12107 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12108 removed.add(pa); 12109 } 12110 } 12111 if (removed.size() > 0) { 12112 for (int r=0; r<removed.size(); r++) { 12113 PreferredActivity pa = removed.get(r); 12114 Slog.w(TAG, "Removing dangling preferred activity: " 12115 + pa.mPref.mComponent); 12116 pir.removeFilter(pa); 12117 } 12118 mSettings.writePackageRestrictionsLPr( 12119 mSettings.mPreferredActivities.keyAt(i)); 12120 } 12121 } 12122 } 12123 sUserManager.systemReady(); 12124 12125 // Kick off any messages waiting for system ready 12126 if (mPostSystemReadyMessages != null) { 12127 for (Message msg : mPostSystemReadyMessages) { 12128 msg.sendToTarget(); 12129 } 12130 mPostSystemReadyMessages = null; 12131 } 12132 } 12133 12134 @Override 12135 public boolean isSafeMode() { 12136 return mSafeMode; 12137 } 12138 12139 @Override 12140 public boolean hasSystemUidErrors() { 12141 return mHasSystemUidErrors; 12142 } 12143 12144 static String arrayToString(int[] array) { 12145 StringBuffer buf = new StringBuffer(128); 12146 buf.append('['); 12147 if (array != null) { 12148 for (int i=0; i<array.length; i++) { 12149 if (i > 0) buf.append(", "); 12150 buf.append(array[i]); 12151 } 12152 } 12153 buf.append(']'); 12154 return buf.toString(); 12155 } 12156 12157 static class DumpState { 12158 public static final int DUMP_LIBS = 1 << 0; 12159 public static final int DUMP_FEATURES = 1 << 1; 12160 public static final int DUMP_RESOLVERS = 1 << 2; 12161 public static final int DUMP_PERMISSIONS = 1 << 3; 12162 public static final int DUMP_PACKAGES = 1 << 4; 12163 public static final int DUMP_SHARED_USERS = 1 << 5; 12164 public static final int DUMP_MESSAGES = 1 << 6; 12165 public static final int DUMP_PROVIDERS = 1 << 7; 12166 public static final int DUMP_VERIFIERS = 1 << 8; 12167 public static final int DUMP_PREFERRED = 1 << 9; 12168 public static final int DUMP_PREFERRED_XML = 1 << 10; 12169 public static final int DUMP_KEYSETS = 1 << 11; 12170 public static final int DUMP_VERSION = 1 << 12; 12171 public static final int DUMP_INSTALLS = 1 << 13; 12172 12173 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12174 12175 private int mTypes; 12176 12177 private int mOptions; 12178 12179 private boolean mTitlePrinted; 12180 12181 private SharedUserSetting mSharedUser; 12182 12183 public boolean isDumping(int type) { 12184 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12185 return true; 12186 } 12187 12188 return (mTypes & type) != 0; 12189 } 12190 12191 public void setDump(int type) { 12192 mTypes |= type; 12193 } 12194 12195 public boolean isOptionEnabled(int option) { 12196 return (mOptions & option) != 0; 12197 } 12198 12199 public void setOptionEnabled(int option) { 12200 mOptions |= option; 12201 } 12202 12203 public boolean onTitlePrinted() { 12204 final boolean printed = mTitlePrinted; 12205 mTitlePrinted = true; 12206 return printed; 12207 } 12208 12209 public boolean getTitlePrinted() { 12210 return mTitlePrinted; 12211 } 12212 12213 public void setTitlePrinted(boolean enabled) { 12214 mTitlePrinted = enabled; 12215 } 12216 12217 public SharedUserSetting getSharedUser() { 12218 return mSharedUser; 12219 } 12220 12221 public void setSharedUser(SharedUserSetting user) { 12222 mSharedUser = user; 12223 } 12224 } 12225 12226 @Override 12227 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12228 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12229 != PackageManager.PERMISSION_GRANTED) { 12230 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12231 + Binder.getCallingPid() 12232 + ", uid=" + Binder.getCallingUid() 12233 + " without permission " 12234 + android.Manifest.permission.DUMP); 12235 return; 12236 } 12237 12238 DumpState dumpState = new DumpState(); 12239 boolean fullPreferred = false; 12240 boolean checkin = false; 12241 12242 String packageName = null; 12243 12244 int opti = 0; 12245 while (opti < args.length) { 12246 String opt = args[opti]; 12247 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12248 break; 12249 } 12250 opti++; 12251 12252 if ("-a".equals(opt)) { 12253 // Right now we only know how to print all. 12254 } else if ("-h".equals(opt)) { 12255 pw.println("Package manager dump options:"); 12256 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12257 pw.println(" --checkin: dump for a checkin"); 12258 pw.println(" -f: print details of intent filters"); 12259 pw.println(" -h: print this help"); 12260 pw.println(" cmd may be one of:"); 12261 pw.println(" l[ibraries]: list known shared libraries"); 12262 pw.println(" f[ibraries]: list device features"); 12263 pw.println(" k[eysets]: print known keysets"); 12264 pw.println(" r[esolvers]: dump intent resolvers"); 12265 pw.println(" perm[issions]: dump permissions"); 12266 pw.println(" pref[erred]: print preferred package settings"); 12267 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12268 pw.println(" prov[iders]: dump content providers"); 12269 pw.println(" p[ackages]: dump installed packages"); 12270 pw.println(" s[hared-users]: dump shared user IDs"); 12271 pw.println(" m[essages]: print collected runtime messages"); 12272 pw.println(" v[erifiers]: print package verifier info"); 12273 pw.println(" version: print database version info"); 12274 pw.println(" write: write current settings now"); 12275 pw.println(" <package.name>: info about given package"); 12276 pw.println(" installs: details about install sessions"); 12277 return; 12278 } else if ("--checkin".equals(opt)) { 12279 checkin = true; 12280 } else if ("-f".equals(opt)) { 12281 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12282 } else { 12283 pw.println("Unknown argument: " + opt + "; use -h for help"); 12284 } 12285 } 12286 12287 // Is the caller requesting to dump a particular piece of data? 12288 if (opti < args.length) { 12289 String cmd = args[opti]; 12290 opti++; 12291 // Is this a package name? 12292 if ("android".equals(cmd) || cmd.contains(".")) { 12293 packageName = cmd; 12294 // When dumping a single package, we always dump all of its 12295 // filter information since the amount of data will be reasonable. 12296 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12297 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12298 dumpState.setDump(DumpState.DUMP_LIBS); 12299 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12300 dumpState.setDump(DumpState.DUMP_FEATURES); 12301 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12302 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12303 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12304 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12305 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12306 dumpState.setDump(DumpState.DUMP_PREFERRED); 12307 } else if ("preferred-xml".equals(cmd)) { 12308 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12309 if (opti < args.length && "--full".equals(args[opti])) { 12310 fullPreferred = true; 12311 opti++; 12312 } 12313 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12314 dumpState.setDump(DumpState.DUMP_PACKAGES); 12315 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12316 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12317 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12318 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12319 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12320 dumpState.setDump(DumpState.DUMP_MESSAGES); 12321 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12322 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12323 } else if ("version".equals(cmd)) { 12324 dumpState.setDump(DumpState.DUMP_VERSION); 12325 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12326 dumpState.setDump(DumpState.DUMP_KEYSETS); 12327 } else if ("installs".equals(cmd)) { 12328 dumpState.setDump(DumpState.DUMP_INSTALLS); 12329 } else if ("write".equals(cmd)) { 12330 synchronized (mPackages) { 12331 mSettings.writeLPr(); 12332 pw.println("Settings written."); 12333 return; 12334 } 12335 } 12336 } 12337 12338 if (checkin) { 12339 pw.println("vers,1"); 12340 } 12341 12342 // reader 12343 synchronized (mPackages) { 12344 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12345 if (!checkin) { 12346 if (dumpState.onTitlePrinted()) 12347 pw.println(); 12348 pw.println("Database versions:"); 12349 pw.print(" SDK Version:"); 12350 pw.print(" internal="); 12351 pw.print(mSettings.mInternalSdkPlatform); 12352 pw.print(" external="); 12353 pw.println(mSettings.mExternalSdkPlatform); 12354 pw.print(" DB Version:"); 12355 pw.print(" internal="); 12356 pw.print(mSettings.mInternalDatabaseVersion); 12357 pw.print(" external="); 12358 pw.println(mSettings.mExternalDatabaseVersion); 12359 } 12360 } 12361 12362 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12363 if (!checkin) { 12364 if (dumpState.onTitlePrinted()) 12365 pw.println(); 12366 pw.println("Verifiers:"); 12367 pw.print(" Required: "); 12368 pw.print(mRequiredVerifierPackage); 12369 pw.print(" (uid="); 12370 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12371 pw.println(")"); 12372 } else if (mRequiredVerifierPackage != null) { 12373 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12374 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12375 } 12376 } 12377 12378 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12379 boolean printedHeader = false; 12380 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12381 while (it.hasNext()) { 12382 String name = it.next(); 12383 SharedLibraryEntry ent = mSharedLibraries.get(name); 12384 if (!checkin) { 12385 if (!printedHeader) { 12386 if (dumpState.onTitlePrinted()) 12387 pw.println(); 12388 pw.println("Libraries:"); 12389 printedHeader = true; 12390 } 12391 pw.print(" "); 12392 } else { 12393 pw.print("lib,"); 12394 } 12395 pw.print(name); 12396 if (!checkin) { 12397 pw.print(" -> "); 12398 } 12399 if (ent.path != null) { 12400 if (!checkin) { 12401 pw.print("(jar) "); 12402 pw.print(ent.path); 12403 } else { 12404 pw.print(",jar,"); 12405 pw.print(ent.path); 12406 } 12407 } else { 12408 if (!checkin) { 12409 pw.print("(apk) "); 12410 pw.print(ent.apk); 12411 } else { 12412 pw.print(",apk,"); 12413 pw.print(ent.apk); 12414 } 12415 } 12416 pw.println(); 12417 } 12418 } 12419 12420 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12421 if (dumpState.onTitlePrinted()) 12422 pw.println(); 12423 if (!checkin) { 12424 pw.println("Features:"); 12425 } 12426 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12427 while (it.hasNext()) { 12428 String name = it.next(); 12429 if (!checkin) { 12430 pw.print(" "); 12431 } else { 12432 pw.print("feat,"); 12433 } 12434 pw.println(name); 12435 } 12436 } 12437 12438 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12439 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12440 : "Activity Resolver Table:", " ", packageName, 12441 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12442 dumpState.setTitlePrinted(true); 12443 } 12444 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12445 : "Receiver Resolver Table:", " ", packageName, 12446 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12447 dumpState.setTitlePrinted(true); 12448 } 12449 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12450 : "Service Resolver Table:", " ", packageName, 12451 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12452 dumpState.setTitlePrinted(true); 12453 } 12454 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12455 : "Provider Resolver Table:", " ", packageName, 12456 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12457 dumpState.setTitlePrinted(true); 12458 } 12459 } 12460 12461 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12462 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12463 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12464 int user = mSettings.mPreferredActivities.keyAt(i); 12465 if (pir.dump(pw, 12466 dumpState.getTitlePrinted() 12467 ? "\nPreferred Activities User " + user + ":" 12468 : "Preferred Activities User " + user + ":", " ", 12469 packageName, true, false)) { 12470 dumpState.setTitlePrinted(true); 12471 } 12472 } 12473 } 12474 12475 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12476 pw.flush(); 12477 FileOutputStream fout = new FileOutputStream(fd); 12478 BufferedOutputStream str = new BufferedOutputStream(fout); 12479 XmlSerializer serializer = new FastXmlSerializer(); 12480 try { 12481 serializer.setOutput(str, "utf-8"); 12482 serializer.startDocument(null, true); 12483 serializer.setFeature( 12484 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12485 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12486 serializer.endDocument(); 12487 serializer.flush(); 12488 } catch (IllegalArgumentException e) { 12489 pw.println("Failed writing: " + e); 12490 } catch (IllegalStateException e) { 12491 pw.println("Failed writing: " + e); 12492 } catch (IOException e) { 12493 pw.println("Failed writing: " + e); 12494 } 12495 } 12496 12497 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12498 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12499 if (packageName == null) { 12500 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12501 if (iperm == 0) { 12502 if (dumpState.onTitlePrinted()) 12503 pw.println(); 12504 pw.println("AppOp Permissions:"); 12505 } 12506 pw.print(" AppOp Permission "); 12507 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12508 pw.println(":"); 12509 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12510 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12511 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12512 } 12513 } 12514 } 12515 } 12516 12517 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12518 boolean printedSomething = false; 12519 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12520 if (packageName != null && !packageName.equals(p.info.packageName)) { 12521 continue; 12522 } 12523 if (!printedSomething) { 12524 if (dumpState.onTitlePrinted()) 12525 pw.println(); 12526 pw.println("Registered ContentProviders:"); 12527 printedSomething = true; 12528 } 12529 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12530 pw.print(" "); pw.println(p.toString()); 12531 } 12532 printedSomething = false; 12533 for (Map.Entry<String, PackageParser.Provider> entry : 12534 mProvidersByAuthority.entrySet()) { 12535 PackageParser.Provider p = entry.getValue(); 12536 if (packageName != null && !packageName.equals(p.info.packageName)) { 12537 continue; 12538 } 12539 if (!printedSomething) { 12540 if (dumpState.onTitlePrinted()) 12541 pw.println(); 12542 pw.println("ContentProvider Authorities:"); 12543 printedSomething = true; 12544 } 12545 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12546 pw.print(" "); pw.println(p.toString()); 12547 if (p.info != null && p.info.applicationInfo != null) { 12548 final String appInfo = p.info.applicationInfo.toString(); 12549 pw.print(" applicationInfo="); pw.println(appInfo); 12550 } 12551 } 12552 } 12553 12554 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12555 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12556 } 12557 12558 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12559 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12560 } 12561 12562 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12563 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 12564 } 12565 12566 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12567 // XXX should handle packageName != null by dumping only install data that 12568 // the given package is involved with. 12569 if (dumpState.onTitlePrinted()) pw.println(); 12570 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12571 } 12572 12573 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12574 if (dumpState.onTitlePrinted()) pw.println(); 12575 mSettings.dumpReadMessagesLPr(pw, dumpState); 12576 12577 pw.println(); 12578 pw.println("Package warning messages:"); 12579 BufferedReader in = null; 12580 String line = null; 12581 try { 12582 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12583 while ((line = in.readLine()) != null) { 12584 if (line.contains("ignored: updated version")) continue; 12585 pw.println(line); 12586 } 12587 } catch (IOException ignored) { 12588 } finally { 12589 IoUtils.closeQuietly(in); 12590 } 12591 } 12592 12593 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12594 BufferedReader in = null; 12595 String line = null; 12596 try { 12597 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12598 while ((line = in.readLine()) != null) { 12599 if (line.contains("ignored: updated version")) continue; 12600 pw.print("msg,"); 12601 pw.println(line); 12602 } 12603 } catch (IOException ignored) { 12604 } finally { 12605 IoUtils.closeQuietly(in); 12606 } 12607 } 12608 } 12609 } 12610 12611 // ------- apps on sdcard specific code ------- 12612 static final boolean DEBUG_SD_INSTALL = false; 12613 12614 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12615 12616 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12617 12618 private boolean mMediaMounted = false; 12619 12620 static String getEncryptKey() { 12621 try { 12622 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12623 SD_ENCRYPTION_KEYSTORE_NAME); 12624 if (sdEncKey == null) { 12625 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12626 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12627 if (sdEncKey == null) { 12628 Slog.e(TAG, "Failed to create encryption keys"); 12629 return null; 12630 } 12631 } 12632 return sdEncKey; 12633 } catch (NoSuchAlgorithmException nsae) { 12634 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12635 return null; 12636 } catch (IOException ioe) { 12637 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12638 return null; 12639 } 12640 } 12641 12642 /* 12643 * Update media status on PackageManager. 12644 */ 12645 @Override 12646 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12647 int callingUid = Binder.getCallingUid(); 12648 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12649 throw new SecurityException("Media status can only be updated by the system"); 12650 } 12651 // reader; this apparently protects mMediaMounted, but should probably 12652 // be a different lock in that case. 12653 synchronized (mPackages) { 12654 Log.i(TAG, "Updating external media status from " 12655 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12656 + (mediaStatus ? "mounted" : "unmounted")); 12657 if (DEBUG_SD_INSTALL) 12658 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12659 + ", mMediaMounted=" + mMediaMounted); 12660 if (mediaStatus == mMediaMounted) { 12661 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12662 : 0, -1); 12663 mHandler.sendMessage(msg); 12664 return; 12665 } 12666 mMediaMounted = mediaStatus; 12667 } 12668 // Queue up an async operation since the package installation may take a 12669 // little while. 12670 mHandler.post(new Runnable() { 12671 public void run() { 12672 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12673 } 12674 }); 12675 } 12676 12677 /** 12678 * Called by MountService when the initial ASECs to scan are available. 12679 * Should block until all the ASEC containers are finished being scanned. 12680 */ 12681 public void scanAvailableAsecs() { 12682 updateExternalMediaStatusInner(true, false, false); 12683 if (mShouldRestoreconData) { 12684 SELinuxMMAC.setRestoreconDone(); 12685 mShouldRestoreconData = false; 12686 } 12687 } 12688 12689 /* 12690 * Collect information of applications on external media, map them against 12691 * existing containers and update information based on current mount status. 12692 * Please note that we always have to report status if reportStatus has been 12693 * set to true especially when unloading packages. 12694 */ 12695 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12696 boolean externalStorage) { 12697 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12698 int[] uidArr = EmptyArray.INT; 12699 12700 final String[] list = PackageHelper.getSecureContainerList(); 12701 if (ArrayUtils.isEmpty(list)) { 12702 Log.i(TAG, "No secure containers found"); 12703 } else { 12704 // Process list of secure containers and categorize them 12705 // as active or stale based on their package internal state. 12706 12707 // reader 12708 synchronized (mPackages) { 12709 for (String cid : list) { 12710 // Leave stages untouched for now; installer service owns them 12711 if (PackageInstallerService.isStageName(cid)) continue; 12712 12713 if (DEBUG_SD_INSTALL) 12714 Log.i(TAG, "Processing container " + cid); 12715 String pkgName = getAsecPackageName(cid); 12716 if (pkgName == null) { 12717 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12718 continue; 12719 } 12720 if (DEBUG_SD_INSTALL) 12721 Log.i(TAG, "Looking for pkg : " + pkgName); 12722 12723 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12724 if (ps == null) { 12725 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12726 continue; 12727 } 12728 12729 /* 12730 * Skip packages that are not external if we're unmounting 12731 * external storage. 12732 */ 12733 if (externalStorage && !isMounted && !isExternal(ps)) { 12734 continue; 12735 } 12736 12737 final AsecInstallArgs args = new AsecInstallArgs(cid, 12738 getAppDexInstructionSets(ps), ps.isForwardLocked()); 12739 // The package status is changed only if the code path 12740 // matches between settings and the container id. 12741 if (ps.codePathString != null 12742 && ps.codePathString.startsWith(args.getCodePath())) { 12743 if (DEBUG_SD_INSTALL) { 12744 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12745 + " at code path: " + ps.codePathString); 12746 } 12747 12748 // We do have a valid package installed on sdcard 12749 processCids.put(args, ps.codePathString); 12750 final int uid = ps.appId; 12751 if (uid != -1) { 12752 uidArr = ArrayUtils.appendInt(uidArr, uid); 12753 } 12754 } else { 12755 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12756 + ps.codePathString); 12757 } 12758 } 12759 } 12760 12761 Arrays.sort(uidArr); 12762 } 12763 12764 // Process packages with valid entries. 12765 if (isMounted) { 12766 if (DEBUG_SD_INSTALL) 12767 Log.i(TAG, "Loading packages"); 12768 loadMediaPackages(processCids, uidArr); 12769 startCleaningPackages(); 12770 mInstallerService.onSecureContainersAvailable(); 12771 } else { 12772 if (DEBUG_SD_INSTALL) 12773 Log.i(TAG, "Unloading packages"); 12774 unloadMediaPackages(processCids, uidArr, reportStatus); 12775 } 12776 } 12777 12778 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12779 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12780 int size = pkgList.size(); 12781 if (size > 0) { 12782 // Send broadcasts here 12783 Bundle extras = new Bundle(); 12784 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12785 .toArray(new String[size])); 12786 if (uidArr != null) { 12787 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12788 } 12789 if (replacing) { 12790 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12791 } 12792 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12793 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12794 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12795 } 12796 } 12797 12798 /* 12799 * Look at potentially valid container ids from processCids If package 12800 * information doesn't match the one on record or package scanning fails, 12801 * the cid is added to list of removeCids. We currently don't delete stale 12802 * containers. 12803 */ 12804 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12805 ArrayList<String> pkgList = new ArrayList<String>(); 12806 Set<AsecInstallArgs> keys = processCids.keySet(); 12807 12808 for (AsecInstallArgs args : keys) { 12809 String codePath = processCids.get(args); 12810 if (DEBUG_SD_INSTALL) 12811 Log.i(TAG, "Loading container : " + args.cid); 12812 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12813 try { 12814 // Make sure there are no container errors first. 12815 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12816 Slog.e(TAG, "Failed to mount cid : " + args.cid 12817 + " when installing from sdcard"); 12818 continue; 12819 } 12820 // Check code path here. 12821 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12822 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12823 + " does not match one in settings " + codePath); 12824 continue; 12825 } 12826 // Parse package 12827 int parseFlags = mDefParseFlags; 12828 if (args.isExternal()) { 12829 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12830 } 12831 if (args.isFwdLocked()) { 12832 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12833 } 12834 12835 synchronized (mInstallLock) { 12836 PackageParser.Package pkg = null; 12837 try { 12838 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12839 } catch (PackageManagerException e) { 12840 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12841 } 12842 // Scan the package 12843 if (pkg != null) { 12844 /* 12845 * TODO why is the lock being held? doPostInstall is 12846 * called in other places without the lock. This needs 12847 * to be straightened out. 12848 */ 12849 // writer 12850 synchronized (mPackages) { 12851 retCode = PackageManager.INSTALL_SUCCEEDED; 12852 pkgList.add(pkg.packageName); 12853 // Post process args 12854 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12855 pkg.applicationInfo.uid); 12856 } 12857 } else { 12858 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12859 } 12860 } 12861 12862 } finally { 12863 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12864 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12865 } 12866 } 12867 } 12868 // writer 12869 synchronized (mPackages) { 12870 // If the platform SDK has changed since the last time we booted, 12871 // we need to re-grant app permission to catch any new ones that 12872 // appear. This is really a hack, and means that apps can in some 12873 // cases get permissions that the user didn't initially explicitly 12874 // allow... it would be nice to have some better way to handle 12875 // this situation. 12876 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12877 if (regrantPermissions) 12878 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12879 + mSdkVersion + "; regranting permissions for external storage"); 12880 mSettings.mExternalSdkPlatform = mSdkVersion; 12881 12882 // Make sure group IDs have been assigned, and any permission 12883 // changes in other apps are accounted for 12884 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12885 | (regrantPermissions 12886 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12887 : 0)); 12888 12889 mSettings.updateExternalDatabaseVersion(); 12890 12891 // can downgrade to reader 12892 // Persist settings 12893 mSettings.writeLPr(); 12894 } 12895 // Send a broadcast to let everyone know we are done processing 12896 if (pkgList.size() > 0) { 12897 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12898 } 12899 } 12900 12901 /* 12902 * Utility method to unload a list of specified containers 12903 */ 12904 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12905 // Just unmount all valid containers. 12906 for (AsecInstallArgs arg : cidArgs) { 12907 synchronized (mInstallLock) { 12908 arg.doPostDeleteLI(false); 12909 } 12910 } 12911 } 12912 12913 /* 12914 * Unload packages mounted on external media. This involves deleting package 12915 * data from internal structures, sending broadcasts about diabled packages, 12916 * gc'ing to free up references, unmounting all secure containers 12917 * corresponding to packages on external media, and posting a 12918 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12919 * that we always have to post this message if status has been requested no 12920 * matter what. 12921 */ 12922 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12923 final boolean reportStatus) { 12924 if (DEBUG_SD_INSTALL) 12925 Log.i(TAG, "unloading media packages"); 12926 ArrayList<String> pkgList = new ArrayList<String>(); 12927 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12928 final Set<AsecInstallArgs> keys = processCids.keySet(); 12929 for (AsecInstallArgs args : keys) { 12930 String pkgName = args.getPackageName(); 12931 if (DEBUG_SD_INSTALL) 12932 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12933 // Delete package internally 12934 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12935 synchronized (mInstallLock) { 12936 boolean res = deletePackageLI(pkgName, null, false, null, null, 12937 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12938 if (res) { 12939 pkgList.add(pkgName); 12940 } else { 12941 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12942 failedList.add(args); 12943 } 12944 } 12945 } 12946 12947 // reader 12948 synchronized (mPackages) { 12949 // We didn't update the settings after removing each package; 12950 // write them now for all packages. 12951 mSettings.writeLPr(); 12952 } 12953 12954 // We have to absolutely send UPDATED_MEDIA_STATUS only 12955 // after confirming that all the receivers processed the ordered 12956 // broadcast when packages get disabled, force a gc to clean things up. 12957 // and unload all the containers. 12958 if (pkgList.size() > 0) { 12959 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12960 new IIntentReceiver.Stub() { 12961 public void performReceive(Intent intent, int resultCode, String data, 12962 Bundle extras, boolean ordered, boolean sticky, 12963 int sendingUser) throws RemoteException { 12964 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12965 reportStatus ? 1 : 0, 1, keys); 12966 mHandler.sendMessage(msg); 12967 } 12968 }); 12969 } else { 12970 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12971 keys); 12972 mHandler.sendMessage(msg); 12973 } 12974 } 12975 12976 /** Binder call */ 12977 @Override 12978 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12979 final int flags) { 12980 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12981 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12982 int returnCode = PackageManager.MOVE_SUCCEEDED; 12983 int currInstallFlags = 0; 12984 int newInstallFlags = 0; 12985 12986 File codeFile = null; 12987 String installerPackageName = null; 12988 String packageAbiOverride = null; 12989 12990 // reader 12991 synchronized (mPackages) { 12992 final PackageParser.Package pkg = mPackages.get(packageName); 12993 final PackageSetting ps = mSettings.mPackages.get(packageName); 12994 if (pkg == null || ps == null) { 12995 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12996 } else { 12997 // Disable moving fwd locked apps and system packages 12998 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12999 Slog.w(TAG, "Cannot move system application"); 13000 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13001 } else if (pkg.mOperationPending) { 13002 Slog.w(TAG, "Attempt to move package which has pending operations"); 13003 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13004 } else { 13005 // Find install location first 13006 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13007 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13008 Slog.w(TAG, "Ambigous flags specified for move location."); 13009 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13010 } else { 13011 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13012 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13013 currInstallFlags = isExternal(pkg) 13014 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13015 13016 if (newInstallFlags == currInstallFlags) { 13017 Slog.w(TAG, "No move required. Trying to move to same location"); 13018 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13019 } else { 13020 if (pkg.isForwardLocked()) { 13021 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13022 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13023 } 13024 } 13025 } 13026 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13027 pkg.mOperationPending = true; 13028 } 13029 } 13030 13031 codeFile = new File(pkg.codePath); 13032 installerPackageName = ps.installerPackageName; 13033 packageAbiOverride = ps.cpuAbiOverrideString; 13034 } 13035 } 13036 13037 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13038 try { 13039 observer.packageMoved(packageName, returnCode); 13040 } catch (RemoteException ignored) { 13041 } 13042 return; 13043 } 13044 13045 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13046 @Override 13047 public void onUserActionRequired(Intent intent) throws RemoteException { 13048 throw new IllegalStateException(); 13049 } 13050 13051 @Override 13052 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13053 Bundle extras) throws RemoteException { 13054 Slog.d(TAG, "Install result for move: " 13055 + PackageManager.installStatusToString(returnCode, msg)); 13056 13057 // We usually have a new package now after the install, but if 13058 // we failed we need to clear the pending flag on the original 13059 // package object. 13060 synchronized (mPackages) { 13061 final PackageParser.Package pkg = mPackages.get(packageName); 13062 if (pkg != null) { 13063 pkg.mOperationPending = false; 13064 } 13065 } 13066 13067 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13068 switch (status) { 13069 case PackageInstaller.STATUS_SUCCESS: 13070 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13071 break; 13072 case PackageInstaller.STATUS_FAILURE_STORAGE: 13073 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13074 break; 13075 default: 13076 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13077 break; 13078 } 13079 } 13080 }; 13081 13082 // Treat a move like reinstalling an existing app, which ensures that we 13083 // process everythign uniformly, like unpacking native libraries. 13084 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13085 13086 final Message msg = mHandler.obtainMessage(INIT_COPY); 13087 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13088 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13089 installerPackageName, null, user, packageAbiOverride); 13090 mHandler.sendMessage(msg); 13091 } 13092 13093 @Override 13094 public boolean setInstallLocation(int loc) { 13095 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13096 null); 13097 if (getInstallLocation() == loc) { 13098 return true; 13099 } 13100 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13101 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13102 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13103 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13104 return true; 13105 } 13106 return false; 13107 } 13108 13109 @Override 13110 public int getInstallLocation() { 13111 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13112 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13113 PackageHelper.APP_INSTALL_AUTO); 13114 } 13115 13116 /** Called by UserManagerService */ 13117 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13118 mDirtyUsers.remove(userHandle); 13119 mSettings.removeUserLPw(userHandle); 13120 mPendingBroadcasts.remove(userHandle); 13121 if (mInstaller != null) { 13122 // Technically, we shouldn't be doing this with the package lock 13123 // held. However, this is very rare, and there is already so much 13124 // other disk I/O going on, that we'll let it slide for now. 13125 mInstaller.removeUserDataDirs(userHandle); 13126 } 13127 mUserNeedsBadging.delete(userHandle); 13128 removeUnusedPackagesLILPw(userManager, userHandle); 13129 } 13130 13131 /** 13132 * We're removing userHandle and would like to remove any downloaded packages 13133 * that are no longer in use by any other user. 13134 * @param userHandle the user being removed 13135 */ 13136 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13137 final boolean DEBUG_CLEAN_APKS = false; 13138 int [] users = userManager.getUserIdsLPr(); 13139 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13140 while (psit.hasNext()) { 13141 PackageSetting ps = psit.next(); 13142 if (ps.pkg == null) { 13143 continue; 13144 } 13145 final String packageName = ps.pkg.packageName; 13146 // Skip over if system app 13147 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13148 continue; 13149 } 13150 if (DEBUG_CLEAN_APKS) { 13151 Slog.i(TAG, "Checking package " + packageName); 13152 } 13153 boolean keep = false; 13154 for (int i = 0; i < users.length; i++) { 13155 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13156 keep = true; 13157 if (DEBUG_CLEAN_APKS) { 13158 Slog.i(TAG, " Keeping package " + packageName + " for user " 13159 + users[i]); 13160 } 13161 break; 13162 } 13163 } 13164 if (!keep) { 13165 if (DEBUG_CLEAN_APKS) { 13166 Slog.i(TAG, " Removing package " + packageName); 13167 } 13168 mHandler.post(new Runnable() { 13169 public void run() { 13170 deletePackageX(packageName, userHandle, 0); 13171 } //end run 13172 }); 13173 } 13174 } 13175 } 13176 13177 /** Called by UserManagerService */ 13178 void createNewUserLILPw(int userHandle, File path) { 13179 if (mInstaller != null) { 13180 mInstaller.createUserConfig(userHandle); 13181 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13182 } 13183 } 13184 13185 @Override 13186 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13187 mContext.enforceCallingOrSelfPermission( 13188 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13189 "Only package verification agents can read the verifier device identity"); 13190 13191 synchronized (mPackages) { 13192 return mSettings.getVerifierDeviceIdentityLPw(); 13193 } 13194 } 13195 13196 @Override 13197 public void setPermissionEnforced(String permission, boolean enforced) { 13198 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13199 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13200 synchronized (mPackages) { 13201 if (mSettings.mReadExternalStorageEnforced == null 13202 || mSettings.mReadExternalStorageEnforced != enforced) { 13203 mSettings.mReadExternalStorageEnforced = enforced; 13204 mSettings.writeLPr(); 13205 } 13206 } 13207 // kill any non-foreground processes so we restart them and 13208 // grant/revoke the GID. 13209 final IActivityManager am = ActivityManagerNative.getDefault(); 13210 if (am != null) { 13211 final long token = Binder.clearCallingIdentity(); 13212 try { 13213 am.killProcessesBelowForeground("setPermissionEnforcement"); 13214 } catch (RemoteException e) { 13215 } finally { 13216 Binder.restoreCallingIdentity(token); 13217 } 13218 } 13219 } else { 13220 throw new IllegalArgumentException("No selective enforcement for " + permission); 13221 } 13222 } 13223 13224 @Override 13225 @Deprecated 13226 public boolean isPermissionEnforced(String permission) { 13227 return true; 13228 } 13229 13230 @Override 13231 public boolean isStorageLow() { 13232 final long token = Binder.clearCallingIdentity(); 13233 try { 13234 final DeviceStorageMonitorInternal 13235 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13236 if (dsm != null) { 13237 return dsm.isMemoryLow(); 13238 } else { 13239 return false; 13240 } 13241 } finally { 13242 Binder.restoreCallingIdentity(token); 13243 } 13244 } 13245 13246 @Override 13247 public IPackageInstaller getPackageInstaller() { 13248 return mInstallerService; 13249 } 13250 13251 private boolean userNeedsBadging(int userId) { 13252 int index = mUserNeedsBadging.indexOfKey(userId); 13253 if (index < 0) { 13254 final UserInfo userInfo; 13255 final long token = Binder.clearCallingIdentity(); 13256 try { 13257 userInfo = sUserManager.getUserInfo(userId); 13258 } finally { 13259 Binder.restoreCallingIdentity(token); 13260 } 13261 final boolean b; 13262 if (userInfo != null && userInfo.isManagedProfile()) { 13263 b = true; 13264 } else { 13265 b = false; 13266 } 13267 mUserNeedsBadging.put(userId, b); 13268 return b; 13269 } 13270 return mUserNeedsBadging.valueAt(index); 13271 } 13272 13273 @Override 13274 public KeySet getKeySetByAlias(String packageName, String alias) { 13275 if (packageName == null || alias == null) { 13276 return null; 13277 } 13278 synchronized(mPackages) { 13279 final PackageParser.Package pkg = mPackages.get(packageName); 13280 if (pkg == null) { 13281 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13282 throw new IllegalArgumentException("Unknown package: " + packageName); 13283 } 13284 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13285 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13286 } 13287 } 13288 13289 @Override 13290 public KeySet getSigningKeySet(String packageName) { 13291 if (packageName == null) { 13292 return null; 13293 } 13294 synchronized(mPackages) { 13295 final PackageParser.Package pkg = mPackages.get(packageName); 13296 if (pkg == null) { 13297 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13298 throw new IllegalArgumentException("Unknown package: " + packageName); 13299 } 13300 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13301 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13302 throw new SecurityException("May not access signing KeySet of other apps."); 13303 } 13304 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13305 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13306 } 13307 } 13308 13309 @Override 13310 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13311 if (packageName == null || ks == null) { 13312 return false; 13313 } 13314 synchronized(mPackages) { 13315 final PackageParser.Package pkg = mPackages.get(packageName); 13316 if (pkg == null) { 13317 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13318 throw new IllegalArgumentException("Unknown package: " + packageName); 13319 } 13320 IBinder ksh = ks.getToken(); 13321 if (ksh instanceof KeySetHandle) { 13322 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13323 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13324 } 13325 return false; 13326 } 13327 } 13328 13329 @Override 13330 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13331 if (packageName == null || ks == null) { 13332 return false; 13333 } 13334 synchronized(mPackages) { 13335 final PackageParser.Package pkg = mPackages.get(packageName); 13336 if (pkg == null) { 13337 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13338 throw new IllegalArgumentException("Unknown package: " + packageName); 13339 } 13340 IBinder ksh = ks.getToken(); 13341 if (ksh instanceof KeySetHandle) { 13342 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13343 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13344 } 13345 return false; 13346 } 13347 } 13348 13349 public void getUsageStatsIfNoPackageUsageInfo() { 13350 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 13351 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 13352 if (usm == null) { 13353 throw new IllegalStateException("UsageStatsManager must be initialized"); 13354 } 13355 long now = System.currentTimeMillis(); 13356 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 13357 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 13358 String packageName = entry.getKey(); 13359 PackageParser.Package pkg = mPackages.get(packageName); 13360 if (pkg == null) { 13361 continue; 13362 } 13363 UsageStats usage = entry.getValue(); 13364 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 13365 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 13366 } 13367 } 13368 } 13369 13370 /** 13371 * Check and throw if the given before/after packages would be considered a 13372 * downgrade. 13373 */ 13374 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 13375 throws PackageManagerException { 13376 if (after.versionCode < before.mVersionCode) { 13377 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13378 "Update version code " + after.versionCode + " is older than current " 13379 + before.mVersionCode); 13380 } else if (after.versionCode == before.mVersionCode) { 13381 if (after.baseRevisionCode < before.baseRevisionCode) { 13382 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13383 "Update base revision code " + after.baseRevisionCode 13384 + " is older than current " + before.baseRevisionCode); 13385 } 13386 13387 if (!ArrayUtils.isEmpty(after.splitNames)) { 13388 for (int i = 0; i < after.splitNames.length; i++) { 13389 final String splitName = after.splitNames[i]; 13390 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 13391 if (j != -1) { 13392 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 13393 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13394 "Update split " + splitName + " revision code " 13395 + after.splitRevisionCodes[i] + " is older than current " 13396 + before.splitRevisionCodes[j]); 13397 } 13398 } 13399 } 13400 } 13401 } 13402 } 13403} 13404