PackageManagerService.java revision b94c1657eb0140f7b91f5372a9f76de5a3d87e36
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 278 static final int REMOVE_CHATTY = 1<<16; 279 280 /** 281 * Timeout (in milliseconds) after which the watchdog should declare that 282 * our handler thread is wedged. The usual default for such things is one 283 * minute but we sometimes do very lengthy I/O operations on this thread, 284 * such as installing multi-gigabyte applications, so ours needs to be longer. 285 */ 286 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 287 288 /** 289 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 290 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 291 * settings entry if available, otherwise we use the hardcoded default. If it's been 292 * more than this long since the last fstrim, we force one during the boot sequence. 293 * 294 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 295 * one gets run at the next available charging+idle time. This final mandatory 296 * no-fstrim check kicks in only of the other scheduling criteria is never met. 297 */ 298 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 299 300 /** 301 * Whether verification is enabled by default. 302 */ 303 private static final boolean DEFAULT_VERIFY_ENABLE = true; 304 305 /** 306 * The default maximum time to wait for the verification agent to return in 307 * milliseconds. 308 */ 309 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 310 311 /** 312 * The default response for package verification timeout. 313 * 314 * This can be either PackageManager.VERIFICATION_ALLOW or 315 * PackageManager.VERIFICATION_REJECT. 316 */ 317 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 318 319 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 320 321 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 322 DEFAULT_CONTAINER_PACKAGE, 323 "com.android.defcontainer.DefaultContainerService"); 324 325 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 326 327 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 328 329 final ServiceThread mHandlerThread; 330 331 final PackageHandler mHandler; 332 333 /** 334 * Messages for {@link #mHandler} that need to wait for system ready before 335 * being dispatched. 336 */ 337 private ArrayList<Message> mPostSystemReadyMessages; 338 339 final int mSdkVersion = Build.VERSION.SDK_INT; 340 341 final Context mContext; 342 final boolean mFactoryTest; 343 final boolean mOnlyCore; 344 final boolean mLazyDexOpt; 345 final long mDexOptLRUThresholdInMills; 346 final DisplayMetrics mMetrics; 347 final int mDefParseFlags; 348 final String[] mSeparateProcesses; 349 final boolean mIsUpgrade; 350 351 // This is where all application persistent data goes. 352 final File mAppDataDir; 353 354 // This is where all application persistent data goes for secondary users. 355 final File mUserAppDataDir; 356 357 /** The location for ASEC container files on internal storage. */ 358 final String mAsecInternalPath; 359 360 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 361 // LOCK HELD. Can be called with mInstallLock held. 362 final Installer mInstaller; 363 364 /** Directory where installed third-party apps stored */ 365 final File mAppInstallDir; 366 367 /** 368 * Directory to which applications installed internally have their 369 * 32 bit native libraries copied. 370 */ 371 private File mAppLib32InstallDir; 372 373 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 374 // apps. 375 final File mDrmAppPrivateInstallDir; 376 377 // ---------------------------------------------------------------- 378 379 // Lock for state used when installing and doing other long running 380 // operations. Methods that must be called with this lock held have 381 // the suffix "LI". 382 final Object mInstallLock = new Object(); 383 384 // ---------------------------------------------------------------- 385 386 // Keys are String (package name), values are Package. This also serves 387 // as the lock for the global state. Methods that must be called with 388 // this lock held have the prefix "LP". 389 final ArrayMap<String, PackageParser.Package> mPackages = 390 new ArrayMap<String, PackageParser.Package>(); 391 392 // Tracks available target package names -> overlay package paths. 393 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 394 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 395 396 final Settings mSettings; 397 boolean mRestoredSettings; 398 399 // System configuration read by SystemConfig. 400 final int[] mGlobalGids; 401 final SparseArray<ArraySet<String>> mSystemPermissions; 402 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 403 404 // If mac_permissions.xml was found for seinfo labeling. 405 boolean mFoundPolicyFile; 406 407 // If a recursive restorecon of /data/data/<pkg> is needed. 408 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 409 410 public static final class SharedLibraryEntry { 411 public final String path; 412 public final String apk; 413 414 SharedLibraryEntry(String _path, String _apk) { 415 path = _path; 416 apk = _apk; 417 } 418 } 419 420 // Currently known shared libraries. 421 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 422 new ArrayMap<String, SharedLibraryEntry>(); 423 424 // All available activities, for your resolving pleasure. 425 final ActivityIntentResolver mActivities = 426 new ActivityIntentResolver(); 427 428 // All available receivers, for your resolving pleasure. 429 final ActivityIntentResolver mReceivers = 430 new ActivityIntentResolver(); 431 432 // All available services, for your resolving pleasure. 433 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 434 435 // All available providers, for your resolving pleasure. 436 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 437 438 // Mapping from provider base names (first directory in content URI codePath) 439 // to the provider information. 440 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 441 new ArrayMap<String, PackageParser.Provider>(); 442 443 // Mapping from instrumentation class names to info about them. 444 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 445 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 446 447 // Mapping from permission names to info about them. 448 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 449 new ArrayMap<String, PackageParser.PermissionGroup>(); 450 451 // Packages whose data we have transfered into another package, thus 452 // should no longer exist. 453 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 454 455 // Broadcast actions that are only available to the system. 456 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 457 458 /** List of packages waiting for verification. */ 459 final SparseArray<PackageVerificationState> mPendingVerification 460 = new SparseArray<PackageVerificationState>(); 461 462 /** Set of packages associated with each app op permission. */ 463 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 464 465 final PackageInstallerService mInstallerService; 466 467 private final PackageDexOptimizer mPackageDexOptimizer; 468 // Cache of users who need badging. 469 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 470 471 /** Token for keys in mPendingVerification. */ 472 private int mPendingVerificationToken = 0; 473 474 volatile boolean mSystemReady; 475 volatile boolean mSafeMode; 476 volatile boolean mHasSystemUidErrors; 477 478 ApplicationInfo mAndroidApplication; 479 final ActivityInfo mResolveActivity = new ActivityInfo(); 480 final ResolveInfo mResolveInfo = new ResolveInfo(); 481 ComponentName mResolveComponentName; 482 PackageParser.Package mPlatformPackage; 483 ComponentName mCustomResolverComponentName; 484 485 boolean mResolverReplaced = false; 486 487 // Set of pending broadcasts for aggregating enable/disable of components. 488 static class PendingPackageBroadcasts { 489 // for each user id, a map of <package name -> components within that package> 490 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 491 492 public PendingPackageBroadcasts() { 493 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 494 } 495 496 public ArrayList<String> get(int userId, String packageName) { 497 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 498 return packages.get(packageName); 499 } 500 501 public void put(int userId, String packageName, ArrayList<String> components) { 502 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 503 packages.put(packageName, components); 504 } 505 506 public void remove(int userId, String packageName) { 507 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 508 if (packages != null) { 509 packages.remove(packageName); 510 } 511 } 512 513 public void remove(int userId) { 514 mUidMap.remove(userId); 515 } 516 517 public int userIdCount() { 518 return mUidMap.size(); 519 } 520 521 public int userIdAt(int n) { 522 return mUidMap.keyAt(n); 523 } 524 525 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 526 return mUidMap.get(userId); 527 } 528 529 public int size() { 530 // total number of pending broadcast entries across all userIds 531 int num = 0; 532 for (int i = 0; i< mUidMap.size(); i++) { 533 num += mUidMap.valueAt(i).size(); 534 } 535 return num; 536 } 537 538 public void clear() { 539 mUidMap.clear(); 540 } 541 542 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 543 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 544 if (map == null) { 545 map = new ArrayMap<String, ArrayList<String>>(); 546 mUidMap.put(userId, map); 547 } 548 return map; 549 } 550 } 551 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 552 553 // Service Connection to remote media container service to copy 554 // package uri's from external media onto secure containers 555 // or internal storage. 556 private IMediaContainerService mContainerService = null; 557 558 static final int SEND_PENDING_BROADCAST = 1; 559 static final int MCS_BOUND = 3; 560 static final int END_COPY = 4; 561 static final int INIT_COPY = 5; 562 static final int MCS_UNBIND = 6; 563 static final int START_CLEANING_PACKAGE = 7; 564 static final int FIND_INSTALL_LOC = 8; 565 static final int POST_INSTALL = 9; 566 static final int MCS_RECONNECT = 10; 567 static final int MCS_GIVE_UP = 11; 568 static final int UPDATED_MEDIA_STATUS = 12; 569 static final int WRITE_SETTINGS = 13; 570 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 571 static final int PACKAGE_VERIFIED = 15; 572 static final int CHECK_PENDING_VERIFICATION = 16; 573 574 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 575 576 // Delay time in millisecs 577 static final int BROADCAST_DELAY = 10 * 1000; 578 579 static UserManagerService sUserManager; 580 581 // Stores a list of users whose package restrictions file needs to be updated 582 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 583 584 final private DefaultContainerConnection mDefContainerConn = 585 new DefaultContainerConnection(); 586 class DefaultContainerConnection implements ServiceConnection { 587 public void onServiceConnected(ComponentName name, IBinder service) { 588 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 589 IMediaContainerService imcs = 590 IMediaContainerService.Stub.asInterface(service); 591 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 592 } 593 594 public void onServiceDisconnected(ComponentName name) { 595 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 596 } 597 }; 598 599 // Recordkeeping of restore-after-install operations that are currently in flight 600 // between the Package Manager and the Backup Manager 601 class PostInstallData { 602 public InstallArgs args; 603 public PackageInstalledInfo res; 604 605 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 606 args = _a; 607 res = _r; 608 } 609 }; 610 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 611 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 612 613 private final String mRequiredVerifierPackage; 614 615 private final PackageUsage mPackageUsage = new PackageUsage(); 616 617 private class PackageUsage { 618 private static final int WRITE_INTERVAL 619 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 620 621 private final Object mFileLock = new Object(); 622 private final AtomicLong mLastWritten = new AtomicLong(0); 623 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 624 625 private boolean mIsHistoricalPackageUsageAvailable = true; 626 627 boolean isHistoricalPackageUsageAvailable() { 628 return mIsHistoricalPackageUsageAvailable; 629 } 630 631 void write(boolean force) { 632 if (force) { 633 writeInternal(); 634 return; 635 } 636 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 637 && !DEBUG_DEXOPT) { 638 return; 639 } 640 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 641 new Thread("PackageUsage_DiskWriter") { 642 @Override 643 public void run() { 644 try { 645 writeInternal(); 646 } finally { 647 mBackgroundWriteRunning.set(false); 648 } 649 } 650 }.start(); 651 } 652 } 653 654 private void writeInternal() { 655 synchronized (mPackages) { 656 synchronized (mFileLock) { 657 AtomicFile file = getFile(); 658 FileOutputStream f = null; 659 try { 660 f = file.startWrite(); 661 BufferedOutputStream out = new BufferedOutputStream(f); 662 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 663 StringBuilder sb = new StringBuilder(); 664 for (PackageParser.Package pkg : mPackages.values()) { 665 if (pkg.mLastPackageUsageTimeInMills == 0) { 666 continue; 667 } 668 sb.setLength(0); 669 sb.append(pkg.packageName); 670 sb.append(' '); 671 sb.append((long)pkg.mLastPackageUsageTimeInMills); 672 sb.append('\n'); 673 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 674 } 675 out.flush(); 676 file.finishWrite(f); 677 } catch (IOException e) { 678 if (f != null) { 679 file.failWrite(f); 680 } 681 Log.e(TAG, "Failed to write package usage times", e); 682 } 683 } 684 } 685 mLastWritten.set(SystemClock.elapsedRealtime()); 686 } 687 688 void readLP() { 689 synchronized (mFileLock) { 690 AtomicFile file = getFile(); 691 BufferedInputStream in = null; 692 try { 693 in = new BufferedInputStream(file.openRead()); 694 StringBuffer sb = new StringBuffer(); 695 while (true) { 696 String packageName = readToken(in, sb, ' '); 697 if (packageName == null) { 698 break; 699 } 700 String timeInMillisString = readToken(in, sb, '\n'); 701 if (timeInMillisString == null) { 702 throw new IOException("Failed to find last usage time for package " 703 + packageName); 704 } 705 PackageParser.Package pkg = mPackages.get(packageName); 706 if (pkg == null) { 707 continue; 708 } 709 long timeInMillis; 710 try { 711 timeInMillis = Long.parseLong(timeInMillisString.toString()); 712 } catch (NumberFormatException e) { 713 throw new IOException("Failed to parse " + timeInMillisString 714 + " as a long.", e); 715 } 716 pkg.mLastPackageUsageTimeInMills = timeInMillis; 717 } 718 } catch (FileNotFoundException expected) { 719 mIsHistoricalPackageUsageAvailable = false; 720 } catch (IOException e) { 721 Log.w(TAG, "Failed to read package usage times", e); 722 } finally { 723 IoUtils.closeQuietly(in); 724 } 725 } 726 mLastWritten.set(SystemClock.elapsedRealtime()); 727 } 728 729 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 730 throws IOException { 731 sb.setLength(0); 732 while (true) { 733 int ch = in.read(); 734 if (ch == -1) { 735 if (sb.length() == 0) { 736 return null; 737 } 738 throw new IOException("Unexpected EOF"); 739 } 740 if (ch == endOfToken) { 741 return sb.toString(); 742 } 743 sb.append((char)ch); 744 } 745 } 746 747 private AtomicFile getFile() { 748 File dataDir = Environment.getDataDirectory(); 749 File systemDir = new File(dataDir, "system"); 750 File fname = new File(systemDir, "package-usage.list"); 751 return new AtomicFile(fname); 752 } 753 } 754 755 class PackageHandler extends Handler { 756 private boolean mBound = false; 757 final ArrayList<HandlerParams> mPendingInstalls = 758 new ArrayList<HandlerParams>(); 759 760 private boolean connectToService() { 761 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 762 " DefaultContainerService"); 763 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 764 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 765 if (mContext.bindServiceAsUser(service, mDefContainerConn, 766 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 767 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 768 mBound = true; 769 return true; 770 } 771 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 772 return false; 773 } 774 775 private void disconnectService() { 776 mContainerService = null; 777 mBound = false; 778 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 779 mContext.unbindService(mDefContainerConn); 780 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 781 } 782 783 PackageHandler(Looper looper) { 784 super(looper); 785 } 786 787 public void handleMessage(Message msg) { 788 try { 789 doHandleMessage(msg); 790 } finally { 791 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 792 } 793 } 794 795 void doHandleMessage(Message msg) { 796 switch (msg.what) { 797 case INIT_COPY: { 798 HandlerParams params = (HandlerParams) msg.obj; 799 int idx = mPendingInstalls.size(); 800 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 801 // If a bind was already initiated we dont really 802 // need to do anything. The pending install 803 // will be processed later on. 804 if (!mBound) { 805 // If this is the only one pending we might 806 // have to bind to the service again. 807 if (!connectToService()) { 808 Slog.e(TAG, "Failed to bind to media container service"); 809 params.serviceError(); 810 return; 811 } else { 812 // Once we bind to the service, the first 813 // pending request will be processed. 814 mPendingInstalls.add(idx, params); 815 } 816 } else { 817 mPendingInstalls.add(idx, params); 818 // Already bound to the service. Just make 819 // sure we trigger off processing the first request. 820 if (idx == 0) { 821 mHandler.sendEmptyMessage(MCS_BOUND); 822 } 823 } 824 break; 825 } 826 case MCS_BOUND: { 827 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 828 if (msg.obj != null) { 829 mContainerService = (IMediaContainerService) msg.obj; 830 } 831 if (mContainerService == null) { 832 // Something seriously wrong. Bail out 833 Slog.e(TAG, "Cannot bind to media container service"); 834 for (HandlerParams params : mPendingInstalls) { 835 // Indicate service bind error 836 params.serviceError(); 837 } 838 mPendingInstalls.clear(); 839 } else if (mPendingInstalls.size() > 0) { 840 HandlerParams params = mPendingInstalls.get(0); 841 if (params != null) { 842 if (params.startCopy()) { 843 // We are done... look for more work or to 844 // go idle. 845 if (DEBUG_SD_INSTALL) Log.i(TAG, 846 "Checking for more work or unbind..."); 847 // Delete pending install 848 if (mPendingInstalls.size() > 0) { 849 mPendingInstalls.remove(0); 850 } 851 if (mPendingInstalls.size() == 0) { 852 if (mBound) { 853 if (DEBUG_SD_INSTALL) Log.i(TAG, 854 "Posting delayed MCS_UNBIND"); 855 removeMessages(MCS_UNBIND); 856 Message ubmsg = obtainMessage(MCS_UNBIND); 857 // Unbind after a little delay, to avoid 858 // continual thrashing. 859 sendMessageDelayed(ubmsg, 10000); 860 } 861 } else { 862 // There are more pending requests in queue. 863 // Just post MCS_BOUND message to trigger processing 864 // of next pending install. 865 if (DEBUG_SD_INSTALL) Log.i(TAG, 866 "Posting MCS_BOUND for next work"); 867 mHandler.sendEmptyMessage(MCS_BOUND); 868 } 869 } 870 } 871 } else { 872 // Should never happen ideally. 873 Slog.w(TAG, "Empty queue"); 874 } 875 break; 876 } 877 case MCS_RECONNECT: { 878 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 879 if (mPendingInstalls.size() > 0) { 880 if (mBound) { 881 disconnectService(); 882 } 883 if (!connectToService()) { 884 Slog.e(TAG, "Failed to bind to media container service"); 885 for (HandlerParams params : mPendingInstalls) { 886 // Indicate service bind error 887 params.serviceError(); 888 } 889 mPendingInstalls.clear(); 890 } 891 } 892 break; 893 } 894 case MCS_UNBIND: { 895 // If there is no actual work left, then time to unbind. 896 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 897 898 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 899 if (mBound) { 900 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 901 902 disconnectService(); 903 } 904 } else if (mPendingInstalls.size() > 0) { 905 // There are more pending requests in queue. 906 // Just post MCS_BOUND message to trigger processing 907 // of next pending install. 908 mHandler.sendEmptyMessage(MCS_BOUND); 909 } 910 911 break; 912 } 913 case MCS_GIVE_UP: { 914 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 915 mPendingInstalls.remove(0); 916 break; 917 } 918 case SEND_PENDING_BROADCAST: { 919 String packages[]; 920 ArrayList<String> components[]; 921 int size = 0; 922 int uids[]; 923 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 924 synchronized (mPackages) { 925 if (mPendingBroadcasts == null) { 926 return; 927 } 928 size = mPendingBroadcasts.size(); 929 if (size <= 0) { 930 // Nothing to be done. Just return 931 return; 932 } 933 packages = new String[size]; 934 components = new ArrayList[size]; 935 uids = new int[size]; 936 int i = 0; // filling out the above arrays 937 938 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 939 int packageUserId = mPendingBroadcasts.userIdAt(n); 940 Iterator<Map.Entry<String, ArrayList<String>>> it 941 = mPendingBroadcasts.packagesForUserId(packageUserId) 942 .entrySet().iterator(); 943 while (it.hasNext() && i < size) { 944 Map.Entry<String, ArrayList<String>> ent = it.next(); 945 packages[i] = ent.getKey(); 946 components[i] = ent.getValue(); 947 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 948 uids[i] = (ps != null) 949 ? UserHandle.getUid(packageUserId, ps.appId) 950 : -1; 951 i++; 952 } 953 } 954 size = i; 955 mPendingBroadcasts.clear(); 956 } 957 // Send broadcasts 958 for (int i = 0; i < size; i++) { 959 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 960 } 961 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 962 break; 963 } 964 case START_CLEANING_PACKAGE: { 965 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 966 final String packageName = (String)msg.obj; 967 final int userId = msg.arg1; 968 final boolean andCode = msg.arg2 != 0; 969 synchronized (mPackages) { 970 if (userId == UserHandle.USER_ALL) { 971 int[] users = sUserManager.getUserIds(); 972 for (int user : users) { 973 mSettings.addPackageToCleanLPw( 974 new PackageCleanItem(user, packageName, andCode)); 975 } 976 } else { 977 mSettings.addPackageToCleanLPw( 978 new PackageCleanItem(userId, packageName, andCode)); 979 } 980 } 981 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 982 startCleaningPackages(); 983 } break; 984 case POST_INSTALL: { 985 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 986 PostInstallData data = mRunningInstalls.get(msg.arg1); 987 mRunningInstalls.delete(msg.arg1); 988 boolean deleteOld = false; 989 990 if (data != null) { 991 InstallArgs args = data.args; 992 PackageInstalledInfo res = data.res; 993 994 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 995 res.removedInfo.sendBroadcast(false, true, false); 996 Bundle extras = new Bundle(1); 997 extras.putInt(Intent.EXTRA_UID, res.uid); 998 // Determine the set of users who are adding this 999 // package for the first time vs. those who are seeing 1000 // an update. 1001 int[] firstUsers; 1002 int[] updateUsers = new int[0]; 1003 if (res.origUsers == null || res.origUsers.length == 0) { 1004 firstUsers = res.newUsers; 1005 } else { 1006 firstUsers = new int[0]; 1007 for (int i=0; i<res.newUsers.length; i++) { 1008 int user = res.newUsers[i]; 1009 boolean isNew = true; 1010 for (int j=0; j<res.origUsers.length; j++) { 1011 if (res.origUsers[j] == user) { 1012 isNew = false; 1013 break; 1014 } 1015 } 1016 if (isNew) { 1017 int[] newFirst = new int[firstUsers.length+1]; 1018 System.arraycopy(firstUsers, 0, newFirst, 0, 1019 firstUsers.length); 1020 newFirst[firstUsers.length] = user; 1021 firstUsers = newFirst; 1022 } else { 1023 int[] newUpdate = new int[updateUsers.length+1]; 1024 System.arraycopy(updateUsers, 0, newUpdate, 0, 1025 updateUsers.length); 1026 newUpdate[updateUsers.length] = user; 1027 updateUsers = newUpdate; 1028 } 1029 } 1030 } 1031 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1032 res.pkg.applicationInfo.packageName, 1033 extras, null, null, firstUsers); 1034 final boolean update = res.removedInfo.removedPackage != null; 1035 if (update) { 1036 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1037 } 1038 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1039 res.pkg.applicationInfo.packageName, 1040 extras, null, null, updateUsers); 1041 if (update) { 1042 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1043 res.pkg.applicationInfo.packageName, 1044 extras, null, null, updateUsers); 1045 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1046 null, null, 1047 res.pkg.applicationInfo.packageName, null, updateUsers); 1048 1049 // treat asec-hosted packages like removable media on upgrade 1050 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1051 if (DEBUG_INSTALL) { 1052 Slog.i(TAG, "upgrading pkg " + res.pkg 1053 + " is ASEC-hosted -> AVAILABLE"); 1054 } 1055 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1056 ArrayList<String> pkgList = new ArrayList<String>(1); 1057 pkgList.add(res.pkg.applicationInfo.packageName); 1058 sendResourcesChangedBroadcast(true, true, 1059 pkgList,uidArray, null); 1060 } 1061 } 1062 if (res.removedInfo.args != null) { 1063 // Remove the replaced package's older resources safely now 1064 deleteOld = true; 1065 } 1066 1067 // Log current value of "unknown sources" setting 1068 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1069 getUnknownSourcesSettings()); 1070 } 1071 // Force a gc to clear up things 1072 Runtime.getRuntime().gc(); 1073 // We delete after a gc for applications on sdcard. 1074 if (deleteOld) { 1075 synchronized (mInstallLock) { 1076 res.removedInfo.args.doPostDeleteLI(true); 1077 } 1078 } 1079 if (args.observer != null) { 1080 try { 1081 Bundle extras = extrasForInstallResult(res); 1082 args.observer.onPackageInstalled(res.name, res.returnCode, 1083 res.returnMsg, extras); 1084 } catch (RemoteException e) { 1085 Slog.i(TAG, "Observer no longer exists."); 1086 } 1087 } 1088 } else { 1089 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1090 } 1091 } break; 1092 case UPDATED_MEDIA_STATUS: { 1093 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1094 boolean reportStatus = msg.arg1 == 1; 1095 boolean doGc = msg.arg2 == 1; 1096 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1097 if (doGc) { 1098 // Force a gc to clear up stale containers. 1099 Runtime.getRuntime().gc(); 1100 } 1101 if (msg.obj != null) { 1102 @SuppressWarnings("unchecked") 1103 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1104 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1105 // Unload containers 1106 unloadAllContainers(args); 1107 } 1108 if (reportStatus) { 1109 try { 1110 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1111 PackageHelper.getMountService().finishMediaUpdate(); 1112 } catch (RemoteException e) { 1113 Log.e(TAG, "MountService not running?"); 1114 } 1115 } 1116 } break; 1117 case WRITE_SETTINGS: { 1118 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1119 synchronized (mPackages) { 1120 removeMessages(WRITE_SETTINGS); 1121 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1122 mSettings.writeLPr(); 1123 mDirtyUsers.clear(); 1124 } 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } break; 1127 case WRITE_PACKAGE_RESTRICTIONS: { 1128 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1129 synchronized (mPackages) { 1130 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1131 for (int userId : mDirtyUsers) { 1132 mSettings.writePackageRestrictionsLPr(userId); 1133 } 1134 mDirtyUsers.clear(); 1135 } 1136 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1137 } break; 1138 case CHECK_PENDING_VERIFICATION: { 1139 final int verificationId = msg.arg1; 1140 final PackageVerificationState state = mPendingVerification.get(verificationId); 1141 1142 if ((state != null) && !state.timeoutExtended()) { 1143 final InstallArgs args = state.getInstallArgs(); 1144 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1145 1146 Slog.i(TAG, "Verification timed out for " + originUri); 1147 mPendingVerification.remove(verificationId); 1148 1149 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1150 1151 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1152 Slog.i(TAG, "Continuing with installation of " + originUri); 1153 state.setVerifierResponse(Binder.getCallingUid(), 1154 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1155 broadcastPackageVerified(verificationId, originUri, 1156 PackageManager.VERIFICATION_ALLOW, 1157 state.getInstallArgs().getUser()); 1158 try { 1159 ret = args.copyApk(mContainerService, true); 1160 } catch (RemoteException e) { 1161 Slog.e(TAG, "Could not contact the ContainerService"); 1162 } 1163 } else { 1164 broadcastPackageVerified(verificationId, originUri, 1165 PackageManager.VERIFICATION_REJECT, 1166 state.getInstallArgs().getUser()); 1167 } 1168 1169 processPendingInstall(args, ret); 1170 mHandler.sendEmptyMessage(MCS_UNBIND); 1171 } 1172 break; 1173 } 1174 case PACKAGE_VERIFIED: { 1175 final int verificationId = msg.arg1; 1176 1177 final PackageVerificationState state = mPendingVerification.get(verificationId); 1178 if (state == null) { 1179 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1180 break; 1181 } 1182 1183 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1184 1185 state.setVerifierResponse(response.callerUid, response.code); 1186 1187 if (state.isVerificationComplete()) { 1188 mPendingVerification.remove(verificationId); 1189 1190 final InstallArgs args = state.getInstallArgs(); 1191 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1192 1193 int ret; 1194 if (state.isInstallAllowed()) { 1195 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1196 broadcastPackageVerified(verificationId, originUri, 1197 response.code, state.getInstallArgs().getUser()); 1198 try { 1199 ret = args.copyApk(mContainerService, true); 1200 } catch (RemoteException e) { 1201 Slog.e(TAG, "Could not contact the ContainerService"); 1202 } 1203 } else { 1204 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1205 } 1206 1207 processPendingInstall(args, ret); 1208 1209 mHandler.sendEmptyMessage(MCS_UNBIND); 1210 } 1211 1212 break; 1213 } 1214 } 1215 } 1216 } 1217 1218 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1219 Bundle extras = null; 1220 switch (res.returnCode) { 1221 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1222 extras = new Bundle(); 1223 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1224 res.origPermission); 1225 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1226 res.origPackage); 1227 break; 1228 } 1229 } 1230 return extras; 1231 } 1232 1233 void scheduleWriteSettingsLocked() { 1234 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1235 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1236 } 1237 } 1238 1239 void scheduleWritePackageRestrictionsLocked(int userId) { 1240 if (!sUserManager.exists(userId)) return; 1241 mDirtyUsers.add(userId); 1242 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1243 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1244 } 1245 } 1246 1247 public static final PackageManagerService main(Context context, Installer installer, 1248 boolean factoryTest, boolean onlyCore) { 1249 PackageManagerService m = new PackageManagerService(context, installer, 1250 factoryTest, onlyCore); 1251 ServiceManager.addService("package", m); 1252 return m; 1253 } 1254 1255 static String[] splitString(String str, char sep) { 1256 int count = 1; 1257 int i = 0; 1258 while ((i=str.indexOf(sep, i)) >= 0) { 1259 count++; 1260 i++; 1261 } 1262 1263 String[] res = new String[count]; 1264 i=0; 1265 count = 0; 1266 int lastI=0; 1267 while ((i=str.indexOf(sep, i)) >= 0) { 1268 res[count] = str.substring(lastI, i); 1269 count++; 1270 i++; 1271 lastI = i; 1272 } 1273 res[count] = str.substring(lastI, str.length()); 1274 return res; 1275 } 1276 1277 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1278 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1279 Context.DISPLAY_SERVICE); 1280 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1281 } 1282 1283 public PackageManagerService(Context context, Installer installer, 1284 boolean factoryTest, boolean onlyCore) { 1285 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1286 SystemClock.uptimeMillis()); 1287 1288 if (mSdkVersion <= 0) { 1289 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1290 } 1291 1292 mContext = context; 1293 mFactoryTest = factoryTest; 1294 mOnlyCore = onlyCore; 1295 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1296 mMetrics = new DisplayMetrics(); 1297 mSettings = new Settings(context); 1298 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1299 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1300 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1301 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1302 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1303 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1304 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1305 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1306 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1307 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1308 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1309 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1310 1311 // TODO: add a property to control this? 1312 long dexOptLRUThresholdInMinutes; 1313 if (mLazyDexOpt) { 1314 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1315 } else { 1316 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1317 } 1318 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1319 1320 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1321 if (separateProcesses != null && separateProcesses.length() > 0) { 1322 if ("*".equals(separateProcesses)) { 1323 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1324 mSeparateProcesses = null; 1325 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1326 } else { 1327 mDefParseFlags = 0; 1328 mSeparateProcesses = separateProcesses.split(","); 1329 Slog.w(TAG, "Running with debug.separate_processes: " 1330 + separateProcesses); 1331 } 1332 } else { 1333 mDefParseFlags = 0; 1334 mSeparateProcesses = null; 1335 } 1336 1337 mInstaller = installer; 1338 mPackageDexOptimizer = new PackageDexOptimizer(this); 1339 1340 getDefaultDisplayMetrics(context, mMetrics); 1341 1342 SystemConfig systemConfig = SystemConfig.getInstance(); 1343 mGlobalGids = systemConfig.getGlobalGids(); 1344 mSystemPermissions = systemConfig.getSystemPermissions(); 1345 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1346 1347 synchronized (mInstallLock) { 1348 // writer 1349 synchronized (mPackages) { 1350 mHandlerThread = new ServiceThread(TAG, 1351 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1352 mHandlerThread.start(); 1353 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1354 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1355 1356 File dataDir = Environment.getDataDirectory(); 1357 mAppDataDir = new File(dataDir, "data"); 1358 mAppInstallDir = new File(dataDir, "app"); 1359 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1360 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1361 mUserAppDataDir = new File(dataDir, "user"); 1362 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1363 1364 sUserManager = new UserManagerService(context, this, 1365 mInstallLock, mPackages); 1366 1367 // Propagate permission configuration in to package manager. 1368 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1369 = systemConfig.getPermissions(); 1370 for (int i=0; i<permConfig.size(); i++) { 1371 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1372 BasePermission bp = mSettings.mPermissions.get(perm.name); 1373 if (bp == null) { 1374 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1375 mSettings.mPermissions.put(perm.name, bp); 1376 } 1377 if (perm.gids != null) { 1378 bp.gids = appendInts(bp.gids, perm.gids); 1379 } 1380 } 1381 1382 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1383 for (int i=0; i<libConfig.size(); i++) { 1384 mSharedLibraries.put(libConfig.keyAt(i), 1385 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1386 } 1387 1388 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1389 1390 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1391 mSdkVersion, mOnlyCore); 1392 1393 String customResolverActivity = Resources.getSystem().getString( 1394 R.string.config_customResolverActivity); 1395 if (TextUtils.isEmpty(customResolverActivity)) { 1396 customResolverActivity = null; 1397 } else { 1398 mCustomResolverComponentName = ComponentName.unflattenFromString( 1399 customResolverActivity); 1400 } 1401 1402 long startTime = SystemClock.uptimeMillis(); 1403 1404 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1405 startTime); 1406 1407 // Set flag to monitor and not change apk file paths when 1408 // scanning install directories. 1409 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1410 1411 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1412 1413 /** 1414 * Add everything in the in the boot class path to the 1415 * list of process files because dexopt will have been run 1416 * if necessary during zygote startup. 1417 */ 1418 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1419 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1420 1421 if (bootClassPath != null) { 1422 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1423 for (String element : bootClassPathElements) { 1424 alreadyDexOpted.add(element); 1425 } 1426 } else { 1427 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1428 } 1429 1430 if (systemServerClassPath != null) { 1431 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1432 for (String element : systemServerClassPathElements) { 1433 alreadyDexOpted.add(element); 1434 } 1435 } else { 1436 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1437 } 1438 1439 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1440 final String[] dexCodeInstructionSets = 1441 getDexCodeInstructionSets( 1442 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1443 1444 /** 1445 * Ensure all external libraries have had dexopt run on them. 1446 */ 1447 if (mSharedLibraries.size() > 0) { 1448 // NOTE: For now, we're compiling these system "shared libraries" 1449 // (and framework jars) into all available architectures. It's possible 1450 // to compile them only when we come across an app that uses them (there's 1451 // already logic for that in scanPackageLI) but that adds some complexity. 1452 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1453 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1454 final String lib = libEntry.path; 1455 if (lib == null) { 1456 continue; 1457 } 1458 1459 try { 1460 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1461 dexCodeInstructionSet, 1462 false); 1463 if (dexoptRequired != DexFile.UP_TO_DATE) { 1464 alreadyDexOpted.add(lib); 1465 1466 // The list of "shared libraries" we have at this point is 1467 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1468 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1469 } else { 1470 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1471 } 1472 } 1473 } catch (FileNotFoundException e) { 1474 Slog.w(TAG, "Library not found: " + lib); 1475 } catch (IOException e) { 1476 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1477 + e.getMessage()); 1478 } 1479 } 1480 } 1481 } 1482 1483 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1484 1485 // Gross hack for now: we know this file doesn't contain any 1486 // code, so don't dexopt it to avoid the resulting log spew. 1487 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1488 1489 // Gross hack for now: we know this file is only part of 1490 // the boot class path for art, so don't dexopt it to 1491 // avoid the resulting log spew. 1492 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1493 1494 /** 1495 * And there are a number of commands implemented in Java, which 1496 * we currently need to do the dexopt on so that they can be 1497 * run from a non-root shell. 1498 */ 1499 String[] frameworkFiles = frameworkDir.list(); 1500 if (frameworkFiles != null) { 1501 // TODO: We could compile these only for the most preferred ABI. We should 1502 // first double check that the dex files for these commands are not referenced 1503 // by other system apps. 1504 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1505 for (int i=0; i<frameworkFiles.length; i++) { 1506 File libPath = new File(frameworkDir, frameworkFiles[i]); 1507 String path = libPath.getPath(); 1508 // Skip the file if we already did it. 1509 if (alreadyDexOpted.contains(path)) { 1510 continue; 1511 } 1512 // Skip the file if it is not a type we want to dexopt. 1513 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1514 continue; 1515 } 1516 try { 1517 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1518 dexCodeInstructionSet, 1519 false); 1520 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1521 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1522 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1523 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1524 } 1525 } catch (FileNotFoundException e) { 1526 Slog.w(TAG, "Jar not found: " + path); 1527 } catch (IOException e) { 1528 Slog.w(TAG, "Exception reading jar: " + path, e); 1529 } 1530 } 1531 } 1532 } 1533 1534 // Collect vendor overlay packages. 1535 // (Do this before scanning any apps.) 1536 // For security and version matching reason, only consider 1537 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1538 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1539 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1540 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1541 1542 // Find base frameworks (resource packages without code). 1543 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1544 | PackageParser.PARSE_IS_SYSTEM_DIR 1545 | PackageParser.PARSE_IS_PRIVILEGED, 1546 scanFlags | SCAN_NO_DEX, 0); 1547 1548 // Collected privileged system packages. 1549 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1550 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1551 | PackageParser.PARSE_IS_SYSTEM_DIR 1552 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1553 1554 // Collect ordinary system packages. 1555 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1556 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1557 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1558 1559 // Collect all vendor packages. 1560 File vendorAppDir = new File("/vendor/app"); 1561 try { 1562 vendorAppDir = vendorAppDir.getCanonicalFile(); 1563 } catch (IOException e) { 1564 // failed to look up canonical path, continue with original one 1565 } 1566 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1567 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1568 1569 // Collect all OEM packages. 1570 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1571 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1572 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1573 1574 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1575 mInstaller.moveFiles(); 1576 1577 // Prune any system packages that no longer exist. 1578 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1579 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1580 if (!mOnlyCore) { 1581 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1582 while (psit.hasNext()) { 1583 PackageSetting ps = psit.next(); 1584 1585 /* 1586 * If this is not a system app, it can't be a 1587 * disable system app. 1588 */ 1589 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1590 continue; 1591 } 1592 1593 /* 1594 * If the package is scanned, it's not erased. 1595 */ 1596 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1597 if (scannedPkg != null) { 1598 /* 1599 * If the system app is both scanned and in the 1600 * disabled packages list, then it must have been 1601 * added via OTA. Remove it from the currently 1602 * scanned package so the previously user-installed 1603 * application can be scanned. 1604 */ 1605 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1606 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1607 + ps.name + "; removing system app. Last known codePath=" 1608 + ps.codePathString + ", installStatus=" + ps.installStatus 1609 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1610 + scannedPkg.mVersionCode); 1611 removePackageLI(ps, true); 1612 expectingBetter.put(ps.name, ps.codePath); 1613 } 1614 1615 continue; 1616 } 1617 1618 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1619 psit.remove(); 1620 logCriticalInfo(Log.WARN, "System package " + ps.name 1621 + " no longer exists; wiping its data"); 1622 removeDataDirsLI(ps.name); 1623 } else { 1624 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1625 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1626 possiblyDeletedUpdatedSystemApps.add(ps.name); 1627 } 1628 } 1629 } 1630 } 1631 1632 //look for any incomplete package installations 1633 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1634 //clean up list 1635 for(int i = 0; i < deletePkgsList.size(); i++) { 1636 //clean up here 1637 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1638 } 1639 //delete tmp files 1640 deleteTempPackageFiles(); 1641 1642 // Remove any shared userIDs that have no associated packages 1643 mSettings.pruneSharedUsersLPw(); 1644 1645 if (!mOnlyCore) { 1646 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1647 SystemClock.uptimeMillis()); 1648 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1649 1650 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1651 scanFlags, 0); 1652 1653 /** 1654 * Remove disable package settings for any updated system 1655 * apps that were removed via an OTA. If they're not a 1656 * previously-updated app, remove them completely. 1657 * Otherwise, just revoke their system-level permissions. 1658 */ 1659 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1660 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1661 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1662 1663 String msg; 1664 if (deletedPkg == null) { 1665 msg = "Updated system package " + deletedAppName 1666 + " no longer exists; wiping its data"; 1667 removeDataDirsLI(deletedAppName); 1668 } else { 1669 msg = "Updated system app + " + deletedAppName 1670 + " no longer present; removing system privileges for " 1671 + deletedAppName; 1672 1673 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1674 1675 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1676 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1677 } 1678 logCriticalInfo(Log.WARN, msg); 1679 } 1680 1681 /** 1682 * Make sure all system apps that we expected to appear on 1683 * the userdata partition actually showed up. If they never 1684 * appeared, crawl back and revive the system version. 1685 */ 1686 for (int i = 0; i < expectingBetter.size(); i++) { 1687 final String packageName = expectingBetter.keyAt(i); 1688 if (!mPackages.containsKey(packageName)) { 1689 final File scanFile = expectingBetter.valueAt(i); 1690 1691 logCriticalInfo(Log.WARN, "Expected better " + packageName 1692 + " but never showed up; reverting to system"); 1693 1694 final int reparseFlags; 1695 if (FileUtils.contains(privilegedAppDir, scanFile)) { 1696 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1697 | PackageParser.PARSE_IS_SYSTEM_DIR 1698 | PackageParser.PARSE_IS_PRIVILEGED; 1699 } else if (FileUtils.contains(systemAppDir, scanFile)) { 1700 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1701 | PackageParser.PARSE_IS_SYSTEM_DIR; 1702 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 1703 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1704 | PackageParser.PARSE_IS_SYSTEM_DIR; 1705 } else if (FileUtils.contains(oemAppDir, scanFile)) { 1706 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1707 | PackageParser.PARSE_IS_SYSTEM_DIR; 1708 } else { 1709 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 1710 continue; 1711 } 1712 1713 mSettings.enableSystemPackageLPw(packageName); 1714 1715 try { 1716 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 1717 } catch (PackageManagerException e) { 1718 Slog.e(TAG, "Failed to parse original system package: " 1719 + e.getMessage()); 1720 } 1721 } 1722 } 1723 } 1724 1725 // Now that we know all of the shared libraries, update all clients to have 1726 // the correct library paths. 1727 updateAllSharedLibrariesLPw(); 1728 1729 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1730 // NOTE: We ignore potential failures here during a system scan (like 1731 // the rest of the commands above) because there's precious little we 1732 // can do about it. A settings error is reported, though. 1733 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1734 false /* force dexopt */, false /* defer dexopt */); 1735 } 1736 1737 // Now that we know all the packages we are keeping, 1738 // read and update their last usage times. 1739 mPackageUsage.readLP(); 1740 1741 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1742 SystemClock.uptimeMillis()); 1743 Slog.i(TAG, "Time to scan packages: " 1744 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1745 + " seconds"); 1746 1747 // If the platform SDK has changed since the last time we booted, 1748 // we need to re-grant app permission to catch any new ones that 1749 // appear. This is really a hack, and means that apps can in some 1750 // cases get permissions that the user didn't initially explicitly 1751 // allow... it would be nice to have some better way to handle 1752 // this situation. 1753 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1754 != mSdkVersion; 1755 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1756 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1757 + "; regranting permissions for internal storage"); 1758 mSettings.mInternalSdkPlatform = mSdkVersion; 1759 1760 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1761 | (regrantPermissions 1762 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1763 : 0)); 1764 1765 // If this is the first boot, and it is a normal boot, then 1766 // we need to initialize the default preferred apps. 1767 if (!mRestoredSettings && !onlyCore) { 1768 mSettings.readDefaultPreferredAppsLPw(this, 0); 1769 } 1770 1771 // If this is first boot after an OTA, and a normal boot, then 1772 // we need to clear code cache directories. 1773 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 1774 if (mIsUpgrade && !onlyCore) { 1775 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1776 for (String pkgName : mSettings.mPackages.keySet()) { 1777 deleteCodeCacheDirsLI(pkgName); 1778 } 1779 mSettings.mFingerprint = Build.FINGERPRINT; 1780 } 1781 1782 // All the changes are done during package scanning. 1783 mSettings.updateInternalDatabaseVersion(); 1784 1785 // can downgrade to reader 1786 mSettings.writeLPr(); 1787 1788 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1789 SystemClock.uptimeMillis()); 1790 1791 1792 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1793 } // synchronized (mPackages) 1794 } // synchronized (mInstallLock) 1795 1796 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1797 1798 // Now after opening every single application zip, make sure they 1799 // are all flushed. Not really needed, but keeps things nice and 1800 // tidy. 1801 Runtime.getRuntime().gc(); 1802 } 1803 1804 @Override 1805 public boolean isFirstBoot() { 1806 return !mRestoredSettings; 1807 } 1808 1809 @Override 1810 public boolean isOnlyCoreApps() { 1811 return mOnlyCore; 1812 } 1813 1814 @Override 1815 public boolean isUpgrade() { 1816 return mIsUpgrade; 1817 } 1818 1819 private String getRequiredVerifierLPr() { 1820 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1821 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1822 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1823 1824 String requiredVerifier = null; 1825 1826 final int N = receivers.size(); 1827 for (int i = 0; i < N; i++) { 1828 final ResolveInfo info = receivers.get(i); 1829 1830 if (info.activityInfo == null) { 1831 continue; 1832 } 1833 1834 final String packageName = info.activityInfo.packageName; 1835 1836 final PackageSetting ps = mSettings.mPackages.get(packageName); 1837 if (ps == null) { 1838 continue; 1839 } 1840 1841 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1842 if (!gp.grantedPermissions 1843 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1844 continue; 1845 } 1846 1847 if (requiredVerifier != null) { 1848 throw new RuntimeException("There can be only one required verifier"); 1849 } 1850 1851 requiredVerifier = packageName; 1852 } 1853 1854 return requiredVerifier; 1855 } 1856 1857 @Override 1858 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1859 throws RemoteException { 1860 try { 1861 return super.onTransact(code, data, reply, flags); 1862 } catch (RuntimeException e) { 1863 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1864 Slog.wtf(TAG, "Package Manager Crash", e); 1865 } 1866 throw e; 1867 } 1868 } 1869 1870 void cleanupInstallFailedPackage(PackageSetting ps) { 1871 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1872 1873 removeDataDirsLI(ps.name); 1874 if (ps.codePath != null) { 1875 if (ps.codePath.isDirectory()) { 1876 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 1877 } else { 1878 ps.codePath.delete(); 1879 } 1880 } 1881 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1882 if (ps.resourcePath.isDirectory()) { 1883 FileUtils.deleteContents(ps.resourcePath); 1884 } 1885 ps.resourcePath.delete(); 1886 } 1887 mSettings.removePackageLPw(ps.name); 1888 } 1889 1890 static int[] appendInts(int[] cur, int[] add) { 1891 if (add == null) return cur; 1892 if (cur == null) return add; 1893 final int N = add.length; 1894 for (int i=0; i<N; i++) { 1895 cur = appendInt(cur, add[i]); 1896 } 1897 return cur; 1898 } 1899 1900 static int[] removeInts(int[] cur, int[] rem) { 1901 if (rem == null) return cur; 1902 if (cur == null) return cur; 1903 final int N = rem.length; 1904 for (int i=0; i<N; i++) { 1905 cur = removeInt(cur, rem[i]); 1906 } 1907 return cur; 1908 } 1909 1910 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1911 if (!sUserManager.exists(userId)) return null; 1912 final PackageSetting ps = (PackageSetting) p.mExtras; 1913 if (ps == null) { 1914 return null; 1915 } 1916 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1917 final PackageUserState state = ps.readUserState(userId); 1918 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1919 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1920 state, userId); 1921 } 1922 1923 @Override 1924 public boolean isPackageAvailable(String packageName, int userId) { 1925 if (!sUserManager.exists(userId)) return false; 1926 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1927 synchronized (mPackages) { 1928 PackageParser.Package p = mPackages.get(packageName); 1929 if (p != null) { 1930 final PackageSetting ps = (PackageSetting) p.mExtras; 1931 if (ps != null) { 1932 final PackageUserState state = ps.readUserState(userId); 1933 if (state != null) { 1934 return PackageParser.isAvailable(state); 1935 } 1936 } 1937 } 1938 } 1939 return false; 1940 } 1941 1942 @Override 1943 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1944 if (!sUserManager.exists(userId)) return null; 1945 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1946 // reader 1947 synchronized (mPackages) { 1948 PackageParser.Package p = mPackages.get(packageName); 1949 if (DEBUG_PACKAGE_INFO) 1950 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1951 if (p != null) { 1952 return generatePackageInfo(p, flags, userId); 1953 } 1954 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1955 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1956 } 1957 } 1958 return null; 1959 } 1960 1961 @Override 1962 public String[] currentToCanonicalPackageNames(String[] names) { 1963 String[] out = new String[names.length]; 1964 // reader 1965 synchronized (mPackages) { 1966 for (int i=names.length-1; i>=0; i--) { 1967 PackageSetting ps = mSettings.mPackages.get(names[i]); 1968 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1969 } 1970 } 1971 return out; 1972 } 1973 1974 @Override 1975 public String[] canonicalToCurrentPackageNames(String[] names) { 1976 String[] out = new String[names.length]; 1977 // reader 1978 synchronized (mPackages) { 1979 for (int i=names.length-1; i>=0; i--) { 1980 String cur = mSettings.mRenamedPackages.get(names[i]); 1981 out[i] = cur != null ? cur : names[i]; 1982 } 1983 } 1984 return out; 1985 } 1986 1987 @Override 1988 public int getPackageUid(String packageName, int userId) { 1989 if (!sUserManager.exists(userId)) return -1; 1990 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1991 // reader 1992 synchronized (mPackages) { 1993 PackageParser.Package p = mPackages.get(packageName); 1994 if(p != null) { 1995 return UserHandle.getUid(userId, p.applicationInfo.uid); 1996 } 1997 PackageSetting ps = mSettings.mPackages.get(packageName); 1998 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1999 return -1; 2000 } 2001 p = ps.pkg; 2002 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2003 } 2004 } 2005 2006 @Override 2007 public int[] getPackageGids(String packageName) { 2008 // reader 2009 synchronized (mPackages) { 2010 PackageParser.Package p = mPackages.get(packageName); 2011 if (DEBUG_PACKAGE_INFO) 2012 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2013 if (p != null) { 2014 final PackageSetting ps = (PackageSetting)p.mExtras; 2015 return ps.getGids(); 2016 } 2017 } 2018 // stupid thing to indicate an error. 2019 return new int[0]; 2020 } 2021 2022 static final PermissionInfo generatePermissionInfo( 2023 BasePermission bp, int flags) { 2024 if (bp.perm != null) { 2025 return PackageParser.generatePermissionInfo(bp.perm, flags); 2026 } 2027 PermissionInfo pi = new PermissionInfo(); 2028 pi.name = bp.name; 2029 pi.packageName = bp.sourcePackage; 2030 pi.nonLocalizedLabel = bp.name; 2031 pi.protectionLevel = bp.protectionLevel; 2032 return pi; 2033 } 2034 2035 @Override 2036 public PermissionInfo getPermissionInfo(String name, int flags) { 2037 // reader 2038 synchronized (mPackages) { 2039 final BasePermission p = mSettings.mPermissions.get(name); 2040 if (p != null) { 2041 return generatePermissionInfo(p, flags); 2042 } 2043 return null; 2044 } 2045 } 2046 2047 @Override 2048 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2049 // reader 2050 synchronized (mPackages) { 2051 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2052 for (BasePermission p : mSettings.mPermissions.values()) { 2053 if (group == null) { 2054 if (p.perm == null || p.perm.info.group == null) { 2055 out.add(generatePermissionInfo(p, flags)); 2056 } 2057 } else { 2058 if (p.perm != null && group.equals(p.perm.info.group)) { 2059 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2060 } 2061 } 2062 } 2063 2064 if (out.size() > 0) { 2065 return out; 2066 } 2067 return mPermissionGroups.containsKey(group) ? out : null; 2068 } 2069 } 2070 2071 @Override 2072 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2073 // reader 2074 synchronized (mPackages) { 2075 return PackageParser.generatePermissionGroupInfo( 2076 mPermissionGroups.get(name), flags); 2077 } 2078 } 2079 2080 @Override 2081 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2082 // reader 2083 synchronized (mPackages) { 2084 final int N = mPermissionGroups.size(); 2085 ArrayList<PermissionGroupInfo> out 2086 = new ArrayList<PermissionGroupInfo>(N); 2087 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2088 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2089 } 2090 return out; 2091 } 2092 } 2093 2094 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2095 int userId) { 2096 if (!sUserManager.exists(userId)) return null; 2097 PackageSetting ps = mSettings.mPackages.get(packageName); 2098 if (ps != null) { 2099 if (ps.pkg == null) { 2100 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2101 flags, userId); 2102 if (pInfo != null) { 2103 return pInfo.applicationInfo; 2104 } 2105 return null; 2106 } 2107 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2108 ps.readUserState(userId), userId); 2109 } 2110 return null; 2111 } 2112 2113 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2114 int userId) { 2115 if (!sUserManager.exists(userId)) return null; 2116 PackageSetting ps = mSettings.mPackages.get(packageName); 2117 if (ps != null) { 2118 PackageParser.Package pkg = ps.pkg; 2119 if (pkg == null) { 2120 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2121 return null; 2122 } 2123 // Only data remains, so we aren't worried about code paths 2124 pkg = new PackageParser.Package(packageName); 2125 pkg.applicationInfo.packageName = packageName; 2126 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2127 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2128 pkg.applicationInfo.dataDir = 2129 getDataPathForPackage(packageName, 0).getPath(); 2130 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2131 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2132 } 2133 return generatePackageInfo(pkg, flags, userId); 2134 } 2135 return null; 2136 } 2137 2138 @Override 2139 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2140 if (!sUserManager.exists(userId)) return null; 2141 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2142 // writer 2143 synchronized (mPackages) { 2144 PackageParser.Package p = mPackages.get(packageName); 2145 if (DEBUG_PACKAGE_INFO) Log.v( 2146 TAG, "getApplicationInfo " + packageName 2147 + ": " + p); 2148 if (p != null) { 2149 PackageSetting ps = mSettings.mPackages.get(packageName); 2150 if (ps == null) return null; 2151 // Note: isEnabledLP() does not apply here - always return info 2152 return PackageParser.generateApplicationInfo( 2153 p, flags, ps.readUserState(userId), userId); 2154 } 2155 if ("android".equals(packageName)||"system".equals(packageName)) { 2156 return mAndroidApplication; 2157 } 2158 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2159 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2160 } 2161 } 2162 return null; 2163 } 2164 2165 2166 @Override 2167 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2168 mContext.enforceCallingOrSelfPermission( 2169 android.Manifest.permission.CLEAR_APP_CACHE, null); 2170 // Queue up an async operation since clearing cache may take a little while. 2171 mHandler.post(new Runnable() { 2172 public void run() { 2173 mHandler.removeCallbacks(this); 2174 int retCode = -1; 2175 synchronized (mInstallLock) { 2176 retCode = mInstaller.freeCache(freeStorageSize); 2177 if (retCode < 0) { 2178 Slog.w(TAG, "Couldn't clear application caches"); 2179 } 2180 } 2181 if (observer != null) { 2182 try { 2183 observer.onRemoveCompleted(null, (retCode >= 0)); 2184 } catch (RemoteException e) { 2185 Slog.w(TAG, "RemoveException when invoking call back"); 2186 } 2187 } 2188 } 2189 }); 2190 } 2191 2192 @Override 2193 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2194 mContext.enforceCallingOrSelfPermission( 2195 android.Manifest.permission.CLEAR_APP_CACHE, null); 2196 // Queue up an async operation since clearing cache may take a little while. 2197 mHandler.post(new Runnable() { 2198 public void run() { 2199 mHandler.removeCallbacks(this); 2200 int retCode = -1; 2201 synchronized (mInstallLock) { 2202 retCode = mInstaller.freeCache(freeStorageSize); 2203 if (retCode < 0) { 2204 Slog.w(TAG, "Couldn't clear application caches"); 2205 } 2206 } 2207 if(pi != null) { 2208 try { 2209 // Callback via pending intent 2210 int code = (retCode >= 0) ? 1 : 0; 2211 pi.sendIntent(null, code, null, 2212 null, null); 2213 } catch (SendIntentException e1) { 2214 Slog.i(TAG, "Failed to send pending intent"); 2215 } 2216 } 2217 } 2218 }); 2219 } 2220 2221 void freeStorage(long freeStorageSize) throws IOException { 2222 synchronized (mInstallLock) { 2223 if (mInstaller.freeCache(freeStorageSize) < 0) { 2224 throw new IOException("Failed to free enough space"); 2225 } 2226 } 2227 } 2228 2229 @Override 2230 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2231 if (!sUserManager.exists(userId)) return null; 2232 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2233 synchronized (mPackages) { 2234 PackageParser.Activity a = mActivities.mActivities.get(component); 2235 2236 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2237 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2238 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2239 if (ps == null) return null; 2240 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2241 userId); 2242 } 2243 if (mResolveComponentName.equals(component)) { 2244 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2245 new PackageUserState(), userId); 2246 } 2247 } 2248 return null; 2249 } 2250 2251 @Override 2252 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2253 String resolvedType) { 2254 synchronized (mPackages) { 2255 PackageParser.Activity a = mActivities.mActivities.get(component); 2256 if (a == null) { 2257 return false; 2258 } 2259 for (int i=0; i<a.intents.size(); i++) { 2260 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2261 intent.getData(), intent.getCategories(), TAG) >= 0) { 2262 return true; 2263 } 2264 } 2265 return false; 2266 } 2267 } 2268 2269 @Override 2270 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2271 if (!sUserManager.exists(userId)) return null; 2272 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2273 synchronized (mPackages) { 2274 PackageParser.Activity a = mReceivers.mActivities.get(component); 2275 if (DEBUG_PACKAGE_INFO) Log.v( 2276 TAG, "getReceiverInfo " + component + ": " + a); 2277 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2278 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2279 if (ps == null) return null; 2280 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2281 userId); 2282 } 2283 } 2284 return null; 2285 } 2286 2287 @Override 2288 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2289 if (!sUserManager.exists(userId)) return null; 2290 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2291 synchronized (mPackages) { 2292 PackageParser.Service s = mServices.mServices.get(component); 2293 if (DEBUG_PACKAGE_INFO) Log.v( 2294 TAG, "getServiceInfo " + component + ": " + s); 2295 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2296 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2297 if (ps == null) return null; 2298 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2299 userId); 2300 } 2301 } 2302 return null; 2303 } 2304 2305 @Override 2306 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2307 if (!sUserManager.exists(userId)) return null; 2308 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2309 synchronized (mPackages) { 2310 PackageParser.Provider p = mProviders.mProviders.get(component); 2311 if (DEBUG_PACKAGE_INFO) Log.v( 2312 TAG, "getProviderInfo " + component + ": " + p); 2313 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2314 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2315 if (ps == null) return null; 2316 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2317 userId); 2318 } 2319 } 2320 return null; 2321 } 2322 2323 @Override 2324 public String[] getSystemSharedLibraryNames() { 2325 Set<String> libSet; 2326 synchronized (mPackages) { 2327 libSet = mSharedLibraries.keySet(); 2328 int size = libSet.size(); 2329 if (size > 0) { 2330 String[] libs = new String[size]; 2331 libSet.toArray(libs); 2332 return libs; 2333 } 2334 } 2335 return null; 2336 } 2337 2338 /** 2339 * @hide 2340 */ 2341 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2342 synchronized (mPackages) { 2343 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2344 if (lib != null && lib.apk != null) { 2345 return mPackages.get(lib.apk); 2346 } 2347 } 2348 return null; 2349 } 2350 2351 @Override 2352 public FeatureInfo[] getSystemAvailableFeatures() { 2353 Collection<FeatureInfo> featSet; 2354 synchronized (mPackages) { 2355 featSet = mAvailableFeatures.values(); 2356 int size = featSet.size(); 2357 if (size > 0) { 2358 FeatureInfo[] features = new FeatureInfo[size+1]; 2359 featSet.toArray(features); 2360 FeatureInfo fi = new FeatureInfo(); 2361 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2362 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2363 features[size] = fi; 2364 return features; 2365 } 2366 } 2367 return null; 2368 } 2369 2370 @Override 2371 public boolean hasSystemFeature(String name) { 2372 synchronized (mPackages) { 2373 return mAvailableFeatures.containsKey(name); 2374 } 2375 } 2376 2377 private void checkValidCaller(int uid, int userId) { 2378 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2379 return; 2380 2381 throw new SecurityException("Caller uid=" + uid 2382 + " is not privileged to communicate with user=" + userId); 2383 } 2384 2385 @Override 2386 public int checkPermission(String permName, String pkgName) { 2387 synchronized (mPackages) { 2388 PackageParser.Package p = mPackages.get(pkgName); 2389 if (p != null && p.mExtras != null) { 2390 PackageSetting ps = (PackageSetting)p.mExtras; 2391 if (ps.sharedUser != null) { 2392 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2393 return PackageManager.PERMISSION_GRANTED; 2394 } 2395 } else if (ps.grantedPermissions.contains(permName)) { 2396 return PackageManager.PERMISSION_GRANTED; 2397 } 2398 } 2399 } 2400 return PackageManager.PERMISSION_DENIED; 2401 } 2402 2403 @Override 2404 public int checkUidPermission(String permName, int uid) { 2405 synchronized (mPackages) { 2406 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2407 if (obj != null) { 2408 GrantedPermissions gp = (GrantedPermissions)obj; 2409 if (gp.grantedPermissions.contains(permName)) { 2410 return PackageManager.PERMISSION_GRANTED; 2411 } 2412 } else { 2413 ArraySet<String> perms = mSystemPermissions.get(uid); 2414 if (perms != null && perms.contains(permName)) { 2415 return PackageManager.PERMISSION_GRANTED; 2416 } 2417 } 2418 } 2419 return PackageManager.PERMISSION_DENIED; 2420 } 2421 2422 /** 2423 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2424 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2425 * @param checkShell TODO(yamasani): 2426 * @param message the message to log on security exception 2427 */ 2428 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2429 boolean checkShell, String message) { 2430 if (userId < 0) { 2431 throw new IllegalArgumentException("Invalid userId " + userId); 2432 } 2433 if (checkShell) { 2434 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2435 } 2436 if (userId == UserHandle.getUserId(callingUid)) return; 2437 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2438 if (requireFullPermission) { 2439 mContext.enforceCallingOrSelfPermission( 2440 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2441 } else { 2442 try { 2443 mContext.enforceCallingOrSelfPermission( 2444 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2445 } catch (SecurityException se) { 2446 mContext.enforceCallingOrSelfPermission( 2447 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2448 } 2449 } 2450 } 2451 } 2452 2453 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2454 if (callingUid == Process.SHELL_UID) { 2455 if (userHandle >= 0 2456 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2457 throw new SecurityException("Shell does not have permission to access user " 2458 + userHandle); 2459 } else if (userHandle < 0) { 2460 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2461 + Debug.getCallers(3)); 2462 } 2463 } 2464 } 2465 2466 private BasePermission findPermissionTreeLP(String permName) { 2467 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2468 if (permName.startsWith(bp.name) && 2469 permName.length() > bp.name.length() && 2470 permName.charAt(bp.name.length()) == '.') { 2471 return bp; 2472 } 2473 } 2474 return null; 2475 } 2476 2477 private BasePermission checkPermissionTreeLP(String permName) { 2478 if (permName != null) { 2479 BasePermission bp = findPermissionTreeLP(permName); 2480 if (bp != null) { 2481 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2482 return bp; 2483 } 2484 throw new SecurityException("Calling uid " 2485 + Binder.getCallingUid() 2486 + " is not allowed to add to permission tree " 2487 + bp.name + " owned by uid " + bp.uid); 2488 } 2489 } 2490 throw new SecurityException("No permission tree found for " + permName); 2491 } 2492 2493 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2494 if (s1 == null) { 2495 return s2 == null; 2496 } 2497 if (s2 == null) { 2498 return false; 2499 } 2500 if (s1.getClass() != s2.getClass()) { 2501 return false; 2502 } 2503 return s1.equals(s2); 2504 } 2505 2506 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2507 if (pi1.icon != pi2.icon) return false; 2508 if (pi1.logo != pi2.logo) return false; 2509 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2510 if (!compareStrings(pi1.name, pi2.name)) return false; 2511 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2512 // We'll take care of setting this one. 2513 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2514 // These are not currently stored in settings. 2515 //if (!compareStrings(pi1.group, pi2.group)) return false; 2516 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2517 //if (pi1.labelRes != pi2.labelRes) return false; 2518 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2519 return true; 2520 } 2521 2522 int permissionInfoFootprint(PermissionInfo info) { 2523 int size = info.name.length(); 2524 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2525 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2526 return size; 2527 } 2528 2529 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2530 int size = 0; 2531 for (BasePermission perm : mSettings.mPermissions.values()) { 2532 if (perm.uid == tree.uid) { 2533 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2534 } 2535 } 2536 return size; 2537 } 2538 2539 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2540 // We calculate the max size of permissions defined by this uid and throw 2541 // if that plus the size of 'info' would exceed our stated maximum. 2542 if (tree.uid != Process.SYSTEM_UID) { 2543 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2544 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2545 throw new SecurityException("Permission tree size cap exceeded"); 2546 } 2547 } 2548 } 2549 2550 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2551 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2552 throw new SecurityException("Label must be specified in permission"); 2553 } 2554 BasePermission tree = checkPermissionTreeLP(info.name); 2555 BasePermission bp = mSettings.mPermissions.get(info.name); 2556 boolean added = bp == null; 2557 boolean changed = true; 2558 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2559 if (added) { 2560 enforcePermissionCapLocked(info, tree); 2561 bp = new BasePermission(info.name, tree.sourcePackage, 2562 BasePermission.TYPE_DYNAMIC); 2563 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2564 throw new SecurityException( 2565 "Not allowed to modify non-dynamic permission " 2566 + info.name); 2567 } else { 2568 if (bp.protectionLevel == fixedLevel 2569 && bp.perm.owner.equals(tree.perm.owner) 2570 && bp.uid == tree.uid 2571 && comparePermissionInfos(bp.perm.info, info)) { 2572 changed = false; 2573 } 2574 } 2575 bp.protectionLevel = fixedLevel; 2576 info = new PermissionInfo(info); 2577 info.protectionLevel = fixedLevel; 2578 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2579 bp.perm.info.packageName = tree.perm.info.packageName; 2580 bp.uid = tree.uid; 2581 if (added) { 2582 mSettings.mPermissions.put(info.name, bp); 2583 } 2584 if (changed) { 2585 if (!async) { 2586 mSettings.writeLPr(); 2587 } else { 2588 scheduleWriteSettingsLocked(); 2589 } 2590 } 2591 return added; 2592 } 2593 2594 @Override 2595 public boolean addPermission(PermissionInfo info) { 2596 synchronized (mPackages) { 2597 return addPermissionLocked(info, false); 2598 } 2599 } 2600 2601 @Override 2602 public boolean addPermissionAsync(PermissionInfo info) { 2603 synchronized (mPackages) { 2604 return addPermissionLocked(info, true); 2605 } 2606 } 2607 2608 @Override 2609 public void removePermission(String name) { 2610 synchronized (mPackages) { 2611 checkPermissionTreeLP(name); 2612 BasePermission bp = mSettings.mPermissions.get(name); 2613 if (bp != null) { 2614 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2615 throw new SecurityException( 2616 "Not allowed to modify non-dynamic permission " 2617 + name); 2618 } 2619 mSettings.mPermissions.remove(name); 2620 mSettings.writeLPr(); 2621 } 2622 } 2623 } 2624 2625 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2626 int index = pkg.requestedPermissions.indexOf(bp.name); 2627 if (index == -1) { 2628 throw new SecurityException("Package " + pkg.packageName 2629 + " has not requested permission " + bp.name); 2630 } 2631 boolean isNormal = 2632 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2633 == PermissionInfo.PROTECTION_NORMAL); 2634 boolean isDangerous = 2635 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2636 == PermissionInfo.PROTECTION_DANGEROUS); 2637 boolean isDevelopment = 2638 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2639 2640 if (!isNormal && !isDangerous && !isDevelopment) { 2641 throw new SecurityException("Permission " + bp.name 2642 + " is not a changeable permission type"); 2643 } 2644 2645 if (isNormal || isDangerous) { 2646 if (pkg.requestedPermissionsRequired.get(index)) { 2647 throw new SecurityException("Can't change " + bp.name 2648 + ". It is required by the application"); 2649 } 2650 } 2651 } 2652 2653 @Override 2654 public void grantPermission(String packageName, String permissionName) { 2655 mContext.enforceCallingOrSelfPermission( 2656 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2657 synchronized (mPackages) { 2658 final PackageParser.Package pkg = mPackages.get(packageName); 2659 if (pkg == null) { 2660 throw new IllegalArgumentException("Unknown package: " + packageName); 2661 } 2662 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2663 if (bp == null) { 2664 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2665 } 2666 2667 checkGrantRevokePermissions(pkg, bp); 2668 2669 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2670 if (ps == null) { 2671 return; 2672 } 2673 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2674 if (gp.grantedPermissions.add(permissionName)) { 2675 if (ps.haveGids) { 2676 gp.gids = appendInts(gp.gids, bp.gids); 2677 } 2678 mSettings.writeLPr(); 2679 } 2680 } 2681 } 2682 2683 @Override 2684 public void revokePermission(String packageName, String permissionName) { 2685 int changedAppId = -1; 2686 2687 synchronized (mPackages) { 2688 final PackageParser.Package pkg = mPackages.get(packageName); 2689 if (pkg == null) { 2690 throw new IllegalArgumentException("Unknown package: " + packageName); 2691 } 2692 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2693 mContext.enforceCallingOrSelfPermission( 2694 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2695 } 2696 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2697 if (bp == null) { 2698 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2699 } 2700 2701 checkGrantRevokePermissions(pkg, bp); 2702 2703 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2704 if (ps == null) { 2705 return; 2706 } 2707 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2708 if (gp.grantedPermissions.remove(permissionName)) { 2709 gp.grantedPermissions.remove(permissionName); 2710 if (ps.haveGids) { 2711 gp.gids = removeInts(gp.gids, bp.gids); 2712 } 2713 mSettings.writeLPr(); 2714 changedAppId = ps.appId; 2715 } 2716 } 2717 2718 if (changedAppId >= 0) { 2719 // We changed the perm on someone, kill its processes. 2720 IActivityManager am = ActivityManagerNative.getDefault(); 2721 if (am != null) { 2722 final int callingUserId = UserHandle.getCallingUserId(); 2723 final long ident = Binder.clearCallingIdentity(); 2724 try { 2725 //XXX we should only revoke for the calling user's app permissions, 2726 // but for now we impact all users. 2727 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2728 // "revoke " + permissionName); 2729 int[] users = sUserManager.getUserIds(); 2730 for (int user : users) { 2731 am.killUid(UserHandle.getUid(user, changedAppId), 2732 "revoke " + permissionName); 2733 } 2734 } catch (RemoteException e) { 2735 } finally { 2736 Binder.restoreCallingIdentity(ident); 2737 } 2738 } 2739 } 2740 } 2741 2742 @Override 2743 public boolean isProtectedBroadcast(String actionName) { 2744 synchronized (mPackages) { 2745 return mProtectedBroadcasts.contains(actionName); 2746 } 2747 } 2748 2749 @Override 2750 public int checkSignatures(String pkg1, String pkg2) { 2751 synchronized (mPackages) { 2752 final PackageParser.Package p1 = mPackages.get(pkg1); 2753 final PackageParser.Package p2 = mPackages.get(pkg2); 2754 if (p1 == null || p1.mExtras == null 2755 || p2 == null || p2.mExtras == null) { 2756 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2757 } 2758 return compareSignatures(p1.mSignatures, p2.mSignatures); 2759 } 2760 } 2761 2762 @Override 2763 public int checkUidSignatures(int uid1, int uid2) { 2764 // Map to base uids. 2765 uid1 = UserHandle.getAppId(uid1); 2766 uid2 = UserHandle.getAppId(uid2); 2767 // reader 2768 synchronized (mPackages) { 2769 Signature[] s1; 2770 Signature[] s2; 2771 Object obj = mSettings.getUserIdLPr(uid1); 2772 if (obj != null) { 2773 if (obj instanceof SharedUserSetting) { 2774 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2775 } else if (obj instanceof PackageSetting) { 2776 s1 = ((PackageSetting)obj).signatures.mSignatures; 2777 } else { 2778 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2779 } 2780 } else { 2781 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2782 } 2783 obj = mSettings.getUserIdLPr(uid2); 2784 if (obj != null) { 2785 if (obj instanceof SharedUserSetting) { 2786 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2787 } else if (obj instanceof PackageSetting) { 2788 s2 = ((PackageSetting)obj).signatures.mSignatures; 2789 } else { 2790 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2791 } 2792 } else { 2793 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2794 } 2795 return compareSignatures(s1, s2); 2796 } 2797 } 2798 2799 /** 2800 * Compares two sets of signatures. Returns: 2801 * <br /> 2802 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2803 * <br /> 2804 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2805 * <br /> 2806 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2807 * <br /> 2808 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2809 * <br /> 2810 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2811 */ 2812 static int compareSignatures(Signature[] s1, Signature[] s2) { 2813 if (s1 == null) { 2814 return s2 == null 2815 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2816 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2817 } 2818 2819 if (s2 == null) { 2820 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2821 } 2822 2823 if (s1.length != s2.length) { 2824 return PackageManager.SIGNATURE_NO_MATCH; 2825 } 2826 2827 // Since both signature sets are of size 1, we can compare without HashSets. 2828 if (s1.length == 1) { 2829 return s1[0].equals(s2[0]) ? 2830 PackageManager.SIGNATURE_MATCH : 2831 PackageManager.SIGNATURE_NO_MATCH; 2832 } 2833 2834 ArraySet<Signature> set1 = new ArraySet<Signature>(); 2835 for (Signature sig : s1) { 2836 set1.add(sig); 2837 } 2838 ArraySet<Signature> set2 = new ArraySet<Signature>(); 2839 for (Signature sig : s2) { 2840 set2.add(sig); 2841 } 2842 // Make sure s2 contains all signatures in s1. 2843 if (set1.equals(set2)) { 2844 return PackageManager.SIGNATURE_MATCH; 2845 } 2846 return PackageManager.SIGNATURE_NO_MATCH; 2847 } 2848 2849 /** 2850 * If the database version for this type of package (internal storage or 2851 * external storage) is less than the version where package signatures 2852 * were updated, return true. 2853 */ 2854 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2855 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2856 DatabaseVersion.SIGNATURE_END_ENTITY)) 2857 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2858 DatabaseVersion.SIGNATURE_END_ENTITY)); 2859 } 2860 2861 /** 2862 * Used for backward compatibility to make sure any packages with 2863 * certificate chains get upgraded to the new style. {@code existingSigs} 2864 * will be in the old format (since they were stored on disk from before the 2865 * system upgrade) and {@code scannedSigs} will be in the newer format. 2866 */ 2867 private int compareSignaturesCompat(PackageSignatures existingSigs, 2868 PackageParser.Package scannedPkg) { 2869 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2870 return PackageManager.SIGNATURE_NO_MATCH; 2871 } 2872 2873 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 2874 for (Signature sig : existingSigs.mSignatures) { 2875 existingSet.add(sig); 2876 } 2877 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 2878 for (Signature sig : scannedPkg.mSignatures) { 2879 try { 2880 Signature[] chainSignatures = sig.getChainSignatures(); 2881 for (Signature chainSig : chainSignatures) { 2882 scannedCompatSet.add(chainSig); 2883 } 2884 } catch (CertificateEncodingException e) { 2885 scannedCompatSet.add(sig); 2886 } 2887 } 2888 /* 2889 * Make sure the expanded scanned set contains all signatures in the 2890 * existing one. 2891 */ 2892 if (scannedCompatSet.equals(existingSet)) { 2893 // Migrate the old signatures to the new scheme. 2894 existingSigs.assignSignatures(scannedPkg.mSignatures); 2895 // The new KeySets will be re-added later in the scanning process. 2896 synchronized (mPackages) { 2897 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2898 } 2899 return PackageManager.SIGNATURE_MATCH; 2900 } 2901 return PackageManager.SIGNATURE_NO_MATCH; 2902 } 2903 2904 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2905 if (isExternal(scannedPkg)) { 2906 return mSettings.isExternalDatabaseVersionOlderThan( 2907 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2908 } else { 2909 return mSettings.isInternalDatabaseVersionOlderThan( 2910 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2911 } 2912 } 2913 2914 private int compareSignaturesRecover(PackageSignatures existingSigs, 2915 PackageParser.Package scannedPkg) { 2916 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 2917 return PackageManager.SIGNATURE_NO_MATCH; 2918 } 2919 2920 String msg = null; 2921 try { 2922 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 2923 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 2924 + scannedPkg.packageName); 2925 return PackageManager.SIGNATURE_MATCH; 2926 } 2927 } catch (CertificateException e) { 2928 msg = e.getMessage(); 2929 } 2930 2931 logCriticalInfo(Log.INFO, 2932 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 2933 return PackageManager.SIGNATURE_NO_MATCH; 2934 } 2935 2936 @Override 2937 public String[] getPackagesForUid(int uid) { 2938 uid = UserHandle.getAppId(uid); 2939 // reader 2940 synchronized (mPackages) { 2941 Object obj = mSettings.getUserIdLPr(uid); 2942 if (obj instanceof SharedUserSetting) { 2943 final SharedUserSetting sus = (SharedUserSetting) obj; 2944 final int N = sus.packages.size(); 2945 final String[] res = new String[N]; 2946 final Iterator<PackageSetting> it = sus.packages.iterator(); 2947 int i = 0; 2948 while (it.hasNext()) { 2949 res[i++] = it.next().name; 2950 } 2951 return res; 2952 } else if (obj instanceof PackageSetting) { 2953 final PackageSetting ps = (PackageSetting) obj; 2954 return new String[] { ps.name }; 2955 } 2956 } 2957 return null; 2958 } 2959 2960 @Override 2961 public String getNameForUid(int uid) { 2962 // reader 2963 synchronized (mPackages) { 2964 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2965 if (obj instanceof SharedUserSetting) { 2966 final SharedUserSetting sus = (SharedUserSetting) obj; 2967 return sus.name + ":" + sus.userId; 2968 } else if (obj instanceof PackageSetting) { 2969 final PackageSetting ps = (PackageSetting) obj; 2970 return ps.name; 2971 } 2972 } 2973 return null; 2974 } 2975 2976 @Override 2977 public int getUidForSharedUser(String sharedUserName) { 2978 if(sharedUserName == null) { 2979 return -1; 2980 } 2981 // reader 2982 synchronized (mPackages) { 2983 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 2984 if (suid == null) { 2985 return -1; 2986 } 2987 return suid.userId; 2988 } 2989 } 2990 2991 @Override 2992 public int getFlagsForUid(int uid) { 2993 synchronized (mPackages) { 2994 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2995 if (obj instanceof SharedUserSetting) { 2996 final SharedUserSetting sus = (SharedUserSetting) obj; 2997 return sus.pkgFlags; 2998 } else if (obj instanceof PackageSetting) { 2999 final PackageSetting ps = (PackageSetting) obj; 3000 return ps.pkgFlags; 3001 } 3002 } 3003 return 0; 3004 } 3005 3006 @Override 3007 public int getPrivateFlagsForUid(int uid) { 3008 synchronized (mPackages) { 3009 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3010 if (obj instanceof SharedUserSetting) { 3011 final SharedUserSetting sus = (SharedUserSetting) obj; 3012 return sus.pkgPrivateFlags; 3013 } else if (obj instanceof PackageSetting) { 3014 final PackageSetting ps = (PackageSetting) obj; 3015 return ps.pkgPrivateFlags; 3016 } 3017 } 3018 return 0; 3019 } 3020 3021 @Override 3022 public boolean isUidPrivileged(int uid) { 3023 uid = UserHandle.getAppId(uid); 3024 // reader 3025 synchronized (mPackages) { 3026 Object obj = mSettings.getUserIdLPr(uid); 3027 if (obj instanceof SharedUserSetting) { 3028 final SharedUserSetting sus = (SharedUserSetting) obj; 3029 final Iterator<PackageSetting> it = sus.packages.iterator(); 3030 while (it.hasNext()) { 3031 if (it.next().isPrivileged()) { 3032 return true; 3033 } 3034 } 3035 } else if (obj instanceof PackageSetting) { 3036 final PackageSetting ps = (PackageSetting) obj; 3037 return ps.isPrivileged(); 3038 } 3039 } 3040 return false; 3041 } 3042 3043 @Override 3044 public String[] getAppOpPermissionPackages(String permissionName) { 3045 synchronized (mPackages) { 3046 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3047 if (pkgs == null) { 3048 return null; 3049 } 3050 return pkgs.toArray(new String[pkgs.size()]); 3051 } 3052 } 3053 3054 @Override 3055 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3056 int flags, int userId) { 3057 if (!sUserManager.exists(userId)) return null; 3058 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3059 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3060 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3061 } 3062 3063 @Override 3064 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3065 IntentFilter filter, int match, ComponentName activity) { 3066 final int userId = UserHandle.getCallingUserId(); 3067 if (DEBUG_PREFERRED) { 3068 Log.v(TAG, "setLastChosenActivity intent=" + intent 3069 + " resolvedType=" + resolvedType 3070 + " flags=" + flags 3071 + " filter=" + filter 3072 + " match=" + match 3073 + " activity=" + activity); 3074 filter.dump(new PrintStreamPrinter(System.out), " "); 3075 } 3076 intent.setComponent(null); 3077 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3078 // Find any earlier preferred or last chosen entries and nuke them 3079 findPreferredActivity(intent, resolvedType, 3080 flags, query, 0, false, true, false, userId); 3081 // Add the new activity as the last chosen for this filter 3082 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3083 "Setting last chosen"); 3084 } 3085 3086 @Override 3087 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3088 final int userId = UserHandle.getCallingUserId(); 3089 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3090 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3091 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3092 false, false, false, userId); 3093 } 3094 3095 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3096 int flags, List<ResolveInfo> query, int userId) { 3097 if (query != null) { 3098 final int N = query.size(); 3099 if (N == 1) { 3100 return query.get(0); 3101 } else if (N > 1) { 3102 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3103 // If there is more than one activity with the same priority, 3104 // then let the user decide between them. 3105 ResolveInfo r0 = query.get(0); 3106 ResolveInfo r1 = query.get(1); 3107 if (DEBUG_INTENT_MATCHING || debug) { 3108 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3109 + r1.activityInfo.name + "=" + r1.priority); 3110 } 3111 // If the first activity has a higher priority, or a different 3112 // default, then it is always desireable to pick it. 3113 if (r0.priority != r1.priority 3114 || r0.preferredOrder != r1.preferredOrder 3115 || r0.isDefault != r1.isDefault) { 3116 return query.get(0); 3117 } 3118 // If we have saved a preference for a preferred activity for 3119 // this Intent, use that. 3120 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3121 flags, query, r0.priority, true, false, debug, userId); 3122 if (ri != null) { 3123 return ri; 3124 } 3125 if (userId != 0) { 3126 ri = new ResolveInfo(mResolveInfo); 3127 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3128 ri.activityInfo.applicationInfo = new ApplicationInfo( 3129 ri.activityInfo.applicationInfo); 3130 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3131 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3132 return ri; 3133 } 3134 return mResolveInfo; 3135 } 3136 } 3137 return null; 3138 } 3139 3140 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3141 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3142 final int N = query.size(); 3143 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3144 .get(userId); 3145 // Get the list of persistent preferred activities that handle the intent 3146 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3147 List<PersistentPreferredActivity> pprefs = ppir != null 3148 ? ppir.queryIntent(intent, resolvedType, 3149 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3150 : null; 3151 if (pprefs != null && pprefs.size() > 0) { 3152 final int M = pprefs.size(); 3153 for (int i=0; i<M; i++) { 3154 final PersistentPreferredActivity ppa = pprefs.get(i); 3155 if (DEBUG_PREFERRED || debug) { 3156 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3157 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3158 + "\n component=" + ppa.mComponent); 3159 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3160 } 3161 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3162 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3163 if (DEBUG_PREFERRED || debug) { 3164 Slog.v(TAG, "Found persistent preferred activity:"); 3165 if (ai != null) { 3166 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3167 } else { 3168 Slog.v(TAG, " null"); 3169 } 3170 } 3171 if (ai == null) { 3172 // This previously registered persistent preferred activity 3173 // component is no longer known. Ignore it and do NOT remove it. 3174 continue; 3175 } 3176 for (int j=0; j<N; j++) { 3177 final ResolveInfo ri = query.get(j); 3178 if (!ri.activityInfo.applicationInfo.packageName 3179 .equals(ai.applicationInfo.packageName)) { 3180 continue; 3181 } 3182 if (!ri.activityInfo.name.equals(ai.name)) { 3183 continue; 3184 } 3185 // Found a persistent preference that can handle the intent. 3186 if (DEBUG_PREFERRED || debug) { 3187 Slog.v(TAG, "Returning persistent preferred activity: " + 3188 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3189 } 3190 return ri; 3191 } 3192 } 3193 } 3194 return null; 3195 } 3196 3197 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3198 List<ResolveInfo> query, int priority, boolean always, 3199 boolean removeMatches, boolean debug, int userId) { 3200 if (!sUserManager.exists(userId)) return null; 3201 // writer 3202 synchronized (mPackages) { 3203 if (intent.getSelector() != null) { 3204 intent = intent.getSelector(); 3205 } 3206 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3207 3208 // Try to find a matching persistent preferred activity. 3209 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3210 debug, userId); 3211 3212 // If a persistent preferred activity matched, use it. 3213 if (pri != null) { 3214 return pri; 3215 } 3216 3217 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3218 // Get the list of preferred activities that handle the intent 3219 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3220 List<PreferredActivity> prefs = pir != null 3221 ? pir.queryIntent(intent, resolvedType, 3222 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3223 : null; 3224 if (prefs != null && prefs.size() > 0) { 3225 boolean changed = false; 3226 try { 3227 // First figure out how good the original match set is. 3228 // We will only allow preferred activities that came 3229 // from the same match quality. 3230 int match = 0; 3231 3232 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3233 3234 final int N = query.size(); 3235 for (int j=0; j<N; j++) { 3236 final ResolveInfo ri = query.get(j); 3237 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3238 + ": 0x" + Integer.toHexString(match)); 3239 if (ri.match > match) { 3240 match = ri.match; 3241 } 3242 } 3243 3244 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3245 + Integer.toHexString(match)); 3246 3247 match &= IntentFilter.MATCH_CATEGORY_MASK; 3248 final int M = prefs.size(); 3249 for (int i=0; i<M; i++) { 3250 final PreferredActivity pa = prefs.get(i); 3251 if (DEBUG_PREFERRED || debug) { 3252 Slog.v(TAG, "Checking PreferredActivity ds=" 3253 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3254 + "\n component=" + pa.mPref.mComponent); 3255 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3256 } 3257 if (pa.mPref.mMatch != match) { 3258 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3259 + Integer.toHexString(pa.mPref.mMatch)); 3260 continue; 3261 } 3262 // If it's not an "always" type preferred activity and that's what we're 3263 // looking for, skip it. 3264 if (always && !pa.mPref.mAlways) { 3265 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3266 continue; 3267 } 3268 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3269 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3270 if (DEBUG_PREFERRED || debug) { 3271 Slog.v(TAG, "Found preferred activity:"); 3272 if (ai != null) { 3273 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3274 } else { 3275 Slog.v(TAG, " null"); 3276 } 3277 } 3278 if (ai == null) { 3279 // This previously registered preferred activity 3280 // component is no longer known. Most likely an update 3281 // to the app was installed and in the new version this 3282 // component no longer exists. Clean it up by removing 3283 // it from the preferred activities list, and skip it. 3284 Slog.w(TAG, "Removing dangling preferred activity: " 3285 + pa.mPref.mComponent); 3286 pir.removeFilter(pa); 3287 changed = true; 3288 continue; 3289 } 3290 for (int j=0; j<N; j++) { 3291 final ResolveInfo ri = query.get(j); 3292 if (!ri.activityInfo.applicationInfo.packageName 3293 .equals(ai.applicationInfo.packageName)) { 3294 continue; 3295 } 3296 if (!ri.activityInfo.name.equals(ai.name)) { 3297 continue; 3298 } 3299 3300 if (removeMatches) { 3301 pir.removeFilter(pa); 3302 changed = true; 3303 if (DEBUG_PREFERRED) { 3304 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3305 } 3306 break; 3307 } 3308 3309 // Okay we found a previously set preferred or last chosen app. 3310 // If the result set is different from when this 3311 // was created, we need to clear it and re-ask the 3312 // user their preference, if we're looking for an "always" type entry. 3313 if (always && !pa.mPref.sameSet(query)) { 3314 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3315 + intent + " type " + resolvedType); 3316 if (DEBUG_PREFERRED) { 3317 Slog.v(TAG, "Removing preferred activity since set changed " 3318 + pa.mPref.mComponent); 3319 } 3320 pir.removeFilter(pa); 3321 // Re-add the filter as a "last chosen" entry (!always) 3322 PreferredActivity lastChosen = new PreferredActivity( 3323 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3324 pir.addFilter(lastChosen); 3325 changed = true; 3326 return null; 3327 } 3328 3329 // Yay! Either the set matched or we're looking for the last chosen 3330 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3331 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3332 return ri; 3333 } 3334 } 3335 } finally { 3336 if (changed) { 3337 if (DEBUG_PREFERRED) { 3338 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3339 } 3340 scheduleWritePackageRestrictionsLocked(userId); 3341 } 3342 } 3343 } 3344 } 3345 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3346 return null; 3347 } 3348 3349 /* 3350 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3351 */ 3352 @Override 3353 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3354 int targetUserId) { 3355 mContext.enforceCallingOrSelfPermission( 3356 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3357 List<CrossProfileIntentFilter> matches = 3358 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3359 if (matches != null) { 3360 int size = matches.size(); 3361 for (int i = 0; i < size; i++) { 3362 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3363 } 3364 } 3365 return false; 3366 } 3367 3368 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3369 String resolvedType, int userId) { 3370 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3371 if (resolver != null) { 3372 return resolver.queryIntent(intent, resolvedType, false, userId); 3373 } 3374 return null; 3375 } 3376 3377 @Override 3378 public List<ResolveInfo> queryIntentActivities(Intent intent, 3379 String resolvedType, int flags, int userId) { 3380 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3381 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3382 ComponentName comp = intent.getComponent(); 3383 if (comp == null) { 3384 if (intent.getSelector() != null) { 3385 intent = intent.getSelector(); 3386 comp = intent.getComponent(); 3387 } 3388 } 3389 3390 if (comp != null) { 3391 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3392 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3393 if (ai != null) { 3394 final ResolveInfo ri = new ResolveInfo(); 3395 ri.activityInfo = ai; 3396 list.add(ri); 3397 } 3398 return list; 3399 } 3400 3401 // reader 3402 synchronized (mPackages) { 3403 final String pkgName = intent.getPackage(); 3404 if (pkgName == null) { 3405 List<CrossProfileIntentFilter> matchingFilters = 3406 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3407 // Check for results that need to skip the current profile. 3408 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3409 resolvedType, flags, userId); 3410 if (resolveInfo != null) { 3411 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3412 result.add(resolveInfo); 3413 return result; 3414 } 3415 // Check for cross profile results. 3416 resolveInfo = queryCrossProfileIntents( 3417 matchingFilters, intent, resolvedType, flags, userId); 3418 3419 // Check for results in the current profile. 3420 List<ResolveInfo> result = mActivities.queryIntent( 3421 intent, resolvedType, flags, userId); 3422 if (resolveInfo != null) { 3423 result.add(resolveInfo); 3424 Collections.sort(result, mResolvePrioritySorter); 3425 } 3426 return result; 3427 } 3428 final PackageParser.Package pkg = mPackages.get(pkgName); 3429 if (pkg != null) { 3430 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3431 pkg.activities, userId); 3432 } 3433 return new ArrayList<ResolveInfo>(); 3434 } 3435 } 3436 3437 private ResolveInfo querySkipCurrentProfileIntents( 3438 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3439 int flags, int sourceUserId) { 3440 if (matchingFilters != null) { 3441 int size = matchingFilters.size(); 3442 for (int i = 0; i < size; i ++) { 3443 CrossProfileIntentFilter filter = matchingFilters.get(i); 3444 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3445 // Checking if there are activities in the target user that can handle the 3446 // intent. 3447 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3448 flags, sourceUserId); 3449 if (resolveInfo != null) { 3450 return resolveInfo; 3451 } 3452 } 3453 } 3454 } 3455 return null; 3456 } 3457 3458 // Return matching ResolveInfo if any for skip current profile intent filters. 3459 private ResolveInfo queryCrossProfileIntents( 3460 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3461 int flags, int sourceUserId) { 3462 if (matchingFilters != null) { 3463 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3464 // match the same intent. For performance reasons, it is better not to 3465 // run queryIntent twice for the same userId 3466 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3467 int size = matchingFilters.size(); 3468 for (int i = 0; i < size; i++) { 3469 CrossProfileIntentFilter filter = matchingFilters.get(i); 3470 int targetUserId = filter.getTargetUserId(); 3471 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3472 && !alreadyTriedUserIds.get(targetUserId)) { 3473 // Checking if there are activities in the target user that can handle the 3474 // intent. 3475 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3476 flags, sourceUserId); 3477 if (resolveInfo != null) return resolveInfo; 3478 alreadyTriedUserIds.put(targetUserId, true); 3479 } 3480 } 3481 } 3482 return null; 3483 } 3484 3485 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3486 String resolvedType, int flags, int sourceUserId) { 3487 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3488 resolvedType, flags, filter.getTargetUserId()); 3489 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3490 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3491 } 3492 return null; 3493 } 3494 3495 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3496 int sourceUserId, int targetUserId) { 3497 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3498 String className; 3499 if (targetUserId == UserHandle.USER_OWNER) { 3500 className = FORWARD_INTENT_TO_USER_OWNER; 3501 } else { 3502 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3503 } 3504 ComponentName forwardingActivityComponentName = new ComponentName( 3505 mAndroidApplication.packageName, className); 3506 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3507 sourceUserId); 3508 if (targetUserId == UserHandle.USER_OWNER) { 3509 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3510 forwardingResolveInfo.noResourceId = true; 3511 } 3512 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3513 forwardingResolveInfo.priority = 0; 3514 forwardingResolveInfo.preferredOrder = 0; 3515 forwardingResolveInfo.match = 0; 3516 forwardingResolveInfo.isDefault = true; 3517 forwardingResolveInfo.filter = filter; 3518 forwardingResolveInfo.targetUserId = targetUserId; 3519 return forwardingResolveInfo; 3520 } 3521 3522 @Override 3523 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3524 Intent[] specifics, String[] specificTypes, Intent intent, 3525 String resolvedType, int flags, int userId) { 3526 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3527 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3528 false, "query intent activity options"); 3529 final String resultsAction = intent.getAction(); 3530 3531 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3532 | PackageManager.GET_RESOLVED_FILTER, userId); 3533 3534 if (DEBUG_INTENT_MATCHING) { 3535 Log.v(TAG, "Query " + intent + ": " + results); 3536 } 3537 3538 int specificsPos = 0; 3539 int N; 3540 3541 // todo: note that the algorithm used here is O(N^2). This 3542 // isn't a problem in our current environment, but if we start running 3543 // into situations where we have more than 5 or 10 matches then this 3544 // should probably be changed to something smarter... 3545 3546 // First we go through and resolve each of the specific items 3547 // that were supplied, taking care of removing any corresponding 3548 // duplicate items in the generic resolve list. 3549 if (specifics != null) { 3550 for (int i=0; i<specifics.length; i++) { 3551 final Intent sintent = specifics[i]; 3552 if (sintent == null) { 3553 continue; 3554 } 3555 3556 if (DEBUG_INTENT_MATCHING) { 3557 Log.v(TAG, "Specific #" + i + ": " + sintent); 3558 } 3559 3560 String action = sintent.getAction(); 3561 if (resultsAction != null && resultsAction.equals(action)) { 3562 // If this action was explicitly requested, then don't 3563 // remove things that have it. 3564 action = null; 3565 } 3566 3567 ResolveInfo ri = null; 3568 ActivityInfo ai = null; 3569 3570 ComponentName comp = sintent.getComponent(); 3571 if (comp == null) { 3572 ri = resolveIntent( 3573 sintent, 3574 specificTypes != null ? specificTypes[i] : null, 3575 flags, userId); 3576 if (ri == null) { 3577 continue; 3578 } 3579 if (ri == mResolveInfo) { 3580 // ACK! Must do something better with this. 3581 } 3582 ai = ri.activityInfo; 3583 comp = new ComponentName(ai.applicationInfo.packageName, 3584 ai.name); 3585 } else { 3586 ai = getActivityInfo(comp, flags, userId); 3587 if (ai == null) { 3588 continue; 3589 } 3590 } 3591 3592 // Look for any generic query activities that are duplicates 3593 // of this specific one, and remove them from the results. 3594 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3595 N = results.size(); 3596 int j; 3597 for (j=specificsPos; j<N; j++) { 3598 ResolveInfo sri = results.get(j); 3599 if ((sri.activityInfo.name.equals(comp.getClassName()) 3600 && sri.activityInfo.applicationInfo.packageName.equals( 3601 comp.getPackageName())) 3602 || (action != null && sri.filter.matchAction(action))) { 3603 results.remove(j); 3604 if (DEBUG_INTENT_MATCHING) Log.v( 3605 TAG, "Removing duplicate item from " + j 3606 + " due to specific " + specificsPos); 3607 if (ri == null) { 3608 ri = sri; 3609 } 3610 j--; 3611 N--; 3612 } 3613 } 3614 3615 // Add this specific item to its proper place. 3616 if (ri == null) { 3617 ri = new ResolveInfo(); 3618 ri.activityInfo = ai; 3619 } 3620 results.add(specificsPos, ri); 3621 ri.specificIndex = i; 3622 specificsPos++; 3623 } 3624 } 3625 3626 // Now we go through the remaining generic results and remove any 3627 // duplicate actions that are found here. 3628 N = results.size(); 3629 for (int i=specificsPos; i<N-1; i++) { 3630 final ResolveInfo rii = results.get(i); 3631 if (rii.filter == null) { 3632 continue; 3633 } 3634 3635 // Iterate over all of the actions of this result's intent 3636 // filter... typically this should be just one. 3637 final Iterator<String> it = rii.filter.actionsIterator(); 3638 if (it == null) { 3639 continue; 3640 } 3641 while (it.hasNext()) { 3642 final String action = it.next(); 3643 if (resultsAction != null && resultsAction.equals(action)) { 3644 // If this action was explicitly requested, then don't 3645 // remove things that have it. 3646 continue; 3647 } 3648 for (int j=i+1; j<N; j++) { 3649 final ResolveInfo rij = results.get(j); 3650 if (rij.filter != null && rij.filter.hasAction(action)) { 3651 results.remove(j); 3652 if (DEBUG_INTENT_MATCHING) Log.v( 3653 TAG, "Removing duplicate item from " + j 3654 + " due to action " + action + " at " + i); 3655 j--; 3656 N--; 3657 } 3658 } 3659 } 3660 3661 // If the caller didn't request filter information, drop it now 3662 // so we don't have to marshall/unmarshall it. 3663 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3664 rii.filter = null; 3665 } 3666 } 3667 3668 // Filter out the caller activity if so requested. 3669 if (caller != null) { 3670 N = results.size(); 3671 for (int i=0; i<N; i++) { 3672 ActivityInfo ainfo = results.get(i).activityInfo; 3673 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3674 && caller.getClassName().equals(ainfo.name)) { 3675 results.remove(i); 3676 break; 3677 } 3678 } 3679 } 3680 3681 // If the caller didn't request filter information, 3682 // drop them now so we don't have to 3683 // marshall/unmarshall it. 3684 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3685 N = results.size(); 3686 for (int i=0; i<N; i++) { 3687 results.get(i).filter = null; 3688 } 3689 } 3690 3691 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3692 return results; 3693 } 3694 3695 @Override 3696 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3697 int userId) { 3698 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3699 ComponentName comp = intent.getComponent(); 3700 if (comp == null) { 3701 if (intent.getSelector() != null) { 3702 intent = intent.getSelector(); 3703 comp = intent.getComponent(); 3704 } 3705 } 3706 if (comp != null) { 3707 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3708 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3709 if (ai != null) { 3710 ResolveInfo ri = new ResolveInfo(); 3711 ri.activityInfo = ai; 3712 list.add(ri); 3713 } 3714 return list; 3715 } 3716 3717 // reader 3718 synchronized (mPackages) { 3719 String pkgName = intent.getPackage(); 3720 if (pkgName == null) { 3721 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3722 } 3723 final PackageParser.Package pkg = mPackages.get(pkgName); 3724 if (pkg != null) { 3725 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3726 userId); 3727 } 3728 return null; 3729 } 3730 } 3731 3732 @Override 3733 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3734 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3735 if (!sUserManager.exists(userId)) return null; 3736 if (query != null) { 3737 if (query.size() >= 1) { 3738 // If there is more than one service with the same priority, 3739 // just arbitrarily pick the first one. 3740 return query.get(0); 3741 } 3742 } 3743 return null; 3744 } 3745 3746 @Override 3747 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3748 int userId) { 3749 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3750 ComponentName comp = intent.getComponent(); 3751 if (comp == null) { 3752 if (intent.getSelector() != null) { 3753 intent = intent.getSelector(); 3754 comp = intent.getComponent(); 3755 } 3756 } 3757 if (comp != null) { 3758 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3759 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3760 if (si != null) { 3761 final ResolveInfo ri = new ResolveInfo(); 3762 ri.serviceInfo = si; 3763 list.add(ri); 3764 } 3765 return list; 3766 } 3767 3768 // reader 3769 synchronized (mPackages) { 3770 String pkgName = intent.getPackage(); 3771 if (pkgName == null) { 3772 return mServices.queryIntent(intent, resolvedType, flags, userId); 3773 } 3774 final PackageParser.Package pkg = mPackages.get(pkgName); 3775 if (pkg != null) { 3776 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3777 userId); 3778 } 3779 return null; 3780 } 3781 } 3782 3783 @Override 3784 public List<ResolveInfo> queryIntentContentProviders( 3785 Intent intent, String resolvedType, int flags, int userId) { 3786 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3787 ComponentName comp = intent.getComponent(); 3788 if (comp == null) { 3789 if (intent.getSelector() != null) { 3790 intent = intent.getSelector(); 3791 comp = intent.getComponent(); 3792 } 3793 } 3794 if (comp != null) { 3795 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3796 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3797 if (pi != null) { 3798 final ResolveInfo ri = new ResolveInfo(); 3799 ri.providerInfo = pi; 3800 list.add(ri); 3801 } 3802 return list; 3803 } 3804 3805 // reader 3806 synchronized (mPackages) { 3807 String pkgName = intent.getPackage(); 3808 if (pkgName == null) { 3809 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3810 } 3811 final PackageParser.Package pkg = mPackages.get(pkgName); 3812 if (pkg != null) { 3813 return mProviders.queryIntentForPackage( 3814 intent, resolvedType, flags, pkg.providers, userId); 3815 } 3816 return null; 3817 } 3818 } 3819 3820 @Override 3821 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3822 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3823 3824 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3825 3826 // writer 3827 synchronized (mPackages) { 3828 ArrayList<PackageInfo> list; 3829 if (listUninstalled) { 3830 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3831 for (PackageSetting ps : mSettings.mPackages.values()) { 3832 PackageInfo pi; 3833 if (ps.pkg != null) { 3834 pi = generatePackageInfo(ps.pkg, flags, userId); 3835 } else { 3836 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3837 } 3838 if (pi != null) { 3839 list.add(pi); 3840 } 3841 } 3842 } else { 3843 list = new ArrayList<PackageInfo>(mPackages.size()); 3844 for (PackageParser.Package p : mPackages.values()) { 3845 PackageInfo pi = generatePackageInfo(p, flags, userId); 3846 if (pi != null) { 3847 list.add(pi); 3848 } 3849 } 3850 } 3851 3852 return new ParceledListSlice<PackageInfo>(list); 3853 } 3854 } 3855 3856 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3857 String[] permissions, boolean[] tmp, int flags, int userId) { 3858 int numMatch = 0; 3859 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3860 for (int i=0; i<permissions.length; i++) { 3861 if (gp.grantedPermissions.contains(permissions[i])) { 3862 tmp[i] = true; 3863 numMatch++; 3864 } else { 3865 tmp[i] = false; 3866 } 3867 } 3868 if (numMatch == 0) { 3869 return; 3870 } 3871 PackageInfo pi; 3872 if (ps.pkg != null) { 3873 pi = generatePackageInfo(ps.pkg, flags, userId); 3874 } else { 3875 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3876 } 3877 // The above might return null in cases of uninstalled apps or install-state 3878 // skew across users/profiles. 3879 if (pi != null) { 3880 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3881 if (numMatch == permissions.length) { 3882 pi.requestedPermissions = permissions; 3883 } else { 3884 pi.requestedPermissions = new String[numMatch]; 3885 numMatch = 0; 3886 for (int i=0; i<permissions.length; i++) { 3887 if (tmp[i]) { 3888 pi.requestedPermissions[numMatch] = permissions[i]; 3889 numMatch++; 3890 } 3891 } 3892 } 3893 } 3894 list.add(pi); 3895 } 3896 } 3897 3898 @Override 3899 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3900 String[] permissions, int flags, int userId) { 3901 if (!sUserManager.exists(userId)) return null; 3902 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3903 3904 // writer 3905 synchronized (mPackages) { 3906 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3907 boolean[] tmpBools = new boolean[permissions.length]; 3908 if (listUninstalled) { 3909 for (PackageSetting ps : mSettings.mPackages.values()) { 3910 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3911 } 3912 } else { 3913 for (PackageParser.Package pkg : mPackages.values()) { 3914 PackageSetting ps = (PackageSetting)pkg.mExtras; 3915 if (ps != null) { 3916 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3917 userId); 3918 } 3919 } 3920 } 3921 3922 return new ParceledListSlice<PackageInfo>(list); 3923 } 3924 } 3925 3926 @Override 3927 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3928 if (!sUserManager.exists(userId)) return null; 3929 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3930 3931 // writer 3932 synchronized (mPackages) { 3933 ArrayList<ApplicationInfo> list; 3934 if (listUninstalled) { 3935 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3936 for (PackageSetting ps : mSettings.mPackages.values()) { 3937 ApplicationInfo ai; 3938 if (ps.pkg != null) { 3939 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3940 ps.readUserState(userId), userId); 3941 } else { 3942 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3943 } 3944 if (ai != null) { 3945 list.add(ai); 3946 } 3947 } 3948 } else { 3949 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3950 for (PackageParser.Package p : mPackages.values()) { 3951 if (p.mExtras != null) { 3952 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3953 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3954 if (ai != null) { 3955 list.add(ai); 3956 } 3957 } 3958 } 3959 } 3960 3961 return new ParceledListSlice<ApplicationInfo>(list); 3962 } 3963 } 3964 3965 public List<ApplicationInfo> getPersistentApplications(int flags) { 3966 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3967 3968 // reader 3969 synchronized (mPackages) { 3970 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3971 final int userId = UserHandle.getCallingUserId(); 3972 while (i.hasNext()) { 3973 final PackageParser.Package p = i.next(); 3974 if (p.applicationInfo != null 3975 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3976 && (!mSafeMode || isSystemApp(p))) { 3977 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3978 if (ps != null) { 3979 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3980 ps.readUserState(userId), userId); 3981 if (ai != null) { 3982 finalList.add(ai); 3983 } 3984 } 3985 } 3986 } 3987 } 3988 3989 return finalList; 3990 } 3991 3992 @Override 3993 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3994 if (!sUserManager.exists(userId)) return null; 3995 // reader 3996 synchronized (mPackages) { 3997 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3998 PackageSetting ps = provider != null 3999 ? mSettings.mPackages.get(provider.owner.packageName) 4000 : null; 4001 return ps != null 4002 && mSettings.isEnabledLPr(provider.info, flags, userId) 4003 && (!mSafeMode || (provider.info.applicationInfo.flags 4004 &ApplicationInfo.FLAG_SYSTEM) != 0) 4005 ? PackageParser.generateProviderInfo(provider, flags, 4006 ps.readUserState(userId), userId) 4007 : null; 4008 } 4009 } 4010 4011 /** 4012 * @deprecated 4013 */ 4014 @Deprecated 4015 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4016 // reader 4017 synchronized (mPackages) { 4018 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4019 .entrySet().iterator(); 4020 final int userId = UserHandle.getCallingUserId(); 4021 while (i.hasNext()) { 4022 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4023 PackageParser.Provider p = entry.getValue(); 4024 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4025 4026 if (ps != null && p.syncable 4027 && (!mSafeMode || (p.info.applicationInfo.flags 4028 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4029 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4030 ps.readUserState(userId), userId); 4031 if (info != null) { 4032 outNames.add(entry.getKey()); 4033 outInfo.add(info); 4034 } 4035 } 4036 } 4037 } 4038 } 4039 4040 @Override 4041 public List<ProviderInfo> queryContentProviders(String processName, 4042 int uid, int flags) { 4043 ArrayList<ProviderInfo> finalList = null; 4044 // reader 4045 synchronized (mPackages) { 4046 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4047 final int userId = processName != null ? 4048 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4049 while (i.hasNext()) { 4050 final PackageParser.Provider p = i.next(); 4051 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4052 if (ps != null && p.info.authority != null 4053 && (processName == null 4054 || (p.info.processName.equals(processName) 4055 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4056 && mSettings.isEnabledLPr(p.info, flags, userId) 4057 && (!mSafeMode 4058 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4059 if (finalList == null) { 4060 finalList = new ArrayList<ProviderInfo>(3); 4061 } 4062 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4063 ps.readUserState(userId), userId); 4064 if (info != null) { 4065 finalList.add(info); 4066 } 4067 } 4068 } 4069 } 4070 4071 if (finalList != null) { 4072 Collections.sort(finalList, mProviderInitOrderSorter); 4073 } 4074 4075 return finalList; 4076 } 4077 4078 @Override 4079 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4080 int flags) { 4081 // reader 4082 synchronized (mPackages) { 4083 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4084 return PackageParser.generateInstrumentationInfo(i, flags); 4085 } 4086 } 4087 4088 @Override 4089 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4090 int flags) { 4091 ArrayList<InstrumentationInfo> finalList = 4092 new ArrayList<InstrumentationInfo>(); 4093 4094 // reader 4095 synchronized (mPackages) { 4096 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4097 while (i.hasNext()) { 4098 final PackageParser.Instrumentation p = i.next(); 4099 if (targetPackage == null 4100 || targetPackage.equals(p.info.targetPackage)) { 4101 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4102 flags); 4103 if (ii != null) { 4104 finalList.add(ii); 4105 } 4106 } 4107 } 4108 } 4109 4110 return finalList; 4111 } 4112 4113 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4114 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4115 if (overlays == null) { 4116 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4117 return; 4118 } 4119 for (PackageParser.Package opkg : overlays.values()) { 4120 // Not much to do if idmap fails: we already logged the error 4121 // and we certainly don't want to abort installation of pkg simply 4122 // because an overlay didn't fit properly. For these reasons, 4123 // ignore the return value of createIdmapForPackagePairLI. 4124 createIdmapForPackagePairLI(pkg, opkg); 4125 } 4126 } 4127 4128 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4129 PackageParser.Package opkg) { 4130 if (!opkg.mTrustedOverlay) { 4131 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4132 opkg.baseCodePath + ": overlay not trusted"); 4133 return false; 4134 } 4135 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4136 if (overlaySet == null) { 4137 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4138 opkg.baseCodePath + " but target package has no known overlays"); 4139 return false; 4140 } 4141 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4142 // TODO: generate idmap for split APKs 4143 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4144 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4145 + opkg.baseCodePath); 4146 return false; 4147 } 4148 PackageParser.Package[] overlayArray = 4149 overlaySet.values().toArray(new PackageParser.Package[0]); 4150 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4151 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4152 return p1.mOverlayPriority - p2.mOverlayPriority; 4153 } 4154 }; 4155 Arrays.sort(overlayArray, cmp); 4156 4157 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4158 int i = 0; 4159 for (PackageParser.Package p : overlayArray) { 4160 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4161 } 4162 return true; 4163 } 4164 4165 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4166 final File[] files = dir.listFiles(); 4167 if (ArrayUtils.isEmpty(files)) { 4168 Log.d(TAG, "No files in app dir " + dir); 4169 return; 4170 } 4171 4172 if (DEBUG_PACKAGE_SCANNING) { 4173 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4174 + " flags=0x" + Integer.toHexString(parseFlags)); 4175 } 4176 4177 for (File file : files) { 4178 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4179 && !PackageInstallerService.isStageName(file.getName()); 4180 if (!isPackage) { 4181 // Ignore entries which are not packages 4182 continue; 4183 } 4184 try { 4185 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4186 scanFlags, currentTime, null); 4187 } catch (PackageManagerException e) { 4188 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4189 4190 // Delete invalid userdata apps 4191 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4192 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4193 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4194 if (file.isDirectory()) { 4195 mInstaller.rmPackageDir(file.getAbsolutePath()); 4196 } else { 4197 file.delete(); 4198 } 4199 } 4200 } 4201 } 4202 } 4203 4204 private static File getSettingsProblemFile() { 4205 File dataDir = Environment.getDataDirectory(); 4206 File systemDir = new File(dataDir, "system"); 4207 File fname = new File(systemDir, "uiderrors.txt"); 4208 return fname; 4209 } 4210 4211 static void reportSettingsProblem(int priority, String msg) { 4212 logCriticalInfo(priority, msg); 4213 } 4214 4215 static void logCriticalInfo(int priority, String msg) { 4216 Slog.println(priority, TAG, msg); 4217 EventLogTags.writePmCriticalInfo(msg); 4218 try { 4219 File fname = getSettingsProblemFile(); 4220 FileOutputStream out = new FileOutputStream(fname, true); 4221 PrintWriter pw = new FastPrintWriter(out); 4222 SimpleDateFormat formatter = new SimpleDateFormat(); 4223 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4224 pw.println(dateString + ": " + msg); 4225 pw.close(); 4226 FileUtils.setPermissions( 4227 fname.toString(), 4228 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4229 -1, -1); 4230 } catch (java.io.IOException e) { 4231 } 4232 } 4233 4234 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4235 PackageParser.Package pkg, File srcFile, int parseFlags) 4236 throws PackageManagerException { 4237 if (ps != null 4238 && ps.codePath.equals(srcFile) 4239 && ps.timeStamp == srcFile.lastModified() 4240 && !isCompatSignatureUpdateNeeded(pkg) 4241 && !isRecoverSignatureUpdateNeeded(pkg)) { 4242 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4243 if (ps.signatures.mSignatures != null 4244 && ps.signatures.mSignatures.length != 0 4245 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4246 // Optimization: reuse the existing cached certificates 4247 // if the package appears to be unchanged. 4248 pkg.mSignatures = ps.signatures.mSignatures; 4249 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4250 synchronized (mPackages) { 4251 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4252 } 4253 return; 4254 } 4255 4256 Slog.w(TAG, "PackageSetting for " + ps.name 4257 + " is missing signatures. Collecting certs again to recover them."); 4258 } else { 4259 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4260 } 4261 4262 try { 4263 pp.collectCertificates(pkg, parseFlags); 4264 pp.collectManifestDigest(pkg); 4265 } catch (PackageParserException e) { 4266 throw PackageManagerException.from(e); 4267 } 4268 } 4269 4270 /* 4271 * Scan a package and return the newly parsed package. 4272 * Returns null in case of errors and the error code is stored in mLastScanError 4273 */ 4274 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4275 long currentTime, UserHandle user) throws PackageManagerException { 4276 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4277 parseFlags |= mDefParseFlags; 4278 PackageParser pp = new PackageParser(); 4279 pp.setSeparateProcesses(mSeparateProcesses); 4280 pp.setOnlyCoreApps(mOnlyCore); 4281 pp.setDisplayMetrics(mMetrics); 4282 4283 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4284 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4285 } 4286 4287 final PackageParser.Package pkg; 4288 try { 4289 pkg = pp.parsePackage(scanFile, parseFlags); 4290 } catch (PackageParserException e) { 4291 throw PackageManagerException.from(e); 4292 } 4293 4294 PackageSetting ps = null; 4295 PackageSetting updatedPkg; 4296 // reader 4297 synchronized (mPackages) { 4298 // Look to see if we already know about this package. 4299 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4300 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4301 // This package has been renamed to its original name. Let's 4302 // use that. 4303 ps = mSettings.peekPackageLPr(oldName); 4304 } 4305 // If there was no original package, see one for the real package name. 4306 if (ps == null) { 4307 ps = mSettings.peekPackageLPr(pkg.packageName); 4308 } 4309 // Check to see if this package could be hiding/updating a system 4310 // package. Must look for it either under the original or real 4311 // package name depending on our state. 4312 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4313 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4314 } 4315 boolean updatedPkgBetter = false; 4316 // First check if this is a system package that may involve an update 4317 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4318 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4319 // it needs to drop FLAG_PRIVILEGED. 4320 if (locationIsPrivileged(scanFile)) { 4321 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4322 } else { 4323 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4324 } 4325 4326 if (ps != null && !ps.codePath.equals(scanFile)) { 4327 // The path has changed from what was last scanned... check the 4328 // version of the new path against what we have stored to determine 4329 // what to do. 4330 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4331 if (pkg.mVersionCode <= ps.versionCode) { 4332 // The system package has been updated and the code path does not match 4333 // Ignore entry. Skip it. 4334 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4335 + " ignored: updated version " + ps.versionCode 4336 + " better than this " + pkg.mVersionCode); 4337 if (!updatedPkg.codePath.equals(scanFile)) { 4338 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4339 + ps.name + " changing from " + updatedPkg.codePathString 4340 + " to " + scanFile); 4341 updatedPkg.codePath = scanFile; 4342 updatedPkg.codePathString = scanFile.toString(); 4343 updatedPkg.resourcePath = scanFile; 4344 updatedPkg.resourcePathString = scanFile.toString(); 4345 } 4346 updatedPkg.pkg = pkg; 4347 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4348 } else { 4349 // The current app on the system partition is better than 4350 // what we have updated to on the data partition; switch 4351 // back to the system partition version. 4352 // At this point, its safely assumed that package installation for 4353 // apps in system partition will go through. If not there won't be a working 4354 // version of the app 4355 // writer 4356 synchronized (mPackages) { 4357 // Just remove the loaded entries from package lists. 4358 mPackages.remove(ps.name); 4359 } 4360 4361 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4362 + " reverting from " + ps.codePathString 4363 + ": new version " + pkg.mVersionCode 4364 + " better than installed " + ps.versionCode); 4365 4366 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4367 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4368 getAppDexInstructionSets(ps)); 4369 synchronized (mInstallLock) { 4370 args.cleanUpResourcesLI(); 4371 } 4372 synchronized (mPackages) { 4373 mSettings.enableSystemPackageLPw(ps.name); 4374 } 4375 updatedPkgBetter = true; 4376 } 4377 } 4378 } 4379 4380 if (updatedPkg != null) { 4381 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4382 // initially 4383 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4384 4385 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4386 // flag set initially 4387 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4388 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4389 } 4390 } 4391 4392 // Verify certificates against what was last scanned 4393 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4394 4395 /* 4396 * A new system app appeared, but we already had a non-system one of the 4397 * same name installed earlier. 4398 */ 4399 boolean shouldHideSystemApp = false; 4400 if (updatedPkg == null && ps != null 4401 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4402 /* 4403 * Check to make sure the signatures match first. If they don't, 4404 * wipe the installed application and its data. 4405 */ 4406 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4407 != PackageManager.SIGNATURE_MATCH) { 4408 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4409 + " signatures don't match existing userdata copy; removing"); 4410 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4411 ps = null; 4412 } else { 4413 /* 4414 * If the newly-added system app is an older version than the 4415 * already installed version, hide it. It will be scanned later 4416 * and re-added like an update. 4417 */ 4418 if (pkg.mVersionCode <= ps.versionCode) { 4419 shouldHideSystemApp = true; 4420 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4421 + " but new version " + pkg.mVersionCode + " better than installed " 4422 + ps.versionCode + "; hiding system"); 4423 } else { 4424 /* 4425 * The newly found system app is a newer version that the 4426 * one previously installed. Simply remove the 4427 * already-installed application and replace it with our own 4428 * while keeping the application data. 4429 */ 4430 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4431 + " reverting from " + ps.codePathString + ": new version " 4432 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4433 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4434 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4435 getAppDexInstructionSets(ps)); 4436 synchronized (mInstallLock) { 4437 args.cleanUpResourcesLI(); 4438 } 4439 } 4440 } 4441 } 4442 4443 // The apk is forward locked (not public) if its code and resources 4444 // are kept in different files. (except for app in either system or 4445 // vendor path). 4446 // TODO grab this value from PackageSettings 4447 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4448 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4449 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4450 } 4451 } 4452 4453 // TODO: extend to support forward-locked splits 4454 String resourcePath = null; 4455 String baseResourcePath = null; 4456 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4457 if (ps != null && ps.resourcePathString != null) { 4458 resourcePath = ps.resourcePathString; 4459 baseResourcePath = ps.resourcePathString; 4460 } else { 4461 // Should not happen at all. Just log an error. 4462 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4463 } 4464 } else { 4465 resourcePath = pkg.codePath; 4466 baseResourcePath = pkg.baseCodePath; 4467 } 4468 4469 // Set application objects path explicitly. 4470 pkg.applicationInfo.setCodePath(pkg.codePath); 4471 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4472 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4473 pkg.applicationInfo.setResourcePath(resourcePath); 4474 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4475 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4476 4477 // Note that we invoke the following method only if we are about to unpack an application 4478 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4479 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4480 4481 /* 4482 * If the system app should be overridden by a previously installed 4483 * data, hide the system app now and let the /data/app scan pick it up 4484 * again. 4485 */ 4486 if (shouldHideSystemApp) { 4487 synchronized (mPackages) { 4488 /* 4489 * We have to grant systems permissions before we hide, because 4490 * grantPermissions will assume the package update is trying to 4491 * expand its permissions. 4492 */ 4493 grantPermissionsLPw(pkg, true, pkg.packageName); 4494 mSettings.disableSystemPackageLPw(pkg.packageName); 4495 } 4496 } 4497 4498 return scannedPkg; 4499 } 4500 4501 private static String fixProcessName(String defProcessName, 4502 String processName, int uid) { 4503 if (processName == null) { 4504 return defProcessName; 4505 } 4506 return processName; 4507 } 4508 4509 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4510 throws PackageManagerException { 4511 if (pkgSetting.signatures.mSignatures != null) { 4512 // Already existing package. Make sure signatures match 4513 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4514 == PackageManager.SIGNATURE_MATCH; 4515 if (!match) { 4516 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4517 == PackageManager.SIGNATURE_MATCH; 4518 } 4519 if (!match) { 4520 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 4521 == PackageManager.SIGNATURE_MATCH; 4522 } 4523 if (!match) { 4524 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4525 + pkg.packageName + " signatures do not match the " 4526 + "previously installed version; ignoring!"); 4527 } 4528 } 4529 4530 // Check for shared user signatures 4531 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4532 // Already existing package. Make sure signatures match 4533 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4534 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4535 if (!match) { 4536 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4537 == PackageManager.SIGNATURE_MATCH; 4538 } 4539 if (!match) { 4540 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 4541 == PackageManager.SIGNATURE_MATCH; 4542 } 4543 if (!match) { 4544 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4545 "Package " + pkg.packageName 4546 + " has no signatures that match those in shared user " 4547 + pkgSetting.sharedUser.name + "; ignoring!"); 4548 } 4549 } 4550 } 4551 4552 /** 4553 * Enforces that only the system UID or root's UID can call a method exposed 4554 * via Binder. 4555 * 4556 * @param message used as message if SecurityException is thrown 4557 * @throws SecurityException if the caller is not system or root 4558 */ 4559 private static final void enforceSystemOrRoot(String message) { 4560 final int uid = Binder.getCallingUid(); 4561 if (uid != Process.SYSTEM_UID && uid != 0) { 4562 throw new SecurityException(message); 4563 } 4564 } 4565 4566 @Override 4567 public void performBootDexOpt() { 4568 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4569 4570 // Before everything else, see whether we need to fstrim. 4571 try { 4572 IMountService ms = PackageHelper.getMountService(); 4573 if (ms != null) { 4574 final boolean isUpgrade = isUpgrade(); 4575 boolean doTrim = isUpgrade; 4576 if (doTrim) { 4577 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 4578 } else { 4579 final long interval = android.provider.Settings.Global.getLong( 4580 mContext.getContentResolver(), 4581 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 4582 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 4583 if (interval > 0) { 4584 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 4585 if (timeSinceLast > interval) { 4586 doTrim = true; 4587 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 4588 + "; running immediately"); 4589 } 4590 } 4591 } 4592 if (doTrim) { 4593 if (!isFirstBoot()) { 4594 try { 4595 ActivityManagerNative.getDefault().showBootMessage( 4596 mContext.getResources().getString( 4597 R.string.android_upgrading_fstrim), true); 4598 } catch (RemoteException e) { 4599 } 4600 } 4601 ms.runMaintenance(); 4602 } 4603 } else { 4604 Slog.e(TAG, "Mount service unavailable!"); 4605 } 4606 } catch (RemoteException e) { 4607 // Can't happen; MountService is local 4608 } 4609 4610 final ArraySet<PackageParser.Package> pkgs; 4611 synchronized (mPackages) { 4612 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 4613 } 4614 4615 if (pkgs != null) { 4616 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4617 // in case the device runs out of space. 4618 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4619 // Give priority to core apps. 4620 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4621 PackageParser.Package pkg = it.next(); 4622 if (pkg.coreApp) { 4623 if (DEBUG_DEXOPT) { 4624 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 4625 } 4626 sortedPkgs.add(pkg); 4627 it.remove(); 4628 } 4629 } 4630 // Give priority to system apps that listen for pre boot complete. 4631 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4632 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 4633 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4634 PackageParser.Package pkg = it.next(); 4635 if (pkgNames.contains(pkg.packageName)) { 4636 if (DEBUG_DEXOPT) { 4637 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 4638 } 4639 sortedPkgs.add(pkg); 4640 it.remove(); 4641 } 4642 } 4643 // Give priority to system apps. 4644 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4645 PackageParser.Package pkg = it.next(); 4646 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 4647 if (DEBUG_DEXOPT) { 4648 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 4649 } 4650 sortedPkgs.add(pkg); 4651 it.remove(); 4652 } 4653 } 4654 // Give priority to updated system apps. 4655 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4656 PackageParser.Package pkg = it.next(); 4657 if (pkg.isUpdatedSystemApp()) { 4658 if (DEBUG_DEXOPT) { 4659 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 4660 } 4661 sortedPkgs.add(pkg); 4662 it.remove(); 4663 } 4664 } 4665 // Give priority to apps that listen for boot complete. 4666 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4667 pkgNames = getPackageNamesForIntent(intent); 4668 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4669 PackageParser.Package pkg = it.next(); 4670 if (pkgNames.contains(pkg.packageName)) { 4671 if (DEBUG_DEXOPT) { 4672 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 4673 } 4674 sortedPkgs.add(pkg); 4675 it.remove(); 4676 } 4677 } 4678 // Filter out packages that aren't recently used. 4679 filterRecentlyUsedApps(pkgs); 4680 // Add all remaining apps. 4681 for (PackageParser.Package pkg : pkgs) { 4682 if (DEBUG_DEXOPT) { 4683 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 4684 } 4685 sortedPkgs.add(pkg); 4686 } 4687 4688 // If we want to be lazy, filter everything that wasn't recently used. 4689 if (mLazyDexOpt) { 4690 filterRecentlyUsedApps(sortedPkgs); 4691 } 4692 4693 int i = 0; 4694 int total = sortedPkgs.size(); 4695 File dataDir = Environment.getDataDirectory(); 4696 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 4697 if (lowThreshold == 0) { 4698 throw new IllegalStateException("Invalid low memory threshold"); 4699 } 4700 for (PackageParser.Package pkg : sortedPkgs) { 4701 long usableSpace = dataDir.getUsableSpace(); 4702 if (usableSpace < lowThreshold) { 4703 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 4704 break; 4705 } 4706 performBootDexOpt(pkg, ++i, total); 4707 } 4708 } 4709 } 4710 4711 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 4712 // Filter out packages that aren't recently used. 4713 // 4714 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4715 // should do a full dexopt. 4716 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4717 int total = pkgs.size(); 4718 int skipped = 0; 4719 long now = System.currentTimeMillis(); 4720 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4721 PackageParser.Package pkg = i.next(); 4722 long then = pkg.mLastPackageUsageTimeInMills; 4723 if (then + mDexOptLRUThresholdInMills < now) { 4724 if (DEBUG_DEXOPT) { 4725 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4726 ((then == 0) ? "never" : new Date(then))); 4727 } 4728 i.remove(); 4729 skipped++; 4730 } 4731 } 4732 if (DEBUG_DEXOPT) { 4733 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4734 } 4735 } 4736 } 4737 4738 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 4739 List<ResolveInfo> ris = null; 4740 try { 4741 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4742 intent, null, 0, UserHandle.USER_OWNER); 4743 } catch (RemoteException e) { 4744 } 4745 ArraySet<String> pkgNames = new ArraySet<String>(); 4746 if (ris != null) { 4747 for (ResolveInfo ri : ris) { 4748 pkgNames.add(ri.activityInfo.packageName); 4749 } 4750 } 4751 return pkgNames; 4752 } 4753 4754 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4755 if (DEBUG_DEXOPT) { 4756 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4757 } 4758 if (!isFirstBoot()) { 4759 try { 4760 ActivityManagerNative.getDefault().showBootMessage( 4761 mContext.getResources().getString(R.string.android_upgrading_apk, 4762 curr, total), true); 4763 } catch (RemoteException e) { 4764 } 4765 } 4766 PackageParser.Package p = pkg; 4767 synchronized (mInstallLock) { 4768 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 4769 false /* force dex */, false /* defer */, true /* include dependencies */); 4770 } 4771 } 4772 4773 @Override 4774 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4775 return performDexOpt(packageName, instructionSet, false); 4776 } 4777 4778 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4779 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4780 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4781 if (!dexopt && !updateUsage) { 4782 // We aren't going to dexopt or update usage, so bail early. 4783 return false; 4784 } 4785 PackageParser.Package p; 4786 final String targetInstructionSet; 4787 synchronized (mPackages) { 4788 p = mPackages.get(packageName); 4789 if (p == null) { 4790 return false; 4791 } 4792 if (updateUsage) { 4793 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4794 } 4795 mPackageUsage.write(false); 4796 if (!dexopt) { 4797 // We aren't going to dexopt, so bail early. 4798 return false; 4799 } 4800 4801 targetInstructionSet = instructionSet != null ? instructionSet : 4802 getPrimaryInstructionSet(p.applicationInfo); 4803 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4804 return false; 4805 } 4806 } 4807 4808 synchronized (mInstallLock) { 4809 final String[] instructionSets = new String[] { targetInstructionSet }; 4810 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 4811 false /* forceDex */, false /* defer */, true /* inclDependencies */); 4812 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 4813 } 4814 } 4815 4816 public ArraySet<String> getPackagesThatNeedDexOpt() { 4817 ArraySet<String> pkgs = null; 4818 synchronized (mPackages) { 4819 for (PackageParser.Package p : mPackages.values()) { 4820 if (DEBUG_DEXOPT) { 4821 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4822 } 4823 if (!p.mDexOptPerformed.isEmpty()) { 4824 continue; 4825 } 4826 if (pkgs == null) { 4827 pkgs = new ArraySet<String>(); 4828 } 4829 pkgs.add(p.packageName); 4830 } 4831 } 4832 return pkgs; 4833 } 4834 4835 public void shutdown() { 4836 mPackageUsage.write(true); 4837 } 4838 4839 @Override 4840 public void forceDexOpt(String packageName) { 4841 enforceSystemOrRoot("forceDexOpt"); 4842 4843 PackageParser.Package pkg; 4844 synchronized (mPackages) { 4845 pkg = mPackages.get(packageName); 4846 if (pkg == null) { 4847 throw new IllegalArgumentException("Missing package: " + packageName); 4848 } 4849 } 4850 4851 synchronized (mInstallLock) { 4852 final String[] instructionSets = new String[] { 4853 getPrimaryInstructionSet(pkg.applicationInfo) }; 4854 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 4855 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 4856 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 4857 throw new IllegalStateException("Failed to dexopt: " + res); 4858 } 4859 } 4860 } 4861 4862 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4863 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4864 Slog.w(TAG, "Unable to update from " + oldPkg.name 4865 + " to " + newPkg.packageName 4866 + ": old package not in system partition"); 4867 return false; 4868 } else if (mPackages.get(oldPkg.name) != null) { 4869 Slog.w(TAG, "Unable to update from " + oldPkg.name 4870 + " to " + newPkg.packageName 4871 + ": old package still exists"); 4872 return false; 4873 } 4874 return true; 4875 } 4876 4877 private File getDataPathForPackage(String packageName, int userId) { 4878 /* 4879 * Until we fully support multiple users, return the directory we 4880 * previously would have. The PackageManagerTests will need to be 4881 * revised when this is changed back.. 4882 */ 4883 if (userId == 0) { 4884 return new File(mAppDataDir, packageName); 4885 } else { 4886 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4887 + File.separator + packageName); 4888 } 4889 } 4890 4891 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4892 int[] users = sUserManager.getUserIds(); 4893 int res = mInstaller.install(packageName, uid, uid, seinfo); 4894 if (res < 0) { 4895 return res; 4896 } 4897 for (int user : users) { 4898 if (user != 0) { 4899 res = mInstaller.createUserData(packageName, 4900 UserHandle.getUid(user, uid), user, seinfo); 4901 if (res < 0) { 4902 return res; 4903 } 4904 } 4905 } 4906 return res; 4907 } 4908 4909 private int removeDataDirsLI(String packageName) { 4910 int[] users = sUserManager.getUserIds(); 4911 int res = 0; 4912 for (int user : users) { 4913 int resInner = mInstaller.remove(packageName, user); 4914 if (resInner < 0) { 4915 res = resInner; 4916 } 4917 } 4918 4919 return res; 4920 } 4921 4922 private int deleteCodeCacheDirsLI(String packageName) { 4923 int[] users = sUserManager.getUserIds(); 4924 int res = 0; 4925 for (int user : users) { 4926 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4927 if (resInner < 0) { 4928 res = resInner; 4929 } 4930 } 4931 return res; 4932 } 4933 4934 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4935 PackageParser.Package changingLib) { 4936 if (file.path != null) { 4937 usesLibraryFiles.add(file.path); 4938 return; 4939 } 4940 PackageParser.Package p = mPackages.get(file.apk); 4941 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4942 // If we are doing this while in the middle of updating a library apk, 4943 // then we need to make sure to use that new apk for determining the 4944 // dependencies here. (We haven't yet finished committing the new apk 4945 // to the package manager state.) 4946 if (p == null || p.packageName.equals(changingLib.packageName)) { 4947 p = changingLib; 4948 } 4949 } 4950 if (p != null) { 4951 usesLibraryFiles.addAll(p.getAllCodePaths()); 4952 } 4953 } 4954 4955 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4956 PackageParser.Package changingLib) throws PackageManagerException { 4957 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4958 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4959 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4960 for (int i=0; i<N; i++) { 4961 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4962 if (file == null) { 4963 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4964 "Package " + pkg.packageName + " requires unavailable shared library " 4965 + pkg.usesLibraries.get(i) + "; failing!"); 4966 } 4967 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4968 } 4969 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4970 for (int i=0; i<N; i++) { 4971 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4972 if (file == null) { 4973 Slog.w(TAG, "Package " + pkg.packageName 4974 + " desires unavailable shared library " 4975 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4976 } else { 4977 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4978 } 4979 } 4980 N = usesLibraryFiles.size(); 4981 if (N > 0) { 4982 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4983 } else { 4984 pkg.usesLibraryFiles = null; 4985 } 4986 } 4987 } 4988 4989 private static boolean hasString(List<String> list, List<String> which) { 4990 if (list == null) { 4991 return false; 4992 } 4993 for (int i=list.size()-1; i>=0; i--) { 4994 for (int j=which.size()-1; j>=0; j--) { 4995 if (which.get(j).equals(list.get(i))) { 4996 return true; 4997 } 4998 } 4999 } 5000 return false; 5001 } 5002 5003 private void updateAllSharedLibrariesLPw() { 5004 for (PackageParser.Package pkg : mPackages.values()) { 5005 try { 5006 updateSharedLibrariesLPw(pkg, null); 5007 } catch (PackageManagerException e) { 5008 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5009 } 5010 } 5011 } 5012 5013 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5014 PackageParser.Package changingPkg) { 5015 ArrayList<PackageParser.Package> res = null; 5016 for (PackageParser.Package pkg : mPackages.values()) { 5017 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5018 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5019 if (res == null) { 5020 res = new ArrayList<PackageParser.Package>(); 5021 } 5022 res.add(pkg); 5023 try { 5024 updateSharedLibrariesLPw(pkg, changingPkg); 5025 } catch (PackageManagerException e) { 5026 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5027 } 5028 } 5029 } 5030 return res; 5031 } 5032 5033 /** 5034 * Derive the value of the {@code cpuAbiOverride} based on the provided 5035 * value and an optional stored value from the package settings. 5036 */ 5037 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5038 String cpuAbiOverride = null; 5039 5040 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5041 cpuAbiOverride = null; 5042 } else if (abiOverride != null) { 5043 cpuAbiOverride = abiOverride; 5044 } else if (settings != null) { 5045 cpuAbiOverride = settings.cpuAbiOverrideString; 5046 } 5047 5048 return cpuAbiOverride; 5049 } 5050 5051 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5052 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5053 boolean success = false; 5054 try { 5055 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5056 currentTime, user); 5057 success = true; 5058 return res; 5059 } finally { 5060 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5061 removeDataDirsLI(pkg.packageName); 5062 } 5063 } 5064 } 5065 5066 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5067 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5068 final File scanFile = new File(pkg.codePath); 5069 if (pkg.applicationInfo.getCodePath() == null || 5070 pkg.applicationInfo.getResourcePath() == null) { 5071 // Bail out. The resource and code paths haven't been set. 5072 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5073 "Code and resource paths haven't been set correctly"); 5074 } 5075 5076 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5077 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5078 } else { 5079 // Only allow system apps to be flagged as core apps. 5080 pkg.coreApp = false; 5081 } 5082 5083 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5084 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5085 } 5086 5087 if (mCustomResolverComponentName != null && 5088 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5089 setUpCustomResolverActivity(pkg); 5090 } 5091 5092 if (pkg.packageName.equals("android")) { 5093 synchronized (mPackages) { 5094 if (mAndroidApplication != null) { 5095 Slog.w(TAG, "*************************************************"); 5096 Slog.w(TAG, "Core android package being redefined. Skipping."); 5097 Slog.w(TAG, " file=" + scanFile); 5098 Slog.w(TAG, "*************************************************"); 5099 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5100 "Core android package being redefined. Skipping."); 5101 } 5102 5103 // Set up information for our fall-back user intent resolution activity. 5104 mPlatformPackage = pkg; 5105 pkg.mVersionCode = mSdkVersion; 5106 mAndroidApplication = pkg.applicationInfo; 5107 5108 if (!mResolverReplaced) { 5109 mResolveActivity.applicationInfo = mAndroidApplication; 5110 mResolveActivity.name = ResolverActivity.class.getName(); 5111 mResolveActivity.packageName = mAndroidApplication.packageName; 5112 mResolveActivity.processName = "system:ui"; 5113 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5114 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5115 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5116 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5117 mResolveActivity.exported = true; 5118 mResolveActivity.enabled = true; 5119 mResolveInfo.activityInfo = mResolveActivity; 5120 mResolveInfo.priority = 0; 5121 mResolveInfo.preferredOrder = 0; 5122 mResolveInfo.match = 0; 5123 mResolveComponentName = new ComponentName( 5124 mAndroidApplication.packageName, mResolveActivity.name); 5125 } 5126 } 5127 } 5128 5129 if (DEBUG_PACKAGE_SCANNING) { 5130 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5131 Log.d(TAG, "Scanning package " + pkg.packageName); 5132 } 5133 5134 if (mPackages.containsKey(pkg.packageName) 5135 || mSharedLibraries.containsKey(pkg.packageName)) { 5136 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5137 "Application package " + pkg.packageName 5138 + " already installed. Skipping duplicate."); 5139 } 5140 5141 // Initialize package source and resource directories 5142 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5143 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5144 5145 SharedUserSetting suid = null; 5146 PackageSetting pkgSetting = null; 5147 5148 if (!isSystemApp(pkg)) { 5149 // Only system apps can use these features. 5150 pkg.mOriginalPackages = null; 5151 pkg.mRealPackage = null; 5152 pkg.mAdoptPermissions = null; 5153 } 5154 5155 // writer 5156 synchronized (mPackages) { 5157 if (pkg.mSharedUserId != null) { 5158 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5159 if (suid == null) { 5160 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5161 "Creating application package " + pkg.packageName 5162 + " for shared user failed"); 5163 } 5164 if (DEBUG_PACKAGE_SCANNING) { 5165 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5166 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5167 + "): packages=" + suid.packages); 5168 } 5169 } 5170 5171 // Check if we are renaming from an original package name. 5172 PackageSetting origPackage = null; 5173 String realName = null; 5174 if (pkg.mOriginalPackages != null) { 5175 // This package may need to be renamed to a previously 5176 // installed name. Let's check on that... 5177 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5178 if (pkg.mOriginalPackages.contains(renamed)) { 5179 // This package had originally been installed as the 5180 // original name, and we have already taken care of 5181 // transitioning to the new one. Just update the new 5182 // one to continue using the old name. 5183 realName = pkg.mRealPackage; 5184 if (!pkg.packageName.equals(renamed)) { 5185 // Callers into this function may have already taken 5186 // care of renaming the package; only do it here if 5187 // it is not already done. 5188 pkg.setPackageName(renamed); 5189 } 5190 5191 } else { 5192 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5193 if ((origPackage = mSettings.peekPackageLPr( 5194 pkg.mOriginalPackages.get(i))) != null) { 5195 // We do have the package already installed under its 5196 // original name... should we use it? 5197 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5198 // New package is not compatible with original. 5199 origPackage = null; 5200 continue; 5201 } else if (origPackage.sharedUser != null) { 5202 // Make sure uid is compatible between packages. 5203 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5204 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5205 + " to " + pkg.packageName + ": old uid " 5206 + origPackage.sharedUser.name 5207 + " differs from " + pkg.mSharedUserId); 5208 origPackage = null; 5209 continue; 5210 } 5211 } else { 5212 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5213 + pkg.packageName + " to old name " + origPackage.name); 5214 } 5215 break; 5216 } 5217 } 5218 } 5219 } 5220 5221 if (mTransferedPackages.contains(pkg.packageName)) { 5222 Slog.w(TAG, "Package " + pkg.packageName 5223 + " was transferred to another, but its .apk remains"); 5224 } 5225 5226 // Just create the setting, don't add it yet. For already existing packages 5227 // the PkgSetting exists already and doesn't have to be created. 5228 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5229 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5230 pkg.applicationInfo.primaryCpuAbi, 5231 pkg.applicationInfo.secondaryCpuAbi, 5232 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5233 user, false); 5234 if (pkgSetting == null) { 5235 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5236 "Creating application package " + pkg.packageName + " failed"); 5237 } 5238 5239 if (pkgSetting.origPackage != null) { 5240 // If we are first transitioning from an original package, 5241 // fix up the new package's name now. We need to do this after 5242 // looking up the package under its new name, so getPackageLP 5243 // can take care of fiddling things correctly. 5244 pkg.setPackageName(origPackage.name); 5245 5246 // File a report about this. 5247 String msg = "New package " + pkgSetting.realName 5248 + " renamed to replace old package " + pkgSetting.name; 5249 reportSettingsProblem(Log.WARN, msg); 5250 5251 // Make a note of it. 5252 mTransferedPackages.add(origPackage.name); 5253 5254 // No longer need to retain this. 5255 pkgSetting.origPackage = null; 5256 } 5257 5258 if (realName != null) { 5259 // Make a note of it. 5260 mTransferedPackages.add(pkg.packageName); 5261 } 5262 5263 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5264 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5265 } 5266 5267 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5268 // Check all shared libraries and map to their actual file path. 5269 // We only do this here for apps not on a system dir, because those 5270 // are the only ones that can fail an install due to this. We 5271 // will take care of the system apps by updating all of their 5272 // library paths after the scan is done. 5273 updateSharedLibrariesLPw(pkg, null); 5274 } 5275 5276 if (mFoundPolicyFile) { 5277 SELinuxMMAC.assignSeinfoValue(pkg); 5278 } 5279 5280 pkg.applicationInfo.uid = pkgSetting.appId; 5281 pkg.mExtras = pkgSetting; 5282 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5283 try { 5284 verifySignaturesLP(pkgSetting, pkg); 5285 // We just determined the app is signed correctly, so bring 5286 // over the latest parsed certs. 5287 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5288 } catch (PackageManagerException e) { 5289 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5290 throw e; 5291 } 5292 // The signature has changed, but this package is in the system 5293 // image... let's recover! 5294 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5295 // However... if this package is part of a shared user, but it 5296 // doesn't match the signature of the shared user, let's fail. 5297 // What this means is that you can't change the signatures 5298 // associated with an overall shared user, which doesn't seem all 5299 // that unreasonable. 5300 if (pkgSetting.sharedUser != null) { 5301 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5302 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5303 throw new PackageManagerException( 5304 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5305 "Signature mismatch for shared user : " 5306 + pkgSetting.sharedUser); 5307 } 5308 } 5309 // File a report about this. 5310 String msg = "System package " + pkg.packageName 5311 + " signature changed; retaining data."; 5312 reportSettingsProblem(Log.WARN, msg); 5313 } 5314 } else { 5315 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5316 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5317 + pkg.packageName + " upgrade keys do not match the " 5318 + "previously installed version"); 5319 } else { 5320 // We just determined the app is signed correctly, so bring 5321 // over the latest parsed certs. 5322 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5323 } 5324 } 5325 // Verify that this new package doesn't have any content providers 5326 // that conflict with existing packages. Only do this if the 5327 // package isn't already installed, since we don't want to break 5328 // things that are installed. 5329 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5330 final int N = pkg.providers.size(); 5331 int i; 5332 for (i=0; i<N; i++) { 5333 PackageParser.Provider p = pkg.providers.get(i); 5334 if (p.info.authority != null) { 5335 String names[] = p.info.authority.split(";"); 5336 for (int j = 0; j < names.length; j++) { 5337 if (mProvidersByAuthority.containsKey(names[j])) { 5338 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5339 final String otherPackageName = 5340 ((other != null && other.getComponentName() != null) ? 5341 other.getComponentName().getPackageName() : "?"); 5342 throw new PackageManagerException( 5343 INSTALL_FAILED_CONFLICTING_PROVIDER, 5344 "Can't install because provider name " + names[j] 5345 + " (in package " + pkg.applicationInfo.packageName 5346 + ") is already used by " + otherPackageName); 5347 } 5348 } 5349 } 5350 } 5351 } 5352 5353 if (pkg.mAdoptPermissions != null) { 5354 // This package wants to adopt ownership of permissions from 5355 // another package. 5356 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5357 final String origName = pkg.mAdoptPermissions.get(i); 5358 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5359 if (orig != null) { 5360 if (verifyPackageUpdateLPr(orig, pkg)) { 5361 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5362 + pkg.packageName); 5363 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5364 } 5365 } 5366 } 5367 } 5368 } 5369 5370 final String pkgName = pkg.packageName; 5371 5372 final long scanFileTime = scanFile.lastModified(); 5373 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5374 pkg.applicationInfo.processName = fixProcessName( 5375 pkg.applicationInfo.packageName, 5376 pkg.applicationInfo.processName, 5377 pkg.applicationInfo.uid); 5378 5379 File dataPath; 5380 if (mPlatformPackage == pkg) { 5381 // The system package is special. 5382 dataPath = new File(Environment.getDataDirectory(), "system"); 5383 5384 pkg.applicationInfo.dataDir = dataPath.getPath(); 5385 5386 } else { 5387 // This is a normal package, need to make its data directory. 5388 dataPath = getDataPathForPackage(pkg.packageName, 0); 5389 5390 boolean uidError = false; 5391 if (dataPath.exists()) { 5392 int currentUid = 0; 5393 try { 5394 StructStat stat = Os.stat(dataPath.getPath()); 5395 currentUid = stat.st_uid; 5396 } catch (ErrnoException e) { 5397 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5398 } 5399 5400 // If we have mismatched owners for the data path, we have a problem. 5401 if (currentUid != pkg.applicationInfo.uid) { 5402 boolean recovered = false; 5403 if (currentUid == 0) { 5404 // The directory somehow became owned by root. Wow. 5405 // This is probably because the system was stopped while 5406 // installd was in the middle of messing with its libs 5407 // directory. Ask installd to fix that. 5408 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5409 pkg.applicationInfo.uid); 5410 if (ret >= 0) { 5411 recovered = true; 5412 String msg = "Package " + pkg.packageName 5413 + " unexpectedly changed to uid 0; recovered to " + 5414 + pkg.applicationInfo.uid; 5415 reportSettingsProblem(Log.WARN, msg); 5416 } 5417 } 5418 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5419 || (scanFlags&SCAN_BOOTING) != 0)) { 5420 // If this is a system app, we can at least delete its 5421 // current data so the application will still work. 5422 int ret = removeDataDirsLI(pkgName); 5423 if (ret >= 0) { 5424 // TODO: Kill the processes first 5425 // Old data gone! 5426 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5427 ? "System package " : "Third party package "; 5428 String msg = prefix + pkg.packageName 5429 + " has changed from uid: " 5430 + currentUid + " to " 5431 + pkg.applicationInfo.uid + "; old data erased"; 5432 reportSettingsProblem(Log.WARN, msg); 5433 recovered = true; 5434 5435 // And now re-install the app. 5436 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5437 pkg.applicationInfo.seinfo); 5438 if (ret == -1) { 5439 // Ack should not happen! 5440 msg = prefix + pkg.packageName 5441 + " could not have data directory re-created after delete."; 5442 reportSettingsProblem(Log.WARN, msg); 5443 throw new PackageManagerException( 5444 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5445 } 5446 } 5447 if (!recovered) { 5448 mHasSystemUidErrors = true; 5449 } 5450 } else if (!recovered) { 5451 // If we allow this install to proceed, we will be broken. 5452 // Abort, abort! 5453 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5454 "scanPackageLI"); 5455 } 5456 if (!recovered) { 5457 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5458 + pkg.applicationInfo.uid + "/fs_" 5459 + currentUid; 5460 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5461 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5462 String msg = "Package " + pkg.packageName 5463 + " has mismatched uid: " 5464 + currentUid + " on disk, " 5465 + pkg.applicationInfo.uid + " in settings"; 5466 // writer 5467 synchronized (mPackages) { 5468 mSettings.mReadMessages.append(msg); 5469 mSettings.mReadMessages.append('\n'); 5470 uidError = true; 5471 if (!pkgSetting.uidError) { 5472 reportSettingsProblem(Log.ERROR, msg); 5473 } 5474 } 5475 } 5476 } 5477 pkg.applicationInfo.dataDir = dataPath.getPath(); 5478 if (mShouldRestoreconData) { 5479 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5480 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5481 pkg.applicationInfo.uid); 5482 } 5483 } else { 5484 if (DEBUG_PACKAGE_SCANNING) { 5485 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5486 Log.v(TAG, "Want this data dir: " + dataPath); 5487 } 5488 //invoke installer to do the actual installation 5489 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5490 pkg.applicationInfo.seinfo); 5491 if (ret < 0) { 5492 // Error from installer 5493 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5494 "Unable to create data dirs [errorCode=" + ret + "]"); 5495 } 5496 5497 if (dataPath.exists()) { 5498 pkg.applicationInfo.dataDir = dataPath.getPath(); 5499 } else { 5500 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5501 pkg.applicationInfo.dataDir = null; 5502 } 5503 } 5504 5505 pkgSetting.uidError = uidError; 5506 } 5507 5508 final String path = scanFile.getPath(); 5509 final String codePath = pkg.applicationInfo.getCodePath(); 5510 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5511 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5512 setBundledAppAbisAndRoots(pkg, pkgSetting); 5513 5514 // If we haven't found any native libraries for the app, check if it has 5515 // renderscript code. We'll need to force the app to 32 bit if it has 5516 // renderscript bitcode. 5517 if (pkg.applicationInfo.primaryCpuAbi == null 5518 && pkg.applicationInfo.secondaryCpuAbi == null 5519 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5520 NativeLibraryHelper.Handle handle = null; 5521 try { 5522 handle = NativeLibraryHelper.Handle.create(scanFile); 5523 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5524 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5525 } 5526 } catch (IOException ioe) { 5527 Slog.w(TAG, "Error scanning system app : " + ioe); 5528 } finally { 5529 IoUtils.closeQuietly(handle); 5530 } 5531 } 5532 5533 setNativeLibraryPaths(pkg); 5534 } else { 5535 // TODO: We can probably be smarter about this stuff. For installed apps, 5536 // we can calculate this information at install time once and for all. For 5537 // system apps, we can probably assume that this information doesn't change 5538 // after the first boot scan. As things stand, we do lots of unnecessary work. 5539 5540 // Give ourselves some initial paths; we'll come back for another 5541 // pass once we've determined ABI below. 5542 setNativeLibraryPaths(pkg); 5543 5544 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 5545 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5546 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5547 5548 NativeLibraryHelper.Handle handle = null; 5549 try { 5550 handle = NativeLibraryHelper.Handle.create(scanFile); 5551 // TODO(multiArch): This can be null for apps that didn't go through the 5552 // usual installation process. We can calculate it again, like we 5553 // do during install time. 5554 // 5555 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5556 // unnecessary. 5557 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5558 5559 // Null out the abis so that they can be recalculated. 5560 pkg.applicationInfo.primaryCpuAbi = null; 5561 pkg.applicationInfo.secondaryCpuAbi = null; 5562 if (isMultiArch(pkg.applicationInfo)) { 5563 // Warn if we've set an abiOverride for multi-lib packages.. 5564 // By definition, we need to copy both 32 and 64 bit libraries for 5565 // such packages. 5566 if (pkg.cpuAbiOverride != null 5567 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5568 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5569 } 5570 5571 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5572 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5573 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5574 if (isAsec) { 5575 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5576 } else { 5577 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5578 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5579 useIsaSpecificSubdirs); 5580 } 5581 } 5582 5583 maybeThrowExceptionForMultiArchCopy( 5584 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5585 5586 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5587 if (isAsec) { 5588 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5589 } else { 5590 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5591 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5592 useIsaSpecificSubdirs); 5593 } 5594 } 5595 5596 maybeThrowExceptionForMultiArchCopy( 5597 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5598 5599 if (abi64 >= 0) { 5600 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5601 } 5602 5603 if (abi32 >= 0) { 5604 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5605 if (abi64 >= 0) { 5606 pkg.applicationInfo.secondaryCpuAbi = abi; 5607 } else { 5608 pkg.applicationInfo.primaryCpuAbi = abi; 5609 } 5610 } 5611 } else { 5612 String[] abiList = (cpuAbiOverride != null) ? 5613 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5614 5615 // Enable gross and lame hacks for apps that are built with old 5616 // SDK tools. We must scan their APKs for renderscript bitcode and 5617 // not launch them if it's present. Don't bother checking on devices 5618 // that don't have 64 bit support. 5619 boolean needsRenderScriptOverride = false; 5620 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5621 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5622 abiList = Build.SUPPORTED_32_BIT_ABIS; 5623 needsRenderScriptOverride = true; 5624 } 5625 5626 final int copyRet; 5627 if (isAsec) { 5628 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5629 } else { 5630 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5631 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5632 } 5633 5634 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5635 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5636 "Error unpackaging native libs for app, errorCode=" + copyRet); 5637 } 5638 5639 if (copyRet >= 0) { 5640 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5641 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5642 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5643 } else if (needsRenderScriptOverride) { 5644 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5645 } 5646 } 5647 } catch (IOException ioe) { 5648 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5649 } finally { 5650 IoUtils.closeQuietly(handle); 5651 } 5652 5653 // Now that we've calculated the ABIs and determined if it's an internal app, 5654 // we will go ahead and populate the nativeLibraryPath. 5655 setNativeLibraryPaths(pkg); 5656 5657 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5658 final int[] userIds = sUserManager.getUserIds(); 5659 synchronized (mInstallLock) { 5660 // Create a native library symlink only if we have native libraries 5661 // and if the native libraries are 32 bit libraries. We do not provide 5662 // this symlink for 64 bit libraries. 5663 if (pkg.applicationInfo.primaryCpuAbi != null && 5664 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5665 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5666 for (int userId : userIds) { 5667 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5668 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5669 "Failed linking native library dir (user=" + userId + ")"); 5670 } 5671 } 5672 } 5673 } 5674 } 5675 5676 // This is a special case for the "system" package, where the ABI is 5677 // dictated by the zygote configuration (and init.rc). We should keep track 5678 // of this ABI so that we can deal with "normal" applications that run under 5679 // the same UID correctly. 5680 if (mPlatformPackage == pkg) { 5681 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5682 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5683 } 5684 5685 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5686 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5687 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5688 // Copy the derived override back to the parsed package, so that we can 5689 // update the package settings accordingly. 5690 pkg.cpuAbiOverride = cpuAbiOverride; 5691 5692 if (DEBUG_ABI_SELECTION) { 5693 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5694 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5695 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5696 } 5697 5698 // Push the derived path down into PackageSettings so we know what to 5699 // clean up at uninstall time. 5700 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5701 5702 if (DEBUG_ABI_SELECTION) { 5703 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5704 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5705 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5706 } 5707 5708 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5709 // We don't do this here during boot because we can do it all 5710 // at once after scanning all existing packages. 5711 // 5712 // We also do this *before* we perform dexopt on this package, so that 5713 // we can avoid redundant dexopts, and also to make sure we've got the 5714 // code and package path correct. 5715 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5716 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5717 } 5718 5719 if ((scanFlags & SCAN_NO_DEX) == 0) { 5720 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 5721 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 5722 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5723 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5724 } 5725 } 5726 if (mFactoryTest && pkg.requestedPermissions.contains( 5727 android.Manifest.permission.FACTORY_TEST)) { 5728 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5729 } 5730 5731 ArrayList<PackageParser.Package> clientLibPkgs = null; 5732 5733 // writer 5734 synchronized (mPackages) { 5735 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5736 // Only system apps can add new shared libraries. 5737 if (pkg.libraryNames != null) { 5738 for (int i=0; i<pkg.libraryNames.size(); i++) { 5739 String name = pkg.libraryNames.get(i); 5740 boolean allowed = false; 5741 if (pkg.isUpdatedSystemApp()) { 5742 // New library entries can only be added through the 5743 // system image. This is important to get rid of a lot 5744 // of nasty edge cases: for example if we allowed a non- 5745 // system update of the app to add a library, then uninstalling 5746 // the update would make the library go away, and assumptions 5747 // we made such as through app install filtering would now 5748 // have allowed apps on the device which aren't compatible 5749 // with it. Better to just have the restriction here, be 5750 // conservative, and create many fewer cases that can negatively 5751 // impact the user experience. 5752 final PackageSetting sysPs = mSettings 5753 .getDisabledSystemPkgLPr(pkg.packageName); 5754 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5755 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5756 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5757 allowed = true; 5758 allowed = true; 5759 break; 5760 } 5761 } 5762 } 5763 } else { 5764 allowed = true; 5765 } 5766 if (allowed) { 5767 if (!mSharedLibraries.containsKey(name)) { 5768 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5769 } else if (!name.equals(pkg.packageName)) { 5770 Slog.w(TAG, "Package " + pkg.packageName + " library " 5771 + name + " already exists; skipping"); 5772 } 5773 } else { 5774 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5775 + name + " that is not declared on system image; skipping"); 5776 } 5777 } 5778 if ((scanFlags&SCAN_BOOTING) == 0) { 5779 // If we are not booting, we need to update any applications 5780 // that are clients of our shared library. If we are booting, 5781 // this will all be done once the scan is complete. 5782 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5783 } 5784 } 5785 } 5786 } 5787 5788 // We also need to dexopt any apps that are dependent on this library. Note that 5789 // if these fail, we should abort the install since installing the library will 5790 // result in some apps being broken. 5791 if (clientLibPkgs != null) { 5792 if ((scanFlags & SCAN_NO_DEX) == 0) { 5793 for (int i = 0; i < clientLibPkgs.size(); i++) { 5794 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5795 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 5796 null /* instruction sets */, forceDex, 5797 (scanFlags & SCAN_DEFER_DEX) != 0, false); 5798 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5799 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5800 "scanPackageLI failed to dexopt clientLibPkgs"); 5801 } 5802 } 5803 } 5804 } 5805 5806 // Request the ActivityManager to kill the process(only for existing packages) 5807 // so that we do not end up in a confused state while the user is still using the older 5808 // version of the application while the new one gets installed. 5809 if ((scanFlags & SCAN_REPLACING) != 0) { 5810 killApplication(pkg.applicationInfo.packageName, 5811 pkg.applicationInfo.uid, "update pkg"); 5812 } 5813 5814 // Also need to kill any apps that are dependent on the library. 5815 if (clientLibPkgs != null) { 5816 for (int i=0; i<clientLibPkgs.size(); i++) { 5817 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5818 killApplication(clientPkg.applicationInfo.packageName, 5819 clientPkg.applicationInfo.uid, "update lib"); 5820 } 5821 } 5822 5823 // writer 5824 synchronized (mPackages) { 5825 // We don't expect installation to fail beyond this point 5826 5827 // Add the new setting to mSettings 5828 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5829 // Add the new setting to mPackages 5830 mPackages.put(pkg.applicationInfo.packageName, pkg); 5831 // Make sure we don't accidentally delete its data. 5832 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5833 while (iter.hasNext()) { 5834 PackageCleanItem item = iter.next(); 5835 if (pkgName.equals(item.packageName)) { 5836 iter.remove(); 5837 } 5838 } 5839 5840 // Take care of first install / last update times. 5841 if (currentTime != 0) { 5842 if (pkgSetting.firstInstallTime == 0) { 5843 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5844 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5845 pkgSetting.lastUpdateTime = currentTime; 5846 } 5847 } else if (pkgSetting.firstInstallTime == 0) { 5848 // We need *something*. Take time time stamp of the file. 5849 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5850 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5851 if (scanFileTime != pkgSetting.timeStamp) { 5852 // A package on the system image has changed; consider this 5853 // to be an update. 5854 pkgSetting.lastUpdateTime = scanFileTime; 5855 } 5856 } 5857 5858 // Add the package's KeySets to the global KeySetManagerService 5859 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5860 try { 5861 // Old KeySetData no longer valid. 5862 ksms.removeAppKeySetDataLPw(pkg.packageName); 5863 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5864 if (pkg.mKeySetMapping != null) { 5865 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5866 pkg.mKeySetMapping.entrySet()) { 5867 if (entry.getValue() != null) { 5868 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5869 entry.getValue(), entry.getKey()); 5870 } 5871 } 5872 if (pkg.mUpgradeKeySets != null) { 5873 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5874 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5875 } 5876 } 5877 } 5878 } catch (NullPointerException e) { 5879 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5880 } catch (IllegalArgumentException e) { 5881 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5882 } 5883 5884 int N = pkg.providers.size(); 5885 StringBuilder r = null; 5886 int i; 5887 for (i=0; i<N; i++) { 5888 PackageParser.Provider p = pkg.providers.get(i); 5889 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5890 p.info.processName, pkg.applicationInfo.uid); 5891 mProviders.addProvider(p); 5892 p.syncable = p.info.isSyncable; 5893 if (p.info.authority != null) { 5894 String names[] = p.info.authority.split(";"); 5895 p.info.authority = null; 5896 for (int j = 0; j < names.length; j++) { 5897 if (j == 1 && p.syncable) { 5898 // We only want the first authority for a provider to possibly be 5899 // syncable, so if we already added this provider using a different 5900 // authority clear the syncable flag. We copy the provider before 5901 // changing it because the mProviders object contains a reference 5902 // to a provider that we don't want to change. 5903 // Only do this for the second authority since the resulting provider 5904 // object can be the same for all future authorities for this provider. 5905 p = new PackageParser.Provider(p); 5906 p.syncable = false; 5907 } 5908 if (!mProvidersByAuthority.containsKey(names[j])) { 5909 mProvidersByAuthority.put(names[j], p); 5910 if (p.info.authority == null) { 5911 p.info.authority = names[j]; 5912 } else { 5913 p.info.authority = p.info.authority + ";" + names[j]; 5914 } 5915 if (DEBUG_PACKAGE_SCANNING) { 5916 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5917 Log.d(TAG, "Registered content provider: " + names[j] 5918 + ", className = " + p.info.name + ", isSyncable = " 5919 + p.info.isSyncable); 5920 } 5921 } else { 5922 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5923 Slog.w(TAG, "Skipping provider name " + names[j] + 5924 " (in package " + pkg.applicationInfo.packageName + 5925 "): name already used by " 5926 + ((other != null && other.getComponentName() != null) 5927 ? other.getComponentName().getPackageName() : "?")); 5928 } 5929 } 5930 } 5931 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5932 if (r == null) { 5933 r = new StringBuilder(256); 5934 } else { 5935 r.append(' '); 5936 } 5937 r.append(p.info.name); 5938 } 5939 } 5940 if (r != null) { 5941 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5942 } 5943 5944 N = pkg.services.size(); 5945 r = null; 5946 for (i=0; i<N; i++) { 5947 PackageParser.Service s = pkg.services.get(i); 5948 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5949 s.info.processName, pkg.applicationInfo.uid); 5950 mServices.addService(s); 5951 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5952 if (r == null) { 5953 r = new StringBuilder(256); 5954 } else { 5955 r.append(' '); 5956 } 5957 r.append(s.info.name); 5958 } 5959 } 5960 if (r != null) { 5961 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5962 } 5963 5964 N = pkg.receivers.size(); 5965 r = null; 5966 for (i=0; i<N; i++) { 5967 PackageParser.Activity a = pkg.receivers.get(i); 5968 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5969 a.info.processName, pkg.applicationInfo.uid); 5970 mReceivers.addActivity(a, "receiver"); 5971 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5972 if (r == null) { 5973 r = new StringBuilder(256); 5974 } else { 5975 r.append(' '); 5976 } 5977 r.append(a.info.name); 5978 } 5979 } 5980 if (r != null) { 5981 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5982 } 5983 5984 N = pkg.activities.size(); 5985 r = null; 5986 for (i=0; i<N; i++) { 5987 PackageParser.Activity a = pkg.activities.get(i); 5988 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5989 a.info.processName, pkg.applicationInfo.uid); 5990 mActivities.addActivity(a, "activity"); 5991 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5992 if (r == null) { 5993 r = new StringBuilder(256); 5994 } else { 5995 r.append(' '); 5996 } 5997 r.append(a.info.name); 5998 } 5999 } 6000 if (r != null) { 6001 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6002 } 6003 6004 N = pkg.permissionGroups.size(); 6005 r = null; 6006 for (i=0; i<N; i++) { 6007 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6008 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6009 if (cur == null) { 6010 mPermissionGroups.put(pg.info.name, pg); 6011 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6012 if (r == null) { 6013 r = new StringBuilder(256); 6014 } else { 6015 r.append(' '); 6016 } 6017 r.append(pg.info.name); 6018 } 6019 } else { 6020 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6021 + pg.info.packageName + " ignored: original from " 6022 + cur.info.packageName); 6023 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6024 if (r == null) { 6025 r = new StringBuilder(256); 6026 } else { 6027 r.append(' '); 6028 } 6029 r.append("DUP:"); 6030 r.append(pg.info.name); 6031 } 6032 } 6033 } 6034 if (r != null) { 6035 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6036 } 6037 6038 N = pkg.permissions.size(); 6039 r = null; 6040 for (i=0; i<N; i++) { 6041 PackageParser.Permission p = pkg.permissions.get(i); 6042 ArrayMap<String, BasePermission> permissionMap = 6043 p.tree ? mSettings.mPermissionTrees 6044 : mSettings.mPermissions; 6045 p.group = mPermissionGroups.get(p.info.group); 6046 if (p.info.group == null || p.group != null) { 6047 BasePermission bp = permissionMap.get(p.info.name); 6048 6049 // Allow system apps to redefine non-system permissions 6050 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6051 final boolean currentOwnerIsSystem = (bp.perm != null 6052 && isSystemApp(bp.perm.owner)); 6053 if (isSystemApp(p.owner)) { 6054 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6055 // It's a built-in permission and no owner, take ownership now 6056 bp.packageSetting = pkgSetting; 6057 bp.perm = p; 6058 bp.uid = pkg.applicationInfo.uid; 6059 bp.sourcePackage = p.info.packageName; 6060 } else if (!currentOwnerIsSystem) { 6061 String msg = "New decl " + p.owner + " of permission " 6062 + p.info.name + " is system; overriding " + bp.sourcePackage; 6063 reportSettingsProblem(Log.WARN, msg); 6064 bp = null; 6065 } 6066 } 6067 } 6068 6069 if (bp == null) { 6070 bp = new BasePermission(p.info.name, p.info.packageName, 6071 BasePermission.TYPE_NORMAL); 6072 permissionMap.put(p.info.name, bp); 6073 } 6074 6075 if (bp.perm == null) { 6076 if (bp.sourcePackage == null 6077 || bp.sourcePackage.equals(p.info.packageName)) { 6078 BasePermission tree = findPermissionTreeLP(p.info.name); 6079 if (tree == null 6080 || tree.sourcePackage.equals(p.info.packageName)) { 6081 bp.packageSetting = pkgSetting; 6082 bp.perm = p; 6083 bp.uid = pkg.applicationInfo.uid; 6084 bp.sourcePackage = p.info.packageName; 6085 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6086 if (r == null) { 6087 r = new StringBuilder(256); 6088 } else { 6089 r.append(' '); 6090 } 6091 r.append(p.info.name); 6092 } 6093 } else { 6094 Slog.w(TAG, "Permission " + p.info.name + " from package " 6095 + p.info.packageName + " ignored: base tree " 6096 + tree.name + " is from package " 6097 + tree.sourcePackage); 6098 } 6099 } else { 6100 Slog.w(TAG, "Permission " + p.info.name + " from package " 6101 + p.info.packageName + " ignored: original from " 6102 + bp.sourcePackage); 6103 } 6104 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6105 if (r == null) { 6106 r = new StringBuilder(256); 6107 } else { 6108 r.append(' '); 6109 } 6110 r.append("DUP:"); 6111 r.append(p.info.name); 6112 } 6113 if (bp.perm == p) { 6114 bp.protectionLevel = p.info.protectionLevel; 6115 } 6116 } else { 6117 Slog.w(TAG, "Permission " + p.info.name + " from package " 6118 + p.info.packageName + " ignored: no group " 6119 + p.group); 6120 } 6121 } 6122 if (r != null) { 6123 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6124 } 6125 6126 N = pkg.instrumentation.size(); 6127 r = null; 6128 for (i=0; i<N; i++) { 6129 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6130 a.info.packageName = pkg.applicationInfo.packageName; 6131 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6132 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6133 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6134 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6135 a.info.dataDir = pkg.applicationInfo.dataDir; 6136 6137 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6138 // need other information about the application, like the ABI and what not ? 6139 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6140 mInstrumentation.put(a.getComponentName(), a); 6141 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6142 if (r == null) { 6143 r = new StringBuilder(256); 6144 } else { 6145 r.append(' '); 6146 } 6147 r.append(a.info.name); 6148 } 6149 } 6150 if (r != null) { 6151 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6152 } 6153 6154 if (pkg.protectedBroadcasts != null) { 6155 N = pkg.protectedBroadcasts.size(); 6156 for (i=0; i<N; i++) { 6157 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6158 } 6159 } 6160 6161 pkgSetting.setTimeStamp(scanFileTime); 6162 6163 // Create idmap files for pairs of (packages, overlay packages). 6164 // Note: "android", ie framework-res.apk, is handled by native layers. 6165 if (pkg.mOverlayTarget != null) { 6166 // This is an overlay package. 6167 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6168 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6169 mOverlays.put(pkg.mOverlayTarget, 6170 new ArrayMap<String, PackageParser.Package>()); 6171 } 6172 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6173 map.put(pkg.packageName, pkg); 6174 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6175 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6176 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6177 "scanPackageLI failed to createIdmap"); 6178 } 6179 } 6180 } else if (mOverlays.containsKey(pkg.packageName) && 6181 !pkg.packageName.equals("android")) { 6182 // This is a regular package, with one or more known overlay packages. 6183 createIdmapsForPackageLI(pkg); 6184 } 6185 } 6186 6187 return pkg; 6188 } 6189 6190 /** 6191 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6192 * i.e, so that all packages can be run inside a single process if required. 6193 * 6194 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6195 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6196 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6197 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6198 * updating a package that belongs to a shared user. 6199 * 6200 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6201 * adds unnecessary complexity. 6202 */ 6203 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6204 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6205 String requiredInstructionSet = null; 6206 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6207 requiredInstructionSet = VMRuntime.getInstructionSet( 6208 scannedPackage.applicationInfo.primaryCpuAbi); 6209 } 6210 6211 PackageSetting requirer = null; 6212 for (PackageSetting ps : packagesForUser) { 6213 // If packagesForUser contains scannedPackage, we skip it. This will happen 6214 // when scannedPackage is an update of an existing package. Without this check, 6215 // we will never be able to change the ABI of any package belonging to a shared 6216 // user, even if it's compatible with other packages. 6217 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6218 if (ps.primaryCpuAbiString == null) { 6219 continue; 6220 } 6221 6222 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6223 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6224 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6225 // this but there's not much we can do. 6226 String errorMessage = "Instruction set mismatch, " 6227 + ((requirer == null) ? "[caller]" : requirer) 6228 + " requires " + requiredInstructionSet + " whereas " + ps 6229 + " requires " + instructionSet; 6230 Slog.w(TAG, errorMessage); 6231 } 6232 6233 if (requiredInstructionSet == null) { 6234 requiredInstructionSet = instructionSet; 6235 requirer = ps; 6236 } 6237 } 6238 } 6239 6240 if (requiredInstructionSet != null) { 6241 String adjustedAbi; 6242 if (requirer != null) { 6243 // requirer != null implies that either scannedPackage was null or that scannedPackage 6244 // did not require an ABI, in which case we have to adjust scannedPackage to match 6245 // the ABI of the set (which is the same as requirer's ABI) 6246 adjustedAbi = requirer.primaryCpuAbiString; 6247 if (scannedPackage != null) { 6248 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6249 } 6250 } else { 6251 // requirer == null implies that we're updating all ABIs in the set to 6252 // match scannedPackage. 6253 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6254 } 6255 6256 for (PackageSetting ps : packagesForUser) { 6257 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6258 if (ps.primaryCpuAbiString != null) { 6259 continue; 6260 } 6261 6262 ps.primaryCpuAbiString = adjustedAbi; 6263 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6264 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6265 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6266 6267 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6268 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6269 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6270 ps.primaryCpuAbiString = null; 6271 ps.pkg.applicationInfo.primaryCpuAbi = null; 6272 return; 6273 } else { 6274 mInstaller.rmdex(ps.codePathString, 6275 getDexCodeInstructionSet(getPreferredInstructionSet())); 6276 } 6277 } 6278 } 6279 } 6280 } 6281 } 6282 6283 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6284 synchronized (mPackages) { 6285 mResolverReplaced = true; 6286 // Set up information for custom user intent resolution activity. 6287 mResolveActivity.applicationInfo = pkg.applicationInfo; 6288 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6289 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6290 mResolveActivity.processName = pkg.applicationInfo.packageName; 6291 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6292 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6293 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6294 mResolveActivity.theme = 0; 6295 mResolveActivity.exported = true; 6296 mResolveActivity.enabled = true; 6297 mResolveInfo.activityInfo = mResolveActivity; 6298 mResolveInfo.priority = 0; 6299 mResolveInfo.preferredOrder = 0; 6300 mResolveInfo.match = 0; 6301 mResolveComponentName = mCustomResolverComponentName; 6302 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6303 mResolveComponentName); 6304 } 6305 } 6306 6307 private static String calculateBundledApkRoot(final String codePathString) { 6308 final File codePath = new File(codePathString); 6309 final File codeRoot; 6310 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6311 codeRoot = Environment.getRootDirectory(); 6312 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6313 codeRoot = Environment.getOemDirectory(); 6314 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6315 codeRoot = Environment.getVendorDirectory(); 6316 } else { 6317 // Unrecognized code path; take its top real segment as the apk root: 6318 // e.g. /something/app/blah.apk => /something 6319 try { 6320 File f = codePath.getCanonicalFile(); 6321 File parent = f.getParentFile(); // non-null because codePath is a file 6322 File tmp; 6323 while ((tmp = parent.getParentFile()) != null) { 6324 f = parent; 6325 parent = tmp; 6326 } 6327 codeRoot = f; 6328 Slog.w(TAG, "Unrecognized code path " 6329 + codePath + " - using " + codeRoot); 6330 } catch (IOException e) { 6331 // Can't canonicalize the code path -- shenanigans? 6332 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6333 return Environment.getRootDirectory().getPath(); 6334 } 6335 } 6336 return codeRoot.getPath(); 6337 } 6338 6339 /** 6340 * Derive and set the location of native libraries for the given package, 6341 * which varies depending on where and how the package was installed. 6342 */ 6343 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6344 final ApplicationInfo info = pkg.applicationInfo; 6345 final String codePath = pkg.codePath; 6346 final File codeFile = new File(codePath); 6347 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 6348 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6349 6350 info.nativeLibraryRootDir = null; 6351 info.nativeLibraryRootRequiresIsa = false; 6352 info.nativeLibraryDir = null; 6353 info.secondaryNativeLibraryDir = null; 6354 6355 if (isApkFile(codeFile)) { 6356 // Monolithic install 6357 if (bundledApp) { 6358 // If "/system/lib64/apkname" exists, assume that is the per-package 6359 // native library directory to use; otherwise use "/system/lib/apkname". 6360 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6361 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6362 getPrimaryInstructionSet(info)); 6363 6364 // This is a bundled system app so choose the path based on the ABI. 6365 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6366 // is just the default path. 6367 final String apkName = deriveCodePathName(codePath); 6368 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6369 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6370 apkName).getAbsolutePath(); 6371 6372 if (info.secondaryCpuAbi != null) { 6373 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6374 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6375 secondaryLibDir, apkName).getAbsolutePath(); 6376 } 6377 } else if (asecApp) { 6378 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6379 .getAbsolutePath(); 6380 } else { 6381 final String apkName = deriveCodePathName(codePath); 6382 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6383 .getAbsolutePath(); 6384 } 6385 6386 info.nativeLibraryRootRequiresIsa = false; 6387 info.nativeLibraryDir = info.nativeLibraryRootDir; 6388 } else { 6389 // Cluster install 6390 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6391 info.nativeLibraryRootRequiresIsa = true; 6392 6393 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6394 getPrimaryInstructionSet(info)).getAbsolutePath(); 6395 6396 if (info.secondaryCpuAbi != null) { 6397 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6398 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6399 } 6400 } 6401 } 6402 6403 /** 6404 * Calculate the abis and roots for a bundled app. These can uniquely 6405 * be determined from the contents of the system partition, i.e whether 6406 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6407 * of this information, and instead assume that the system was built 6408 * sensibly. 6409 */ 6410 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6411 PackageSetting pkgSetting) { 6412 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6413 6414 // If "/system/lib64/apkname" exists, assume that is the per-package 6415 // native library directory to use; otherwise use "/system/lib/apkname". 6416 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6417 setBundledAppAbi(pkg, apkRoot, apkName); 6418 // pkgSetting might be null during rescan following uninstall of updates 6419 // to a bundled app, so accommodate that possibility. The settings in 6420 // that case will be established later from the parsed package. 6421 // 6422 // If the settings aren't null, sync them up with what we've just derived. 6423 // note that apkRoot isn't stored in the package settings. 6424 if (pkgSetting != null) { 6425 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6426 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6427 } 6428 } 6429 6430 /** 6431 * Deduces the ABI of a bundled app and sets the relevant fields on the 6432 * parsed pkg object. 6433 * 6434 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6435 * under which system libraries are installed. 6436 * @param apkName the name of the installed package. 6437 */ 6438 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6439 final File codeFile = new File(pkg.codePath); 6440 6441 final boolean has64BitLibs; 6442 final boolean has32BitLibs; 6443 if (isApkFile(codeFile)) { 6444 // Monolithic install 6445 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6446 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6447 } else { 6448 // Cluster install 6449 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6450 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6451 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6452 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6453 has64BitLibs = (new File(rootDir, isa)).exists(); 6454 } else { 6455 has64BitLibs = false; 6456 } 6457 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6458 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6459 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6460 has32BitLibs = (new File(rootDir, isa)).exists(); 6461 } else { 6462 has32BitLibs = false; 6463 } 6464 } 6465 6466 if (has64BitLibs && !has32BitLibs) { 6467 // The package has 64 bit libs, but not 32 bit libs. Its primary 6468 // ABI should be 64 bit. We can safely assume here that the bundled 6469 // native libraries correspond to the most preferred ABI in the list. 6470 6471 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6472 pkg.applicationInfo.secondaryCpuAbi = null; 6473 } else if (has32BitLibs && !has64BitLibs) { 6474 // The package has 32 bit libs but not 64 bit libs. Its primary 6475 // ABI should be 32 bit. 6476 6477 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6478 pkg.applicationInfo.secondaryCpuAbi = null; 6479 } else if (has32BitLibs && has64BitLibs) { 6480 // The application has both 64 and 32 bit bundled libraries. We check 6481 // here that the app declares multiArch support, and warn if it doesn't. 6482 // 6483 // We will be lenient here and record both ABIs. The primary will be the 6484 // ABI that's higher on the list, i.e, a device that's configured to prefer 6485 // 64 bit apps will see a 64 bit primary ABI, 6486 6487 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6488 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6489 } 6490 6491 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6492 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6493 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6494 } else { 6495 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6496 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6497 } 6498 } else { 6499 pkg.applicationInfo.primaryCpuAbi = null; 6500 pkg.applicationInfo.secondaryCpuAbi = null; 6501 } 6502 } 6503 6504 private void killApplication(String pkgName, int appId, String reason) { 6505 // Request the ActivityManager to kill the process(only for existing packages) 6506 // so that we do not end up in a confused state while the user is still using the older 6507 // version of the application while the new one gets installed. 6508 IActivityManager am = ActivityManagerNative.getDefault(); 6509 if (am != null) { 6510 try { 6511 am.killApplicationWithAppId(pkgName, appId, reason); 6512 } catch (RemoteException e) { 6513 } 6514 } 6515 } 6516 6517 void removePackageLI(PackageSetting ps, boolean chatty) { 6518 if (DEBUG_INSTALL) { 6519 if (chatty) 6520 Log.d(TAG, "Removing package " + ps.name); 6521 } 6522 6523 // writer 6524 synchronized (mPackages) { 6525 mPackages.remove(ps.name); 6526 final PackageParser.Package pkg = ps.pkg; 6527 if (pkg != null) { 6528 cleanPackageDataStructuresLILPw(pkg, chatty); 6529 } 6530 } 6531 } 6532 6533 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6534 if (DEBUG_INSTALL) { 6535 if (chatty) 6536 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6537 } 6538 6539 // writer 6540 synchronized (mPackages) { 6541 mPackages.remove(pkg.applicationInfo.packageName); 6542 cleanPackageDataStructuresLILPw(pkg, chatty); 6543 } 6544 } 6545 6546 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6547 int N = pkg.providers.size(); 6548 StringBuilder r = null; 6549 int i; 6550 for (i=0; i<N; i++) { 6551 PackageParser.Provider p = pkg.providers.get(i); 6552 mProviders.removeProvider(p); 6553 if (p.info.authority == null) { 6554 6555 /* There was another ContentProvider with this authority when 6556 * this app was installed so this authority is null, 6557 * Ignore it as we don't have to unregister the provider. 6558 */ 6559 continue; 6560 } 6561 String names[] = p.info.authority.split(";"); 6562 for (int j = 0; j < names.length; j++) { 6563 if (mProvidersByAuthority.get(names[j]) == p) { 6564 mProvidersByAuthority.remove(names[j]); 6565 if (DEBUG_REMOVE) { 6566 if (chatty) 6567 Log.d(TAG, "Unregistered content provider: " + names[j] 6568 + ", className = " + p.info.name + ", isSyncable = " 6569 + p.info.isSyncable); 6570 } 6571 } 6572 } 6573 if (DEBUG_REMOVE && chatty) { 6574 if (r == null) { 6575 r = new StringBuilder(256); 6576 } else { 6577 r.append(' '); 6578 } 6579 r.append(p.info.name); 6580 } 6581 } 6582 if (r != null) { 6583 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6584 } 6585 6586 N = pkg.services.size(); 6587 r = null; 6588 for (i=0; i<N; i++) { 6589 PackageParser.Service s = pkg.services.get(i); 6590 mServices.removeService(s); 6591 if (chatty) { 6592 if (r == null) { 6593 r = new StringBuilder(256); 6594 } else { 6595 r.append(' '); 6596 } 6597 r.append(s.info.name); 6598 } 6599 } 6600 if (r != null) { 6601 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6602 } 6603 6604 N = pkg.receivers.size(); 6605 r = null; 6606 for (i=0; i<N; i++) { 6607 PackageParser.Activity a = pkg.receivers.get(i); 6608 mReceivers.removeActivity(a, "receiver"); 6609 if (DEBUG_REMOVE && chatty) { 6610 if (r == null) { 6611 r = new StringBuilder(256); 6612 } else { 6613 r.append(' '); 6614 } 6615 r.append(a.info.name); 6616 } 6617 } 6618 if (r != null) { 6619 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6620 } 6621 6622 N = pkg.activities.size(); 6623 r = null; 6624 for (i=0; i<N; i++) { 6625 PackageParser.Activity a = pkg.activities.get(i); 6626 mActivities.removeActivity(a, "activity"); 6627 if (DEBUG_REMOVE && chatty) { 6628 if (r == null) { 6629 r = new StringBuilder(256); 6630 } else { 6631 r.append(' '); 6632 } 6633 r.append(a.info.name); 6634 } 6635 } 6636 if (r != null) { 6637 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6638 } 6639 6640 N = pkg.permissions.size(); 6641 r = null; 6642 for (i=0; i<N; i++) { 6643 PackageParser.Permission p = pkg.permissions.get(i); 6644 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6645 if (bp == null) { 6646 bp = mSettings.mPermissionTrees.get(p.info.name); 6647 } 6648 if (bp != null && bp.perm == p) { 6649 bp.perm = null; 6650 if (DEBUG_REMOVE && chatty) { 6651 if (r == null) { 6652 r = new StringBuilder(256); 6653 } else { 6654 r.append(' '); 6655 } 6656 r.append(p.info.name); 6657 } 6658 } 6659 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6660 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6661 if (appOpPerms != null) { 6662 appOpPerms.remove(pkg.packageName); 6663 } 6664 } 6665 } 6666 if (r != null) { 6667 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6668 } 6669 6670 N = pkg.requestedPermissions.size(); 6671 r = null; 6672 for (i=0; i<N; i++) { 6673 String perm = pkg.requestedPermissions.get(i); 6674 BasePermission bp = mSettings.mPermissions.get(perm); 6675 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6676 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6677 if (appOpPerms != null) { 6678 appOpPerms.remove(pkg.packageName); 6679 if (appOpPerms.isEmpty()) { 6680 mAppOpPermissionPackages.remove(perm); 6681 } 6682 } 6683 } 6684 } 6685 if (r != null) { 6686 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6687 } 6688 6689 N = pkg.instrumentation.size(); 6690 r = null; 6691 for (i=0; i<N; i++) { 6692 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6693 mInstrumentation.remove(a.getComponentName()); 6694 if (DEBUG_REMOVE && chatty) { 6695 if (r == null) { 6696 r = new StringBuilder(256); 6697 } else { 6698 r.append(' '); 6699 } 6700 r.append(a.info.name); 6701 } 6702 } 6703 if (r != null) { 6704 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6705 } 6706 6707 r = null; 6708 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6709 // Only system apps can hold shared libraries. 6710 if (pkg.libraryNames != null) { 6711 for (i=0; i<pkg.libraryNames.size(); i++) { 6712 String name = pkg.libraryNames.get(i); 6713 SharedLibraryEntry cur = mSharedLibraries.get(name); 6714 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6715 mSharedLibraries.remove(name); 6716 if (DEBUG_REMOVE && chatty) { 6717 if (r == null) { 6718 r = new StringBuilder(256); 6719 } else { 6720 r.append(' '); 6721 } 6722 r.append(name); 6723 } 6724 } 6725 } 6726 } 6727 } 6728 if (r != null) { 6729 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6730 } 6731 } 6732 6733 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6734 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6735 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6736 return true; 6737 } 6738 } 6739 return false; 6740 } 6741 6742 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6743 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6744 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6745 6746 private void updatePermissionsLPw(String changingPkg, 6747 PackageParser.Package pkgInfo, int flags) { 6748 // Make sure there are no dangling permission trees. 6749 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6750 while (it.hasNext()) { 6751 final BasePermission bp = it.next(); 6752 if (bp.packageSetting == null) { 6753 // We may not yet have parsed the package, so just see if 6754 // we still know about its settings. 6755 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6756 } 6757 if (bp.packageSetting == null) { 6758 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6759 + " from package " + bp.sourcePackage); 6760 it.remove(); 6761 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6762 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6763 Slog.i(TAG, "Removing old permission tree: " + bp.name 6764 + " from package " + bp.sourcePackage); 6765 flags |= UPDATE_PERMISSIONS_ALL; 6766 it.remove(); 6767 } 6768 } 6769 } 6770 6771 // Make sure all dynamic permissions have been assigned to a package, 6772 // and make sure there are no dangling permissions. 6773 it = mSettings.mPermissions.values().iterator(); 6774 while (it.hasNext()) { 6775 final BasePermission bp = it.next(); 6776 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6777 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6778 + bp.name + " pkg=" + bp.sourcePackage 6779 + " info=" + bp.pendingInfo); 6780 if (bp.packageSetting == null && bp.pendingInfo != null) { 6781 final BasePermission tree = findPermissionTreeLP(bp.name); 6782 if (tree != null && tree.perm != null) { 6783 bp.packageSetting = tree.packageSetting; 6784 bp.perm = new PackageParser.Permission(tree.perm.owner, 6785 new PermissionInfo(bp.pendingInfo)); 6786 bp.perm.info.packageName = tree.perm.info.packageName; 6787 bp.perm.info.name = bp.name; 6788 bp.uid = tree.uid; 6789 } 6790 } 6791 } 6792 if (bp.packageSetting == null) { 6793 // We may not yet have parsed the package, so just see if 6794 // we still know about its settings. 6795 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6796 } 6797 if (bp.packageSetting == null) { 6798 Slog.w(TAG, "Removing dangling permission: " + bp.name 6799 + " from package " + bp.sourcePackage); 6800 it.remove(); 6801 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6802 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6803 Slog.i(TAG, "Removing old permission: " + bp.name 6804 + " from package " + bp.sourcePackage); 6805 flags |= UPDATE_PERMISSIONS_ALL; 6806 it.remove(); 6807 } 6808 } 6809 } 6810 6811 // Now update the permissions for all packages, in particular 6812 // replace the granted permissions of the system packages. 6813 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6814 for (PackageParser.Package pkg : mPackages.values()) { 6815 if (pkg != pkgInfo) { 6816 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6817 changingPkg); 6818 } 6819 } 6820 } 6821 6822 if (pkgInfo != null) { 6823 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6824 } 6825 } 6826 6827 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6828 String packageOfInterest) { 6829 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6830 if (ps == null) { 6831 return; 6832 } 6833 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6834 ArraySet<String> origPermissions = gp.grantedPermissions; 6835 boolean changedPermission = false; 6836 6837 if (replace) { 6838 ps.permissionsFixed = false; 6839 if (gp == ps) { 6840 origPermissions = new ArraySet<String>(gp.grantedPermissions); 6841 gp.grantedPermissions.clear(); 6842 gp.gids = mGlobalGids; 6843 } 6844 } 6845 6846 if (gp.gids == null) { 6847 gp.gids = mGlobalGids; 6848 } 6849 6850 final int N = pkg.requestedPermissions.size(); 6851 for (int i=0; i<N; i++) { 6852 final String name = pkg.requestedPermissions.get(i); 6853 final boolean required = pkg.requestedPermissionsRequired.get(i); 6854 final BasePermission bp = mSettings.mPermissions.get(name); 6855 if (DEBUG_INSTALL) { 6856 if (gp != ps) { 6857 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6858 } 6859 } 6860 6861 if (bp == null || bp.packageSetting == null) { 6862 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6863 Slog.w(TAG, "Unknown permission " + name 6864 + " in package " + pkg.packageName); 6865 } 6866 continue; 6867 } 6868 6869 final String perm = bp.name; 6870 boolean allowed; 6871 boolean allowedSig = false; 6872 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6873 // Keep track of app op permissions. 6874 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6875 if (pkgs == null) { 6876 pkgs = new ArraySet<>(); 6877 mAppOpPermissionPackages.put(bp.name, pkgs); 6878 } 6879 pkgs.add(pkg.packageName); 6880 } 6881 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6882 if (level == PermissionInfo.PROTECTION_NORMAL 6883 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6884 // We grant a normal or dangerous permission if any of the following 6885 // are true: 6886 // 1) The permission is required 6887 // 2) The permission is optional, but was granted in the past 6888 // 3) The permission is optional, but was requested by an 6889 // app in /system (not /data) 6890 // 6891 // Otherwise, reject the permission. 6892 allowed = (required || origPermissions.contains(perm) 6893 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6894 } else if (bp.packageSetting == null) { 6895 // This permission is invalid; skip it. 6896 allowed = false; 6897 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6898 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6899 if (allowed) { 6900 allowedSig = true; 6901 } 6902 } else { 6903 allowed = false; 6904 } 6905 if (DEBUG_INSTALL) { 6906 if (gp != ps) { 6907 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6908 } 6909 } 6910 if (allowed) { 6911 if (!isSystemApp(ps) && ps.permissionsFixed) { 6912 // If this is an existing, non-system package, then 6913 // we can't add any new permissions to it. 6914 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6915 // Except... if this is a permission that was added 6916 // to the platform (note: need to only do this when 6917 // updating the platform). 6918 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6919 } 6920 } 6921 if (allowed) { 6922 if (!gp.grantedPermissions.contains(perm)) { 6923 changedPermission = true; 6924 gp.grantedPermissions.add(perm); 6925 gp.gids = appendInts(gp.gids, bp.gids); 6926 } else if (!ps.haveGids) { 6927 gp.gids = appendInts(gp.gids, bp.gids); 6928 } 6929 } else { 6930 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6931 Slog.w(TAG, "Not granting permission " + perm 6932 + " to package " + pkg.packageName 6933 + " because it was previously installed without"); 6934 } 6935 } 6936 } else { 6937 if (gp.grantedPermissions.remove(perm)) { 6938 changedPermission = true; 6939 gp.gids = removeInts(gp.gids, bp.gids); 6940 Slog.i(TAG, "Un-granting permission " + perm 6941 + " from package " + pkg.packageName 6942 + " (protectionLevel=" + bp.protectionLevel 6943 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6944 + ")"); 6945 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6946 // Don't print warning for app op permissions, since it is fine for them 6947 // not to be granted, there is a UI for the user to decide. 6948 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6949 Slog.w(TAG, "Not granting permission " + perm 6950 + " to package " + pkg.packageName 6951 + " (protectionLevel=" + bp.protectionLevel 6952 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6953 + ")"); 6954 } 6955 } 6956 } 6957 } 6958 6959 if ((changedPermission || replace) && !ps.permissionsFixed && 6960 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6961 // This is the first that we have heard about this package, so the 6962 // permissions we have now selected are fixed until explicitly 6963 // changed. 6964 ps.permissionsFixed = true; 6965 } 6966 ps.haveGids = true; 6967 } 6968 6969 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6970 boolean allowed = false; 6971 final int NP = PackageParser.NEW_PERMISSIONS.length; 6972 for (int ip=0; ip<NP; ip++) { 6973 final PackageParser.NewPermissionInfo npi 6974 = PackageParser.NEW_PERMISSIONS[ip]; 6975 if (npi.name.equals(perm) 6976 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6977 allowed = true; 6978 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6979 + pkg.packageName); 6980 break; 6981 } 6982 } 6983 return allowed; 6984 } 6985 6986 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6987 BasePermission bp, ArraySet<String> origPermissions) { 6988 boolean allowed; 6989 allowed = (compareSignatures( 6990 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6991 == PackageManager.SIGNATURE_MATCH) 6992 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6993 == PackageManager.SIGNATURE_MATCH); 6994 if (!allowed && (bp.protectionLevel 6995 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6996 if (isSystemApp(pkg)) { 6997 // For updated system applications, a system permission 6998 // is granted only if it had been defined by the original application. 6999 if (pkg.isUpdatedSystemApp()) { 7000 final PackageSetting sysPs = mSettings 7001 .getDisabledSystemPkgLPr(pkg.packageName); 7002 final GrantedPermissions origGp = sysPs.sharedUser != null 7003 ? sysPs.sharedUser : sysPs; 7004 7005 if (origGp.grantedPermissions.contains(perm)) { 7006 // If the original was granted this permission, we take 7007 // that grant decision as read and propagate it to the 7008 // update. 7009 if (sysPs.isPrivileged()) { 7010 allowed = true; 7011 } 7012 } else { 7013 // The system apk may have been updated with an older 7014 // version of the one on the data partition, but which 7015 // granted a new system permission that it didn't have 7016 // before. In this case we do want to allow the app to 7017 // now get the new permission if the ancestral apk is 7018 // privileged to get it. 7019 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7020 for (int j=0; 7021 j<sysPs.pkg.requestedPermissions.size(); j++) { 7022 if (perm.equals( 7023 sysPs.pkg.requestedPermissions.get(j))) { 7024 allowed = true; 7025 break; 7026 } 7027 } 7028 } 7029 } 7030 } else { 7031 allowed = isPrivilegedApp(pkg); 7032 } 7033 } 7034 } 7035 if (!allowed && (bp.protectionLevel 7036 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7037 // For development permissions, a development permission 7038 // is granted only if it was already granted. 7039 allowed = origPermissions.contains(perm); 7040 } 7041 return allowed; 7042 } 7043 7044 final class ActivityIntentResolver 7045 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7046 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7047 boolean defaultOnly, int userId) { 7048 if (!sUserManager.exists(userId)) return null; 7049 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7050 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7051 } 7052 7053 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7054 int userId) { 7055 if (!sUserManager.exists(userId)) return null; 7056 mFlags = flags; 7057 return super.queryIntent(intent, resolvedType, 7058 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7059 } 7060 7061 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7062 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7063 if (!sUserManager.exists(userId)) return null; 7064 if (packageActivities == null) { 7065 return null; 7066 } 7067 mFlags = flags; 7068 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7069 final int N = packageActivities.size(); 7070 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7071 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7072 7073 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7074 for (int i = 0; i < N; ++i) { 7075 intentFilters = packageActivities.get(i).intents; 7076 if (intentFilters != null && intentFilters.size() > 0) { 7077 PackageParser.ActivityIntentInfo[] array = 7078 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7079 intentFilters.toArray(array); 7080 listCut.add(array); 7081 } 7082 } 7083 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7084 } 7085 7086 public final void addActivity(PackageParser.Activity a, String type) { 7087 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7088 mActivities.put(a.getComponentName(), a); 7089 if (DEBUG_SHOW_INFO) 7090 Log.v( 7091 TAG, " " + type + " " + 7092 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7093 if (DEBUG_SHOW_INFO) 7094 Log.v(TAG, " Class=" + a.info.name); 7095 final int NI = a.intents.size(); 7096 for (int j=0; j<NI; j++) { 7097 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7098 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7099 intent.setPriority(0); 7100 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7101 + a.className + " with priority > 0, forcing to 0"); 7102 } 7103 if (DEBUG_SHOW_INFO) { 7104 Log.v(TAG, " IntentFilter:"); 7105 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7106 } 7107 if (!intent.debugCheck()) { 7108 Log.w(TAG, "==> For Activity " + a.info.name); 7109 } 7110 addFilter(intent); 7111 } 7112 } 7113 7114 public final void removeActivity(PackageParser.Activity a, String type) { 7115 mActivities.remove(a.getComponentName()); 7116 if (DEBUG_SHOW_INFO) { 7117 Log.v(TAG, " " + type + " " 7118 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7119 : a.info.name) + ":"); 7120 Log.v(TAG, " Class=" + a.info.name); 7121 } 7122 final int NI = a.intents.size(); 7123 for (int j=0; j<NI; j++) { 7124 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7125 if (DEBUG_SHOW_INFO) { 7126 Log.v(TAG, " IntentFilter:"); 7127 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7128 } 7129 removeFilter(intent); 7130 } 7131 } 7132 7133 @Override 7134 protected boolean allowFilterResult( 7135 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7136 ActivityInfo filterAi = filter.activity.info; 7137 for (int i=dest.size()-1; i>=0; i--) { 7138 ActivityInfo destAi = dest.get(i).activityInfo; 7139 if (destAi.name == filterAi.name 7140 && destAi.packageName == filterAi.packageName) { 7141 return false; 7142 } 7143 } 7144 return true; 7145 } 7146 7147 @Override 7148 protected ActivityIntentInfo[] newArray(int size) { 7149 return new ActivityIntentInfo[size]; 7150 } 7151 7152 @Override 7153 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7154 if (!sUserManager.exists(userId)) return true; 7155 PackageParser.Package p = filter.activity.owner; 7156 if (p != null) { 7157 PackageSetting ps = (PackageSetting)p.mExtras; 7158 if (ps != null) { 7159 // System apps are never considered stopped for purposes of 7160 // filtering, because there may be no way for the user to 7161 // actually re-launch them. 7162 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7163 && ps.getStopped(userId); 7164 } 7165 } 7166 return false; 7167 } 7168 7169 @Override 7170 protected boolean isPackageForFilter(String packageName, 7171 PackageParser.ActivityIntentInfo info) { 7172 return packageName.equals(info.activity.owner.packageName); 7173 } 7174 7175 @Override 7176 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7177 int match, int userId) { 7178 if (!sUserManager.exists(userId)) return null; 7179 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7180 return null; 7181 } 7182 final PackageParser.Activity activity = info.activity; 7183 if (mSafeMode && (activity.info.applicationInfo.flags 7184 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7185 return null; 7186 } 7187 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7188 if (ps == null) { 7189 return null; 7190 } 7191 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7192 ps.readUserState(userId), userId); 7193 if (ai == null) { 7194 return null; 7195 } 7196 final ResolveInfo res = new ResolveInfo(); 7197 res.activityInfo = ai; 7198 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7199 res.filter = info; 7200 } 7201 res.priority = info.getPriority(); 7202 res.preferredOrder = activity.owner.mPreferredOrder; 7203 //System.out.println("Result: " + res.activityInfo.className + 7204 // " = " + res.priority); 7205 res.match = match; 7206 res.isDefault = info.hasDefault; 7207 res.labelRes = info.labelRes; 7208 res.nonLocalizedLabel = info.nonLocalizedLabel; 7209 if (userNeedsBadging(userId)) { 7210 res.noResourceId = true; 7211 } else { 7212 res.icon = info.icon; 7213 } 7214 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7215 return res; 7216 } 7217 7218 @Override 7219 protected void sortResults(List<ResolveInfo> results) { 7220 Collections.sort(results, mResolvePrioritySorter); 7221 } 7222 7223 @Override 7224 protected void dumpFilter(PrintWriter out, String prefix, 7225 PackageParser.ActivityIntentInfo filter) { 7226 out.print(prefix); out.print( 7227 Integer.toHexString(System.identityHashCode(filter.activity))); 7228 out.print(' '); 7229 filter.activity.printComponentShortName(out); 7230 out.print(" filter "); 7231 out.println(Integer.toHexString(System.identityHashCode(filter))); 7232 } 7233 7234 @Override 7235 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7236 return filter.activity; 7237 } 7238 7239 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7240 PackageParser.Activity activity = (PackageParser.Activity)label; 7241 out.print(prefix); out.print( 7242 Integer.toHexString(System.identityHashCode(activity))); 7243 out.print(' '); 7244 activity.printComponentShortName(out); 7245 if (count > 1) { 7246 out.print(" ("); out.print(count); out.print(" filters)"); 7247 } 7248 out.println(); 7249 } 7250 7251// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7252// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7253// final List<ResolveInfo> retList = Lists.newArrayList(); 7254// while (i.hasNext()) { 7255// final ResolveInfo resolveInfo = i.next(); 7256// if (isEnabledLP(resolveInfo.activityInfo)) { 7257// retList.add(resolveInfo); 7258// } 7259// } 7260// return retList; 7261// } 7262 7263 // Keys are String (activity class name), values are Activity. 7264 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7265 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7266 private int mFlags; 7267 } 7268 7269 private final class ServiceIntentResolver 7270 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7271 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7272 boolean defaultOnly, int userId) { 7273 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7274 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7275 } 7276 7277 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7278 int userId) { 7279 if (!sUserManager.exists(userId)) return null; 7280 mFlags = flags; 7281 return super.queryIntent(intent, resolvedType, 7282 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7283 } 7284 7285 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7286 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7287 if (!sUserManager.exists(userId)) return null; 7288 if (packageServices == null) { 7289 return null; 7290 } 7291 mFlags = flags; 7292 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7293 final int N = packageServices.size(); 7294 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7295 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7296 7297 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7298 for (int i = 0; i < N; ++i) { 7299 intentFilters = packageServices.get(i).intents; 7300 if (intentFilters != null && intentFilters.size() > 0) { 7301 PackageParser.ServiceIntentInfo[] array = 7302 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7303 intentFilters.toArray(array); 7304 listCut.add(array); 7305 } 7306 } 7307 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7308 } 7309 7310 public final void addService(PackageParser.Service s) { 7311 mServices.put(s.getComponentName(), s); 7312 if (DEBUG_SHOW_INFO) { 7313 Log.v(TAG, " " 7314 + (s.info.nonLocalizedLabel != null 7315 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7316 Log.v(TAG, " Class=" + s.info.name); 7317 } 7318 final int NI = s.intents.size(); 7319 int j; 7320 for (j=0; j<NI; j++) { 7321 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7322 if (DEBUG_SHOW_INFO) { 7323 Log.v(TAG, " IntentFilter:"); 7324 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7325 } 7326 if (!intent.debugCheck()) { 7327 Log.w(TAG, "==> For Service " + s.info.name); 7328 } 7329 addFilter(intent); 7330 } 7331 } 7332 7333 public final void removeService(PackageParser.Service s) { 7334 mServices.remove(s.getComponentName()); 7335 if (DEBUG_SHOW_INFO) { 7336 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7337 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7338 Log.v(TAG, " Class=" + s.info.name); 7339 } 7340 final int NI = s.intents.size(); 7341 int j; 7342 for (j=0; j<NI; j++) { 7343 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7344 if (DEBUG_SHOW_INFO) { 7345 Log.v(TAG, " IntentFilter:"); 7346 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7347 } 7348 removeFilter(intent); 7349 } 7350 } 7351 7352 @Override 7353 protected boolean allowFilterResult( 7354 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7355 ServiceInfo filterSi = filter.service.info; 7356 for (int i=dest.size()-1; i>=0; i--) { 7357 ServiceInfo destAi = dest.get(i).serviceInfo; 7358 if (destAi.name == filterSi.name 7359 && destAi.packageName == filterSi.packageName) { 7360 return false; 7361 } 7362 } 7363 return true; 7364 } 7365 7366 @Override 7367 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7368 return new PackageParser.ServiceIntentInfo[size]; 7369 } 7370 7371 @Override 7372 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7373 if (!sUserManager.exists(userId)) return true; 7374 PackageParser.Package p = filter.service.owner; 7375 if (p != null) { 7376 PackageSetting ps = (PackageSetting)p.mExtras; 7377 if (ps != null) { 7378 // System apps are never considered stopped for purposes of 7379 // filtering, because there may be no way for the user to 7380 // actually re-launch them. 7381 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7382 && ps.getStopped(userId); 7383 } 7384 } 7385 return false; 7386 } 7387 7388 @Override 7389 protected boolean isPackageForFilter(String packageName, 7390 PackageParser.ServiceIntentInfo info) { 7391 return packageName.equals(info.service.owner.packageName); 7392 } 7393 7394 @Override 7395 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7396 int match, int userId) { 7397 if (!sUserManager.exists(userId)) return null; 7398 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7399 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7400 return null; 7401 } 7402 final PackageParser.Service service = info.service; 7403 if (mSafeMode && (service.info.applicationInfo.flags 7404 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7405 return null; 7406 } 7407 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7408 if (ps == null) { 7409 return null; 7410 } 7411 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7412 ps.readUserState(userId), userId); 7413 if (si == null) { 7414 return null; 7415 } 7416 final ResolveInfo res = new ResolveInfo(); 7417 res.serviceInfo = si; 7418 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7419 res.filter = filter; 7420 } 7421 res.priority = info.getPriority(); 7422 res.preferredOrder = service.owner.mPreferredOrder; 7423 //System.out.println("Result: " + res.activityInfo.className + 7424 // " = " + res.priority); 7425 res.match = match; 7426 res.isDefault = info.hasDefault; 7427 res.labelRes = info.labelRes; 7428 res.nonLocalizedLabel = info.nonLocalizedLabel; 7429 res.icon = info.icon; 7430 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 7431 return res; 7432 } 7433 7434 @Override 7435 protected void sortResults(List<ResolveInfo> results) { 7436 Collections.sort(results, mResolvePrioritySorter); 7437 } 7438 7439 @Override 7440 protected void dumpFilter(PrintWriter out, String prefix, 7441 PackageParser.ServiceIntentInfo filter) { 7442 out.print(prefix); out.print( 7443 Integer.toHexString(System.identityHashCode(filter.service))); 7444 out.print(' '); 7445 filter.service.printComponentShortName(out); 7446 out.print(" filter "); 7447 out.println(Integer.toHexString(System.identityHashCode(filter))); 7448 } 7449 7450 @Override 7451 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 7452 return filter.service; 7453 } 7454 7455 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7456 PackageParser.Service service = (PackageParser.Service)label; 7457 out.print(prefix); out.print( 7458 Integer.toHexString(System.identityHashCode(service))); 7459 out.print(' '); 7460 service.printComponentShortName(out); 7461 if (count > 1) { 7462 out.print(" ("); out.print(count); out.print(" filters)"); 7463 } 7464 out.println(); 7465 } 7466 7467// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7468// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7469// final List<ResolveInfo> retList = Lists.newArrayList(); 7470// while (i.hasNext()) { 7471// final ResolveInfo resolveInfo = (ResolveInfo) i; 7472// if (isEnabledLP(resolveInfo.serviceInfo)) { 7473// retList.add(resolveInfo); 7474// } 7475// } 7476// return retList; 7477// } 7478 7479 // Keys are String (activity class name), values are Activity. 7480 private final ArrayMap<ComponentName, PackageParser.Service> mServices 7481 = new ArrayMap<ComponentName, PackageParser.Service>(); 7482 private int mFlags; 7483 }; 7484 7485 private final class ProviderIntentResolver 7486 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7487 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7488 boolean defaultOnly, int userId) { 7489 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7490 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7491 } 7492 7493 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7494 int userId) { 7495 if (!sUserManager.exists(userId)) 7496 return null; 7497 mFlags = flags; 7498 return super.queryIntent(intent, resolvedType, 7499 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7500 } 7501 7502 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7503 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7504 if (!sUserManager.exists(userId)) 7505 return null; 7506 if (packageProviders == null) { 7507 return null; 7508 } 7509 mFlags = flags; 7510 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7511 final int N = packageProviders.size(); 7512 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7513 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7514 7515 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7516 for (int i = 0; i < N; ++i) { 7517 intentFilters = packageProviders.get(i).intents; 7518 if (intentFilters != null && intentFilters.size() > 0) { 7519 PackageParser.ProviderIntentInfo[] array = 7520 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7521 intentFilters.toArray(array); 7522 listCut.add(array); 7523 } 7524 } 7525 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7526 } 7527 7528 public final void addProvider(PackageParser.Provider p) { 7529 if (mProviders.containsKey(p.getComponentName())) { 7530 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7531 return; 7532 } 7533 7534 mProviders.put(p.getComponentName(), p); 7535 if (DEBUG_SHOW_INFO) { 7536 Log.v(TAG, " " 7537 + (p.info.nonLocalizedLabel != null 7538 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7539 Log.v(TAG, " Class=" + p.info.name); 7540 } 7541 final int NI = p.intents.size(); 7542 int j; 7543 for (j = 0; j < NI; j++) { 7544 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7545 if (DEBUG_SHOW_INFO) { 7546 Log.v(TAG, " IntentFilter:"); 7547 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7548 } 7549 if (!intent.debugCheck()) { 7550 Log.w(TAG, "==> For Provider " + p.info.name); 7551 } 7552 addFilter(intent); 7553 } 7554 } 7555 7556 public final void removeProvider(PackageParser.Provider p) { 7557 mProviders.remove(p.getComponentName()); 7558 if (DEBUG_SHOW_INFO) { 7559 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7560 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7561 Log.v(TAG, " Class=" + p.info.name); 7562 } 7563 final int NI = p.intents.size(); 7564 int j; 7565 for (j = 0; j < NI; j++) { 7566 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7567 if (DEBUG_SHOW_INFO) { 7568 Log.v(TAG, " IntentFilter:"); 7569 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7570 } 7571 removeFilter(intent); 7572 } 7573 } 7574 7575 @Override 7576 protected boolean allowFilterResult( 7577 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7578 ProviderInfo filterPi = filter.provider.info; 7579 for (int i = dest.size() - 1; i >= 0; i--) { 7580 ProviderInfo destPi = dest.get(i).providerInfo; 7581 if (destPi.name == filterPi.name 7582 && destPi.packageName == filterPi.packageName) { 7583 return false; 7584 } 7585 } 7586 return true; 7587 } 7588 7589 @Override 7590 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7591 return new PackageParser.ProviderIntentInfo[size]; 7592 } 7593 7594 @Override 7595 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7596 if (!sUserManager.exists(userId)) 7597 return true; 7598 PackageParser.Package p = filter.provider.owner; 7599 if (p != null) { 7600 PackageSetting ps = (PackageSetting) p.mExtras; 7601 if (ps != null) { 7602 // System apps are never considered stopped for purposes of 7603 // filtering, because there may be no way for the user to 7604 // actually re-launch them. 7605 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7606 && ps.getStopped(userId); 7607 } 7608 } 7609 return false; 7610 } 7611 7612 @Override 7613 protected boolean isPackageForFilter(String packageName, 7614 PackageParser.ProviderIntentInfo info) { 7615 return packageName.equals(info.provider.owner.packageName); 7616 } 7617 7618 @Override 7619 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7620 int match, int userId) { 7621 if (!sUserManager.exists(userId)) 7622 return null; 7623 final PackageParser.ProviderIntentInfo info = filter; 7624 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7625 return null; 7626 } 7627 final PackageParser.Provider provider = info.provider; 7628 if (mSafeMode && (provider.info.applicationInfo.flags 7629 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7630 return null; 7631 } 7632 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7633 if (ps == null) { 7634 return null; 7635 } 7636 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7637 ps.readUserState(userId), userId); 7638 if (pi == null) { 7639 return null; 7640 } 7641 final ResolveInfo res = new ResolveInfo(); 7642 res.providerInfo = pi; 7643 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7644 res.filter = filter; 7645 } 7646 res.priority = info.getPriority(); 7647 res.preferredOrder = provider.owner.mPreferredOrder; 7648 res.match = match; 7649 res.isDefault = info.hasDefault; 7650 res.labelRes = info.labelRes; 7651 res.nonLocalizedLabel = info.nonLocalizedLabel; 7652 res.icon = info.icon; 7653 res.system = res.providerInfo.applicationInfo.isSystemApp(); 7654 return res; 7655 } 7656 7657 @Override 7658 protected void sortResults(List<ResolveInfo> results) { 7659 Collections.sort(results, mResolvePrioritySorter); 7660 } 7661 7662 @Override 7663 protected void dumpFilter(PrintWriter out, String prefix, 7664 PackageParser.ProviderIntentInfo filter) { 7665 out.print(prefix); 7666 out.print( 7667 Integer.toHexString(System.identityHashCode(filter.provider))); 7668 out.print(' '); 7669 filter.provider.printComponentShortName(out); 7670 out.print(" filter "); 7671 out.println(Integer.toHexString(System.identityHashCode(filter))); 7672 } 7673 7674 @Override 7675 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 7676 return filter.provider; 7677 } 7678 7679 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7680 PackageParser.Provider provider = (PackageParser.Provider)label; 7681 out.print(prefix); out.print( 7682 Integer.toHexString(System.identityHashCode(provider))); 7683 out.print(' '); 7684 provider.printComponentShortName(out); 7685 if (count > 1) { 7686 out.print(" ("); out.print(count); out.print(" filters)"); 7687 } 7688 out.println(); 7689 } 7690 7691 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 7692 = new ArrayMap<ComponentName, PackageParser.Provider>(); 7693 private int mFlags; 7694 }; 7695 7696 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7697 new Comparator<ResolveInfo>() { 7698 public int compare(ResolveInfo r1, ResolveInfo r2) { 7699 int v1 = r1.priority; 7700 int v2 = r2.priority; 7701 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7702 if (v1 != v2) { 7703 return (v1 > v2) ? -1 : 1; 7704 } 7705 v1 = r1.preferredOrder; 7706 v2 = r2.preferredOrder; 7707 if (v1 != v2) { 7708 return (v1 > v2) ? -1 : 1; 7709 } 7710 if (r1.isDefault != r2.isDefault) { 7711 return r1.isDefault ? -1 : 1; 7712 } 7713 v1 = r1.match; 7714 v2 = r2.match; 7715 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7716 if (v1 != v2) { 7717 return (v1 > v2) ? -1 : 1; 7718 } 7719 if (r1.system != r2.system) { 7720 return r1.system ? -1 : 1; 7721 } 7722 return 0; 7723 } 7724 }; 7725 7726 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7727 new Comparator<ProviderInfo>() { 7728 public int compare(ProviderInfo p1, ProviderInfo p2) { 7729 final int v1 = p1.initOrder; 7730 final int v2 = p2.initOrder; 7731 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7732 } 7733 }; 7734 7735 static final void sendPackageBroadcast(String action, String pkg, 7736 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7737 int[] userIds) { 7738 IActivityManager am = ActivityManagerNative.getDefault(); 7739 if (am != null) { 7740 try { 7741 if (userIds == null) { 7742 userIds = am.getRunningUserIds(); 7743 } 7744 for (int id : userIds) { 7745 final Intent intent = new Intent(action, 7746 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7747 if (extras != null) { 7748 intent.putExtras(extras); 7749 } 7750 if (targetPkg != null) { 7751 intent.setPackage(targetPkg); 7752 } 7753 // Modify the UID when posting to other users 7754 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7755 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7756 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7757 intent.putExtra(Intent.EXTRA_UID, uid); 7758 } 7759 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7760 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7761 if (DEBUG_BROADCASTS) { 7762 RuntimeException here = new RuntimeException("here"); 7763 here.fillInStackTrace(); 7764 Slog.d(TAG, "Sending to user " + id + ": " 7765 + intent.toShortString(false, true, false, false) 7766 + " " + intent.getExtras(), here); 7767 } 7768 am.broadcastIntent(null, intent, null, finishedReceiver, 7769 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7770 finishedReceiver != null, false, id); 7771 } 7772 } catch (RemoteException ex) { 7773 } 7774 } 7775 } 7776 7777 /** 7778 * Check if the external storage media is available. This is true if there 7779 * is a mounted external storage medium or if the external storage is 7780 * emulated. 7781 */ 7782 private boolean isExternalMediaAvailable() { 7783 return mMediaMounted || Environment.isExternalStorageEmulated(); 7784 } 7785 7786 @Override 7787 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7788 // writer 7789 synchronized (mPackages) { 7790 if (!isExternalMediaAvailable()) { 7791 // If the external storage is no longer mounted at this point, 7792 // the caller may not have been able to delete all of this 7793 // packages files and can not delete any more. Bail. 7794 return null; 7795 } 7796 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7797 if (lastPackage != null) { 7798 pkgs.remove(lastPackage); 7799 } 7800 if (pkgs.size() > 0) { 7801 return pkgs.get(0); 7802 } 7803 } 7804 return null; 7805 } 7806 7807 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7808 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7809 userId, andCode ? 1 : 0, packageName); 7810 if (mSystemReady) { 7811 msg.sendToTarget(); 7812 } else { 7813 if (mPostSystemReadyMessages == null) { 7814 mPostSystemReadyMessages = new ArrayList<>(); 7815 } 7816 mPostSystemReadyMessages.add(msg); 7817 } 7818 } 7819 7820 void startCleaningPackages() { 7821 // reader 7822 synchronized (mPackages) { 7823 if (!isExternalMediaAvailable()) { 7824 return; 7825 } 7826 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7827 return; 7828 } 7829 } 7830 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7831 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7832 IActivityManager am = ActivityManagerNative.getDefault(); 7833 if (am != null) { 7834 try { 7835 am.startService(null, intent, null, UserHandle.USER_OWNER); 7836 } catch (RemoteException e) { 7837 } 7838 } 7839 } 7840 7841 @Override 7842 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7843 int installFlags, String installerPackageName, VerificationParams verificationParams, 7844 String packageAbiOverride) { 7845 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7846 packageAbiOverride, UserHandle.getCallingUserId()); 7847 } 7848 7849 @Override 7850 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7851 int installFlags, String installerPackageName, VerificationParams verificationParams, 7852 String packageAbiOverride, int userId) { 7853 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 7854 7855 final int callingUid = Binder.getCallingUid(); 7856 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 7857 7858 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7859 try { 7860 if (observer != null) { 7861 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7862 } 7863 } catch (RemoteException re) { 7864 } 7865 return; 7866 } 7867 7868 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 7869 installFlags |= PackageManager.INSTALL_FROM_ADB; 7870 7871 } else { 7872 // Caller holds INSTALL_PACKAGES permission, so we're less strict 7873 // about installerPackageName. 7874 7875 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 7876 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 7877 } 7878 7879 UserHandle user; 7880 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7881 user = UserHandle.ALL; 7882 } else { 7883 user = new UserHandle(userId); 7884 } 7885 7886 verificationParams.setInstallerUid(callingUid); 7887 7888 final File originFile = new File(originPath); 7889 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7890 7891 final Message msg = mHandler.obtainMessage(INIT_COPY); 7892 msg.obj = new InstallParams(origin, observer, installFlags, 7893 installerPackageName, verificationParams, user, packageAbiOverride); 7894 mHandler.sendMessage(msg); 7895 } 7896 7897 void installStage(String packageName, File stagedDir, String stagedCid, 7898 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7899 String installerPackageName, int installerUid, UserHandle user) { 7900 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7901 params.referrerUri, installerUid, null); 7902 7903 final OriginInfo origin; 7904 if (stagedDir != null) { 7905 origin = OriginInfo.fromStagedFile(stagedDir); 7906 } else { 7907 origin = OriginInfo.fromStagedContainer(stagedCid); 7908 } 7909 7910 final Message msg = mHandler.obtainMessage(INIT_COPY); 7911 msg.obj = new InstallParams(origin, observer, params.installFlags, 7912 installerPackageName, verifParams, user, params.abiOverride); 7913 mHandler.sendMessage(msg); 7914 } 7915 7916 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7917 Bundle extras = new Bundle(1); 7918 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7919 7920 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7921 packageName, extras, null, null, new int[] {userId}); 7922 try { 7923 IActivityManager am = ActivityManagerNative.getDefault(); 7924 final boolean isSystem = 7925 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7926 if (isSystem && am.isUserRunning(userId, false)) { 7927 // The just-installed/enabled app is bundled on the system, so presumed 7928 // to be able to run automatically without needing an explicit launch. 7929 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7930 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7931 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7932 .setPackage(packageName); 7933 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7934 android.app.AppOpsManager.OP_NONE, false, false, userId); 7935 } 7936 } catch (RemoteException e) { 7937 // shouldn't happen 7938 Slog.w(TAG, "Unable to bootstrap installed package", e); 7939 } 7940 } 7941 7942 @Override 7943 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7944 int userId) { 7945 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7946 PackageSetting pkgSetting; 7947 final int uid = Binder.getCallingUid(); 7948 enforceCrossUserPermission(uid, userId, true, true, 7949 "setApplicationHiddenSetting for user " + userId); 7950 7951 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7952 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7953 return false; 7954 } 7955 7956 long callingId = Binder.clearCallingIdentity(); 7957 try { 7958 boolean sendAdded = false; 7959 boolean sendRemoved = false; 7960 // writer 7961 synchronized (mPackages) { 7962 pkgSetting = mSettings.mPackages.get(packageName); 7963 if (pkgSetting == null) { 7964 return false; 7965 } 7966 if (pkgSetting.getHidden(userId) != hidden) { 7967 pkgSetting.setHidden(hidden, userId); 7968 mSettings.writePackageRestrictionsLPr(userId); 7969 if (hidden) { 7970 sendRemoved = true; 7971 } else { 7972 sendAdded = true; 7973 } 7974 } 7975 } 7976 if (sendAdded) { 7977 sendPackageAddedForUser(packageName, pkgSetting, userId); 7978 return true; 7979 } 7980 if (sendRemoved) { 7981 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7982 "hiding pkg"); 7983 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7984 } 7985 } finally { 7986 Binder.restoreCallingIdentity(callingId); 7987 } 7988 return false; 7989 } 7990 7991 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7992 int userId) { 7993 final PackageRemovedInfo info = new PackageRemovedInfo(); 7994 info.removedPackage = packageName; 7995 info.removedUsers = new int[] {userId}; 7996 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7997 info.sendBroadcast(false, false, false); 7998 } 7999 8000 /** 8001 * Returns true if application is not found or there was an error. Otherwise it returns 8002 * the hidden state of the package for the given user. 8003 */ 8004 @Override 8005 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8006 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8007 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8008 false, "getApplicationHidden for user " + userId); 8009 PackageSetting pkgSetting; 8010 long callingId = Binder.clearCallingIdentity(); 8011 try { 8012 // writer 8013 synchronized (mPackages) { 8014 pkgSetting = mSettings.mPackages.get(packageName); 8015 if (pkgSetting == null) { 8016 return true; 8017 } 8018 return pkgSetting.getHidden(userId); 8019 } 8020 } finally { 8021 Binder.restoreCallingIdentity(callingId); 8022 } 8023 } 8024 8025 /** 8026 * @hide 8027 */ 8028 @Override 8029 public int installExistingPackageAsUser(String packageName, int userId) { 8030 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8031 null); 8032 PackageSetting pkgSetting; 8033 final int uid = Binder.getCallingUid(); 8034 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8035 + userId); 8036 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8037 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8038 } 8039 8040 long callingId = Binder.clearCallingIdentity(); 8041 try { 8042 boolean sendAdded = false; 8043 Bundle extras = new Bundle(1); 8044 8045 // writer 8046 synchronized (mPackages) { 8047 pkgSetting = mSettings.mPackages.get(packageName); 8048 if (pkgSetting == null) { 8049 return PackageManager.INSTALL_FAILED_INVALID_URI; 8050 } 8051 if (!pkgSetting.getInstalled(userId)) { 8052 pkgSetting.setInstalled(true, userId); 8053 pkgSetting.setHidden(false, userId); 8054 mSettings.writePackageRestrictionsLPr(userId); 8055 sendAdded = true; 8056 } 8057 } 8058 8059 if (sendAdded) { 8060 sendPackageAddedForUser(packageName, pkgSetting, userId); 8061 } 8062 } finally { 8063 Binder.restoreCallingIdentity(callingId); 8064 } 8065 8066 return PackageManager.INSTALL_SUCCEEDED; 8067 } 8068 8069 boolean isUserRestricted(int userId, String restrictionKey) { 8070 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8071 if (restrictions.getBoolean(restrictionKey, false)) { 8072 Log.w(TAG, "User is restricted: " + restrictionKey); 8073 return true; 8074 } 8075 return false; 8076 } 8077 8078 @Override 8079 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8080 mContext.enforceCallingOrSelfPermission( 8081 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8082 "Only package verification agents can verify applications"); 8083 8084 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8085 final PackageVerificationResponse response = new PackageVerificationResponse( 8086 verificationCode, Binder.getCallingUid()); 8087 msg.arg1 = id; 8088 msg.obj = response; 8089 mHandler.sendMessage(msg); 8090 } 8091 8092 @Override 8093 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8094 long millisecondsToDelay) { 8095 mContext.enforceCallingOrSelfPermission( 8096 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8097 "Only package verification agents can extend verification timeouts"); 8098 8099 final PackageVerificationState state = mPendingVerification.get(id); 8100 final PackageVerificationResponse response = new PackageVerificationResponse( 8101 verificationCodeAtTimeout, Binder.getCallingUid()); 8102 8103 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8104 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8105 } 8106 if (millisecondsToDelay < 0) { 8107 millisecondsToDelay = 0; 8108 } 8109 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8110 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8111 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8112 } 8113 8114 if ((state != null) && !state.timeoutExtended()) { 8115 state.extendTimeout(); 8116 8117 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8118 msg.arg1 = id; 8119 msg.obj = response; 8120 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8121 } 8122 } 8123 8124 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8125 int verificationCode, UserHandle user) { 8126 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8127 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8128 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8129 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8130 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8131 8132 mContext.sendBroadcastAsUser(intent, user, 8133 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8134 } 8135 8136 private ComponentName matchComponentForVerifier(String packageName, 8137 List<ResolveInfo> receivers) { 8138 ActivityInfo targetReceiver = null; 8139 8140 final int NR = receivers.size(); 8141 for (int i = 0; i < NR; i++) { 8142 final ResolveInfo info = receivers.get(i); 8143 if (info.activityInfo == null) { 8144 continue; 8145 } 8146 8147 if (packageName.equals(info.activityInfo.packageName)) { 8148 targetReceiver = info.activityInfo; 8149 break; 8150 } 8151 } 8152 8153 if (targetReceiver == null) { 8154 return null; 8155 } 8156 8157 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8158 } 8159 8160 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8161 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8162 if (pkgInfo.verifiers.length == 0) { 8163 return null; 8164 } 8165 8166 final int N = pkgInfo.verifiers.length; 8167 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8168 for (int i = 0; i < N; i++) { 8169 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8170 8171 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8172 receivers); 8173 if (comp == null) { 8174 continue; 8175 } 8176 8177 final int verifierUid = getUidForVerifier(verifierInfo); 8178 if (verifierUid == -1) { 8179 continue; 8180 } 8181 8182 if (DEBUG_VERIFY) { 8183 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8184 + " with the correct signature"); 8185 } 8186 sufficientVerifiers.add(comp); 8187 verificationState.addSufficientVerifier(verifierUid); 8188 } 8189 8190 return sufficientVerifiers; 8191 } 8192 8193 private int getUidForVerifier(VerifierInfo verifierInfo) { 8194 synchronized (mPackages) { 8195 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8196 if (pkg == null) { 8197 return -1; 8198 } else if (pkg.mSignatures.length != 1) { 8199 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8200 + " has more than one signature; ignoring"); 8201 return -1; 8202 } 8203 8204 /* 8205 * If the public key of the package's signature does not match 8206 * our expected public key, then this is a different package and 8207 * we should skip. 8208 */ 8209 8210 final byte[] expectedPublicKey; 8211 try { 8212 final Signature verifierSig = pkg.mSignatures[0]; 8213 final PublicKey publicKey = verifierSig.getPublicKey(); 8214 expectedPublicKey = publicKey.getEncoded(); 8215 } catch (CertificateException e) { 8216 return -1; 8217 } 8218 8219 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8220 8221 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8222 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8223 + " does not have the expected public key; ignoring"); 8224 return -1; 8225 } 8226 8227 return pkg.applicationInfo.uid; 8228 } 8229 } 8230 8231 @Override 8232 public void finishPackageInstall(int token) { 8233 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8234 8235 if (DEBUG_INSTALL) { 8236 Slog.v(TAG, "BM finishing package install for " + token); 8237 } 8238 8239 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8240 mHandler.sendMessage(msg); 8241 } 8242 8243 /** 8244 * Get the verification agent timeout. 8245 * 8246 * @return verification timeout in milliseconds 8247 */ 8248 private long getVerificationTimeout() { 8249 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8250 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8251 DEFAULT_VERIFICATION_TIMEOUT); 8252 } 8253 8254 /** 8255 * Get the default verification agent response code. 8256 * 8257 * @return default verification response code 8258 */ 8259 private int getDefaultVerificationResponse() { 8260 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8261 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8262 DEFAULT_VERIFICATION_RESPONSE); 8263 } 8264 8265 /** 8266 * Check whether or not package verification has been enabled. 8267 * 8268 * @return true if verification should be performed 8269 */ 8270 private boolean isVerificationEnabled(int userId, int installFlags) { 8271 if (!DEFAULT_VERIFY_ENABLE) { 8272 return false; 8273 } 8274 8275 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8276 8277 // Check if installing from ADB 8278 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8279 // Do not run verification in a test harness environment 8280 if (ActivityManager.isRunningInTestHarness()) { 8281 return false; 8282 } 8283 if (ensureVerifyAppsEnabled) { 8284 return true; 8285 } 8286 // Check if the developer does not want package verification for ADB installs 8287 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8288 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8289 return false; 8290 } 8291 } 8292 8293 if (ensureVerifyAppsEnabled) { 8294 return true; 8295 } 8296 8297 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8298 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8299 } 8300 8301 /** 8302 * Get the "allow unknown sources" setting. 8303 * 8304 * @return the current "allow unknown sources" setting 8305 */ 8306 private int getUnknownSourcesSettings() { 8307 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8308 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8309 -1); 8310 } 8311 8312 @Override 8313 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8314 final int uid = Binder.getCallingUid(); 8315 // writer 8316 synchronized (mPackages) { 8317 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8318 if (targetPackageSetting == null) { 8319 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8320 } 8321 8322 PackageSetting installerPackageSetting; 8323 if (installerPackageName != null) { 8324 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8325 if (installerPackageSetting == null) { 8326 throw new IllegalArgumentException("Unknown installer package: " 8327 + installerPackageName); 8328 } 8329 } else { 8330 installerPackageSetting = null; 8331 } 8332 8333 Signature[] callerSignature; 8334 Object obj = mSettings.getUserIdLPr(uid); 8335 if (obj != null) { 8336 if (obj instanceof SharedUserSetting) { 8337 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8338 } else if (obj instanceof PackageSetting) { 8339 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8340 } else { 8341 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8342 } 8343 } else { 8344 throw new SecurityException("Unknown calling uid " + uid); 8345 } 8346 8347 // Verify: can't set installerPackageName to a package that is 8348 // not signed with the same cert as the caller. 8349 if (installerPackageSetting != null) { 8350 if (compareSignatures(callerSignature, 8351 installerPackageSetting.signatures.mSignatures) 8352 != PackageManager.SIGNATURE_MATCH) { 8353 throw new SecurityException( 8354 "Caller does not have same cert as new installer package " 8355 + installerPackageName); 8356 } 8357 } 8358 8359 // Verify: if target already has an installer package, it must 8360 // be signed with the same cert as the caller. 8361 if (targetPackageSetting.installerPackageName != null) { 8362 PackageSetting setting = mSettings.mPackages.get( 8363 targetPackageSetting.installerPackageName); 8364 // If the currently set package isn't valid, then it's always 8365 // okay to change it. 8366 if (setting != null) { 8367 if (compareSignatures(callerSignature, 8368 setting.signatures.mSignatures) 8369 != PackageManager.SIGNATURE_MATCH) { 8370 throw new SecurityException( 8371 "Caller does not have same cert as old installer package " 8372 + targetPackageSetting.installerPackageName); 8373 } 8374 } 8375 } 8376 8377 // Okay! 8378 targetPackageSetting.installerPackageName = installerPackageName; 8379 scheduleWriteSettingsLocked(); 8380 } 8381 } 8382 8383 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8384 // Queue up an async operation since the package installation may take a little while. 8385 mHandler.post(new Runnable() { 8386 public void run() { 8387 mHandler.removeCallbacks(this); 8388 // Result object to be returned 8389 PackageInstalledInfo res = new PackageInstalledInfo(); 8390 res.returnCode = currentStatus; 8391 res.uid = -1; 8392 res.pkg = null; 8393 res.removedInfo = new PackageRemovedInfo(); 8394 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8395 args.doPreInstall(res.returnCode); 8396 synchronized (mInstallLock) { 8397 installPackageLI(args, res); 8398 } 8399 args.doPostInstall(res.returnCode, res.uid); 8400 } 8401 8402 // A restore should be performed at this point if (a) the install 8403 // succeeded, (b) the operation is not an update, and (c) the new 8404 // package has not opted out of backup participation. 8405 final boolean update = res.removedInfo.removedPackage != null; 8406 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8407 boolean doRestore = !update 8408 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8409 8410 // Set up the post-install work request bookkeeping. This will be used 8411 // and cleaned up by the post-install event handling regardless of whether 8412 // there's a restore pass performed. Token values are >= 1. 8413 int token; 8414 if (mNextInstallToken < 0) mNextInstallToken = 1; 8415 token = mNextInstallToken++; 8416 8417 PostInstallData data = new PostInstallData(args, res); 8418 mRunningInstalls.put(token, data); 8419 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8420 8421 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8422 // Pass responsibility to the Backup Manager. It will perform a 8423 // restore if appropriate, then pass responsibility back to the 8424 // Package Manager to run the post-install observer callbacks 8425 // and broadcasts. 8426 IBackupManager bm = IBackupManager.Stub.asInterface( 8427 ServiceManager.getService(Context.BACKUP_SERVICE)); 8428 if (bm != null) { 8429 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8430 + " to BM for possible restore"); 8431 try { 8432 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 8433 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8434 } else { 8435 doRestore = false; 8436 } 8437 } catch (RemoteException e) { 8438 // can't happen; the backup manager is local 8439 } catch (Exception e) { 8440 Slog.e(TAG, "Exception trying to enqueue restore", e); 8441 doRestore = false; 8442 } 8443 } else { 8444 Slog.e(TAG, "Backup Manager not found!"); 8445 doRestore = false; 8446 } 8447 } 8448 8449 if (!doRestore) { 8450 // No restore possible, or the Backup Manager was mysteriously not 8451 // available -- just fire the post-install work request directly. 8452 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8453 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8454 mHandler.sendMessage(msg); 8455 } 8456 } 8457 }); 8458 } 8459 8460 private abstract class HandlerParams { 8461 private static final int MAX_RETRIES = 4; 8462 8463 /** 8464 * Number of times startCopy() has been attempted and had a non-fatal 8465 * error. 8466 */ 8467 private int mRetries = 0; 8468 8469 /** User handle for the user requesting the information or installation. */ 8470 private final UserHandle mUser; 8471 8472 HandlerParams(UserHandle user) { 8473 mUser = user; 8474 } 8475 8476 UserHandle getUser() { 8477 return mUser; 8478 } 8479 8480 final boolean startCopy() { 8481 boolean res; 8482 try { 8483 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8484 8485 if (++mRetries > MAX_RETRIES) { 8486 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8487 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8488 handleServiceError(); 8489 return false; 8490 } else { 8491 handleStartCopy(); 8492 res = true; 8493 } 8494 } catch (RemoteException e) { 8495 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8496 mHandler.sendEmptyMessage(MCS_RECONNECT); 8497 res = false; 8498 } 8499 handleReturnCode(); 8500 return res; 8501 } 8502 8503 final void serviceError() { 8504 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8505 handleServiceError(); 8506 handleReturnCode(); 8507 } 8508 8509 abstract void handleStartCopy() throws RemoteException; 8510 abstract void handleServiceError(); 8511 abstract void handleReturnCode(); 8512 } 8513 8514 class MeasureParams extends HandlerParams { 8515 private final PackageStats mStats; 8516 private boolean mSuccess; 8517 8518 private final IPackageStatsObserver mObserver; 8519 8520 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8521 super(new UserHandle(stats.userHandle)); 8522 mObserver = observer; 8523 mStats = stats; 8524 } 8525 8526 @Override 8527 public String toString() { 8528 return "MeasureParams{" 8529 + Integer.toHexString(System.identityHashCode(this)) 8530 + " " + mStats.packageName + "}"; 8531 } 8532 8533 @Override 8534 void handleStartCopy() throws RemoteException { 8535 synchronized (mInstallLock) { 8536 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8537 } 8538 8539 if (mSuccess) { 8540 final boolean mounted; 8541 if (Environment.isExternalStorageEmulated()) { 8542 mounted = true; 8543 } else { 8544 final String status = Environment.getExternalStorageState(); 8545 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8546 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8547 } 8548 8549 if (mounted) { 8550 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8551 8552 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8553 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8554 8555 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8556 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8557 8558 // Always subtract cache size, since it's a subdirectory 8559 mStats.externalDataSize -= mStats.externalCacheSize; 8560 8561 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8562 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8563 8564 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8565 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8566 } 8567 } 8568 } 8569 8570 @Override 8571 void handleReturnCode() { 8572 if (mObserver != null) { 8573 try { 8574 mObserver.onGetStatsCompleted(mStats, mSuccess); 8575 } catch (RemoteException e) { 8576 Slog.i(TAG, "Observer no longer exists."); 8577 } 8578 } 8579 } 8580 8581 @Override 8582 void handleServiceError() { 8583 Slog.e(TAG, "Could not measure application " + mStats.packageName 8584 + " external storage"); 8585 } 8586 } 8587 8588 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8589 throws RemoteException { 8590 long result = 0; 8591 for (File path : paths) { 8592 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8593 } 8594 return result; 8595 } 8596 8597 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8598 for (File path : paths) { 8599 try { 8600 mcs.clearDirectory(path.getAbsolutePath()); 8601 } catch (RemoteException e) { 8602 } 8603 } 8604 } 8605 8606 static class OriginInfo { 8607 /** 8608 * Location where install is coming from, before it has been 8609 * copied/renamed into place. This could be a single monolithic APK 8610 * file, or a cluster directory. This location may be untrusted. 8611 */ 8612 final File file; 8613 final String cid; 8614 8615 /** 8616 * Flag indicating that {@link #file} or {@link #cid} has already been 8617 * staged, meaning downstream users don't need to defensively copy the 8618 * contents. 8619 */ 8620 final boolean staged; 8621 8622 /** 8623 * Flag indicating that {@link #file} or {@link #cid} is an already 8624 * installed app that is being moved. 8625 */ 8626 final boolean existing; 8627 8628 final String resolvedPath; 8629 final File resolvedFile; 8630 8631 static OriginInfo fromNothing() { 8632 return new OriginInfo(null, null, false, false); 8633 } 8634 8635 static OriginInfo fromUntrustedFile(File file) { 8636 return new OriginInfo(file, null, false, false); 8637 } 8638 8639 static OriginInfo fromExistingFile(File file) { 8640 return new OriginInfo(file, null, false, true); 8641 } 8642 8643 static OriginInfo fromStagedFile(File file) { 8644 return new OriginInfo(file, null, true, false); 8645 } 8646 8647 static OriginInfo fromStagedContainer(String cid) { 8648 return new OriginInfo(null, cid, true, false); 8649 } 8650 8651 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8652 this.file = file; 8653 this.cid = cid; 8654 this.staged = staged; 8655 this.existing = existing; 8656 8657 if (cid != null) { 8658 resolvedPath = PackageHelper.getSdDir(cid); 8659 resolvedFile = new File(resolvedPath); 8660 } else if (file != null) { 8661 resolvedPath = file.getAbsolutePath(); 8662 resolvedFile = file; 8663 } else { 8664 resolvedPath = null; 8665 resolvedFile = null; 8666 } 8667 } 8668 } 8669 8670 class InstallParams extends HandlerParams { 8671 final OriginInfo origin; 8672 final IPackageInstallObserver2 observer; 8673 int installFlags; 8674 final String installerPackageName; 8675 final VerificationParams verificationParams; 8676 private InstallArgs mArgs; 8677 private int mRet; 8678 final String packageAbiOverride; 8679 8680 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8681 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8682 String packageAbiOverride) { 8683 super(user); 8684 this.origin = origin; 8685 this.observer = observer; 8686 this.installFlags = installFlags; 8687 this.installerPackageName = installerPackageName; 8688 this.verificationParams = verificationParams; 8689 this.packageAbiOverride = packageAbiOverride; 8690 } 8691 8692 @Override 8693 public String toString() { 8694 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8695 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8696 } 8697 8698 public ManifestDigest getManifestDigest() { 8699 if (verificationParams == null) { 8700 return null; 8701 } 8702 return verificationParams.getManifestDigest(); 8703 } 8704 8705 private int installLocationPolicy(PackageInfoLite pkgLite) { 8706 String packageName = pkgLite.packageName; 8707 int installLocation = pkgLite.installLocation; 8708 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8709 // reader 8710 synchronized (mPackages) { 8711 PackageParser.Package pkg = mPackages.get(packageName); 8712 if (pkg != null) { 8713 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8714 // Check for downgrading. 8715 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8716 try { 8717 checkDowngrade(pkg, pkgLite); 8718 } catch (PackageManagerException e) { 8719 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 8720 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8721 } 8722 } 8723 // Check for updated system application. 8724 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8725 if (onSd) { 8726 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8727 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8728 } 8729 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8730 } else { 8731 if (onSd) { 8732 // Install flag overrides everything. 8733 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8734 } 8735 // If current upgrade specifies particular preference 8736 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8737 // Application explicitly specified internal. 8738 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8739 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8740 // App explictly prefers external. Let policy decide 8741 } else { 8742 // Prefer previous location 8743 if (isExternal(pkg)) { 8744 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8745 } 8746 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8747 } 8748 } 8749 } else { 8750 // Invalid install. Return error code 8751 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8752 } 8753 } 8754 } 8755 // All the special cases have been taken care of. 8756 // Return result based on recommended install location. 8757 if (onSd) { 8758 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8759 } 8760 return pkgLite.recommendedInstallLocation; 8761 } 8762 8763 /* 8764 * Invoke remote method to get package information and install 8765 * location values. Override install location based on default 8766 * policy if needed and then create install arguments based 8767 * on the install location. 8768 */ 8769 public void handleStartCopy() throws RemoteException { 8770 int ret = PackageManager.INSTALL_SUCCEEDED; 8771 8772 // If we're already staged, we've firmly committed to an install location 8773 if (origin.staged) { 8774 if (origin.file != null) { 8775 installFlags |= PackageManager.INSTALL_INTERNAL; 8776 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8777 } else if (origin.cid != null) { 8778 installFlags |= PackageManager.INSTALL_EXTERNAL; 8779 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8780 } else { 8781 throw new IllegalStateException("Invalid stage location"); 8782 } 8783 } 8784 8785 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8786 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8787 8788 PackageInfoLite pkgLite = null; 8789 8790 if (onInt && onSd) { 8791 // Check if both bits are set. 8792 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8793 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8794 } else { 8795 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8796 packageAbiOverride); 8797 8798 /* 8799 * If we have too little free space, try to free cache 8800 * before giving up. 8801 */ 8802 if (!origin.staged && pkgLite.recommendedInstallLocation 8803 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8804 // TODO: focus freeing disk space on the target device 8805 final StorageManager storage = StorageManager.from(mContext); 8806 final long lowThreshold = storage.getStorageLowBytes( 8807 Environment.getDataDirectory()); 8808 8809 final long sizeBytes = mContainerService.calculateInstalledSize( 8810 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8811 8812 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8813 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8814 installFlags, packageAbiOverride); 8815 } 8816 8817 /* 8818 * The cache free must have deleted the file we 8819 * downloaded to install. 8820 * 8821 * TODO: fix the "freeCache" call to not delete 8822 * the file we care about. 8823 */ 8824 if (pkgLite.recommendedInstallLocation 8825 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8826 pkgLite.recommendedInstallLocation 8827 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8828 } 8829 } 8830 } 8831 8832 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8833 int loc = pkgLite.recommendedInstallLocation; 8834 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8835 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8836 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8837 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8838 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8839 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8840 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8841 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8842 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8843 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8844 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8845 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8846 } else { 8847 // Override with defaults if needed. 8848 loc = installLocationPolicy(pkgLite); 8849 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8850 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8851 } else if (!onSd && !onInt) { 8852 // Override install location with flags 8853 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8854 // Set the flag to install on external media. 8855 installFlags |= PackageManager.INSTALL_EXTERNAL; 8856 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8857 } else { 8858 // Make sure the flag for installing on external 8859 // media is unset 8860 installFlags |= PackageManager.INSTALL_INTERNAL; 8861 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8862 } 8863 } 8864 } 8865 } 8866 8867 final InstallArgs args = createInstallArgs(this); 8868 mArgs = args; 8869 8870 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8871 /* 8872 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8873 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8874 */ 8875 int userIdentifier = getUser().getIdentifier(); 8876 if (userIdentifier == UserHandle.USER_ALL 8877 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8878 userIdentifier = UserHandle.USER_OWNER; 8879 } 8880 8881 /* 8882 * Determine if we have any installed package verifiers. If we 8883 * do, then we'll defer to them to verify the packages. 8884 */ 8885 final int requiredUid = mRequiredVerifierPackage == null ? -1 8886 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8887 if (!origin.existing && requiredUid != -1 8888 && isVerificationEnabled(userIdentifier, installFlags)) { 8889 final Intent verification = new Intent( 8890 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8891 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 8892 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8893 PACKAGE_MIME_TYPE); 8894 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8895 8896 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8897 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8898 0 /* TODO: Which userId? */); 8899 8900 if (DEBUG_VERIFY) { 8901 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8902 + verification.toString() + " with " + pkgLite.verifiers.length 8903 + " optional verifiers"); 8904 } 8905 8906 final int verificationId = mPendingVerificationToken++; 8907 8908 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8909 8910 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8911 installerPackageName); 8912 8913 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8914 installFlags); 8915 8916 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8917 pkgLite.packageName); 8918 8919 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8920 pkgLite.versionCode); 8921 8922 if (verificationParams != null) { 8923 if (verificationParams.getVerificationURI() != null) { 8924 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8925 verificationParams.getVerificationURI()); 8926 } 8927 if (verificationParams.getOriginatingURI() != null) { 8928 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8929 verificationParams.getOriginatingURI()); 8930 } 8931 if (verificationParams.getReferrer() != null) { 8932 verification.putExtra(Intent.EXTRA_REFERRER, 8933 verificationParams.getReferrer()); 8934 } 8935 if (verificationParams.getOriginatingUid() >= 0) { 8936 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8937 verificationParams.getOriginatingUid()); 8938 } 8939 if (verificationParams.getInstallerUid() >= 0) { 8940 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8941 verificationParams.getInstallerUid()); 8942 } 8943 } 8944 8945 final PackageVerificationState verificationState = new PackageVerificationState( 8946 requiredUid, args); 8947 8948 mPendingVerification.append(verificationId, verificationState); 8949 8950 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8951 receivers, verificationState); 8952 8953 /* 8954 * If any sufficient verifiers were listed in the package 8955 * manifest, attempt to ask them. 8956 */ 8957 if (sufficientVerifiers != null) { 8958 final int N = sufficientVerifiers.size(); 8959 if (N == 0) { 8960 Slog.i(TAG, "Additional verifiers required, but none installed."); 8961 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8962 } else { 8963 for (int i = 0; i < N; i++) { 8964 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8965 8966 final Intent sufficientIntent = new Intent(verification); 8967 sufficientIntent.setComponent(verifierComponent); 8968 8969 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8970 } 8971 } 8972 } 8973 8974 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8975 mRequiredVerifierPackage, receivers); 8976 if (ret == PackageManager.INSTALL_SUCCEEDED 8977 && mRequiredVerifierPackage != null) { 8978 /* 8979 * Send the intent to the required verification agent, 8980 * but only start the verification timeout after the 8981 * target BroadcastReceivers have run. 8982 */ 8983 verification.setComponent(requiredVerifierComponent); 8984 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8985 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8986 new BroadcastReceiver() { 8987 @Override 8988 public void onReceive(Context context, Intent intent) { 8989 final Message msg = mHandler 8990 .obtainMessage(CHECK_PENDING_VERIFICATION); 8991 msg.arg1 = verificationId; 8992 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8993 } 8994 }, null, 0, null, null); 8995 8996 /* 8997 * We don't want the copy to proceed until verification 8998 * succeeds, so null out this field. 8999 */ 9000 mArgs = null; 9001 } 9002 } else { 9003 /* 9004 * No package verification is enabled, so immediately start 9005 * the remote call to initiate copy using temporary file. 9006 */ 9007 ret = args.copyApk(mContainerService, true); 9008 } 9009 } 9010 9011 mRet = ret; 9012 } 9013 9014 @Override 9015 void handleReturnCode() { 9016 // If mArgs is null, then MCS couldn't be reached. When it 9017 // reconnects, it will try again to install. At that point, this 9018 // will succeed. 9019 if (mArgs != null) { 9020 processPendingInstall(mArgs, mRet); 9021 } 9022 } 9023 9024 @Override 9025 void handleServiceError() { 9026 mArgs = createInstallArgs(this); 9027 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9028 } 9029 9030 public boolean isForwardLocked() { 9031 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9032 } 9033 } 9034 9035 /** 9036 * Used during creation of InstallArgs 9037 * 9038 * @param installFlags package installation flags 9039 * @return true if should be installed on external storage 9040 */ 9041 private static boolean installOnSd(int installFlags) { 9042 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9043 return false; 9044 } 9045 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9046 return true; 9047 } 9048 return false; 9049 } 9050 9051 /** 9052 * Used during creation of InstallArgs 9053 * 9054 * @param installFlags package installation flags 9055 * @return true if should be installed as forward locked 9056 */ 9057 private static boolean installForwardLocked(int installFlags) { 9058 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9059 } 9060 9061 private InstallArgs createInstallArgs(InstallParams params) { 9062 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9063 return new AsecInstallArgs(params); 9064 } else { 9065 return new FileInstallArgs(params); 9066 } 9067 } 9068 9069 /** 9070 * Create args that describe an existing installed package. Typically used 9071 * when cleaning up old installs, or used as a move source. 9072 */ 9073 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9074 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9075 final boolean isInAsec; 9076 if (installOnSd(installFlags)) { 9077 /* Apps on SD card are always in ASEC containers. */ 9078 isInAsec = true; 9079 } else if (installForwardLocked(installFlags) 9080 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9081 /* 9082 * Forward-locked apps are only in ASEC containers if they're the 9083 * new style 9084 */ 9085 isInAsec = true; 9086 } else { 9087 isInAsec = false; 9088 } 9089 9090 if (isInAsec) { 9091 return new AsecInstallArgs(codePath, instructionSets, 9092 installOnSd(installFlags), installForwardLocked(installFlags)); 9093 } else { 9094 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9095 instructionSets); 9096 } 9097 } 9098 9099 static abstract class InstallArgs { 9100 /** @see InstallParams#origin */ 9101 final OriginInfo origin; 9102 9103 final IPackageInstallObserver2 observer; 9104 // Always refers to PackageManager flags only 9105 final int installFlags; 9106 final String installerPackageName; 9107 final ManifestDigest manifestDigest; 9108 final UserHandle user; 9109 final String abiOverride; 9110 9111 // The list of instruction sets supported by this app. This is currently 9112 // only used during the rmdex() phase to clean up resources. We can get rid of this 9113 // if we move dex files under the common app path. 9114 /* nullable */ String[] instructionSets; 9115 9116 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9117 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9118 String[] instructionSets, String abiOverride) { 9119 this.origin = origin; 9120 this.installFlags = installFlags; 9121 this.observer = observer; 9122 this.installerPackageName = installerPackageName; 9123 this.manifestDigest = manifestDigest; 9124 this.user = user; 9125 this.instructionSets = instructionSets; 9126 this.abiOverride = abiOverride; 9127 } 9128 9129 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9130 abstract int doPreInstall(int status); 9131 9132 /** 9133 * Rename package into final resting place. All paths on the given 9134 * scanned package should be updated to reflect the rename. 9135 */ 9136 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9137 abstract int doPostInstall(int status, int uid); 9138 9139 /** @see PackageSettingBase#codePathString */ 9140 abstract String getCodePath(); 9141 /** @see PackageSettingBase#resourcePathString */ 9142 abstract String getResourcePath(); 9143 abstract String getLegacyNativeLibraryPath(); 9144 9145 // Need installer lock especially for dex file removal. 9146 abstract void cleanUpResourcesLI(); 9147 abstract boolean doPostDeleteLI(boolean delete); 9148 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9149 9150 /** 9151 * Called before the source arguments are copied. This is used mostly 9152 * for MoveParams when it needs to read the source file to put it in the 9153 * destination. 9154 */ 9155 int doPreCopy() { 9156 return PackageManager.INSTALL_SUCCEEDED; 9157 } 9158 9159 /** 9160 * Called after the source arguments are copied. This is used mostly for 9161 * MoveParams when it needs to read the source file to put it in the 9162 * destination. 9163 * 9164 * @return 9165 */ 9166 int doPostCopy(int uid) { 9167 return PackageManager.INSTALL_SUCCEEDED; 9168 } 9169 9170 protected boolean isFwdLocked() { 9171 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9172 } 9173 9174 protected boolean isExternal() { 9175 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9176 } 9177 9178 UserHandle getUser() { 9179 return user; 9180 } 9181 } 9182 9183 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9184 if (!allCodePaths.isEmpty()) { 9185 if (instructionSets == null) { 9186 throw new IllegalStateException("instructionSet == null"); 9187 } 9188 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9189 for (String codePath : allCodePaths) { 9190 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9191 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9192 if (retCode < 0) { 9193 Slog.w(TAG, "Couldn't remove dex file for package: " 9194 + " at location " + codePath + ", retcode=" + retCode); 9195 // we don't consider this to be a failure of the core package deletion 9196 } 9197 } 9198 } 9199 } 9200 } 9201 9202 /** 9203 * Logic to handle installation of non-ASEC applications, including copying 9204 * and renaming logic. 9205 */ 9206 class FileInstallArgs extends InstallArgs { 9207 private File codeFile; 9208 private File resourceFile; 9209 private File legacyNativeLibraryPath; 9210 9211 // Example topology: 9212 // /data/app/com.example/base.apk 9213 // /data/app/com.example/split_foo.apk 9214 // /data/app/com.example/lib/arm/libfoo.so 9215 // /data/app/com.example/lib/arm64/libfoo.so 9216 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9217 9218 /** New install */ 9219 FileInstallArgs(InstallParams params) { 9220 super(params.origin, params.observer, params.installFlags, 9221 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9222 null /* instruction sets */, params.packageAbiOverride); 9223 if (isFwdLocked()) { 9224 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9225 } 9226 } 9227 9228 /** Existing install */ 9229 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9230 String[] instructionSets) { 9231 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9232 this.codeFile = (codePath != null) ? new File(codePath) : null; 9233 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9234 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9235 new File(legacyNativeLibraryPath) : null; 9236 } 9237 9238 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9239 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9240 isFwdLocked(), abiOverride); 9241 9242 final StorageManager storage = StorageManager.from(mContext); 9243 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9244 } 9245 9246 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9247 if (origin.staged) { 9248 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9249 codeFile = origin.file; 9250 resourceFile = origin.file; 9251 return PackageManager.INSTALL_SUCCEEDED; 9252 } 9253 9254 try { 9255 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9256 codeFile = tempDir; 9257 resourceFile = tempDir; 9258 } catch (IOException e) { 9259 Slog.w(TAG, "Failed to create copy file: " + e); 9260 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9261 } 9262 9263 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9264 @Override 9265 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9266 if (!FileUtils.isValidExtFilename(name)) { 9267 throw new IllegalArgumentException("Invalid filename: " + name); 9268 } 9269 try { 9270 final File file = new File(codeFile, name); 9271 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9272 O_RDWR | O_CREAT, 0644); 9273 Os.chmod(file.getAbsolutePath(), 0644); 9274 return new ParcelFileDescriptor(fd); 9275 } catch (ErrnoException e) { 9276 throw new RemoteException("Failed to open: " + e.getMessage()); 9277 } 9278 } 9279 }; 9280 9281 int ret = PackageManager.INSTALL_SUCCEEDED; 9282 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9283 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9284 Slog.e(TAG, "Failed to copy package"); 9285 return ret; 9286 } 9287 9288 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9289 NativeLibraryHelper.Handle handle = null; 9290 try { 9291 handle = NativeLibraryHelper.Handle.create(codeFile); 9292 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9293 abiOverride); 9294 } catch (IOException e) { 9295 Slog.e(TAG, "Copying native libraries failed", e); 9296 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9297 } finally { 9298 IoUtils.closeQuietly(handle); 9299 } 9300 9301 return ret; 9302 } 9303 9304 int doPreInstall(int status) { 9305 if (status != PackageManager.INSTALL_SUCCEEDED) { 9306 cleanUp(); 9307 } 9308 return status; 9309 } 9310 9311 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9312 if (status != PackageManager.INSTALL_SUCCEEDED) { 9313 cleanUp(); 9314 return false; 9315 } else { 9316 final File beforeCodeFile = codeFile; 9317 final File afterCodeFile = getNextCodePath(pkg.packageName); 9318 9319 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9320 try { 9321 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9322 } catch (ErrnoException e) { 9323 Slog.d(TAG, "Failed to rename", e); 9324 return false; 9325 } 9326 9327 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9328 Slog.d(TAG, "Failed to restorecon"); 9329 return false; 9330 } 9331 9332 // Reflect the rename internally 9333 codeFile = afterCodeFile; 9334 resourceFile = afterCodeFile; 9335 9336 // Reflect the rename in scanned details 9337 pkg.codePath = afterCodeFile.getAbsolutePath(); 9338 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9339 pkg.baseCodePath); 9340 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9341 pkg.splitCodePaths); 9342 9343 // Reflect the rename in app info 9344 pkg.applicationInfo.setCodePath(pkg.codePath); 9345 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9346 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9347 pkg.applicationInfo.setResourcePath(pkg.codePath); 9348 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9349 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9350 9351 return true; 9352 } 9353 } 9354 9355 int doPostInstall(int status, int uid) { 9356 if (status != PackageManager.INSTALL_SUCCEEDED) { 9357 cleanUp(); 9358 } 9359 return status; 9360 } 9361 9362 @Override 9363 String getCodePath() { 9364 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9365 } 9366 9367 @Override 9368 String getResourcePath() { 9369 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9370 } 9371 9372 @Override 9373 String getLegacyNativeLibraryPath() { 9374 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9375 } 9376 9377 private boolean cleanUp() { 9378 if (codeFile == null || !codeFile.exists()) { 9379 return false; 9380 } 9381 9382 if (codeFile.isDirectory()) { 9383 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 9384 } else { 9385 codeFile.delete(); 9386 } 9387 9388 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9389 resourceFile.delete(); 9390 } 9391 9392 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9393 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9394 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9395 } 9396 legacyNativeLibraryPath.delete(); 9397 } 9398 9399 return true; 9400 } 9401 9402 void cleanUpResourcesLI() { 9403 // Try enumerating all code paths before deleting 9404 List<String> allCodePaths = Collections.EMPTY_LIST; 9405 if (codeFile != null && codeFile.exists()) { 9406 try { 9407 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9408 allCodePaths = pkg.getAllCodePaths(); 9409 } catch (PackageParserException e) { 9410 // Ignored; we tried our best 9411 } 9412 } 9413 9414 cleanUp(); 9415 removeDexFiles(allCodePaths, instructionSets); 9416 } 9417 9418 boolean doPostDeleteLI(boolean delete) { 9419 // XXX err, shouldn't we respect the delete flag? 9420 cleanUpResourcesLI(); 9421 return true; 9422 } 9423 } 9424 9425 private boolean isAsecExternal(String cid) { 9426 final String asecPath = PackageHelper.getSdFilesystem(cid); 9427 return !asecPath.startsWith(mAsecInternalPath); 9428 } 9429 9430 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9431 PackageManagerException { 9432 if (copyRet < 0) { 9433 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9434 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9435 throw new PackageManagerException(copyRet, message); 9436 } 9437 } 9438 } 9439 9440 /** 9441 * Extract the MountService "container ID" from the full code path of an 9442 * .apk. 9443 */ 9444 static String cidFromCodePath(String fullCodePath) { 9445 int eidx = fullCodePath.lastIndexOf("/"); 9446 String subStr1 = fullCodePath.substring(0, eidx); 9447 int sidx = subStr1.lastIndexOf("/"); 9448 return subStr1.substring(sidx+1, eidx); 9449 } 9450 9451 /** 9452 * Logic to handle installation of ASEC applications, including copying and 9453 * renaming logic. 9454 */ 9455 class AsecInstallArgs extends InstallArgs { 9456 static final String RES_FILE_NAME = "pkg.apk"; 9457 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9458 9459 String cid; 9460 String packagePath; 9461 String resourcePath; 9462 String legacyNativeLibraryDir; 9463 9464 /** New install */ 9465 AsecInstallArgs(InstallParams params) { 9466 super(params.origin, params.observer, params.installFlags, 9467 params.installerPackageName, params.getManifestDigest(), 9468 params.getUser(), null /* instruction sets */, 9469 params.packageAbiOverride); 9470 } 9471 9472 /** Existing install */ 9473 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9474 boolean isExternal, boolean isForwardLocked) { 9475 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9476 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9477 instructionSets, null); 9478 // Hackily pretend we're still looking at a full code path 9479 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9480 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9481 } 9482 9483 // Extract cid from fullCodePath 9484 int eidx = fullCodePath.lastIndexOf("/"); 9485 String subStr1 = fullCodePath.substring(0, eidx); 9486 int sidx = subStr1.lastIndexOf("/"); 9487 cid = subStr1.substring(sidx+1, eidx); 9488 setMountPath(subStr1); 9489 } 9490 9491 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9492 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9493 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9494 instructionSets, null); 9495 this.cid = cid; 9496 setMountPath(PackageHelper.getSdDir(cid)); 9497 } 9498 9499 void createCopyFile() { 9500 cid = mInstallerService.allocateExternalStageCidLegacy(); 9501 } 9502 9503 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9504 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9505 abiOverride); 9506 9507 final File target; 9508 if (isExternal()) { 9509 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9510 } else { 9511 target = Environment.getDataDirectory(); 9512 } 9513 9514 final StorageManager storage = StorageManager.from(mContext); 9515 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9516 } 9517 9518 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9519 if (origin.staged) { 9520 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9521 cid = origin.cid; 9522 setMountPath(PackageHelper.getSdDir(cid)); 9523 return PackageManager.INSTALL_SUCCEEDED; 9524 } 9525 9526 if (temp) { 9527 createCopyFile(); 9528 } else { 9529 /* 9530 * Pre-emptively destroy the container since it's destroyed if 9531 * copying fails due to it existing anyway. 9532 */ 9533 PackageHelper.destroySdDir(cid); 9534 } 9535 9536 final String newMountPath = imcs.copyPackageToContainer( 9537 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9538 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9539 9540 if (newMountPath != null) { 9541 setMountPath(newMountPath); 9542 return PackageManager.INSTALL_SUCCEEDED; 9543 } else { 9544 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9545 } 9546 } 9547 9548 @Override 9549 String getCodePath() { 9550 return packagePath; 9551 } 9552 9553 @Override 9554 String getResourcePath() { 9555 return resourcePath; 9556 } 9557 9558 @Override 9559 String getLegacyNativeLibraryPath() { 9560 return legacyNativeLibraryDir; 9561 } 9562 9563 int doPreInstall(int status) { 9564 if (status != PackageManager.INSTALL_SUCCEEDED) { 9565 // Destroy container 9566 PackageHelper.destroySdDir(cid); 9567 } else { 9568 boolean mounted = PackageHelper.isContainerMounted(cid); 9569 if (!mounted) { 9570 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9571 Process.SYSTEM_UID); 9572 if (newMountPath != null) { 9573 setMountPath(newMountPath); 9574 } else { 9575 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9576 } 9577 } 9578 } 9579 return status; 9580 } 9581 9582 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9583 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9584 String newMountPath = null; 9585 if (PackageHelper.isContainerMounted(cid)) { 9586 // Unmount the container 9587 if (!PackageHelper.unMountSdDir(cid)) { 9588 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9589 return false; 9590 } 9591 } 9592 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9593 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9594 " which might be stale. Will try to clean up."); 9595 // Clean up the stale container and proceed to recreate. 9596 if (!PackageHelper.destroySdDir(newCacheId)) { 9597 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9598 return false; 9599 } 9600 // Successfully cleaned up stale container. Try to rename again. 9601 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9602 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9603 + " inspite of cleaning it up."); 9604 return false; 9605 } 9606 } 9607 if (!PackageHelper.isContainerMounted(newCacheId)) { 9608 Slog.w(TAG, "Mounting container " + newCacheId); 9609 newMountPath = PackageHelper.mountSdDir(newCacheId, 9610 getEncryptKey(), Process.SYSTEM_UID); 9611 } else { 9612 newMountPath = PackageHelper.getSdDir(newCacheId); 9613 } 9614 if (newMountPath == null) { 9615 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9616 return false; 9617 } 9618 Log.i(TAG, "Succesfully renamed " + cid + 9619 " to " + newCacheId + 9620 " at new path: " + newMountPath); 9621 cid = newCacheId; 9622 9623 final File beforeCodeFile = new File(packagePath); 9624 setMountPath(newMountPath); 9625 final File afterCodeFile = new File(packagePath); 9626 9627 // Reflect the rename in scanned details 9628 pkg.codePath = afterCodeFile.getAbsolutePath(); 9629 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9630 pkg.baseCodePath); 9631 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9632 pkg.splitCodePaths); 9633 9634 // Reflect the rename in app info 9635 pkg.applicationInfo.setCodePath(pkg.codePath); 9636 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9637 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9638 pkg.applicationInfo.setResourcePath(pkg.codePath); 9639 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9640 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9641 9642 return true; 9643 } 9644 9645 private void setMountPath(String mountPath) { 9646 final File mountFile = new File(mountPath); 9647 9648 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9649 if (monolithicFile.exists()) { 9650 packagePath = monolithicFile.getAbsolutePath(); 9651 if (isFwdLocked()) { 9652 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9653 } else { 9654 resourcePath = packagePath; 9655 } 9656 } else { 9657 packagePath = mountFile.getAbsolutePath(); 9658 resourcePath = packagePath; 9659 } 9660 9661 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9662 } 9663 9664 int doPostInstall(int status, int uid) { 9665 if (status != PackageManager.INSTALL_SUCCEEDED) { 9666 cleanUp(); 9667 } else { 9668 final int groupOwner; 9669 final String protectedFile; 9670 if (isFwdLocked()) { 9671 groupOwner = UserHandle.getSharedAppGid(uid); 9672 protectedFile = RES_FILE_NAME; 9673 } else { 9674 groupOwner = -1; 9675 protectedFile = null; 9676 } 9677 9678 if (uid < Process.FIRST_APPLICATION_UID 9679 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9680 Slog.e(TAG, "Failed to finalize " + cid); 9681 PackageHelper.destroySdDir(cid); 9682 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9683 } 9684 9685 boolean mounted = PackageHelper.isContainerMounted(cid); 9686 if (!mounted) { 9687 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9688 } 9689 } 9690 return status; 9691 } 9692 9693 private void cleanUp() { 9694 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9695 9696 // Destroy secure container 9697 PackageHelper.destroySdDir(cid); 9698 } 9699 9700 private List<String> getAllCodePaths() { 9701 final File codeFile = new File(getCodePath()); 9702 if (codeFile != null && codeFile.exists()) { 9703 try { 9704 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9705 return pkg.getAllCodePaths(); 9706 } catch (PackageParserException e) { 9707 // Ignored; we tried our best 9708 } 9709 } 9710 return Collections.EMPTY_LIST; 9711 } 9712 9713 void cleanUpResourcesLI() { 9714 // Enumerate all code paths before deleting 9715 cleanUpResourcesLI(getAllCodePaths()); 9716 } 9717 9718 private void cleanUpResourcesLI(List<String> allCodePaths) { 9719 cleanUp(); 9720 removeDexFiles(allCodePaths, instructionSets); 9721 } 9722 9723 9724 9725 String getPackageName() { 9726 return getAsecPackageName(cid); 9727 } 9728 9729 boolean doPostDeleteLI(boolean delete) { 9730 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9731 final List<String> allCodePaths = getAllCodePaths(); 9732 boolean mounted = PackageHelper.isContainerMounted(cid); 9733 if (mounted) { 9734 // Unmount first 9735 if (PackageHelper.unMountSdDir(cid)) { 9736 mounted = false; 9737 } 9738 } 9739 if (!mounted && delete) { 9740 cleanUpResourcesLI(allCodePaths); 9741 } 9742 return !mounted; 9743 } 9744 9745 @Override 9746 int doPreCopy() { 9747 if (isFwdLocked()) { 9748 if (!PackageHelper.fixSdPermissions(cid, 9749 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9750 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9751 } 9752 } 9753 9754 return PackageManager.INSTALL_SUCCEEDED; 9755 } 9756 9757 @Override 9758 int doPostCopy(int uid) { 9759 if (isFwdLocked()) { 9760 if (uid < Process.FIRST_APPLICATION_UID 9761 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9762 RES_FILE_NAME)) { 9763 Slog.e(TAG, "Failed to finalize " + cid); 9764 PackageHelper.destroySdDir(cid); 9765 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9766 } 9767 } 9768 9769 return PackageManager.INSTALL_SUCCEEDED; 9770 } 9771 } 9772 9773 static String getAsecPackageName(String packageCid) { 9774 int idx = packageCid.lastIndexOf("-"); 9775 if (idx == -1) { 9776 return packageCid; 9777 } 9778 return packageCid.substring(0, idx); 9779 } 9780 9781 // Utility method used to create code paths based on package name and available index. 9782 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9783 String idxStr = ""; 9784 int idx = 1; 9785 // Fall back to default value of idx=1 if prefix is not 9786 // part of oldCodePath 9787 if (oldCodePath != null) { 9788 String subStr = oldCodePath; 9789 // Drop the suffix right away 9790 if (suffix != null && subStr.endsWith(suffix)) { 9791 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9792 } 9793 // If oldCodePath already contains prefix find out the 9794 // ending index to either increment or decrement. 9795 int sidx = subStr.lastIndexOf(prefix); 9796 if (sidx != -1) { 9797 subStr = subStr.substring(sidx + prefix.length()); 9798 if (subStr != null) { 9799 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9800 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9801 } 9802 try { 9803 idx = Integer.parseInt(subStr); 9804 if (idx <= 1) { 9805 idx++; 9806 } else { 9807 idx--; 9808 } 9809 } catch(NumberFormatException e) { 9810 } 9811 } 9812 } 9813 } 9814 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9815 return prefix + idxStr; 9816 } 9817 9818 private File getNextCodePath(String packageName) { 9819 int suffix = 1; 9820 File result; 9821 do { 9822 result = new File(mAppInstallDir, packageName + "-" + suffix); 9823 suffix++; 9824 } while (result.exists()); 9825 return result; 9826 } 9827 9828 // Utility method that returns the relative package path with respect 9829 // to the installation directory. Like say for /data/data/com.test-1.apk 9830 // string com.test-1 is returned. 9831 static String deriveCodePathName(String codePath) { 9832 if (codePath == null) { 9833 return null; 9834 } 9835 final File codeFile = new File(codePath); 9836 final String name = codeFile.getName(); 9837 if (codeFile.isDirectory()) { 9838 return name; 9839 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9840 final int lastDot = name.lastIndexOf('.'); 9841 return name.substring(0, lastDot); 9842 } else { 9843 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9844 return null; 9845 } 9846 } 9847 9848 class PackageInstalledInfo { 9849 String name; 9850 int uid; 9851 // The set of users that originally had this package installed. 9852 int[] origUsers; 9853 // The set of users that now have this package installed. 9854 int[] newUsers; 9855 PackageParser.Package pkg; 9856 int returnCode; 9857 String returnMsg; 9858 PackageRemovedInfo removedInfo; 9859 9860 public void setError(int code, String msg) { 9861 returnCode = code; 9862 returnMsg = msg; 9863 Slog.w(TAG, msg); 9864 } 9865 9866 public void setError(String msg, PackageParserException e) { 9867 returnCode = e.error; 9868 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9869 Slog.w(TAG, msg, e); 9870 } 9871 9872 public void setError(String msg, PackageManagerException e) { 9873 returnCode = e.error; 9874 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9875 Slog.w(TAG, msg, e); 9876 } 9877 9878 // In some error cases we want to convey more info back to the observer 9879 String origPackage; 9880 String origPermission; 9881 } 9882 9883 /* 9884 * Install a non-existing package. 9885 */ 9886 private void installNewPackageLI(PackageParser.Package pkg, 9887 int parseFlags, int scanFlags, UserHandle user, 9888 String installerPackageName, PackageInstalledInfo res) { 9889 // Remember this for later, in case we need to rollback this install 9890 String pkgName = pkg.packageName; 9891 9892 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9893 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9894 synchronized(mPackages) { 9895 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9896 // A package with the same name is already installed, though 9897 // it has been renamed to an older name. The package we 9898 // are trying to install should be installed as an update to 9899 // the existing one, but that has not been requested, so bail. 9900 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9901 + " without first uninstalling package running as " 9902 + mSettings.mRenamedPackages.get(pkgName)); 9903 return; 9904 } 9905 if (mPackages.containsKey(pkgName)) { 9906 // Don't allow installation over an existing package with the same name. 9907 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9908 + " without first uninstalling."); 9909 return; 9910 } 9911 } 9912 9913 try { 9914 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9915 System.currentTimeMillis(), user); 9916 9917 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9918 // delete the partially installed application. the data directory will have to be 9919 // restored if it was already existing 9920 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9921 // remove package from internal structures. Note that we want deletePackageX to 9922 // delete the package data and cache directories that it created in 9923 // scanPackageLocked, unless those directories existed before we even tried to 9924 // install. 9925 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9926 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9927 res.removedInfo, true); 9928 } 9929 9930 } catch (PackageManagerException e) { 9931 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9932 } 9933 } 9934 9935 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9936 // Upgrade keysets are being used. Determine if new package has a superset of the 9937 // required keys. 9938 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9939 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9940 for (int i = 0; i < upgradeKeySets.length; i++) { 9941 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9942 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9943 return true; 9944 } 9945 } 9946 return false; 9947 } 9948 9949 private void replacePackageLI(PackageParser.Package pkg, 9950 int parseFlags, int scanFlags, UserHandle user, 9951 String installerPackageName, PackageInstalledInfo res) { 9952 PackageParser.Package oldPackage; 9953 String pkgName = pkg.packageName; 9954 int[] allUsers; 9955 boolean[] perUserInstalled; 9956 9957 // First find the old package info and check signatures 9958 synchronized(mPackages) { 9959 oldPackage = mPackages.get(pkgName); 9960 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9961 PackageSetting ps = mSettings.mPackages.get(pkgName); 9962 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9963 // default to original signature matching 9964 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9965 != PackageManager.SIGNATURE_MATCH) { 9966 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9967 "New package has a different signature: " + pkgName); 9968 return; 9969 } 9970 } else { 9971 if(!checkUpgradeKeySetLP(ps, pkg)) { 9972 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9973 "New package not signed by keys specified by upgrade-keysets: " 9974 + pkgName); 9975 return; 9976 } 9977 } 9978 9979 // In case of rollback, remember per-user/profile install state 9980 allUsers = sUserManager.getUserIds(); 9981 perUserInstalled = new boolean[allUsers.length]; 9982 for (int i = 0; i < allUsers.length; i++) { 9983 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9984 } 9985 } 9986 9987 boolean sysPkg = (isSystemApp(oldPackage)); 9988 if (sysPkg) { 9989 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9990 user, allUsers, perUserInstalled, installerPackageName, res); 9991 } else { 9992 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9993 user, allUsers, perUserInstalled, installerPackageName, res); 9994 } 9995 } 9996 9997 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9998 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9999 int[] allUsers, boolean[] perUserInstalled, 10000 String installerPackageName, PackageInstalledInfo res) { 10001 String pkgName = deletedPackage.packageName; 10002 boolean deletedPkg = true; 10003 boolean updatedSettings = false; 10004 10005 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10006 + deletedPackage); 10007 long origUpdateTime; 10008 if (pkg.mExtras != null) { 10009 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10010 } else { 10011 origUpdateTime = 0; 10012 } 10013 10014 // First delete the existing package while retaining the data directory 10015 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10016 res.removedInfo, true)) { 10017 // If the existing package wasn't successfully deleted 10018 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10019 deletedPkg = false; 10020 } else { 10021 // Successfully deleted the old package; proceed with replace. 10022 10023 // If deleted package lived in a container, give users a chance to 10024 // relinquish resources before killing. 10025 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10026 if (DEBUG_INSTALL) { 10027 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10028 } 10029 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10030 final ArrayList<String> pkgList = new ArrayList<String>(1); 10031 pkgList.add(deletedPackage.applicationInfo.packageName); 10032 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10033 } 10034 10035 deleteCodeCacheDirsLI(pkgName); 10036 try { 10037 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10038 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10039 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10040 updatedSettings = true; 10041 } catch (PackageManagerException e) { 10042 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10043 } 10044 } 10045 10046 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10047 // remove package from internal structures. Note that we want deletePackageX to 10048 // delete the package data and cache directories that it created in 10049 // scanPackageLocked, unless those directories existed before we even tried to 10050 // install. 10051 if(updatedSettings) { 10052 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10053 deletePackageLI( 10054 pkgName, null, true, allUsers, perUserInstalled, 10055 PackageManager.DELETE_KEEP_DATA, 10056 res.removedInfo, true); 10057 } 10058 // Since we failed to install the new package we need to restore the old 10059 // package that we deleted. 10060 if (deletedPkg) { 10061 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10062 File restoreFile = new File(deletedPackage.codePath); 10063 // Parse old package 10064 boolean oldOnSd = isExternal(deletedPackage); 10065 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10066 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10067 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10068 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10069 try { 10070 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10071 } catch (PackageManagerException e) { 10072 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10073 + e.getMessage()); 10074 return; 10075 } 10076 // Restore of old package succeeded. Update permissions. 10077 // writer 10078 synchronized (mPackages) { 10079 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10080 UPDATE_PERMISSIONS_ALL); 10081 // can downgrade to reader 10082 mSettings.writeLPr(); 10083 } 10084 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10085 } 10086 } 10087 } 10088 10089 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10090 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10091 int[] allUsers, boolean[] perUserInstalled, 10092 String installerPackageName, PackageInstalledInfo res) { 10093 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10094 + ", old=" + deletedPackage); 10095 boolean disabledSystem = false; 10096 boolean updatedSettings = false; 10097 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10098 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10099 != 0) { 10100 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10101 } 10102 String packageName = deletedPackage.packageName; 10103 if (packageName == null) { 10104 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10105 "Attempt to delete null packageName."); 10106 return; 10107 } 10108 PackageParser.Package oldPkg; 10109 PackageSetting oldPkgSetting; 10110 // reader 10111 synchronized (mPackages) { 10112 oldPkg = mPackages.get(packageName); 10113 oldPkgSetting = mSettings.mPackages.get(packageName); 10114 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10115 (oldPkgSetting == null)) { 10116 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10117 "Couldn't find package:" + packageName + " information"); 10118 return; 10119 } 10120 } 10121 10122 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10123 10124 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10125 res.removedInfo.removedPackage = packageName; 10126 // Remove existing system package 10127 removePackageLI(oldPkgSetting, true); 10128 // writer 10129 synchronized (mPackages) { 10130 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10131 if (!disabledSystem && deletedPackage != null) { 10132 // We didn't need to disable the .apk as a current system package, 10133 // which means we are replacing another update that is already 10134 // installed. We need to make sure to delete the older one's .apk. 10135 res.removedInfo.args = createInstallArgsForExisting(0, 10136 deletedPackage.applicationInfo.getCodePath(), 10137 deletedPackage.applicationInfo.getResourcePath(), 10138 deletedPackage.applicationInfo.nativeLibraryRootDir, 10139 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10140 } else { 10141 res.removedInfo.args = null; 10142 } 10143 } 10144 10145 // Successfully disabled the old package. Now proceed with re-installation 10146 deleteCodeCacheDirsLI(packageName); 10147 10148 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10149 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10150 10151 PackageParser.Package newPackage = null; 10152 try { 10153 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10154 if (newPackage.mExtras != null) { 10155 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10156 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10157 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10158 10159 // is the update attempting to change shared user? that isn't going to work... 10160 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10161 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10162 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10163 + " to " + newPkgSetting.sharedUser); 10164 updatedSettings = true; 10165 } 10166 } 10167 10168 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10169 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10170 updatedSettings = true; 10171 } 10172 10173 } catch (PackageManagerException e) { 10174 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10175 } 10176 10177 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10178 // Re installation failed. Restore old information 10179 // Remove new pkg information 10180 if (newPackage != null) { 10181 removeInstalledPackageLI(newPackage, true); 10182 } 10183 // Add back the old system package 10184 try { 10185 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10186 } catch (PackageManagerException e) { 10187 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10188 } 10189 // Restore the old system information in Settings 10190 synchronized (mPackages) { 10191 if (disabledSystem) { 10192 mSettings.enableSystemPackageLPw(packageName); 10193 } 10194 if (updatedSettings) { 10195 mSettings.setInstallerPackageName(packageName, 10196 oldPkgSetting.installerPackageName); 10197 } 10198 mSettings.writeLPr(); 10199 } 10200 } 10201 } 10202 10203 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10204 int[] allUsers, boolean[] perUserInstalled, 10205 PackageInstalledInfo res) { 10206 String pkgName = newPackage.packageName; 10207 synchronized (mPackages) { 10208 //write settings. the installStatus will be incomplete at this stage. 10209 //note that the new package setting would have already been 10210 //added to mPackages. It hasn't been persisted yet. 10211 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10212 mSettings.writeLPr(); 10213 } 10214 10215 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10216 10217 synchronized (mPackages) { 10218 updatePermissionsLPw(newPackage.packageName, newPackage, 10219 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10220 ? UPDATE_PERMISSIONS_ALL : 0)); 10221 // For system-bundled packages, we assume that installing an upgraded version 10222 // of the package implies that the user actually wants to run that new code, 10223 // so we enable the package. 10224 if (isSystemApp(newPackage)) { 10225 // NB: implicit assumption that system package upgrades apply to all users 10226 if (DEBUG_INSTALL) { 10227 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10228 } 10229 PackageSetting ps = mSettings.mPackages.get(pkgName); 10230 if (ps != null) { 10231 if (res.origUsers != null) { 10232 for (int userHandle : res.origUsers) { 10233 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10234 userHandle, installerPackageName); 10235 } 10236 } 10237 // Also convey the prior install/uninstall state 10238 if (allUsers != null && perUserInstalled != null) { 10239 for (int i = 0; i < allUsers.length; i++) { 10240 if (DEBUG_INSTALL) { 10241 Slog.d(TAG, " user " + allUsers[i] 10242 + " => " + perUserInstalled[i]); 10243 } 10244 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10245 } 10246 // these install state changes will be persisted in the 10247 // upcoming call to mSettings.writeLPr(). 10248 } 10249 } 10250 } 10251 res.name = pkgName; 10252 res.uid = newPackage.applicationInfo.uid; 10253 res.pkg = newPackage; 10254 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10255 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10256 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10257 //to update install status 10258 mSettings.writeLPr(); 10259 } 10260 } 10261 10262 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10263 final int installFlags = args.installFlags; 10264 String installerPackageName = args.installerPackageName; 10265 File tmpPackageFile = new File(args.getCodePath()); 10266 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10267 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10268 boolean replace = false; 10269 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10270 // Result object to be returned 10271 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10272 10273 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10274 // Retrieve PackageSettings and parse package 10275 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10276 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10277 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10278 PackageParser pp = new PackageParser(); 10279 pp.setSeparateProcesses(mSeparateProcesses); 10280 pp.setDisplayMetrics(mMetrics); 10281 10282 final PackageParser.Package pkg; 10283 try { 10284 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10285 } catch (PackageParserException e) { 10286 res.setError("Failed parse during installPackageLI", e); 10287 return; 10288 } 10289 10290 // Mark that we have an install time CPU ABI override. 10291 pkg.cpuAbiOverride = args.abiOverride; 10292 10293 String pkgName = res.name = pkg.packageName; 10294 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10295 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10296 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10297 return; 10298 } 10299 } 10300 10301 try { 10302 pp.collectCertificates(pkg, parseFlags); 10303 pp.collectManifestDigest(pkg); 10304 } catch (PackageParserException e) { 10305 res.setError("Failed collect during installPackageLI", e); 10306 return; 10307 } 10308 10309 /* If the installer passed in a manifest digest, compare it now. */ 10310 if (args.manifestDigest != null) { 10311 if (DEBUG_INSTALL) { 10312 final String parsedManifest = pkg.manifestDigest == null ? "null" 10313 : pkg.manifestDigest.toString(); 10314 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10315 + parsedManifest); 10316 } 10317 10318 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10319 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10320 return; 10321 } 10322 } else if (DEBUG_INSTALL) { 10323 final String parsedManifest = pkg.manifestDigest == null 10324 ? "null" : pkg.manifestDigest.toString(); 10325 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10326 } 10327 10328 // Get rid of all references to package scan path via parser. 10329 pp = null; 10330 String oldCodePath = null; 10331 boolean systemApp = false; 10332 synchronized (mPackages) { 10333 // Check if installing already existing package 10334 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10335 String oldName = mSettings.mRenamedPackages.get(pkgName); 10336 if (pkg.mOriginalPackages != null 10337 && pkg.mOriginalPackages.contains(oldName) 10338 && mPackages.containsKey(oldName)) { 10339 // This package is derived from an original package, 10340 // and this device has been updating from that original 10341 // name. We must continue using the original name, so 10342 // rename the new package here. 10343 pkg.setPackageName(oldName); 10344 pkgName = pkg.packageName; 10345 replace = true; 10346 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10347 + oldName + " pkgName=" + pkgName); 10348 } else if (mPackages.containsKey(pkgName)) { 10349 // This package, under its official name, already exists 10350 // on the device; we should replace it. 10351 replace = true; 10352 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10353 } 10354 } 10355 10356 PackageSetting ps = mSettings.mPackages.get(pkgName); 10357 if (ps != null) { 10358 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10359 10360 // Quick sanity check that we're signed correctly if updating; 10361 // we'll check this again later when scanning, but we want to 10362 // bail early here before tripping over redefined permissions. 10363 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10364 try { 10365 verifySignaturesLP(ps, pkg); 10366 } catch (PackageManagerException e) { 10367 res.setError(e.error, e.getMessage()); 10368 return; 10369 } 10370 } else { 10371 if (!checkUpgradeKeySetLP(ps, pkg)) { 10372 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 10373 + pkg.packageName + " upgrade keys do not match the " 10374 + "previously installed version"); 10375 return; 10376 } 10377 } 10378 10379 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10380 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10381 systemApp = (ps.pkg.applicationInfo.flags & 10382 ApplicationInfo.FLAG_SYSTEM) != 0; 10383 } 10384 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10385 } 10386 10387 // Check whether the newly-scanned package wants to define an already-defined perm 10388 int N = pkg.permissions.size(); 10389 for (int i = N-1; i >= 0; i--) { 10390 PackageParser.Permission perm = pkg.permissions.get(i); 10391 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10392 if (bp != null) { 10393 // If the defining package is signed with our cert, it's okay. This 10394 // also includes the "updating the same package" case, of course. 10395 // "updating same package" could also involve key-rotation. 10396 final boolean sigsOk; 10397 if (!bp.sourcePackage.equals(pkg.packageName) 10398 || !(bp.packageSetting instanceof PackageSetting) 10399 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10400 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10401 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10402 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10403 } else { 10404 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10405 } 10406 if (!sigsOk) { 10407 // If the owning package is the system itself, we log but allow 10408 // install to proceed; we fail the install on all other permission 10409 // redefinitions. 10410 if (!bp.sourcePackage.equals("android")) { 10411 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10412 + pkg.packageName + " attempting to redeclare permission " 10413 + perm.info.name + " already owned by " + bp.sourcePackage); 10414 res.origPermission = perm.info.name; 10415 res.origPackage = bp.sourcePackage; 10416 return; 10417 } else { 10418 Slog.w(TAG, "Package " + pkg.packageName 10419 + " attempting to redeclare system permission " 10420 + perm.info.name + "; ignoring new declaration"); 10421 pkg.permissions.remove(i); 10422 } 10423 } 10424 } 10425 } 10426 10427 } 10428 10429 if (systemApp && onSd) { 10430 // Disable updates to system apps on sdcard 10431 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10432 "Cannot install updates to system apps on sdcard"); 10433 return; 10434 } 10435 10436 // Run dexopt before old package gets removed, to minimize time when app is not available 10437 int result = mPackageDexOptimizer 10438 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 10439 false /* defer */, false /* inclDependencies */); 10440 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 10441 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 10442 return; 10443 } 10444 10445 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10446 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10447 return; 10448 } 10449 10450 if (replace) { 10451 // Call replacePackageLI with SCAN_NO_DEX, since we already made dexopt 10452 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING | SCAN_NO_DEX, args.user, 10453 installerPackageName, res); 10454 } else { 10455 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10456 args.user, installerPackageName, res); 10457 } 10458 synchronized (mPackages) { 10459 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10460 if (ps != null) { 10461 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10462 } 10463 } 10464 } 10465 10466 private static boolean isMultiArch(PackageSetting ps) { 10467 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10468 } 10469 10470 private static boolean isMultiArch(ApplicationInfo info) { 10471 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10472 } 10473 10474 private static boolean isExternal(PackageParser.Package pkg) { 10475 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10476 } 10477 10478 private static boolean isExternal(PackageSetting ps) { 10479 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10480 } 10481 10482 private static boolean isExternal(ApplicationInfo info) { 10483 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10484 } 10485 10486 private static boolean isSystemApp(PackageParser.Package pkg) { 10487 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10488 } 10489 10490 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10491 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 10492 } 10493 10494 private static boolean isSystemApp(PackageSetting ps) { 10495 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10496 } 10497 10498 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10499 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10500 } 10501 10502 private int packageFlagsToInstallFlags(PackageSetting ps) { 10503 int installFlags = 0; 10504 if (isExternal(ps)) { 10505 installFlags |= PackageManager.INSTALL_EXTERNAL; 10506 } 10507 if (ps.isForwardLocked()) { 10508 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10509 } 10510 return installFlags; 10511 } 10512 10513 private void deleteTempPackageFiles() { 10514 final FilenameFilter filter = new FilenameFilter() { 10515 public boolean accept(File dir, String name) { 10516 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10517 } 10518 }; 10519 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10520 file.delete(); 10521 } 10522 } 10523 10524 @Override 10525 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10526 int flags) { 10527 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10528 flags); 10529 } 10530 10531 @Override 10532 public void deletePackage(final String packageName, 10533 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10534 mContext.enforceCallingOrSelfPermission( 10535 android.Manifest.permission.DELETE_PACKAGES, null); 10536 final int uid = Binder.getCallingUid(); 10537 if (UserHandle.getUserId(uid) != userId) { 10538 mContext.enforceCallingPermission( 10539 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10540 "deletePackage for user " + userId); 10541 } 10542 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10543 try { 10544 observer.onPackageDeleted(packageName, 10545 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10546 } catch (RemoteException re) { 10547 } 10548 return; 10549 } 10550 10551 boolean uninstallBlocked = false; 10552 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10553 int[] users = sUserManager.getUserIds(); 10554 for (int i = 0; i < users.length; ++i) { 10555 if (getBlockUninstallForUser(packageName, users[i])) { 10556 uninstallBlocked = true; 10557 break; 10558 } 10559 } 10560 } else { 10561 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10562 } 10563 if (uninstallBlocked) { 10564 try { 10565 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10566 null); 10567 } catch (RemoteException re) { 10568 } 10569 return; 10570 } 10571 10572 if (DEBUG_REMOVE) { 10573 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10574 } 10575 // Queue up an async operation since the package deletion may take a little while. 10576 mHandler.post(new Runnable() { 10577 public void run() { 10578 mHandler.removeCallbacks(this); 10579 final int returnCode = deletePackageX(packageName, userId, flags); 10580 if (observer != null) { 10581 try { 10582 observer.onPackageDeleted(packageName, returnCode, null); 10583 } catch (RemoteException e) { 10584 Log.i(TAG, "Observer no longer exists."); 10585 } //end catch 10586 } //end if 10587 } //end run 10588 }); 10589 } 10590 10591 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10592 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10593 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10594 try { 10595 if (dpm != null) { 10596 if (dpm.isDeviceOwner(packageName)) { 10597 return true; 10598 } 10599 int[] users; 10600 if (userId == UserHandle.USER_ALL) { 10601 users = sUserManager.getUserIds(); 10602 } else { 10603 users = new int[]{userId}; 10604 } 10605 for (int i = 0; i < users.length; ++i) { 10606 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10607 return true; 10608 } 10609 } 10610 } 10611 } catch (RemoteException e) { 10612 } 10613 return false; 10614 } 10615 10616 /** 10617 * This method is an internal method that could be get invoked either 10618 * to delete an installed package or to clean up a failed installation. 10619 * After deleting an installed package, a broadcast is sent to notify any 10620 * listeners that the package has been installed. For cleaning up a failed 10621 * installation, the broadcast is not necessary since the package's 10622 * installation wouldn't have sent the initial broadcast either 10623 * The key steps in deleting a package are 10624 * deleting the package information in internal structures like mPackages, 10625 * deleting the packages base directories through installd 10626 * updating mSettings to reflect current status 10627 * persisting settings for later use 10628 * sending a broadcast if necessary 10629 */ 10630 private int deletePackageX(String packageName, int userId, int flags) { 10631 final PackageRemovedInfo info = new PackageRemovedInfo(); 10632 final boolean res; 10633 10634 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10635 ? UserHandle.ALL : new UserHandle(userId); 10636 10637 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10638 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10639 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10640 } 10641 10642 boolean removedForAllUsers = false; 10643 boolean systemUpdate = false; 10644 10645 // for the uninstall-updates case and restricted profiles, remember the per- 10646 // userhandle installed state 10647 int[] allUsers; 10648 boolean[] perUserInstalled; 10649 synchronized (mPackages) { 10650 PackageSetting ps = mSettings.mPackages.get(packageName); 10651 allUsers = sUserManager.getUserIds(); 10652 perUserInstalled = new boolean[allUsers.length]; 10653 for (int i = 0; i < allUsers.length; i++) { 10654 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10655 } 10656 } 10657 10658 synchronized (mInstallLock) { 10659 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10660 res = deletePackageLI(packageName, removeForUser, 10661 true, allUsers, perUserInstalled, 10662 flags | REMOVE_CHATTY, info, true); 10663 systemUpdate = info.isRemovedPackageSystemUpdate; 10664 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10665 removedForAllUsers = true; 10666 } 10667 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10668 + " removedForAllUsers=" + removedForAllUsers); 10669 } 10670 10671 if (res) { 10672 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10673 10674 // If the removed package was a system update, the old system package 10675 // was re-enabled; we need to broadcast this information 10676 if (systemUpdate) { 10677 Bundle extras = new Bundle(1); 10678 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10679 ? info.removedAppId : info.uid); 10680 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10681 10682 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10683 extras, null, null, null); 10684 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10685 extras, null, null, null); 10686 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10687 null, packageName, null, null); 10688 } 10689 } 10690 // Force a gc here. 10691 Runtime.getRuntime().gc(); 10692 // Delete the resources here after sending the broadcast to let 10693 // other processes clean up before deleting resources. 10694 if (info.args != null) { 10695 synchronized (mInstallLock) { 10696 info.args.doPostDeleteLI(true); 10697 } 10698 } 10699 10700 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10701 } 10702 10703 static class PackageRemovedInfo { 10704 String removedPackage; 10705 int uid = -1; 10706 int removedAppId = -1; 10707 int[] removedUsers = null; 10708 boolean isRemovedPackageSystemUpdate = false; 10709 // Clean up resources deleted packages. 10710 InstallArgs args = null; 10711 10712 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10713 Bundle extras = new Bundle(1); 10714 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10715 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10716 if (replacing) { 10717 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10718 } 10719 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10720 if (removedPackage != null) { 10721 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10722 extras, null, null, removedUsers); 10723 if (fullRemove && !replacing) { 10724 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10725 extras, null, null, removedUsers); 10726 } 10727 } 10728 if (removedAppId >= 0) { 10729 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10730 removedUsers); 10731 } 10732 } 10733 } 10734 10735 /* 10736 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10737 * flag is not set, the data directory is removed as well. 10738 * make sure this flag is set for partially installed apps. If not its meaningless to 10739 * delete a partially installed application. 10740 */ 10741 private void removePackageDataLI(PackageSetting ps, 10742 int[] allUserHandles, boolean[] perUserInstalled, 10743 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10744 String packageName = ps.name; 10745 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10746 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10747 // Retrieve object to delete permissions for shared user later on 10748 final PackageSetting deletedPs; 10749 // reader 10750 synchronized (mPackages) { 10751 deletedPs = mSettings.mPackages.get(packageName); 10752 if (outInfo != null) { 10753 outInfo.removedPackage = packageName; 10754 outInfo.removedUsers = deletedPs != null 10755 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10756 : null; 10757 } 10758 } 10759 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10760 removeDataDirsLI(packageName); 10761 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10762 } 10763 // writer 10764 synchronized (mPackages) { 10765 if (deletedPs != null) { 10766 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10767 if (outInfo != null) { 10768 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10769 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10770 } 10771 if (deletedPs != null) { 10772 updatePermissionsLPw(deletedPs.name, null, 0); 10773 if (deletedPs.sharedUser != null) { 10774 // remove permissions associated with package 10775 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10776 } 10777 } 10778 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10779 } 10780 // make sure to preserve per-user disabled state if this removal was just 10781 // a downgrade of a system app to the factory package 10782 if (allUserHandles != null && perUserInstalled != null) { 10783 if (DEBUG_REMOVE) { 10784 Slog.d(TAG, "Propagating install state across downgrade"); 10785 } 10786 for (int i = 0; i < allUserHandles.length; i++) { 10787 if (DEBUG_REMOVE) { 10788 Slog.d(TAG, " user " + allUserHandles[i] 10789 + " => " + perUserInstalled[i]); 10790 } 10791 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10792 } 10793 } 10794 } 10795 // can downgrade to reader 10796 if (writeSettings) { 10797 // Save settings now 10798 mSettings.writeLPr(); 10799 } 10800 } 10801 if (outInfo != null) { 10802 // A user ID was deleted here. Go through all users and remove it 10803 // from KeyStore. 10804 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10805 } 10806 } 10807 10808 static boolean locationIsPrivileged(File path) { 10809 try { 10810 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10811 .getCanonicalPath(); 10812 return path.getCanonicalPath().startsWith(privilegedAppDir); 10813 } catch (IOException e) { 10814 Slog.e(TAG, "Unable to access code path " + path); 10815 } 10816 return false; 10817 } 10818 10819 /* 10820 * Tries to delete system package. 10821 */ 10822 private boolean deleteSystemPackageLI(PackageSetting newPs, 10823 int[] allUserHandles, boolean[] perUserInstalled, 10824 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10825 final boolean applyUserRestrictions 10826 = (allUserHandles != null) && (perUserInstalled != null); 10827 PackageSetting disabledPs = null; 10828 // Confirm if the system package has been updated 10829 // An updated system app can be deleted. This will also have to restore 10830 // the system pkg from system partition 10831 // reader 10832 synchronized (mPackages) { 10833 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10834 } 10835 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10836 + " disabledPs=" + disabledPs); 10837 if (disabledPs == null) { 10838 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10839 return false; 10840 } else if (DEBUG_REMOVE) { 10841 Slog.d(TAG, "Deleting system pkg from data partition"); 10842 } 10843 if (DEBUG_REMOVE) { 10844 if (applyUserRestrictions) { 10845 Slog.d(TAG, "Remembering install states:"); 10846 for (int i = 0; i < allUserHandles.length; i++) { 10847 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10848 } 10849 } 10850 } 10851 // Delete the updated package 10852 outInfo.isRemovedPackageSystemUpdate = true; 10853 if (disabledPs.versionCode < newPs.versionCode) { 10854 // Delete data for downgrades 10855 flags &= ~PackageManager.DELETE_KEEP_DATA; 10856 } else { 10857 // Preserve data by setting flag 10858 flags |= PackageManager.DELETE_KEEP_DATA; 10859 } 10860 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10861 allUserHandles, perUserInstalled, outInfo, writeSettings); 10862 if (!ret) { 10863 return false; 10864 } 10865 // writer 10866 synchronized (mPackages) { 10867 // Reinstate the old system package 10868 mSettings.enableSystemPackageLPw(newPs.name); 10869 // Remove any native libraries from the upgraded package. 10870 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10871 } 10872 // Install the system package 10873 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10874 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10875 if (locationIsPrivileged(disabledPs.codePath)) { 10876 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10877 } 10878 10879 final PackageParser.Package newPkg; 10880 try { 10881 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10882 } catch (PackageManagerException e) { 10883 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10884 return false; 10885 } 10886 10887 // writer 10888 synchronized (mPackages) { 10889 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10890 updatePermissionsLPw(newPkg.packageName, newPkg, 10891 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10892 if (applyUserRestrictions) { 10893 if (DEBUG_REMOVE) { 10894 Slog.d(TAG, "Propagating install state across reinstall"); 10895 } 10896 for (int i = 0; i < allUserHandles.length; i++) { 10897 if (DEBUG_REMOVE) { 10898 Slog.d(TAG, " user " + allUserHandles[i] 10899 + " => " + perUserInstalled[i]); 10900 } 10901 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10902 } 10903 // Regardless of writeSettings we need to ensure that this restriction 10904 // state propagation is persisted 10905 mSettings.writeAllUsersPackageRestrictionsLPr(); 10906 } 10907 // can downgrade to reader here 10908 if (writeSettings) { 10909 mSettings.writeLPr(); 10910 } 10911 } 10912 return true; 10913 } 10914 10915 private boolean deleteInstalledPackageLI(PackageSetting ps, 10916 boolean deleteCodeAndResources, int flags, 10917 int[] allUserHandles, boolean[] perUserInstalled, 10918 PackageRemovedInfo outInfo, boolean writeSettings) { 10919 if (outInfo != null) { 10920 outInfo.uid = ps.appId; 10921 } 10922 10923 // Delete package data from internal structures and also remove data if flag is set 10924 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10925 10926 // Delete application code and resources 10927 if (deleteCodeAndResources && (outInfo != null)) { 10928 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10929 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10930 getAppDexInstructionSets(ps)); 10931 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10932 } 10933 return true; 10934 } 10935 10936 @Override 10937 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10938 int userId) { 10939 mContext.enforceCallingOrSelfPermission( 10940 android.Manifest.permission.DELETE_PACKAGES, null); 10941 synchronized (mPackages) { 10942 PackageSetting ps = mSettings.mPackages.get(packageName); 10943 if (ps == null) { 10944 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10945 return false; 10946 } 10947 if (!ps.getInstalled(userId)) { 10948 // Can't block uninstall for an app that is not installed or enabled. 10949 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10950 return false; 10951 } 10952 ps.setBlockUninstall(blockUninstall, userId); 10953 mSettings.writePackageRestrictionsLPr(userId); 10954 } 10955 return true; 10956 } 10957 10958 @Override 10959 public boolean getBlockUninstallForUser(String packageName, int userId) { 10960 synchronized (mPackages) { 10961 PackageSetting ps = mSettings.mPackages.get(packageName); 10962 if (ps == null) { 10963 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10964 return false; 10965 } 10966 return ps.getBlockUninstall(userId); 10967 } 10968 } 10969 10970 /* 10971 * This method handles package deletion in general 10972 */ 10973 private boolean deletePackageLI(String packageName, UserHandle user, 10974 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10975 int flags, PackageRemovedInfo outInfo, 10976 boolean writeSettings) { 10977 if (packageName == null) { 10978 Slog.w(TAG, "Attempt to delete null packageName."); 10979 return false; 10980 } 10981 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10982 PackageSetting ps; 10983 boolean dataOnly = false; 10984 int removeUser = -1; 10985 int appId = -1; 10986 synchronized (mPackages) { 10987 ps = mSettings.mPackages.get(packageName); 10988 if (ps == null) { 10989 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10990 return false; 10991 } 10992 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10993 && user.getIdentifier() != UserHandle.USER_ALL) { 10994 // The caller is asking that the package only be deleted for a single 10995 // user. To do this, we just mark its uninstalled state and delete 10996 // its data. If this is a system app, we only allow this to happen if 10997 // they have set the special DELETE_SYSTEM_APP which requests different 10998 // semantics than normal for uninstalling system apps. 10999 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11000 ps.setUserState(user.getIdentifier(), 11001 COMPONENT_ENABLED_STATE_DEFAULT, 11002 false, //installed 11003 true, //stopped 11004 true, //notLaunched 11005 false, //hidden 11006 null, null, null, 11007 false // blockUninstall 11008 ); 11009 if (!isSystemApp(ps)) { 11010 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11011 // Other user still have this package installed, so all 11012 // we need to do is clear this user's data and save that 11013 // it is uninstalled. 11014 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11015 removeUser = user.getIdentifier(); 11016 appId = ps.appId; 11017 mSettings.writePackageRestrictionsLPr(removeUser); 11018 } else { 11019 // We need to set it back to 'installed' so the uninstall 11020 // broadcasts will be sent correctly. 11021 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11022 ps.setInstalled(true, user.getIdentifier()); 11023 } 11024 } else { 11025 // This is a system app, so we assume that the 11026 // other users still have this package installed, so all 11027 // we need to do is clear this user's data and save that 11028 // it is uninstalled. 11029 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11030 removeUser = user.getIdentifier(); 11031 appId = ps.appId; 11032 mSettings.writePackageRestrictionsLPr(removeUser); 11033 } 11034 } 11035 } 11036 11037 if (removeUser >= 0) { 11038 // From above, we determined that we are deleting this only 11039 // for a single user. Continue the work here. 11040 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11041 if (outInfo != null) { 11042 outInfo.removedPackage = packageName; 11043 outInfo.removedAppId = appId; 11044 outInfo.removedUsers = new int[] {removeUser}; 11045 } 11046 mInstaller.clearUserData(packageName, removeUser); 11047 removeKeystoreDataIfNeeded(removeUser, appId); 11048 schedulePackageCleaning(packageName, removeUser, false); 11049 return true; 11050 } 11051 11052 if (dataOnly) { 11053 // Delete application data first 11054 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11055 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11056 return true; 11057 } 11058 11059 boolean ret = false; 11060 if (isSystemApp(ps)) { 11061 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11062 // When an updated system application is deleted we delete the existing resources as well and 11063 // fall back to existing code in system partition 11064 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11065 flags, outInfo, writeSettings); 11066 } else { 11067 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11068 // Kill application pre-emptively especially for apps on sd. 11069 killApplication(packageName, ps.appId, "uninstall pkg"); 11070 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11071 allUserHandles, perUserInstalled, 11072 outInfo, writeSettings); 11073 } 11074 11075 return ret; 11076 } 11077 11078 private final class ClearStorageConnection implements ServiceConnection { 11079 IMediaContainerService mContainerService; 11080 11081 @Override 11082 public void onServiceConnected(ComponentName name, IBinder service) { 11083 synchronized (this) { 11084 mContainerService = IMediaContainerService.Stub.asInterface(service); 11085 notifyAll(); 11086 } 11087 } 11088 11089 @Override 11090 public void onServiceDisconnected(ComponentName name) { 11091 } 11092 } 11093 11094 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11095 final boolean mounted; 11096 if (Environment.isExternalStorageEmulated()) { 11097 mounted = true; 11098 } else { 11099 final String status = Environment.getExternalStorageState(); 11100 11101 mounted = status.equals(Environment.MEDIA_MOUNTED) 11102 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11103 } 11104 11105 if (!mounted) { 11106 return; 11107 } 11108 11109 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11110 int[] users; 11111 if (userId == UserHandle.USER_ALL) { 11112 users = sUserManager.getUserIds(); 11113 } else { 11114 users = new int[] { userId }; 11115 } 11116 final ClearStorageConnection conn = new ClearStorageConnection(); 11117 if (mContext.bindServiceAsUser( 11118 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11119 try { 11120 for (int curUser : users) { 11121 long timeout = SystemClock.uptimeMillis() + 5000; 11122 synchronized (conn) { 11123 long now = SystemClock.uptimeMillis(); 11124 while (conn.mContainerService == null && now < timeout) { 11125 try { 11126 conn.wait(timeout - now); 11127 } catch (InterruptedException e) { 11128 } 11129 } 11130 } 11131 if (conn.mContainerService == null) { 11132 return; 11133 } 11134 11135 final UserEnvironment userEnv = new UserEnvironment(curUser); 11136 clearDirectory(conn.mContainerService, 11137 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11138 if (allData) { 11139 clearDirectory(conn.mContainerService, 11140 userEnv.buildExternalStorageAppDataDirs(packageName)); 11141 clearDirectory(conn.mContainerService, 11142 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11143 } 11144 } 11145 } finally { 11146 mContext.unbindService(conn); 11147 } 11148 } 11149 } 11150 11151 @Override 11152 public void clearApplicationUserData(final String packageName, 11153 final IPackageDataObserver observer, final int userId) { 11154 mContext.enforceCallingOrSelfPermission( 11155 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11156 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11157 // Queue up an async operation since the package deletion may take a little while. 11158 mHandler.post(new Runnable() { 11159 public void run() { 11160 mHandler.removeCallbacks(this); 11161 final boolean succeeded; 11162 synchronized (mInstallLock) { 11163 succeeded = clearApplicationUserDataLI(packageName, userId); 11164 } 11165 clearExternalStorageDataSync(packageName, userId, true); 11166 if (succeeded) { 11167 // invoke DeviceStorageMonitor's update method to clear any notifications 11168 DeviceStorageMonitorInternal 11169 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11170 if (dsm != null) { 11171 dsm.checkMemory(); 11172 } 11173 } 11174 if(observer != null) { 11175 try { 11176 observer.onRemoveCompleted(packageName, succeeded); 11177 } catch (RemoteException e) { 11178 Log.i(TAG, "Observer no longer exists."); 11179 } 11180 } //end if observer 11181 } //end run 11182 }); 11183 } 11184 11185 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11186 if (packageName == null) { 11187 Slog.w(TAG, "Attempt to delete null packageName."); 11188 return false; 11189 } 11190 11191 // Try finding details about the requested package 11192 PackageParser.Package pkg; 11193 synchronized (mPackages) { 11194 pkg = mPackages.get(packageName); 11195 if (pkg == null) { 11196 final PackageSetting ps = mSettings.mPackages.get(packageName); 11197 if (ps != null) { 11198 pkg = ps.pkg; 11199 } 11200 } 11201 } 11202 11203 if (pkg == null) { 11204 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11205 } 11206 11207 // Always delete data directories for package, even if we found no other 11208 // record of app. This helps users recover from UID mismatches without 11209 // resorting to a full data wipe. 11210 int retCode = mInstaller.clearUserData(packageName, userId); 11211 if (retCode < 0) { 11212 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11213 return false; 11214 } 11215 11216 if (pkg == null) { 11217 return false; 11218 } 11219 11220 if (pkg != null && pkg.applicationInfo != null) { 11221 final int appId = pkg.applicationInfo.uid; 11222 removeKeystoreDataIfNeeded(userId, appId); 11223 } 11224 11225 // Create a native library symlink only if we have native libraries 11226 // and if the native libraries are 32 bit libraries. We do not provide 11227 // this symlink for 64 bit libraries. 11228 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11229 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11230 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11231 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11232 Slog.w(TAG, "Failed linking native library dir"); 11233 return false; 11234 } 11235 } 11236 11237 return true; 11238 } 11239 11240 /** 11241 * Remove entries from the keystore daemon. Will only remove it if the 11242 * {@code appId} is valid. 11243 */ 11244 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11245 if (appId < 0) { 11246 return; 11247 } 11248 11249 final KeyStore keyStore = KeyStore.getInstance(); 11250 if (keyStore != null) { 11251 if (userId == UserHandle.USER_ALL) { 11252 for (final int individual : sUserManager.getUserIds()) { 11253 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11254 } 11255 } else { 11256 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11257 } 11258 } else { 11259 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11260 } 11261 } 11262 11263 @Override 11264 public void deleteApplicationCacheFiles(final String packageName, 11265 final IPackageDataObserver observer) { 11266 mContext.enforceCallingOrSelfPermission( 11267 android.Manifest.permission.DELETE_CACHE_FILES, null); 11268 // Queue up an async operation since the package deletion may take a little while. 11269 final int userId = UserHandle.getCallingUserId(); 11270 mHandler.post(new Runnable() { 11271 public void run() { 11272 mHandler.removeCallbacks(this); 11273 final boolean succeded; 11274 synchronized (mInstallLock) { 11275 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11276 } 11277 clearExternalStorageDataSync(packageName, userId, false); 11278 if(observer != null) { 11279 try { 11280 observer.onRemoveCompleted(packageName, succeded); 11281 } catch (RemoteException e) { 11282 Log.i(TAG, "Observer no longer exists."); 11283 } 11284 } //end if observer 11285 } //end run 11286 }); 11287 } 11288 11289 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11290 if (packageName == null) { 11291 Slog.w(TAG, "Attempt to delete null packageName."); 11292 return false; 11293 } 11294 PackageParser.Package p; 11295 synchronized (mPackages) { 11296 p = mPackages.get(packageName); 11297 } 11298 if (p == null) { 11299 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11300 return false; 11301 } 11302 final ApplicationInfo applicationInfo = p.applicationInfo; 11303 if (applicationInfo == null) { 11304 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11305 return false; 11306 } 11307 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11308 if (retCode < 0) { 11309 Slog.w(TAG, "Couldn't remove cache files for package: " 11310 + packageName + " u" + userId); 11311 return false; 11312 } 11313 return true; 11314 } 11315 11316 @Override 11317 public void getPackageSizeInfo(final String packageName, int userHandle, 11318 final IPackageStatsObserver observer) { 11319 mContext.enforceCallingOrSelfPermission( 11320 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11321 if (packageName == null) { 11322 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11323 } 11324 11325 PackageStats stats = new PackageStats(packageName, userHandle); 11326 11327 /* 11328 * Queue up an async operation since the package measurement may take a 11329 * little while. 11330 */ 11331 Message msg = mHandler.obtainMessage(INIT_COPY); 11332 msg.obj = new MeasureParams(stats, observer); 11333 mHandler.sendMessage(msg); 11334 } 11335 11336 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11337 PackageStats pStats) { 11338 if (packageName == null) { 11339 Slog.w(TAG, "Attempt to get size of null packageName."); 11340 return false; 11341 } 11342 PackageParser.Package p; 11343 boolean dataOnly = false; 11344 String libDirRoot = null; 11345 String asecPath = null; 11346 PackageSetting ps = null; 11347 synchronized (mPackages) { 11348 p = mPackages.get(packageName); 11349 ps = mSettings.mPackages.get(packageName); 11350 if(p == null) { 11351 dataOnly = true; 11352 if((ps == null) || (ps.pkg == null)) { 11353 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11354 return false; 11355 } 11356 p = ps.pkg; 11357 } 11358 if (ps != null) { 11359 libDirRoot = ps.legacyNativeLibraryPathString; 11360 } 11361 if (p != null && (isExternal(p) || p.isForwardLocked())) { 11362 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11363 if (secureContainerId != null) { 11364 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11365 } 11366 } 11367 } 11368 String publicSrcDir = null; 11369 if(!dataOnly) { 11370 final ApplicationInfo applicationInfo = p.applicationInfo; 11371 if (applicationInfo == null) { 11372 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11373 return false; 11374 } 11375 if (p.isForwardLocked()) { 11376 publicSrcDir = applicationInfo.getBaseResourcePath(); 11377 } 11378 } 11379 // TODO: extend to measure size of split APKs 11380 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11381 // not just the first level. 11382 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11383 // just the primary. 11384 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11385 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11386 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11387 if (res < 0) { 11388 return false; 11389 } 11390 11391 // Fix-up for forward-locked applications in ASEC containers. 11392 if (!isExternal(p)) { 11393 pStats.codeSize += pStats.externalCodeSize; 11394 pStats.externalCodeSize = 0L; 11395 } 11396 11397 return true; 11398 } 11399 11400 11401 @Override 11402 public void addPackageToPreferred(String packageName) { 11403 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11404 } 11405 11406 @Override 11407 public void removePackageFromPreferred(String packageName) { 11408 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11409 } 11410 11411 @Override 11412 public List<PackageInfo> getPreferredPackages(int flags) { 11413 return new ArrayList<PackageInfo>(); 11414 } 11415 11416 private int getUidTargetSdkVersionLockedLPr(int uid) { 11417 Object obj = mSettings.getUserIdLPr(uid); 11418 if (obj instanceof SharedUserSetting) { 11419 final SharedUserSetting sus = (SharedUserSetting) obj; 11420 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11421 final Iterator<PackageSetting> it = sus.packages.iterator(); 11422 while (it.hasNext()) { 11423 final PackageSetting ps = it.next(); 11424 if (ps.pkg != null) { 11425 int v = ps.pkg.applicationInfo.targetSdkVersion; 11426 if (v < vers) vers = v; 11427 } 11428 } 11429 return vers; 11430 } else if (obj instanceof PackageSetting) { 11431 final PackageSetting ps = (PackageSetting) obj; 11432 if (ps.pkg != null) { 11433 return ps.pkg.applicationInfo.targetSdkVersion; 11434 } 11435 } 11436 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11437 } 11438 11439 @Override 11440 public void addPreferredActivity(IntentFilter filter, int match, 11441 ComponentName[] set, ComponentName activity, int userId) { 11442 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11443 "Adding preferred"); 11444 } 11445 11446 private void addPreferredActivityInternal(IntentFilter filter, int match, 11447 ComponentName[] set, ComponentName activity, boolean always, int userId, 11448 String opname) { 11449 // writer 11450 int callingUid = Binder.getCallingUid(); 11451 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11452 if (filter.countActions() == 0) { 11453 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11454 return; 11455 } 11456 synchronized (mPackages) { 11457 if (mContext.checkCallingOrSelfPermission( 11458 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11459 != PackageManager.PERMISSION_GRANTED) { 11460 if (getUidTargetSdkVersionLockedLPr(callingUid) 11461 < Build.VERSION_CODES.FROYO) { 11462 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11463 + callingUid); 11464 return; 11465 } 11466 mContext.enforceCallingOrSelfPermission( 11467 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11468 } 11469 11470 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11471 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11472 + userId + ":"); 11473 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11474 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11475 scheduleWritePackageRestrictionsLocked(userId); 11476 } 11477 } 11478 11479 @Override 11480 public void replacePreferredActivity(IntentFilter filter, int match, 11481 ComponentName[] set, ComponentName activity, int userId) { 11482 if (filter.countActions() != 1) { 11483 throw new IllegalArgumentException( 11484 "replacePreferredActivity expects filter to have only 1 action."); 11485 } 11486 if (filter.countDataAuthorities() != 0 11487 || filter.countDataPaths() != 0 11488 || filter.countDataSchemes() > 1 11489 || filter.countDataTypes() != 0) { 11490 throw new IllegalArgumentException( 11491 "replacePreferredActivity expects filter to have no data authorities, " + 11492 "paths, or types; and at most one scheme."); 11493 } 11494 11495 final int callingUid = Binder.getCallingUid(); 11496 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11497 synchronized (mPackages) { 11498 if (mContext.checkCallingOrSelfPermission( 11499 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11500 != PackageManager.PERMISSION_GRANTED) { 11501 if (getUidTargetSdkVersionLockedLPr(callingUid) 11502 < Build.VERSION_CODES.FROYO) { 11503 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11504 + Binder.getCallingUid()); 11505 return; 11506 } 11507 mContext.enforceCallingOrSelfPermission( 11508 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11509 } 11510 11511 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11512 if (pir != null) { 11513 // Get all of the existing entries that exactly match this filter. 11514 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11515 if (existing != null && existing.size() == 1) { 11516 PreferredActivity cur = existing.get(0); 11517 if (DEBUG_PREFERRED) { 11518 Slog.i(TAG, "Checking replace of preferred:"); 11519 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11520 if (!cur.mPref.mAlways) { 11521 Slog.i(TAG, " -- CUR; not mAlways!"); 11522 } else { 11523 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11524 Slog.i(TAG, " -- CUR: mSet=" 11525 + Arrays.toString(cur.mPref.mSetComponents)); 11526 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11527 Slog.i(TAG, " -- NEW: mMatch=" 11528 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11529 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11530 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11531 } 11532 } 11533 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11534 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11535 && cur.mPref.sameSet(set)) { 11536 // Setting the preferred activity to what it happens to be already 11537 if (DEBUG_PREFERRED) { 11538 Slog.i(TAG, "Replacing with same preferred activity " 11539 + cur.mPref.mShortComponent + " for user " 11540 + userId + ":"); 11541 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11542 } 11543 return; 11544 } 11545 } 11546 11547 if (existing != null) { 11548 if (DEBUG_PREFERRED) { 11549 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11550 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11551 } 11552 for (int i = 0; i < existing.size(); i++) { 11553 PreferredActivity pa = existing.get(i); 11554 if (DEBUG_PREFERRED) { 11555 Slog.i(TAG, "Removing existing preferred activity " 11556 + pa.mPref.mComponent + ":"); 11557 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11558 } 11559 pir.removeFilter(pa); 11560 } 11561 } 11562 } 11563 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11564 "Replacing preferred"); 11565 } 11566 } 11567 11568 @Override 11569 public void clearPackagePreferredActivities(String packageName) { 11570 final int uid = Binder.getCallingUid(); 11571 // writer 11572 synchronized (mPackages) { 11573 PackageParser.Package pkg = mPackages.get(packageName); 11574 if (pkg == null || pkg.applicationInfo.uid != uid) { 11575 if (mContext.checkCallingOrSelfPermission( 11576 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11577 != PackageManager.PERMISSION_GRANTED) { 11578 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11579 < Build.VERSION_CODES.FROYO) { 11580 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11581 + Binder.getCallingUid()); 11582 return; 11583 } 11584 mContext.enforceCallingOrSelfPermission( 11585 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11586 } 11587 } 11588 11589 int user = UserHandle.getCallingUserId(); 11590 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11591 scheduleWritePackageRestrictionsLocked(user); 11592 } 11593 } 11594 } 11595 11596 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11597 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11598 ArrayList<PreferredActivity> removed = null; 11599 boolean changed = false; 11600 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11601 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11602 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11603 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11604 continue; 11605 } 11606 Iterator<PreferredActivity> it = pir.filterIterator(); 11607 while (it.hasNext()) { 11608 PreferredActivity pa = it.next(); 11609 // Mark entry for removal only if it matches the package name 11610 // and the entry is of type "always". 11611 if (packageName == null || 11612 (pa.mPref.mComponent.getPackageName().equals(packageName) 11613 && pa.mPref.mAlways)) { 11614 if (removed == null) { 11615 removed = new ArrayList<PreferredActivity>(); 11616 } 11617 removed.add(pa); 11618 } 11619 } 11620 if (removed != null) { 11621 for (int j=0; j<removed.size(); j++) { 11622 PreferredActivity pa = removed.get(j); 11623 pir.removeFilter(pa); 11624 } 11625 changed = true; 11626 } 11627 } 11628 return changed; 11629 } 11630 11631 @Override 11632 public void resetPreferredActivities(int userId) { 11633 /* TODO: Actually use userId. Why is it being passed in? */ 11634 mContext.enforceCallingOrSelfPermission( 11635 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11636 // writer 11637 synchronized (mPackages) { 11638 int user = UserHandle.getCallingUserId(); 11639 clearPackagePreferredActivitiesLPw(null, user); 11640 mSettings.readDefaultPreferredAppsLPw(this, user); 11641 scheduleWritePackageRestrictionsLocked(user); 11642 } 11643 } 11644 11645 @Override 11646 public int getPreferredActivities(List<IntentFilter> outFilters, 11647 List<ComponentName> outActivities, String packageName) { 11648 11649 int num = 0; 11650 final int userId = UserHandle.getCallingUserId(); 11651 // reader 11652 synchronized (mPackages) { 11653 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11654 if (pir != null) { 11655 final Iterator<PreferredActivity> it = pir.filterIterator(); 11656 while (it.hasNext()) { 11657 final PreferredActivity pa = it.next(); 11658 if (packageName == null 11659 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11660 && pa.mPref.mAlways)) { 11661 if (outFilters != null) { 11662 outFilters.add(new IntentFilter(pa)); 11663 } 11664 if (outActivities != null) { 11665 outActivities.add(pa.mPref.mComponent); 11666 } 11667 } 11668 } 11669 } 11670 } 11671 11672 return num; 11673 } 11674 11675 @Override 11676 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11677 int userId) { 11678 int callingUid = Binder.getCallingUid(); 11679 if (callingUid != Process.SYSTEM_UID) { 11680 throw new SecurityException( 11681 "addPersistentPreferredActivity can only be run by the system"); 11682 } 11683 if (filter.countActions() == 0) { 11684 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11685 return; 11686 } 11687 synchronized (mPackages) { 11688 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11689 " :"); 11690 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11691 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11692 new PersistentPreferredActivity(filter, activity)); 11693 scheduleWritePackageRestrictionsLocked(userId); 11694 } 11695 } 11696 11697 @Override 11698 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11699 int callingUid = Binder.getCallingUid(); 11700 if (callingUid != Process.SYSTEM_UID) { 11701 throw new SecurityException( 11702 "clearPackagePersistentPreferredActivities can only be run by the system"); 11703 } 11704 ArrayList<PersistentPreferredActivity> removed = null; 11705 boolean changed = false; 11706 synchronized (mPackages) { 11707 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11708 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11709 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11710 .valueAt(i); 11711 if (userId != thisUserId) { 11712 continue; 11713 } 11714 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11715 while (it.hasNext()) { 11716 PersistentPreferredActivity ppa = it.next(); 11717 // Mark entry for removal only if it matches the package name. 11718 if (ppa.mComponent.getPackageName().equals(packageName)) { 11719 if (removed == null) { 11720 removed = new ArrayList<PersistentPreferredActivity>(); 11721 } 11722 removed.add(ppa); 11723 } 11724 } 11725 if (removed != null) { 11726 for (int j=0; j<removed.size(); j++) { 11727 PersistentPreferredActivity ppa = removed.get(j); 11728 ppir.removeFilter(ppa); 11729 } 11730 changed = true; 11731 } 11732 } 11733 11734 if (changed) { 11735 scheduleWritePackageRestrictionsLocked(userId); 11736 } 11737 } 11738 } 11739 11740 @Override 11741 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11742 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11743 mContext.enforceCallingOrSelfPermission( 11744 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11745 int callingUid = Binder.getCallingUid(); 11746 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11747 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11748 if (intentFilter.countActions() == 0) { 11749 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11750 return; 11751 } 11752 synchronized (mPackages) { 11753 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 11754 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11755 CrossProfileIntentResolver resolver = 11756 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11757 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 11758 // We have all those whose filter is equal. Now checking if the rest is equal as well. 11759 if (existing != null) { 11760 int size = existing.size(); 11761 for (int i = 0; i < size; i++) { 11762 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 11763 return; 11764 } 11765 } 11766 } 11767 resolver.addFilter(newFilter); 11768 scheduleWritePackageRestrictionsLocked(sourceUserId); 11769 } 11770 } 11771 11772 @Override 11773 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11774 int ownerUserId) { 11775 mContext.enforceCallingOrSelfPermission( 11776 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11777 int callingUid = Binder.getCallingUid(); 11778 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11779 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11780 int callingUserId = UserHandle.getUserId(callingUid); 11781 synchronized (mPackages) { 11782 CrossProfileIntentResolver resolver = 11783 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11784 ArraySet<CrossProfileIntentFilter> set = 11785 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 11786 for (CrossProfileIntentFilter filter : set) { 11787 if (filter.getOwnerPackage().equals(ownerPackage) 11788 && filter.getOwnerUserId() == callingUserId) { 11789 resolver.removeFilter(filter); 11790 } 11791 } 11792 scheduleWritePackageRestrictionsLocked(sourceUserId); 11793 } 11794 } 11795 11796 // Enforcing that callingUid is owning pkg on userId 11797 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11798 // The system owns everything. 11799 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11800 return; 11801 } 11802 int callingUserId = UserHandle.getUserId(callingUid); 11803 if (callingUserId != userId) { 11804 throw new SecurityException("calling uid " + callingUid 11805 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11806 + callingUserId); 11807 } 11808 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11809 if (pi == null) { 11810 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11811 + callingUserId); 11812 } 11813 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11814 throw new SecurityException("Calling uid " + callingUid 11815 + " does not own package " + pkg); 11816 } 11817 } 11818 11819 @Override 11820 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11821 Intent intent = new Intent(Intent.ACTION_MAIN); 11822 intent.addCategory(Intent.CATEGORY_HOME); 11823 11824 final int callingUserId = UserHandle.getCallingUserId(); 11825 List<ResolveInfo> list = queryIntentActivities(intent, null, 11826 PackageManager.GET_META_DATA, callingUserId); 11827 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11828 true, false, false, callingUserId); 11829 11830 allHomeCandidates.clear(); 11831 if (list != null) { 11832 for (ResolveInfo ri : list) { 11833 allHomeCandidates.add(ri); 11834 } 11835 } 11836 return (preferred == null || preferred.activityInfo == null) 11837 ? null 11838 : new ComponentName(preferred.activityInfo.packageName, 11839 preferred.activityInfo.name); 11840 } 11841 11842 @Override 11843 public void setApplicationEnabledSetting(String appPackageName, 11844 int newState, int flags, int userId, String callingPackage) { 11845 if (!sUserManager.exists(userId)) return; 11846 if (callingPackage == null) { 11847 callingPackage = Integer.toString(Binder.getCallingUid()); 11848 } 11849 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11850 } 11851 11852 @Override 11853 public void setComponentEnabledSetting(ComponentName componentName, 11854 int newState, int flags, int userId) { 11855 if (!sUserManager.exists(userId)) return; 11856 setEnabledSetting(componentName.getPackageName(), 11857 componentName.getClassName(), newState, flags, userId, null); 11858 } 11859 11860 private void setEnabledSetting(final String packageName, String className, int newState, 11861 final int flags, int userId, String callingPackage) { 11862 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11863 || newState == COMPONENT_ENABLED_STATE_ENABLED 11864 || newState == COMPONENT_ENABLED_STATE_DISABLED 11865 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11866 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11867 throw new IllegalArgumentException("Invalid new component state: " 11868 + newState); 11869 } 11870 PackageSetting pkgSetting; 11871 final int uid = Binder.getCallingUid(); 11872 final int permission = mContext.checkCallingOrSelfPermission( 11873 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11874 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 11875 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11876 boolean sendNow = false; 11877 boolean isApp = (className == null); 11878 String componentName = isApp ? packageName : className; 11879 int packageUid = -1; 11880 ArrayList<String> components; 11881 11882 // writer 11883 synchronized (mPackages) { 11884 pkgSetting = mSettings.mPackages.get(packageName); 11885 if (pkgSetting == null) { 11886 if (className == null) { 11887 throw new IllegalArgumentException( 11888 "Unknown package: " + packageName); 11889 } 11890 throw new IllegalArgumentException( 11891 "Unknown component: " + packageName 11892 + "/" + className); 11893 } 11894 // Allow root and verify that userId is not being specified by a different user 11895 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11896 throw new SecurityException( 11897 "Permission Denial: attempt to change component state from pid=" 11898 + Binder.getCallingPid() 11899 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11900 } 11901 if (className == null) { 11902 // We're dealing with an application/package level state change 11903 if (pkgSetting.getEnabled(userId) == newState) { 11904 // Nothing to do 11905 return; 11906 } 11907 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11908 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11909 // Don't care about who enables an app. 11910 callingPackage = null; 11911 } 11912 pkgSetting.setEnabled(newState, userId, callingPackage); 11913 // pkgSetting.pkg.mSetEnabled = newState; 11914 } else { 11915 // We're dealing with a component level state change 11916 // First, verify that this is a valid class name. 11917 PackageParser.Package pkg = pkgSetting.pkg; 11918 if (pkg == null || !pkg.hasComponentClassName(className)) { 11919 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11920 throw new IllegalArgumentException("Component class " + className 11921 + " does not exist in " + packageName); 11922 } else { 11923 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11924 + className + " does not exist in " + packageName); 11925 } 11926 } 11927 switch (newState) { 11928 case COMPONENT_ENABLED_STATE_ENABLED: 11929 if (!pkgSetting.enableComponentLPw(className, userId)) { 11930 return; 11931 } 11932 break; 11933 case COMPONENT_ENABLED_STATE_DISABLED: 11934 if (!pkgSetting.disableComponentLPw(className, userId)) { 11935 return; 11936 } 11937 break; 11938 case COMPONENT_ENABLED_STATE_DEFAULT: 11939 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11940 return; 11941 } 11942 break; 11943 default: 11944 Slog.e(TAG, "Invalid new component state: " + newState); 11945 return; 11946 } 11947 } 11948 mSettings.writePackageRestrictionsLPr(userId); 11949 components = mPendingBroadcasts.get(userId, packageName); 11950 final boolean newPackage = components == null; 11951 if (newPackage) { 11952 components = new ArrayList<String>(); 11953 } 11954 if (!components.contains(componentName)) { 11955 components.add(componentName); 11956 } 11957 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11958 sendNow = true; 11959 // Purge entry from pending broadcast list if another one exists already 11960 // since we are sending one right away. 11961 mPendingBroadcasts.remove(userId, packageName); 11962 } else { 11963 if (newPackage) { 11964 mPendingBroadcasts.put(userId, packageName, components); 11965 } 11966 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11967 // Schedule a message 11968 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11969 } 11970 } 11971 } 11972 11973 long callingId = Binder.clearCallingIdentity(); 11974 try { 11975 if (sendNow) { 11976 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11977 sendPackageChangedBroadcast(packageName, 11978 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11979 } 11980 } finally { 11981 Binder.restoreCallingIdentity(callingId); 11982 } 11983 } 11984 11985 private void sendPackageChangedBroadcast(String packageName, 11986 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11987 if (DEBUG_INSTALL) 11988 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11989 + componentNames); 11990 Bundle extras = new Bundle(4); 11991 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11992 String nameList[] = new String[componentNames.size()]; 11993 componentNames.toArray(nameList); 11994 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11995 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11996 extras.putInt(Intent.EXTRA_UID, packageUid); 11997 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11998 new int[] {UserHandle.getUserId(packageUid)}); 11999 } 12000 12001 @Override 12002 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12003 if (!sUserManager.exists(userId)) return; 12004 final int uid = Binder.getCallingUid(); 12005 final int permission = mContext.checkCallingOrSelfPermission( 12006 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12007 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12008 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12009 // writer 12010 synchronized (mPackages) { 12011 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12012 uid, userId)) { 12013 scheduleWritePackageRestrictionsLocked(userId); 12014 } 12015 } 12016 } 12017 12018 @Override 12019 public String getInstallerPackageName(String packageName) { 12020 // reader 12021 synchronized (mPackages) { 12022 return mSettings.getInstallerPackageNameLPr(packageName); 12023 } 12024 } 12025 12026 @Override 12027 public int getApplicationEnabledSetting(String packageName, int userId) { 12028 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12029 int uid = Binder.getCallingUid(); 12030 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12031 // reader 12032 synchronized (mPackages) { 12033 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12034 } 12035 } 12036 12037 @Override 12038 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12039 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12040 int uid = Binder.getCallingUid(); 12041 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12042 // reader 12043 synchronized (mPackages) { 12044 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12045 } 12046 } 12047 12048 @Override 12049 public void enterSafeMode() { 12050 enforceSystemOrRoot("Only the system can request entering safe mode"); 12051 12052 if (!mSystemReady) { 12053 mSafeMode = true; 12054 } 12055 } 12056 12057 @Override 12058 public void systemReady() { 12059 mSystemReady = true; 12060 12061 // Read the compatibilty setting when the system is ready. 12062 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12063 mContext.getContentResolver(), 12064 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12065 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12066 if (DEBUG_SETTINGS) { 12067 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12068 } 12069 12070 synchronized (mPackages) { 12071 // Verify that all of the preferred activity components actually 12072 // exist. It is possible for applications to be updated and at 12073 // that point remove a previously declared activity component that 12074 // had been set as a preferred activity. We try to clean this up 12075 // the next time we encounter that preferred activity, but it is 12076 // possible for the user flow to never be able to return to that 12077 // situation so here we do a sanity check to make sure we haven't 12078 // left any junk around. 12079 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12080 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12081 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12082 removed.clear(); 12083 for (PreferredActivity pa : pir.filterSet()) { 12084 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12085 removed.add(pa); 12086 } 12087 } 12088 if (removed.size() > 0) { 12089 for (int r=0; r<removed.size(); r++) { 12090 PreferredActivity pa = removed.get(r); 12091 Slog.w(TAG, "Removing dangling preferred activity: " 12092 + pa.mPref.mComponent); 12093 pir.removeFilter(pa); 12094 } 12095 mSettings.writePackageRestrictionsLPr( 12096 mSettings.mPreferredActivities.keyAt(i)); 12097 } 12098 } 12099 } 12100 sUserManager.systemReady(); 12101 12102 // Kick off any messages waiting for system ready 12103 if (mPostSystemReadyMessages != null) { 12104 for (Message msg : mPostSystemReadyMessages) { 12105 msg.sendToTarget(); 12106 } 12107 mPostSystemReadyMessages = null; 12108 } 12109 } 12110 12111 @Override 12112 public boolean isSafeMode() { 12113 return mSafeMode; 12114 } 12115 12116 @Override 12117 public boolean hasSystemUidErrors() { 12118 return mHasSystemUidErrors; 12119 } 12120 12121 static String arrayToString(int[] array) { 12122 StringBuffer buf = new StringBuffer(128); 12123 buf.append('['); 12124 if (array != null) { 12125 for (int i=0; i<array.length; i++) { 12126 if (i > 0) buf.append(", "); 12127 buf.append(array[i]); 12128 } 12129 } 12130 buf.append(']'); 12131 return buf.toString(); 12132 } 12133 12134 static class DumpState { 12135 public static final int DUMP_LIBS = 1 << 0; 12136 public static final int DUMP_FEATURES = 1 << 1; 12137 public static final int DUMP_RESOLVERS = 1 << 2; 12138 public static final int DUMP_PERMISSIONS = 1 << 3; 12139 public static final int DUMP_PACKAGES = 1 << 4; 12140 public static final int DUMP_SHARED_USERS = 1 << 5; 12141 public static final int DUMP_MESSAGES = 1 << 6; 12142 public static final int DUMP_PROVIDERS = 1 << 7; 12143 public static final int DUMP_VERIFIERS = 1 << 8; 12144 public static final int DUMP_PREFERRED = 1 << 9; 12145 public static final int DUMP_PREFERRED_XML = 1 << 10; 12146 public static final int DUMP_KEYSETS = 1 << 11; 12147 public static final int DUMP_VERSION = 1 << 12; 12148 public static final int DUMP_INSTALLS = 1 << 13; 12149 12150 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12151 12152 private int mTypes; 12153 12154 private int mOptions; 12155 12156 private boolean mTitlePrinted; 12157 12158 private SharedUserSetting mSharedUser; 12159 12160 public boolean isDumping(int type) { 12161 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12162 return true; 12163 } 12164 12165 return (mTypes & type) != 0; 12166 } 12167 12168 public void setDump(int type) { 12169 mTypes |= type; 12170 } 12171 12172 public boolean isOptionEnabled(int option) { 12173 return (mOptions & option) != 0; 12174 } 12175 12176 public void setOptionEnabled(int option) { 12177 mOptions |= option; 12178 } 12179 12180 public boolean onTitlePrinted() { 12181 final boolean printed = mTitlePrinted; 12182 mTitlePrinted = true; 12183 return printed; 12184 } 12185 12186 public boolean getTitlePrinted() { 12187 return mTitlePrinted; 12188 } 12189 12190 public void setTitlePrinted(boolean enabled) { 12191 mTitlePrinted = enabled; 12192 } 12193 12194 public SharedUserSetting getSharedUser() { 12195 return mSharedUser; 12196 } 12197 12198 public void setSharedUser(SharedUserSetting user) { 12199 mSharedUser = user; 12200 } 12201 } 12202 12203 @Override 12204 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12205 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12206 != PackageManager.PERMISSION_GRANTED) { 12207 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12208 + Binder.getCallingPid() 12209 + ", uid=" + Binder.getCallingUid() 12210 + " without permission " 12211 + android.Manifest.permission.DUMP); 12212 return; 12213 } 12214 12215 DumpState dumpState = new DumpState(); 12216 boolean fullPreferred = false; 12217 boolean checkin = false; 12218 12219 String packageName = null; 12220 12221 int opti = 0; 12222 while (opti < args.length) { 12223 String opt = args[opti]; 12224 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12225 break; 12226 } 12227 opti++; 12228 12229 if ("-a".equals(opt)) { 12230 // Right now we only know how to print all. 12231 } else if ("-h".equals(opt)) { 12232 pw.println("Package manager dump options:"); 12233 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12234 pw.println(" --checkin: dump for a checkin"); 12235 pw.println(" -f: print details of intent filters"); 12236 pw.println(" -h: print this help"); 12237 pw.println(" cmd may be one of:"); 12238 pw.println(" l[ibraries]: list known shared libraries"); 12239 pw.println(" f[ibraries]: list device features"); 12240 pw.println(" k[eysets]: print known keysets"); 12241 pw.println(" r[esolvers]: dump intent resolvers"); 12242 pw.println(" perm[issions]: dump permissions"); 12243 pw.println(" pref[erred]: print preferred package settings"); 12244 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12245 pw.println(" prov[iders]: dump content providers"); 12246 pw.println(" p[ackages]: dump installed packages"); 12247 pw.println(" s[hared-users]: dump shared user IDs"); 12248 pw.println(" m[essages]: print collected runtime messages"); 12249 pw.println(" v[erifiers]: print package verifier info"); 12250 pw.println(" version: print database version info"); 12251 pw.println(" write: write current settings now"); 12252 pw.println(" <package.name>: info about given package"); 12253 pw.println(" installs: details about install sessions"); 12254 return; 12255 } else if ("--checkin".equals(opt)) { 12256 checkin = true; 12257 } else if ("-f".equals(opt)) { 12258 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12259 } else { 12260 pw.println("Unknown argument: " + opt + "; use -h for help"); 12261 } 12262 } 12263 12264 // Is the caller requesting to dump a particular piece of data? 12265 if (opti < args.length) { 12266 String cmd = args[opti]; 12267 opti++; 12268 // Is this a package name? 12269 if ("android".equals(cmd) || cmd.contains(".")) { 12270 packageName = cmd; 12271 // When dumping a single package, we always dump all of its 12272 // filter information since the amount of data will be reasonable. 12273 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12274 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12275 dumpState.setDump(DumpState.DUMP_LIBS); 12276 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12277 dumpState.setDump(DumpState.DUMP_FEATURES); 12278 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12279 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12280 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12281 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12282 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12283 dumpState.setDump(DumpState.DUMP_PREFERRED); 12284 } else if ("preferred-xml".equals(cmd)) { 12285 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12286 if (opti < args.length && "--full".equals(args[opti])) { 12287 fullPreferred = true; 12288 opti++; 12289 } 12290 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12291 dumpState.setDump(DumpState.DUMP_PACKAGES); 12292 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12293 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12294 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12295 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12296 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12297 dumpState.setDump(DumpState.DUMP_MESSAGES); 12298 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12299 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12300 } else if ("version".equals(cmd)) { 12301 dumpState.setDump(DumpState.DUMP_VERSION); 12302 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12303 dumpState.setDump(DumpState.DUMP_KEYSETS); 12304 } else if ("installs".equals(cmd)) { 12305 dumpState.setDump(DumpState.DUMP_INSTALLS); 12306 } else if ("write".equals(cmd)) { 12307 synchronized (mPackages) { 12308 mSettings.writeLPr(); 12309 pw.println("Settings written."); 12310 return; 12311 } 12312 } 12313 } 12314 12315 if (checkin) { 12316 pw.println("vers,1"); 12317 } 12318 12319 // reader 12320 synchronized (mPackages) { 12321 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12322 if (!checkin) { 12323 if (dumpState.onTitlePrinted()) 12324 pw.println(); 12325 pw.println("Database versions:"); 12326 pw.print(" SDK Version:"); 12327 pw.print(" internal="); 12328 pw.print(mSettings.mInternalSdkPlatform); 12329 pw.print(" external="); 12330 pw.println(mSettings.mExternalSdkPlatform); 12331 pw.print(" DB Version:"); 12332 pw.print(" internal="); 12333 pw.print(mSettings.mInternalDatabaseVersion); 12334 pw.print(" external="); 12335 pw.println(mSettings.mExternalDatabaseVersion); 12336 } 12337 } 12338 12339 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12340 if (!checkin) { 12341 if (dumpState.onTitlePrinted()) 12342 pw.println(); 12343 pw.println("Verifiers:"); 12344 pw.print(" Required: "); 12345 pw.print(mRequiredVerifierPackage); 12346 pw.print(" (uid="); 12347 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12348 pw.println(")"); 12349 } else if (mRequiredVerifierPackage != null) { 12350 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12351 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12352 } 12353 } 12354 12355 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12356 boolean printedHeader = false; 12357 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12358 while (it.hasNext()) { 12359 String name = it.next(); 12360 SharedLibraryEntry ent = mSharedLibraries.get(name); 12361 if (!checkin) { 12362 if (!printedHeader) { 12363 if (dumpState.onTitlePrinted()) 12364 pw.println(); 12365 pw.println("Libraries:"); 12366 printedHeader = true; 12367 } 12368 pw.print(" "); 12369 } else { 12370 pw.print("lib,"); 12371 } 12372 pw.print(name); 12373 if (!checkin) { 12374 pw.print(" -> "); 12375 } 12376 if (ent.path != null) { 12377 if (!checkin) { 12378 pw.print("(jar) "); 12379 pw.print(ent.path); 12380 } else { 12381 pw.print(",jar,"); 12382 pw.print(ent.path); 12383 } 12384 } else { 12385 if (!checkin) { 12386 pw.print("(apk) "); 12387 pw.print(ent.apk); 12388 } else { 12389 pw.print(",apk,"); 12390 pw.print(ent.apk); 12391 } 12392 } 12393 pw.println(); 12394 } 12395 } 12396 12397 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12398 if (dumpState.onTitlePrinted()) 12399 pw.println(); 12400 if (!checkin) { 12401 pw.println("Features:"); 12402 } 12403 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12404 while (it.hasNext()) { 12405 String name = it.next(); 12406 if (!checkin) { 12407 pw.print(" "); 12408 } else { 12409 pw.print("feat,"); 12410 } 12411 pw.println(name); 12412 } 12413 } 12414 12415 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12416 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12417 : "Activity Resolver Table:", " ", packageName, 12418 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12419 dumpState.setTitlePrinted(true); 12420 } 12421 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12422 : "Receiver Resolver Table:", " ", packageName, 12423 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12424 dumpState.setTitlePrinted(true); 12425 } 12426 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12427 : "Service Resolver Table:", " ", packageName, 12428 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12429 dumpState.setTitlePrinted(true); 12430 } 12431 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12432 : "Provider Resolver Table:", " ", packageName, 12433 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12434 dumpState.setTitlePrinted(true); 12435 } 12436 } 12437 12438 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12439 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12440 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12441 int user = mSettings.mPreferredActivities.keyAt(i); 12442 if (pir.dump(pw, 12443 dumpState.getTitlePrinted() 12444 ? "\nPreferred Activities User " + user + ":" 12445 : "Preferred Activities User " + user + ":", " ", 12446 packageName, true, false)) { 12447 dumpState.setTitlePrinted(true); 12448 } 12449 } 12450 } 12451 12452 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12453 pw.flush(); 12454 FileOutputStream fout = new FileOutputStream(fd); 12455 BufferedOutputStream str = new BufferedOutputStream(fout); 12456 XmlSerializer serializer = new FastXmlSerializer(); 12457 try { 12458 serializer.setOutput(str, "utf-8"); 12459 serializer.startDocument(null, true); 12460 serializer.setFeature( 12461 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12462 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12463 serializer.endDocument(); 12464 serializer.flush(); 12465 } catch (IllegalArgumentException e) { 12466 pw.println("Failed writing: " + e); 12467 } catch (IllegalStateException e) { 12468 pw.println("Failed writing: " + e); 12469 } catch (IOException e) { 12470 pw.println("Failed writing: " + e); 12471 } 12472 } 12473 12474 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12475 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12476 if (packageName == null) { 12477 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12478 if (iperm == 0) { 12479 if (dumpState.onTitlePrinted()) 12480 pw.println(); 12481 pw.println("AppOp Permissions:"); 12482 } 12483 pw.print(" AppOp Permission "); 12484 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12485 pw.println(":"); 12486 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12487 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12488 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12489 } 12490 } 12491 } 12492 } 12493 12494 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12495 boolean printedSomething = false; 12496 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12497 if (packageName != null && !packageName.equals(p.info.packageName)) { 12498 continue; 12499 } 12500 if (!printedSomething) { 12501 if (dumpState.onTitlePrinted()) 12502 pw.println(); 12503 pw.println("Registered ContentProviders:"); 12504 printedSomething = true; 12505 } 12506 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12507 pw.print(" "); pw.println(p.toString()); 12508 } 12509 printedSomething = false; 12510 for (Map.Entry<String, PackageParser.Provider> entry : 12511 mProvidersByAuthority.entrySet()) { 12512 PackageParser.Provider p = entry.getValue(); 12513 if (packageName != null && !packageName.equals(p.info.packageName)) { 12514 continue; 12515 } 12516 if (!printedSomething) { 12517 if (dumpState.onTitlePrinted()) 12518 pw.println(); 12519 pw.println("ContentProvider Authorities:"); 12520 printedSomething = true; 12521 } 12522 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12523 pw.print(" "); pw.println(p.toString()); 12524 if (p.info != null && p.info.applicationInfo != null) { 12525 final String appInfo = p.info.applicationInfo.toString(); 12526 pw.print(" applicationInfo="); pw.println(appInfo); 12527 } 12528 } 12529 } 12530 12531 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12532 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12533 } 12534 12535 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12536 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12537 } 12538 12539 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12540 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 12541 } 12542 12543 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12544 // XXX should handle packageName != null by dumping only install data that 12545 // the given package is involved with. 12546 if (dumpState.onTitlePrinted()) pw.println(); 12547 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12548 } 12549 12550 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12551 if (dumpState.onTitlePrinted()) pw.println(); 12552 mSettings.dumpReadMessagesLPr(pw, dumpState); 12553 12554 pw.println(); 12555 pw.println("Package warning messages:"); 12556 BufferedReader in = null; 12557 String line = null; 12558 try { 12559 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12560 while ((line = in.readLine()) != null) { 12561 if (line.contains("ignored: updated version")) continue; 12562 pw.println(line); 12563 } 12564 } catch (IOException ignored) { 12565 } finally { 12566 IoUtils.closeQuietly(in); 12567 } 12568 } 12569 12570 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12571 BufferedReader in = null; 12572 String line = null; 12573 try { 12574 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12575 while ((line = in.readLine()) != null) { 12576 if (line.contains("ignored: updated version")) continue; 12577 pw.print("msg,"); 12578 pw.println(line); 12579 } 12580 } catch (IOException ignored) { 12581 } finally { 12582 IoUtils.closeQuietly(in); 12583 } 12584 } 12585 } 12586 } 12587 12588 // ------- apps on sdcard specific code ------- 12589 static final boolean DEBUG_SD_INSTALL = false; 12590 12591 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12592 12593 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12594 12595 private boolean mMediaMounted = false; 12596 12597 static String getEncryptKey() { 12598 try { 12599 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12600 SD_ENCRYPTION_KEYSTORE_NAME); 12601 if (sdEncKey == null) { 12602 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12603 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12604 if (sdEncKey == null) { 12605 Slog.e(TAG, "Failed to create encryption keys"); 12606 return null; 12607 } 12608 } 12609 return sdEncKey; 12610 } catch (NoSuchAlgorithmException nsae) { 12611 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12612 return null; 12613 } catch (IOException ioe) { 12614 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12615 return null; 12616 } 12617 } 12618 12619 /* 12620 * Update media status on PackageManager. 12621 */ 12622 @Override 12623 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12624 int callingUid = Binder.getCallingUid(); 12625 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12626 throw new SecurityException("Media status can only be updated by the system"); 12627 } 12628 // reader; this apparently protects mMediaMounted, but should probably 12629 // be a different lock in that case. 12630 synchronized (mPackages) { 12631 Log.i(TAG, "Updating external media status from " 12632 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12633 + (mediaStatus ? "mounted" : "unmounted")); 12634 if (DEBUG_SD_INSTALL) 12635 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12636 + ", mMediaMounted=" + mMediaMounted); 12637 if (mediaStatus == mMediaMounted) { 12638 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12639 : 0, -1); 12640 mHandler.sendMessage(msg); 12641 return; 12642 } 12643 mMediaMounted = mediaStatus; 12644 } 12645 // Queue up an async operation since the package installation may take a 12646 // little while. 12647 mHandler.post(new Runnable() { 12648 public void run() { 12649 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12650 } 12651 }); 12652 } 12653 12654 /** 12655 * Called by MountService when the initial ASECs to scan are available. 12656 * Should block until all the ASEC containers are finished being scanned. 12657 */ 12658 public void scanAvailableAsecs() { 12659 updateExternalMediaStatusInner(true, false, false); 12660 if (mShouldRestoreconData) { 12661 SELinuxMMAC.setRestoreconDone(); 12662 mShouldRestoreconData = false; 12663 } 12664 } 12665 12666 /* 12667 * Collect information of applications on external media, map them against 12668 * existing containers and update information based on current mount status. 12669 * Please note that we always have to report status if reportStatus has been 12670 * set to true especially when unloading packages. 12671 */ 12672 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12673 boolean externalStorage) { 12674 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12675 int[] uidArr = EmptyArray.INT; 12676 12677 final String[] list = PackageHelper.getSecureContainerList(); 12678 if (ArrayUtils.isEmpty(list)) { 12679 Log.i(TAG, "No secure containers found"); 12680 } else { 12681 // Process list of secure containers and categorize them 12682 // as active or stale based on their package internal state. 12683 12684 // reader 12685 synchronized (mPackages) { 12686 for (String cid : list) { 12687 // Leave stages untouched for now; installer service owns them 12688 if (PackageInstallerService.isStageName(cid)) continue; 12689 12690 if (DEBUG_SD_INSTALL) 12691 Log.i(TAG, "Processing container " + cid); 12692 String pkgName = getAsecPackageName(cid); 12693 if (pkgName == null) { 12694 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12695 continue; 12696 } 12697 if (DEBUG_SD_INSTALL) 12698 Log.i(TAG, "Looking for pkg : " + pkgName); 12699 12700 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12701 if (ps == null) { 12702 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12703 continue; 12704 } 12705 12706 /* 12707 * Skip packages that are not external if we're unmounting 12708 * external storage. 12709 */ 12710 if (externalStorage && !isMounted && !isExternal(ps)) { 12711 continue; 12712 } 12713 12714 final AsecInstallArgs args = new AsecInstallArgs(cid, 12715 getAppDexInstructionSets(ps), ps.isForwardLocked()); 12716 // The package status is changed only if the code path 12717 // matches between settings and the container id. 12718 if (ps.codePathString != null 12719 && ps.codePathString.startsWith(args.getCodePath())) { 12720 if (DEBUG_SD_INSTALL) { 12721 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12722 + " at code path: " + ps.codePathString); 12723 } 12724 12725 // We do have a valid package installed on sdcard 12726 processCids.put(args, ps.codePathString); 12727 final int uid = ps.appId; 12728 if (uid != -1) { 12729 uidArr = ArrayUtils.appendInt(uidArr, uid); 12730 } 12731 } else { 12732 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12733 + ps.codePathString); 12734 } 12735 } 12736 } 12737 12738 Arrays.sort(uidArr); 12739 } 12740 12741 // Process packages with valid entries. 12742 if (isMounted) { 12743 if (DEBUG_SD_INSTALL) 12744 Log.i(TAG, "Loading packages"); 12745 loadMediaPackages(processCids, uidArr); 12746 startCleaningPackages(); 12747 mInstallerService.onSecureContainersAvailable(); 12748 } else { 12749 if (DEBUG_SD_INSTALL) 12750 Log.i(TAG, "Unloading packages"); 12751 unloadMediaPackages(processCids, uidArr, reportStatus); 12752 } 12753 } 12754 12755 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12756 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12757 int size = pkgList.size(); 12758 if (size > 0) { 12759 // Send broadcasts here 12760 Bundle extras = new Bundle(); 12761 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12762 .toArray(new String[size])); 12763 if (uidArr != null) { 12764 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12765 } 12766 if (replacing) { 12767 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12768 } 12769 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12770 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12771 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12772 } 12773 } 12774 12775 /* 12776 * Look at potentially valid container ids from processCids If package 12777 * information doesn't match the one on record or package scanning fails, 12778 * the cid is added to list of removeCids. We currently don't delete stale 12779 * containers. 12780 */ 12781 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12782 ArrayList<String> pkgList = new ArrayList<String>(); 12783 Set<AsecInstallArgs> keys = processCids.keySet(); 12784 12785 for (AsecInstallArgs args : keys) { 12786 String codePath = processCids.get(args); 12787 if (DEBUG_SD_INSTALL) 12788 Log.i(TAG, "Loading container : " + args.cid); 12789 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12790 try { 12791 // Make sure there are no container errors first. 12792 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12793 Slog.e(TAG, "Failed to mount cid : " + args.cid 12794 + " when installing from sdcard"); 12795 continue; 12796 } 12797 // Check code path here. 12798 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12799 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12800 + " does not match one in settings " + codePath); 12801 continue; 12802 } 12803 // Parse package 12804 int parseFlags = mDefParseFlags; 12805 if (args.isExternal()) { 12806 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12807 } 12808 if (args.isFwdLocked()) { 12809 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12810 } 12811 12812 synchronized (mInstallLock) { 12813 PackageParser.Package pkg = null; 12814 try { 12815 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12816 } catch (PackageManagerException e) { 12817 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12818 } 12819 // Scan the package 12820 if (pkg != null) { 12821 /* 12822 * TODO why is the lock being held? doPostInstall is 12823 * called in other places without the lock. This needs 12824 * to be straightened out. 12825 */ 12826 // writer 12827 synchronized (mPackages) { 12828 retCode = PackageManager.INSTALL_SUCCEEDED; 12829 pkgList.add(pkg.packageName); 12830 // Post process args 12831 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12832 pkg.applicationInfo.uid); 12833 } 12834 } else { 12835 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12836 } 12837 } 12838 12839 } finally { 12840 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12841 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12842 } 12843 } 12844 } 12845 // writer 12846 synchronized (mPackages) { 12847 // If the platform SDK has changed since the last time we booted, 12848 // we need to re-grant app permission to catch any new ones that 12849 // appear. This is really a hack, and means that apps can in some 12850 // cases get permissions that the user didn't initially explicitly 12851 // allow... it would be nice to have some better way to handle 12852 // this situation. 12853 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12854 if (regrantPermissions) 12855 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12856 + mSdkVersion + "; regranting permissions for external storage"); 12857 mSettings.mExternalSdkPlatform = mSdkVersion; 12858 12859 // Make sure group IDs have been assigned, and any permission 12860 // changes in other apps are accounted for 12861 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12862 | (regrantPermissions 12863 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12864 : 0)); 12865 12866 mSettings.updateExternalDatabaseVersion(); 12867 12868 // can downgrade to reader 12869 // Persist settings 12870 mSettings.writeLPr(); 12871 } 12872 // Send a broadcast to let everyone know we are done processing 12873 if (pkgList.size() > 0) { 12874 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12875 } 12876 } 12877 12878 /* 12879 * Utility method to unload a list of specified containers 12880 */ 12881 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12882 // Just unmount all valid containers. 12883 for (AsecInstallArgs arg : cidArgs) { 12884 synchronized (mInstallLock) { 12885 arg.doPostDeleteLI(false); 12886 } 12887 } 12888 } 12889 12890 /* 12891 * Unload packages mounted on external media. This involves deleting package 12892 * data from internal structures, sending broadcasts about diabled packages, 12893 * gc'ing to free up references, unmounting all secure containers 12894 * corresponding to packages on external media, and posting a 12895 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12896 * that we always have to post this message if status has been requested no 12897 * matter what. 12898 */ 12899 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12900 final boolean reportStatus) { 12901 if (DEBUG_SD_INSTALL) 12902 Log.i(TAG, "unloading media packages"); 12903 ArrayList<String> pkgList = new ArrayList<String>(); 12904 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12905 final Set<AsecInstallArgs> keys = processCids.keySet(); 12906 for (AsecInstallArgs args : keys) { 12907 String pkgName = args.getPackageName(); 12908 if (DEBUG_SD_INSTALL) 12909 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12910 // Delete package internally 12911 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12912 synchronized (mInstallLock) { 12913 boolean res = deletePackageLI(pkgName, null, false, null, null, 12914 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12915 if (res) { 12916 pkgList.add(pkgName); 12917 } else { 12918 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12919 failedList.add(args); 12920 } 12921 } 12922 } 12923 12924 // reader 12925 synchronized (mPackages) { 12926 // We didn't update the settings after removing each package; 12927 // write them now for all packages. 12928 mSettings.writeLPr(); 12929 } 12930 12931 // We have to absolutely send UPDATED_MEDIA_STATUS only 12932 // after confirming that all the receivers processed the ordered 12933 // broadcast when packages get disabled, force a gc to clean things up. 12934 // and unload all the containers. 12935 if (pkgList.size() > 0) { 12936 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12937 new IIntentReceiver.Stub() { 12938 public void performReceive(Intent intent, int resultCode, String data, 12939 Bundle extras, boolean ordered, boolean sticky, 12940 int sendingUser) throws RemoteException { 12941 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12942 reportStatus ? 1 : 0, 1, keys); 12943 mHandler.sendMessage(msg); 12944 } 12945 }); 12946 } else { 12947 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12948 keys); 12949 mHandler.sendMessage(msg); 12950 } 12951 } 12952 12953 /** Binder call */ 12954 @Override 12955 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12956 final int flags) { 12957 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12958 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12959 int returnCode = PackageManager.MOVE_SUCCEEDED; 12960 int currInstallFlags = 0; 12961 int newInstallFlags = 0; 12962 12963 File codeFile = null; 12964 String installerPackageName = null; 12965 String packageAbiOverride = null; 12966 12967 // reader 12968 synchronized (mPackages) { 12969 final PackageParser.Package pkg = mPackages.get(packageName); 12970 final PackageSetting ps = mSettings.mPackages.get(packageName); 12971 if (pkg == null || ps == null) { 12972 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12973 } else { 12974 // Disable moving fwd locked apps and system packages 12975 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12976 Slog.w(TAG, "Cannot move system application"); 12977 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12978 } else if (pkg.mOperationPending) { 12979 Slog.w(TAG, "Attempt to move package which has pending operations"); 12980 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12981 } else { 12982 // Find install location first 12983 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12984 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12985 Slog.w(TAG, "Ambigous flags specified for move location."); 12986 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12987 } else { 12988 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12989 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12990 currInstallFlags = isExternal(pkg) 12991 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12992 12993 if (newInstallFlags == currInstallFlags) { 12994 Slog.w(TAG, "No move required. Trying to move to same location"); 12995 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12996 } else { 12997 if (pkg.isForwardLocked()) { 12998 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12999 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13000 } 13001 } 13002 } 13003 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13004 pkg.mOperationPending = true; 13005 } 13006 } 13007 13008 codeFile = new File(pkg.codePath); 13009 installerPackageName = ps.installerPackageName; 13010 packageAbiOverride = ps.cpuAbiOverrideString; 13011 } 13012 } 13013 13014 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13015 try { 13016 observer.packageMoved(packageName, returnCode); 13017 } catch (RemoteException ignored) { 13018 } 13019 return; 13020 } 13021 13022 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13023 @Override 13024 public void onUserActionRequired(Intent intent) throws RemoteException { 13025 throw new IllegalStateException(); 13026 } 13027 13028 @Override 13029 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13030 Bundle extras) throws RemoteException { 13031 Slog.d(TAG, "Install result for move: " 13032 + PackageManager.installStatusToString(returnCode, msg)); 13033 13034 // We usually have a new package now after the install, but if 13035 // we failed we need to clear the pending flag on the original 13036 // package object. 13037 synchronized (mPackages) { 13038 final PackageParser.Package pkg = mPackages.get(packageName); 13039 if (pkg != null) { 13040 pkg.mOperationPending = false; 13041 } 13042 } 13043 13044 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13045 switch (status) { 13046 case PackageInstaller.STATUS_SUCCESS: 13047 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13048 break; 13049 case PackageInstaller.STATUS_FAILURE_STORAGE: 13050 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13051 break; 13052 default: 13053 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13054 break; 13055 } 13056 } 13057 }; 13058 13059 // Treat a move like reinstalling an existing app, which ensures that we 13060 // process everythign uniformly, like unpacking native libraries. 13061 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13062 13063 final Message msg = mHandler.obtainMessage(INIT_COPY); 13064 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13065 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13066 installerPackageName, null, user, packageAbiOverride); 13067 mHandler.sendMessage(msg); 13068 } 13069 13070 @Override 13071 public boolean setInstallLocation(int loc) { 13072 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13073 null); 13074 if (getInstallLocation() == loc) { 13075 return true; 13076 } 13077 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13078 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13079 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13080 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13081 return true; 13082 } 13083 return false; 13084 } 13085 13086 @Override 13087 public int getInstallLocation() { 13088 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13089 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13090 PackageHelper.APP_INSTALL_AUTO); 13091 } 13092 13093 /** Called by UserManagerService */ 13094 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13095 mDirtyUsers.remove(userHandle); 13096 mSettings.removeUserLPw(userHandle); 13097 mPendingBroadcasts.remove(userHandle); 13098 if (mInstaller != null) { 13099 // Technically, we shouldn't be doing this with the package lock 13100 // held. However, this is very rare, and there is already so much 13101 // other disk I/O going on, that we'll let it slide for now. 13102 mInstaller.removeUserDataDirs(userHandle); 13103 } 13104 mUserNeedsBadging.delete(userHandle); 13105 removeUnusedPackagesLILPw(userManager, userHandle); 13106 } 13107 13108 /** 13109 * We're removing userHandle and would like to remove any downloaded packages 13110 * that are no longer in use by any other user. 13111 * @param userHandle the user being removed 13112 */ 13113 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13114 final boolean DEBUG_CLEAN_APKS = false; 13115 int [] users = userManager.getUserIdsLPr(); 13116 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13117 while (psit.hasNext()) { 13118 PackageSetting ps = psit.next(); 13119 if (ps.pkg == null) { 13120 continue; 13121 } 13122 final String packageName = ps.pkg.packageName; 13123 // Skip over if system app 13124 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13125 continue; 13126 } 13127 if (DEBUG_CLEAN_APKS) { 13128 Slog.i(TAG, "Checking package " + packageName); 13129 } 13130 boolean keep = false; 13131 for (int i = 0; i < users.length; i++) { 13132 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13133 keep = true; 13134 if (DEBUG_CLEAN_APKS) { 13135 Slog.i(TAG, " Keeping package " + packageName + " for user " 13136 + users[i]); 13137 } 13138 break; 13139 } 13140 } 13141 if (!keep) { 13142 if (DEBUG_CLEAN_APKS) { 13143 Slog.i(TAG, " Removing package " + packageName); 13144 } 13145 mHandler.post(new Runnable() { 13146 public void run() { 13147 deletePackageX(packageName, userHandle, 0); 13148 } //end run 13149 }); 13150 } 13151 } 13152 } 13153 13154 /** Called by UserManagerService */ 13155 void createNewUserLILPw(int userHandle, File path) { 13156 if (mInstaller != null) { 13157 mInstaller.createUserConfig(userHandle); 13158 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13159 } 13160 } 13161 13162 @Override 13163 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13164 mContext.enforceCallingOrSelfPermission( 13165 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13166 "Only package verification agents can read the verifier device identity"); 13167 13168 synchronized (mPackages) { 13169 return mSettings.getVerifierDeviceIdentityLPw(); 13170 } 13171 } 13172 13173 @Override 13174 public void setPermissionEnforced(String permission, boolean enforced) { 13175 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13176 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13177 synchronized (mPackages) { 13178 if (mSettings.mReadExternalStorageEnforced == null 13179 || mSettings.mReadExternalStorageEnforced != enforced) { 13180 mSettings.mReadExternalStorageEnforced = enforced; 13181 mSettings.writeLPr(); 13182 } 13183 } 13184 // kill any non-foreground processes so we restart them and 13185 // grant/revoke the GID. 13186 final IActivityManager am = ActivityManagerNative.getDefault(); 13187 if (am != null) { 13188 final long token = Binder.clearCallingIdentity(); 13189 try { 13190 am.killProcessesBelowForeground("setPermissionEnforcement"); 13191 } catch (RemoteException e) { 13192 } finally { 13193 Binder.restoreCallingIdentity(token); 13194 } 13195 } 13196 } else { 13197 throw new IllegalArgumentException("No selective enforcement for " + permission); 13198 } 13199 } 13200 13201 @Override 13202 @Deprecated 13203 public boolean isPermissionEnforced(String permission) { 13204 return true; 13205 } 13206 13207 @Override 13208 public boolean isStorageLow() { 13209 final long token = Binder.clearCallingIdentity(); 13210 try { 13211 final DeviceStorageMonitorInternal 13212 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13213 if (dsm != null) { 13214 return dsm.isMemoryLow(); 13215 } else { 13216 return false; 13217 } 13218 } finally { 13219 Binder.restoreCallingIdentity(token); 13220 } 13221 } 13222 13223 @Override 13224 public IPackageInstaller getPackageInstaller() { 13225 return mInstallerService; 13226 } 13227 13228 private boolean userNeedsBadging(int userId) { 13229 int index = mUserNeedsBadging.indexOfKey(userId); 13230 if (index < 0) { 13231 final UserInfo userInfo; 13232 final long token = Binder.clearCallingIdentity(); 13233 try { 13234 userInfo = sUserManager.getUserInfo(userId); 13235 } finally { 13236 Binder.restoreCallingIdentity(token); 13237 } 13238 final boolean b; 13239 if (userInfo != null && userInfo.isManagedProfile()) { 13240 b = true; 13241 } else { 13242 b = false; 13243 } 13244 mUserNeedsBadging.put(userId, b); 13245 return b; 13246 } 13247 return mUserNeedsBadging.valueAt(index); 13248 } 13249 13250 @Override 13251 public KeySet getKeySetByAlias(String packageName, String alias) { 13252 if (packageName == null || alias == null) { 13253 return null; 13254 } 13255 synchronized(mPackages) { 13256 final PackageParser.Package pkg = mPackages.get(packageName); 13257 if (pkg == null) { 13258 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13259 throw new IllegalArgumentException("Unknown package: " + packageName); 13260 } 13261 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13262 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13263 } 13264 } 13265 13266 @Override 13267 public KeySet getSigningKeySet(String packageName) { 13268 if (packageName == null) { 13269 return null; 13270 } 13271 synchronized(mPackages) { 13272 final PackageParser.Package pkg = mPackages.get(packageName); 13273 if (pkg == null) { 13274 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13275 throw new IllegalArgumentException("Unknown package: " + packageName); 13276 } 13277 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13278 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13279 throw new SecurityException("May not access signing KeySet of other apps."); 13280 } 13281 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13282 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13283 } 13284 } 13285 13286 @Override 13287 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13288 if (packageName == null || ks == null) { 13289 return false; 13290 } 13291 synchronized(mPackages) { 13292 final PackageParser.Package pkg = mPackages.get(packageName); 13293 if (pkg == null) { 13294 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13295 throw new IllegalArgumentException("Unknown package: " + packageName); 13296 } 13297 IBinder ksh = ks.getToken(); 13298 if (ksh instanceof KeySetHandle) { 13299 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13300 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13301 } 13302 return false; 13303 } 13304 } 13305 13306 @Override 13307 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13308 if (packageName == null || ks == null) { 13309 return false; 13310 } 13311 synchronized(mPackages) { 13312 final PackageParser.Package pkg = mPackages.get(packageName); 13313 if (pkg == null) { 13314 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13315 throw new IllegalArgumentException("Unknown package: " + packageName); 13316 } 13317 IBinder ksh = ks.getToken(); 13318 if (ksh instanceof KeySetHandle) { 13319 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13320 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13321 } 13322 return false; 13323 } 13324 } 13325 13326 public void getUsageStatsIfNoPackageUsageInfo() { 13327 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 13328 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 13329 if (usm == null) { 13330 throw new IllegalStateException("UsageStatsManager must be initialized"); 13331 } 13332 long now = System.currentTimeMillis(); 13333 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 13334 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 13335 String packageName = entry.getKey(); 13336 PackageParser.Package pkg = mPackages.get(packageName); 13337 if (pkg == null) { 13338 continue; 13339 } 13340 UsageStats usage = entry.getValue(); 13341 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 13342 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 13343 } 13344 } 13345 } 13346 13347 /** 13348 * Check and throw if the given before/after packages would be considered a 13349 * downgrade. 13350 */ 13351 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 13352 throws PackageManagerException { 13353 if (after.versionCode < before.mVersionCode) { 13354 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13355 "Update version code " + after.versionCode + " is older than current " 13356 + before.mVersionCode); 13357 } else if (after.versionCode == before.mVersionCode) { 13358 if (after.baseRevisionCode < before.baseRevisionCode) { 13359 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13360 "Update base revision code " + after.baseRevisionCode 13361 + " is older than current " + before.baseRevisionCode); 13362 } 13363 13364 if (!ArrayUtils.isEmpty(after.splitNames)) { 13365 for (int i = 0; i < after.splitNames.length; i++) { 13366 final String splitName = after.splitNames[i]; 13367 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 13368 if (j != -1) { 13369 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 13370 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13371 "Update split " + splitName + " revision code " 13372 + after.splitRevisionCodes[i] + " is older than current " 13373 + before.splitRevisionCodes[j]); 13374 } 13375 } 13376 } 13377 } 13378 } 13379 } 13380} 13381