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