PackageManagerService.java revision 2b6d792ad56795050f01abbd2d732cf717037b1c
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 47import static android.content.pm.PackageParser.isApkFile; 48import static android.os.Process.PACKAGE_INFO_GID; 49import static android.os.Process.SYSTEM_UID; 50import static android.system.OsConstants.O_CREAT; 51import static android.system.OsConstants.O_RDWR; 52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 53import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 54import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 55import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 56import static com.android.internal.util.ArrayUtils.appendInt; 57import static com.android.internal.util.ArrayUtils.removeInt; 58import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 59import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 60import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 61import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 62import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 63 64import android.util.ArrayMap; 65 66import com.android.internal.R; 67import com.android.internal.app.IMediaContainerService; 68import com.android.internal.app.ResolverActivity; 69import com.android.internal.content.NativeLibraryHelper; 70import com.android.internal.content.PackageHelper; 71import com.android.internal.os.IParcelFileDescriptorFactory; 72import com.android.internal.util.ArrayUtils; 73import com.android.internal.util.FastPrintWriter; 74import com.android.internal.util.FastXmlSerializer; 75import com.android.internal.util.IndentingPrintWriter; 76import com.android.server.EventLogTags; 77import com.android.server.IntentResolver; 78import com.android.server.LocalServices; 79import com.android.server.ServiceThread; 80import com.android.server.SystemConfig; 81import com.android.server.Watchdog; 82import com.android.server.pm.Settings.DatabaseVersion; 83import com.android.server.storage.DeviceStorageMonitorInternal; 84 85import org.xmlpull.v1.XmlSerializer; 86 87import android.app.ActivityManager; 88import android.app.ActivityManagerNative; 89import android.app.AppGlobals; 90import android.app.IActivityManager; 91import android.app.admin.IDevicePolicyManager; 92import android.app.backup.IBackupManager; 93import android.app.usage.UsageStats; 94import android.app.usage.UsageStatsManager; 95import android.content.BroadcastReceiver; 96import android.content.ComponentName; 97import android.content.Context; 98import android.content.IIntentReceiver; 99import android.content.Intent; 100import android.content.IntentFilter; 101import android.content.IntentSender; 102import android.content.IntentSender.SendIntentException; 103import android.content.ServiceConnection; 104import android.content.pm.ActivityInfo; 105import android.content.pm.ApplicationInfo; 106import android.content.pm.FeatureInfo; 107import android.content.pm.IPackageDataObserver; 108import android.content.pm.IPackageDeleteObserver; 109import android.content.pm.IPackageDeleteObserver2; 110import android.content.pm.IPackageInstallObserver2; 111import android.content.pm.IPackageInstaller; 112import android.content.pm.IPackageManager; 113import android.content.pm.IPackageMoveObserver; 114import android.content.pm.IPackageStatsObserver; 115import android.content.pm.InstrumentationInfo; 116import android.content.pm.KeySet; 117import android.content.pm.ManifestDigest; 118import android.content.pm.PackageCleanItem; 119import android.content.pm.PackageInfo; 120import android.content.pm.PackageInfoLite; 121import android.content.pm.PackageInstaller; 122import android.content.pm.PackageManager; 123import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 124import android.content.pm.PackageParser.ActivityIntentInfo; 125import android.content.pm.PackageParser.PackageLite; 126import android.content.pm.PackageParser.PackageParserException; 127import android.content.pm.PackageParser; 128import android.content.pm.PackageStats; 129import android.content.pm.PackageUserState; 130import android.content.pm.ParceledListSlice; 131import android.content.pm.PermissionGroupInfo; 132import android.content.pm.PermissionInfo; 133import android.content.pm.ProviderInfo; 134import android.content.pm.ResolveInfo; 135import android.content.pm.ServiceInfo; 136import android.content.pm.Signature; 137import android.content.pm.UserInfo; 138import android.content.pm.VerificationParams; 139import android.content.pm.VerifierDeviceIdentity; 140import android.content.pm.VerifierInfo; 141import android.content.res.Resources; 142import android.hardware.display.DisplayManager; 143import android.net.Uri; 144import android.os.Binder; 145import android.os.Build; 146import android.os.Bundle; 147import android.os.Environment; 148import android.os.Environment.UserEnvironment; 149import android.os.storage.IMountService; 150import android.os.storage.StorageManager; 151import android.os.Debug; 152import android.os.FileUtils; 153import android.os.Handler; 154import android.os.IBinder; 155import android.os.Looper; 156import android.os.Message; 157import android.os.Parcel; 158import android.os.ParcelFileDescriptor; 159import android.os.Process; 160import android.os.RemoteException; 161import android.os.SELinux; 162import android.os.ServiceManager; 163import android.os.SystemClock; 164import android.os.SystemProperties; 165import android.os.UserHandle; 166import android.os.UserManager; 167import android.security.KeyStore; 168import android.security.SystemKeyStore; 169import android.system.ErrnoException; 170import android.system.Os; 171import android.system.StructStat; 172import android.text.TextUtils; 173import android.text.format.DateUtils; 174import android.util.ArraySet; 175import android.util.AtomicFile; 176import android.util.DisplayMetrics; 177import android.util.EventLog; 178import android.util.ExceptionUtils; 179import android.util.Log; 180import android.util.LogPrinter; 181import android.util.PrintStreamPrinter; 182import android.util.Slog; 183import android.util.SparseArray; 184import android.util.SparseBooleanArray; 185import android.view.Display; 186 187import java.io.BufferedInputStream; 188import java.io.BufferedOutputStream; 189import java.io.BufferedReader; 190import java.io.File; 191import java.io.FileDescriptor; 192import java.io.FileNotFoundException; 193import java.io.FileOutputStream; 194import java.io.FileReader; 195import java.io.FilenameFilter; 196import java.io.IOException; 197import java.io.InputStream; 198import java.io.PrintWriter; 199import java.nio.charset.StandardCharsets; 200import java.security.NoSuchAlgorithmException; 201import java.security.PublicKey; 202import java.security.cert.CertificateEncodingException; 203import java.security.cert.CertificateException; 204import java.text.SimpleDateFormat; 205import java.util.ArrayList; 206import java.util.Arrays; 207import java.util.Collection; 208import java.util.Collections; 209import java.util.Comparator; 210import java.util.Date; 211import java.util.Iterator; 212import java.util.List; 213import java.util.Map; 214import java.util.Objects; 215import java.util.Set; 216import java.util.concurrent.atomic.AtomicBoolean; 217import java.util.concurrent.atomic.AtomicLong; 218 219import dalvik.system.DexFile; 220import dalvik.system.VMRuntime; 221 222import libcore.io.IoUtils; 223import libcore.util.EmptyArray; 224 225/** 226 * Keep track of all those .apks everywhere. 227 * 228 * This is very central to the platform's security; please run the unit 229 * tests whenever making modifications here: 230 * 231mmm frameworks/base/tests/AndroidTests 232adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 233adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 234 * 235 * {@hide} 236 */ 237public class PackageManagerService extends IPackageManager.Stub { 238 static final String TAG = "PackageManager"; 239 static final boolean DEBUG_SETTINGS = false; 240 static final boolean DEBUG_PREFERRED = false; 241 static final boolean DEBUG_UPGRADE = false; 242 private static final boolean DEBUG_INSTALL = false; 243 private static final boolean DEBUG_REMOVE = false; 244 private static final boolean DEBUG_BROADCASTS = false; 245 private static final boolean DEBUG_SHOW_INFO = false; 246 private static final boolean DEBUG_PACKAGE_INFO = false; 247 private static final boolean DEBUG_INTENT_MATCHING = false; 248 private static final boolean DEBUG_PACKAGE_SCANNING = false; 249 private static final boolean DEBUG_VERIFY = false; 250 private static final boolean DEBUG_DEXOPT = false; 251 private static final boolean DEBUG_ABI_SELECTION = false; 252 253 private static final int RADIO_UID = Process.PHONE_UID; 254 private static final int LOG_UID = Process.LOG_UID; 255 private static final int NFC_UID = Process.NFC_UID; 256 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 257 private static final int SHELL_UID = Process.SHELL_UID; 258 259 // Cap the size of permission trees that 3rd party apps can define 260 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 261 262 // Suffix used during package installation when copying/moving 263 // package apks to install directory. 264 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 265 266 static final int SCAN_NO_DEX = 1<<1; 267 static final int SCAN_FORCE_DEX = 1<<2; 268 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 269 static final int SCAN_NEW_INSTALL = 1<<4; 270 static final int SCAN_NO_PATHS = 1<<5; 271 static final int SCAN_UPDATE_TIME = 1<<6; 272 static final int SCAN_DEFER_DEX = 1<<7; 273 static final int SCAN_BOOTING = 1<<8; 274 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 275 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 276 static final int SCAN_REPLACING = 1<<11; 277 278 static final int REMOVE_CHATTY = 1<<16; 279 280 /** 281 * Timeout (in milliseconds) after which the watchdog should declare that 282 * our handler thread is wedged. The usual default for such things is one 283 * minute but we sometimes do very lengthy I/O operations on this thread, 284 * such as installing multi-gigabyte applications, so ours needs to be longer. 285 */ 286 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 287 288 /** 289 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 290 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 291 * settings entry if available, otherwise we use the hardcoded default. If it's been 292 * more than this long since the last fstrim, we force one during the boot sequence. 293 * 294 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 295 * one gets run at the next available charging+idle time. This final mandatory 296 * no-fstrim check kicks in only of the other scheduling criteria is never met. 297 */ 298 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 299 300 /** 301 * Whether verification is enabled by default. 302 */ 303 private static final boolean DEFAULT_VERIFY_ENABLE = true; 304 305 /** 306 * The default maximum time to wait for the verification agent to return in 307 * milliseconds. 308 */ 309 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 310 311 /** 312 * The default response for package verification timeout. 313 * 314 * This can be either PackageManager.VERIFICATION_ALLOW or 315 * PackageManager.VERIFICATION_REJECT. 316 */ 317 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 318 319 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 320 321 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 322 DEFAULT_CONTAINER_PACKAGE, 323 "com.android.defcontainer.DefaultContainerService"); 324 325 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 326 327 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 328 329 final ServiceThread mHandlerThread; 330 331 final PackageHandler mHandler; 332 333 /** 334 * Messages for {@link #mHandler} that need to wait for system ready before 335 * being dispatched. 336 */ 337 private ArrayList<Message> mPostSystemReadyMessages; 338 339 final int mSdkVersion = Build.VERSION.SDK_INT; 340 341 final Context mContext; 342 final boolean mFactoryTest; 343 final boolean mOnlyCore; 344 final boolean mLazyDexOpt; 345 final long mDexOptLRUThresholdInMills; 346 final DisplayMetrics mMetrics; 347 final int mDefParseFlags; 348 final String[] mSeparateProcesses; 349 final boolean mIsUpgrade; 350 351 // This is where all application persistent data goes. 352 final File mAppDataDir; 353 354 // This is where all application persistent data goes for secondary users. 355 final File mUserAppDataDir; 356 357 /** The location for ASEC container files on internal storage. */ 358 final String mAsecInternalPath; 359 360 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 361 // LOCK HELD. Can be called with mInstallLock held. 362 final Installer mInstaller; 363 364 /** Directory where installed third-party apps stored */ 365 final File mAppInstallDir; 366 367 /** 368 * Directory to which applications installed internally have their 369 * 32 bit native libraries copied. 370 */ 371 private File mAppLib32InstallDir; 372 373 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 374 // apps. 375 final File mDrmAppPrivateInstallDir; 376 377 // ---------------------------------------------------------------- 378 379 // Lock for state used when installing and doing other long running 380 // operations. Methods that must be called with this lock held have 381 // the suffix "LI". 382 final Object mInstallLock = new Object(); 383 384 // ---------------------------------------------------------------- 385 386 // Keys are String (package name), values are Package. This also serves 387 // as the lock for the global state. Methods that must be called with 388 // this lock held have the prefix "LP". 389 final ArrayMap<String, PackageParser.Package> mPackages = 390 new ArrayMap<String, PackageParser.Package>(); 391 392 // Tracks available target package names -> overlay package paths. 393 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 394 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 395 396 final Settings mSettings; 397 boolean mRestoredSettings; 398 399 // System configuration read by SystemConfig. 400 final int[] mGlobalGids; 401 final SparseArray<ArraySet<String>> mSystemPermissions; 402 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 403 404 // If mac_permissions.xml was found for seinfo labeling. 405 boolean mFoundPolicyFile; 406 407 // If a recursive restorecon of /data/data/<pkg> is needed. 408 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 409 410 public static final class SharedLibraryEntry { 411 public final String path; 412 public final String apk; 413 414 SharedLibraryEntry(String _path, String _apk) { 415 path = _path; 416 apk = _apk; 417 } 418 } 419 420 // Currently known shared libraries. 421 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 422 new ArrayMap<String, SharedLibraryEntry>(); 423 424 // All available activities, for your resolving pleasure. 425 final ActivityIntentResolver mActivities = 426 new ActivityIntentResolver(); 427 428 // All available receivers, for your resolving pleasure. 429 final ActivityIntentResolver mReceivers = 430 new ActivityIntentResolver(); 431 432 // All available services, for your resolving pleasure. 433 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 434 435 // All available providers, for your resolving pleasure. 436 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 437 438 // Mapping from provider base names (first directory in content URI codePath) 439 // to the provider information. 440 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 441 new ArrayMap<String, PackageParser.Provider>(); 442 443 // Mapping from instrumentation class names to info about them. 444 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 445 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 446 447 // Mapping from permission names to info about them. 448 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 449 new ArrayMap<String, PackageParser.PermissionGroup>(); 450 451 // Packages whose data we have transfered into another package, thus 452 // should no longer exist. 453 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 454 455 // Broadcast actions that are only available to the system. 456 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 457 458 /** List of packages waiting for verification. */ 459 final SparseArray<PackageVerificationState> mPendingVerification 460 = new SparseArray<PackageVerificationState>(); 461 462 /** Set of packages associated with each app op permission. */ 463 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 464 465 final PackageInstallerService mInstallerService; 466 467 private final PackageDexOptimizer mPackageDexOptimizer; 468 // Cache of users who need badging. 469 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 470 471 /** Token for keys in mPendingVerification. */ 472 private int mPendingVerificationToken = 0; 473 474 volatile boolean mSystemReady; 475 volatile boolean mSafeMode; 476 volatile boolean mHasSystemUidErrors; 477 478 ApplicationInfo mAndroidApplication; 479 final ActivityInfo mResolveActivity = new ActivityInfo(); 480 final ResolveInfo mResolveInfo = new ResolveInfo(); 481 ComponentName mResolveComponentName; 482 PackageParser.Package mPlatformPackage; 483 ComponentName mCustomResolverComponentName; 484 485 boolean mResolverReplaced = false; 486 487 // Set of pending broadcasts for aggregating enable/disable of components. 488 static class PendingPackageBroadcasts { 489 // for each user id, a map of <package name -> components within that package> 490 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 491 492 public PendingPackageBroadcasts() { 493 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 494 } 495 496 public ArrayList<String> get(int userId, String packageName) { 497 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 498 return packages.get(packageName); 499 } 500 501 public void put(int userId, String packageName, ArrayList<String> components) { 502 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 503 packages.put(packageName, components); 504 } 505 506 public void remove(int userId, String packageName) { 507 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 508 if (packages != null) { 509 packages.remove(packageName); 510 } 511 } 512 513 public void remove(int userId) { 514 mUidMap.remove(userId); 515 } 516 517 public int userIdCount() { 518 return mUidMap.size(); 519 } 520 521 public int userIdAt(int n) { 522 return mUidMap.keyAt(n); 523 } 524 525 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 526 return mUidMap.get(userId); 527 } 528 529 public int size() { 530 // total number of pending broadcast entries across all userIds 531 int num = 0; 532 for (int i = 0; i< mUidMap.size(); i++) { 533 num += mUidMap.valueAt(i).size(); 534 } 535 return num; 536 } 537 538 public void clear() { 539 mUidMap.clear(); 540 } 541 542 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 543 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 544 if (map == null) { 545 map = new ArrayMap<String, ArrayList<String>>(); 546 mUidMap.put(userId, map); 547 } 548 return map; 549 } 550 } 551 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 552 553 // Service Connection to remote media container service to copy 554 // package uri's from external media onto secure containers 555 // or internal storage. 556 private IMediaContainerService mContainerService = null; 557 558 static final int SEND_PENDING_BROADCAST = 1; 559 static final int MCS_BOUND = 3; 560 static final int END_COPY = 4; 561 static final int INIT_COPY = 5; 562 static final int MCS_UNBIND = 6; 563 static final int START_CLEANING_PACKAGE = 7; 564 static final int FIND_INSTALL_LOC = 8; 565 static final int POST_INSTALL = 9; 566 static final int MCS_RECONNECT = 10; 567 static final int MCS_GIVE_UP = 11; 568 static final int UPDATED_MEDIA_STATUS = 12; 569 static final int WRITE_SETTINGS = 13; 570 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 571 static final int PACKAGE_VERIFIED = 15; 572 static final int CHECK_PENDING_VERIFICATION = 16; 573 574 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 575 576 // Delay time in millisecs 577 static final int BROADCAST_DELAY = 10 * 1000; 578 579 static UserManagerService sUserManager; 580 581 // Stores a list of users whose package restrictions file needs to be updated 582 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 583 584 final private DefaultContainerConnection mDefContainerConn = 585 new DefaultContainerConnection(); 586 class DefaultContainerConnection implements ServiceConnection { 587 public void onServiceConnected(ComponentName name, IBinder service) { 588 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 589 IMediaContainerService imcs = 590 IMediaContainerService.Stub.asInterface(service); 591 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 592 } 593 594 public void onServiceDisconnected(ComponentName name) { 595 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 596 } 597 }; 598 599 // Recordkeeping of restore-after-install operations that are currently in flight 600 // between the Package Manager and the Backup Manager 601 class PostInstallData { 602 public InstallArgs args; 603 public PackageInstalledInfo res; 604 605 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 606 args = _a; 607 res = _r; 608 } 609 }; 610 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 611 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 612 613 private final String mRequiredVerifierPackage; 614 615 private final PackageUsage mPackageUsage = new PackageUsage(); 616 617 private class PackageUsage { 618 private static final int WRITE_INTERVAL 619 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 620 621 private final Object mFileLock = new Object(); 622 private final AtomicLong mLastWritten = new AtomicLong(0); 623 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 624 625 private boolean mIsHistoricalPackageUsageAvailable = true; 626 627 boolean isHistoricalPackageUsageAvailable() { 628 return mIsHistoricalPackageUsageAvailable; 629 } 630 631 void write(boolean force) { 632 if (force) { 633 writeInternal(); 634 return; 635 } 636 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 637 && !DEBUG_DEXOPT) { 638 return; 639 } 640 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 641 new Thread("PackageUsage_DiskWriter") { 642 @Override 643 public void run() { 644 try { 645 writeInternal(); 646 } finally { 647 mBackgroundWriteRunning.set(false); 648 } 649 } 650 }.start(); 651 } 652 } 653 654 private void writeInternal() { 655 synchronized (mPackages) { 656 synchronized (mFileLock) { 657 AtomicFile file = getFile(); 658 FileOutputStream f = null; 659 try { 660 f = file.startWrite(); 661 BufferedOutputStream out = new BufferedOutputStream(f); 662 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 663 StringBuilder sb = new StringBuilder(); 664 for (PackageParser.Package pkg : mPackages.values()) { 665 if (pkg.mLastPackageUsageTimeInMills == 0) { 666 continue; 667 } 668 sb.setLength(0); 669 sb.append(pkg.packageName); 670 sb.append(' '); 671 sb.append((long)pkg.mLastPackageUsageTimeInMills); 672 sb.append('\n'); 673 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 674 } 675 out.flush(); 676 file.finishWrite(f); 677 } catch (IOException e) { 678 if (f != null) { 679 file.failWrite(f); 680 } 681 Log.e(TAG, "Failed to write package usage times", e); 682 } 683 } 684 } 685 mLastWritten.set(SystemClock.elapsedRealtime()); 686 } 687 688 void readLP() { 689 synchronized (mFileLock) { 690 AtomicFile file = getFile(); 691 BufferedInputStream in = null; 692 try { 693 in = new BufferedInputStream(file.openRead()); 694 StringBuffer sb = new StringBuffer(); 695 while (true) { 696 String packageName = readToken(in, sb, ' '); 697 if (packageName == null) { 698 break; 699 } 700 String timeInMillisString = readToken(in, sb, '\n'); 701 if (timeInMillisString == null) { 702 throw new IOException("Failed to find last usage time for package " 703 + packageName); 704 } 705 PackageParser.Package pkg = mPackages.get(packageName); 706 if (pkg == null) { 707 continue; 708 } 709 long timeInMillis; 710 try { 711 timeInMillis = Long.parseLong(timeInMillisString.toString()); 712 } catch (NumberFormatException e) { 713 throw new IOException("Failed to parse " + timeInMillisString 714 + " as a long.", e); 715 } 716 pkg.mLastPackageUsageTimeInMills = timeInMillis; 717 } 718 } catch (FileNotFoundException expected) { 719 mIsHistoricalPackageUsageAvailable = false; 720 } catch (IOException e) { 721 Log.w(TAG, "Failed to read package usage times", e); 722 } finally { 723 IoUtils.closeQuietly(in); 724 } 725 } 726 mLastWritten.set(SystemClock.elapsedRealtime()); 727 } 728 729 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 730 throws IOException { 731 sb.setLength(0); 732 while (true) { 733 int ch = in.read(); 734 if (ch == -1) { 735 if (sb.length() == 0) { 736 return null; 737 } 738 throw new IOException("Unexpected EOF"); 739 } 740 if (ch == endOfToken) { 741 return sb.toString(); 742 } 743 sb.append((char)ch); 744 } 745 } 746 747 private AtomicFile getFile() { 748 File dataDir = Environment.getDataDirectory(); 749 File systemDir = new File(dataDir, "system"); 750 File fname = new File(systemDir, "package-usage.list"); 751 return new AtomicFile(fname); 752 } 753 } 754 755 class PackageHandler extends Handler { 756 private boolean mBound = false; 757 final ArrayList<HandlerParams> mPendingInstalls = 758 new ArrayList<HandlerParams>(); 759 760 private boolean connectToService() { 761 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 762 " DefaultContainerService"); 763 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 764 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 765 if (mContext.bindServiceAsUser(service, mDefContainerConn, 766 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 767 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 768 mBound = true; 769 return true; 770 } 771 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 772 return false; 773 } 774 775 private void disconnectService() { 776 mContainerService = null; 777 mBound = false; 778 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 779 mContext.unbindService(mDefContainerConn); 780 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 781 } 782 783 PackageHandler(Looper looper) { 784 super(looper); 785 } 786 787 public void handleMessage(Message msg) { 788 try { 789 doHandleMessage(msg); 790 } finally { 791 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 792 } 793 } 794 795 void doHandleMessage(Message msg) { 796 switch (msg.what) { 797 case INIT_COPY: { 798 HandlerParams params = (HandlerParams) msg.obj; 799 int idx = mPendingInstalls.size(); 800 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 801 // If a bind was already initiated we dont really 802 // need to do anything. The pending install 803 // will be processed later on. 804 if (!mBound) { 805 // If this is the only one pending we might 806 // have to bind to the service again. 807 if (!connectToService()) { 808 Slog.e(TAG, "Failed to bind to media container service"); 809 params.serviceError(); 810 return; 811 } else { 812 // Once we bind to the service, the first 813 // pending request will be processed. 814 mPendingInstalls.add(idx, params); 815 } 816 } else { 817 mPendingInstalls.add(idx, params); 818 // Already bound to the service. Just make 819 // sure we trigger off processing the first request. 820 if (idx == 0) { 821 mHandler.sendEmptyMessage(MCS_BOUND); 822 } 823 } 824 break; 825 } 826 case MCS_BOUND: { 827 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 828 if (msg.obj != null) { 829 mContainerService = (IMediaContainerService) msg.obj; 830 } 831 if (mContainerService == null) { 832 // Something seriously wrong. Bail out 833 Slog.e(TAG, "Cannot bind to media container service"); 834 for (HandlerParams params : mPendingInstalls) { 835 // Indicate service bind error 836 params.serviceError(); 837 } 838 mPendingInstalls.clear(); 839 } else if (mPendingInstalls.size() > 0) { 840 HandlerParams params = mPendingInstalls.get(0); 841 if (params != null) { 842 if (params.startCopy()) { 843 // We are done... look for more work or to 844 // go idle. 845 if (DEBUG_SD_INSTALL) Log.i(TAG, 846 "Checking for more work or unbind..."); 847 // Delete pending install 848 if (mPendingInstalls.size() > 0) { 849 mPendingInstalls.remove(0); 850 } 851 if (mPendingInstalls.size() == 0) { 852 if (mBound) { 853 if (DEBUG_SD_INSTALL) Log.i(TAG, 854 "Posting delayed MCS_UNBIND"); 855 removeMessages(MCS_UNBIND); 856 Message ubmsg = obtainMessage(MCS_UNBIND); 857 // Unbind after a little delay, to avoid 858 // continual thrashing. 859 sendMessageDelayed(ubmsg, 10000); 860 } 861 } else { 862 // There are more pending requests in queue. 863 // Just post MCS_BOUND message to trigger processing 864 // of next pending install. 865 if (DEBUG_SD_INSTALL) Log.i(TAG, 866 "Posting MCS_BOUND for next work"); 867 mHandler.sendEmptyMessage(MCS_BOUND); 868 } 869 } 870 } 871 } else { 872 // Should never happen ideally. 873 Slog.w(TAG, "Empty queue"); 874 } 875 break; 876 } 877 case MCS_RECONNECT: { 878 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 879 if (mPendingInstalls.size() > 0) { 880 if (mBound) { 881 disconnectService(); 882 } 883 if (!connectToService()) { 884 Slog.e(TAG, "Failed to bind to media container service"); 885 for (HandlerParams params : mPendingInstalls) { 886 // Indicate service bind error 887 params.serviceError(); 888 } 889 mPendingInstalls.clear(); 890 } 891 } 892 break; 893 } 894 case MCS_UNBIND: { 895 // If there is no actual work left, then time to unbind. 896 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 897 898 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 899 if (mBound) { 900 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 901 902 disconnectService(); 903 } 904 } else if (mPendingInstalls.size() > 0) { 905 // There are more pending requests in queue. 906 // Just post MCS_BOUND message to trigger processing 907 // of next pending install. 908 mHandler.sendEmptyMessage(MCS_BOUND); 909 } 910 911 break; 912 } 913 case MCS_GIVE_UP: { 914 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 915 mPendingInstalls.remove(0); 916 break; 917 } 918 case SEND_PENDING_BROADCAST: { 919 String packages[]; 920 ArrayList<String> components[]; 921 int size = 0; 922 int uids[]; 923 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 924 synchronized (mPackages) { 925 if (mPendingBroadcasts == null) { 926 return; 927 } 928 size = mPendingBroadcasts.size(); 929 if (size <= 0) { 930 // Nothing to be done. Just return 931 return; 932 } 933 packages = new String[size]; 934 components = new ArrayList[size]; 935 uids = new int[size]; 936 int i = 0; // filling out the above arrays 937 938 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 939 int packageUserId = mPendingBroadcasts.userIdAt(n); 940 Iterator<Map.Entry<String, ArrayList<String>>> it 941 = mPendingBroadcasts.packagesForUserId(packageUserId) 942 .entrySet().iterator(); 943 while (it.hasNext() && i < size) { 944 Map.Entry<String, ArrayList<String>> ent = it.next(); 945 packages[i] = ent.getKey(); 946 components[i] = ent.getValue(); 947 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 948 uids[i] = (ps != null) 949 ? UserHandle.getUid(packageUserId, ps.appId) 950 : -1; 951 i++; 952 } 953 } 954 size = i; 955 mPendingBroadcasts.clear(); 956 } 957 // Send broadcasts 958 for (int i = 0; i < size; i++) { 959 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 960 } 961 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 962 break; 963 } 964 case START_CLEANING_PACKAGE: { 965 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 966 final String packageName = (String)msg.obj; 967 final int userId = msg.arg1; 968 final boolean andCode = msg.arg2 != 0; 969 synchronized (mPackages) { 970 if (userId == UserHandle.USER_ALL) { 971 int[] users = sUserManager.getUserIds(); 972 for (int user : users) { 973 mSettings.addPackageToCleanLPw( 974 new PackageCleanItem(user, packageName, andCode)); 975 } 976 } else { 977 mSettings.addPackageToCleanLPw( 978 new PackageCleanItem(userId, packageName, andCode)); 979 } 980 } 981 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 982 startCleaningPackages(); 983 } break; 984 case POST_INSTALL: { 985 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 986 PostInstallData data = mRunningInstalls.get(msg.arg1); 987 mRunningInstalls.delete(msg.arg1); 988 boolean deleteOld = false; 989 990 if (data != null) { 991 InstallArgs args = data.args; 992 PackageInstalledInfo res = data.res; 993 994 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 995 res.removedInfo.sendBroadcast(false, true, false); 996 Bundle extras = new Bundle(1); 997 extras.putInt(Intent.EXTRA_UID, res.uid); 998 // Determine the set of users who are adding this 999 // package for the first time vs. those who are seeing 1000 // an update. 1001 int[] firstUsers; 1002 int[] updateUsers = new int[0]; 1003 if (res.origUsers == null || res.origUsers.length == 0) { 1004 firstUsers = res.newUsers; 1005 } else { 1006 firstUsers = new int[0]; 1007 for (int i=0; i<res.newUsers.length; i++) { 1008 int user = res.newUsers[i]; 1009 boolean isNew = true; 1010 for (int j=0; j<res.origUsers.length; j++) { 1011 if (res.origUsers[j] == user) { 1012 isNew = false; 1013 break; 1014 } 1015 } 1016 if (isNew) { 1017 int[] newFirst = new int[firstUsers.length+1]; 1018 System.arraycopy(firstUsers, 0, newFirst, 0, 1019 firstUsers.length); 1020 newFirst[firstUsers.length] = user; 1021 firstUsers = newFirst; 1022 } else { 1023 int[] newUpdate = new int[updateUsers.length+1]; 1024 System.arraycopy(updateUsers, 0, newUpdate, 0, 1025 updateUsers.length); 1026 newUpdate[updateUsers.length] = user; 1027 updateUsers = newUpdate; 1028 } 1029 } 1030 } 1031 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1032 res.pkg.applicationInfo.packageName, 1033 extras, null, null, firstUsers); 1034 final boolean update = res.removedInfo.removedPackage != null; 1035 if (update) { 1036 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1037 } 1038 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1039 res.pkg.applicationInfo.packageName, 1040 extras, null, null, updateUsers); 1041 if (update) { 1042 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1043 res.pkg.applicationInfo.packageName, 1044 extras, null, null, updateUsers); 1045 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1046 null, null, 1047 res.pkg.applicationInfo.packageName, null, updateUsers); 1048 1049 // treat asec-hosted packages like removable media on upgrade 1050 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1051 if (DEBUG_INSTALL) { 1052 Slog.i(TAG, "upgrading pkg " + res.pkg 1053 + " is ASEC-hosted -> AVAILABLE"); 1054 } 1055 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1056 ArrayList<String> pkgList = new ArrayList<String>(1); 1057 pkgList.add(res.pkg.applicationInfo.packageName); 1058 sendResourcesChangedBroadcast(true, true, 1059 pkgList,uidArray, null); 1060 } 1061 } 1062 if (res.removedInfo.args != null) { 1063 // Remove the replaced package's older resources safely now 1064 deleteOld = true; 1065 } 1066 1067 // Log current value of "unknown sources" setting 1068 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1069 getUnknownSourcesSettings()); 1070 } 1071 // Force a gc to clear up things 1072 Runtime.getRuntime().gc(); 1073 // We delete after a gc for applications on sdcard. 1074 if (deleteOld) { 1075 synchronized (mInstallLock) { 1076 res.removedInfo.args.doPostDeleteLI(true); 1077 } 1078 } 1079 if (args.observer != null) { 1080 try { 1081 Bundle extras = extrasForInstallResult(res); 1082 args.observer.onPackageInstalled(res.name, res.returnCode, 1083 res.returnMsg, extras); 1084 } catch (RemoteException e) { 1085 Slog.i(TAG, "Observer no longer exists."); 1086 } 1087 } 1088 } else { 1089 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1090 } 1091 } break; 1092 case UPDATED_MEDIA_STATUS: { 1093 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1094 boolean reportStatus = msg.arg1 == 1; 1095 boolean doGc = msg.arg2 == 1; 1096 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1097 if (doGc) { 1098 // Force a gc to clear up stale containers. 1099 Runtime.getRuntime().gc(); 1100 } 1101 if (msg.obj != null) { 1102 @SuppressWarnings("unchecked") 1103 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1104 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1105 // Unload containers 1106 unloadAllContainers(args); 1107 } 1108 if (reportStatus) { 1109 try { 1110 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1111 PackageHelper.getMountService().finishMediaUpdate(); 1112 } catch (RemoteException e) { 1113 Log.e(TAG, "MountService not running?"); 1114 } 1115 } 1116 } break; 1117 case WRITE_SETTINGS: { 1118 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1119 synchronized (mPackages) { 1120 removeMessages(WRITE_SETTINGS); 1121 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1122 mSettings.writeLPr(); 1123 mDirtyUsers.clear(); 1124 } 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } break; 1127 case WRITE_PACKAGE_RESTRICTIONS: { 1128 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1129 synchronized (mPackages) { 1130 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1131 for (int userId : mDirtyUsers) { 1132 mSettings.writePackageRestrictionsLPr(userId); 1133 } 1134 mDirtyUsers.clear(); 1135 } 1136 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1137 } break; 1138 case CHECK_PENDING_VERIFICATION: { 1139 final int verificationId = msg.arg1; 1140 final PackageVerificationState state = mPendingVerification.get(verificationId); 1141 1142 if ((state != null) && !state.timeoutExtended()) { 1143 final InstallArgs args = state.getInstallArgs(); 1144 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1145 1146 Slog.i(TAG, "Verification timed out for " + originUri); 1147 mPendingVerification.remove(verificationId); 1148 1149 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1150 1151 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1152 Slog.i(TAG, "Continuing with installation of " + originUri); 1153 state.setVerifierResponse(Binder.getCallingUid(), 1154 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1155 broadcastPackageVerified(verificationId, originUri, 1156 PackageManager.VERIFICATION_ALLOW, 1157 state.getInstallArgs().getUser()); 1158 try { 1159 ret = args.copyApk(mContainerService, true); 1160 } catch (RemoteException e) { 1161 Slog.e(TAG, "Could not contact the ContainerService"); 1162 } 1163 } else { 1164 broadcastPackageVerified(verificationId, originUri, 1165 PackageManager.VERIFICATION_REJECT, 1166 state.getInstallArgs().getUser()); 1167 } 1168 1169 processPendingInstall(args, ret); 1170 mHandler.sendEmptyMessage(MCS_UNBIND); 1171 } 1172 break; 1173 } 1174 case PACKAGE_VERIFIED: { 1175 final int verificationId = msg.arg1; 1176 1177 final PackageVerificationState state = mPendingVerification.get(verificationId); 1178 if (state == null) { 1179 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1180 break; 1181 } 1182 1183 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1184 1185 state.setVerifierResponse(response.callerUid, response.code); 1186 1187 if (state.isVerificationComplete()) { 1188 mPendingVerification.remove(verificationId); 1189 1190 final InstallArgs args = state.getInstallArgs(); 1191 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1192 1193 int ret; 1194 if (state.isInstallAllowed()) { 1195 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1196 broadcastPackageVerified(verificationId, originUri, 1197 response.code, state.getInstallArgs().getUser()); 1198 try { 1199 ret = args.copyApk(mContainerService, true); 1200 } catch (RemoteException e) { 1201 Slog.e(TAG, "Could not contact the ContainerService"); 1202 } 1203 } else { 1204 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1205 } 1206 1207 processPendingInstall(args, ret); 1208 1209 mHandler.sendEmptyMessage(MCS_UNBIND); 1210 } 1211 1212 break; 1213 } 1214 } 1215 } 1216 } 1217 1218 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1219 Bundle extras = null; 1220 switch (res.returnCode) { 1221 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1222 extras = new Bundle(); 1223 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1224 res.origPermission); 1225 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1226 res.origPackage); 1227 break; 1228 } 1229 } 1230 return extras; 1231 } 1232 1233 void scheduleWriteSettingsLocked() { 1234 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1235 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1236 } 1237 } 1238 1239 void scheduleWritePackageRestrictionsLocked(int userId) { 1240 if (!sUserManager.exists(userId)) return; 1241 mDirtyUsers.add(userId); 1242 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1243 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1244 } 1245 } 1246 1247 public static final PackageManagerService main(Context context, Installer installer, 1248 boolean factoryTest, boolean onlyCore) { 1249 PackageManagerService m = new PackageManagerService(context, installer, 1250 factoryTest, onlyCore); 1251 ServiceManager.addService("package", m); 1252 return m; 1253 } 1254 1255 static String[] splitString(String str, char sep) { 1256 int count = 1; 1257 int i = 0; 1258 while ((i=str.indexOf(sep, i)) >= 0) { 1259 count++; 1260 i++; 1261 } 1262 1263 String[] res = new String[count]; 1264 i=0; 1265 count = 0; 1266 int lastI=0; 1267 while ((i=str.indexOf(sep, i)) >= 0) { 1268 res[count] = str.substring(lastI, i); 1269 count++; 1270 i++; 1271 lastI = i; 1272 } 1273 res[count] = str.substring(lastI, str.length()); 1274 return res; 1275 } 1276 1277 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1278 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1279 Context.DISPLAY_SERVICE); 1280 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1281 } 1282 1283 public PackageManagerService(Context context, Installer installer, 1284 boolean factoryTest, boolean onlyCore) { 1285 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1286 SystemClock.uptimeMillis()); 1287 1288 if (mSdkVersion <= 0) { 1289 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1290 } 1291 1292 mContext = context; 1293 mFactoryTest = factoryTest; 1294 mOnlyCore = onlyCore; 1295 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1296 mMetrics = new DisplayMetrics(); 1297 mSettings = new Settings(context); 1298 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1299 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1300 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1301 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1302 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1303 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1304 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1305 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1306 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1307 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1308 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1309 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1310 1311 // TODO: add a property to control this? 1312 long dexOptLRUThresholdInMinutes; 1313 if (mLazyDexOpt) { 1314 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1315 } else { 1316 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1317 } 1318 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1319 1320 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1321 if (separateProcesses != null && separateProcesses.length() > 0) { 1322 if ("*".equals(separateProcesses)) { 1323 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1324 mSeparateProcesses = null; 1325 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1326 } else { 1327 mDefParseFlags = 0; 1328 mSeparateProcesses = separateProcesses.split(","); 1329 Slog.w(TAG, "Running with debug.separate_processes: " 1330 + separateProcesses); 1331 } 1332 } else { 1333 mDefParseFlags = 0; 1334 mSeparateProcesses = null; 1335 } 1336 1337 mInstaller = installer; 1338 mPackageDexOptimizer = new PackageDexOptimizer(this); 1339 1340 getDefaultDisplayMetrics(context, mMetrics); 1341 1342 SystemConfig systemConfig = SystemConfig.getInstance(); 1343 mGlobalGids = systemConfig.getGlobalGids(); 1344 mSystemPermissions = systemConfig.getSystemPermissions(); 1345 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1346 1347 synchronized (mInstallLock) { 1348 // writer 1349 synchronized (mPackages) { 1350 mHandlerThread = new ServiceThread(TAG, 1351 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1352 mHandlerThread.start(); 1353 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1354 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1355 1356 File dataDir = Environment.getDataDirectory(); 1357 mAppDataDir = new File(dataDir, "data"); 1358 mAppInstallDir = new File(dataDir, "app"); 1359 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1360 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1361 mUserAppDataDir = new File(dataDir, "user"); 1362 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1363 1364 sUserManager = new UserManagerService(context, this, 1365 mInstallLock, mPackages); 1366 1367 // Propagate permission configuration in to package manager. 1368 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1369 = systemConfig.getPermissions(); 1370 for (int i=0; i<permConfig.size(); i++) { 1371 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1372 BasePermission bp = mSettings.mPermissions.get(perm.name); 1373 if (bp == null) { 1374 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1375 mSettings.mPermissions.put(perm.name, bp); 1376 } 1377 if (perm.gids != null) { 1378 bp.gids = appendInts(bp.gids, perm.gids); 1379 } 1380 } 1381 1382 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1383 for (int i=0; i<libConfig.size(); i++) { 1384 mSharedLibraries.put(libConfig.keyAt(i), 1385 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1386 } 1387 1388 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1389 1390 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1391 mSdkVersion, mOnlyCore); 1392 1393 String customResolverActivity = Resources.getSystem().getString( 1394 R.string.config_customResolverActivity); 1395 if (TextUtils.isEmpty(customResolverActivity)) { 1396 customResolverActivity = null; 1397 } else { 1398 mCustomResolverComponentName = ComponentName.unflattenFromString( 1399 customResolverActivity); 1400 } 1401 1402 long startTime = SystemClock.uptimeMillis(); 1403 1404 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1405 startTime); 1406 1407 // Set flag to monitor and not change apk file paths when 1408 // scanning install directories. 1409 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1410 1411 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1412 1413 /** 1414 * Add everything in the in the boot class path to the 1415 * list of process files because dexopt will have been run 1416 * if necessary during zygote startup. 1417 */ 1418 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1419 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1420 1421 if (bootClassPath != null) { 1422 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1423 for (String element : bootClassPathElements) { 1424 alreadyDexOpted.add(element); 1425 } 1426 } else { 1427 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1428 } 1429 1430 if (systemServerClassPath != null) { 1431 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1432 for (String element : systemServerClassPathElements) { 1433 alreadyDexOpted.add(element); 1434 } 1435 } else { 1436 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1437 } 1438 1439 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1440 final String[] dexCodeInstructionSets = 1441 getDexCodeInstructionSets( 1442 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1443 1444 /** 1445 * Ensure all external libraries have had dexopt run on them. 1446 */ 1447 if (mSharedLibraries.size() > 0) { 1448 // NOTE: For now, we're compiling these system "shared libraries" 1449 // (and framework jars) into all available architectures. It's possible 1450 // to compile them only when we come across an app that uses them (there's 1451 // already logic for that in scanPackageLI) but that adds some complexity. 1452 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1453 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1454 final String lib = libEntry.path; 1455 if (lib == null) { 1456 continue; 1457 } 1458 1459 try { 1460 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1461 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1462 alreadyDexOpted.add(lib); 1463 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1464 } 1465 } catch (FileNotFoundException e) { 1466 Slog.w(TAG, "Library not found: " + lib); 1467 } catch (IOException e) { 1468 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1469 + e.getMessage()); 1470 } 1471 } 1472 } 1473 } 1474 1475 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1476 1477 // Gross hack for now: we know this file doesn't contain any 1478 // code, so don't dexopt it to avoid the resulting log spew. 1479 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1480 1481 // Gross hack for now: we know this file is only part of 1482 // the boot class path for art, so don't dexopt it to 1483 // avoid the resulting log spew. 1484 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1485 1486 /** 1487 * And there are a number of commands implemented in Java, which 1488 * we currently need to do the dexopt on so that they can be 1489 * run from a non-root shell. 1490 */ 1491 String[] frameworkFiles = frameworkDir.list(); 1492 if (frameworkFiles != null) { 1493 // TODO: We could compile these only for the most preferred ABI. We should 1494 // first double check that the dex files for these commands are not referenced 1495 // by other system apps. 1496 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1497 for (int i=0; i<frameworkFiles.length; i++) { 1498 File libPath = new File(frameworkDir, frameworkFiles[i]); 1499 String path = libPath.getPath(); 1500 // Skip the file if we already did it. 1501 if (alreadyDexOpted.contains(path)) { 1502 continue; 1503 } 1504 // Skip the file if it is not a type we want to dexopt. 1505 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1506 continue; 1507 } 1508 try { 1509 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1510 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1511 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1512 } 1513 } catch (FileNotFoundException e) { 1514 Slog.w(TAG, "Jar not found: " + path); 1515 } catch (IOException e) { 1516 Slog.w(TAG, "Exception reading jar: " + path, e); 1517 } 1518 } 1519 } 1520 } 1521 1522 // Collect vendor overlay packages. 1523 // (Do this before scanning any apps.) 1524 // For security and version matching reason, only consider 1525 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1526 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1527 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1528 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1529 1530 // Find base frameworks (resource packages without code). 1531 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1532 | PackageParser.PARSE_IS_SYSTEM_DIR 1533 | PackageParser.PARSE_IS_PRIVILEGED, 1534 scanFlags | SCAN_NO_DEX, 0); 1535 1536 // Collected privileged system packages. 1537 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1538 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1539 | PackageParser.PARSE_IS_SYSTEM_DIR 1540 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1541 1542 // Collect ordinary system packages. 1543 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1544 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1545 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1546 1547 // Collect all vendor packages. 1548 File vendorAppDir = new File("/vendor/app"); 1549 try { 1550 vendorAppDir = vendorAppDir.getCanonicalFile(); 1551 } catch (IOException e) { 1552 // failed to look up canonical path, continue with original one 1553 } 1554 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1555 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1556 1557 // Collect all OEM packages. 1558 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1559 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1560 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1561 1562 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1563 mInstaller.moveFiles(); 1564 1565 // Prune any system packages that no longer exist. 1566 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1567 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1568 if (!mOnlyCore) { 1569 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1570 while (psit.hasNext()) { 1571 PackageSetting ps = psit.next(); 1572 1573 /* 1574 * If this is not a system app, it can't be a 1575 * disable system app. 1576 */ 1577 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1578 continue; 1579 } 1580 1581 /* 1582 * If the package is scanned, it's not erased. 1583 */ 1584 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1585 if (scannedPkg != null) { 1586 /* 1587 * If the system app is both scanned and in the 1588 * disabled packages list, then it must have been 1589 * added via OTA. Remove it from the currently 1590 * scanned package so the previously user-installed 1591 * application can be scanned. 1592 */ 1593 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1594 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1595 + ps.name + "; removing system app. Last known codePath=" 1596 + ps.codePathString + ", installStatus=" + ps.installStatus 1597 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1598 + scannedPkg.mVersionCode); 1599 removePackageLI(ps, true); 1600 expectingBetter.put(ps.name, ps.codePath); 1601 } 1602 1603 continue; 1604 } 1605 1606 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1607 psit.remove(); 1608 logCriticalInfo(Log.WARN, "System package " + ps.name 1609 + " no longer exists; wiping its data"); 1610 removeDataDirsLI(ps.name); 1611 } else { 1612 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1613 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1614 possiblyDeletedUpdatedSystemApps.add(ps.name); 1615 } 1616 } 1617 } 1618 } 1619 1620 //look for any incomplete package installations 1621 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1622 //clean up list 1623 for(int i = 0; i < deletePkgsList.size(); i++) { 1624 //clean up here 1625 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1626 } 1627 //delete tmp files 1628 deleteTempPackageFiles(); 1629 1630 // Remove any shared userIDs that have no associated packages 1631 mSettings.pruneSharedUsersLPw(); 1632 1633 if (!mOnlyCore) { 1634 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1635 SystemClock.uptimeMillis()); 1636 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1637 1638 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1639 scanFlags, 0); 1640 1641 /** 1642 * Remove disable package settings for any updated system 1643 * apps that were removed via an OTA. If they're not a 1644 * previously-updated app, remove them completely. 1645 * Otherwise, just revoke their system-level permissions. 1646 */ 1647 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1648 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1649 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1650 1651 String msg; 1652 if (deletedPkg == null) { 1653 msg = "Updated system package " + deletedAppName 1654 + " no longer exists; wiping its data"; 1655 removeDataDirsLI(deletedAppName); 1656 } else { 1657 msg = "Updated system app + " + deletedAppName 1658 + " no longer present; removing system privileges for " 1659 + deletedAppName; 1660 1661 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1662 1663 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1664 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1665 } 1666 logCriticalInfo(Log.WARN, msg); 1667 } 1668 1669 /** 1670 * Make sure all system apps that we expected to appear on 1671 * the userdata partition actually showed up. If they never 1672 * appeared, crawl back and revive the system version. 1673 */ 1674 for (int i = 0; i < expectingBetter.size(); i++) { 1675 final String packageName = expectingBetter.keyAt(i); 1676 if (!mPackages.containsKey(packageName)) { 1677 final File scanFile = expectingBetter.valueAt(i); 1678 1679 logCriticalInfo(Log.WARN, "Expected better " + packageName 1680 + " but never showed up; reverting to system"); 1681 1682 final int reparseFlags; 1683 if (FileUtils.contains(privilegedAppDir, scanFile)) { 1684 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1685 | PackageParser.PARSE_IS_SYSTEM_DIR 1686 | PackageParser.PARSE_IS_PRIVILEGED; 1687 } else if (FileUtils.contains(systemAppDir, scanFile)) { 1688 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1689 | PackageParser.PARSE_IS_SYSTEM_DIR; 1690 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 1691 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1692 | PackageParser.PARSE_IS_SYSTEM_DIR; 1693 } else if (FileUtils.contains(oemAppDir, scanFile)) { 1694 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1695 | PackageParser.PARSE_IS_SYSTEM_DIR; 1696 } else { 1697 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 1698 continue; 1699 } 1700 1701 mSettings.enableSystemPackageLPw(packageName); 1702 1703 try { 1704 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 1705 } catch (PackageManagerException e) { 1706 Slog.e(TAG, "Failed to parse original system package: " 1707 + e.getMessage()); 1708 } 1709 } 1710 } 1711 } 1712 1713 // Now that we know all of the shared libraries, update all clients to have 1714 // the correct library paths. 1715 updateAllSharedLibrariesLPw(); 1716 1717 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1718 // NOTE: We ignore potential failures here during a system scan (like 1719 // the rest of the commands above) because there's precious little we 1720 // can do about it. A settings error is reported, though. 1721 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1722 false /* force dexopt */, false /* defer dexopt */); 1723 } 1724 1725 // Now that we know all the packages we are keeping, 1726 // read and update their last usage times. 1727 mPackageUsage.readLP(); 1728 1729 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1730 SystemClock.uptimeMillis()); 1731 Slog.i(TAG, "Time to scan packages: " 1732 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1733 + " seconds"); 1734 1735 // If the platform SDK has changed since the last time we booted, 1736 // we need to re-grant app permission to catch any new ones that 1737 // appear. This is really a hack, and means that apps can in some 1738 // cases get permissions that the user didn't initially explicitly 1739 // allow... it would be nice to have some better way to handle 1740 // this situation. 1741 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1742 != mSdkVersion; 1743 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1744 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1745 + "; regranting permissions for internal storage"); 1746 mSettings.mInternalSdkPlatform = mSdkVersion; 1747 1748 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1749 | (regrantPermissions 1750 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1751 : 0)); 1752 1753 // If this is the first boot, and it is a normal boot, then 1754 // we need to initialize the default preferred apps. 1755 if (!mRestoredSettings && !onlyCore) { 1756 mSettings.readDefaultPreferredAppsLPw(this, 0); 1757 } 1758 1759 // If this is first boot after an OTA, and a normal boot, then 1760 // we need to clear code cache directories. 1761 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 1762 if (mIsUpgrade && !onlyCore) { 1763 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1764 for (String pkgName : mSettings.mPackages.keySet()) { 1765 deleteCodeCacheDirsLI(pkgName); 1766 } 1767 mSettings.mFingerprint = Build.FINGERPRINT; 1768 } 1769 1770 // All the changes are done during package scanning. 1771 mSettings.updateInternalDatabaseVersion(); 1772 1773 // can downgrade to reader 1774 mSettings.writeLPr(); 1775 1776 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1777 SystemClock.uptimeMillis()); 1778 1779 1780 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1781 } // synchronized (mPackages) 1782 } // synchronized (mInstallLock) 1783 1784 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1785 1786 // Now after opening every single application zip, make sure they 1787 // are all flushed. Not really needed, but keeps things nice and 1788 // tidy. 1789 Runtime.getRuntime().gc(); 1790 } 1791 1792 @Override 1793 public boolean isFirstBoot() { 1794 return !mRestoredSettings; 1795 } 1796 1797 @Override 1798 public boolean isOnlyCoreApps() { 1799 return mOnlyCore; 1800 } 1801 1802 @Override 1803 public boolean isUpgrade() { 1804 return mIsUpgrade; 1805 } 1806 1807 private String getRequiredVerifierLPr() { 1808 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1809 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1810 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1811 1812 String requiredVerifier = null; 1813 1814 final int N = receivers.size(); 1815 for (int i = 0; i < N; i++) { 1816 final ResolveInfo info = receivers.get(i); 1817 1818 if (info.activityInfo == null) { 1819 continue; 1820 } 1821 1822 final String packageName = info.activityInfo.packageName; 1823 1824 final PackageSetting ps = mSettings.mPackages.get(packageName); 1825 if (ps == null) { 1826 continue; 1827 } 1828 1829 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1830 if (!gp.grantedPermissions 1831 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1832 continue; 1833 } 1834 1835 if (requiredVerifier != null) { 1836 throw new RuntimeException("There can be only one required verifier"); 1837 } 1838 1839 requiredVerifier = packageName; 1840 } 1841 1842 return requiredVerifier; 1843 } 1844 1845 @Override 1846 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1847 throws RemoteException { 1848 try { 1849 return super.onTransact(code, data, reply, flags); 1850 } catch (RuntimeException e) { 1851 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1852 Slog.wtf(TAG, "Package Manager Crash", e); 1853 } 1854 throw e; 1855 } 1856 } 1857 1858 void cleanupInstallFailedPackage(PackageSetting ps) { 1859 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1860 1861 removeDataDirsLI(ps.name); 1862 if (ps.codePath != null) { 1863 if (ps.codePath.isDirectory()) { 1864 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 1865 } else { 1866 ps.codePath.delete(); 1867 } 1868 } 1869 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1870 if (ps.resourcePath.isDirectory()) { 1871 FileUtils.deleteContents(ps.resourcePath); 1872 } 1873 ps.resourcePath.delete(); 1874 } 1875 mSettings.removePackageLPw(ps.name); 1876 } 1877 1878 static int[] appendInts(int[] cur, int[] add) { 1879 if (add == null) return cur; 1880 if (cur == null) return add; 1881 final int N = add.length; 1882 for (int i=0; i<N; i++) { 1883 cur = appendInt(cur, add[i]); 1884 } 1885 return cur; 1886 } 1887 1888 static int[] removeInts(int[] cur, int[] rem) { 1889 if (rem == null) return cur; 1890 if (cur == null) return cur; 1891 final int N = rem.length; 1892 for (int i=0; i<N; i++) { 1893 cur = removeInt(cur, rem[i]); 1894 } 1895 return cur; 1896 } 1897 1898 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1899 if (!sUserManager.exists(userId)) return null; 1900 final PackageSetting ps = (PackageSetting) p.mExtras; 1901 if (ps == null) { 1902 return null; 1903 } 1904 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1905 final PackageUserState state = ps.readUserState(userId); 1906 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1907 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1908 state, userId); 1909 } 1910 1911 @Override 1912 public boolean isPackageAvailable(String packageName, int userId) { 1913 if (!sUserManager.exists(userId)) return false; 1914 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1915 synchronized (mPackages) { 1916 PackageParser.Package p = mPackages.get(packageName); 1917 if (p != null) { 1918 final PackageSetting ps = (PackageSetting) p.mExtras; 1919 if (ps != null) { 1920 final PackageUserState state = ps.readUserState(userId); 1921 if (state != null) { 1922 return PackageParser.isAvailable(state); 1923 } 1924 } 1925 } 1926 } 1927 return false; 1928 } 1929 1930 @Override 1931 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1932 if (!sUserManager.exists(userId)) return null; 1933 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1934 // reader 1935 synchronized (mPackages) { 1936 PackageParser.Package p = mPackages.get(packageName); 1937 if (DEBUG_PACKAGE_INFO) 1938 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1939 if (p != null) { 1940 return generatePackageInfo(p, flags, userId); 1941 } 1942 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1943 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1944 } 1945 } 1946 return null; 1947 } 1948 1949 @Override 1950 public String[] currentToCanonicalPackageNames(String[] names) { 1951 String[] out = new String[names.length]; 1952 // reader 1953 synchronized (mPackages) { 1954 for (int i=names.length-1; i>=0; i--) { 1955 PackageSetting ps = mSettings.mPackages.get(names[i]); 1956 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1957 } 1958 } 1959 return out; 1960 } 1961 1962 @Override 1963 public String[] canonicalToCurrentPackageNames(String[] names) { 1964 String[] out = new String[names.length]; 1965 // reader 1966 synchronized (mPackages) { 1967 for (int i=names.length-1; i>=0; i--) { 1968 String cur = mSettings.mRenamedPackages.get(names[i]); 1969 out[i] = cur != null ? cur : names[i]; 1970 } 1971 } 1972 return out; 1973 } 1974 1975 @Override 1976 public int getPackageUid(String packageName, int userId) { 1977 if (!sUserManager.exists(userId)) return -1; 1978 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1979 // reader 1980 synchronized (mPackages) { 1981 PackageParser.Package p = mPackages.get(packageName); 1982 if(p != null) { 1983 return UserHandle.getUid(userId, p.applicationInfo.uid); 1984 } 1985 PackageSetting ps = mSettings.mPackages.get(packageName); 1986 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1987 return -1; 1988 } 1989 p = ps.pkg; 1990 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1991 } 1992 } 1993 1994 @Override 1995 public int[] getPackageGids(String packageName) { 1996 // reader 1997 synchronized (mPackages) { 1998 PackageParser.Package p = mPackages.get(packageName); 1999 if (DEBUG_PACKAGE_INFO) 2000 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2001 if (p != null) { 2002 final PackageSetting ps = (PackageSetting)p.mExtras; 2003 return ps.getGids(); 2004 } 2005 } 2006 // stupid thing to indicate an error. 2007 return new int[0]; 2008 } 2009 2010 static final PermissionInfo generatePermissionInfo( 2011 BasePermission bp, int flags) { 2012 if (bp.perm != null) { 2013 return PackageParser.generatePermissionInfo(bp.perm, flags); 2014 } 2015 PermissionInfo pi = new PermissionInfo(); 2016 pi.name = bp.name; 2017 pi.packageName = bp.sourcePackage; 2018 pi.nonLocalizedLabel = bp.name; 2019 pi.protectionLevel = bp.protectionLevel; 2020 return pi; 2021 } 2022 2023 @Override 2024 public PermissionInfo getPermissionInfo(String name, int flags) { 2025 // reader 2026 synchronized (mPackages) { 2027 final BasePermission p = mSettings.mPermissions.get(name); 2028 if (p != null) { 2029 return generatePermissionInfo(p, flags); 2030 } 2031 return null; 2032 } 2033 } 2034 2035 @Override 2036 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2037 // reader 2038 synchronized (mPackages) { 2039 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2040 for (BasePermission p : mSettings.mPermissions.values()) { 2041 if (group == null) { 2042 if (p.perm == null || p.perm.info.group == null) { 2043 out.add(generatePermissionInfo(p, flags)); 2044 } 2045 } else { 2046 if (p.perm != null && group.equals(p.perm.info.group)) { 2047 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2048 } 2049 } 2050 } 2051 2052 if (out.size() > 0) { 2053 return out; 2054 } 2055 return mPermissionGroups.containsKey(group) ? out : null; 2056 } 2057 } 2058 2059 @Override 2060 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2061 // reader 2062 synchronized (mPackages) { 2063 return PackageParser.generatePermissionGroupInfo( 2064 mPermissionGroups.get(name), flags); 2065 } 2066 } 2067 2068 @Override 2069 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2070 // reader 2071 synchronized (mPackages) { 2072 final int N = mPermissionGroups.size(); 2073 ArrayList<PermissionGroupInfo> out 2074 = new ArrayList<PermissionGroupInfo>(N); 2075 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2076 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2077 } 2078 return out; 2079 } 2080 } 2081 2082 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2083 int userId) { 2084 if (!sUserManager.exists(userId)) return null; 2085 PackageSetting ps = mSettings.mPackages.get(packageName); 2086 if (ps != null) { 2087 if (ps.pkg == null) { 2088 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2089 flags, userId); 2090 if (pInfo != null) { 2091 return pInfo.applicationInfo; 2092 } 2093 return null; 2094 } 2095 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2096 ps.readUserState(userId), userId); 2097 } 2098 return null; 2099 } 2100 2101 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2102 int userId) { 2103 if (!sUserManager.exists(userId)) return null; 2104 PackageSetting ps = mSettings.mPackages.get(packageName); 2105 if (ps != null) { 2106 PackageParser.Package pkg = ps.pkg; 2107 if (pkg == null) { 2108 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2109 return null; 2110 } 2111 // Only data remains, so we aren't worried about code paths 2112 pkg = new PackageParser.Package(packageName); 2113 pkg.applicationInfo.packageName = packageName; 2114 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2115 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2116 pkg.applicationInfo.dataDir = 2117 getDataPathForPackage(packageName, 0).getPath(); 2118 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2119 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2120 } 2121 return generatePackageInfo(pkg, flags, userId); 2122 } 2123 return null; 2124 } 2125 2126 @Override 2127 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2128 if (!sUserManager.exists(userId)) return null; 2129 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2130 // writer 2131 synchronized (mPackages) { 2132 PackageParser.Package p = mPackages.get(packageName); 2133 if (DEBUG_PACKAGE_INFO) Log.v( 2134 TAG, "getApplicationInfo " + packageName 2135 + ": " + p); 2136 if (p != null) { 2137 PackageSetting ps = mSettings.mPackages.get(packageName); 2138 if (ps == null) return null; 2139 // Note: isEnabledLP() does not apply here - always return info 2140 return PackageParser.generateApplicationInfo( 2141 p, flags, ps.readUserState(userId), userId); 2142 } 2143 if ("android".equals(packageName)||"system".equals(packageName)) { 2144 return mAndroidApplication; 2145 } 2146 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2147 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2148 } 2149 } 2150 return null; 2151 } 2152 2153 2154 @Override 2155 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2156 mContext.enforceCallingOrSelfPermission( 2157 android.Manifest.permission.CLEAR_APP_CACHE, null); 2158 // Queue up an async operation since clearing cache may take a little while. 2159 mHandler.post(new Runnable() { 2160 public void run() { 2161 mHandler.removeCallbacks(this); 2162 int retCode = -1; 2163 synchronized (mInstallLock) { 2164 retCode = mInstaller.freeCache(freeStorageSize); 2165 if (retCode < 0) { 2166 Slog.w(TAG, "Couldn't clear application caches"); 2167 } 2168 } 2169 if (observer != null) { 2170 try { 2171 observer.onRemoveCompleted(null, (retCode >= 0)); 2172 } catch (RemoteException e) { 2173 Slog.w(TAG, "RemoveException when invoking call back"); 2174 } 2175 } 2176 } 2177 }); 2178 } 2179 2180 @Override 2181 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2182 mContext.enforceCallingOrSelfPermission( 2183 android.Manifest.permission.CLEAR_APP_CACHE, null); 2184 // Queue up an async operation since clearing cache may take a little while. 2185 mHandler.post(new Runnable() { 2186 public void run() { 2187 mHandler.removeCallbacks(this); 2188 int retCode = -1; 2189 synchronized (mInstallLock) { 2190 retCode = mInstaller.freeCache(freeStorageSize); 2191 if (retCode < 0) { 2192 Slog.w(TAG, "Couldn't clear application caches"); 2193 } 2194 } 2195 if(pi != null) { 2196 try { 2197 // Callback via pending intent 2198 int code = (retCode >= 0) ? 1 : 0; 2199 pi.sendIntent(null, code, null, 2200 null, null); 2201 } catch (SendIntentException e1) { 2202 Slog.i(TAG, "Failed to send pending intent"); 2203 } 2204 } 2205 } 2206 }); 2207 } 2208 2209 void freeStorage(long freeStorageSize) throws IOException { 2210 synchronized (mInstallLock) { 2211 if (mInstaller.freeCache(freeStorageSize) < 0) { 2212 throw new IOException("Failed to free enough space"); 2213 } 2214 } 2215 } 2216 2217 @Override 2218 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2219 if (!sUserManager.exists(userId)) return null; 2220 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2221 synchronized (mPackages) { 2222 PackageParser.Activity a = mActivities.mActivities.get(component); 2223 2224 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2225 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2226 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2227 if (ps == null) return null; 2228 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2229 userId); 2230 } 2231 if (mResolveComponentName.equals(component)) { 2232 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2233 new PackageUserState(), userId); 2234 } 2235 } 2236 return null; 2237 } 2238 2239 @Override 2240 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2241 String resolvedType) { 2242 synchronized (mPackages) { 2243 PackageParser.Activity a = mActivities.mActivities.get(component); 2244 if (a == null) { 2245 return false; 2246 } 2247 for (int i=0; i<a.intents.size(); i++) { 2248 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2249 intent.getData(), intent.getCategories(), TAG) >= 0) { 2250 return true; 2251 } 2252 } 2253 return false; 2254 } 2255 } 2256 2257 @Override 2258 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2259 if (!sUserManager.exists(userId)) return null; 2260 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2261 synchronized (mPackages) { 2262 PackageParser.Activity a = mReceivers.mActivities.get(component); 2263 if (DEBUG_PACKAGE_INFO) Log.v( 2264 TAG, "getReceiverInfo " + component + ": " + a); 2265 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2266 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2267 if (ps == null) return null; 2268 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2269 userId); 2270 } 2271 } 2272 return null; 2273 } 2274 2275 @Override 2276 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2277 if (!sUserManager.exists(userId)) return null; 2278 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2279 synchronized (mPackages) { 2280 PackageParser.Service s = mServices.mServices.get(component); 2281 if (DEBUG_PACKAGE_INFO) Log.v( 2282 TAG, "getServiceInfo " + component + ": " + s); 2283 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2284 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2285 if (ps == null) return null; 2286 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2287 userId); 2288 } 2289 } 2290 return null; 2291 } 2292 2293 @Override 2294 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2295 if (!sUserManager.exists(userId)) return null; 2296 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2297 synchronized (mPackages) { 2298 PackageParser.Provider p = mProviders.mProviders.get(component); 2299 if (DEBUG_PACKAGE_INFO) Log.v( 2300 TAG, "getProviderInfo " + component + ": " + p); 2301 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2302 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2303 if (ps == null) return null; 2304 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2305 userId); 2306 } 2307 } 2308 return null; 2309 } 2310 2311 @Override 2312 public String[] getSystemSharedLibraryNames() { 2313 Set<String> libSet; 2314 synchronized (mPackages) { 2315 libSet = mSharedLibraries.keySet(); 2316 int size = libSet.size(); 2317 if (size > 0) { 2318 String[] libs = new String[size]; 2319 libSet.toArray(libs); 2320 return libs; 2321 } 2322 } 2323 return null; 2324 } 2325 2326 /** 2327 * @hide 2328 */ 2329 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2330 synchronized (mPackages) { 2331 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2332 if (lib != null && lib.apk != null) { 2333 return mPackages.get(lib.apk); 2334 } 2335 } 2336 return null; 2337 } 2338 2339 @Override 2340 public FeatureInfo[] getSystemAvailableFeatures() { 2341 Collection<FeatureInfo> featSet; 2342 synchronized (mPackages) { 2343 featSet = mAvailableFeatures.values(); 2344 int size = featSet.size(); 2345 if (size > 0) { 2346 FeatureInfo[] features = new FeatureInfo[size+1]; 2347 featSet.toArray(features); 2348 FeatureInfo fi = new FeatureInfo(); 2349 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2350 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2351 features[size] = fi; 2352 return features; 2353 } 2354 } 2355 return null; 2356 } 2357 2358 @Override 2359 public boolean hasSystemFeature(String name) { 2360 synchronized (mPackages) { 2361 return mAvailableFeatures.containsKey(name); 2362 } 2363 } 2364 2365 private void checkValidCaller(int uid, int userId) { 2366 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2367 return; 2368 2369 throw new SecurityException("Caller uid=" + uid 2370 + " is not privileged to communicate with user=" + userId); 2371 } 2372 2373 @Override 2374 public int checkPermission(String permName, String pkgName) { 2375 synchronized (mPackages) { 2376 PackageParser.Package p = mPackages.get(pkgName); 2377 if (p != null && p.mExtras != null) { 2378 PackageSetting ps = (PackageSetting)p.mExtras; 2379 if (ps.sharedUser != null) { 2380 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2381 return PackageManager.PERMISSION_GRANTED; 2382 } 2383 } else if (ps.grantedPermissions.contains(permName)) { 2384 return PackageManager.PERMISSION_GRANTED; 2385 } 2386 } 2387 } 2388 return PackageManager.PERMISSION_DENIED; 2389 } 2390 2391 @Override 2392 public int checkUidPermission(String permName, int uid) { 2393 synchronized (mPackages) { 2394 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2395 if (obj != null) { 2396 GrantedPermissions gp = (GrantedPermissions)obj; 2397 if (gp.grantedPermissions.contains(permName)) { 2398 return PackageManager.PERMISSION_GRANTED; 2399 } 2400 } else { 2401 ArraySet<String> perms = mSystemPermissions.get(uid); 2402 if (perms != null && perms.contains(permName)) { 2403 return PackageManager.PERMISSION_GRANTED; 2404 } 2405 } 2406 } 2407 return PackageManager.PERMISSION_DENIED; 2408 } 2409 2410 /** 2411 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2412 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2413 * @param checkShell TODO(yamasani): 2414 * @param message the message to log on security exception 2415 */ 2416 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2417 boolean checkShell, String message) { 2418 if (userId < 0) { 2419 throw new IllegalArgumentException("Invalid userId " + userId); 2420 } 2421 if (checkShell) { 2422 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2423 } 2424 if (userId == UserHandle.getUserId(callingUid)) return; 2425 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2426 if (requireFullPermission) { 2427 mContext.enforceCallingOrSelfPermission( 2428 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2429 } else { 2430 try { 2431 mContext.enforceCallingOrSelfPermission( 2432 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2433 } catch (SecurityException se) { 2434 mContext.enforceCallingOrSelfPermission( 2435 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2436 } 2437 } 2438 } 2439 } 2440 2441 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2442 if (callingUid == Process.SHELL_UID) { 2443 if (userHandle >= 0 2444 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2445 throw new SecurityException("Shell does not have permission to access user " 2446 + userHandle); 2447 } else if (userHandle < 0) { 2448 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2449 + Debug.getCallers(3)); 2450 } 2451 } 2452 } 2453 2454 private BasePermission findPermissionTreeLP(String permName) { 2455 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2456 if (permName.startsWith(bp.name) && 2457 permName.length() > bp.name.length() && 2458 permName.charAt(bp.name.length()) == '.') { 2459 return bp; 2460 } 2461 } 2462 return null; 2463 } 2464 2465 private BasePermission checkPermissionTreeLP(String permName) { 2466 if (permName != null) { 2467 BasePermission bp = findPermissionTreeLP(permName); 2468 if (bp != null) { 2469 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2470 return bp; 2471 } 2472 throw new SecurityException("Calling uid " 2473 + Binder.getCallingUid() 2474 + " is not allowed to add to permission tree " 2475 + bp.name + " owned by uid " + bp.uid); 2476 } 2477 } 2478 throw new SecurityException("No permission tree found for " + permName); 2479 } 2480 2481 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2482 if (s1 == null) { 2483 return s2 == null; 2484 } 2485 if (s2 == null) { 2486 return false; 2487 } 2488 if (s1.getClass() != s2.getClass()) { 2489 return false; 2490 } 2491 return s1.equals(s2); 2492 } 2493 2494 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2495 if (pi1.icon != pi2.icon) return false; 2496 if (pi1.logo != pi2.logo) return false; 2497 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2498 if (!compareStrings(pi1.name, pi2.name)) return false; 2499 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2500 // We'll take care of setting this one. 2501 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2502 // These are not currently stored in settings. 2503 //if (!compareStrings(pi1.group, pi2.group)) return false; 2504 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2505 //if (pi1.labelRes != pi2.labelRes) return false; 2506 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2507 return true; 2508 } 2509 2510 int permissionInfoFootprint(PermissionInfo info) { 2511 int size = info.name.length(); 2512 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2513 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2514 return size; 2515 } 2516 2517 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2518 int size = 0; 2519 for (BasePermission perm : mSettings.mPermissions.values()) { 2520 if (perm.uid == tree.uid) { 2521 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2522 } 2523 } 2524 return size; 2525 } 2526 2527 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2528 // We calculate the max size of permissions defined by this uid and throw 2529 // if that plus the size of 'info' would exceed our stated maximum. 2530 if (tree.uid != Process.SYSTEM_UID) { 2531 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2532 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2533 throw new SecurityException("Permission tree size cap exceeded"); 2534 } 2535 } 2536 } 2537 2538 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2539 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2540 throw new SecurityException("Label must be specified in permission"); 2541 } 2542 BasePermission tree = checkPermissionTreeLP(info.name); 2543 BasePermission bp = mSettings.mPermissions.get(info.name); 2544 boolean added = bp == null; 2545 boolean changed = true; 2546 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2547 if (added) { 2548 enforcePermissionCapLocked(info, tree); 2549 bp = new BasePermission(info.name, tree.sourcePackage, 2550 BasePermission.TYPE_DYNAMIC); 2551 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2552 throw new SecurityException( 2553 "Not allowed to modify non-dynamic permission " 2554 + info.name); 2555 } else { 2556 if (bp.protectionLevel == fixedLevel 2557 && bp.perm.owner.equals(tree.perm.owner) 2558 && bp.uid == tree.uid 2559 && comparePermissionInfos(bp.perm.info, info)) { 2560 changed = false; 2561 } 2562 } 2563 bp.protectionLevel = fixedLevel; 2564 info = new PermissionInfo(info); 2565 info.protectionLevel = fixedLevel; 2566 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2567 bp.perm.info.packageName = tree.perm.info.packageName; 2568 bp.uid = tree.uid; 2569 if (added) { 2570 mSettings.mPermissions.put(info.name, bp); 2571 } 2572 if (changed) { 2573 if (!async) { 2574 mSettings.writeLPr(); 2575 } else { 2576 scheduleWriteSettingsLocked(); 2577 } 2578 } 2579 return added; 2580 } 2581 2582 @Override 2583 public boolean addPermission(PermissionInfo info) { 2584 synchronized (mPackages) { 2585 return addPermissionLocked(info, false); 2586 } 2587 } 2588 2589 @Override 2590 public boolean addPermissionAsync(PermissionInfo info) { 2591 synchronized (mPackages) { 2592 return addPermissionLocked(info, true); 2593 } 2594 } 2595 2596 @Override 2597 public void removePermission(String name) { 2598 synchronized (mPackages) { 2599 checkPermissionTreeLP(name); 2600 BasePermission bp = mSettings.mPermissions.get(name); 2601 if (bp != null) { 2602 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2603 throw new SecurityException( 2604 "Not allowed to modify non-dynamic permission " 2605 + name); 2606 } 2607 mSettings.mPermissions.remove(name); 2608 mSettings.writeLPr(); 2609 } 2610 } 2611 } 2612 2613 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2614 int index = pkg.requestedPermissions.indexOf(bp.name); 2615 if (index == -1) { 2616 throw new SecurityException("Package " + pkg.packageName 2617 + " has not requested permission " + bp.name); 2618 } 2619 boolean isNormal = 2620 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2621 == PermissionInfo.PROTECTION_NORMAL); 2622 boolean isDangerous = 2623 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2624 == PermissionInfo.PROTECTION_DANGEROUS); 2625 boolean isDevelopment = 2626 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2627 2628 if (!isNormal && !isDangerous && !isDevelopment) { 2629 throw new SecurityException("Permission " + bp.name 2630 + " is not a changeable permission type"); 2631 } 2632 2633 if (isNormal || isDangerous) { 2634 if (pkg.requestedPermissionsRequired.get(index)) { 2635 throw new SecurityException("Can't change " + bp.name 2636 + ". It is required by the application"); 2637 } 2638 } 2639 } 2640 2641 @Override 2642 public void grantPermission(String packageName, String permissionName) { 2643 mContext.enforceCallingOrSelfPermission( 2644 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2645 synchronized (mPackages) { 2646 final PackageParser.Package pkg = mPackages.get(packageName); 2647 if (pkg == null) { 2648 throw new IllegalArgumentException("Unknown package: " + packageName); 2649 } 2650 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2651 if (bp == null) { 2652 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2653 } 2654 2655 checkGrantRevokePermissions(pkg, bp); 2656 2657 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2658 if (ps == null) { 2659 return; 2660 } 2661 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2662 if (gp.grantedPermissions.add(permissionName)) { 2663 if (ps.haveGids) { 2664 gp.gids = appendInts(gp.gids, bp.gids); 2665 } 2666 mSettings.writeLPr(); 2667 } 2668 } 2669 } 2670 2671 @Override 2672 public void revokePermission(String packageName, String permissionName) { 2673 int changedAppId = -1; 2674 2675 synchronized (mPackages) { 2676 final PackageParser.Package pkg = mPackages.get(packageName); 2677 if (pkg == null) { 2678 throw new IllegalArgumentException("Unknown package: " + packageName); 2679 } 2680 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2681 mContext.enforceCallingOrSelfPermission( 2682 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2683 } 2684 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2685 if (bp == null) { 2686 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2687 } 2688 2689 checkGrantRevokePermissions(pkg, bp); 2690 2691 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2692 if (ps == null) { 2693 return; 2694 } 2695 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2696 if (gp.grantedPermissions.remove(permissionName)) { 2697 gp.grantedPermissions.remove(permissionName); 2698 if (ps.haveGids) { 2699 gp.gids = removeInts(gp.gids, bp.gids); 2700 } 2701 mSettings.writeLPr(); 2702 changedAppId = ps.appId; 2703 } 2704 } 2705 2706 if (changedAppId >= 0) { 2707 // We changed the perm on someone, kill its processes. 2708 IActivityManager am = ActivityManagerNative.getDefault(); 2709 if (am != null) { 2710 final int callingUserId = UserHandle.getCallingUserId(); 2711 final long ident = Binder.clearCallingIdentity(); 2712 try { 2713 //XXX we should only revoke for the calling user's app permissions, 2714 // but for now we impact all users. 2715 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2716 // "revoke " + permissionName); 2717 int[] users = sUserManager.getUserIds(); 2718 for (int user : users) { 2719 am.killUid(UserHandle.getUid(user, changedAppId), 2720 "revoke " + permissionName); 2721 } 2722 } catch (RemoteException e) { 2723 } finally { 2724 Binder.restoreCallingIdentity(ident); 2725 } 2726 } 2727 } 2728 } 2729 2730 @Override 2731 public boolean isProtectedBroadcast(String actionName) { 2732 synchronized (mPackages) { 2733 return mProtectedBroadcasts.contains(actionName); 2734 } 2735 } 2736 2737 @Override 2738 public int checkSignatures(String pkg1, String pkg2) { 2739 synchronized (mPackages) { 2740 final PackageParser.Package p1 = mPackages.get(pkg1); 2741 final PackageParser.Package p2 = mPackages.get(pkg2); 2742 if (p1 == null || p1.mExtras == null 2743 || p2 == null || p2.mExtras == null) { 2744 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2745 } 2746 return compareSignatures(p1.mSignatures, p2.mSignatures); 2747 } 2748 } 2749 2750 @Override 2751 public int checkUidSignatures(int uid1, int uid2) { 2752 // Map to base uids. 2753 uid1 = UserHandle.getAppId(uid1); 2754 uid2 = UserHandle.getAppId(uid2); 2755 // reader 2756 synchronized (mPackages) { 2757 Signature[] s1; 2758 Signature[] s2; 2759 Object obj = mSettings.getUserIdLPr(uid1); 2760 if (obj != null) { 2761 if (obj instanceof SharedUserSetting) { 2762 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2763 } else if (obj instanceof PackageSetting) { 2764 s1 = ((PackageSetting)obj).signatures.mSignatures; 2765 } else { 2766 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2767 } 2768 } else { 2769 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2770 } 2771 obj = mSettings.getUserIdLPr(uid2); 2772 if (obj != null) { 2773 if (obj instanceof SharedUserSetting) { 2774 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2775 } else if (obj instanceof PackageSetting) { 2776 s2 = ((PackageSetting)obj).signatures.mSignatures; 2777 } else { 2778 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2779 } 2780 } else { 2781 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2782 } 2783 return compareSignatures(s1, s2); 2784 } 2785 } 2786 2787 /** 2788 * Compares two sets of signatures. Returns: 2789 * <br /> 2790 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2791 * <br /> 2792 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2793 * <br /> 2794 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2795 * <br /> 2796 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2797 * <br /> 2798 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2799 */ 2800 static int compareSignatures(Signature[] s1, Signature[] s2) { 2801 if (s1 == null) { 2802 return s2 == null 2803 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2804 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2805 } 2806 2807 if (s2 == null) { 2808 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2809 } 2810 2811 if (s1.length != s2.length) { 2812 return PackageManager.SIGNATURE_NO_MATCH; 2813 } 2814 2815 // Since both signature sets are of size 1, we can compare without HashSets. 2816 if (s1.length == 1) { 2817 return s1[0].equals(s2[0]) ? 2818 PackageManager.SIGNATURE_MATCH : 2819 PackageManager.SIGNATURE_NO_MATCH; 2820 } 2821 2822 ArraySet<Signature> set1 = new ArraySet<Signature>(); 2823 for (Signature sig : s1) { 2824 set1.add(sig); 2825 } 2826 ArraySet<Signature> set2 = new ArraySet<Signature>(); 2827 for (Signature sig : s2) { 2828 set2.add(sig); 2829 } 2830 // Make sure s2 contains all signatures in s1. 2831 if (set1.equals(set2)) { 2832 return PackageManager.SIGNATURE_MATCH; 2833 } 2834 return PackageManager.SIGNATURE_NO_MATCH; 2835 } 2836 2837 /** 2838 * If the database version for this type of package (internal storage or 2839 * external storage) is less than the version where package signatures 2840 * were updated, return true. 2841 */ 2842 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2843 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2844 DatabaseVersion.SIGNATURE_END_ENTITY)) 2845 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2846 DatabaseVersion.SIGNATURE_END_ENTITY)); 2847 } 2848 2849 /** 2850 * Used for backward compatibility to make sure any packages with 2851 * certificate chains get upgraded to the new style. {@code existingSigs} 2852 * will be in the old format (since they were stored on disk from before the 2853 * system upgrade) and {@code scannedSigs} will be in the newer format. 2854 */ 2855 private int compareSignaturesCompat(PackageSignatures existingSigs, 2856 PackageParser.Package scannedPkg) { 2857 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2858 return PackageManager.SIGNATURE_NO_MATCH; 2859 } 2860 2861 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 2862 for (Signature sig : existingSigs.mSignatures) { 2863 existingSet.add(sig); 2864 } 2865 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 2866 for (Signature sig : scannedPkg.mSignatures) { 2867 try { 2868 Signature[] chainSignatures = sig.getChainSignatures(); 2869 for (Signature chainSig : chainSignatures) { 2870 scannedCompatSet.add(chainSig); 2871 } 2872 } catch (CertificateEncodingException e) { 2873 scannedCompatSet.add(sig); 2874 } 2875 } 2876 /* 2877 * Make sure the expanded scanned set contains all signatures in the 2878 * existing one. 2879 */ 2880 if (scannedCompatSet.equals(existingSet)) { 2881 // Migrate the old signatures to the new scheme. 2882 existingSigs.assignSignatures(scannedPkg.mSignatures); 2883 // The new KeySets will be re-added later in the scanning process. 2884 synchronized (mPackages) { 2885 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2886 } 2887 return PackageManager.SIGNATURE_MATCH; 2888 } 2889 return PackageManager.SIGNATURE_NO_MATCH; 2890 } 2891 2892 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2893 if (isExternal(scannedPkg)) { 2894 return mSettings.isExternalDatabaseVersionOlderThan( 2895 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2896 } else { 2897 return mSettings.isInternalDatabaseVersionOlderThan( 2898 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2899 } 2900 } 2901 2902 private int compareSignaturesRecover(PackageSignatures existingSigs, 2903 PackageParser.Package scannedPkg) { 2904 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 2905 return PackageManager.SIGNATURE_NO_MATCH; 2906 } 2907 2908 String msg = null; 2909 try { 2910 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 2911 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 2912 + scannedPkg.packageName); 2913 return PackageManager.SIGNATURE_MATCH; 2914 } 2915 } catch (CertificateException e) { 2916 msg = e.getMessage(); 2917 } 2918 2919 logCriticalInfo(Log.INFO, 2920 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 2921 return PackageManager.SIGNATURE_NO_MATCH; 2922 } 2923 2924 @Override 2925 public String[] getPackagesForUid(int uid) { 2926 uid = UserHandle.getAppId(uid); 2927 // reader 2928 synchronized (mPackages) { 2929 Object obj = mSettings.getUserIdLPr(uid); 2930 if (obj instanceof SharedUserSetting) { 2931 final SharedUserSetting sus = (SharedUserSetting) obj; 2932 final int N = sus.packages.size(); 2933 final String[] res = new String[N]; 2934 final Iterator<PackageSetting> it = sus.packages.iterator(); 2935 int i = 0; 2936 while (it.hasNext()) { 2937 res[i++] = it.next().name; 2938 } 2939 return res; 2940 } else if (obj instanceof PackageSetting) { 2941 final PackageSetting ps = (PackageSetting) obj; 2942 return new String[] { ps.name }; 2943 } 2944 } 2945 return null; 2946 } 2947 2948 @Override 2949 public String getNameForUid(int uid) { 2950 // reader 2951 synchronized (mPackages) { 2952 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2953 if (obj instanceof SharedUserSetting) { 2954 final SharedUserSetting sus = (SharedUserSetting) obj; 2955 return sus.name + ":" + sus.userId; 2956 } else if (obj instanceof PackageSetting) { 2957 final PackageSetting ps = (PackageSetting) obj; 2958 return ps.name; 2959 } 2960 } 2961 return null; 2962 } 2963 2964 @Override 2965 public int getUidForSharedUser(String sharedUserName) { 2966 if(sharedUserName == null) { 2967 return -1; 2968 } 2969 // reader 2970 synchronized (mPackages) { 2971 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 2972 if (suid == null) { 2973 return -1; 2974 } 2975 return suid.userId; 2976 } 2977 } 2978 2979 @Override 2980 public int getFlagsForUid(int uid) { 2981 synchronized (mPackages) { 2982 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2983 if (obj instanceof SharedUserSetting) { 2984 final SharedUserSetting sus = (SharedUserSetting) obj; 2985 return sus.pkgFlags; 2986 } else if (obj instanceof PackageSetting) { 2987 final PackageSetting ps = (PackageSetting) obj; 2988 return ps.pkgFlags; 2989 } 2990 } 2991 return 0; 2992 } 2993 2994 @Override 2995 public int getPrivateFlagsForUid(int uid) { 2996 synchronized (mPackages) { 2997 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2998 if (obj instanceof SharedUserSetting) { 2999 final SharedUserSetting sus = (SharedUserSetting) obj; 3000 return sus.pkgPrivateFlags; 3001 } else if (obj instanceof PackageSetting) { 3002 final PackageSetting ps = (PackageSetting) obj; 3003 return ps.pkgPrivateFlags; 3004 } 3005 } 3006 return 0; 3007 } 3008 3009 @Override 3010 public boolean isUidPrivileged(int uid) { 3011 uid = UserHandle.getAppId(uid); 3012 // reader 3013 synchronized (mPackages) { 3014 Object obj = mSettings.getUserIdLPr(uid); 3015 if (obj instanceof SharedUserSetting) { 3016 final SharedUserSetting sus = (SharedUserSetting) obj; 3017 final Iterator<PackageSetting> it = sus.packages.iterator(); 3018 while (it.hasNext()) { 3019 if (it.next().isPrivileged()) { 3020 return true; 3021 } 3022 } 3023 } else if (obj instanceof PackageSetting) { 3024 final PackageSetting ps = (PackageSetting) obj; 3025 return ps.isPrivileged(); 3026 } 3027 } 3028 return false; 3029 } 3030 3031 @Override 3032 public String[] getAppOpPermissionPackages(String permissionName) { 3033 synchronized (mPackages) { 3034 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3035 if (pkgs == null) { 3036 return null; 3037 } 3038 return pkgs.toArray(new String[pkgs.size()]); 3039 } 3040 } 3041 3042 @Override 3043 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3044 int flags, int userId) { 3045 if (!sUserManager.exists(userId)) return null; 3046 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3047 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3048 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3049 } 3050 3051 @Override 3052 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3053 IntentFilter filter, int match, ComponentName activity) { 3054 final int userId = UserHandle.getCallingUserId(); 3055 if (DEBUG_PREFERRED) { 3056 Log.v(TAG, "setLastChosenActivity intent=" + intent 3057 + " resolvedType=" + resolvedType 3058 + " flags=" + flags 3059 + " filter=" + filter 3060 + " match=" + match 3061 + " activity=" + activity); 3062 filter.dump(new PrintStreamPrinter(System.out), " "); 3063 } 3064 intent.setComponent(null); 3065 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3066 // Find any earlier preferred or last chosen entries and nuke them 3067 findPreferredActivity(intent, resolvedType, 3068 flags, query, 0, false, true, false, userId); 3069 // Add the new activity as the last chosen for this filter 3070 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3071 "Setting last chosen"); 3072 } 3073 3074 @Override 3075 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3076 final int userId = UserHandle.getCallingUserId(); 3077 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3078 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3079 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3080 false, false, false, userId); 3081 } 3082 3083 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3084 int flags, List<ResolveInfo> query, int userId) { 3085 if (query != null) { 3086 final int N = query.size(); 3087 if (N == 1) { 3088 return query.get(0); 3089 } else if (N > 1) { 3090 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3091 // If there is more than one activity with the same priority, 3092 // then let the user decide between them. 3093 ResolveInfo r0 = query.get(0); 3094 ResolveInfo r1 = query.get(1); 3095 if (DEBUG_INTENT_MATCHING || debug) { 3096 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3097 + r1.activityInfo.name + "=" + r1.priority); 3098 } 3099 // If the first activity has a higher priority, or a different 3100 // default, then it is always desireable to pick it. 3101 if (r0.priority != r1.priority 3102 || r0.preferredOrder != r1.preferredOrder 3103 || r0.isDefault != r1.isDefault) { 3104 return query.get(0); 3105 } 3106 // If we have saved a preference for a preferred activity for 3107 // this Intent, use that. 3108 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3109 flags, query, r0.priority, true, false, debug, userId); 3110 if (ri != null) { 3111 return ri; 3112 } 3113 if (userId != 0) { 3114 ri = new ResolveInfo(mResolveInfo); 3115 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3116 ri.activityInfo.applicationInfo = new ApplicationInfo( 3117 ri.activityInfo.applicationInfo); 3118 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3119 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3120 return ri; 3121 } 3122 return mResolveInfo; 3123 } 3124 } 3125 return null; 3126 } 3127 3128 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3129 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3130 final int N = query.size(); 3131 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3132 .get(userId); 3133 // Get the list of persistent preferred activities that handle the intent 3134 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3135 List<PersistentPreferredActivity> pprefs = ppir != null 3136 ? ppir.queryIntent(intent, resolvedType, 3137 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3138 : null; 3139 if (pprefs != null && pprefs.size() > 0) { 3140 final int M = pprefs.size(); 3141 for (int i=0; i<M; i++) { 3142 final PersistentPreferredActivity ppa = pprefs.get(i); 3143 if (DEBUG_PREFERRED || debug) { 3144 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3145 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3146 + "\n component=" + ppa.mComponent); 3147 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3148 } 3149 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3150 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3151 if (DEBUG_PREFERRED || debug) { 3152 Slog.v(TAG, "Found persistent preferred activity:"); 3153 if (ai != null) { 3154 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3155 } else { 3156 Slog.v(TAG, " null"); 3157 } 3158 } 3159 if (ai == null) { 3160 // This previously registered persistent preferred activity 3161 // component is no longer known. Ignore it and do NOT remove it. 3162 continue; 3163 } 3164 for (int j=0; j<N; j++) { 3165 final ResolveInfo ri = query.get(j); 3166 if (!ri.activityInfo.applicationInfo.packageName 3167 .equals(ai.applicationInfo.packageName)) { 3168 continue; 3169 } 3170 if (!ri.activityInfo.name.equals(ai.name)) { 3171 continue; 3172 } 3173 // Found a persistent preference that can handle the intent. 3174 if (DEBUG_PREFERRED || debug) { 3175 Slog.v(TAG, "Returning persistent preferred activity: " + 3176 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3177 } 3178 return ri; 3179 } 3180 } 3181 } 3182 return null; 3183 } 3184 3185 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3186 List<ResolveInfo> query, int priority, boolean always, 3187 boolean removeMatches, boolean debug, int userId) { 3188 if (!sUserManager.exists(userId)) return null; 3189 // writer 3190 synchronized (mPackages) { 3191 if (intent.getSelector() != null) { 3192 intent = intent.getSelector(); 3193 } 3194 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3195 3196 // Try to find a matching persistent preferred activity. 3197 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3198 debug, userId); 3199 3200 // If a persistent preferred activity matched, use it. 3201 if (pri != null) { 3202 return pri; 3203 } 3204 3205 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3206 // Get the list of preferred activities that handle the intent 3207 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3208 List<PreferredActivity> prefs = pir != null 3209 ? pir.queryIntent(intent, resolvedType, 3210 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3211 : null; 3212 if (prefs != null && prefs.size() > 0) { 3213 boolean changed = false; 3214 try { 3215 // First figure out how good the original match set is. 3216 // We will only allow preferred activities that came 3217 // from the same match quality. 3218 int match = 0; 3219 3220 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3221 3222 final int N = query.size(); 3223 for (int j=0; j<N; j++) { 3224 final ResolveInfo ri = query.get(j); 3225 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3226 + ": 0x" + Integer.toHexString(match)); 3227 if (ri.match > match) { 3228 match = ri.match; 3229 } 3230 } 3231 3232 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3233 + Integer.toHexString(match)); 3234 3235 match &= IntentFilter.MATCH_CATEGORY_MASK; 3236 final int M = prefs.size(); 3237 for (int i=0; i<M; i++) { 3238 final PreferredActivity pa = prefs.get(i); 3239 if (DEBUG_PREFERRED || debug) { 3240 Slog.v(TAG, "Checking PreferredActivity ds=" 3241 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3242 + "\n component=" + pa.mPref.mComponent); 3243 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3244 } 3245 if (pa.mPref.mMatch != match) { 3246 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3247 + Integer.toHexString(pa.mPref.mMatch)); 3248 continue; 3249 } 3250 // If it's not an "always" type preferred activity and that's what we're 3251 // looking for, skip it. 3252 if (always && !pa.mPref.mAlways) { 3253 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3254 continue; 3255 } 3256 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3257 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3258 if (DEBUG_PREFERRED || debug) { 3259 Slog.v(TAG, "Found preferred activity:"); 3260 if (ai != null) { 3261 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3262 } else { 3263 Slog.v(TAG, " null"); 3264 } 3265 } 3266 if (ai == null) { 3267 // This previously registered preferred activity 3268 // component is no longer known. Most likely an update 3269 // to the app was installed and in the new version this 3270 // component no longer exists. Clean it up by removing 3271 // it from the preferred activities list, and skip it. 3272 Slog.w(TAG, "Removing dangling preferred activity: " 3273 + pa.mPref.mComponent); 3274 pir.removeFilter(pa); 3275 changed = true; 3276 continue; 3277 } 3278 for (int j=0; j<N; j++) { 3279 final ResolveInfo ri = query.get(j); 3280 if (!ri.activityInfo.applicationInfo.packageName 3281 .equals(ai.applicationInfo.packageName)) { 3282 continue; 3283 } 3284 if (!ri.activityInfo.name.equals(ai.name)) { 3285 continue; 3286 } 3287 3288 if (removeMatches) { 3289 pir.removeFilter(pa); 3290 changed = true; 3291 if (DEBUG_PREFERRED) { 3292 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3293 } 3294 break; 3295 } 3296 3297 // Okay we found a previously set preferred or last chosen app. 3298 // If the result set is different from when this 3299 // was created, we need to clear it and re-ask the 3300 // user their preference, if we're looking for an "always" type entry. 3301 if (always && !pa.mPref.sameSet(query)) { 3302 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3303 + intent + " type " + resolvedType); 3304 if (DEBUG_PREFERRED) { 3305 Slog.v(TAG, "Removing preferred activity since set changed " 3306 + pa.mPref.mComponent); 3307 } 3308 pir.removeFilter(pa); 3309 // Re-add the filter as a "last chosen" entry (!always) 3310 PreferredActivity lastChosen = new PreferredActivity( 3311 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3312 pir.addFilter(lastChosen); 3313 changed = true; 3314 return null; 3315 } 3316 3317 // Yay! Either the set matched or we're looking for the last chosen 3318 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3319 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3320 return ri; 3321 } 3322 } 3323 } finally { 3324 if (changed) { 3325 if (DEBUG_PREFERRED) { 3326 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3327 } 3328 scheduleWritePackageRestrictionsLocked(userId); 3329 } 3330 } 3331 } 3332 } 3333 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3334 return null; 3335 } 3336 3337 /* 3338 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3339 */ 3340 @Override 3341 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3342 int targetUserId) { 3343 mContext.enforceCallingOrSelfPermission( 3344 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3345 List<CrossProfileIntentFilter> matches = 3346 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3347 if (matches != null) { 3348 int size = matches.size(); 3349 for (int i = 0; i < size; i++) { 3350 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3351 } 3352 } 3353 return false; 3354 } 3355 3356 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3357 String resolvedType, int userId) { 3358 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3359 if (resolver != null) { 3360 return resolver.queryIntent(intent, resolvedType, false, userId); 3361 } 3362 return null; 3363 } 3364 3365 @Override 3366 public List<ResolveInfo> queryIntentActivities(Intent intent, 3367 String resolvedType, int flags, int userId) { 3368 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3369 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3370 ComponentName comp = intent.getComponent(); 3371 if (comp == null) { 3372 if (intent.getSelector() != null) { 3373 intent = intent.getSelector(); 3374 comp = intent.getComponent(); 3375 } 3376 } 3377 3378 if (comp != null) { 3379 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3380 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3381 if (ai != null) { 3382 final ResolveInfo ri = new ResolveInfo(); 3383 ri.activityInfo = ai; 3384 list.add(ri); 3385 } 3386 return list; 3387 } 3388 3389 // reader 3390 synchronized (mPackages) { 3391 final String pkgName = intent.getPackage(); 3392 if (pkgName == null) { 3393 List<CrossProfileIntentFilter> matchingFilters = 3394 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3395 // Check for results that need to skip the current profile. 3396 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3397 resolvedType, flags, userId); 3398 if (resolveInfo != null) { 3399 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3400 result.add(resolveInfo); 3401 return result; 3402 } 3403 // Check for cross profile results. 3404 resolveInfo = queryCrossProfileIntents( 3405 matchingFilters, intent, resolvedType, flags, userId); 3406 3407 // Check for results in the current profile. 3408 List<ResolveInfo> result = mActivities.queryIntent( 3409 intent, resolvedType, flags, userId); 3410 if (resolveInfo != null) { 3411 result.add(resolveInfo); 3412 Collections.sort(result, mResolvePrioritySorter); 3413 } 3414 return result; 3415 } 3416 final PackageParser.Package pkg = mPackages.get(pkgName); 3417 if (pkg != null) { 3418 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3419 pkg.activities, userId); 3420 } 3421 return new ArrayList<ResolveInfo>(); 3422 } 3423 } 3424 3425 private ResolveInfo querySkipCurrentProfileIntents( 3426 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3427 int flags, int sourceUserId) { 3428 if (matchingFilters != null) { 3429 int size = matchingFilters.size(); 3430 for (int i = 0; i < size; i ++) { 3431 CrossProfileIntentFilter filter = matchingFilters.get(i); 3432 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3433 // Checking if there are activities in the target user that can handle the 3434 // intent. 3435 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3436 flags, sourceUserId); 3437 if (resolveInfo != null) { 3438 return resolveInfo; 3439 } 3440 } 3441 } 3442 } 3443 return null; 3444 } 3445 3446 // Return matching ResolveInfo if any for skip current profile intent filters. 3447 private ResolveInfo queryCrossProfileIntents( 3448 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3449 int flags, int sourceUserId) { 3450 if (matchingFilters != null) { 3451 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3452 // match the same intent. For performance reasons, it is better not to 3453 // run queryIntent twice for the same userId 3454 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3455 int size = matchingFilters.size(); 3456 for (int i = 0; i < size; i++) { 3457 CrossProfileIntentFilter filter = matchingFilters.get(i); 3458 int targetUserId = filter.getTargetUserId(); 3459 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3460 && !alreadyTriedUserIds.get(targetUserId)) { 3461 // Checking if there are activities in the target user that can handle the 3462 // intent. 3463 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3464 flags, sourceUserId); 3465 if (resolveInfo != null) return resolveInfo; 3466 alreadyTriedUserIds.put(targetUserId, true); 3467 } 3468 } 3469 } 3470 return null; 3471 } 3472 3473 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3474 String resolvedType, int flags, int sourceUserId) { 3475 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3476 resolvedType, flags, filter.getTargetUserId()); 3477 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3478 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3479 } 3480 return null; 3481 } 3482 3483 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3484 int sourceUserId, int targetUserId) { 3485 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3486 String className; 3487 if (targetUserId == UserHandle.USER_OWNER) { 3488 className = FORWARD_INTENT_TO_USER_OWNER; 3489 } else { 3490 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3491 } 3492 ComponentName forwardingActivityComponentName = new ComponentName( 3493 mAndroidApplication.packageName, className); 3494 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3495 sourceUserId); 3496 if (targetUserId == UserHandle.USER_OWNER) { 3497 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3498 forwardingResolveInfo.noResourceId = true; 3499 } 3500 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3501 forwardingResolveInfo.priority = 0; 3502 forwardingResolveInfo.preferredOrder = 0; 3503 forwardingResolveInfo.match = 0; 3504 forwardingResolveInfo.isDefault = true; 3505 forwardingResolveInfo.filter = filter; 3506 forwardingResolveInfo.targetUserId = targetUserId; 3507 return forwardingResolveInfo; 3508 } 3509 3510 @Override 3511 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3512 Intent[] specifics, String[] specificTypes, Intent intent, 3513 String resolvedType, int flags, int userId) { 3514 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3515 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3516 false, "query intent activity options"); 3517 final String resultsAction = intent.getAction(); 3518 3519 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3520 | PackageManager.GET_RESOLVED_FILTER, userId); 3521 3522 if (DEBUG_INTENT_MATCHING) { 3523 Log.v(TAG, "Query " + intent + ": " + results); 3524 } 3525 3526 int specificsPos = 0; 3527 int N; 3528 3529 // todo: note that the algorithm used here is O(N^2). This 3530 // isn't a problem in our current environment, but if we start running 3531 // into situations where we have more than 5 or 10 matches then this 3532 // should probably be changed to something smarter... 3533 3534 // First we go through and resolve each of the specific items 3535 // that were supplied, taking care of removing any corresponding 3536 // duplicate items in the generic resolve list. 3537 if (specifics != null) { 3538 for (int i=0; i<specifics.length; i++) { 3539 final Intent sintent = specifics[i]; 3540 if (sintent == null) { 3541 continue; 3542 } 3543 3544 if (DEBUG_INTENT_MATCHING) { 3545 Log.v(TAG, "Specific #" + i + ": " + sintent); 3546 } 3547 3548 String action = sintent.getAction(); 3549 if (resultsAction != null && resultsAction.equals(action)) { 3550 // If this action was explicitly requested, then don't 3551 // remove things that have it. 3552 action = null; 3553 } 3554 3555 ResolveInfo ri = null; 3556 ActivityInfo ai = null; 3557 3558 ComponentName comp = sintent.getComponent(); 3559 if (comp == null) { 3560 ri = resolveIntent( 3561 sintent, 3562 specificTypes != null ? specificTypes[i] : null, 3563 flags, userId); 3564 if (ri == null) { 3565 continue; 3566 } 3567 if (ri == mResolveInfo) { 3568 // ACK! Must do something better with this. 3569 } 3570 ai = ri.activityInfo; 3571 comp = new ComponentName(ai.applicationInfo.packageName, 3572 ai.name); 3573 } else { 3574 ai = getActivityInfo(comp, flags, userId); 3575 if (ai == null) { 3576 continue; 3577 } 3578 } 3579 3580 // Look for any generic query activities that are duplicates 3581 // of this specific one, and remove them from the results. 3582 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3583 N = results.size(); 3584 int j; 3585 for (j=specificsPos; j<N; j++) { 3586 ResolveInfo sri = results.get(j); 3587 if ((sri.activityInfo.name.equals(comp.getClassName()) 3588 && sri.activityInfo.applicationInfo.packageName.equals( 3589 comp.getPackageName())) 3590 || (action != null && sri.filter.matchAction(action))) { 3591 results.remove(j); 3592 if (DEBUG_INTENT_MATCHING) Log.v( 3593 TAG, "Removing duplicate item from " + j 3594 + " due to specific " + specificsPos); 3595 if (ri == null) { 3596 ri = sri; 3597 } 3598 j--; 3599 N--; 3600 } 3601 } 3602 3603 // Add this specific item to its proper place. 3604 if (ri == null) { 3605 ri = new ResolveInfo(); 3606 ri.activityInfo = ai; 3607 } 3608 results.add(specificsPos, ri); 3609 ri.specificIndex = i; 3610 specificsPos++; 3611 } 3612 } 3613 3614 // Now we go through the remaining generic results and remove any 3615 // duplicate actions that are found here. 3616 N = results.size(); 3617 for (int i=specificsPos; i<N-1; i++) { 3618 final ResolveInfo rii = results.get(i); 3619 if (rii.filter == null) { 3620 continue; 3621 } 3622 3623 // Iterate over all of the actions of this result's intent 3624 // filter... typically this should be just one. 3625 final Iterator<String> it = rii.filter.actionsIterator(); 3626 if (it == null) { 3627 continue; 3628 } 3629 while (it.hasNext()) { 3630 final String action = it.next(); 3631 if (resultsAction != null && resultsAction.equals(action)) { 3632 // If this action was explicitly requested, then don't 3633 // remove things that have it. 3634 continue; 3635 } 3636 for (int j=i+1; j<N; j++) { 3637 final ResolveInfo rij = results.get(j); 3638 if (rij.filter != null && rij.filter.hasAction(action)) { 3639 results.remove(j); 3640 if (DEBUG_INTENT_MATCHING) Log.v( 3641 TAG, "Removing duplicate item from " + j 3642 + " due to action " + action + " at " + i); 3643 j--; 3644 N--; 3645 } 3646 } 3647 } 3648 3649 // If the caller didn't request filter information, drop it now 3650 // so we don't have to marshall/unmarshall it. 3651 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3652 rii.filter = null; 3653 } 3654 } 3655 3656 // Filter out the caller activity if so requested. 3657 if (caller != null) { 3658 N = results.size(); 3659 for (int i=0; i<N; i++) { 3660 ActivityInfo ainfo = results.get(i).activityInfo; 3661 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3662 && caller.getClassName().equals(ainfo.name)) { 3663 results.remove(i); 3664 break; 3665 } 3666 } 3667 } 3668 3669 // If the caller didn't request filter information, 3670 // drop them now so we don't have to 3671 // marshall/unmarshall it. 3672 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3673 N = results.size(); 3674 for (int i=0; i<N; i++) { 3675 results.get(i).filter = null; 3676 } 3677 } 3678 3679 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3680 return results; 3681 } 3682 3683 @Override 3684 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3685 int userId) { 3686 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3687 ComponentName comp = intent.getComponent(); 3688 if (comp == null) { 3689 if (intent.getSelector() != null) { 3690 intent = intent.getSelector(); 3691 comp = intent.getComponent(); 3692 } 3693 } 3694 if (comp != null) { 3695 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3696 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3697 if (ai != null) { 3698 ResolveInfo ri = new ResolveInfo(); 3699 ri.activityInfo = ai; 3700 list.add(ri); 3701 } 3702 return list; 3703 } 3704 3705 // reader 3706 synchronized (mPackages) { 3707 String pkgName = intent.getPackage(); 3708 if (pkgName == null) { 3709 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3710 } 3711 final PackageParser.Package pkg = mPackages.get(pkgName); 3712 if (pkg != null) { 3713 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3714 userId); 3715 } 3716 return null; 3717 } 3718 } 3719 3720 @Override 3721 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3722 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3723 if (!sUserManager.exists(userId)) return null; 3724 if (query != null) { 3725 if (query.size() >= 1) { 3726 // If there is more than one service with the same priority, 3727 // just arbitrarily pick the first one. 3728 return query.get(0); 3729 } 3730 } 3731 return null; 3732 } 3733 3734 @Override 3735 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3736 int userId) { 3737 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3738 ComponentName comp = intent.getComponent(); 3739 if (comp == null) { 3740 if (intent.getSelector() != null) { 3741 intent = intent.getSelector(); 3742 comp = intent.getComponent(); 3743 } 3744 } 3745 if (comp != null) { 3746 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3747 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3748 if (si != null) { 3749 final ResolveInfo ri = new ResolveInfo(); 3750 ri.serviceInfo = si; 3751 list.add(ri); 3752 } 3753 return list; 3754 } 3755 3756 // reader 3757 synchronized (mPackages) { 3758 String pkgName = intent.getPackage(); 3759 if (pkgName == null) { 3760 return mServices.queryIntent(intent, resolvedType, flags, userId); 3761 } 3762 final PackageParser.Package pkg = mPackages.get(pkgName); 3763 if (pkg != null) { 3764 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3765 userId); 3766 } 3767 return null; 3768 } 3769 } 3770 3771 @Override 3772 public List<ResolveInfo> queryIntentContentProviders( 3773 Intent intent, String resolvedType, int flags, int userId) { 3774 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3775 ComponentName comp = intent.getComponent(); 3776 if (comp == null) { 3777 if (intent.getSelector() != null) { 3778 intent = intent.getSelector(); 3779 comp = intent.getComponent(); 3780 } 3781 } 3782 if (comp != null) { 3783 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3784 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3785 if (pi != null) { 3786 final ResolveInfo ri = new ResolveInfo(); 3787 ri.providerInfo = pi; 3788 list.add(ri); 3789 } 3790 return list; 3791 } 3792 3793 // reader 3794 synchronized (mPackages) { 3795 String pkgName = intent.getPackage(); 3796 if (pkgName == null) { 3797 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3798 } 3799 final PackageParser.Package pkg = mPackages.get(pkgName); 3800 if (pkg != null) { 3801 return mProviders.queryIntentForPackage( 3802 intent, resolvedType, flags, pkg.providers, userId); 3803 } 3804 return null; 3805 } 3806 } 3807 3808 @Override 3809 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3810 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3811 3812 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3813 3814 // writer 3815 synchronized (mPackages) { 3816 ArrayList<PackageInfo> list; 3817 if (listUninstalled) { 3818 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3819 for (PackageSetting ps : mSettings.mPackages.values()) { 3820 PackageInfo pi; 3821 if (ps.pkg != null) { 3822 pi = generatePackageInfo(ps.pkg, flags, userId); 3823 } else { 3824 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3825 } 3826 if (pi != null) { 3827 list.add(pi); 3828 } 3829 } 3830 } else { 3831 list = new ArrayList<PackageInfo>(mPackages.size()); 3832 for (PackageParser.Package p : mPackages.values()) { 3833 PackageInfo pi = generatePackageInfo(p, flags, userId); 3834 if (pi != null) { 3835 list.add(pi); 3836 } 3837 } 3838 } 3839 3840 return new ParceledListSlice<PackageInfo>(list); 3841 } 3842 } 3843 3844 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3845 String[] permissions, boolean[] tmp, int flags, int userId) { 3846 int numMatch = 0; 3847 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3848 for (int i=0; i<permissions.length; i++) { 3849 if (gp.grantedPermissions.contains(permissions[i])) { 3850 tmp[i] = true; 3851 numMatch++; 3852 } else { 3853 tmp[i] = false; 3854 } 3855 } 3856 if (numMatch == 0) { 3857 return; 3858 } 3859 PackageInfo pi; 3860 if (ps.pkg != null) { 3861 pi = generatePackageInfo(ps.pkg, flags, userId); 3862 } else { 3863 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3864 } 3865 // The above might return null in cases of uninstalled apps or install-state 3866 // skew across users/profiles. 3867 if (pi != null) { 3868 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3869 if (numMatch == permissions.length) { 3870 pi.requestedPermissions = permissions; 3871 } else { 3872 pi.requestedPermissions = new String[numMatch]; 3873 numMatch = 0; 3874 for (int i=0; i<permissions.length; i++) { 3875 if (tmp[i]) { 3876 pi.requestedPermissions[numMatch] = permissions[i]; 3877 numMatch++; 3878 } 3879 } 3880 } 3881 } 3882 list.add(pi); 3883 } 3884 } 3885 3886 @Override 3887 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3888 String[] permissions, int flags, int userId) { 3889 if (!sUserManager.exists(userId)) return null; 3890 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3891 3892 // writer 3893 synchronized (mPackages) { 3894 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3895 boolean[] tmpBools = new boolean[permissions.length]; 3896 if (listUninstalled) { 3897 for (PackageSetting ps : mSettings.mPackages.values()) { 3898 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3899 } 3900 } else { 3901 for (PackageParser.Package pkg : mPackages.values()) { 3902 PackageSetting ps = (PackageSetting)pkg.mExtras; 3903 if (ps != null) { 3904 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3905 userId); 3906 } 3907 } 3908 } 3909 3910 return new ParceledListSlice<PackageInfo>(list); 3911 } 3912 } 3913 3914 @Override 3915 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3916 if (!sUserManager.exists(userId)) return null; 3917 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3918 3919 // writer 3920 synchronized (mPackages) { 3921 ArrayList<ApplicationInfo> list; 3922 if (listUninstalled) { 3923 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3924 for (PackageSetting ps : mSettings.mPackages.values()) { 3925 ApplicationInfo ai; 3926 if (ps.pkg != null) { 3927 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3928 ps.readUserState(userId), userId); 3929 } else { 3930 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3931 } 3932 if (ai != null) { 3933 list.add(ai); 3934 } 3935 } 3936 } else { 3937 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3938 for (PackageParser.Package p : mPackages.values()) { 3939 if (p.mExtras != null) { 3940 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3941 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3942 if (ai != null) { 3943 list.add(ai); 3944 } 3945 } 3946 } 3947 } 3948 3949 return new ParceledListSlice<ApplicationInfo>(list); 3950 } 3951 } 3952 3953 public List<ApplicationInfo> getPersistentApplications(int flags) { 3954 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3955 3956 // reader 3957 synchronized (mPackages) { 3958 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3959 final int userId = UserHandle.getCallingUserId(); 3960 while (i.hasNext()) { 3961 final PackageParser.Package p = i.next(); 3962 if (p.applicationInfo != null 3963 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3964 && (!mSafeMode || isSystemApp(p))) { 3965 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3966 if (ps != null) { 3967 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3968 ps.readUserState(userId), userId); 3969 if (ai != null) { 3970 finalList.add(ai); 3971 } 3972 } 3973 } 3974 } 3975 } 3976 3977 return finalList; 3978 } 3979 3980 @Override 3981 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3982 if (!sUserManager.exists(userId)) return null; 3983 // reader 3984 synchronized (mPackages) { 3985 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3986 PackageSetting ps = provider != null 3987 ? mSettings.mPackages.get(provider.owner.packageName) 3988 : null; 3989 return ps != null 3990 && mSettings.isEnabledLPr(provider.info, flags, userId) 3991 && (!mSafeMode || (provider.info.applicationInfo.flags 3992 &ApplicationInfo.FLAG_SYSTEM) != 0) 3993 ? PackageParser.generateProviderInfo(provider, flags, 3994 ps.readUserState(userId), userId) 3995 : null; 3996 } 3997 } 3998 3999 /** 4000 * @deprecated 4001 */ 4002 @Deprecated 4003 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4004 // reader 4005 synchronized (mPackages) { 4006 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4007 .entrySet().iterator(); 4008 final int userId = UserHandle.getCallingUserId(); 4009 while (i.hasNext()) { 4010 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4011 PackageParser.Provider p = entry.getValue(); 4012 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4013 4014 if (ps != null && p.syncable 4015 && (!mSafeMode || (p.info.applicationInfo.flags 4016 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4017 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4018 ps.readUserState(userId), userId); 4019 if (info != null) { 4020 outNames.add(entry.getKey()); 4021 outInfo.add(info); 4022 } 4023 } 4024 } 4025 } 4026 } 4027 4028 @Override 4029 public List<ProviderInfo> queryContentProviders(String processName, 4030 int uid, int flags) { 4031 ArrayList<ProviderInfo> finalList = null; 4032 // reader 4033 synchronized (mPackages) { 4034 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4035 final int userId = processName != null ? 4036 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4037 while (i.hasNext()) { 4038 final PackageParser.Provider p = i.next(); 4039 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4040 if (ps != null && p.info.authority != null 4041 && (processName == null 4042 || (p.info.processName.equals(processName) 4043 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4044 && mSettings.isEnabledLPr(p.info, flags, userId) 4045 && (!mSafeMode 4046 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4047 if (finalList == null) { 4048 finalList = new ArrayList<ProviderInfo>(3); 4049 } 4050 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4051 ps.readUserState(userId), userId); 4052 if (info != null) { 4053 finalList.add(info); 4054 } 4055 } 4056 } 4057 } 4058 4059 if (finalList != null) { 4060 Collections.sort(finalList, mProviderInitOrderSorter); 4061 } 4062 4063 return finalList; 4064 } 4065 4066 @Override 4067 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4068 int flags) { 4069 // reader 4070 synchronized (mPackages) { 4071 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4072 return PackageParser.generateInstrumentationInfo(i, flags); 4073 } 4074 } 4075 4076 @Override 4077 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4078 int flags) { 4079 ArrayList<InstrumentationInfo> finalList = 4080 new ArrayList<InstrumentationInfo>(); 4081 4082 // reader 4083 synchronized (mPackages) { 4084 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4085 while (i.hasNext()) { 4086 final PackageParser.Instrumentation p = i.next(); 4087 if (targetPackage == null 4088 || targetPackage.equals(p.info.targetPackage)) { 4089 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4090 flags); 4091 if (ii != null) { 4092 finalList.add(ii); 4093 } 4094 } 4095 } 4096 } 4097 4098 return finalList; 4099 } 4100 4101 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4102 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4103 if (overlays == null) { 4104 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4105 return; 4106 } 4107 for (PackageParser.Package opkg : overlays.values()) { 4108 // Not much to do if idmap fails: we already logged the error 4109 // and we certainly don't want to abort installation of pkg simply 4110 // because an overlay didn't fit properly. For these reasons, 4111 // ignore the return value of createIdmapForPackagePairLI. 4112 createIdmapForPackagePairLI(pkg, opkg); 4113 } 4114 } 4115 4116 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4117 PackageParser.Package opkg) { 4118 if (!opkg.mTrustedOverlay) { 4119 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4120 opkg.baseCodePath + ": overlay not trusted"); 4121 return false; 4122 } 4123 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4124 if (overlaySet == null) { 4125 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4126 opkg.baseCodePath + " but target package has no known overlays"); 4127 return false; 4128 } 4129 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4130 // TODO: generate idmap for split APKs 4131 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4132 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4133 + opkg.baseCodePath); 4134 return false; 4135 } 4136 PackageParser.Package[] overlayArray = 4137 overlaySet.values().toArray(new PackageParser.Package[0]); 4138 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4139 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4140 return p1.mOverlayPriority - p2.mOverlayPriority; 4141 } 4142 }; 4143 Arrays.sort(overlayArray, cmp); 4144 4145 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4146 int i = 0; 4147 for (PackageParser.Package p : overlayArray) { 4148 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4149 } 4150 return true; 4151 } 4152 4153 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4154 final File[] files = dir.listFiles(); 4155 if (ArrayUtils.isEmpty(files)) { 4156 Log.d(TAG, "No files in app dir " + dir); 4157 return; 4158 } 4159 4160 if (DEBUG_PACKAGE_SCANNING) { 4161 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4162 + " flags=0x" + Integer.toHexString(parseFlags)); 4163 } 4164 4165 for (File file : files) { 4166 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4167 && !PackageInstallerService.isStageName(file.getName()); 4168 if (!isPackage) { 4169 // Ignore entries which are not packages 4170 continue; 4171 } 4172 try { 4173 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4174 scanFlags, currentTime, null); 4175 } catch (PackageManagerException e) { 4176 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4177 4178 // Delete invalid userdata apps 4179 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4180 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4181 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4182 if (file.isDirectory()) { 4183 mInstaller.rmPackageDir(file.getAbsolutePath()); 4184 } else { 4185 file.delete(); 4186 } 4187 } 4188 } 4189 } 4190 } 4191 4192 private static File getSettingsProblemFile() { 4193 File dataDir = Environment.getDataDirectory(); 4194 File systemDir = new File(dataDir, "system"); 4195 File fname = new File(systemDir, "uiderrors.txt"); 4196 return fname; 4197 } 4198 4199 static void reportSettingsProblem(int priority, String msg) { 4200 logCriticalInfo(priority, msg); 4201 } 4202 4203 static void logCriticalInfo(int priority, String msg) { 4204 Slog.println(priority, TAG, msg); 4205 EventLogTags.writePmCriticalInfo(msg); 4206 try { 4207 File fname = getSettingsProblemFile(); 4208 FileOutputStream out = new FileOutputStream(fname, true); 4209 PrintWriter pw = new FastPrintWriter(out); 4210 SimpleDateFormat formatter = new SimpleDateFormat(); 4211 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4212 pw.println(dateString + ": " + msg); 4213 pw.close(); 4214 FileUtils.setPermissions( 4215 fname.toString(), 4216 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4217 -1, -1); 4218 } catch (java.io.IOException e) { 4219 } 4220 } 4221 4222 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4223 PackageParser.Package pkg, File srcFile, int parseFlags) 4224 throws PackageManagerException { 4225 if (ps != null 4226 && ps.codePath.equals(srcFile) 4227 && ps.timeStamp == srcFile.lastModified() 4228 && !isCompatSignatureUpdateNeeded(pkg) 4229 && !isRecoverSignatureUpdateNeeded(pkg)) { 4230 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4231 if (ps.signatures.mSignatures != null 4232 && ps.signatures.mSignatures.length != 0 4233 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4234 // Optimization: reuse the existing cached certificates 4235 // if the package appears to be unchanged. 4236 pkg.mSignatures = ps.signatures.mSignatures; 4237 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4238 synchronized (mPackages) { 4239 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4240 } 4241 return; 4242 } 4243 4244 Slog.w(TAG, "PackageSetting for " + ps.name 4245 + " is missing signatures. Collecting certs again to recover them."); 4246 } else { 4247 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4248 } 4249 4250 try { 4251 pp.collectCertificates(pkg, parseFlags); 4252 pp.collectManifestDigest(pkg); 4253 } catch (PackageParserException e) { 4254 throw PackageManagerException.from(e); 4255 } 4256 } 4257 4258 /* 4259 * Scan a package and return the newly parsed package. 4260 * Returns null in case of errors and the error code is stored in mLastScanError 4261 */ 4262 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4263 long currentTime, UserHandle user) throws PackageManagerException { 4264 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4265 parseFlags |= mDefParseFlags; 4266 PackageParser pp = new PackageParser(); 4267 pp.setSeparateProcesses(mSeparateProcesses); 4268 pp.setOnlyCoreApps(mOnlyCore); 4269 pp.setDisplayMetrics(mMetrics); 4270 4271 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4272 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4273 } 4274 4275 final PackageParser.Package pkg; 4276 try { 4277 pkg = pp.parsePackage(scanFile, parseFlags); 4278 } catch (PackageParserException e) { 4279 throw PackageManagerException.from(e); 4280 } 4281 4282 PackageSetting ps = null; 4283 PackageSetting updatedPkg; 4284 // reader 4285 synchronized (mPackages) { 4286 // Look to see if we already know about this package. 4287 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4288 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4289 // This package has been renamed to its original name. Let's 4290 // use that. 4291 ps = mSettings.peekPackageLPr(oldName); 4292 } 4293 // If there was no original package, see one for the real package name. 4294 if (ps == null) { 4295 ps = mSettings.peekPackageLPr(pkg.packageName); 4296 } 4297 // Check to see if this package could be hiding/updating a system 4298 // package. Must look for it either under the original or real 4299 // package name depending on our state. 4300 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4301 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4302 } 4303 boolean updatedPkgBetter = false; 4304 // First check if this is a system package that may involve an update 4305 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4306 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4307 // it needs to drop FLAG_PRIVILEGED. 4308 if (locationIsPrivileged(scanFile)) { 4309 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4310 } else { 4311 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4312 } 4313 4314 if (ps != null && !ps.codePath.equals(scanFile)) { 4315 // The path has changed from what was last scanned... check the 4316 // version of the new path against what we have stored to determine 4317 // what to do. 4318 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4319 if (pkg.mVersionCode <= ps.versionCode) { 4320 // The system package has been updated and the code path does not match 4321 // Ignore entry. Skip it. 4322 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4323 + " ignored: updated version " + ps.versionCode 4324 + " better than this " + pkg.mVersionCode); 4325 if (!updatedPkg.codePath.equals(scanFile)) { 4326 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4327 + ps.name + " changing from " + updatedPkg.codePathString 4328 + " to " + scanFile); 4329 updatedPkg.codePath = scanFile; 4330 updatedPkg.codePathString = scanFile.toString(); 4331 updatedPkg.resourcePath = scanFile; 4332 updatedPkg.resourcePathString = scanFile.toString(); 4333 } 4334 updatedPkg.pkg = pkg; 4335 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4336 } else { 4337 // The current app on the system partition is better than 4338 // what we have updated to on the data partition; switch 4339 // back to the system partition version. 4340 // At this point, its safely assumed that package installation for 4341 // apps in system partition will go through. If not there won't be a working 4342 // version of the app 4343 // writer 4344 synchronized (mPackages) { 4345 // Just remove the loaded entries from package lists. 4346 mPackages.remove(ps.name); 4347 } 4348 4349 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4350 + " reverting from " + ps.codePathString 4351 + ": new version " + pkg.mVersionCode 4352 + " better than installed " + ps.versionCode); 4353 4354 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4355 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4356 getAppDexInstructionSets(ps)); 4357 synchronized (mInstallLock) { 4358 args.cleanUpResourcesLI(); 4359 } 4360 synchronized (mPackages) { 4361 mSettings.enableSystemPackageLPw(ps.name); 4362 } 4363 updatedPkgBetter = true; 4364 } 4365 } 4366 } 4367 4368 if (updatedPkg != null) { 4369 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4370 // initially 4371 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4372 4373 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4374 // flag set initially 4375 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4376 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4377 } 4378 } 4379 4380 // Verify certificates against what was last scanned 4381 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4382 4383 /* 4384 * A new system app appeared, but we already had a non-system one of the 4385 * same name installed earlier. 4386 */ 4387 boolean shouldHideSystemApp = false; 4388 if (updatedPkg == null && ps != null 4389 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4390 /* 4391 * Check to make sure the signatures match first. If they don't, 4392 * wipe the installed application and its data. 4393 */ 4394 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4395 != PackageManager.SIGNATURE_MATCH) { 4396 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4397 + " signatures don't match existing userdata copy; removing"); 4398 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4399 ps = null; 4400 } else { 4401 /* 4402 * If the newly-added system app is an older version than the 4403 * already installed version, hide it. It will be scanned later 4404 * and re-added like an update. 4405 */ 4406 if (pkg.mVersionCode <= ps.versionCode) { 4407 shouldHideSystemApp = true; 4408 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4409 + " but new version " + pkg.mVersionCode + " better than installed " 4410 + ps.versionCode + "; hiding system"); 4411 } else { 4412 /* 4413 * The newly found system app is a newer version that the 4414 * one previously installed. Simply remove the 4415 * already-installed application and replace it with our own 4416 * while keeping the application data. 4417 */ 4418 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4419 + " reverting from " + ps.codePathString + ": new version " 4420 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4421 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4422 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4423 getAppDexInstructionSets(ps)); 4424 synchronized (mInstallLock) { 4425 args.cleanUpResourcesLI(); 4426 } 4427 } 4428 } 4429 } 4430 4431 // The apk is forward locked (not public) if its code and resources 4432 // are kept in different files. (except for app in either system or 4433 // vendor path). 4434 // TODO grab this value from PackageSettings 4435 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4436 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4437 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4438 } 4439 } 4440 4441 // TODO: extend to support forward-locked splits 4442 String resourcePath = null; 4443 String baseResourcePath = null; 4444 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4445 if (ps != null && ps.resourcePathString != null) { 4446 resourcePath = ps.resourcePathString; 4447 baseResourcePath = ps.resourcePathString; 4448 } else { 4449 // Should not happen at all. Just log an error. 4450 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4451 } 4452 } else { 4453 resourcePath = pkg.codePath; 4454 baseResourcePath = pkg.baseCodePath; 4455 } 4456 4457 // Set application objects path explicitly. 4458 pkg.applicationInfo.setCodePath(pkg.codePath); 4459 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4460 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4461 pkg.applicationInfo.setResourcePath(resourcePath); 4462 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4463 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4464 4465 // Note that we invoke the following method only if we are about to unpack an application 4466 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4467 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4468 4469 /* 4470 * If the system app should be overridden by a previously installed 4471 * data, hide the system app now and let the /data/app scan pick it up 4472 * again. 4473 */ 4474 if (shouldHideSystemApp) { 4475 synchronized (mPackages) { 4476 /* 4477 * We have to grant systems permissions before we hide, because 4478 * grantPermissions will assume the package update is trying to 4479 * expand its permissions. 4480 */ 4481 grantPermissionsLPw(pkg, true, pkg.packageName); 4482 mSettings.disableSystemPackageLPw(pkg.packageName); 4483 } 4484 } 4485 4486 return scannedPkg; 4487 } 4488 4489 private static String fixProcessName(String defProcessName, 4490 String processName, int uid) { 4491 if (processName == null) { 4492 return defProcessName; 4493 } 4494 return processName; 4495 } 4496 4497 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4498 throws PackageManagerException { 4499 if (pkgSetting.signatures.mSignatures != null) { 4500 // Already existing package. Make sure signatures match 4501 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4502 == PackageManager.SIGNATURE_MATCH; 4503 if (!match) { 4504 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4505 == PackageManager.SIGNATURE_MATCH; 4506 } 4507 if (!match) { 4508 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 4509 == PackageManager.SIGNATURE_MATCH; 4510 } 4511 if (!match) { 4512 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4513 + pkg.packageName + " signatures do not match the " 4514 + "previously installed version; ignoring!"); 4515 } 4516 } 4517 4518 // Check for shared user signatures 4519 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4520 // Already existing package. Make sure signatures match 4521 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4522 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4523 if (!match) { 4524 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4525 == PackageManager.SIGNATURE_MATCH; 4526 } 4527 if (!match) { 4528 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 4529 == PackageManager.SIGNATURE_MATCH; 4530 } 4531 if (!match) { 4532 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4533 "Package " + pkg.packageName 4534 + " has no signatures that match those in shared user " 4535 + pkgSetting.sharedUser.name + "; ignoring!"); 4536 } 4537 } 4538 } 4539 4540 /** 4541 * Enforces that only the system UID or root's UID can call a method exposed 4542 * via Binder. 4543 * 4544 * @param message used as message if SecurityException is thrown 4545 * @throws SecurityException if the caller is not system or root 4546 */ 4547 private static final void enforceSystemOrRoot(String message) { 4548 final int uid = Binder.getCallingUid(); 4549 if (uid != Process.SYSTEM_UID && uid != 0) { 4550 throw new SecurityException(message); 4551 } 4552 } 4553 4554 @Override 4555 public void performBootDexOpt() { 4556 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4557 4558 // Before everything else, see whether we need to fstrim. 4559 try { 4560 IMountService ms = PackageHelper.getMountService(); 4561 if (ms != null) { 4562 final boolean isUpgrade = isUpgrade(); 4563 boolean doTrim = isUpgrade; 4564 if (doTrim) { 4565 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 4566 } else { 4567 final long interval = android.provider.Settings.Global.getLong( 4568 mContext.getContentResolver(), 4569 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 4570 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 4571 if (interval > 0) { 4572 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 4573 if (timeSinceLast > interval) { 4574 doTrim = true; 4575 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 4576 + "; running immediately"); 4577 } 4578 } 4579 } 4580 if (doTrim) { 4581 if (!isFirstBoot()) { 4582 try { 4583 ActivityManagerNative.getDefault().showBootMessage( 4584 mContext.getResources().getString( 4585 R.string.android_upgrading_fstrim), true); 4586 } catch (RemoteException e) { 4587 } 4588 } 4589 ms.runMaintenance(); 4590 } 4591 } else { 4592 Slog.e(TAG, "Mount service unavailable!"); 4593 } 4594 } catch (RemoteException e) { 4595 // Can't happen; MountService is local 4596 } 4597 4598 final ArraySet<PackageParser.Package> pkgs; 4599 synchronized (mPackages) { 4600 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 4601 } 4602 4603 if (pkgs != null) { 4604 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4605 // in case the device runs out of space. 4606 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4607 // Give priority to core apps. 4608 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4609 PackageParser.Package pkg = it.next(); 4610 if (pkg.coreApp) { 4611 if (DEBUG_DEXOPT) { 4612 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 4613 } 4614 sortedPkgs.add(pkg); 4615 it.remove(); 4616 } 4617 } 4618 // Give priority to system apps that listen for pre boot complete. 4619 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4620 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 4621 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4622 PackageParser.Package pkg = it.next(); 4623 if (pkgNames.contains(pkg.packageName)) { 4624 if (DEBUG_DEXOPT) { 4625 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 4626 } 4627 sortedPkgs.add(pkg); 4628 it.remove(); 4629 } 4630 } 4631 // Give priority to system apps. 4632 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4633 PackageParser.Package pkg = it.next(); 4634 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 4635 if (DEBUG_DEXOPT) { 4636 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 4637 } 4638 sortedPkgs.add(pkg); 4639 it.remove(); 4640 } 4641 } 4642 // Give priority to updated system apps. 4643 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4644 PackageParser.Package pkg = it.next(); 4645 if (pkg.isUpdatedSystemApp()) { 4646 if (DEBUG_DEXOPT) { 4647 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 4648 } 4649 sortedPkgs.add(pkg); 4650 it.remove(); 4651 } 4652 } 4653 // Give priority to apps that listen for boot complete. 4654 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4655 pkgNames = getPackageNamesForIntent(intent); 4656 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4657 PackageParser.Package pkg = it.next(); 4658 if (pkgNames.contains(pkg.packageName)) { 4659 if (DEBUG_DEXOPT) { 4660 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 4661 } 4662 sortedPkgs.add(pkg); 4663 it.remove(); 4664 } 4665 } 4666 // Filter out packages that aren't recently used. 4667 filterRecentlyUsedApps(pkgs); 4668 // Add all remaining apps. 4669 for (PackageParser.Package pkg : pkgs) { 4670 if (DEBUG_DEXOPT) { 4671 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 4672 } 4673 sortedPkgs.add(pkg); 4674 } 4675 4676 // If we want to be lazy, filter everything that wasn't recently used. 4677 if (mLazyDexOpt) { 4678 filterRecentlyUsedApps(sortedPkgs); 4679 } 4680 4681 int i = 0; 4682 int total = sortedPkgs.size(); 4683 File dataDir = Environment.getDataDirectory(); 4684 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 4685 if (lowThreshold == 0) { 4686 throw new IllegalStateException("Invalid low memory threshold"); 4687 } 4688 for (PackageParser.Package pkg : sortedPkgs) { 4689 long usableSpace = dataDir.getUsableSpace(); 4690 if (usableSpace < lowThreshold) { 4691 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 4692 break; 4693 } 4694 performBootDexOpt(pkg, ++i, total); 4695 } 4696 } 4697 } 4698 4699 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 4700 // Filter out packages that aren't recently used. 4701 // 4702 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4703 // should do a full dexopt. 4704 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4705 int total = pkgs.size(); 4706 int skipped = 0; 4707 long now = System.currentTimeMillis(); 4708 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4709 PackageParser.Package pkg = i.next(); 4710 long then = pkg.mLastPackageUsageTimeInMills; 4711 if (then + mDexOptLRUThresholdInMills < now) { 4712 if (DEBUG_DEXOPT) { 4713 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4714 ((then == 0) ? "never" : new Date(then))); 4715 } 4716 i.remove(); 4717 skipped++; 4718 } 4719 } 4720 if (DEBUG_DEXOPT) { 4721 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4722 } 4723 } 4724 } 4725 4726 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 4727 List<ResolveInfo> ris = null; 4728 try { 4729 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4730 intent, null, 0, UserHandle.USER_OWNER); 4731 } catch (RemoteException e) { 4732 } 4733 ArraySet<String> pkgNames = new ArraySet<String>(); 4734 if (ris != null) { 4735 for (ResolveInfo ri : ris) { 4736 pkgNames.add(ri.activityInfo.packageName); 4737 } 4738 } 4739 return pkgNames; 4740 } 4741 4742 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4743 if (DEBUG_DEXOPT) { 4744 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4745 } 4746 if (!isFirstBoot()) { 4747 try { 4748 ActivityManagerNative.getDefault().showBootMessage( 4749 mContext.getResources().getString(R.string.android_upgrading_apk, 4750 curr, total), true); 4751 } catch (RemoteException e) { 4752 } 4753 } 4754 PackageParser.Package p = pkg; 4755 synchronized (mInstallLock) { 4756 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 4757 false /* force dex */, false /* defer */, true /* include dependencies */); 4758 } 4759 } 4760 4761 @Override 4762 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4763 return performDexOpt(packageName, instructionSet, false); 4764 } 4765 4766 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4767 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4768 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4769 if (!dexopt && !updateUsage) { 4770 // We aren't going to dexopt or update usage, so bail early. 4771 return false; 4772 } 4773 PackageParser.Package p; 4774 final String targetInstructionSet; 4775 synchronized (mPackages) { 4776 p = mPackages.get(packageName); 4777 if (p == null) { 4778 return false; 4779 } 4780 if (updateUsage) { 4781 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4782 } 4783 mPackageUsage.write(false); 4784 if (!dexopt) { 4785 // We aren't going to dexopt, so bail early. 4786 return false; 4787 } 4788 4789 targetInstructionSet = instructionSet != null ? instructionSet : 4790 getPrimaryInstructionSet(p.applicationInfo); 4791 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4792 return false; 4793 } 4794 } 4795 4796 synchronized (mInstallLock) { 4797 final String[] instructionSets = new String[] { targetInstructionSet }; 4798 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 4799 false /* forceDex */, false /* defer */, true /* inclDependencies */); 4800 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 4801 } 4802 } 4803 4804 public ArraySet<String> getPackagesThatNeedDexOpt() { 4805 ArraySet<String> pkgs = null; 4806 synchronized (mPackages) { 4807 for (PackageParser.Package p : mPackages.values()) { 4808 if (DEBUG_DEXOPT) { 4809 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4810 } 4811 if (!p.mDexOptPerformed.isEmpty()) { 4812 continue; 4813 } 4814 if (pkgs == null) { 4815 pkgs = new ArraySet<String>(); 4816 } 4817 pkgs.add(p.packageName); 4818 } 4819 } 4820 return pkgs; 4821 } 4822 4823 public void shutdown() { 4824 mPackageUsage.write(true); 4825 } 4826 4827 @Override 4828 public void forceDexOpt(String packageName) { 4829 enforceSystemOrRoot("forceDexOpt"); 4830 4831 PackageParser.Package pkg; 4832 synchronized (mPackages) { 4833 pkg = mPackages.get(packageName); 4834 if (pkg == null) { 4835 throw new IllegalArgumentException("Missing package: " + packageName); 4836 } 4837 } 4838 4839 synchronized (mInstallLock) { 4840 final String[] instructionSets = new String[] { 4841 getPrimaryInstructionSet(pkg.applicationInfo) }; 4842 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 4843 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 4844 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 4845 throw new IllegalStateException("Failed to dexopt: " + res); 4846 } 4847 } 4848 } 4849 4850 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4851 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4852 Slog.w(TAG, "Unable to update from " + oldPkg.name 4853 + " to " + newPkg.packageName 4854 + ": old package not in system partition"); 4855 return false; 4856 } else if (mPackages.get(oldPkg.name) != null) { 4857 Slog.w(TAG, "Unable to update from " + oldPkg.name 4858 + " to " + newPkg.packageName 4859 + ": old package still exists"); 4860 return false; 4861 } 4862 return true; 4863 } 4864 4865 private File getDataPathForPackage(String packageName, int userId) { 4866 /* 4867 * Until we fully support multiple users, return the directory we 4868 * previously would have. The PackageManagerTests will need to be 4869 * revised when this is changed back.. 4870 */ 4871 if (userId == 0) { 4872 return new File(mAppDataDir, packageName); 4873 } else { 4874 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4875 + File.separator + packageName); 4876 } 4877 } 4878 4879 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4880 int[] users = sUserManager.getUserIds(); 4881 int res = mInstaller.install(packageName, uid, uid, seinfo); 4882 if (res < 0) { 4883 return res; 4884 } 4885 for (int user : users) { 4886 if (user != 0) { 4887 res = mInstaller.createUserData(packageName, 4888 UserHandle.getUid(user, uid), user, seinfo); 4889 if (res < 0) { 4890 return res; 4891 } 4892 } 4893 } 4894 return res; 4895 } 4896 4897 private int removeDataDirsLI(String packageName) { 4898 int[] users = sUserManager.getUserIds(); 4899 int res = 0; 4900 for (int user : users) { 4901 int resInner = mInstaller.remove(packageName, user); 4902 if (resInner < 0) { 4903 res = resInner; 4904 } 4905 } 4906 4907 return res; 4908 } 4909 4910 private int deleteCodeCacheDirsLI(String packageName) { 4911 int[] users = sUserManager.getUserIds(); 4912 int res = 0; 4913 for (int user : users) { 4914 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4915 if (resInner < 0) { 4916 res = resInner; 4917 } 4918 } 4919 return res; 4920 } 4921 4922 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4923 PackageParser.Package changingLib) { 4924 if (file.path != null) { 4925 usesLibraryFiles.add(file.path); 4926 return; 4927 } 4928 PackageParser.Package p = mPackages.get(file.apk); 4929 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4930 // If we are doing this while in the middle of updating a library apk, 4931 // then we need to make sure to use that new apk for determining the 4932 // dependencies here. (We haven't yet finished committing the new apk 4933 // to the package manager state.) 4934 if (p == null || p.packageName.equals(changingLib.packageName)) { 4935 p = changingLib; 4936 } 4937 } 4938 if (p != null) { 4939 usesLibraryFiles.addAll(p.getAllCodePaths()); 4940 } 4941 } 4942 4943 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4944 PackageParser.Package changingLib) throws PackageManagerException { 4945 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4946 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4947 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4948 for (int i=0; i<N; i++) { 4949 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4950 if (file == null) { 4951 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4952 "Package " + pkg.packageName + " requires unavailable shared library " 4953 + pkg.usesLibraries.get(i) + "; failing!"); 4954 } 4955 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4956 } 4957 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4958 for (int i=0; i<N; i++) { 4959 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4960 if (file == null) { 4961 Slog.w(TAG, "Package " + pkg.packageName 4962 + " desires unavailable shared library " 4963 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4964 } else { 4965 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4966 } 4967 } 4968 N = usesLibraryFiles.size(); 4969 if (N > 0) { 4970 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4971 } else { 4972 pkg.usesLibraryFiles = null; 4973 } 4974 } 4975 } 4976 4977 private static boolean hasString(List<String> list, List<String> which) { 4978 if (list == null) { 4979 return false; 4980 } 4981 for (int i=list.size()-1; i>=0; i--) { 4982 for (int j=which.size()-1; j>=0; j--) { 4983 if (which.get(j).equals(list.get(i))) { 4984 return true; 4985 } 4986 } 4987 } 4988 return false; 4989 } 4990 4991 private void updateAllSharedLibrariesLPw() { 4992 for (PackageParser.Package pkg : mPackages.values()) { 4993 try { 4994 updateSharedLibrariesLPw(pkg, null); 4995 } catch (PackageManagerException e) { 4996 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4997 } 4998 } 4999 } 5000 5001 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5002 PackageParser.Package changingPkg) { 5003 ArrayList<PackageParser.Package> res = null; 5004 for (PackageParser.Package pkg : mPackages.values()) { 5005 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5006 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5007 if (res == null) { 5008 res = new ArrayList<PackageParser.Package>(); 5009 } 5010 res.add(pkg); 5011 try { 5012 updateSharedLibrariesLPw(pkg, changingPkg); 5013 } catch (PackageManagerException e) { 5014 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5015 } 5016 } 5017 } 5018 return res; 5019 } 5020 5021 /** 5022 * Derive the value of the {@code cpuAbiOverride} based on the provided 5023 * value and an optional stored value from the package settings. 5024 */ 5025 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5026 String cpuAbiOverride = null; 5027 5028 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5029 cpuAbiOverride = null; 5030 } else if (abiOverride != null) { 5031 cpuAbiOverride = abiOverride; 5032 } else if (settings != null) { 5033 cpuAbiOverride = settings.cpuAbiOverrideString; 5034 } 5035 5036 return cpuAbiOverride; 5037 } 5038 5039 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5040 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5041 boolean success = false; 5042 try { 5043 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5044 currentTime, user); 5045 success = true; 5046 return res; 5047 } finally { 5048 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5049 removeDataDirsLI(pkg.packageName); 5050 } 5051 } 5052 } 5053 5054 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5055 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5056 final File scanFile = new File(pkg.codePath); 5057 if (pkg.applicationInfo.getCodePath() == null || 5058 pkg.applicationInfo.getResourcePath() == null) { 5059 // Bail out. The resource and code paths haven't been set. 5060 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5061 "Code and resource paths haven't been set correctly"); 5062 } 5063 5064 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5065 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5066 } else { 5067 // Only allow system apps to be flagged as core apps. 5068 pkg.coreApp = false; 5069 } 5070 5071 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5072 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5073 } 5074 5075 if (mCustomResolverComponentName != null && 5076 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5077 setUpCustomResolverActivity(pkg); 5078 } 5079 5080 if (pkg.packageName.equals("android")) { 5081 synchronized (mPackages) { 5082 if (mAndroidApplication != null) { 5083 Slog.w(TAG, "*************************************************"); 5084 Slog.w(TAG, "Core android package being redefined. Skipping."); 5085 Slog.w(TAG, " file=" + scanFile); 5086 Slog.w(TAG, "*************************************************"); 5087 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5088 "Core android package being redefined. Skipping."); 5089 } 5090 5091 // Set up information for our fall-back user intent resolution activity. 5092 mPlatformPackage = pkg; 5093 pkg.mVersionCode = mSdkVersion; 5094 mAndroidApplication = pkg.applicationInfo; 5095 5096 if (!mResolverReplaced) { 5097 mResolveActivity.applicationInfo = mAndroidApplication; 5098 mResolveActivity.name = ResolverActivity.class.getName(); 5099 mResolveActivity.packageName = mAndroidApplication.packageName; 5100 mResolveActivity.processName = "system:ui"; 5101 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5102 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5103 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5104 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5105 mResolveActivity.exported = true; 5106 mResolveActivity.enabled = true; 5107 mResolveInfo.activityInfo = mResolveActivity; 5108 mResolveInfo.priority = 0; 5109 mResolveInfo.preferredOrder = 0; 5110 mResolveInfo.match = 0; 5111 mResolveComponentName = new ComponentName( 5112 mAndroidApplication.packageName, mResolveActivity.name); 5113 } 5114 } 5115 } 5116 5117 if (DEBUG_PACKAGE_SCANNING) { 5118 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5119 Log.d(TAG, "Scanning package " + pkg.packageName); 5120 } 5121 5122 if (mPackages.containsKey(pkg.packageName) 5123 || mSharedLibraries.containsKey(pkg.packageName)) { 5124 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5125 "Application package " + pkg.packageName 5126 + " already installed. Skipping duplicate."); 5127 } 5128 5129 // Initialize package source and resource directories 5130 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5131 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5132 5133 SharedUserSetting suid = null; 5134 PackageSetting pkgSetting = null; 5135 5136 if (!isSystemApp(pkg)) { 5137 // Only system apps can use these features. 5138 pkg.mOriginalPackages = null; 5139 pkg.mRealPackage = null; 5140 pkg.mAdoptPermissions = null; 5141 } 5142 5143 // writer 5144 synchronized (mPackages) { 5145 if (pkg.mSharedUserId != null) { 5146 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5147 if (suid == null) { 5148 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5149 "Creating application package " + pkg.packageName 5150 + " for shared user failed"); 5151 } 5152 if (DEBUG_PACKAGE_SCANNING) { 5153 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5154 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5155 + "): packages=" + suid.packages); 5156 } 5157 } 5158 5159 // Check if we are renaming from an original package name. 5160 PackageSetting origPackage = null; 5161 String realName = null; 5162 if (pkg.mOriginalPackages != null) { 5163 // This package may need to be renamed to a previously 5164 // installed name. Let's check on that... 5165 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5166 if (pkg.mOriginalPackages.contains(renamed)) { 5167 // This package had originally been installed as the 5168 // original name, and we have already taken care of 5169 // transitioning to the new one. Just update the new 5170 // one to continue using the old name. 5171 realName = pkg.mRealPackage; 5172 if (!pkg.packageName.equals(renamed)) { 5173 // Callers into this function may have already taken 5174 // care of renaming the package; only do it here if 5175 // it is not already done. 5176 pkg.setPackageName(renamed); 5177 } 5178 5179 } else { 5180 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5181 if ((origPackage = mSettings.peekPackageLPr( 5182 pkg.mOriginalPackages.get(i))) != null) { 5183 // We do have the package already installed under its 5184 // original name... should we use it? 5185 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5186 // New package is not compatible with original. 5187 origPackage = null; 5188 continue; 5189 } else if (origPackage.sharedUser != null) { 5190 // Make sure uid is compatible between packages. 5191 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5192 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5193 + " to " + pkg.packageName + ": old uid " 5194 + origPackage.sharedUser.name 5195 + " differs from " + pkg.mSharedUserId); 5196 origPackage = null; 5197 continue; 5198 } 5199 } else { 5200 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5201 + pkg.packageName + " to old name " + origPackage.name); 5202 } 5203 break; 5204 } 5205 } 5206 } 5207 } 5208 5209 if (mTransferedPackages.contains(pkg.packageName)) { 5210 Slog.w(TAG, "Package " + pkg.packageName 5211 + " was transferred to another, but its .apk remains"); 5212 } 5213 5214 // Just create the setting, don't add it yet. For already existing packages 5215 // the PkgSetting exists already and doesn't have to be created. 5216 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5217 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5218 pkg.applicationInfo.primaryCpuAbi, 5219 pkg.applicationInfo.secondaryCpuAbi, 5220 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5221 user, false); 5222 if (pkgSetting == null) { 5223 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5224 "Creating application package " + pkg.packageName + " failed"); 5225 } 5226 5227 if (pkgSetting.origPackage != null) { 5228 // If we are first transitioning from an original package, 5229 // fix up the new package's name now. We need to do this after 5230 // looking up the package under its new name, so getPackageLP 5231 // can take care of fiddling things correctly. 5232 pkg.setPackageName(origPackage.name); 5233 5234 // File a report about this. 5235 String msg = "New package " + pkgSetting.realName 5236 + " renamed to replace old package " + pkgSetting.name; 5237 reportSettingsProblem(Log.WARN, msg); 5238 5239 // Make a note of it. 5240 mTransferedPackages.add(origPackage.name); 5241 5242 // No longer need to retain this. 5243 pkgSetting.origPackage = null; 5244 } 5245 5246 if (realName != null) { 5247 // Make a note of it. 5248 mTransferedPackages.add(pkg.packageName); 5249 } 5250 5251 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5252 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5253 } 5254 5255 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5256 // Check all shared libraries and map to their actual file path. 5257 // We only do this here for apps not on a system dir, because those 5258 // are the only ones that can fail an install due to this. We 5259 // will take care of the system apps by updating all of their 5260 // library paths after the scan is done. 5261 updateSharedLibrariesLPw(pkg, null); 5262 } 5263 5264 if (mFoundPolicyFile) { 5265 SELinuxMMAC.assignSeinfoValue(pkg); 5266 } 5267 5268 pkg.applicationInfo.uid = pkgSetting.appId; 5269 pkg.mExtras = pkgSetting; 5270 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5271 try { 5272 verifySignaturesLP(pkgSetting, pkg); 5273 // We just determined the app is signed correctly, so bring 5274 // over the latest parsed certs. 5275 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5276 } catch (PackageManagerException e) { 5277 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5278 throw e; 5279 } 5280 // The signature has changed, but this package is in the system 5281 // image... let's recover! 5282 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5283 // However... if this package is part of a shared user, but it 5284 // doesn't match the signature of the shared user, let's fail. 5285 // What this means is that you can't change the signatures 5286 // associated with an overall shared user, which doesn't seem all 5287 // that unreasonable. 5288 if (pkgSetting.sharedUser != null) { 5289 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5290 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5291 throw new PackageManagerException( 5292 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5293 "Signature mismatch for shared user : " 5294 + pkgSetting.sharedUser); 5295 } 5296 } 5297 // File a report about this. 5298 String msg = "System package " + pkg.packageName 5299 + " signature changed; retaining data."; 5300 reportSettingsProblem(Log.WARN, msg); 5301 } 5302 } else { 5303 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5304 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5305 + pkg.packageName + " upgrade keys do not match the " 5306 + "previously installed version"); 5307 } else { 5308 // We just determined the app is signed correctly, so bring 5309 // over the latest parsed certs. 5310 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5311 } 5312 } 5313 // Verify that this new package doesn't have any content providers 5314 // that conflict with existing packages. Only do this if the 5315 // package isn't already installed, since we don't want to break 5316 // things that are installed. 5317 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5318 final int N = pkg.providers.size(); 5319 int i; 5320 for (i=0; i<N; i++) { 5321 PackageParser.Provider p = pkg.providers.get(i); 5322 if (p.info.authority != null) { 5323 String names[] = p.info.authority.split(";"); 5324 for (int j = 0; j < names.length; j++) { 5325 if (mProvidersByAuthority.containsKey(names[j])) { 5326 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5327 final String otherPackageName = 5328 ((other != null && other.getComponentName() != null) ? 5329 other.getComponentName().getPackageName() : "?"); 5330 throw new PackageManagerException( 5331 INSTALL_FAILED_CONFLICTING_PROVIDER, 5332 "Can't install because provider name " + names[j] 5333 + " (in package " + pkg.applicationInfo.packageName 5334 + ") is already used by " + otherPackageName); 5335 } 5336 } 5337 } 5338 } 5339 } 5340 5341 if (pkg.mAdoptPermissions != null) { 5342 // This package wants to adopt ownership of permissions from 5343 // another package. 5344 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5345 final String origName = pkg.mAdoptPermissions.get(i); 5346 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5347 if (orig != null) { 5348 if (verifyPackageUpdateLPr(orig, pkg)) { 5349 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5350 + pkg.packageName); 5351 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5352 } 5353 } 5354 } 5355 } 5356 } 5357 5358 final String pkgName = pkg.packageName; 5359 5360 final long scanFileTime = scanFile.lastModified(); 5361 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5362 pkg.applicationInfo.processName = fixProcessName( 5363 pkg.applicationInfo.packageName, 5364 pkg.applicationInfo.processName, 5365 pkg.applicationInfo.uid); 5366 5367 File dataPath; 5368 if (mPlatformPackage == pkg) { 5369 // The system package is special. 5370 dataPath = new File(Environment.getDataDirectory(), "system"); 5371 5372 pkg.applicationInfo.dataDir = dataPath.getPath(); 5373 5374 } else { 5375 // This is a normal package, need to make its data directory. 5376 dataPath = getDataPathForPackage(pkg.packageName, 0); 5377 5378 boolean uidError = false; 5379 if (dataPath.exists()) { 5380 int currentUid = 0; 5381 try { 5382 StructStat stat = Os.stat(dataPath.getPath()); 5383 currentUid = stat.st_uid; 5384 } catch (ErrnoException e) { 5385 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5386 } 5387 5388 // If we have mismatched owners for the data path, we have a problem. 5389 if (currentUid != pkg.applicationInfo.uid) { 5390 boolean recovered = false; 5391 if (currentUid == 0) { 5392 // The directory somehow became owned by root. Wow. 5393 // This is probably because the system was stopped while 5394 // installd was in the middle of messing with its libs 5395 // directory. Ask installd to fix that. 5396 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5397 pkg.applicationInfo.uid); 5398 if (ret >= 0) { 5399 recovered = true; 5400 String msg = "Package " + pkg.packageName 5401 + " unexpectedly changed to uid 0; recovered to " + 5402 + pkg.applicationInfo.uid; 5403 reportSettingsProblem(Log.WARN, msg); 5404 } 5405 } 5406 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5407 || (scanFlags&SCAN_BOOTING) != 0)) { 5408 // If this is a system app, we can at least delete its 5409 // current data so the application will still work. 5410 int ret = removeDataDirsLI(pkgName); 5411 if (ret >= 0) { 5412 // TODO: Kill the processes first 5413 // Old data gone! 5414 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5415 ? "System package " : "Third party package "; 5416 String msg = prefix + pkg.packageName 5417 + " has changed from uid: " 5418 + currentUid + " to " 5419 + pkg.applicationInfo.uid + "; old data erased"; 5420 reportSettingsProblem(Log.WARN, msg); 5421 recovered = true; 5422 5423 // And now re-install the app. 5424 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5425 pkg.applicationInfo.seinfo); 5426 if (ret == -1) { 5427 // Ack should not happen! 5428 msg = prefix + pkg.packageName 5429 + " could not have data directory re-created after delete."; 5430 reportSettingsProblem(Log.WARN, msg); 5431 throw new PackageManagerException( 5432 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5433 } 5434 } 5435 if (!recovered) { 5436 mHasSystemUidErrors = true; 5437 } 5438 } else if (!recovered) { 5439 // If we allow this install to proceed, we will be broken. 5440 // Abort, abort! 5441 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5442 "scanPackageLI"); 5443 } 5444 if (!recovered) { 5445 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5446 + pkg.applicationInfo.uid + "/fs_" 5447 + currentUid; 5448 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5449 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5450 String msg = "Package " + pkg.packageName 5451 + " has mismatched uid: " 5452 + currentUid + " on disk, " 5453 + pkg.applicationInfo.uid + " in settings"; 5454 // writer 5455 synchronized (mPackages) { 5456 mSettings.mReadMessages.append(msg); 5457 mSettings.mReadMessages.append('\n'); 5458 uidError = true; 5459 if (!pkgSetting.uidError) { 5460 reportSettingsProblem(Log.ERROR, msg); 5461 } 5462 } 5463 } 5464 } 5465 pkg.applicationInfo.dataDir = dataPath.getPath(); 5466 if (mShouldRestoreconData) { 5467 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5468 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5469 pkg.applicationInfo.uid); 5470 } 5471 } else { 5472 if (DEBUG_PACKAGE_SCANNING) { 5473 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5474 Log.v(TAG, "Want this data dir: " + dataPath); 5475 } 5476 //invoke installer to do the actual installation 5477 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5478 pkg.applicationInfo.seinfo); 5479 if (ret < 0) { 5480 // Error from installer 5481 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5482 "Unable to create data dirs [errorCode=" + ret + "]"); 5483 } 5484 5485 if (dataPath.exists()) { 5486 pkg.applicationInfo.dataDir = dataPath.getPath(); 5487 } else { 5488 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5489 pkg.applicationInfo.dataDir = null; 5490 } 5491 } 5492 5493 pkgSetting.uidError = uidError; 5494 } 5495 5496 final String path = scanFile.getPath(); 5497 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5498 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5499 setBundledAppAbisAndRoots(pkg, pkgSetting); 5500 5501 // If we haven't found any native libraries for the app, check if it has 5502 // renderscript code. We'll need to force the app to 32 bit if it has 5503 // renderscript bitcode. 5504 if (pkg.applicationInfo.primaryCpuAbi == null 5505 && pkg.applicationInfo.secondaryCpuAbi == null 5506 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5507 NativeLibraryHelper.Handle handle = null; 5508 try { 5509 handle = NativeLibraryHelper.Handle.create(scanFile); 5510 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5511 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5512 } 5513 } catch (IOException ioe) { 5514 Slog.w(TAG, "Error scanning system app : " + ioe); 5515 } finally { 5516 IoUtils.closeQuietly(handle); 5517 } 5518 } 5519 5520 setNativeLibraryPaths(pkg); 5521 } else { 5522 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 5523 deriveNonSystemPackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 5524 } else { 5525 // Verify the ABIs haven't changed since we last deduced them. 5526 String oldPrimaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 5527 String oldSecondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi; 5528 5529 // TODO: The only purpose of this code is to update the native library paths 5530 // based on the final install location. We can simplify this and avoid having 5531 // to scan the package again. 5532 deriveNonSystemPackageAbi(pkg, scanFile, cpuAbiOverride, false /* extract libs */); 5533 if (!TextUtils.equals(oldPrimaryCpuAbi, pkg.applicationInfo.primaryCpuAbi)) { 5534 throw new IllegalStateException("unexpected abi change for " + pkg.packageName + " (" 5535 + oldPrimaryCpuAbi + "-> " + pkg.applicationInfo.primaryCpuAbi); 5536 } 5537 5538 if (!TextUtils.equals(oldSecondaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi)) { 5539 throw new IllegalStateException("unexpected abi change for " + pkg.packageName + " (" 5540 + oldSecondaryCpuAbi + "-> " + pkg.applicationInfo.secondaryCpuAbi); 5541 } 5542 } 5543 5544 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5545 final int[] userIds = sUserManager.getUserIds(); 5546 synchronized (mInstallLock) { 5547 // Create a native library symlink only if we have native libraries 5548 // and if the native libraries are 32 bit libraries. We do not provide 5549 // this symlink for 64 bit libraries. 5550 if (pkg.applicationInfo.primaryCpuAbi != null && 5551 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5552 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5553 for (int userId : userIds) { 5554 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5555 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5556 "Failed linking native library dir (user=" + userId + ")"); 5557 } 5558 } 5559 } 5560 } 5561 } 5562 5563 // This is a special case for the "system" package, where the ABI is 5564 // dictated by the zygote configuration (and init.rc). We should keep track 5565 // of this ABI so that we can deal with "normal" applications that run under 5566 // the same UID correctly. 5567 if (mPlatformPackage == pkg) { 5568 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5569 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5570 } 5571 5572 // If there's a mismatch between the abi-override in the package setting 5573 // and the abiOverride specified for the install. Warn about this because we 5574 // would've already compiled the app without taking the package setting into 5575 // account. 5576 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 5577 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 5578 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 5579 " for package: " + pkg.packageName); 5580 } 5581 } 5582 5583 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5584 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5585 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5586 5587 // Copy the derived override back to the parsed package, so that we can 5588 // update the package settings accordingly. 5589 pkg.cpuAbiOverride = cpuAbiOverride; 5590 5591 if (DEBUG_ABI_SELECTION) { 5592 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5593 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5594 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5595 } 5596 5597 // Push the derived path down into PackageSettings so we know what to 5598 // clean up at uninstall time. 5599 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5600 5601 if (DEBUG_ABI_SELECTION) { 5602 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5603 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5604 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5605 } 5606 5607 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5608 // We don't do this here during boot because we can do it all 5609 // at once after scanning all existing packages. 5610 // 5611 // We also do this *before* we perform dexopt on this package, so that 5612 // we can avoid redundant dexopts, and also to make sure we've got the 5613 // code and package path correct. 5614 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5615 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5616 } 5617 5618 if ((scanFlags & SCAN_NO_DEX) == 0) { 5619 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 5620 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 5621 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5622 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5623 } 5624 } 5625 if (mFactoryTest && pkg.requestedPermissions.contains( 5626 android.Manifest.permission.FACTORY_TEST)) { 5627 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5628 } 5629 5630 ArrayList<PackageParser.Package> clientLibPkgs = null; 5631 5632 // writer 5633 synchronized (mPackages) { 5634 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5635 // Only system apps can add new shared libraries. 5636 if (pkg.libraryNames != null) { 5637 for (int i=0; i<pkg.libraryNames.size(); i++) { 5638 String name = pkg.libraryNames.get(i); 5639 boolean allowed = false; 5640 if (pkg.isUpdatedSystemApp()) { 5641 // New library entries can only be added through the 5642 // system image. This is important to get rid of a lot 5643 // of nasty edge cases: for example if we allowed a non- 5644 // system update of the app to add a library, then uninstalling 5645 // the update would make the library go away, and assumptions 5646 // we made such as through app install filtering would now 5647 // have allowed apps on the device which aren't compatible 5648 // with it. Better to just have the restriction here, be 5649 // conservative, and create many fewer cases that can negatively 5650 // impact the user experience. 5651 final PackageSetting sysPs = mSettings 5652 .getDisabledSystemPkgLPr(pkg.packageName); 5653 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5654 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5655 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5656 allowed = true; 5657 allowed = true; 5658 break; 5659 } 5660 } 5661 } 5662 } else { 5663 allowed = true; 5664 } 5665 if (allowed) { 5666 if (!mSharedLibraries.containsKey(name)) { 5667 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5668 } else if (!name.equals(pkg.packageName)) { 5669 Slog.w(TAG, "Package " + pkg.packageName + " library " 5670 + name + " already exists; skipping"); 5671 } 5672 } else { 5673 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5674 + name + " that is not declared on system image; skipping"); 5675 } 5676 } 5677 if ((scanFlags&SCAN_BOOTING) == 0) { 5678 // If we are not booting, we need to update any applications 5679 // that are clients of our shared library. If we are booting, 5680 // this will all be done once the scan is complete. 5681 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5682 } 5683 } 5684 } 5685 } 5686 5687 // We also need to dexopt any apps that are dependent on this library. Note that 5688 // if these fail, we should abort the install since installing the library will 5689 // result in some apps being broken. 5690 if (clientLibPkgs != null) { 5691 if ((scanFlags & SCAN_NO_DEX) == 0) { 5692 for (int i = 0; i < clientLibPkgs.size(); i++) { 5693 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5694 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 5695 null /* instruction sets */, forceDex, 5696 (scanFlags & SCAN_DEFER_DEX) != 0, false); 5697 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 5698 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5699 "scanPackageLI failed to dexopt clientLibPkgs"); 5700 } 5701 } 5702 } 5703 } 5704 5705 // Request the ActivityManager to kill the process(only for existing packages) 5706 // so that we do not end up in a confused state while the user is still using the older 5707 // version of the application while the new one gets installed. 5708 if ((scanFlags & SCAN_REPLACING) != 0) { 5709 killApplication(pkg.applicationInfo.packageName, 5710 pkg.applicationInfo.uid, "update pkg"); 5711 } 5712 5713 // Also need to kill any apps that are dependent on the library. 5714 if (clientLibPkgs != null) { 5715 for (int i=0; i<clientLibPkgs.size(); i++) { 5716 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5717 killApplication(clientPkg.applicationInfo.packageName, 5718 clientPkg.applicationInfo.uid, "update lib"); 5719 } 5720 } 5721 5722 // writer 5723 synchronized (mPackages) { 5724 // We don't expect installation to fail beyond this point 5725 5726 // Add the new setting to mSettings 5727 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5728 // Add the new setting to mPackages 5729 mPackages.put(pkg.applicationInfo.packageName, pkg); 5730 // Make sure we don't accidentally delete its data. 5731 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5732 while (iter.hasNext()) { 5733 PackageCleanItem item = iter.next(); 5734 if (pkgName.equals(item.packageName)) { 5735 iter.remove(); 5736 } 5737 } 5738 5739 // Take care of first install / last update times. 5740 if (currentTime != 0) { 5741 if (pkgSetting.firstInstallTime == 0) { 5742 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5743 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5744 pkgSetting.lastUpdateTime = currentTime; 5745 } 5746 } else if (pkgSetting.firstInstallTime == 0) { 5747 // We need *something*. Take time time stamp of the file. 5748 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5749 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5750 if (scanFileTime != pkgSetting.timeStamp) { 5751 // A package on the system image has changed; consider this 5752 // to be an update. 5753 pkgSetting.lastUpdateTime = scanFileTime; 5754 } 5755 } 5756 5757 // Add the package's KeySets to the global KeySetManagerService 5758 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5759 try { 5760 // Old KeySetData no longer valid. 5761 ksms.removeAppKeySetDataLPw(pkg.packageName); 5762 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5763 if (pkg.mKeySetMapping != null) { 5764 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5765 pkg.mKeySetMapping.entrySet()) { 5766 if (entry.getValue() != null) { 5767 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5768 entry.getValue(), entry.getKey()); 5769 } 5770 } 5771 if (pkg.mUpgradeKeySets != null) { 5772 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5773 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5774 } 5775 } 5776 } 5777 } catch (NullPointerException e) { 5778 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5779 } catch (IllegalArgumentException e) { 5780 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5781 } 5782 5783 int N = pkg.providers.size(); 5784 StringBuilder r = null; 5785 int i; 5786 for (i=0; i<N; i++) { 5787 PackageParser.Provider p = pkg.providers.get(i); 5788 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5789 p.info.processName, pkg.applicationInfo.uid); 5790 mProviders.addProvider(p); 5791 p.syncable = p.info.isSyncable; 5792 if (p.info.authority != null) { 5793 String names[] = p.info.authority.split(";"); 5794 p.info.authority = null; 5795 for (int j = 0; j < names.length; j++) { 5796 if (j == 1 && p.syncable) { 5797 // We only want the first authority for a provider to possibly be 5798 // syncable, so if we already added this provider using a different 5799 // authority clear the syncable flag. We copy the provider before 5800 // changing it because the mProviders object contains a reference 5801 // to a provider that we don't want to change. 5802 // Only do this for the second authority since the resulting provider 5803 // object can be the same for all future authorities for this provider. 5804 p = new PackageParser.Provider(p); 5805 p.syncable = false; 5806 } 5807 if (!mProvidersByAuthority.containsKey(names[j])) { 5808 mProvidersByAuthority.put(names[j], p); 5809 if (p.info.authority == null) { 5810 p.info.authority = names[j]; 5811 } else { 5812 p.info.authority = p.info.authority + ";" + names[j]; 5813 } 5814 if (DEBUG_PACKAGE_SCANNING) { 5815 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5816 Log.d(TAG, "Registered content provider: " + names[j] 5817 + ", className = " + p.info.name + ", isSyncable = " 5818 + p.info.isSyncable); 5819 } 5820 } else { 5821 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5822 Slog.w(TAG, "Skipping provider name " + names[j] + 5823 " (in package " + pkg.applicationInfo.packageName + 5824 "): name already used by " 5825 + ((other != null && other.getComponentName() != null) 5826 ? other.getComponentName().getPackageName() : "?")); 5827 } 5828 } 5829 } 5830 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5831 if (r == null) { 5832 r = new StringBuilder(256); 5833 } else { 5834 r.append(' '); 5835 } 5836 r.append(p.info.name); 5837 } 5838 } 5839 if (r != null) { 5840 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5841 } 5842 5843 N = pkg.services.size(); 5844 r = null; 5845 for (i=0; i<N; i++) { 5846 PackageParser.Service s = pkg.services.get(i); 5847 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5848 s.info.processName, pkg.applicationInfo.uid); 5849 mServices.addService(s); 5850 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5851 if (r == null) { 5852 r = new StringBuilder(256); 5853 } else { 5854 r.append(' '); 5855 } 5856 r.append(s.info.name); 5857 } 5858 } 5859 if (r != null) { 5860 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5861 } 5862 5863 N = pkg.receivers.size(); 5864 r = null; 5865 for (i=0; i<N; i++) { 5866 PackageParser.Activity a = pkg.receivers.get(i); 5867 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5868 a.info.processName, pkg.applicationInfo.uid); 5869 mReceivers.addActivity(a, "receiver"); 5870 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5871 if (r == null) { 5872 r = new StringBuilder(256); 5873 } else { 5874 r.append(' '); 5875 } 5876 r.append(a.info.name); 5877 } 5878 } 5879 if (r != null) { 5880 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5881 } 5882 5883 N = pkg.activities.size(); 5884 r = null; 5885 for (i=0; i<N; i++) { 5886 PackageParser.Activity a = pkg.activities.get(i); 5887 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5888 a.info.processName, pkg.applicationInfo.uid); 5889 mActivities.addActivity(a, "activity"); 5890 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5891 if (r == null) { 5892 r = new StringBuilder(256); 5893 } else { 5894 r.append(' '); 5895 } 5896 r.append(a.info.name); 5897 } 5898 } 5899 if (r != null) { 5900 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5901 } 5902 5903 N = pkg.permissionGroups.size(); 5904 r = null; 5905 for (i=0; i<N; i++) { 5906 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5907 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5908 if (cur == null) { 5909 mPermissionGroups.put(pg.info.name, pg); 5910 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5911 if (r == null) { 5912 r = new StringBuilder(256); 5913 } else { 5914 r.append(' '); 5915 } 5916 r.append(pg.info.name); 5917 } 5918 } else { 5919 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5920 + pg.info.packageName + " ignored: original from " 5921 + cur.info.packageName); 5922 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5923 if (r == null) { 5924 r = new StringBuilder(256); 5925 } else { 5926 r.append(' '); 5927 } 5928 r.append("DUP:"); 5929 r.append(pg.info.name); 5930 } 5931 } 5932 } 5933 if (r != null) { 5934 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5935 } 5936 5937 N = pkg.permissions.size(); 5938 r = null; 5939 for (i=0; i<N; i++) { 5940 PackageParser.Permission p = pkg.permissions.get(i); 5941 ArrayMap<String, BasePermission> permissionMap = 5942 p.tree ? mSettings.mPermissionTrees 5943 : mSettings.mPermissions; 5944 p.group = mPermissionGroups.get(p.info.group); 5945 if (p.info.group == null || p.group != null) { 5946 BasePermission bp = permissionMap.get(p.info.name); 5947 5948 // Allow system apps to redefine non-system permissions 5949 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 5950 final boolean currentOwnerIsSystem = (bp.perm != null 5951 && isSystemApp(bp.perm.owner)); 5952 if (isSystemApp(p.owner)) { 5953 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 5954 // It's a built-in permission and no owner, take ownership now 5955 bp.packageSetting = pkgSetting; 5956 bp.perm = p; 5957 bp.uid = pkg.applicationInfo.uid; 5958 bp.sourcePackage = p.info.packageName; 5959 } else if (!currentOwnerIsSystem) { 5960 String msg = "New decl " + p.owner + " of permission " 5961 + p.info.name + " is system; overriding " + bp.sourcePackage; 5962 reportSettingsProblem(Log.WARN, msg); 5963 bp = null; 5964 } 5965 } 5966 } 5967 5968 if (bp == null) { 5969 bp = new BasePermission(p.info.name, p.info.packageName, 5970 BasePermission.TYPE_NORMAL); 5971 permissionMap.put(p.info.name, bp); 5972 } 5973 5974 if (bp.perm == null) { 5975 if (bp.sourcePackage == null 5976 || bp.sourcePackage.equals(p.info.packageName)) { 5977 BasePermission tree = findPermissionTreeLP(p.info.name); 5978 if (tree == null 5979 || tree.sourcePackage.equals(p.info.packageName)) { 5980 bp.packageSetting = pkgSetting; 5981 bp.perm = p; 5982 bp.uid = pkg.applicationInfo.uid; 5983 bp.sourcePackage = p.info.packageName; 5984 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5985 if (r == null) { 5986 r = new StringBuilder(256); 5987 } else { 5988 r.append(' '); 5989 } 5990 r.append(p.info.name); 5991 } 5992 } else { 5993 Slog.w(TAG, "Permission " + p.info.name + " from package " 5994 + p.info.packageName + " ignored: base tree " 5995 + tree.name + " is from package " 5996 + tree.sourcePackage); 5997 } 5998 } else { 5999 Slog.w(TAG, "Permission " + p.info.name + " from package " 6000 + p.info.packageName + " ignored: original from " 6001 + bp.sourcePackage); 6002 } 6003 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6004 if (r == null) { 6005 r = new StringBuilder(256); 6006 } else { 6007 r.append(' '); 6008 } 6009 r.append("DUP:"); 6010 r.append(p.info.name); 6011 } 6012 if (bp.perm == p) { 6013 bp.protectionLevel = p.info.protectionLevel; 6014 } 6015 } else { 6016 Slog.w(TAG, "Permission " + p.info.name + " from package " 6017 + p.info.packageName + " ignored: no group " 6018 + p.group); 6019 } 6020 } 6021 if (r != null) { 6022 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6023 } 6024 6025 N = pkg.instrumentation.size(); 6026 r = null; 6027 for (i=0; i<N; i++) { 6028 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6029 a.info.packageName = pkg.applicationInfo.packageName; 6030 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6031 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6032 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6033 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6034 a.info.dataDir = pkg.applicationInfo.dataDir; 6035 6036 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6037 // need other information about the application, like the ABI and what not ? 6038 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6039 mInstrumentation.put(a.getComponentName(), a); 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(a.info.name); 6047 } 6048 } 6049 if (r != null) { 6050 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6051 } 6052 6053 if (pkg.protectedBroadcasts != null) { 6054 N = pkg.protectedBroadcasts.size(); 6055 for (i=0; i<N; i++) { 6056 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6057 } 6058 } 6059 6060 pkgSetting.setTimeStamp(scanFileTime); 6061 6062 // Create idmap files for pairs of (packages, overlay packages). 6063 // Note: "android", ie framework-res.apk, is handled by native layers. 6064 if (pkg.mOverlayTarget != null) { 6065 // This is an overlay package. 6066 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6067 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6068 mOverlays.put(pkg.mOverlayTarget, 6069 new ArrayMap<String, PackageParser.Package>()); 6070 } 6071 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6072 map.put(pkg.packageName, pkg); 6073 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6074 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6075 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6076 "scanPackageLI failed to createIdmap"); 6077 } 6078 } 6079 } else if (mOverlays.containsKey(pkg.packageName) && 6080 !pkg.packageName.equals("android")) { 6081 // This is a regular package, with one or more known overlay packages. 6082 createIdmapsForPackageLI(pkg); 6083 } 6084 } 6085 6086 return pkg; 6087 } 6088 6089 /** 6090 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6091 * is derived purely on the basis of the contents of {@code scanFile} and 6092 * {@code cpuAbiOverride}. 6093 * 6094 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6095 */ 6096 public void deriveNonSystemPackageAbi(PackageParser.Package pkg, File scanFile, 6097 String cpuAbiOverride, boolean extractLibs) 6098 throws PackageManagerException { 6099 // TODO: We can probably be smarter about this stuff. For installed apps, 6100 // we can calculate this information at install time once and for all. For 6101 // system apps, we can probably assume that this information doesn't change 6102 // after the first boot scan. As things stand, we do lots of unnecessary work. 6103 6104 // Give ourselves some initial paths; we'll come back for another 6105 // pass once we've determined ABI below. 6106 setNativeLibraryPaths(pkg); 6107 6108 // We would never need to extract libs for forward-locked and external packages, 6109 // since the container service will do it for us. 6110 if (pkg.isForwardLocked() || isExternal(pkg)) { 6111 extractLibs = false; 6112 } 6113 6114 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6115 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6116 6117 NativeLibraryHelper.Handle handle = null; 6118 try { 6119 handle = NativeLibraryHelper.Handle.create(scanFile); 6120 // TODO(multiArch): This can be null for apps that didn't go through the 6121 // usual installation process. We can calculate it again, like we 6122 // do during install time. 6123 // 6124 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6125 // unnecessary. 6126 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6127 6128 // Null out the abis so that they can be recalculated. 6129 pkg.applicationInfo.primaryCpuAbi = null; 6130 pkg.applicationInfo.secondaryCpuAbi = null; 6131 if (isMultiArch(pkg.applicationInfo)) { 6132 // Warn if we've set an abiOverride for multi-lib packages.. 6133 // By definition, we need to copy both 32 and 64 bit libraries for 6134 // such packages. 6135 if (pkg.cpuAbiOverride != null 6136 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6137 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6138 } 6139 6140 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6141 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6142 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6143 if (extractLibs) { 6144 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6145 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6146 useIsaSpecificSubdirs); 6147 } else { 6148 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6149 } 6150 } 6151 6152 maybeThrowExceptionForMultiArchCopy( 6153 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6154 6155 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6156 if (extractLibs) { 6157 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6158 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6159 useIsaSpecificSubdirs); 6160 } else { 6161 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6162 } 6163 } 6164 6165 maybeThrowExceptionForMultiArchCopy( 6166 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6167 6168 if (abi64 >= 0) { 6169 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6170 } 6171 6172 if (abi32 >= 0) { 6173 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6174 if (abi64 >= 0) { 6175 pkg.applicationInfo.secondaryCpuAbi = abi; 6176 } else { 6177 pkg.applicationInfo.primaryCpuAbi = abi; 6178 } 6179 } 6180 } else { 6181 String[] abiList = (cpuAbiOverride != null) ? 6182 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6183 6184 // Enable gross and lame hacks for apps that are built with old 6185 // SDK tools. We must scan their APKs for renderscript bitcode and 6186 // not launch them if it's present. Don't bother checking on devices 6187 // that don't have 64 bit support. 6188 boolean needsRenderScriptOverride = false; 6189 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6190 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6191 abiList = Build.SUPPORTED_32_BIT_ABIS; 6192 needsRenderScriptOverride = true; 6193 } 6194 6195 final int copyRet; 6196 if (extractLibs) { 6197 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6198 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6199 } else { 6200 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6201 } 6202 6203 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6204 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6205 "Error unpackaging native libs for app, errorCode=" + copyRet); 6206 } 6207 6208 if (copyRet >= 0) { 6209 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6210 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6211 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6212 } else if (needsRenderScriptOverride) { 6213 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6214 } 6215 } 6216 } catch (IOException ioe) { 6217 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6218 } finally { 6219 IoUtils.closeQuietly(handle); 6220 } 6221 6222 // Now that we've calculated the ABIs and determined if it's an internal app, 6223 // we will go ahead and populate the nativeLibraryPath. 6224 setNativeLibraryPaths(pkg); 6225 } 6226 6227 /** 6228 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6229 * i.e, so that all packages can be run inside a single process if required. 6230 * 6231 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6232 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6233 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6234 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6235 * updating a package that belongs to a shared user. 6236 * 6237 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6238 * adds unnecessary complexity. 6239 */ 6240 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6241 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6242 String requiredInstructionSet = null; 6243 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6244 requiredInstructionSet = VMRuntime.getInstructionSet( 6245 scannedPackage.applicationInfo.primaryCpuAbi); 6246 } 6247 6248 PackageSetting requirer = null; 6249 for (PackageSetting ps : packagesForUser) { 6250 // If packagesForUser contains scannedPackage, we skip it. This will happen 6251 // when scannedPackage is an update of an existing package. Without this check, 6252 // we will never be able to change the ABI of any package belonging to a shared 6253 // user, even if it's compatible with other packages. 6254 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6255 if (ps.primaryCpuAbiString == null) { 6256 continue; 6257 } 6258 6259 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6260 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6261 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6262 // this but there's not much we can do. 6263 String errorMessage = "Instruction set mismatch, " 6264 + ((requirer == null) ? "[caller]" : requirer) 6265 + " requires " + requiredInstructionSet + " whereas " + ps 6266 + " requires " + instructionSet; 6267 Slog.w(TAG, errorMessage); 6268 } 6269 6270 if (requiredInstructionSet == null) { 6271 requiredInstructionSet = instructionSet; 6272 requirer = ps; 6273 } 6274 } 6275 } 6276 6277 if (requiredInstructionSet != null) { 6278 String adjustedAbi; 6279 if (requirer != null) { 6280 // requirer != null implies that either scannedPackage was null or that scannedPackage 6281 // did not require an ABI, in which case we have to adjust scannedPackage to match 6282 // the ABI of the set (which is the same as requirer's ABI) 6283 adjustedAbi = requirer.primaryCpuAbiString; 6284 if (scannedPackage != null) { 6285 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6286 } 6287 } else { 6288 // requirer == null implies that we're updating all ABIs in the set to 6289 // match scannedPackage. 6290 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6291 } 6292 6293 for (PackageSetting ps : packagesForUser) { 6294 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6295 if (ps.primaryCpuAbiString != null) { 6296 continue; 6297 } 6298 6299 ps.primaryCpuAbiString = adjustedAbi; 6300 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6301 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6302 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6303 6304 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6305 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6306 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6307 ps.primaryCpuAbiString = null; 6308 ps.pkg.applicationInfo.primaryCpuAbi = null; 6309 return; 6310 } else { 6311 mInstaller.rmdex(ps.codePathString, 6312 getDexCodeInstructionSet(getPreferredInstructionSet())); 6313 } 6314 } 6315 } 6316 } 6317 } 6318 } 6319 6320 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6321 synchronized (mPackages) { 6322 mResolverReplaced = true; 6323 // Set up information for custom user intent resolution activity. 6324 mResolveActivity.applicationInfo = pkg.applicationInfo; 6325 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6326 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6327 mResolveActivity.processName = pkg.applicationInfo.packageName; 6328 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6329 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6330 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6331 mResolveActivity.theme = 0; 6332 mResolveActivity.exported = true; 6333 mResolveActivity.enabled = true; 6334 mResolveInfo.activityInfo = mResolveActivity; 6335 mResolveInfo.priority = 0; 6336 mResolveInfo.preferredOrder = 0; 6337 mResolveInfo.match = 0; 6338 mResolveComponentName = mCustomResolverComponentName; 6339 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6340 mResolveComponentName); 6341 } 6342 } 6343 6344 private static String calculateBundledApkRoot(final String codePathString) { 6345 final File codePath = new File(codePathString); 6346 final File codeRoot; 6347 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6348 codeRoot = Environment.getRootDirectory(); 6349 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6350 codeRoot = Environment.getOemDirectory(); 6351 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6352 codeRoot = Environment.getVendorDirectory(); 6353 } else { 6354 // Unrecognized code path; take its top real segment as the apk root: 6355 // e.g. /something/app/blah.apk => /something 6356 try { 6357 File f = codePath.getCanonicalFile(); 6358 File parent = f.getParentFile(); // non-null because codePath is a file 6359 File tmp; 6360 while ((tmp = parent.getParentFile()) != null) { 6361 f = parent; 6362 parent = tmp; 6363 } 6364 codeRoot = f; 6365 Slog.w(TAG, "Unrecognized code path " 6366 + codePath + " - using " + codeRoot); 6367 } catch (IOException e) { 6368 // Can't canonicalize the code path -- shenanigans? 6369 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6370 return Environment.getRootDirectory().getPath(); 6371 } 6372 } 6373 return codeRoot.getPath(); 6374 } 6375 6376 /** 6377 * Derive and set the location of native libraries for the given package, 6378 * which varies depending on where and how the package was installed. 6379 */ 6380 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6381 final ApplicationInfo info = pkg.applicationInfo; 6382 final String codePath = pkg.codePath; 6383 final File codeFile = new File(codePath); 6384 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 6385 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6386 6387 info.nativeLibraryRootDir = null; 6388 info.nativeLibraryRootRequiresIsa = false; 6389 info.nativeLibraryDir = null; 6390 info.secondaryNativeLibraryDir = null; 6391 6392 if (isApkFile(codeFile)) { 6393 // Monolithic install 6394 if (bundledApp) { 6395 // If "/system/lib64/apkname" exists, assume that is the per-package 6396 // native library directory to use; otherwise use "/system/lib/apkname". 6397 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6398 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6399 getPrimaryInstructionSet(info)); 6400 6401 // This is a bundled system app so choose the path based on the ABI. 6402 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6403 // is just the default path. 6404 final String apkName = deriveCodePathName(codePath); 6405 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6406 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6407 apkName).getAbsolutePath(); 6408 6409 if (info.secondaryCpuAbi != null) { 6410 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6411 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6412 secondaryLibDir, apkName).getAbsolutePath(); 6413 } 6414 } else if (asecApp) { 6415 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6416 .getAbsolutePath(); 6417 } else { 6418 final String apkName = deriveCodePathName(codePath); 6419 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6420 .getAbsolutePath(); 6421 } 6422 6423 info.nativeLibraryRootRequiresIsa = false; 6424 info.nativeLibraryDir = info.nativeLibraryRootDir; 6425 } else { 6426 // Cluster install 6427 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6428 info.nativeLibraryRootRequiresIsa = true; 6429 6430 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6431 getPrimaryInstructionSet(info)).getAbsolutePath(); 6432 6433 if (info.secondaryCpuAbi != null) { 6434 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6435 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6436 } 6437 } 6438 } 6439 6440 /** 6441 * Calculate the abis and roots for a bundled app. These can uniquely 6442 * be determined from the contents of the system partition, i.e whether 6443 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6444 * of this information, and instead assume that the system was built 6445 * sensibly. 6446 */ 6447 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6448 PackageSetting pkgSetting) { 6449 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6450 6451 // If "/system/lib64/apkname" exists, assume that is the per-package 6452 // native library directory to use; otherwise use "/system/lib/apkname". 6453 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6454 setBundledAppAbi(pkg, apkRoot, apkName); 6455 // pkgSetting might be null during rescan following uninstall of updates 6456 // to a bundled app, so accommodate that possibility. The settings in 6457 // that case will be established later from the parsed package. 6458 // 6459 // If the settings aren't null, sync them up with what we've just derived. 6460 // note that apkRoot isn't stored in the package settings. 6461 if (pkgSetting != null) { 6462 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6463 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6464 } 6465 } 6466 6467 /** 6468 * Deduces the ABI of a bundled app and sets the relevant fields on the 6469 * parsed pkg object. 6470 * 6471 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6472 * under which system libraries are installed. 6473 * @param apkName the name of the installed package. 6474 */ 6475 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6476 final File codeFile = new File(pkg.codePath); 6477 6478 final boolean has64BitLibs; 6479 final boolean has32BitLibs; 6480 if (isApkFile(codeFile)) { 6481 // Monolithic install 6482 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6483 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6484 } else { 6485 // Cluster install 6486 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6487 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6488 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6489 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6490 has64BitLibs = (new File(rootDir, isa)).exists(); 6491 } else { 6492 has64BitLibs = false; 6493 } 6494 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6495 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6496 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6497 has32BitLibs = (new File(rootDir, isa)).exists(); 6498 } else { 6499 has32BitLibs = false; 6500 } 6501 } 6502 6503 if (has64BitLibs && !has32BitLibs) { 6504 // The package has 64 bit libs, but not 32 bit libs. Its primary 6505 // ABI should be 64 bit. We can safely assume here that the bundled 6506 // native libraries correspond to the most preferred ABI in the list. 6507 6508 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6509 pkg.applicationInfo.secondaryCpuAbi = null; 6510 } else if (has32BitLibs && !has64BitLibs) { 6511 // The package has 32 bit libs but not 64 bit libs. Its primary 6512 // ABI should be 32 bit. 6513 6514 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6515 pkg.applicationInfo.secondaryCpuAbi = null; 6516 } else if (has32BitLibs && has64BitLibs) { 6517 // The application has both 64 and 32 bit bundled libraries. We check 6518 // here that the app declares multiArch support, and warn if it doesn't. 6519 // 6520 // We will be lenient here and record both ABIs. The primary will be the 6521 // ABI that's higher on the list, i.e, a device that's configured to prefer 6522 // 64 bit apps will see a 64 bit primary ABI, 6523 6524 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6525 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6526 } 6527 6528 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6529 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6530 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6531 } else { 6532 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6533 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6534 } 6535 } else { 6536 pkg.applicationInfo.primaryCpuAbi = null; 6537 pkg.applicationInfo.secondaryCpuAbi = null; 6538 } 6539 } 6540 6541 private void killApplication(String pkgName, int appId, String reason) { 6542 // Request the ActivityManager to kill the process(only for existing packages) 6543 // so that we do not end up in a confused state while the user is still using the older 6544 // version of the application while the new one gets installed. 6545 IActivityManager am = ActivityManagerNative.getDefault(); 6546 if (am != null) { 6547 try { 6548 am.killApplicationWithAppId(pkgName, appId, reason); 6549 } catch (RemoteException e) { 6550 } 6551 } 6552 } 6553 6554 void removePackageLI(PackageSetting ps, boolean chatty) { 6555 if (DEBUG_INSTALL) { 6556 if (chatty) 6557 Log.d(TAG, "Removing package " + ps.name); 6558 } 6559 6560 // writer 6561 synchronized (mPackages) { 6562 mPackages.remove(ps.name); 6563 final PackageParser.Package pkg = ps.pkg; 6564 if (pkg != null) { 6565 cleanPackageDataStructuresLILPw(pkg, chatty); 6566 } 6567 } 6568 } 6569 6570 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6571 if (DEBUG_INSTALL) { 6572 if (chatty) 6573 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6574 } 6575 6576 // writer 6577 synchronized (mPackages) { 6578 mPackages.remove(pkg.applicationInfo.packageName); 6579 cleanPackageDataStructuresLILPw(pkg, chatty); 6580 } 6581 } 6582 6583 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6584 int N = pkg.providers.size(); 6585 StringBuilder r = null; 6586 int i; 6587 for (i=0; i<N; i++) { 6588 PackageParser.Provider p = pkg.providers.get(i); 6589 mProviders.removeProvider(p); 6590 if (p.info.authority == null) { 6591 6592 /* There was another ContentProvider with this authority when 6593 * this app was installed so this authority is null, 6594 * Ignore it as we don't have to unregister the provider. 6595 */ 6596 continue; 6597 } 6598 String names[] = p.info.authority.split(";"); 6599 for (int j = 0; j < names.length; j++) { 6600 if (mProvidersByAuthority.get(names[j]) == p) { 6601 mProvidersByAuthority.remove(names[j]); 6602 if (DEBUG_REMOVE) { 6603 if (chatty) 6604 Log.d(TAG, "Unregistered content provider: " + names[j] 6605 + ", className = " + p.info.name + ", isSyncable = " 6606 + p.info.isSyncable); 6607 } 6608 } 6609 } 6610 if (DEBUG_REMOVE && chatty) { 6611 if (r == null) { 6612 r = new StringBuilder(256); 6613 } else { 6614 r.append(' '); 6615 } 6616 r.append(p.info.name); 6617 } 6618 } 6619 if (r != null) { 6620 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6621 } 6622 6623 N = pkg.services.size(); 6624 r = null; 6625 for (i=0; i<N; i++) { 6626 PackageParser.Service s = pkg.services.get(i); 6627 mServices.removeService(s); 6628 if (chatty) { 6629 if (r == null) { 6630 r = new StringBuilder(256); 6631 } else { 6632 r.append(' '); 6633 } 6634 r.append(s.info.name); 6635 } 6636 } 6637 if (r != null) { 6638 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6639 } 6640 6641 N = pkg.receivers.size(); 6642 r = null; 6643 for (i=0; i<N; i++) { 6644 PackageParser.Activity a = pkg.receivers.get(i); 6645 mReceivers.removeActivity(a, "receiver"); 6646 if (DEBUG_REMOVE && chatty) { 6647 if (r == null) { 6648 r = new StringBuilder(256); 6649 } else { 6650 r.append(' '); 6651 } 6652 r.append(a.info.name); 6653 } 6654 } 6655 if (r != null) { 6656 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6657 } 6658 6659 N = pkg.activities.size(); 6660 r = null; 6661 for (i=0; i<N; i++) { 6662 PackageParser.Activity a = pkg.activities.get(i); 6663 mActivities.removeActivity(a, "activity"); 6664 if (DEBUG_REMOVE && chatty) { 6665 if (r == null) { 6666 r = new StringBuilder(256); 6667 } else { 6668 r.append(' '); 6669 } 6670 r.append(a.info.name); 6671 } 6672 } 6673 if (r != null) { 6674 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6675 } 6676 6677 N = pkg.permissions.size(); 6678 r = null; 6679 for (i=0; i<N; i++) { 6680 PackageParser.Permission p = pkg.permissions.get(i); 6681 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6682 if (bp == null) { 6683 bp = mSettings.mPermissionTrees.get(p.info.name); 6684 } 6685 if (bp != null && bp.perm == p) { 6686 bp.perm = null; 6687 if (DEBUG_REMOVE && chatty) { 6688 if (r == null) { 6689 r = new StringBuilder(256); 6690 } else { 6691 r.append(' '); 6692 } 6693 r.append(p.info.name); 6694 } 6695 } 6696 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6697 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6698 if (appOpPerms != null) { 6699 appOpPerms.remove(pkg.packageName); 6700 } 6701 } 6702 } 6703 if (r != null) { 6704 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6705 } 6706 6707 N = pkg.requestedPermissions.size(); 6708 r = null; 6709 for (i=0; i<N; i++) { 6710 String perm = pkg.requestedPermissions.get(i); 6711 BasePermission bp = mSettings.mPermissions.get(perm); 6712 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6713 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6714 if (appOpPerms != null) { 6715 appOpPerms.remove(pkg.packageName); 6716 if (appOpPerms.isEmpty()) { 6717 mAppOpPermissionPackages.remove(perm); 6718 } 6719 } 6720 } 6721 } 6722 if (r != null) { 6723 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6724 } 6725 6726 N = pkg.instrumentation.size(); 6727 r = null; 6728 for (i=0; i<N; i++) { 6729 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6730 mInstrumentation.remove(a.getComponentName()); 6731 if (DEBUG_REMOVE && chatty) { 6732 if (r == null) { 6733 r = new StringBuilder(256); 6734 } else { 6735 r.append(' '); 6736 } 6737 r.append(a.info.name); 6738 } 6739 } 6740 if (r != null) { 6741 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6742 } 6743 6744 r = null; 6745 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6746 // Only system apps can hold shared libraries. 6747 if (pkg.libraryNames != null) { 6748 for (i=0; i<pkg.libraryNames.size(); i++) { 6749 String name = pkg.libraryNames.get(i); 6750 SharedLibraryEntry cur = mSharedLibraries.get(name); 6751 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6752 mSharedLibraries.remove(name); 6753 if (DEBUG_REMOVE && chatty) { 6754 if (r == null) { 6755 r = new StringBuilder(256); 6756 } else { 6757 r.append(' '); 6758 } 6759 r.append(name); 6760 } 6761 } 6762 } 6763 } 6764 } 6765 if (r != null) { 6766 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6767 } 6768 } 6769 6770 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6771 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6772 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6773 return true; 6774 } 6775 } 6776 return false; 6777 } 6778 6779 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6780 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6781 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6782 6783 private void updatePermissionsLPw(String changingPkg, 6784 PackageParser.Package pkgInfo, int flags) { 6785 // Make sure there are no dangling permission trees. 6786 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6787 while (it.hasNext()) { 6788 final BasePermission bp = it.next(); 6789 if (bp.packageSetting == null) { 6790 // We may not yet have parsed the package, so just see if 6791 // we still know about its settings. 6792 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6793 } 6794 if (bp.packageSetting == null) { 6795 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6796 + " from package " + bp.sourcePackage); 6797 it.remove(); 6798 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6799 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6800 Slog.i(TAG, "Removing old permission tree: " + bp.name 6801 + " from package " + bp.sourcePackage); 6802 flags |= UPDATE_PERMISSIONS_ALL; 6803 it.remove(); 6804 } 6805 } 6806 } 6807 6808 // Make sure all dynamic permissions have been assigned to a package, 6809 // and make sure there are no dangling permissions. 6810 it = mSettings.mPermissions.values().iterator(); 6811 while (it.hasNext()) { 6812 final BasePermission bp = it.next(); 6813 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6814 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6815 + bp.name + " pkg=" + bp.sourcePackage 6816 + " info=" + bp.pendingInfo); 6817 if (bp.packageSetting == null && bp.pendingInfo != null) { 6818 final BasePermission tree = findPermissionTreeLP(bp.name); 6819 if (tree != null && tree.perm != null) { 6820 bp.packageSetting = tree.packageSetting; 6821 bp.perm = new PackageParser.Permission(tree.perm.owner, 6822 new PermissionInfo(bp.pendingInfo)); 6823 bp.perm.info.packageName = tree.perm.info.packageName; 6824 bp.perm.info.name = bp.name; 6825 bp.uid = tree.uid; 6826 } 6827 } 6828 } 6829 if (bp.packageSetting == null) { 6830 // We may not yet have parsed the package, so just see if 6831 // we still know about its settings. 6832 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6833 } 6834 if (bp.packageSetting == null) { 6835 Slog.w(TAG, "Removing dangling permission: " + bp.name 6836 + " from package " + bp.sourcePackage); 6837 it.remove(); 6838 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6839 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6840 Slog.i(TAG, "Removing old permission: " + bp.name 6841 + " from package " + bp.sourcePackage); 6842 flags |= UPDATE_PERMISSIONS_ALL; 6843 it.remove(); 6844 } 6845 } 6846 } 6847 6848 // Now update the permissions for all packages, in particular 6849 // replace the granted permissions of the system packages. 6850 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6851 for (PackageParser.Package pkg : mPackages.values()) { 6852 if (pkg != pkgInfo) { 6853 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6854 changingPkg); 6855 } 6856 } 6857 } 6858 6859 if (pkgInfo != null) { 6860 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6861 } 6862 } 6863 6864 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6865 String packageOfInterest) { 6866 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6867 if (ps == null) { 6868 return; 6869 } 6870 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6871 ArraySet<String> origPermissions = gp.grantedPermissions; 6872 boolean changedPermission = false; 6873 6874 if (replace) { 6875 ps.permissionsFixed = false; 6876 if (gp == ps) { 6877 origPermissions = new ArraySet<String>(gp.grantedPermissions); 6878 gp.grantedPermissions.clear(); 6879 gp.gids = mGlobalGids; 6880 } 6881 } 6882 6883 if (gp.gids == null) { 6884 gp.gids = mGlobalGids; 6885 } 6886 6887 final int N = pkg.requestedPermissions.size(); 6888 for (int i=0; i<N; i++) { 6889 final String name = pkg.requestedPermissions.get(i); 6890 final boolean required = pkg.requestedPermissionsRequired.get(i); 6891 final BasePermission bp = mSettings.mPermissions.get(name); 6892 if (DEBUG_INSTALL) { 6893 if (gp != ps) { 6894 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6895 } 6896 } 6897 6898 if (bp == null || bp.packageSetting == null) { 6899 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6900 Slog.w(TAG, "Unknown permission " + name 6901 + " in package " + pkg.packageName); 6902 } 6903 continue; 6904 } 6905 6906 final String perm = bp.name; 6907 boolean allowed; 6908 boolean allowedSig = false; 6909 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6910 // Keep track of app op permissions. 6911 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6912 if (pkgs == null) { 6913 pkgs = new ArraySet<>(); 6914 mAppOpPermissionPackages.put(bp.name, pkgs); 6915 } 6916 pkgs.add(pkg.packageName); 6917 } 6918 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6919 if (level == PermissionInfo.PROTECTION_NORMAL 6920 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6921 // We grant a normal or dangerous permission if any of the following 6922 // are true: 6923 // 1) The permission is required 6924 // 2) The permission is optional, but was granted in the past 6925 // 3) The permission is optional, but was requested by an 6926 // app in /system (not /data) 6927 // 6928 // Otherwise, reject the permission. 6929 allowed = (required || origPermissions.contains(perm) 6930 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6931 } else if (bp.packageSetting == null) { 6932 // This permission is invalid; skip it. 6933 allowed = false; 6934 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6935 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6936 if (allowed) { 6937 allowedSig = true; 6938 } 6939 } else { 6940 allowed = false; 6941 } 6942 if (DEBUG_INSTALL) { 6943 if (gp != ps) { 6944 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6945 } 6946 } 6947 if (allowed) { 6948 if (!isSystemApp(ps) && ps.permissionsFixed) { 6949 // If this is an existing, non-system package, then 6950 // we can't add any new permissions to it. 6951 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6952 // Except... if this is a permission that was added 6953 // to the platform (note: need to only do this when 6954 // updating the platform). 6955 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6956 } 6957 } 6958 if (allowed) { 6959 if (!gp.grantedPermissions.contains(perm)) { 6960 changedPermission = true; 6961 gp.grantedPermissions.add(perm); 6962 gp.gids = appendInts(gp.gids, bp.gids); 6963 } else if (!ps.haveGids) { 6964 gp.gids = appendInts(gp.gids, bp.gids); 6965 } 6966 } else { 6967 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6968 Slog.w(TAG, "Not granting permission " + perm 6969 + " to package " + pkg.packageName 6970 + " because it was previously installed without"); 6971 } 6972 } 6973 } else { 6974 if (gp.grantedPermissions.remove(perm)) { 6975 changedPermission = true; 6976 gp.gids = removeInts(gp.gids, bp.gids); 6977 Slog.i(TAG, "Un-granting permission " + perm 6978 + " from package " + pkg.packageName 6979 + " (protectionLevel=" + bp.protectionLevel 6980 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6981 + ")"); 6982 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6983 // Don't print warning for app op permissions, since it is fine for them 6984 // not to be granted, there is a UI for the user to decide. 6985 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6986 Slog.w(TAG, "Not granting permission " + perm 6987 + " to package " + pkg.packageName 6988 + " (protectionLevel=" + bp.protectionLevel 6989 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6990 + ")"); 6991 } 6992 } 6993 } 6994 } 6995 6996 if ((changedPermission || replace) && !ps.permissionsFixed && 6997 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6998 // This is the first that we have heard about this package, so the 6999 // permissions we have now selected are fixed until explicitly 7000 // changed. 7001 ps.permissionsFixed = true; 7002 } 7003 ps.haveGids = true; 7004 } 7005 7006 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7007 boolean allowed = false; 7008 final int NP = PackageParser.NEW_PERMISSIONS.length; 7009 for (int ip=0; ip<NP; ip++) { 7010 final PackageParser.NewPermissionInfo npi 7011 = PackageParser.NEW_PERMISSIONS[ip]; 7012 if (npi.name.equals(perm) 7013 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7014 allowed = true; 7015 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7016 + pkg.packageName); 7017 break; 7018 } 7019 } 7020 return allowed; 7021 } 7022 7023 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7024 BasePermission bp, ArraySet<String> origPermissions) { 7025 boolean allowed; 7026 allowed = (compareSignatures( 7027 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7028 == PackageManager.SIGNATURE_MATCH) 7029 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7030 == PackageManager.SIGNATURE_MATCH); 7031 if (!allowed && (bp.protectionLevel 7032 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7033 if (isSystemApp(pkg)) { 7034 // For updated system applications, a system permission 7035 // is granted only if it had been defined by the original application. 7036 if (pkg.isUpdatedSystemApp()) { 7037 final PackageSetting sysPs = mSettings 7038 .getDisabledSystemPkgLPr(pkg.packageName); 7039 final GrantedPermissions origGp = sysPs.sharedUser != null 7040 ? sysPs.sharedUser : sysPs; 7041 7042 if (origGp.grantedPermissions.contains(perm)) { 7043 // If the original was granted this permission, we take 7044 // that grant decision as read and propagate it to the 7045 // update. 7046 if (sysPs.isPrivileged()) { 7047 allowed = true; 7048 } 7049 } else { 7050 // The system apk may have been updated with an older 7051 // version of the one on the data partition, but which 7052 // granted a new system permission that it didn't have 7053 // before. In this case we do want to allow the app to 7054 // now get the new permission if the ancestral apk is 7055 // privileged to get it. 7056 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7057 for (int j=0; 7058 j<sysPs.pkg.requestedPermissions.size(); j++) { 7059 if (perm.equals( 7060 sysPs.pkg.requestedPermissions.get(j))) { 7061 allowed = true; 7062 break; 7063 } 7064 } 7065 } 7066 } 7067 } else { 7068 allowed = isPrivilegedApp(pkg); 7069 } 7070 } 7071 } 7072 if (!allowed && (bp.protectionLevel 7073 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7074 // For development permissions, a development permission 7075 // is granted only if it was already granted. 7076 allowed = origPermissions.contains(perm); 7077 } 7078 return allowed; 7079 } 7080 7081 final class ActivityIntentResolver 7082 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7083 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7084 boolean defaultOnly, int userId) { 7085 if (!sUserManager.exists(userId)) return null; 7086 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7087 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7088 } 7089 7090 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7091 int userId) { 7092 if (!sUserManager.exists(userId)) return null; 7093 mFlags = flags; 7094 return super.queryIntent(intent, resolvedType, 7095 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7096 } 7097 7098 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7099 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7100 if (!sUserManager.exists(userId)) return null; 7101 if (packageActivities == null) { 7102 return null; 7103 } 7104 mFlags = flags; 7105 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7106 final int N = packageActivities.size(); 7107 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7108 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7109 7110 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7111 for (int i = 0; i < N; ++i) { 7112 intentFilters = packageActivities.get(i).intents; 7113 if (intentFilters != null && intentFilters.size() > 0) { 7114 PackageParser.ActivityIntentInfo[] array = 7115 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7116 intentFilters.toArray(array); 7117 listCut.add(array); 7118 } 7119 } 7120 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7121 } 7122 7123 public final void addActivity(PackageParser.Activity a, String type) { 7124 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7125 mActivities.put(a.getComponentName(), a); 7126 if (DEBUG_SHOW_INFO) 7127 Log.v( 7128 TAG, " " + type + " " + 7129 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7130 if (DEBUG_SHOW_INFO) 7131 Log.v(TAG, " Class=" + a.info.name); 7132 final int NI = a.intents.size(); 7133 for (int j=0; j<NI; j++) { 7134 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7135 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7136 intent.setPriority(0); 7137 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7138 + a.className + " with priority > 0, forcing to 0"); 7139 } 7140 if (DEBUG_SHOW_INFO) { 7141 Log.v(TAG, " IntentFilter:"); 7142 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7143 } 7144 if (!intent.debugCheck()) { 7145 Log.w(TAG, "==> For Activity " + a.info.name); 7146 } 7147 addFilter(intent); 7148 } 7149 } 7150 7151 public final void removeActivity(PackageParser.Activity a, String type) { 7152 mActivities.remove(a.getComponentName()); 7153 if (DEBUG_SHOW_INFO) { 7154 Log.v(TAG, " " + type + " " 7155 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7156 : a.info.name) + ":"); 7157 Log.v(TAG, " Class=" + a.info.name); 7158 } 7159 final int NI = a.intents.size(); 7160 for (int j=0; j<NI; j++) { 7161 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7162 if (DEBUG_SHOW_INFO) { 7163 Log.v(TAG, " IntentFilter:"); 7164 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7165 } 7166 removeFilter(intent); 7167 } 7168 } 7169 7170 @Override 7171 protected boolean allowFilterResult( 7172 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7173 ActivityInfo filterAi = filter.activity.info; 7174 for (int i=dest.size()-1; i>=0; i--) { 7175 ActivityInfo destAi = dest.get(i).activityInfo; 7176 if (destAi.name == filterAi.name 7177 && destAi.packageName == filterAi.packageName) { 7178 return false; 7179 } 7180 } 7181 return true; 7182 } 7183 7184 @Override 7185 protected ActivityIntentInfo[] newArray(int size) { 7186 return new ActivityIntentInfo[size]; 7187 } 7188 7189 @Override 7190 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7191 if (!sUserManager.exists(userId)) return true; 7192 PackageParser.Package p = filter.activity.owner; 7193 if (p != null) { 7194 PackageSetting ps = (PackageSetting)p.mExtras; 7195 if (ps != null) { 7196 // System apps are never considered stopped for purposes of 7197 // filtering, because there may be no way for the user to 7198 // actually re-launch them. 7199 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7200 && ps.getStopped(userId); 7201 } 7202 } 7203 return false; 7204 } 7205 7206 @Override 7207 protected boolean isPackageForFilter(String packageName, 7208 PackageParser.ActivityIntentInfo info) { 7209 return packageName.equals(info.activity.owner.packageName); 7210 } 7211 7212 @Override 7213 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7214 int match, int userId) { 7215 if (!sUserManager.exists(userId)) return null; 7216 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7217 return null; 7218 } 7219 final PackageParser.Activity activity = info.activity; 7220 if (mSafeMode && (activity.info.applicationInfo.flags 7221 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7222 return null; 7223 } 7224 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7225 if (ps == null) { 7226 return null; 7227 } 7228 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7229 ps.readUserState(userId), userId); 7230 if (ai == null) { 7231 return null; 7232 } 7233 final ResolveInfo res = new ResolveInfo(); 7234 res.activityInfo = ai; 7235 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7236 res.filter = info; 7237 } 7238 res.priority = info.getPriority(); 7239 res.preferredOrder = activity.owner.mPreferredOrder; 7240 //System.out.println("Result: " + res.activityInfo.className + 7241 // " = " + res.priority); 7242 res.match = match; 7243 res.isDefault = info.hasDefault; 7244 res.labelRes = info.labelRes; 7245 res.nonLocalizedLabel = info.nonLocalizedLabel; 7246 if (userNeedsBadging(userId)) { 7247 res.noResourceId = true; 7248 } else { 7249 res.icon = info.icon; 7250 } 7251 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7252 return res; 7253 } 7254 7255 @Override 7256 protected void sortResults(List<ResolveInfo> results) { 7257 Collections.sort(results, mResolvePrioritySorter); 7258 } 7259 7260 @Override 7261 protected void dumpFilter(PrintWriter out, String prefix, 7262 PackageParser.ActivityIntentInfo filter) { 7263 out.print(prefix); out.print( 7264 Integer.toHexString(System.identityHashCode(filter.activity))); 7265 out.print(' '); 7266 filter.activity.printComponentShortName(out); 7267 out.print(" filter "); 7268 out.println(Integer.toHexString(System.identityHashCode(filter))); 7269 } 7270 7271 @Override 7272 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7273 return filter.activity; 7274 } 7275 7276 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7277 PackageParser.Activity activity = (PackageParser.Activity)label; 7278 out.print(prefix); out.print( 7279 Integer.toHexString(System.identityHashCode(activity))); 7280 out.print(' '); 7281 activity.printComponentShortName(out); 7282 if (count > 1) { 7283 out.print(" ("); out.print(count); out.print(" filters)"); 7284 } 7285 out.println(); 7286 } 7287 7288// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7289// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7290// final List<ResolveInfo> retList = Lists.newArrayList(); 7291// while (i.hasNext()) { 7292// final ResolveInfo resolveInfo = i.next(); 7293// if (isEnabledLP(resolveInfo.activityInfo)) { 7294// retList.add(resolveInfo); 7295// } 7296// } 7297// return retList; 7298// } 7299 7300 // Keys are String (activity class name), values are Activity. 7301 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7302 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7303 private int mFlags; 7304 } 7305 7306 private final class ServiceIntentResolver 7307 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7308 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7309 boolean defaultOnly, int userId) { 7310 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7311 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7312 } 7313 7314 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7315 int userId) { 7316 if (!sUserManager.exists(userId)) return null; 7317 mFlags = flags; 7318 return super.queryIntent(intent, resolvedType, 7319 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7320 } 7321 7322 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7323 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7324 if (!sUserManager.exists(userId)) return null; 7325 if (packageServices == null) { 7326 return null; 7327 } 7328 mFlags = flags; 7329 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7330 final int N = packageServices.size(); 7331 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7332 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7333 7334 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7335 for (int i = 0; i < N; ++i) { 7336 intentFilters = packageServices.get(i).intents; 7337 if (intentFilters != null && intentFilters.size() > 0) { 7338 PackageParser.ServiceIntentInfo[] array = 7339 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7340 intentFilters.toArray(array); 7341 listCut.add(array); 7342 } 7343 } 7344 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7345 } 7346 7347 public final void addService(PackageParser.Service s) { 7348 mServices.put(s.getComponentName(), s); 7349 if (DEBUG_SHOW_INFO) { 7350 Log.v(TAG, " " 7351 + (s.info.nonLocalizedLabel != null 7352 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7353 Log.v(TAG, " Class=" + s.info.name); 7354 } 7355 final int NI = s.intents.size(); 7356 int j; 7357 for (j=0; j<NI; j++) { 7358 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7359 if (DEBUG_SHOW_INFO) { 7360 Log.v(TAG, " IntentFilter:"); 7361 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7362 } 7363 if (!intent.debugCheck()) { 7364 Log.w(TAG, "==> For Service " + s.info.name); 7365 } 7366 addFilter(intent); 7367 } 7368 } 7369 7370 public final void removeService(PackageParser.Service s) { 7371 mServices.remove(s.getComponentName()); 7372 if (DEBUG_SHOW_INFO) { 7373 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7374 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7375 Log.v(TAG, " Class=" + s.info.name); 7376 } 7377 final int NI = s.intents.size(); 7378 int j; 7379 for (j=0; j<NI; j++) { 7380 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7381 if (DEBUG_SHOW_INFO) { 7382 Log.v(TAG, " IntentFilter:"); 7383 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7384 } 7385 removeFilter(intent); 7386 } 7387 } 7388 7389 @Override 7390 protected boolean allowFilterResult( 7391 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7392 ServiceInfo filterSi = filter.service.info; 7393 for (int i=dest.size()-1; i>=0; i--) { 7394 ServiceInfo destAi = dest.get(i).serviceInfo; 7395 if (destAi.name == filterSi.name 7396 && destAi.packageName == filterSi.packageName) { 7397 return false; 7398 } 7399 } 7400 return true; 7401 } 7402 7403 @Override 7404 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7405 return new PackageParser.ServiceIntentInfo[size]; 7406 } 7407 7408 @Override 7409 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7410 if (!sUserManager.exists(userId)) return true; 7411 PackageParser.Package p = filter.service.owner; 7412 if (p != null) { 7413 PackageSetting ps = (PackageSetting)p.mExtras; 7414 if (ps != null) { 7415 // System apps are never considered stopped for purposes of 7416 // filtering, because there may be no way for the user to 7417 // actually re-launch them. 7418 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7419 && ps.getStopped(userId); 7420 } 7421 } 7422 return false; 7423 } 7424 7425 @Override 7426 protected boolean isPackageForFilter(String packageName, 7427 PackageParser.ServiceIntentInfo info) { 7428 return packageName.equals(info.service.owner.packageName); 7429 } 7430 7431 @Override 7432 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7433 int match, int userId) { 7434 if (!sUserManager.exists(userId)) return null; 7435 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7436 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7437 return null; 7438 } 7439 final PackageParser.Service service = info.service; 7440 if (mSafeMode && (service.info.applicationInfo.flags 7441 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7442 return null; 7443 } 7444 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7445 if (ps == null) { 7446 return null; 7447 } 7448 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7449 ps.readUserState(userId), userId); 7450 if (si == null) { 7451 return null; 7452 } 7453 final ResolveInfo res = new ResolveInfo(); 7454 res.serviceInfo = si; 7455 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7456 res.filter = filter; 7457 } 7458 res.priority = info.getPriority(); 7459 res.preferredOrder = service.owner.mPreferredOrder; 7460 //System.out.println("Result: " + res.activityInfo.className + 7461 // " = " + res.priority); 7462 res.match = match; 7463 res.isDefault = info.hasDefault; 7464 res.labelRes = info.labelRes; 7465 res.nonLocalizedLabel = info.nonLocalizedLabel; 7466 res.icon = info.icon; 7467 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 7468 return res; 7469 } 7470 7471 @Override 7472 protected void sortResults(List<ResolveInfo> results) { 7473 Collections.sort(results, mResolvePrioritySorter); 7474 } 7475 7476 @Override 7477 protected void dumpFilter(PrintWriter out, String prefix, 7478 PackageParser.ServiceIntentInfo filter) { 7479 out.print(prefix); out.print( 7480 Integer.toHexString(System.identityHashCode(filter.service))); 7481 out.print(' '); 7482 filter.service.printComponentShortName(out); 7483 out.print(" filter "); 7484 out.println(Integer.toHexString(System.identityHashCode(filter))); 7485 } 7486 7487 @Override 7488 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 7489 return filter.service; 7490 } 7491 7492 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7493 PackageParser.Service service = (PackageParser.Service)label; 7494 out.print(prefix); out.print( 7495 Integer.toHexString(System.identityHashCode(service))); 7496 out.print(' '); 7497 service.printComponentShortName(out); 7498 if (count > 1) { 7499 out.print(" ("); out.print(count); out.print(" filters)"); 7500 } 7501 out.println(); 7502 } 7503 7504// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7505// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7506// final List<ResolveInfo> retList = Lists.newArrayList(); 7507// while (i.hasNext()) { 7508// final ResolveInfo resolveInfo = (ResolveInfo) i; 7509// if (isEnabledLP(resolveInfo.serviceInfo)) { 7510// retList.add(resolveInfo); 7511// } 7512// } 7513// return retList; 7514// } 7515 7516 // Keys are String (activity class name), values are Activity. 7517 private final ArrayMap<ComponentName, PackageParser.Service> mServices 7518 = new ArrayMap<ComponentName, PackageParser.Service>(); 7519 private int mFlags; 7520 }; 7521 7522 private final class ProviderIntentResolver 7523 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7524 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7525 boolean defaultOnly, int userId) { 7526 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7527 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7528 } 7529 7530 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7531 int userId) { 7532 if (!sUserManager.exists(userId)) 7533 return null; 7534 mFlags = flags; 7535 return super.queryIntent(intent, resolvedType, 7536 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7537 } 7538 7539 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7540 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7541 if (!sUserManager.exists(userId)) 7542 return null; 7543 if (packageProviders == null) { 7544 return null; 7545 } 7546 mFlags = flags; 7547 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7548 final int N = packageProviders.size(); 7549 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7550 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7551 7552 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7553 for (int i = 0; i < N; ++i) { 7554 intentFilters = packageProviders.get(i).intents; 7555 if (intentFilters != null && intentFilters.size() > 0) { 7556 PackageParser.ProviderIntentInfo[] array = 7557 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7558 intentFilters.toArray(array); 7559 listCut.add(array); 7560 } 7561 } 7562 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7563 } 7564 7565 public final void addProvider(PackageParser.Provider p) { 7566 if (mProviders.containsKey(p.getComponentName())) { 7567 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7568 return; 7569 } 7570 7571 mProviders.put(p.getComponentName(), p); 7572 if (DEBUG_SHOW_INFO) { 7573 Log.v(TAG, " " 7574 + (p.info.nonLocalizedLabel != null 7575 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7576 Log.v(TAG, " Class=" + p.info.name); 7577 } 7578 final int NI = p.intents.size(); 7579 int j; 7580 for (j = 0; j < NI; j++) { 7581 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7582 if (DEBUG_SHOW_INFO) { 7583 Log.v(TAG, " IntentFilter:"); 7584 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7585 } 7586 if (!intent.debugCheck()) { 7587 Log.w(TAG, "==> For Provider " + p.info.name); 7588 } 7589 addFilter(intent); 7590 } 7591 } 7592 7593 public final void removeProvider(PackageParser.Provider p) { 7594 mProviders.remove(p.getComponentName()); 7595 if (DEBUG_SHOW_INFO) { 7596 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7597 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7598 Log.v(TAG, " Class=" + p.info.name); 7599 } 7600 final int NI = p.intents.size(); 7601 int j; 7602 for (j = 0; j < NI; j++) { 7603 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7604 if (DEBUG_SHOW_INFO) { 7605 Log.v(TAG, " IntentFilter:"); 7606 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7607 } 7608 removeFilter(intent); 7609 } 7610 } 7611 7612 @Override 7613 protected boolean allowFilterResult( 7614 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7615 ProviderInfo filterPi = filter.provider.info; 7616 for (int i = dest.size() - 1; i >= 0; i--) { 7617 ProviderInfo destPi = dest.get(i).providerInfo; 7618 if (destPi.name == filterPi.name 7619 && destPi.packageName == filterPi.packageName) { 7620 return false; 7621 } 7622 } 7623 return true; 7624 } 7625 7626 @Override 7627 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7628 return new PackageParser.ProviderIntentInfo[size]; 7629 } 7630 7631 @Override 7632 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7633 if (!sUserManager.exists(userId)) 7634 return true; 7635 PackageParser.Package p = filter.provider.owner; 7636 if (p != null) { 7637 PackageSetting ps = (PackageSetting) p.mExtras; 7638 if (ps != null) { 7639 // System apps are never considered stopped for purposes of 7640 // filtering, because there may be no way for the user to 7641 // actually re-launch them. 7642 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7643 && ps.getStopped(userId); 7644 } 7645 } 7646 return false; 7647 } 7648 7649 @Override 7650 protected boolean isPackageForFilter(String packageName, 7651 PackageParser.ProviderIntentInfo info) { 7652 return packageName.equals(info.provider.owner.packageName); 7653 } 7654 7655 @Override 7656 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7657 int match, int userId) { 7658 if (!sUserManager.exists(userId)) 7659 return null; 7660 final PackageParser.ProviderIntentInfo info = filter; 7661 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7662 return null; 7663 } 7664 final PackageParser.Provider provider = info.provider; 7665 if (mSafeMode && (provider.info.applicationInfo.flags 7666 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7667 return null; 7668 } 7669 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7670 if (ps == null) { 7671 return null; 7672 } 7673 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7674 ps.readUserState(userId), userId); 7675 if (pi == null) { 7676 return null; 7677 } 7678 final ResolveInfo res = new ResolveInfo(); 7679 res.providerInfo = pi; 7680 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7681 res.filter = filter; 7682 } 7683 res.priority = info.getPriority(); 7684 res.preferredOrder = provider.owner.mPreferredOrder; 7685 res.match = match; 7686 res.isDefault = info.hasDefault; 7687 res.labelRes = info.labelRes; 7688 res.nonLocalizedLabel = info.nonLocalizedLabel; 7689 res.icon = info.icon; 7690 res.system = res.providerInfo.applicationInfo.isSystemApp(); 7691 return res; 7692 } 7693 7694 @Override 7695 protected void sortResults(List<ResolveInfo> results) { 7696 Collections.sort(results, mResolvePrioritySorter); 7697 } 7698 7699 @Override 7700 protected void dumpFilter(PrintWriter out, String prefix, 7701 PackageParser.ProviderIntentInfo filter) { 7702 out.print(prefix); 7703 out.print( 7704 Integer.toHexString(System.identityHashCode(filter.provider))); 7705 out.print(' '); 7706 filter.provider.printComponentShortName(out); 7707 out.print(" filter "); 7708 out.println(Integer.toHexString(System.identityHashCode(filter))); 7709 } 7710 7711 @Override 7712 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 7713 return filter.provider; 7714 } 7715 7716 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7717 PackageParser.Provider provider = (PackageParser.Provider)label; 7718 out.print(prefix); out.print( 7719 Integer.toHexString(System.identityHashCode(provider))); 7720 out.print(' '); 7721 provider.printComponentShortName(out); 7722 if (count > 1) { 7723 out.print(" ("); out.print(count); out.print(" filters)"); 7724 } 7725 out.println(); 7726 } 7727 7728 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 7729 = new ArrayMap<ComponentName, PackageParser.Provider>(); 7730 private int mFlags; 7731 }; 7732 7733 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7734 new Comparator<ResolveInfo>() { 7735 public int compare(ResolveInfo r1, ResolveInfo r2) { 7736 int v1 = r1.priority; 7737 int v2 = r2.priority; 7738 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7739 if (v1 != v2) { 7740 return (v1 > v2) ? -1 : 1; 7741 } 7742 v1 = r1.preferredOrder; 7743 v2 = r2.preferredOrder; 7744 if (v1 != v2) { 7745 return (v1 > v2) ? -1 : 1; 7746 } 7747 if (r1.isDefault != r2.isDefault) { 7748 return r1.isDefault ? -1 : 1; 7749 } 7750 v1 = r1.match; 7751 v2 = r2.match; 7752 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7753 if (v1 != v2) { 7754 return (v1 > v2) ? -1 : 1; 7755 } 7756 if (r1.system != r2.system) { 7757 return r1.system ? -1 : 1; 7758 } 7759 return 0; 7760 } 7761 }; 7762 7763 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7764 new Comparator<ProviderInfo>() { 7765 public int compare(ProviderInfo p1, ProviderInfo p2) { 7766 final int v1 = p1.initOrder; 7767 final int v2 = p2.initOrder; 7768 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7769 } 7770 }; 7771 7772 static final void sendPackageBroadcast(String action, String pkg, 7773 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7774 int[] userIds) { 7775 IActivityManager am = ActivityManagerNative.getDefault(); 7776 if (am != null) { 7777 try { 7778 if (userIds == null) { 7779 userIds = am.getRunningUserIds(); 7780 } 7781 for (int id : userIds) { 7782 final Intent intent = new Intent(action, 7783 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7784 if (extras != null) { 7785 intent.putExtras(extras); 7786 } 7787 if (targetPkg != null) { 7788 intent.setPackage(targetPkg); 7789 } 7790 // Modify the UID when posting to other users 7791 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7792 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7793 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7794 intent.putExtra(Intent.EXTRA_UID, uid); 7795 } 7796 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7797 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7798 if (DEBUG_BROADCASTS) { 7799 RuntimeException here = new RuntimeException("here"); 7800 here.fillInStackTrace(); 7801 Slog.d(TAG, "Sending to user " + id + ": " 7802 + intent.toShortString(false, true, false, false) 7803 + " " + intent.getExtras(), here); 7804 } 7805 am.broadcastIntent(null, intent, null, finishedReceiver, 7806 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7807 finishedReceiver != null, false, id); 7808 } 7809 } catch (RemoteException ex) { 7810 } 7811 } 7812 } 7813 7814 /** 7815 * Check if the external storage media is available. This is true if there 7816 * is a mounted external storage medium or if the external storage is 7817 * emulated. 7818 */ 7819 private boolean isExternalMediaAvailable() { 7820 return mMediaMounted || Environment.isExternalStorageEmulated(); 7821 } 7822 7823 @Override 7824 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7825 // writer 7826 synchronized (mPackages) { 7827 if (!isExternalMediaAvailable()) { 7828 // If the external storage is no longer mounted at this point, 7829 // the caller may not have been able to delete all of this 7830 // packages files and can not delete any more. Bail. 7831 return null; 7832 } 7833 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7834 if (lastPackage != null) { 7835 pkgs.remove(lastPackage); 7836 } 7837 if (pkgs.size() > 0) { 7838 return pkgs.get(0); 7839 } 7840 } 7841 return null; 7842 } 7843 7844 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7845 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7846 userId, andCode ? 1 : 0, packageName); 7847 if (mSystemReady) { 7848 msg.sendToTarget(); 7849 } else { 7850 if (mPostSystemReadyMessages == null) { 7851 mPostSystemReadyMessages = new ArrayList<>(); 7852 } 7853 mPostSystemReadyMessages.add(msg); 7854 } 7855 } 7856 7857 void startCleaningPackages() { 7858 // reader 7859 synchronized (mPackages) { 7860 if (!isExternalMediaAvailable()) { 7861 return; 7862 } 7863 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7864 return; 7865 } 7866 } 7867 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7868 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7869 IActivityManager am = ActivityManagerNative.getDefault(); 7870 if (am != null) { 7871 try { 7872 am.startService(null, intent, null, UserHandle.USER_OWNER); 7873 } catch (RemoteException e) { 7874 } 7875 } 7876 } 7877 7878 @Override 7879 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7880 int installFlags, String installerPackageName, VerificationParams verificationParams, 7881 String packageAbiOverride) { 7882 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7883 packageAbiOverride, UserHandle.getCallingUserId()); 7884 } 7885 7886 @Override 7887 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7888 int installFlags, String installerPackageName, VerificationParams verificationParams, 7889 String packageAbiOverride, int userId) { 7890 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 7891 7892 final int callingUid = Binder.getCallingUid(); 7893 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 7894 7895 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7896 try { 7897 if (observer != null) { 7898 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7899 } 7900 } catch (RemoteException re) { 7901 } 7902 return; 7903 } 7904 7905 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 7906 installFlags |= PackageManager.INSTALL_FROM_ADB; 7907 7908 } else { 7909 // Caller holds INSTALL_PACKAGES permission, so we're less strict 7910 // about installerPackageName. 7911 7912 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 7913 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 7914 } 7915 7916 UserHandle user; 7917 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7918 user = UserHandle.ALL; 7919 } else { 7920 user = new UserHandle(userId); 7921 } 7922 7923 verificationParams.setInstallerUid(callingUid); 7924 7925 final File originFile = new File(originPath); 7926 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7927 7928 final Message msg = mHandler.obtainMessage(INIT_COPY); 7929 msg.obj = new InstallParams(origin, observer, installFlags, 7930 installerPackageName, verificationParams, user, packageAbiOverride); 7931 mHandler.sendMessage(msg); 7932 } 7933 7934 void installStage(String packageName, File stagedDir, String stagedCid, 7935 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7936 String installerPackageName, int installerUid, UserHandle user) { 7937 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7938 params.referrerUri, installerUid, null); 7939 7940 final OriginInfo origin; 7941 if (stagedDir != null) { 7942 origin = OriginInfo.fromStagedFile(stagedDir); 7943 } else { 7944 origin = OriginInfo.fromStagedContainer(stagedCid); 7945 } 7946 7947 final Message msg = mHandler.obtainMessage(INIT_COPY); 7948 msg.obj = new InstallParams(origin, observer, params.installFlags, 7949 installerPackageName, verifParams, user, params.abiOverride); 7950 mHandler.sendMessage(msg); 7951 } 7952 7953 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7954 Bundle extras = new Bundle(1); 7955 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7956 7957 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7958 packageName, extras, null, null, new int[] {userId}); 7959 try { 7960 IActivityManager am = ActivityManagerNative.getDefault(); 7961 final boolean isSystem = 7962 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7963 if (isSystem && am.isUserRunning(userId, false)) { 7964 // The just-installed/enabled app is bundled on the system, so presumed 7965 // to be able to run automatically without needing an explicit launch. 7966 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7967 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7968 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7969 .setPackage(packageName); 7970 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7971 android.app.AppOpsManager.OP_NONE, false, false, userId); 7972 } 7973 } catch (RemoteException e) { 7974 // shouldn't happen 7975 Slog.w(TAG, "Unable to bootstrap installed package", e); 7976 } 7977 } 7978 7979 @Override 7980 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7981 int userId) { 7982 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7983 PackageSetting pkgSetting; 7984 final int uid = Binder.getCallingUid(); 7985 enforceCrossUserPermission(uid, userId, true, true, 7986 "setApplicationHiddenSetting for user " + userId); 7987 7988 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7989 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7990 return false; 7991 } 7992 7993 long callingId = Binder.clearCallingIdentity(); 7994 try { 7995 boolean sendAdded = false; 7996 boolean sendRemoved = false; 7997 // writer 7998 synchronized (mPackages) { 7999 pkgSetting = mSettings.mPackages.get(packageName); 8000 if (pkgSetting == null) { 8001 return false; 8002 } 8003 if (pkgSetting.getHidden(userId) != hidden) { 8004 pkgSetting.setHidden(hidden, userId); 8005 mSettings.writePackageRestrictionsLPr(userId); 8006 if (hidden) { 8007 sendRemoved = true; 8008 } else { 8009 sendAdded = true; 8010 } 8011 } 8012 } 8013 if (sendAdded) { 8014 sendPackageAddedForUser(packageName, pkgSetting, userId); 8015 return true; 8016 } 8017 if (sendRemoved) { 8018 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8019 "hiding pkg"); 8020 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8021 } 8022 } finally { 8023 Binder.restoreCallingIdentity(callingId); 8024 } 8025 return false; 8026 } 8027 8028 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8029 int userId) { 8030 final PackageRemovedInfo info = new PackageRemovedInfo(); 8031 info.removedPackage = packageName; 8032 info.removedUsers = new int[] {userId}; 8033 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8034 info.sendBroadcast(false, false, false); 8035 } 8036 8037 /** 8038 * Returns true if application is not found or there was an error. Otherwise it returns 8039 * the hidden state of the package for the given user. 8040 */ 8041 @Override 8042 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8043 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8044 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8045 false, "getApplicationHidden for user " + userId); 8046 PackageSetting pkgSetting; 8047 long callingId = Binder.clearCallingIdentity(); 8048 try { 8049 // writer 8050 synchronized (mPackages) { 8051 pkgSetting = mSettings.mPackages.get(packageName); 8052 if (pkgSetting == null) { 8053 return true; 8054 } 8055 return pkgSetting.getHidden(userId); 8056 } 8057 } finally { 8058 Binder.restoreCallingIdentity(callingId); 8059 } 8060 } 8061 8062 /** 8063 * @hide 8064 */ 8065 @Override 8066 public int installExistingPackageAsUser(String packageName, int userId) { 8067 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8068 null); 8069 PackageSetting pkgSetting; 8070 final int uid = Binder.getCallingUid(); 8071 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8072 + userId); 8073 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8074 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8075 } 8076 8077 long callingId = Binder.clearCallingIdentity(); 8078 try { 8079 boolean sendAdded = false; 8080 Bundle extras = new Bundle(1); 8081 8082 // writer 8083 synchronized (mPackages) { 8084 pkgSetting = mSettings.mPackages.get(packageName); 8085 if (pkgSetting == null) { 8086 return PackageManager.INSTALL_FAILED_INVALID_URI; 8087 } 8088 if (!pkgSetting.getInstalled(userId)) { 8089 pkgSetting.setInstalled(true, userId); 8090 pkgSetting.setHidden(false, userId); 8091 mSettings.writePackageRestrictionsLPr(userId); 8092 sendAdded = true; 8093 } 8094 } 8095 8096 if (sendAdded) { 8097 sendPackageAddedForUser(packageName, pkgSetting, userId); 8098 } 8099 } finally { 8100 Binder.restoreCallingIdentity(callingId); 8101 } 8102 8103 return PackageManager.INSTALL_SUCCEEDED; 8104 } 8105 8106 boolean isUserRestricted(int userId, String restrictionKey) { 8107 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8108 if (restrictions.getBoolean(restrictionKey, false)) { 8109 Log.w(TAG, "User is restricted: " + restrictionKey); 8110 return true; 8111 } 8112 return false; 8113 } 8114 8115 @Override 8116 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8117 mContext.enforceCallingOrSelfPermission( 8118 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8119 "Only package verification agents can verify applications"); 8120 8121 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8122 final PackageVerificationResponse response = new PackageVerificationResponse( 8123 verificationCode, Binder.getCallingUid()); 8124 msg.arg1 = id; 8125 msg.obj = response; 8126 mHandler.sendMessage(msg); 8127 } 8128 8129 @Override 8130 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8131 long millisecondsToDelay) { 8132 mContext.enforceCallingOrSelfPermission( 8133 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8134 "Only package verification agents can extend verification timeouts"); 8135 8136 final PackageVerificationState state = mPendingVerification.get(id); 8137 final PackageVerificationResponse response = new PackageVerificationResponse( 8138 verificationCodeAtTimeout, Binder.getCallingUid()); 8139 8140 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8141 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8142 } 8143 if (millisecondsToDelay < 0) { 8144 millisecondsToDelay = 0; 8145 } 8146 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8147 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8148 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8149 } 8150 8151 if ((state != null) && !state.timeoutExtended()) { 8152 state.extendTimeout(); 8153 8154 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8155 msg.arg1 = id; 8156 msg.obj = response; 8157 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8158 } 8159 } 8160 8161 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8162 int verificationCode, UserHandle user) { 8163 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8164 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8165 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8166 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8167 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8168 8169 mContext.sendBroadcastAsUser(intent, user, 8170 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8171 } 8172 8173 private ComponentName matchComponentForVerifier(String packageName, 8174 List<ResolveInfo> receivers) { 8175 ActivityInfo targetReceiver = null; 8176 8177 final int NR = receivers.size(); 8178 for (int i = 0; i < NR; i++) { 8179 final ResolveInfo info = receivers.get(i); 8180 if (info.activityInfo == null) { 8181 continue; 8182 } 8183 8184 if (packageName.equals(info.activityInfo.packageName)) { 8185 targetReceiver = info.activityInfo; 8186 break; 8187 } 8188 } 8189 8190 if (targetReceiver == null) { 8191 return null; 8192 } 8193 8194 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8195 } 8196 8197 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8198 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8199 if (pkgInfo.verifiers.length == 0) { 8200 return null; 8201 } 8202 8203 final int N = pkgInfo.verifiers.length; 8204 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8205 for (int i = 0; i < N; i++) { 8206 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8207 8208 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8209 receivers); 8210 if (comp == null) { 8211 continue; 8212 } 8213 8214 final int verifierUid = getUidForVerifier(verifierInfo); 8215 if (verifierUid == -1) { 8216 continue; 8217 } 8218 8219 if (DEBUG_VERIFY) { 8220 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8221 + " with the correct signature"); 8222 } 8223 sufficientVerifiers.add(comp); 8224 verificationState.addSufficientVerifier(verifierUid); 8225 } 8226 8227 return sufficientVerifiers; 8228 } 8229 8230 private int getUidForVerifier(VerifierInfo verifierInfo) { 8231 synchronized (mPackages) { 8232 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8233 if (pkg == null) { 8234 return -1; 8235 } else if (pkg.mSignatures.length != 1) { 8236 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8237 + " has more than one signature; ignoring"); 8238 return -1; 8239 } 8240 8241 /* 8242 * If the public key of the package's signature does not match 8243 * our expected public key, then this is a different package and 8244 * we should skip. 8245 */ 8246 8247 final byte[] expectedPublicKey; 8248 try { 8249 final Signature verifierSig = pkg.mSignatures[0]; 8250 final PublicKey publicKey = verifierSig.getPublicKey(); 8251 expectedPublicKey = publicKey.getEncoded(); 8252 } catch (CertificateException e) { 8253 return -1; 8254 } 8255 8256 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8257 8258 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8259 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8260 + " does not have the expected public key; ignoring"); 8261 return -1; 8262 } 8263 8264 return pkg.applicationInfo.uid; 8265 } 8266 } 8267 8268 @Override 8269 public void finishPackageInstall(int token) { 8270 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8271 8272 if (DEBUG_INSTALL) { 8273 Slog.v(TAG, "BM finishing package install for " + token); 8274 } 8275 8276 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8277 mHandler.sendMessage(msg); 8278 } 8279 8280 /** 8281 * Get the verification agent timeout. 8282 * 8283 * @return verification timeout in milliseconds 8284 */ 8285 private long getVerificationTimeout() { 8286 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8287 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8288 DEFAULT_VERIFICATION_TIMEOUT); 8289 } 8290 8291 /** 8292 * Get the default verification agent response code. 8293 * 8294 * @return default verification response code 8295 */ 8296 private int getDefaultVerificationResponse() { 8297 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8298 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8299 DEFAULT_VERIFICATION_RESPONSE); 8300 } 8301 8302 /** 8303 * Check whether or not package verification has been enabled. 8304 * 8305 * @return true if verification should be performed 8306 */ 8307 private boolean isVerificationEnabled(int userId, int installFlags) { 8308 if (!DEFAULT_VERIFY_ENABLE) { 8309 return false; 8310 } 8311 8312 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8313 8314 // Check if installing from ADB 8315 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8316 // Do not run verification in a test harness environment 8317 if (ActivityManager.isRunningInTestHarness()) { 8318 return false; 8319 } 8320 if (ensureVerifyAppsEnabled) { 8321 return true; 8322 } 8323 // Check if the developer does not want package verification for ADB installs 8324 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8325 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8326 return false; 8327 } 8328 } 8329 8330 if (ensureVerifyAppsEnabled) { 8331 return true; 8332 } 8333 8334 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8335 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8336 } 8337 8338 /** 8339 * Get the "allow unknown sources" setting. 8340 * 8341 * @return the current "allow unknown sources" setting 8342 */ 8343 private int getUnknownSourcesSettings() { 8344 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8345 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8346 -1); 8347 } 8348 8349 @Override 8350 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8351 final int uid = Binder.getCallingUid(); 8352 // writer 8353 synchronized (mPackages) { 8354 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8355 if (targetPackageSetting == null) { 8356 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8357 } 8358 8359 PackageSetting installerPackageSetting; 8360 if (installerPackageName != null) { 8361 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8362 if (installerPackageSetting == null) { 8363 throw new IllegalArgumentException("Unknown installer package: " 8364 + installerPackageName); 8365 } 8366 } else { 8367 installerPackageSetting = null; 8368 } 8369 8370 Signature[] callerSignature; 8371 Object obj = mSettings.getUserIdLPr(uid); 8372 if (obj != null) { 8373 if (obj instanceof SharedUserSetting) { 8374 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8375 } else if (obj instanceof PackageSetting) { 8376 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8377 } else { 8378 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8379 } 8380 } else { 8381 throw new SecurityException("Unknown calling uid " + uid); 8382 } 8383 8384 // Verify: can't set installerPackageName to a package that is 8385 // not signed with the same cert as the caller. 8386 if (installerPackageSetting != null) { 8387 if (compareSignatures(callerSignature, 8388 installerPackageSetting.signatures.mSignatures) 8389 != PackageManager.SIGNATURE_MATCH) { 8390 throw new SecurityException( 8391 "Caller does not have same cert as new installer package " 8392 + installerPackageName); 8393 } 8394 } 8395 8396 // Verify: if target already has an installer package, it must 8397 // be signed with the same cert as the caller. 8398 if (targetPackageSetting.installerPackageName != null) { 8399 PackageSetting setting = mSettings.mPackages.get( 8400 targetPackageSetting.installerPackageName); 8401 // If the currently set package isn't valid, then it's always 8402 // okay to change it. 8403 if (setting != null) { 8404 if (compareSignatures(callerSignature, 8405 setting.signatures.mSignatures) 8406 != PackageManager.SIGNATURE_MATCH) { 8407 throw new SecurityException( 8408 "Caller does not have same cert as old installer package " 8409 + targetPackageSetting.installerPackageName); 8410 } 8411 } 8412 } 8413 8414 // Okay! 8415 targetPackageSetting.installerPackageName = installerPackageName; 8416 scheduleWriteSettingsLocked(); 8417 } 8418 } 8419 8420 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8421 // Queue up an async operation since the package installation may take a little while. 8422 mHandler.post(new Runnable() { 8423 public void run() { 8424 mHandler.removeCallbacks(this); 8425 // Result object to be returned 8426 PackageInstalledInfo res = new PackageInstalledInfo(); 8427 res.returnCode = currentStatus; 8428 res.uid = -1; 8429 res.pkg = null; 8430 res.removedInfo = new PackageRemovedInfo(); 8431 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8432 args.doPreInstall(res.returnCode); 8433 synchronized (mInstallLock) { 8434 installPackageLI(args, res); 8435 } 8436 args.doPostInstall(res.returnCode, res.uid); 8437 } 8438 8439 // A restore should be performed at this point if (a) the install 8440 // succeeded, (b) the operation is not an update, and (c) the new 8441 // package has not opted out of backup participation. 8442 final boolean update = res.removedInfo.removedPackage != null; 8443 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8444 boolean doRestore = !update 8445 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8446 8447 // Set up the post-install work request bookkeeping. This will be used 8448 // and cleaned up by the post-install event handling regardless of whether 8449 // there's a restore pass performed. Token values are >= 1. 8450 int token; 8451 if (mNextInstallToken < 0) mNextInstallToken = 1; 8452 token = mNextInstallToken++; 8453 8454 PostInstallData data = new PostInstallData(args, res); 8455 mRunningInstalls.put(token, data); 8456 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8457 8458 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8459 // Pass responsibility to the Backup Manager. It will perform a 8460 // restore if appropriate, then pass responsibility back to the 8461 // Package Manager to run the post-install observer callbacks 8462 // and broadcasts. 8463 IBackupManager bm = IBackupManager.Stub.asInterface( 8464 ServiceManager.getService(Context.BACKUP_SERVICE)); 8465 if (bm != null) { 8466 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8467 + " to BM for possible restore"); 8468 try { 8469 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 8470 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8471 } else { 8472 doRestore = false; 8473 } 8474 } catch (RemoteException e) { 8475 // can't happen; the backup manager is local 8476 } catch (Exception e) { 8477 Slog.e(TAG, "Exception trying to enqueue restore", e); 8478 doRestore = false; 8479 } 8480 } else { 8481 Slog.e(TAG, "Backup Manager not found!"); 8482 doRestore = false; 8483 } 8484 } 8485 8486 if (!doRestore) { 8487 // No restore possible, or the Backup Manager was mysteriously not 8488 // available -- just fire the post-install work request directly. 8489 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8490 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8491 mHandler.sendMessage(msg); 8492 } 8493 } 8494 }); 8495 } 8496 8497 private abstract class HandlerParams { 8498 private static final int MAX_RETRIES = 4; 8499 8500 /** 8501 * Number of times startCopy() has been attempted and had a non-fatal 8502 * error. 8503 */ 8504 private int mRetries = 0; 8505 8506 /** User handle for the user requesting the information or installation. */ 8507 private final UserHandle mUser; 8508 8509 HandlerParams(UserHandle user) { 8510 mUser = user; 8511 } 8512 8513 UserHandle getUser() { 8514 return mUser; 8515 } 8516 8517 final boolean startCopy() { 8518 boolean res; 8519 try { 8520 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8521 8522 if (++mRetries > MAX_RETRIES) { 8523 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8524 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8525 handleServiceError(); 8526 return false; 8527 } else { 8528 handleStartCopy(); 8529 res = true; 8530 } 8531 } catch (RemoteException e) { 8532 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8533 mHandler.sendEmptyMessage(MCS_RECONNECT); 8534 res = false; 8535 } 8536 handleReturnCode(); 8537 return res; 8538 } 8539 8540 final void serviceError() { 8541 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8542 handleServiceError(); 8543 handleReturnCode(); 8544 } 8545 8546 abstract void handleStartCopy() throws RemoteException; 8547 abstract void handleServiceError(); 8548 abstract void handleReturnCode(); 8549 } 8550 8551 class MeasureParams extends HandlerParams { 8552 private final PackageStats mStats; 8553 private boolean mSuccess; 8554 8555 private final IPackageStatsObserver mObserver; 8556 8557 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8558 super(new UserHandle(stats.userHandle)); 8559 mObserver = observer; 8560 mStats = stats; 8561 } 8562 8563 @Override 8564 public String toString() { 8565 return "MeasureParams{" 8566 + Integer.toHexString(System.identityHashCode(this)) 8567 + " " + mStats.packageName + "}"; 8568 } 8569 8570 @Override 8571 void handleStartCopy() throws RemoteException { 8572 synchronized (mInstallLock) { 8573 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8574 } 8575 8576 if (mSuccess) { 8577 final boolean mounted; 8578 if (Environment.isExternalStorageEmulated()) { 8579 mounted = true; 8580 } else { 8581 final String status = Environment.getExternalStorageState(); 8582 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8583 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8584 } 8585 8586 if (mounted) { 8587 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8588 8589 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8590 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8591 8592 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8593 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8594 8595 // Always subtract cache size, since it's a subdirectory 8596 mStats.externalDataSize -= mStats.externalCacheSize; 8597 8598 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8599 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8600 8601 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8602 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8603 } 8604 } 8605 } 8606 8607 @Override 8608 void handleReturnCode() { 8609 if (mObserver != null) { 8610 try { 8611 mObserver.onGetStatsCompleted(mStats, mSuccess); 8612 } catch (RemoteException e) { 8613 Slog.i(TAG, "Observer no longer exists."); 8614 } 8615 } 8616 } 8617 8618 @Override 8619 void handleServiceError() { 8620 Slog.e(TAG, "Could not measure application " + mStats.packageName 8621 + " external storage"); 8622 } 8623 } 8624 8625 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8626 throws RemoteException { 8627 long result = 0; 8628 for (File path : paths) { 8629 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8630 } 8631 return result; 8632 } 8633 8634 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8635 for (File path : paths) { 8636 try { 8637 mcs.clearDirectory(path.getAbsolutePath()); 8638 } catch (RemoteException e) { 8639 } 8640 } 8641 } 8642 8643 static class OriginInfo { 8644 /** 8645 * Location where install is coming from, before it has been 8646 * copied/renamed into place. This could be a single monolithic APK 8647 * file, or a cluster directory. This location may be untrusted. 8648 */ 8649 final File file; 8650 final String cid; 8651 8652 /** 8653 * Flag indicating that {@link #file} or {@link #cid} has already been 8654 * staged, meaning downstream users don't need to defensively copy the 8655 * contents. 8656 */ 8657 final boolean staged; 8658 8659 /** 8660 * Flag indicating that {@link #file} or {@link #cid} is an already 8661 * installed app that is being moved. 8662 */ 8663 final boolean existing; 8664 8665 final String resolvedPath; 8666 final File resolvedFile; 8667 8668 static OriginInfo fromNothing() { 8669 return new OriginInfo(null, null, false, false); 8670 } 8671 8672 static OriginInfo fromUntrustedFile(File file) { 8673 return new OriginInfo(file, null, false, false); 8674 } 8675 8676 static OriginInfo fromExistingFile(File file) { 8677 return new OriginInfo(file, null, false, true); 8678 } 8679 8680 static OriginInfo fromStagedFile(File file) { 8681 return new OriginInfo(file, null, true, false); 8682 } 8683 8684 static OriginInfo fromStagedContainer(String cid) { 8685 return new OriginInfo(null, cid, true, false); 8686 } 8687 8688 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8689 this.file = file; 8690 this.cid = cid; 8691 this.staged = staged; 8692 this.existing = existing; 8693 8694 if (cid != null) { 8695 resolvedPath = PackageHelper.getSdDir(cid); 8696 resolvedFile = new File(resolvedPath); 8697 } else if (file != null) { 8698 resolvedPath = file.getAbsolutePath(); 8699 resolvedFile = file; 8700 } else { 8701 resolvedPath = null; 8702 resolvedFile = null; 8703 } 8704 } 8705 } 8706 8707 class InstallParams extends HandlerParams { 8708 final OriginInfo origin; 8709 final IPackageInstallObserver2 observer; 8710 int installFlags; 8711 final String installerPackageName; 8712 final VerificationParams verificationParams; 8713 private InstallArgs mArgs; 8714 private int mRet; 8715 final String packageAbiOverride; 8716 8717 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8718 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8719 String packageAbiOverride) { 8720 super(user); 8721 this.origin = origin; 8722 this.observer = observer; 8723 this.installFlags = installFlags; 8724 this.installerPackageName = installerPackageName; 8725 this.verificationParams = verificationParams; 8726 this.packageAbiOverride = packageAbiOverride; 8727 } 8728 8729 @Override 8730 public String toString() { 8731 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8732 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8733 } 8734 8735 public ManifestDigest getManifestDigest() { 8736 if (verificationParams == null) { 8737 return null; 8738 } 8739 return verificationParams.getManifestDigest(); 8740 } 8741 8742 private int installLocationPolicy(PackageInfoLite pkgLite) { 8743 String packageName = pkgLite.packageName; 8744 int installLocation = pkgLite.installLocation; 8745 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8746 // reader 8747 synchronized (mPackages) { 8748 PackageParser.Package pkg = mPackages.get(packageName); 8749 if (pkg != null) { 8750 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8751 // Check for downgrading. 8752 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8753 try { 8754 checkDowngrade(pkg, pkgLite); 8755 } catch (PackageManagerException e) { 8756 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 8757 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8758 } 8759 } 8760 // Check for updated system application. 8761 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8762 if (onSd) { 8763 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8764 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8765 } 8766 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8767 } else { 8768 if (onSd) { 8769 // Install flag overrides everything. 8770 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8771 } 8772 // If current upgrade specifies particular preference 8773 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8774 // Application explicitly specified internal. 8775 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8776 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8777 // App explictly prefers external. Let policy decide 8778 } else { 8779 // Prefer previous location 8780 if (isExternal(pkg)) { 8781 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8782 } 8783 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8784 } 8785 } 8786 } else { 8787 // Invalid install. Return error code 8788 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8789 } 8790 } 8791 } 8792 // All the special cases have been taken care of. 8793 // Return result based on recommended install location. 8794 if (onSd) { 8795 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8796 } 8797 return pkgLite.recommendedInstallLocation; 8798 } 8799 8800 /* 8801 * Invoke remote method to get package information and install 8802 * location values. Override install location based on default 8803 * policy if needed and then create install arguments based 8804 * on the install location. 8805 */ 8806 public void handleStartCopy() throws RemoteException { 8807 int ret = PackageManager.INSTALL_SUCCEEDED; 8808 8809 // If we're already staged, we've firmly committed to an install location 8810 if (origin.staged) { 8811 if (origin.file != null) { 8812 installFlags |= PackageManager.INSTALL_INTERNAL; 8813 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8814 } else if (origin.cid != null) { 8815 installFlags |= PackageManager.INSTALL_EXTERNAL; 8816 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8817 } else { 8818 throw new IllegalStateException("Invalid stage location"); 8819 } 8820 } 8821 8822 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8823 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8824 8825 PackageInfoLite pkgLite = null; 8826 8827 if (onInt && onSd) { 8828 // Check if both bits are set. 8829 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8830 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8831 } else { 8832 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8833 packageAbiOverride); 8834 8835 /* 8836 * If we have too little free space, try to free cache 8837 * before giving up. 8838 */ 8839 if (!origin.staged && pkgLite.recommendedInstallLocation 8840 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8841 // TODO: focus freeing disk space on the target device 8842 final StorageManager storage = StorageManager.from(mContext); 8843 final long lowThreshold = storage.getStorageLowBytes( 8844 Environment.getDataDirectory()); 8845 8846 final long sizeBytes = mContainerService.calculateInstalledSize( 8847 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8848 8849 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8850 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8851 installFlags, packageAbiOverride); 8852 } 8853 8854 /* 8855 * The cache free must have deleted the file we 8856 * downloaded to install. 8857 * 8858 * TODO: fix the "freeCache" call to not delete 8859 * the file we care about. 8860 */ 8861 if (pkgLite.recommendedInstallLocation 8862 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8863 pkgLite.recommendedInstallLocation 8864 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8865 } 8866 } 8867 } 8868 8869 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8870 int loc = pkgLite.recommendedInstallLocation; 8871 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8872 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8873 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8874 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8875 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8876 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8877 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8878 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8879 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8880 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8881 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8882 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8883 } else { 8884 // Override with defaults if needed. 8885 loc = installLocationPolicy(pkgLite); 8886 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8887 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8888 } else if (!onSd && !onInt) { 8889 // Override install location with flags 8890 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8891 // Set the flag to install on external media. 8892 installFlags |= PackageManager.INSTALL_EXTERNAL; 8893 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8894 } else { 8895 // Make sure the flag for installing on external 8896 // media is unset 8897 installFlags |= PackageManager.INSTALL_INTERNAL; 8898 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8899 } 8900 } 8901 } 8902 } 8903 8904 final InstallArgs args = createInstallArgs(this); 8905 mArgs = args; 8906 8907 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8908 /* 8909 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8910 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8911 */ 8912 int userIdentifier = getUser().getIdentifier(); 8913 if (userIdentifier == UserHandle.USER_ALL 8914 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8915 userIdentifier = UserHandle.USER_OWNER; 8916 } 8917 8918 /* 8919 * Determine if we have any installed package verifiers. If we 8920 * do, then we'll defer to them to verify the packages. 8921 */ 8922 final int requiredUid = mRequiredVerifierPackage == null ? -1 8923 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8924 if (!origin.existing && requiredUid != -1 8925 && isVerificationEnabled(userIdentifier, installFlags)) { 8926 final Intent verification = new Intent( 8927 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8928 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 8929 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8930 PACKAGE_MIME_TYPE); 8931 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8932 8933 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8934 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8935 0 /* TODO: Which userId? */); 8936 8937 if (DEBUG_VERIFY) { 8938 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8939 + verification.toString() + " with " + pkgLite.verifiers.length 8940 + " optional verifiers"); 8941 } 8942 8943 final int verificationId = mPendingVerificationToken++; 8944 8945 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8946 8947 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8948 installerPackageName); 8949 8950 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8951 installFlags); 8952 8953 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8954 pkgLite.packageName); 8955 8956 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8957 pkgLite.versionCode); 8958 8959 if (verificationParams != null) { 8960 if (verificationParams.getVerificationURI() != null) { 8961 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8962 verificationParams.getVerificationURI()); 8963 } 8964 if (verificationParams.getOriginatingURI() != null) { 8965 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8966 verificationParams.getOriginatingURI()); 8967 } 8968 if (verificationParams.getReferrer() != null) { 8969 verification.putExtra(Intent.EXTRA_REFERRER, 8970 verificationParams.getReferrer()); 8971 } 8972 if (verificationParams.getOriginatingUid() >= 0) { 8973 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8974 verificationParams.getOriginatingUid()); 8975 } 8976 if (verificationParams.getInstallerUid() >= 0) { 8977 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8978 verificationParams.getInstallerUid()); 8979 } 8980 } 8981 8982 final PackageVerificationState verificationState = new PackageVerificationState( 8983 requiredUid, args); 8984 8985 mPendingVerification.append(verificationId, verificationState); 8986 8987 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8988 receivers, verificationState); 8989 8990 /* 8991 * If any sufficient verifiers were listed in the package 8992 * manifest, attempt to ask them. 8993 */ 8994 if (sufficientVerifiers != null) { 8995 final int N = sufficientVerifiers.size(); 8996 if (N == 0) { 8997 Slog.i(TAG, "Additional verifiers required, but none installed."); 8998 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8999 } else { 9000 for (int i = 0; i < N; i++) { 9001 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9002 9003 final Intent sufficientIntent = new Intent(verification); 9004 sufficientIntent.setComponent(verifierComponent); 9005 9006 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9007 } 9008 } 9009 } 9010 9011 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9012 mRequiredVerifierPackage, receivers); 9013 if (ret == PackageManager.INSTALL_SUCCEEDED 9014 && mRequiredVerifierPackage != null) { 9015 /* 9016 * Send the intent to the required verification agent, 9017 * but only start the verification timeout after the 9018 * target BroadcastReceivers have run. 9019 */ 9020 verification.setComponent(requiredVerifierComponent); 9021 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9022 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9023 new BroadcastReceiver() { 9024 @Override 9025 public void onReceive(Context context, Intent intent) { 9026 final Message msg = mHandler 9027 .obtainMessage(CHECK_PENDING_VERIFICATION); 9028 msg.arg1 = verificationId; 9029 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9030 } 9031 }, null, 0, null, null); 9032 9033 /* 9034 * We don't want the copy to proceed until verification 9035 * succeeds, so null out this field. 9036 */ 9037 mArgs = null; 9038 } 9039 } else { 9040 /* 9041 * No package verification is enabled, so immediately start 9042 * the remote call to initiate copy using temporary file. 9043 */ 9044 ret = args.copyApk(mContainerService, true); 9045 } 9046 } 9047 9048 mRet = ret; 9049 } 9050 9051 @Override 9052 void handleReturnCode() { 9053 // If mArgs is null, then MCS couldn't be reached. When it 9054 // reconnects, it will try again to install. At that point, this 9055 // will succeed. 9056 if (mArgs != null) { 9057 processPendingInstall(mArgs, mRet); 9058 } 9059 } 9060 9061 @Override 9062 void handleServiceError() { 9063 mArgs = createInstallArgs(this); 9064 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9065 } 9066 9067 public boolean isForwardLocked() { 9068 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9069 } 9070 } 9071 9072 /** 9073 * Used during creation of InstallArgs 9074 * 9075 * @param installFlags package installation flags 9076 * @return true if should be installed on external storage 9077 */ 9078 private static boolean installOnSd(int installFlags) { 9079 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9080 return false; 9081 } 9082 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9083 return true; 9084 } 9085 return false; 9086 } 9087 9088 /** 9089 * Used during creation of InstallArgs 9090 * 9091 * @param installFlags package installation flags 9092 * @return true if should be installed as forward locked 9093 */ 9094 private static boolean installForwardLocked(int installFlags) { 9095 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9096 } 9097 9098 private InstallArgs createInstallArgs(InstallParams params) { 9099 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9100 return new AsecInstallArgs(params); 9101 } else { 9102 return new FileInstallArgs(params); 9103 } 9104 } 9105 9106 /** 9107 * Create args that describe an existing installed package. Typically used 9108 * when cleaning up old installs, or used as a move source. 9109 */ 9110 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9111 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9112 final boolean isInAsec; 9113 if (installOnSd(installFlags)) { 9114 /* Apps on SD card are always in ASEC containers. */ 9115 isInAsec = true; 9116 } else if (installForwardLocked(installFlags) 9117 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9118 /* 9119 * Forward-locked apps are only in ASEC containers if they're the 9120 * new style 9121 */ 9122 isInAsec = true; 9123 } else { 9124 isInAsec = false; 9125 } 9126 9127 if (isInAsec) { 9128 return new AsecInstallArgs(codePath, instructionSets, 9129 installOnSd(installFlags), installForwardLocked(installFlags)); 9130 } else { 9131 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9132 instructionSets); 9133 } 9134 } 9135 9136 static abstract class InstallArgs { 9137 /** @see InstallParams#origin */ 9138 final OriginInfo origin; 9139 9140 final IPackageInstallObserver2 observer; 9141 // Always refers to PackageManager flags only 9142 final int installFlags; 9143 final String installerPackageName; 9144 final ManifestDigest manifestDigest; 9145 final UserHandle user; 9146 final String abiOverride; 9147 9148 // The list of instruction sets supported by this app. This is currently 9149 // only used during the rmdex() phase to clean up resources. We can get rid of this 9150 // if we move dex files under the common app path. 9151 /* nullable */ String[] instructionSets; 9152 9153 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9154 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9155 String[] instructionSets, String abiOverride) { 9156 this.origin = origin; 9157 this.installFlags = installFlags; 9158 this.observer = observer; 9159 this.installerPackageName = installerPackageName; 9160 this.manifestDigest = manifestDigest; 9161 this.user = user; 9162 this.instructionSets = instructionSets; 9163 this.abiOverride = abiOverride; 9164 } 9165 9166 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9167 abstract int doPreInstall(int status); 9168 9169 /** 9170 * Rename package into final resting place. All paths on the given 9171 * scanned package should be updated to reflect the rename. 9172 */ 9173 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9174 abstract int doPostInstall(int status, int uid); 9175 9176 /** @see PackageSettingBase#codePathString */ 9177 abstract String getCodePath(); 9178 /** @see PackageSettingBase#resourcePathString */ 9179 abstract String getResourcePath(); 9180 abstract String getLegacyNativeLibraryPath(); 9181 9182 // Need installer lock especially for dex file removal. 9183 abstract void cleanUpResourcesLI(); 9184 abstract boolean doPostDeleteLI(boolean delete); 9185 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9186 9187 /** 9188 * Called before the source arguments are copied. This is used mostly 9189 * for MoveParams when it needs to read the source file to put it in the 9190 * destination. 9191 */ 9192 int doPreCopy() { 9193 return PackageManager.INSTALL_SUCCEEDED; 9194 } 9195 9196 /** 9197 * Called after the source arguments are copied. This is used mostly for 9198 * MoveParams when it needs to read the source file to put it in the 9199 * destination. 9200 * 9201 * @return 9202 */ 9203 int doPostCopy(int uid) { 9204 return PackageManager.INSTALL_SUCCEEDED; 9205 } 9206 9207 protected boolean isFwdLocked() { 9208 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9209 } 9210 9211 protected boolean isExternal() { 9212 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9213 } 9214 9215 UserHandle getUser() { 9216 return user; 9217 } 9218 } 9219 9220 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9221 if (!allCodePaths.isEmpty()) { 9222 if (instructionSets == null) { 9223 throw new IllegalStateException("instructionSet == null"); 9224 } 9225 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9226 for (String codePath : allCodePaths) { 9227 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9228 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9229 if (retCode < 0) { 9230 Slog.w(TAG, "Couldn't remove dex file for package: " 9231 + " at location " + codePath + ", retcode=" + retCode); 9232 // we don't consider this to be a failure of the core package deletion 9233 } 9234 } 9235 } 9236 } 9237 } 9238 9239 /** 9240 * Logic to handle installation of non-ASEC applications, including copying 9241 * and renaming logic. 9242 */ 9243 class FileInstallArgs extends InstallArgs { 9244 private File codeFile; 9245 private File resourceFile; 9246 private File legacyNativeLibraryPath; 9247 9248 // Example topology: 9249 // /data/app/com.example/base.apk 9250 // /data/app/com.example/split_foo.apk 9251 // /data/app/com.example/lib/arm/libfoo.so 9252 // /data/app/com.example/lib/arm64/libfoo.so 9253 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9254 9255 /** New install */ 9256 FileInstallArgs(InstallParams params) { 9257 super(params.origin, params.observer, params.installFlags, 9258 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9259 null /* instruction sets */, params.packageAbiOverride); 9260 if (isFwdLocked()) { 9261 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9262 } 9263 } 9264 9265 /** Existing install */ 9266 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9267 String[] instructionSets) { 9268 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9269 this.codeFile = (codePath != null) ? new File(codePath) : null; 9270 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9271 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9272 new File(legacyNativeLibraryPath) : null; 9273 } 9274 9275 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9276 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9277 isFwdLocked(), abiOverride); 9278 9279 final StorageManager storage = StorageManager.from(mContext); 9280 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9281 } 9282 9283 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9284 if (origin.staged) { 9285 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9286 codeFile = origin.file; 9287 resourceFile = origin.file; 9288 return PackageManager.INSTALL_SUCCEEDED; 9289 } 9290 9291 try { 9292 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9293 codeFile = tempDir; 9294 resourceFile = tempDir; 9295 } catch (IOException e) { 9296 Slog.w(TAG, "Failed to create copy file: " + e); 9297 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9298 } 9299 9300 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9301 @Override 9302 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9303 if (!FileUtils.isValidExtFilename(name)) { 9304 throw new IllegalArgumentException("Invalid filename: " + name); 9305 } 9306 try { 9307 final File file = new File(codeFile, name); 9308 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9309 O_RDWR | O_CREAT, 0644); 9310 Os.chmod(file.getAbsolutePath(), 0644); 9311 return new ParcelFileDescriptor(fd); 9312 } catch (ErrnoException e) { 9313 throw new RemoteException("Failed to open: " + e.getMessage()); 9314 } 9315 } 9316 }; 9317 9318 int ret = PackageManager.INSTALL_SUCCEEDED; 9319 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9320 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9321 Slog.e(TAG, "Failed to copy package"); 9322 return ret; 9323 } 9324 9325 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9326 NativeLibraryHelper.Handle handle = null; 9327 try { 9328 handle = NativeLibraryHelper.Handle.create(codeFile); 9329 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9330 abiOverride); 9331 } catch (IOException e) { 9332 Slog.e(TAG, "Copying native libraries failed", e); 9333 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9334 } finally { 9335 IoUtils.closeQuietly(handle); 9336 } 9337 9338 return ret; 9339 } 9340 9341 int doPreInstall(int status) { 9342 if (status != PackageManager.INSTALL_SUCCEEDED) { 9343 cleanUp(); 9344 } 9345 return status; 9346 } 9347 9348 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9349 if (status != PackageManager.INSTALL_SUCCEEDED) { 9350 cleanUp(); 9351 return false; 9352 } else { 9353 final File beforeCodeFile = codeFile; 9354 final File afterCodeFile = getNextCodePath(pkg.packageName); 9355 9356 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9357 try { 9358 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9359 } catch (ErrnoException e) { 9360 Slog.d(TAG, "Failed to rename", e); 9361 return false; 9362 } 9363 9364 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9365 Slog.d(TAG, "Failed to restorecon"); 9366 return false; 9367 } 9368 9369 // Reflect the rename internally 9370 codeFile = afterCodeFile; 9371 resourceFile = afterCodeFile; 9372 9373 // Reflect the rename in scanned details 9374 pkg.codePath = afterCodeFile.getAbsolutePath(); 9375 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9376 pkg.baseCodePath); 9377 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9378 pkg.splitCodePaths); 9379 9380 // Reflect the rename in app info 9381 pkg.applicationInfo.setCodePath(pkg.codePath); 9382 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9383 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9384 pkg.applicationInfo.setResourcePath(pkg.codePath); 9385 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9386 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9387 9388 return true; 9389 } 9390 } 9391 9392 int doPostInstall(int status, int uid) { 9393 if (status != PackageManager.INSTALL_SUCCEEDED) { 9394 cleanUp(); 9395 } 9396 return status; 9397 } 9398 9399 @Override 9400 String getCodePath() { 9401 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9402 } 9403 9404 @Override 9405 String getResourcePath() { 9406 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9407 } 9408 9409 @Override 9410 String getLegacyNativeLibraryPath() { 9411 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9412 } 9413 9414 private boolean cleanUp() { 9415 if (codeFile == null || !codeFile.exists()) { 9416 return false; 9417 } 9418 9419 if (codeFile.isDirectory()) { 9420 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 9421 } else { 9422 codeFile.delete(); 9423 } 9424 9425 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9426 resourceFile.delete(); 9427 } 9428 9429 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9430 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9431 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9432 } 9433 legacyNativeLibraryPath.delete(); 9434 } 9435 9436 return true; 9437 } 9438 9439 void cleanUpResourcesLI() { 9440 // Try enumerating all code paths before deleting 9441 List<String> allCodePaths = Collections.EMPTY_LIST; 9442 if (codeFile != null && codeFile.exists()) { 9443 try { 9444 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9445 allCodePaths = pkg.getAllCodePaths(); 9446 } catch (PackageParserException e) { 9447 // Ignored; we tried our best 9448 } 9449 } 9450 9451 cleanUp(); 9452 removeDexFiles(allCodePaths, instructionSets); 9453 } 9454 9455 boolean doPostDeleteLI(boolean delete) { 9456 // XXX err, shouldn't we respect the delete flag? 9457 cleanUpResourcesLI(); 9458 return true; 9459 } 9460 } 9461 9462 private boolean isAsecExternal(String cid) { 9463 final String asecPath = PackageHelper.getSdFilesystem(cid); 9464 return !asecPath.startsWith(mAsecInternalPath); 9465 } 9466 9467 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9468 PackageManagerException { 9469 if (copyRet < 0) { 9470 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9471 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9472 throw new PackageManagerException(copyRet, message); 9473 } 9474 } 9475 } 9476 9477 /** 9478 * Extract the MountService "container ID" from the full code path of an 9479 * .apk. 9480 */ 9481 static String cidFromCodePath(String fullCodePath) { 9482 int eidx = fullCodePath.lastIndexOf("/"); 9483 String subStr1 = fullCodePath.substring(0, eidx); 9484 int sidx = subStr1.lastIndexOf("/"); 9485 return subStr1.substring(sidx+1, eidx); 9486 } 9487 9488 /** 9489 * Logic to handle installation of ASEC applications, including copying and 9490 * renaming logic. 9491 */ 9492 class AsecInstallArgs extends InstallArgs { 9493 static final String RES_FILE_NAME = "pkg.apk"; 9494 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9495 9496 String cid; 9497 String packagePath; 9498 String resourcePath; 9499 String legacyNativeLibraryDir; 9500 9501 /** New install */ 9502 AsecInstallArgs(InstallParams params) { 9503 super(params.origin, params.observer, params.installFlags, 9504 params.installerPackageName, params.getManifestDigest(), 9505 params.getUser(), null /* instruction sets */, 9506 params.packageAbiOverride); 9507 } 9508 9509 /** Existing install */ 9510 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9511 boolean isExternal, boolean isForwardLocked) { 9512 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9513 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9514 instructionSets, null); 9515 // Hackily pretend we're still looking at a full code path 9516 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9517 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9518 } 9519 9520 // Extract cid from fullCodePath 9521 int eidx = fullCodePath.lastIndexOf("/"); 9522 String subStr1 = fullCodePath.substring(0, eidx); 9523 int sidx = subStr1.lastIndexOf("/"); 9524 cid = subStr1.substring(sidx+1, eidx); 9525 setMountPath(subStr1); 9526 } 9527 9528 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9529 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9530 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9531 instructionSets, null); 9532 this.cid = cid; 9533 setMountPath(PackageHelper.getSdDir(cid)); 9534 } 9535 9536 void createCopyFile() { 9537 cid = mInstallerService.allocateExternalStageCidLegacy(); 9538 } 9539 9540 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9541 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9542 abiOverride); 9543 9544 final File target; 9545 if (isExternal()) { 9546 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9547 } else { 9548 target = Environment.getDataDirectory(); 9549 } 9550 9551 final StorageManager storage = StorageManager.from(mContext); 9552 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9553 } 9554 9555 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9556 if (origin.staged) { 9557 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9558 cid = origin.cid; 9559 setMountPath(PackageHelper.getSdDir(cid)); 9560 return PackageManager.INSTALL_SUCCEEDED; 9561 } 9562 9563 if (temp) { 9564 createCopyFile(); 9565 } else { 9566 /* 9567 * Pre-emptively destroy the container since it's destroyed if 9568 * copying fails due to it existing anyway. 9569 */ 9570 PackageHelper.destroySdDir(cid); 9571 } 9572 9573 final String newMountPath = imcs.copyPackageToContainer( 9574 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9575 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9576 9577 if (newMountPath != null) { 9578 setMountPath(newMountPath); 9579 return PackageManager.INSTALL_SUCCEEDED; 9580 } else { 9581 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9582 } 9583 } 9584 9585 @Override 9586 String getCodePath() { 9587 return packagePath; 9588 } 9589 9590 @Override 9591 String getResourcePath() { 9592 return resourcePath; 9593 } 9594 9595 @Override 9596 String getLegacyNativeLibraryPath() { 9597 return legacyNativeLibraryDir; 9598 } 9599 9600 int doPreInstall(int status) { 9601 if (status != PackageManager.INSTALL_SUCCEEDED) { 9602 // Destroy container 9603 PackageHelper.destroySdDir(cid); 9604 } else { 9605 boolean mounted = PackageHelper.isContainerMounted(cid); 9606 if (!mounted) { 9607 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9608 Process.SYSTEM_UID); 9609 if (newMountPath != null) { 9610 setMountPath(newMountPath); 9611 } else { 9612 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9613 } 9614 } 9615 } 9616 return status; 9617 } 9618 9619 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9620 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9621 String newMountPath = null; 9622 if (PackageHelper.isContainerMounted(cid)) { 9623 // Unmount the container 9624 if (!PackageHelper.unMountSdDir(cid)) { 9625 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9626 return false; 9627 } 9628 } 9629 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9630 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9631 " which might be stale. Will try to clean up."); 9632 // Clean up the stale container and proceed to recreate. 9633 if (!PackageHelper.destroySdDir(newCacheId)) { 9634 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9635 return false; 9636 } 9637 // Successfully cleaned up stale container. Try to rename again. 9638 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9639 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9640 + " inspite of cleaning it up."); 9641 return false; 9642 } 9643 } 9644 if (!PackageHelper.isContainerMounted(newCacheId)) { 9645 Slog.w(TAG, "Mounting container " + newCacheId); 9646 newMountPath = PackageHelper.mountSdDir(newCacheId, 9647 getEncryptKey(), Process.SYSTEM_UID); 9648 } else { 9649 newMountPath = PackageHelper.getSdDir(newCacheId); 9650 } 9651 if (newMountPath == null) { 9652 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9653 return false; 9654 } 9655 Log.i(TAG, "Succesfully renamed " + cid + 9656 " to " + newCacheId + 9657 " at new path: " + newMountPath); 9658 cid = newCacheId; 9659 9660 final File beforeCodeFile = new File(packagePath); 9661 setMountPath(newMountPath); 9662 final File afterCodeFile = new File(packagePath); 9663 9664 // Reflect the rename in scanned details 9665 pkg.codePath = afterCodeFile.getAbsolutePath(); 9666 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9667 pkg.baseCodePath); 9668 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9669 pkg.splitCodePaths); 9670 9671 // Reflect the rename in app info 9672 pkg.applicationInfo.setCodePath(pkg.codePath); 9673 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9674 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9675 pkg.applicationInfo.setResourcePath(pkg.codePath); 9676 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9677 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9678 9679 return true; 9680 } 9681 9682 private void setMountPath(String mountPath) { 9683 final File mountFile = new File(mountPath); 9684 9685 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9686 if (monolithicFile.exists()) { 9687 packagePath = monolithicFile.getAbsolutePath(); 9688 if (isFwdLocked()) { 9689 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9690 } else { 9691 resourcePath = packagePath; 9692 } 9693 } else { 9694 packagePath = mountFile.getAbsolutePath(); 9695 resourcePath = packagePath; 9696 } 9697 9698 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9699 } 9700 9701 int doPostInstall(int status, int uid) { 9702 if (status != PackageManager.INSTALL_SUCCEEDED) { 9703 cleanUp(); 9704 } else { 9705 final int groupOwner; 9706 final String protectedFile; 9707 if (isFwdLocked()) { 9708 groupOwner = UserHandle.getSharedAppGid(uid); 9709 protectedFile = RES_FILE_NAME; 9710 } else { 9711 groupOwner = -1; 9712 protectedFile = null; 9713 } 9714 9715 if (uid < Process.FIRST_APPLICATION_UID 9716 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9717 Slog.e(TAG, "Failed to finalize " + cid); 9718 PackageHelper.destroySdDir(cid); 9719 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9720 } 9721 9722 boolean mounted = PackageHelper.isContainerMounted(cid); 9723 if (!mounted) { 9724 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9725 } 9726 } 9727 return status; 9728 } 9729 9730 private void cleanUp() { 9731 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9732 9733 // Destroy secure container 9734 PackageHelper.destroySdDir(cid); 9735 } 9736 9737 private List<String> getAllCodePaths() { 9738 final File codeFile = new File(getCodePath()); 9739 if (codeFile != null && codeFile.exists()) { 9740 try { 9741 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9742 return pkg.getAllCodePaths(); 9743 } catch (PackageParserException e) { 9744 // Ignored; we tried our best 9745 } 9746 } 9747 return Collections.EMPTY_LIST; 9748 } 9749 9750 void cleanUpResourcesLI() { 9751 // Enumerate all code paths before deleting 9752 cleanUpResourcesLI(getAllCodePaths()); 9753 } 9754 9755 private void cleanUpResourcesLI(List<String> allCodePaths) { 9756 cleanUp(); 9757 removeDexFiles(allCodePaths, instructionSets); 9758 } 9759 9760 9761 9762 String getPackageName() { 9763 return getAsecPackageName(cid); 9764 } 9765 9766 boolean doPostDeleteLI(boolean delete) { 9767 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9768 final List<String> allCodePaths = getAllCodePaths(); 9769 boolean mounted = PackageHelper.isContainerMounted(cid); 9770 if (mounted) { 9771 // Unmount first 9772 if (PackageHelper.unMountSdDir(cid)) { 9773 mounted = false; 9774 } 9775 } 9776 if (!mounted && delete) { 9777 cleanUpResourcesLI(allCodePaths); 9778 } 9779 return !mounted; 9780 } 9781 9782 @Override 9783 int doPreCopy() { 9784 if (isFwdLocked()) { 9785 if (!PackageHelper.fixSdPermissions(cid, 9786 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9787 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9788 } 9789 } 9790 9791 return PackageManager.INSTALL_SUCCEEDED; 9792 } 9793 9794 @Override 9795 int doPostCopy(int uid) { 9796 if (isFwdLocked()) { 9797 if (uid < Process.FIRST_APPLICATION_UID 9798 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9799 RES_FILE_NAME)) { 9800 Slog.e(TAG, "Failed to finalize " + cid); 9801 PackageHelper.destroySdDir(cid); 9802 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9803 } 9804 } 9805 9806 return PackageManager.INSTALL_SUCCEEDED; 9807 } 9808 } 9809 9810 static String getAsecPackageName(String packageCid) { 9811 int idx = packageCid.lastIndexOf("-"); 9812 if (idx == -1) { 9813 return packageCid; 9814 } 9815 return packageCid.substring(0, idx); 9816 } 9817 9818 // Utility method used to create code paths based on package name and available index. 9819 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9820 String idxStr = ""; 9821 int idx = 1; 9822 // Fall back to default value of idx=1 if prefix is not 9823 // part of oldCodePath 9824 if (oldCodePath != null) { 9825 String subStr = oldCodePath; 9826 // Drop the suffix right away 9827 if (suffix != null && subStr.endsWith(suffix)) { 9828 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9829 } 9830 // If oldCodePath already contains prefix find out the 9831 // ending index to either increment or decrement. 9832 int sidx = subStr.lastIndexOf(prefix); 9833 if (sidx != -1) { 9834 subStr = subStr.substring(sidx + prefix.length()); 9835 if (subStr != null) { 9836 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9837 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9838 } 9839 try { 9840 idx = Integer.parseInt(subStr); 9841 if (idx <= 1) { 9842 idx++; 9843 } else { 9844 idx--; 9845 } 9846 } catch(NumberFormatException e) { 9847 } 9848 } 9849 } 9850 } 9851 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9852 return prefix + idxStr; 9853 } 9854 9855 private File getNextCodePath(String packageName) { 9856 int suffix = 1; 9857 File result; 9858 do { 9859 result = new File(mAppInstallDir, packageName + "-" + suffix); 9860 suffix++; 9861 } while (result.exists()); 9862 return result; 9863 } 9864 9865 // Utility method that returns the relative package path with respect 9866 // to the installation directory. Like say for /data/data/com.test-1.apk 9867 // string com.test-1 is returned. 9868 static String deriveCodePathName(String codePath) { 9869 if (codePath == null) { 9870 return null; 9871 } 9872 final File codeFile = new File(codePath); 9873 final String name = codeFile.getName(); 9874 if (codeFile.isDirectory()) { 9875 return name; 9876 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9877 final int lastDot = name.lastIndexOf('.'); 9878 return name.substring(0, lastDot); 9879 } else { 9880 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9881 return null; 9882 } 9883 } 9884 9885 class PackageInstalledInfo { 9886 String name; 9887 int uid; 9888 // The set of users that originally had this package installed. 9889 int[] origUsers; 9890 // The set of users that now have this package installed. 9891 int[] newUsers; 9892 PackageParser.Package pkg; 9893 int returnCode; 9894 String returnMsg; 9895 PackageRemovedInfo removedInfo; 9896 9897 public void setError(int code, String msg) { 9898 returnCode = code; 9899 returnMsg = msg; 9900 Slog.w(TAG, msg); 9901 } 9902 9903 public void setError(String msg, PackageParserException e) { 9904 returnCode = e.error; 9905 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9906 Slog.w(TAG, msg, e); 9907 } 9908 9909 public void setError(String msg, PackageManagerException e) { 9910 returnCode = e.error; 9911 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9912 Slog.w(TAG, msg, e); 9913 } 9914 9915 // In some error cases we want to convey more info back to the observer 9916 String origPackage; 9917 String origPermission; 9918 } 9919 9920 /* 9921 * Install a non-existing package. 9922 */ 9923 private void installNewPackageLI(PackageParser.Package pkg, 9924 int parseFlags, int scanFlags, UserHandle user, 9925 String installerPackageName, PackageInstalledInfo res) { 9926 // Remember this for later, in case we need to rollback this install 9927 String pkgName = pkg.packageName; 9928 9929 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9930 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9931 synchronized(mPackages) { 9932 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9933 // A package with the same name is already installed, though 9934 // it has been renamed to an older name. The package we 9935 // are trying to install should be installed as an update to 9936 // the existing one, but that has not been requested, so bail. 9937 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9938 + " without first uninstalling package running as " 9939 + mSettings.mRenamedPackages.get(pkgName)); 9940 return; 9941 } 9942 if (mPackages.containsKey(pkgName)) { 9943 // Don't allow installation over an existing package with the same name. 9944 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9945 + " without first uninstalling."); 9946 return; 9947 } 9948 } 9949 9950 try { 9951 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9952 System.currentTimeMillis(), user); 9953 9954 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9955 // delete the partially installed application. the data directory will have to be 9956 // restored if it was already existing 9957 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9958 // remove package from internal structures. Note that we want deletePackageX to 9959 // delete the package data and cache directories that it created in 9960 // scanPackageLocked, unless those directories existed before we even tried to 9961 // install. 9962 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9963 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9964 res.removedInfo, true); 9965 } 9966 9967 } catch (PackageManagerException e) { 9968 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9969 } 9970 } 9971 9972 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9973 // Upgrade keysets are being used. Determine if new package has a superset of the 9974 // required keys. 9975 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9976 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9977 for (int i = 0; i < upgradeKeySets.length; i++) { 9978 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9979 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9980 return true; 9981 } 9982 } 9983 return false; 9984 } 9985 9986 private void replacePackageLI(PackageParser.Package pkg, 9987 int parseFlags, int scanFlags, UserHandle user, 9988 String installerPackageName, PackageInstalledInfo res) { 9989 PackageParser.Package oldPackage; 9990 String pkgName = pkg.packageName; 9991 int[] allUsers; 9992 boolean[] perUserInstalled; 9993 9994 // First find the old package info and check signatures 9995 synchronized(mPackages) { 9996 oldPackage = mPackages.get(pkgName); 9997 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9998 PackageSetting ps = mSettings.mPackages.get(pkgName); 9999 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10000 // default to original signature matching 10001 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10002 != PackageManager.SIGNATURE_MATCH) { 10003 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10004 "New package has a different signature: " + pkgName); 10005 return; 10006 } 10007 } else { 10008 if(!checkUpgradeKeySetLP(ps, pkg)) { 10009 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10010 "New package not signed by keys specified by upgrade-keysets: " 10011 + pkgName); 10012 return; 10013 } 10014 } 10015 10016 // In case of rollback, remember per-user/profile install state 10017 allUsers = sUserManager.getUserIds(); 10018 perUserInstalled = new boolean[allUsers.length]; 10019 for (int i = 0; i < allUsers.length; i++) { 10020 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10021 } 10022 } 10023 10024 boolean sysPkg = (isSystemApp(oldPackage)); 10025 if (sysPkg) { 10026 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10027 user, allUsers, perUserInstalled, installerPackageName, res); 10028 } else { 10029 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10030 user, allUsers, perUserInstalled, installerPackageName, res); 10031 } 10032 } 10033 10034 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10035 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10036 int[] allUsers, boolean[] perUserInstalled, 10037 String installerPackageName, PackageInstalledInfo res) { 10038 String pkgName = deletedPackage.packageName; 10039 boolean deletedPkg = true; 10040 boolean updatedSettings = false; 10041 10042 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10043 + deletedPackage); 10044 long origUpdateTime; 10045 if (pkg.mExtras != null) { 10046 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10047 } else { 10048 origUpdateTime = 0; 10049 } 10050 10051 // First delete the existing package while retaining the data directory 10052 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10053 res.removedInfo, true)) { 10054 // If the existing package wasn't successfully deleted 10055 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10056 deletedPkg = false; 10057 } else { 10058 // Successfully deleted the old package; proceed with replace. 10059 10060 // If deleted package lived in a container, give users a chance to 10061 // relinquish resources before killing. 10062 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10063 if (DEBUG_INSTALL) { 10064 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10065 } 10066 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10067 final ArrayList<String> pkgList = new ArrayList<String>(1); 10068 pkgList.add(deletedPackage.applicationInfo.packageName); 10069 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10070 } 10071 10072 deleteCodeCacheDirsLI(pkgName); 10073 try { 10074 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10075 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10076 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10077 updatedSettings = true; 10078 } catch (PackageManagerException e) { 10079 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10080 } 10081 } 10082 10083 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10084 // remove package from internal structures. Note that we want deletePackageX to 10085 // delete the package data and cache directories that it created in 10086 // scanPackageLocked, unless those directories existed before we even tried to 10087 // install. 10088 if(updatedSettings) { 10089 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10090 deletePackageLI( 10091 pkgName, null, true, allUsers, perUserInstalled, 10092 PackageManager.DELETE_KEEP_DATA, 10093 res.removedInfo, true); 10094 } 10095 // Since we failed to install the new package we need to restore the old 10096 // package that we deleted. 10097 if (deletedPkg) { 10098 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10099 File restoreFile = new File(deletedPackage.codePath); 10100 // Parse old package 10101 boolean oldOnSd = isExternal(deletedPackage); 10102 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10103 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10104 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10105 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10106 try { 10107 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10108 } catch (PackageManagerException e) { 10109 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10110 + e.getMessage()); 10111 return; 10112 } 10113 // Restore of old package succeeded. Update permissions. 10114 // writer 10115 synchronized (mPackages) { 10116 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10117 UPDATE_PERMISSIONS_ALL); 10118 // can downgrade to reader 10119 mSettings.writeLPr(); 10120 } 10121 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10122 } 10123 } 10124 } 10125 10126 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10127 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10128 int[] allUsers, boolean[] perUserInstalled, 10129 String installerPackageName, PackageInstalledInfo res) { 10130 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10131 + ", old=" + deletedPackage); 10132 boolean disabledSystem = false; 10133 boolean updatedSettings = false; 10134 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10135 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10136 != 0) { 10137 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10138 } 10139 String packageName = deletedPackage.packageName; 10140 if (packageName == null) { 10141 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10142 "Attempt to delete null packageName."); 10143 return; 10144 } 10145 PackageParser.Package oldPkg; 10146 PackageSetting oldPkgSetting; 10147 // reader 10148 synchronized (mPackages) { 10149 oldPkg = mPackages.get(packageName); 10150 oldPkgSetting = mSettings.mPackages.get(packageName); 10151 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10152 (oldPkgSetting == null)) { 10153 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10154 "Couldn't find package:" + packageName + " information"); 10155 return; 10156 } 10157 } 10158 10159 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10160 10161 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10162 res.removedInfo.removedPackage = packageName; 10163 // Remove existing system package 10164 removePackageLI(oldPkgSetting, true); 10165 // writer 10166 synchronized (mPackages) { 10167 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10168 if (!disabledSystem && deletedPackage != null) { 10169 // We didn't need to disable the .apk as a current system package, 10170 // which means we are replacing another update that is already 10171 // installed. We need to make sure to delete the older one's .apk. 10172 res.removedInfo.args = createInstallArgsForExisting(0, 10173 deletedPackage.applicationInfo.getCodePath(), 10174 deletedPackage.applicationInfo.getResourcePath(), 10175 deletedPackage.applicationInfo.nativeLibraryRootDir, 10176 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10177 } else { 10178 res.removedInfo.args = null; 10179 } 10180 } 10181 10182 // Successfully disabled the old package. Now proceed with re-installation 10183 deleteCodeCacheDirsLI(packageName); 10184 10185 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10186 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10187 10188 PackageParser.Package newPackage = null; 10189 try { 10190 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10191 if (newPackage.mExtras != null) { 10192 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10193 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10194 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10195 10196 // is the update attempting to change shared user? that isn't going to work... 10197 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10198 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10199 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10200 + " to " + newPkgSetting.sharedUser); 10201 updatedSettings = true; 10202 } 10203 } 10204 10205 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10206 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10207 updatedSettings = true; 10208 } 10209 10210 } catch (PackageManagerException e) { 10211 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10212 } 10213 10214 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10215 // Re installation failed. Restore old information 10216 // Remove new pkg information 10217 if (newPackage != null) { 10218 removeInstalledPackageLI(newPackage, true); 10219 } 10220 // Add back the old system package 10221 try { 10222 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10223 } catch (PackageManagerException e) { 10224 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10225 } 10226 // Restore the old system information in Settings 10227 synchronized (mPackages) { 10228 if (disabledSystem) { 10229 mSettings.enableSystemPackageLPw(packageName); 10230 } 10231 if (updatedSettings) { 10232 mSettings.setInstallerPackageName(packageName, 10233 oldPkgSetting.installerPackageName); 10234 } 10235 mSettings.writeLPr(); 10236 } 10237 } 10238 } 10239 10240 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10241 int[] allUsers, boolean[] perUserInstalled, 10242 PackageInstalledInfo res) { 10243 String pkgName = newPackage.packageName; 10244 synchronized (mPackages) { 10245 //write settings. the installStatus will be incomplete at this stage. 10246 //note that the new package setting would have already been 10247 //added to mPackages. It hasn't been persisted yet. 10248 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10249 mSettings.writeLPr(); 10250 } 10251 10252 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10253 10254 synchronized (mPackages) { 10255 updatePermissionsLPw(newPackage.packageName, newPackage, 10256 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10257 ? UPDATE_PERMISSIONS_ALL : 0)); 10258 // For system-bundled packages, we assume that installing an upgraded version 10259 // of the package implies that the user actually wants to run that new code, 10260 // so we enable the package. 10261 if (isSystemApp(newPackage)) { 10262 // NB: implicit assumption that system package upgrades apply to all users 10263 if (DEBUG_INSTALL) { 10264 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10265 } 10266 PackageSetting ps = mSettings.mPackages.get(pkgName); 10267 if (ps != null) { 10268 if (res.origUsers != null) { 10269 for (int userHandle : res.origUsers) { 10270 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10271 userHandle, installerPackageName); 10272 } 10273 } 10274 // Also convey the prior install/uninstall state 10275 if (allUsers != null && perUserInstalled != null) { 10276 for (int i = 0; i < allUsers.length; i++) { 10277 if (DEBUG_INSTALL) { 10278 Slog.d(TAG, " user " + allUsers[i] 10279 + " => " + perUserInstalled[i]); 10280 } 10281 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10282 } 10283 // these install state changes will be persisted in the 10284 // upcoming call to mSettings.writeLPr(). 10285 } 10286 } 10287 } 10288 res.name = pkgName; 10289 res.uid = newPackage.applicationInfo.uid; 10290 res.pkg = newPackage; 10291 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10292 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10293 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10294 //to update install status 10295 mSettings.writeLPr(); 10296 } 10297 } 10298 10299 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10300 final int installFlags = args.installFlags; 10301 String installerPackageName = args.installerPackageName; 10302 File tmpPackageFile = new File(args.getCodePath()); 10303 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10304 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10305 boolean replace = false; 10306 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10307 // Result object to be returned 10308 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10309 10310 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10311 // Retrieve PackageSettings and parse package 10312 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10313 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10314 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10315 PackageParser pp = new PackageParser(); 10316 pp.setSeparateProcesses(mSeparateProcesses); 10317 pp.setDisplayMetrics(mMetrics); 10318 10319 final PackageParser.Package pkg; 10320 try { 10321 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10322 } catch (PackageParserException e) { 10323 res.setError("Failed parse during installPackageLI", e); 10324 return; 10325 } 10326 10327 // Mark that we have an install time CPU ABI override. 10328 pkg.cpuAbiOverride = args.abiOverride; 10329 10330 String pkgName = res.name = pkg.packageName; 10331 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10332 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10333 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10334 return; 10335 } 10336 } 10337 10338 try { 10339 pp.collectCertificates(pkg, parseFlags); 10340 pp.collectManifestDigest(pkg); 10341 } catch (PackageParserException e) { 10342 res.setError("Failed collect during installPackageLI", e); 10343 return; 10344 } 10345 10346 /* If the installer passed in a manifest digest, compare it now. */ 10347 if (args.manifestDigest != null) { 10348 if (DEBUG_INSTALL) { 10349 final String parsedManifest = pkg.manifestDigest == null ? "null" 10350 : pkg.manifestDigest.toString(); 10351 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10352 + parsedManifest); 10353 } 10354 10355 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10356 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10357 return; 10358 } 10359 } else if (DEBUG_INSTALL) { 10360 final String parsedManifest = pkg.manifestDigest == null 10361 ? "null" : pkg.manifestDigest.toString(); 10362 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10363 } 10364 10365 // Get rid of all references to package scan path via parser. 10366 pp = null; 10367 String oldCodePath = null; 10368 boolean systemApp = false; 10369 synchronized (mPackages) { 10370 // Check if installing already existing package 10371 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10372 String oldName = mSettings.mRenamedPackages.get(pkgName); 10373 if (pkg.mOriginalPackages != null 10374 && pkg.mOriginalPackages.contains(oldName) 10375 && mPackages.containsKey(oldName)) { 10376 // This package is derived from an original package, 10377 // and this device has been updating from that original 10378 // name. We must continue using the original name, so 10379 // rename the new package here. 10380 pkg.setPackageName(oldName); 10381 pkgName = pkg.packageName; 10382 replace = true; 10383 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10384 + oldName + " pkgName=" + pkgName); 10385 } else if (mPackages.containsKey(pkgName)) { 10386 // This package, under its official name, already exists 10387 // on the device; we should replace it. 10388 replace = true; 10389 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10390 } 10391 } 10392 10393 PackageSetting ps = mSettings.mPackages.get(pkgName); 10394 if (ps != null) { 10395 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10396 10397 // Quick sanity check that we're signed correctly if updating; 10398 // we'll check this again later when scanning, but we want to 10399 // bail early here before tripping over redefined permissions. 10400 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10401 try { 10402 verifySignaturesLP(ps, pkg); 10403 } catch (PackageManagerException e) { 10404 res.setError(e.error, e.getMessage()); 10405 return; 10406 } 10407 } else { 10408 if (!checkUpgradeKeySetLP(ps, pkg)) { 10409 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 10410 + pkg.packageName + " upgrade keys do not match the " 10411 + "previously installed version"); 10412 return; 10413 } 10414 } 10415 10416 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10417 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10418 systemApp = (ps.pkg.applicationInfo.flags & 10419 ApplicationInfo.FLAG_SYSTEM) != 0; 10420 } 10421 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10422 } 10423 10424 // Check whether the newly-scanned package wants to define an already-defined perm 10425 int N = pkg.permissions.size(); 10426 for (int i = N-1; i >= 0; i--) { 10427 PackageParser.Permission perm = pkg.permissions.get(i); 10428 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10429 if (bp != null) { 10430 // If the defining package is signed with our cert, it's okay. This 10431 // also includes the "updating the same package" case, of course. 10432 // "updating same package" could also involve key-rotation. 10433 final boolean sigsOk; 10434 if (!bp.sourcePackage.equals(pkg.packageName) 10435 || !(bp.packageSetting instanceof PackageSetting) 10436 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10437 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10438 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10439 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10440 } else { 10441 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10442 } 10443 if (!sigsOk) { 10444 // If the owning package is the system itself, we log but allow 10445 // install to proceed; we fail the install on all other permission 10446 // redefinitions. 10447 if (!bp.sourcePackage.equals("android")) { 10448 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10449 + pkg.packageName + " attempting to redeclare permission " 10450 + perm.info.name + " already owned by " + bp.sourcePackage); 10451 res.origPermission = perm.info.name; 10452 res.origPackage = bp.sourcePackage; 10453 return; 10454 } else { 10455 Slog.w(TAG, "Package " + pkg.packageName 10456 + " attempting to redeclare system permission " 10457 + perm.info.name + "; ignoring new declaration"); 10458 pkg.permissions.remove(i); 10459 } 10460 } 10461 } 10462 } 10463 10464 } 10465 10466 if (systemApp && onSd) { 10467 // Disable updates to system apps on sdcard 10468 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10469 "Cannot install updates to system apps on sdcard"); 10470 return; 10471 } 10472 10473 // If app directory is not writable, dexopt will be called after the rename 10474 if (!forwardLocked && pkg.applicationInfo.isInternal()) { 10475 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 10476 scanFlags |= SCAN_NO_DEX; 10477 try { 10478 deriveNonSystemPackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 10479 true /* extract libs */); 10480 } catch (PackageManagerException pme) { 10481 Slog.e(TAG, "Error deriving application ABI", pme); 10482 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error "); 10483 return; 10484 } 10485 10486 // Run dexopt before old package gets removed, to minimize time when app is unavailable 10487 int result = mPackageDexOptimizer 10488 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 10489 false /* defer */, false /* inclDependencies */); 10490 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 10491 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 10492 return; 10493 } 10494 } 10495 10496 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10497 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10498 return; 10499 } 10500 10501 if (replace) { 10502 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10503 installerPackageName, res); 10504 } else { 10505 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10506 args.user, installerPackageName, res); 10507 } 10508 synchronized (mPackages) { 10509 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10510 if (ps != null) { 10511 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10512 } 10513 } 10514 } 10515 10516 private static boolean isMultiArch(PackageSetting ps) { 10517 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10518 } 10519 10520 private static boolean isMultiArch(ApplicationInfo info) { 10521 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10522 } 10523 10524 private static boolean isExternal(PackageParser.Package pkg) { 10525 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10526 } 10527 10528 private static boolean isExternal(PackageSetting ps) { 10529 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10530 } 10531 10532 private static boolean isExternal(ApplicationInfo info) { 10533 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10534 } 10535 10536 private static boolean isSystemApp(PackageParser.Package pkg) { 10537 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10538 } 10539 10540 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10541 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 10542 } 10543 10544 private static boolean isSystemApp(PackageSetting ps) { 10545 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10546 } 10547 10548 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10549 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10550 } 10551 10552 private int packageFlagsToInstallFlags(PackageSetting ps) { 10553 int installFlags = 0; 10554 if (isExternal(ps)) { 10555 installFlags |= PackageManager.INSTALL_EXTERNAL; 10556 } 10557 if (ps.isForwardLocked()) { 10558 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10559 } 10560 return installFlags; 10561 } 10562 10563 private void deleteTempPackageFiles() { 10564 final FilenameFilter filter = new FilenameFilter() { 10565 public boolean accept(File dir, String name) { 10566 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10567 } 10568 }; 10569 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10570 file.delete(); 10571 } 10572 } 10573 10574 @Override 10575 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10576 int flags) { 10577 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10578 flags); 10579 } 10580 10581 @Override 10582 public void deletePackage(final String packageName, 10583 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10584 mContext.enforceCallingOrSelfPermission( 10585 android.Manifest.permission.DELETE_PACKAGES, null); 10586 final int uid = Binder.getCallingUid(); 10587 if (UserHandle.getUserId(uid) != userId) { 10588 mContext.enforceCallingPermission( 10589 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10590 "deletePackage for user " + userId); 10591 } 10592 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10593 try { 10594 observer.onPackageDeleted(packageName, 10595 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10596 } catch (RemoteException re) { 10597 } 10598 return; 10599 } 10600 10601 boolean uninstallBlocked = false; 10602 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10603 int[] users = sUserManager.getUserIds(); 10604 for (int i = 0; i < users.length; ++i) { 10605 if (getBlockUninstallForUser(packageName, users[i])) { 10606 uninstallBlocked = true; 10607 break; 10608 } 10609 } 10610 } else { 10611 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10612 } 10613 if (uninstallBlocked) { 10614 try { 10615 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10616 null); 10617 } catch (RemoteException re) { 10618 } 10619 return; 10620 } 10621 10622 if (DEBUG_REMOVE) { 10623 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10624 } 10625 // Queue up an async operation since the package deletion may take a little while. 10626 mHandler.post(new Runnable() { 10627 public void run() { 10628 mHandler.removeCallbacks(this); 10629 final int returnCode = deletePackageX(packageName, userId, flags); 10630 if (observer != null) { 10631 try { 10632 observer.onPackageDeleted(packageName, returnCode, null); 10633 } catch (RemoteException e) { 10634 Log.i(TAG, "Observer no longer exists."); 10635 } //end catch 10636 } //end if 10637 } //end run 10638 }); 10639 } 10640 10641 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10642 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10643 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10644 try { 10645 if (dpm != null) { 10646 if (dpm.isDeviceOwner(packageName)) { 10647 return true; 10648 } 10649 int[] users; 10650 if (userId == UserHandle.USER_ALL) { 10651 users = sUserManager.getUserIds(); 10652 } else { 10653 users = new int[]{userId}; 10654 } 10655 for (int i = 0; i < users.length; ++i) { 10656 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10657 return true; 10658 } 10659 } 10660 } 10661 } catch (RemoteException e) { 10662 } 10663 return false; 10664 } 10665 10666 /** 10667 * This method is an internal method that could be get invoked either 10668 * to delete an installed package or to clean up a failed installation. 10669 * After deleting an installed package, a broadcast is sent to notify any 10670 * listeners that the package has been installed. For cleaning up a failed 10671 * installation, the broadcast is not necessary since the package's 10672 * installation wouldn't have sent the initial broadcast either 10673 * The key steps in deleting a package are 10674 * deleting the package information in internal structures like mPackages, 10675 * deleting the packages base directories through installd 10676 * updating mSettings to reflect current status 10677 * persisting settings for later use 10678 * sending a broadcast if necessary 10679 */ 10680 private int deletePackageX(String packageName, int userId, int flags) { 10681 final PackageRemovedInfo info = new PackageRemovedInfo(); 10682 final boolean res; 10683 10684 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10685 ? UserHandle.ALL : new UserHandle(userId); 10686 10687 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10688 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10689 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10690 } 10691 10692 boolean removedForAllUsers = false; 10693 boolean systemUpdate = false; 10694 10695 // for the uninstall-updates case and restricted profiles, remember the per- 10696 // userhandle installed state 10697 int[] allUsers; 10698 boolean[] perUserInstalled; 10699 synchronized (mPackages) { 10700 PackageSetting ps = mSettings.mPackages.get(packageName); 10701 allUsers = sUserManager.getUserIds(); 10702 perUserInstalled = new boolean[allUsers.length]; 10703 for (int i = 0; i < allUsers.length; i++) { 10704 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10705 } 10706 } 10707 10708 synchronized (mInstallLock) { 10709 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10710 res = deletePackageLI(packageName, removeForUser, 10711 true, allUsers, perUserInstalled, 10712 flags | REMOVE_CHATTY, info, true); 10713 systemUpdate = info.isRemovedPackageSystemUpdate; 10714 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10715 removedForAllUsers = true; 10716 } 10717 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10718 + " removedForAllUsers=" + removedForAllUsers); 10719 } 10720 10721 if (res) { 10722 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10723 10724 // If the removed package was a system update, the old system package 10725 // was re-enabled; we need to broadcast this information 10726 if (systemUpdate) { 10727 Bundle extras = new Bundle(1); 10728 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10729 ? info.removedAppId : info.uid); 10730 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10731 10732 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10733 extras, null, null, null); 10734 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10735 extras, null, null, null); 10736 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10737 null, packageName, null, null); 10738 } 10739 } 10740 // Force a gc here. 10741 Runtime.getRuntime().gc(); 10742 // Delete the resources here after sending the broadcast to let 10743 // other processes clean up before deleting resources. 10744 if (info.args != null) { 10745 synchronized (mInstallLock) { 10746 info.args.doPostDeleteLI(true); 10747 } 10748 } 10749 10750 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10751 } 10752 10753 static class PackageRemovedInfo { 10754 String removedPackage; 10755 int uid = -1; 10756 int removedAppId = -1; 10757 int[] removedUsers = null; 10758 boolean isRemovedPackageSystemUpdate = false; 10759 // Clean up resources deleted packages. 10760 InstallArgs args = null; 10761 10762 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10763 Bundle extras = new Bundle(1); 10764 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10765 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10766 if (replacing) { 10767 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10768 } 10769 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10770 if (removedPackage != null) { 10771 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10772 extras, null, null, removedUsers); 10773 if (fullRemove && !replacing) { 10774 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10775 extras, null, null, removedUsers); 10776 } 10777 } 10778 if (removedAppId >= 0) { 10779 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10780 removedUsers); 10781 } 10782 } 10783 } 10784 10785 /* 10786 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10787 * flag is not set, the data directory is removed as well. 10788 * make sure this flag is set for partially installed apps. If not its meaningless to 10789 * delete a partially installed application. 10790 */ 10791 private void removePackageDataLI(PackageSetting ps, 10792 int[] allUserHandles, boolean[] perUserInstalled, 10793 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10794 String packageName = ps.name; 10795 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10796 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10797 // Retrieve object to delete permissions for shared user later on 10798 final PackageSetting deletedPs; 10799 // reader 10800 synchronized (mPackages) { 10801 deletedPs = mSettings.mPackages.get(packageName); 10802 if (outInfo != null) { 10803 outInfo.removedPackage = packageName; 10804 outInfo.removedUsers = deletedPs != null 10805 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10806 : null; 10807 } 10808 } 10809 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10810 removeDataDirsLI(packageName); 10811 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10812 } 10813 // writer 10814 synchronized (mPackages) { 10815 if (deletedPs != null) { 10816 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10817 if (outInfo != null) { 10818 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10819 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10820 } 10821 if (deletedPs != null) { 10822 updatePermissionsLPw(deletedPs.name, null, 0); 10823 if (deletedPs.sharedUser != null) { 10824 // remove permissions associated with package 10825 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10826 } 10827 } 10828 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10829 } 10830 // make sure to preserve per-user disabled state if this removal was just 10831 // a downgrade of a system app to the factory package 10832 if (allUserHandles != null && perUserInstalled != null) { 10833 if (DEBUG_REMOVE) { 10834 Slog.d(TAG, "Propagating install state across downgrade"); 10835 } 10836 for (int i = 0; i < allUserHandles.length; i++) { 10837 if (DEBUG_REMOVE) { 10838 Slog.d(TAG, " user " + allUserHandles[i] 10839 + " => " + perUserInstalled[i]); 10840 } 10841 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10842 } 10843 } 10844 } 10845 // can downgrade to reader 10846 if (writeSettings) { 10847 // Save settings now 10848 mSettings.writeLPr(); 10849 } 10850 } 10851 if (outInfo != null) { 10852 // A user ID was deleted here. Go through all users and remove it 10853 // from KeyStore. 10854 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10855 } 10856 } 10857 10858 static boolean locationIsPrivileged(File path) { 10859 try { 10860 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10861 .getCanonicalPath(); 10862 return path.getCanonicalPath().startsWith(privilegedAppDir); 10863 } catch (IOException e) { 10864 Slog.e(TAG, "Unable to access code path " + path); 10865 } 10866 return false; 10867 } 10868 10869 /* 10870 * Tries to delete system package. 10871 */ 10872 private boolean deleteSystemPackageLI(PackageSetting newPs, 10873 int[] allUserHandles, boolean[] perUserInstalled, 10874 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10875 final boolean applyUserRestrictions 10876 = (allUserHandles != null) && (perUserInstalled != null); 10877 PackageSetting disabledPs = null; 10878 // Confirm if the system package has been updated 10879 // An updated system app can be deleted. This will also have to restore 10880 // the system pkg from system partition 10881 // reader 10882 synchronized (mPackages) { 10883 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10884 } 10885 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10886 + " disabledPs=" + disabledPs); 10887 if (disabledPs == null) { 10888 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10889 return false; 10890 } else if (DEBUG_REMOVE) { 10891 Slog.d(TAG, "Deleting system pkg from data partition"); 10892 } 10893 if (DEBUG_REMOVE) { 10894 if (applyUserRestrictions) { 10895 Slog.d(TAG, "Remembering install states:"); 10896 for (int i = 0; i < allUserHandles.length; i++) { 10897 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10898 } 10899 } 10900 } 10901 // Delete the updated package 10902 outInfo.isRemovedPackageSystemUpdate = true; 10903 if (disabledPs.versionCode < newPs.versionCode) { 10904 // Delete data for downgrades 10905 flags &= ~PackageManager.DELETE_KEEP_DATA; 10906 } else { 10907 // Preserve data by setting flag 10908 flags |= PackageManager.DELETE_KEEP_DATA; 10909 } 10910 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10911 allUserHandles, perUserInstalled, outInfo, writeSettings); 10912 if (!ret) { 10913 return false; 10914 } 10915 // writer 10916 synchronized (mPackages) { 10917 // Reinstate the old system package 10918 mSettings.enableSystemPackageLPw(newPs.name); 10919 // Remove any native libraries from the upgraded package. 10920 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10921 } 10922 // Install the system package 10923 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10924 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10925 if (locationIsPrivileged(disabledPs.codePath)) { 10926 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10927 } 10928 10929 final PackageParser.Package newPkg; 10930 try { 10931 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10932 } catch (PackageManagerException e) { 10933 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10934 return false; 10935 } 10936 10937 // writer 10938 synchronized (mPackages) { 10939 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10940 updatePermissionsLPw(newPkg.packageName, newPkg, 10941 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10942 if (applyUserRestrictions) { 10943 if (DEBUG_REMOVE) { 10944 Slog.d(TAG, "Propagating install state across reinstall"); 10945 } 10946 for (int i = 0; i < allUserHandles.length; i++) { 10947 if (DEBUG_REMOVE) { 10948 Slog.d(TAG, " user " + allUserHandles[i] 10949 + " => " + perUserInstalled[i]); 10950 } 10951 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10952 } 10953 // Regardless of writeSettings we need to ensure that this restriction 10954 // state propagation is persisted 10955 mSettings.writeAllUsersPackageRestrictionsLPr(); 10956 } 10957 // can downgrade to reader here 10958 if (writeSettings) { 10959 mSettings.writeLPr(); 10960 } 10961 } 10962 return true; 10963 } 10964 10965 private boolean deleteInstalledPackageLI(PackageSetting ps, 10966 boolean deleteCodeAndResources, int flags, 10967 int[] allUserHandles, boolean[] perUserInstalled, 10968 PackageRemovedInfo outInfo, boolean writeSettings) { 10969 if (outInfo != null) { 10970 outInfo.uid = ps.appId; 10971 } 10972 10973 // Delete package data from internal structures and also remove data if flag is set 10974 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10975 10976 // Delete application code and resources 10977 if (deleteCodeAndResources && (outInfo != null)) { 10978 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10979 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10980 getAppDexInstructionSets(ps)); 10981 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10982 } 10983 return true; 10984 } 10985 10986 @Override 10987 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10988 int userId) { 10989 mContext.enforceCallingOrSelfPermission( 10990 android.Manifest.permission.DELETE_PACKAGES, null); 10991 synchronized (mPackages) { 10992 PackageSetting ps = mSettings.mPackages.get(packageName); 10993 if (ps == null) { 10994 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10995 return false; 10996 } 10997 if (!ps.getInstalled(userId)) { 10998 // Can't block uninstall for an app that is not installed or enabled. 10999 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11000 return false; 11001 } 11002 ps.setBlockUninstall(blockUninstall, userId); 11003 mSettings.writePackageRestrictionsLPr(userId); 11004 } 11005 return true; 11006 } 11007 11008 @Override 11009 public boolean getBlockUninstallForUser(String packageName, int userId) { 11010 synchronized (mPackages) { 11011 PackageSetting ps = mSettings.mPackages.get(packageName); 11012 if (ps == null) { 11013 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11014 return false; 11015 } 11016 return ps.getBlockUninstall(userId); 11017 } 11018 } 11019 11020 /* 11021 * This method handles package deletion in general 11022 */ 11023 private boolean deletePackageLI(String packageName, UserHandle user, 11024 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11025 int flags, PackageRemovedInfo outInfo, 11026 boolean writeSettings) { 11027 if (packageName == null) { 11028 Slog.w(TAG, "Attempt to delete null packageName."); 11029 return false; 11030 } 11031 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11032 PackageSetting ps; 11033 boolean dataOnly = false; 11034 int removeUser = -1; 11035 int appId = -1; 11036 synchronized (mPackages) { 11037 ps = mSettings.mPackages.get(packageName); 11038 if (ps == null) { 11039 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11040 return false; 11041 } 11042 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11043 && user.getIdentifier() != UserHandle.USER_ALL) { 11044 // The caller is asking that the package only be deleted for a single 11045 // user. To do this, we just mark its uninstalled state and delete 11046 // its data. If this is a system app, we only allow this to happen if 11047 // they have set the special DELETE_SYSTEM_APP which requests different 11048 // semantics than normal for uninstalling system apps. 11049 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11050 ps.setUserState(user.getIdentifier(), 11051 COMPONENT_ENABLED_STATE_DEFAULT, 11052 false, //installed 11053 true, //stopped 11054 true, //notLaunched 11055 false, //hidden 11056 null, null, null, 11057 false // blockUninstall 11058 ); 11059 if (!isSystemApp(ps)) { 11060 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11061 // Other user still have this package installed, so all 11062 // we need to do is clear this user's data and save that 11063 // it is uninstalled. 11064 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11065 removeUser = user.getIdentifier(); 11066 appId = ps.appId; 11067 mSettings.writePackageRestrictionsLPr(removeUser); 11068 } else { 11069 // We need to set it back to 'installed' so the uninstall 11070 // broadcasts will be sent correctly. 11071 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11072 ps.setInstalled(true, user.getIdentifier()); 11073 } 11074 } else { 11075 // This is a system app, so we assume that the 11076 // other users still have this package installed, so all 11077 // we need to do is clear this user's data and save that 11078 // it is uninstalled. 11079 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11080 removeUser = user.getIdentifier(); 11081 appId = ps.appId; 11082 mSettings.writePackageRestrictionsLPr(removeUser); 11083 } 11084 } 11085 } 11086 11087 if (removeUser >= 0) { 11088 // From above, we determined that we are deleting this only 11089 // for a single user. Continue the work here. 11090 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11091 if (outInfo != null) { 11092 outInfo.removedPackage = packageName; 11093 outInfo.removedAppId = appId; 11094 outInfo.removedUsers = new int[] {removeUser}; 11095 } 11096 mInstaller.clearUserData(packageName, removeUser); 11097 removeKeystoreDataIfNeeded(removeUser, appId); 11098 schedulePackageCleaning(packageName, removeUser, false); 11099 return true; 11100 } 11101 11102 if (dataOnly) { 11103 // Delete application data first 11104 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11105 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11106 return true; 11107 } 11108 11109 boolean ret = false; 11110 if (isSystemApp(ps)) { 11111 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11112 // When an updated system application is deleted we delete the existing resources as well and 11113 // fall back to existing code in system partition 11114 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11115 flags, outInfo, writeSettings); 11116 } else { 11117 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11118 // Kill application pre-emptively especially for apps on sd. 11119 killApplication(packageName, ps.appId, "uninstall pkg"); 11120 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11121 allUserHandles, perUserInstalled, 11122 outInfo, writeSettings); 11123 } 11124 11125 return ret; 11126 } 11127 11128 private final class ClearStorageConnection implements ServiceConnection { 11129 IMediaContainerService mContainerService; 11130 11131 @Override 11132 public void onServiceConnected(ComponentName name, IBinder service) { 11133 synchronized (this) { 11134 mContainerService = IMediaContainerService.Stub.asInterface(service); 11135 notifyAll(); 11136 } 11137 } 11138 11139 @Override 11140 public void onServiceDisconnected(ComponentName name) { 11141 } 11142 } 11143 11144 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11145 final boolean mounted; 11146 if (Environment.isExternalStorageEmulated()) { 11147 mounted = true; 11148 } else { 11149 final String status = Environment.getExternalStorageState(); 11150 11151 mounted = status.equals(Environment.MEDIA_MOUNTED) 11152 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11153 } 11154 11155 if (!mounted) { 11156 return; 11157 } 11158 11159 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11160 int[] users; 11161 if (userId == UserHandle.USER_ALL) { 11162 users = sUserManager.getUserIds(); 11163 } else { 11164 users = new int[] { userId }; 11165 } 11166 final ClearStorageConnection conn = new ClearStorageConnection(); 11167 if (mContext.bindServiceAsUser( 11168 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11169 try { 11170 for (int curUser : users) { 11171 long timeout = SystemClock.uptimeMillis() + 5000; 11172 synchronized (conn) { 11173 long now = SystemClock.uptimeMillis(); 11174 while (conn.mContainerService == null && now < timeout) { 11175 try { 11176 conn.wait(timeout - now); 11177 } catch (InterruptedException e) { 11178 } 11179 } 11180 } 11181 if (conn.mContainerService == null) { 11182 return; 11183 } 11184 11185 final UserEnvironment userEnv = new UserEnvironment(curUser); 11186 clearDirectory(conn.mContainerService, 11187 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11188 if (allData) { 11189 clearDirectory(conn.mContainerService, 11190 userEnv.buildExternalStorageAppDataDirs(packageName)); 11191 clearDirectory(conn.mContainerService, 11192 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11193 } 11194 } 11195 } finally { 11196 mContext.unbindService(conn); 11197 } 11198 } 11199 } 11200 11201 @Override 11202 public void clearApplicationUserData(final String packageName, 11203 final IPackageDataObserver observer, final int userId) { 11204 mContext.enforceCallingOrSelfPermission( 11205 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11206 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11207 // Queue up an async operation since the package deletion may take a little while. 11208 mHandler.post(new Runnable() { 11209 public void run() { 11210 mHandler.removeCallbacks(this); 11211 final boolean succeeded; 11212 synchronized (mInstallLock) { 11213 succeeded = clearApplicationUserDataLI(packageName, userId); 11214 } 11215 clearExternalStorageDataSync(packageName, userId, true); 11216 if (succeeded) { 11217 // invoke DeviceStorageMonitor's update method to clear any notifications 11218 DeviceStorageMonitorInternal 11219 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11220 if (dsm != null) { 11221 dsm.checkMemory(); 11222 } 11223 } 11224 if(observer != null) { 11225 try { 11226 observer.onRemoveCompleted(packageName, succeeded); 11227 } catch (RemoteException e) { 11228 Log.i(TAG, "Observer no longer exists."); 11229 } 11230 } //end if observer 11231 } //end run 11232 }); 11233 } 11234 11235 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11236 if (packageName == null) { 11237 Slog.w(TAG, "Attempt to delete null packageName."); 11238 return false; 11239 } 11240 11241 // Try finding details about the requested package 11242 PackageParser.Package pkg; 11243 synchronized (mPackages) { 11244 pkg = mPackages.get(packageName); 11245 if (pkg == null) { 11246 final PackageSetting ps = mSettings.mPackages.get(packageName); 11247 if (ps != null) { 11248 pkg = ps.pkg; 11249 } 11250 } 11251 } 11252 11253 if (pkg == null) { 11254 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11255 } 11256 11257 // Always delete data directories for package, even if we found no other 11258 // record of app. This helps users recover from UID mismatches without 11259 // resorting to a full data wipe. 11260 int retCode = mInstaller.clearUserData(packageName, userId); 11261 if (retCode < 0) { 11262 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11263 return false; 11264 } 11265 11266 if (pkg == null) { 11267 return false; 11268 } 11269 11270 if (pkg != null && pkg.applicationInfo != null) { 11271 final int appId = pkg.applicationInfo.uid; 11272 removeKeystoreDataIfNeeded(userId, appId); 11273 } 11274 11275 // Create a native library symlink only if we have native libraries 11276 // and if the native libraries are 32 bit libraries. We do not provide 11277 // this symlink for 64 bit libraries. 11278 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11279 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11280 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11281 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11282 Slog.w(TAG, "Failed linking native library dir"); 11283 return false; 11284 } 11285 } 11286 11287 return true; 11288 } 11289 11290 /** 11291 * Remove entries from the keystore daemon. Will only remove it if the 11292 * {@code appId} is valid. 11293 */ 11294 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11295 if (appId < 0) { 11296 return; 11297 } 11298 11299 final KeyStore keyStore = KeyStore.getInstance(); 11300 if (keyStore != null) { 11301 if (userId == UserHandle.USER_ALL) { 11302 for (final int individual : sUserManager.getUserIds()) { 11303 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11304 } 11305 } else { 11306 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11307 } 11308 } else { 11309 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11310 } 11311 } 11312 11313 @Override 11314 public void deleteApplicationCacheFiles(final String packageName, 11315 final IPackageDataObserver observer) { 11316 mContext.enforceCallingOrSelfPermission( 11317 android.Manifest.permission.DELETE_CACHE_FILES, null); 11318 // Queue up an async operation since the package deletion may take a little while. 11319 final int userId = UserHandle.getCallingUserId(); 11320 mHandler.post(new Runnable() { 11321 public void run() { 11322 mHandler.removeCallbacks(this); 11323 final boolean succeded; 11324 synchronized (mInstallLock) { 11325 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11326 } 11327 clearExternalStorageDataSync(packageName, userId, false); 11328 if(observer != null) { 11329 try { 11330 observer.onRemoveCompleted(packageName, succeded); 11331 } catch (RemoteException e) { 11332 Log.i(TAG, "Observer no longer exists."); 11333 } 11334 } //end if observer 11335 } //end run 11336 }); 11337 } 11338 11339 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11340 if (packageName == null) { 11341 Slog.w(TAG, "Attempt to delete null packageName."); 11342 return false; 11343 } 11344 PackageParser.Package p; 11345 synchronized (mPackages) { 11346 p = mPackages.get(packageName); 11347 } 11348 if (p == null) { 11349 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11350 return false; 11351 } 11352 final ApplicationInfo applicationInfo = p.applicationInfo; 11353 if (applicationInfo == null) { 11354 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11355 return false; 11356 } 11357 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11358 if (retCode < 0) { 11359 Slog.w(TAG, "Couldn't remove cache files for package: " 11360 + packageName + " u" + userId); 11361 return false; 11362 } 11363 return true; 11364 } 11365 11366 @Override 11367 public void getPackageSizeInfo(final String packageName, int userHandle, 11368 final IPackageStatsObserver observer) { 11369 mContext.enforceCallingOrSelfPermission( 11370 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11371 if (packageName == null) { 11372 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11373 } 11374 11375 PackageStats stats = new PackageStats(packageName, userHandle); 11376 11377 /* 11378 * Queue up an async operation since the package measurement may take a 11379 * little while. 11380 */ 11381 Message msg = mHandler.obtainMessage(INIT_COPY); 11382 msg.obj = new MeasureParams(stats, observer); 11383 mHandler.sendMessage(msg); 11384 } 11385 11386 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11387 PackageStats pStats) { 11388 if (packageName == null) { 11389 Slog.w(TAG, "Attempt to get size of null packageName."); 11390 return false; 11391 } 11392 PackageParser.Package p; 11393 boolean dataOnly = false; 11394 String libDirRoot = null; 11395 String asecPath = null; 11396 PackageSetting ps = null; 11397 synchronized (mPackages) { 11398 p = mPackages.get(packageName); 11399 ps = mSettings.mPackages.get(packageName); 11400 if(p == null) { 11401 dataOnly = true; 11402 if((ps == null) || (ps.pkg == null)) { 11403 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11404 return false; 11405 } 11406 p = ps.pkg; 11407 } 11408 if (ps != null) { 11409 libDirRoot = ps.legacyNativeLibraryPathString; 11410 } 11411 if (p != null && (isExternal(p) || p.isForwardLocked())) { 11412 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11413 if (secureContainerId != null) { 11414 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11415 } 11416 } 11417 } 11418 String publicSrcDir = null; 11419 if(!dataOnly) { 11420 final ApplicationInfo applicationInfo = p.applicationInfo; 11421 if (applicationInfo == null) { 11422 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11423 return false; 11424 } 11425 if (p.isForwardLocked()) { 11426 publicSrcDir = applicationInfo.getBaseResourcePath(); 11427 } 11428 } 11429 // TODO: extend to measure size of split APKs 11430 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11431 // not just the first level. 11432 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11433 // just the primary. 11434 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11435 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11436 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11437 if (res < 0) { 11438 return false; 11439 } 11440 11441 // Fix-up for forward-locked applications in ASEC containers. 11442 if (!isExternal(p)) { 11443 pStats.codeSize += pStats.externalCodeSize; 11444 pStats.externalCodeSize = 0L; 11445 } 11446 11447 return true; 11448 } 11449 11450 11451 @Override 11452 public void addPackageToPreferred(String packageName) { 11453 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11454 } 11455 11456 @Override 11457 public void removePackageFromPreferred(String packageName) { 11458 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11459 } 11460 11461 @Override 11462 public List<PackageInfo> getPreferredPackages(int flags) { 11463 return new ArrayList<PackageInfo>(); 11464 } 11465 11466 private int getUidTargetSdkVersionLockedLPr(int uid) { 11467 Object obj = mSettings.getUserIdLPr(uid); 11468 if (obj instanceof SharedUserSetting) { 11469 final SharedUserSetting sus = (SharedUserSetting) obj; 11470 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11471 final Iterator<PackageSetting> it = sus.packages.iterator(); 11472 while (it.hasNext()) { 11473 final PackageSetting ps = it.next(); 11474 if (ps.pkg != null) { 11475 int v = ps.pkg.applicationInfo.targetSdkVersion; 11476 if (v < vers) vers = v; 11477 } 11478 } 11479 return vers; 11480 } else if (obj instanceof PackageSetting) { 11481 final PackageSetting ps = (PackageSetting) obj; 11482 if (ps.pkg != null) { 11483 return ps.pkg.applicationInfo.targetSdkVersion; 11484 } 11485 } 11486 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11487 } 11488 11489 @Override 11490 public void addPreferredActivity(IntentFilter filter, int match, 11491 ComponentName[] set, ComponentName activity, int userId) { 11492 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11493 "Adding preferred"); 11494 } 11495 11496 private void addPreferredActivityInternal(IntentFilter filter, int match, 11497 ComponentName[] set, ComponentName activity, boolean always, int userId, 11498 String opname) { 11499 // writer 11500 int callingUid = Binder.getCallingUid(); 11501 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11502 if (filter.countActions() == 0) { 11503 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11504 return; 11505 } 11506 synchronized (mPackages) { 11507 if (mContext.checkCallingOrSelfPermission( 11508 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11509 != PackageManager.PERMISSION_GRANTED) { 11510 if (getUidTargetSdkVersionLockedLPr(callingUid) 11511 < Build.VERSION_CODES.FROYO) { 11512 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11513 + callingUid); 11514 return; 11515 } 11516 mContext.enforceCallingOrSelfPermission( 11517 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11518 } 11519 11520 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11521 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11522 + userId + ":"); 11523 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11524 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11525 scheduleWritePackageRestrictionsLocked(userId); 11526 } 11527 } 11528 11529 @Override 11530 public void replacePreferredActivity(IntentFilter filter, int match, 11531 ComponentName[] set, ComponentName activity, int userId) { 11532 if (filter.countActions() != 1) { 11533 throw new IllegalArgumentException( 11534 "replacePreferredActivity expects filter to have only 1 action."); 11535 } 11536 if (filter.countDataAuthorities() != 0 11537 || filter.countDataPaths() != 0 11538 || filter.countDataSchemes() > 1 11539 || filter.countDataTypes() != 0) { 11540 throw new IllegalArgumentException( 11541 "replacePreferredActivity expects filter to have no data authorities, " + 11542 "paths, or types; and at most one scheme."); 11543 } 11544 11545 final int callingUid = Binder.getCallingUid(); 11546 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11547 synchronized (mPackages) { 11548 if (mContext.checkCallingOrSelfPermission( 11549 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11550 != PackageManager.PERMISSION_GRANTED) { 11551 if (getUidTargetSdkVersionLockedLPr(callingUid) 11552 < Build.VERSION_CODES.FROYO) { 11553 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11554 + Binder.getCallingUid()); 11555 return; 11556 } 11557 mContext.enforceCallingOrSelfPermission( 11558 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11559 } 11560 11561 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11562 if (pir != null) { 11563 // Get all of the existing entries that exactly match this filter. 11564 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11565 if (existing != null && existing.size() == 1) { 11566 PreferredActivity cur = existing.get(0); 11567 if (DEBUG_PREFERRED) { 11568 Slog.i(TAG, "Checking replace of preferred:"); 11569 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11570 if (!cur.mPref.mAlways) { 11571 Slog.i(TAG, " -- CUR; not mAlways!"); 11572 } else { 11573 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11574 Slog.i(TAG, " -- CUR: mSet=" 11575 + Arrays.toString(cur.mPref.mSetComponents)); 11576 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11577 Slog.i(TAG, " -- NEW: mMatch=" 11578 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11579 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11580 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11581 } 11582 } 11583 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11584 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11585 && cur.mPref.sameSet(set)) { 11586 // Setting the preferred activity to what it happens to be already 11587 if (DEBUG_PREFERRED) { 11588 Slog.i(TAG, "Replacing with same preferred activity " 11589 + cur.mPref.mShortComponent + " for user " 11590 + userId + ":"); 11591 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11592 } 11593 return; 11594 } 11595 } 11596 11597 if (existing != null) { 11598 if (DEBUG_PREFERRED) { 11599 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11600 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11601 } 11602 for (int i = 0; i < existing.size(); i++) { 11603 PreferredActivity pa = existing.get(i); 11604 if (DEBUG_PREFERRED) { 11605 Slog.i(TAG, "Removing existing preferred activity " 11606 + pa.mPref.mComponent + ":"); 11607 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11608 } 11609 pir.removeFilter(pa); 11610 } 11611 } 11612 } 11613 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11614 "Replacing preferred"); 11615 } 11616 } 11617 11618 @Override 11619 public void clearPackagePreferredActivities(String packageName) { 11620 final int uid = Binder.getCallingUid(); 11621 // writer 11622 synchronized (mPackages) { 11623 PackageParser.Package pkg = mPackages.get(packageName); 11624 if (pkg == null || pkg.applicationInfo.uid != uid) { 11625 if (mContext.checkCallingOrSelfPermission( 11626 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11627 != PackageManager.PERMISSION_GRANTED) { 11628 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11629 < Build.VERSION_CODES.FROYO) { 11630 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11631 + Binder.getCallingUid()); 11632 return; 11633 } 11634 mContext.enforceCallingOrSelfPermission( 11635 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11636 } 11637 } 11638 11639 int user = UserHandle.getCallingUserId(); 11640 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11641 scheduleWritePackageRestrictionsLocked(user); 11642 } 11643 } 11644 } 11645 11646 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11647 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11648 ArrayList<PreferredActivity> removed = null; 11649 boolean changed = false; 11650 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11651 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11652 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11653 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11654 continue; 11655 } 11656 Iterator<PreferredActivity> it = pir.filterIterator(); 11657 while (it.hasNext()) { 11658 PreferredActivity pa = it.next(); 11659 // Mark entry for removal only if it matches the package name 11660 // and the entry is of type "always". 11661 if (packageName == null || 11662 (pa.mPref.mComponent.getPackageName().equals(packageName) 11663 && pa.mPref.mAlways)) { 11664 if (removed == null) { 11665 removed = new ArrayList<PreferredActivity>(); 11666 } 11667 removed.add(pa); 11668 } 11669 } 11670 if (removed != null) { 11671 for (int j=0; j<removed.size(); j++) { 11672 PreferredActivity pa = removed.get(j); 11673 pir.removeFilter(pa); 11674 } 11675 changed = true; 11676 } 11677 } 11678 return changed; 11679 } 11680 11681 @Override 11682 public void resetPreferredActivities(int userId) { 11683 /* TODO: Actually use userId. Why is it being passed in? */ 11684 mContext.enforceCallingOrSelfPermission( 11685 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11686 // writer 11687 synchronized (mPackages) { 11688 int user = UserHandle.getCallingUserId(); 11689 clearPackagePreferredActivitiesLPw(null, user); 11690 mSettings.readDefaultPreferredAppsLPw(this, user); 11691 scheduleWritePackageRestrictionsLocked(user); 11692 } 11693 } 11694 11695 @Override 11696 public int getPreferredActivities(List<IntentFilter> outFilters, 11697 List<ComponentName> outActivities, String packageName) { 11698 11699 int num = 0; 11700 final int userId = UserHandle.getCallingUserId(); 11701 // reader 11702 synchronized (mPackages) { 11703 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11704 if (pir != null) { 11705 final Iterator<PreferredActivity> it = pir.filterIterator(); 11706 while (it.hasNext()) { 11707 final PreferredActivity pa = it.next(); 11708 if (packageName == null 11709 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11710 && pa.mPref.mAlways)) { 11711 if (outFilters != null) { 11712 outFilters.add(new IntentFilter(pa)); 11713 } 11714 if (outActivities != null) { 11715 outActivities.add(pa.mPref.mComponent); 11716 } 11717 } 11718 } 11719 } 11720 } 11721 11722 return num; 11723 } 11724 11725 @Override 11726 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11727 int userId) { 11728 int callingUid = Binder.getCallingUid(); 11729 if (callingUid != Process.SYSTEM_UID) { 11730 throw new SecurityException( 11731 "addPersistentPreferredActivity can only be run by the system"); 11732 } 11733 if (filter.countActions() == 0) { 11734 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11735 return; 11736 } 11737 synchronized (mPackages) { 11738 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11739 " :"); 11740 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11741 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11742 new PersistentPreferredActivity(filter, activity)); 11743 scheduleWritePackageRestrictionsLocked(userId); 11744 } 11745 } 11746 11747 @Override 11748 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11749 int callingUid = Binder.getCallingUid(); 11750 if (callingUid != Process.SYSTEM_UID) { 11751 throw new SecurityException( 11752 "clearPackagePersistentPreferredActivities can only be run by the system"); 11753 } 11754 ArrayList<PersistentPreferredActivity> removed = null; 11755 boolean changed = false; 11756 synchronized (mPackages) { 11757 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11758 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11759 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11760 .valueAt(i); 11761 if (userId != thisUserId) { 11762 continue; 11763 } 11764 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11765 while (it.hasNext()) { 11766 PersistentPreferredActivity ppa = it.next(); 11767 // Mark entry for removal only if it matches the package name. 11768 if (ppa.mComponent.getPackageName().equals(packageName)) { 11769 if (removed == null) { 11770 removed = new ArrayList<PersistentPreferredActivity>(); 11771 } 11772 removed.add(ppa); 11773 } 11774 } 11775 if (removed != null) { 11776 for (int j=0; j<removed.size(); j++) { 11777 PersistentPreferredActivity ppa = removed.get(j); 11778 ppir.removeFilter(ppa); 11779 } 11780 changed = true; 11781 } 11782 } 11783 11784 if (changed) { 11785 scheduleWritePackageRestrictionsLocked(userId); 11786 } 11787 } 11788 } 11789 11790 @Override 11791 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11792 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11793 mContext.enforceCallingOrSelfPermission( 11794 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11795 int callingUid = Binder.getCallingUid(); 11796 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11797 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11798 if (intentFilter.countActions() == 0) { 11799 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11800 return; 11801 } 11802 synchronized (mPackages) { 11803 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 11804 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11805 CrossProfileIntentResolver resolver = 11806 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11807 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 11808 // We have all those whose filter is equal. Now checking if the rest is equal as well. 11809 if (existing != null) { 11810 int size = existing.size(); 11811 for (int i = 0; i < size; i++) { 11812 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 11813 return; 11814 } 11815 } 11816 } 11817 resolver.addFilter(newFilter); 11818 scheduleWritePackageRestrictionsLocked(sourceUserId); 11819 } 11820 } 11821 11822 @Override 11823 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11824 int ownerUserId) { 11825 mContext.enforceCallingOrSelfPermission( 11826 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11827 int callingUid = Binder.getCallingUid(); 11828 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11829 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11830 int callingUserId = UserHandle.getUserId(callingUid); 11831 synchronized (mPackages) { 11832 CrossProfileIntentResolver resolver = 11833 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11834 ArraySet<CrossProfileIntentFilter> set = 11835 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 11836 for (CrossProfileIntentFilter filter : set) { 11837 if (filter.getOwnerPackage().equals(ownerPackage) 11838 && filter.getOwnerUserId() == callingUserId) { 11839 resolver.removeFilter(filter); 11840 } 11841 } 11842 scheduleWritePackageRestrictionsLocked(sourceUserId); 11843 } 11844 } 11845 11846 // Enforcing that callingUid is owning pkg on userId 11847 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11848 // The system owns everything. 11849 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11850 return; 11851 } 11852 int callingUserId = UserHandle.getUserId(callingUid); 11853 if (callingUserId != userId) { 11854 throw new SecurityException("calling uid " + callingUid 11855 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11856 + callingUserId); 11857 } 11858 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11859 if (pi == null) { 11860 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11861 + callingUserId); 11862 } 11863 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11864 throw new SecurityException("Calling uid " + callingUid 11865 + " does not own package " + pkg); 11866 } 11867 } 11868 11869 @Override 11870 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11871 Intent intent = new Intent(Intent.ACTION_MAIN); 11872 intent.addCategory(Intent.CATEGORY_HOME); 11873 11874 final int callingUserId = UserHandle.getCallingUserId(); 11875 List<ResolveInfo> list = queryIntentActivities(intent, null, 11876 PackageManager.GET_META_DATA, callingUserId); 11877 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11878 true, false, false, callingUserId); 11879 11880 allHomeCandidates.clear(); 11881 if (list != null) { 11882 for (ResolveInfo ri : list) { 11883 allHomeCandidates.add(ri); 11884 } 11885 } 11886 return (preferred == null || preferred.activityInfo == null) 11887 ? null 11888 : new ComponentName(preferred.activityInfo.packageName, 11889 preferred.activityInfo.name); 11890 } 11891 11892 @Override 11893 public void setApplicationEnabledSetting(String appPackageName, 11894 int newState, int flags, int userId, String callingPackage) { 11895 if (!sUserManager.exists(userId)) return; 11896 if (callingPackage == null) { 11897 callingPackage = Integer.toString(Binder.getCallingUid()); 11898 } 11899 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11900 } 11901 11902 @Override 11903 public void setComponentEnabledSetting(ComponentName componentName, 11904 int newState, int flags, int userId) { 11905 if (!sUserManager.exists(userId)) return; 11906 setEnabledSetting(componentName.getPackageName(), 11907 componentName.getClassName(), newState, flags, userId, null); 11908 } 11909 11910 private void setEnabledSetting(final String packageName, String className, int newState, 11911 final int flags, int userId, String callingPackage) { 11912 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11913 || newState == COMPONENT_ENABLED_STATE_ENABLED 11914 || newState == COMPONENT_ENABLED_STATE_DISABLED 11915 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11916 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11917 throw new IllegalArgumentException("Invalid new component state: " 11918 + newState); 11919 } 11920 PackageSetting pkgSetting; 11921 final int uid = Binder.getCallingUid(); 11922 final int permission = mContext.checkCallingOrSelfPermission( 11923 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11924 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 11925 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11926 boolean sendNow = false; 11927 boolean isApp = (className == null); 11928 String componentName = isApp ? packageName : className; 11929 int packageUid = -1; 11930 ArrayList<String> components; 11931 11932 // writer 11933 synchronized (mPackages) { 11934 pkgSetting = mSettings.mPackages.get(packageName); 11935 if (pkgSetting == null) { 11936 if (className == null) { 11937 throw new IllegalArgumentException( 11938 "Unknown package: " + packageName); 11939 } 11940 throw new IllegalArgumentException( 11941 "Unknown component: " + packageName 11942 + "/" + className); 11943 } 11944 // Allow root and verify that userId is not being specified by a different user 11945 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11946 throw new SecurityException( 11947 "Permission Denial: attempt to change component state from pid=" 11948 + Binder.getCallingPid() 11949 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11950 } 11951 if (className == null) { 11952 // We're dealing with an application/package level state change 11953 if (pkgSetting.getEnabled(userId) == newState) { 11954 // Nothing to do 11955 return; 11956 } 11957 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11958 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11959 // Don't care about who enables an app. 11960 callingPackage = null; 11961 } 11962 pkgSetting.setEnabled(newState, userId, callingPackage); 11963 // pkgSetting.pkg.mSetEnabled = newState; 11964 } else { 11965 // We're dealing with a component level state change 11966 // First, verify that this is a valid class name. 11967 PackageParser.Package pkg = pkgSetting.pkg; 11968 if (pkg == null || !pkg.hasComponentClassName(className)) { 11969 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11970 throw new IllegalArgumentException("Component class " + className 11971 + " does not exist in " + packageName); 11972 } else { 11973 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11974 + className + " does not exist in " + packageName); 11975 } 11976 } 11977 switch (newState) { 11978 case COMPONENT_ENABLED_STATE_ENABLED: 11979 if (!pkgSetting.enableComponentLPw(className, userId)) { 11980 return; 11981 } 11982 break; 11983 case COMPONENT_ENABLED_STATE_DISABLED: 11984 if (!pkgSetting.disableComponentLPw(className, userId)) { 11985 return; 11986 } 11987 break; 11988 case COMPONENT_ENABLED_STATE_DEFAULT: 11989 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11990 return; 11991 } 11992 break; 11993 default: 11994 Slog.e(TAG, "Invalid new component state: " + newState); 11995 return; 11996 } 11997 } 11998 mSettings.writePackageRestrictionsLPr(userId); 11999 components = mPendingBroadcasts.get(userId, packageName); 12000 final boolean newPackage = components == null; 12001 if (newPackage) { 12002 components = new ArrayList<String>(); 12003 } 12004 if (!components.contains(componentName)) { 12005 components.add(componentName); 12006 } 12007 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12008 sendNow = true; 12009 // Purge entry from pending broadcast list if another one exists already 12010 // since we are sending one right away. 12011 mPendingBroadcasts.remove(userId, packageName); 12012 } else { 12013 if (newPackage) { 12014 mPendingBroadcasts.put(userId, packageName, components); 12015 } 12016 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12017 // Schedule a message 12018 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12019 } 12020 } 12021 } 12022 12023 long callingId = Binder.clearCallingIdentity(); 12024 try { 12025 if (sendNow) { 12026 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12027 sendPackageChangedBroadcast(packageName, 12028 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12029 } 12030 } finally { 12031 Binder.restoreCallingIdentity(callingId); 12032 } 12033 } 12034 12035 private void sendPackageChangedBroadcast(String packageName, 12036 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12037 if (DEBUG_INSTALL) 12038 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12039 + componentNames); 12040 Bundle extras = new Bundle(4); 12041 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12042 String nameList[] = new String[componentNames.size()]; 12043 componentNames.toArray(nameList); 12044 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12045 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12046 extras.putInt(Intent.EXTRA_UID, packageUid); 12047 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12048 new int[] {UserHandle.getUserId(packageUid)}); 12049 } 12050 12051 @Override 12052 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12053 if (!sUserManager.exists(userId)) return; 12054 final int uid = Binder.getCallingUid(); 12055 final int permission = mContext.checkCallingOrSelfPermission( 12056 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12057 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12058 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12059 // writer 12060 synchronized (mPackages) { 12061 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12062 uid, userId)) { 12063 scheduleWritePackageRestrictionsLocked(userId); 12064 } 12065 } 12066 } 12067 12068 @Override 12069 public String getInstallerPackageName(String packageName) { 12070 // reader 12071 synchronized (mPackages) { 12072 return mSettings.getInstallerPackageNameLPr(packageName); 12073 } 12074 } 12075 12076 @Override 12077 public int getApplicationEnabledSetting(String packageName, int userId) { 12078 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12079 int uid = Binder.getCallingUid(); 12080 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12081 // reader 12082 synchronized (mPackages) { 12083 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12084 } 12085 } 12086 12087 @Override 12088 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12089 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12090 int uid = Binder.getCallingUid(); 12091 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12092 // reader 12093 synchronized (mPackages) { 12094 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12095 } 12096 } 12097 12098 @Override 12099 public void enterSafeMode() { 12100 enforceSystemOrRoot("Only the system can request entering safe mode"); 12101 12102 if (!mSystemReady) { 12103 mSafeMode = true; 12104 } 12105 } 12106 12107 @Override 12108 public void systemReady() { 12109 mSystemReady = true; 12110 12111 // Read the compatibilty setting when the system is ready. 12112 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12113 mContext.getContentResolver(), 12114 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12115 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12116 if (DEBUG_SETTINGS) { 12117 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12118 } 12119 12120 synchronized (mPackages) { 12121 // Verify that all of the preferred activity components actually 12122 // exist. It is possible for applications to be updated and at 12123 // that point remove a previously declared activity component that 12124 // had been set as a preferred activity. We try to clean this up 12125 // the next time we encounter that preferred activity, but it is 12126 // possible for the user flow to never be able to return to that 12127 // situation so here we do a sanity check to make sure we haven't 12128 // left any junk around. 12129 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12130 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12131 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12132 removed.clear(); 12133 for (PreferredActivity pa : pir.filterSet()) { 12134 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12135 removed.add(pa); 12136 } 12137 } 12138 if (removed.size() > 0) { 12139 for (int r=0; r<removed.size(); r++) { 12140 PreferredActivity pa = removed.get(r); 12141 Slog.w(TAG, "Removing dangling preferred activity: " 12142 + pa.mPref.mComponent); 12143 pir.removeFilter(pa); 12144 } 12145 mSettings.writePackageRestrictionsLPr( 12146 mSettings.mPreferredActivities.keyAt(i)); 12147 } 12148 } 12149 } 12150 sUserManager.systemReady(); 12151 12152 // Kick off any messages waiting for system ready 12153 if (mPostSystemReadyMessages != null) { 12154 for (Message msg : mPostSystemReadyMessages) { 12155 msg.sendToTarget(); 12156 } 12157 mPostSystemReadyMessages = null; 12158 } 12159 } 12160 12161 @Override 12162 public boolean isSafeMode() { 12163 return mSafeMode; 12164 } 12165 12166 @Override 12167 public boolean hasSystemUidErrors() { 12168 return mHasSystemUidErrors; 12169 } 12170 12171 static String arrayToString(int[] array) { 12172 StringBuffer buf = new StringBuffer(128); 12173 buf.append('['); 12174 if (array != null) { 12175 for (int i=0; i<array.length; i++) { 12176 if (i > 0) buf.append(", "); 12177 buf.append(array[i]); 12178 } 12179 } 12180 buf.append(']'); 12181 return buf.toString(); 12182 } 12183 12184 static class DumpState { 12185 public static final int DUMP_LIBS = 1 << 0; 12186 public static final int DUMP_FEATURES = 1 << 1; 12187 public static final int DUMP_RESOLVERS = 1 << 2; 12188 public static final int DUMP_PERMISSIONS = 1 << 3; 12189 public static final int DUMP_PACKAGES = 1 << 4; 12190 public static final int DUMP_SHARED_USERS = 1 << 5; 12191 public static final int DUMP_MESSAGES = 1 << 6; 12192 public static final int DUMP_PROVIDERS = 1 << 7; 12193 public static final int DUMP_VERIFIERS = 1 << 8; 12194 public static final int DUMP_PREFERRED = 1 << 9; 12195 public static final int DUMP_PREFERRED_XML = 1 << 10; 12196 public static final int DUMP_KEYSETS = 1 << 11; 12197 public static final int DUMP_VERSION = 1 << 12; 12198 public static final int DUMP_INSTALLS = 1 << 13; 12199 12200 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12201 12202 private int mTypes; 12203 12204 private int mOptions; 12205 12206 private boolean mTitlePrinted; 12207 12208 private SharedUserSetting mSharedUser; 12209 12210 public boolean isDumping(int type) { 12211 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12212 return true; 12213 } 12214 12215 return (mTypes & type) != 0; 12216 } 12217 12218 public void setDump(int type) { 12219 mTypes |= type; 12220 } 12221 12222 public boolean isOptionEnabled(int option) { 12223 return (mOptions & option) != 0; 12224 } 12225 12226 public void setOptionEnabled(int option) { 12227 mOptions |= option; 12228 } 12229 12230 public boolean onTitlePrinted() { 12231 final boolean printed = mTitlePrinted; 12232 mTitlePrinted = true; 12233 return printed; 12234 } 12235 12236 public boolean getTitlePrinted() { 12237 return mTitlePrinted; 12238 } 12239 12240 public void setTitlePrinted(boolean enabled) { 12241 mTitlePrinted = enabled; 12242 } 12243 12244 public SharedUserSetting getSharedUser() { 12245 return mSharedUser; 12246 } 12247 12248 public void setSharedUser(SharedUserSetting user) { 12249 mSharedUser = user; 12250 } 12251 } 12252 12253 @Override 12254 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12255 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12256 != PackageManager.PERMISSION_GRANTED) { 12257 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12258 + Binder.getCallingPid() 12259 + ", uid=" + Binder.getCallingUid() 12260 + " without permission " 12261 + android.Manifest.permission.DUMP); 12262 return; 12263 } 12264 12265 DumpState dumpState = new DumpState(); 12266 boolean fullPreferred = false; 12267 boolean checkin = false; 12268 12269 String packageName = null; 12270 12271 int opti = 0; 12272 while (opti < args.length) { 12273 String opt = args[opti]; 12274 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12275 break; 12276 } 12277 opti++; 12278 12279 if ("-a".equals(opt)) { 12280 // Right now we only know how to print all. 12281 } else if ("-h".equals(opt)) { 12282 pw.println("Package manager dump options:"); 12283 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12284 pw.println(" --checkin: dump for a checkin"); 12285 pw.println(" -f: print details of intent filters"); 12286 pw.println(" -h: print this help"); 12287 pw.println(" cmd may be one of:"); 12288 pw.println(" l[ibraries]: list known shared libraries"); 12289 pw.println(" f[ibraries]: list device features"); 12290 pw.println(" k[eysets]: print known keysets"); 12291 pw.println(" r[esolvers]: dump intent resolvers"); 12292 pw.println(" perm[issions]: dump permissions"); 12293 pw.println(" pref[erred]: print preferred package settings"); 12294 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12295 pw.println(" prov[iders]: dump content providers"); 12296 pw.println(" p[ackages]: dump installed packages"); 12297 pw.println(" s[hared-users]: dump shared user IDs"); 12298 pw.println(" m[essages]: print collected runtime messages"); 12299 pw.println(" v[erifiers]: print package verifier info"); 12300 pw.println(" version: print database version info"); 12301 pw.println(" write: write current settings now"); 12302 pw.println(" <package.name>: info about given package"); 12303 pw.println(" installs: details about install sessions"); 12304 return; 12305 } else if ("--checkin".equals(opt)) { 12306 checkin = true; 12307 } else if ("-f".equals(opt)) { 12308 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12309 } else { 12310 pw.println("Unknown argument: " + opt + "; use -h for help"); 12311 } 12312 } 12313 12314 // Is the caller requesting to dump a particular piece of data? 12315 if (opti < args.length) { 12316 String cmd = args[opti]; 12317 opti++; 12318 // Is this a package name? 12319 if ("android".equals(cmd) || cmd.contains(".")) { 12320 packageName = cmd; 12321 // When dumping a single package, we always dump all of its 12322 // filter information since the amount of data will be reasonable. 12323 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12324 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12325 dumpState.setDump(DumpState.DUMP_LIBS); 12326 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12327 dumpState.setDump(DumpState.DUMP_FEATURES); 12328 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12329 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12330 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12331 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12332 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12333 dumpState.setDump(DumpState.DUMP_PREFERRED); 12334 } else if ("preferred-xml".equals(cmd)) { 12335 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12336 if (opti < args.length && "--full".equals(args[opti])) { 12337 fullPreferred = true; 12338 opti++; 12339 } 12340 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12341 dumpState.setDump(DumpState.DUMP_PACKAGES); 12342 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12343 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12344 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12345 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12346 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12347 dumpState.setDump(DumpState.DUMP_MESSAGES); 12348 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12349 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12350 } else if ("version".equals(cmd)) { 12351 dumpState.setDump(DumpState.DUMP_VERSION); 12352 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12353 dumpState.setDump(DumpState.DUMP_KEYSETS); 12354 } else if ("installs".equals(cmd)) { 12355 dumpState.setDump(DumpState.DUMP_INSTALLS); 12356 } else if ("write".equals(cmd)) { 12357 synchronized (mPackages) { 12358 mSettings.writeLPr(); 12359 pw.println("Settings written."); 12360 return; 12361 } 12362 } 12363 } 12364 12365 if (checkin) { 12366 pw.println("vers,1"); 12367 } 12368 12369 // reader 12370 synchronized (mPackages) { 12371 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12372 if (!checkin) { 12373 if (dumpState.onTitlePrinted()) 12374 pw.println(); 12375 pw.println("Database versions:"); 12376 pw.print(" SDK Version:"); 12377 pw.print(" internal="); 12378 pw.print(mSettings.mInternalSdkPlatform); 12379 pw.print(" external="); 12380 pw.println(mSettings.mExternalSdkPlatform); 12381 pw.print(" DB Version:"); 12382 pw.print(" internal="); 12383 pw.print(mSettings.mInternalDatabaseVersion); 12384 pw.print(" external="); 12385 pw.println(mSettings.mExternalDatabaseVersion); 12386 } 12387 } 12388 12389 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12390 if (!checkin) { 12391 if (dumpState.onTitlePrinted()) 12392 pw.println(); 12393 pw.println("Verifiers:"); 12394 pw.print(" Required: "); 12395 pw.print(mRequiredVerifierPackage); 12396 pw.print(" (uid="); 12397 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12398 pw.println(")"); 12399 } else if (mRequiredVerifierPackage != null) { 12400 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12401 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12402 } 12403 } 12404 12405 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12406 boolean printedHeader = false; 12407 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12408 while (it.hasNext()) { 12409 String name = it.next(); 12410 SharedLibraryEntry ent = mSharedLibraries.get(name); 12411 if (!checkin) { 12412 if (!printedHeader) { 12413 if (dumpState.onTitlePrinted()) 12414 pw.println(); 12415 pw.println("Libraries:"); 12416 printedHeader = true; 12417 } 12418 pw.print(" "); 12419 } else { 12420 pw.print("lib,"); 12421 } 12422 pw.print(name); 12423 if (!checkin) { 12424 pw.print(" -> "); 12425 } 12426 if (ent.path != null) { 12427 if (!checkin) { 12428 pw.print("(jar) "); 12429 pw.print(ent.path); 12430 } else { 12431 pw.print(",jar,"); 12432 pw.print(ent.path); 12433 } 12434 } else { 12435 if (!checkin) { 12436 pw.print("(apk) "); 12437 pw.print(ent.apk); 12438 } else { 12439 pw.print(",apk,"); 12440 pw.print(ent.apk); 12441 } 12442 } 12443 pw.println(); 12444 } 12445 } 12446 12447 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12448 if (dumpState.onTitlePrinted()) 12449 pw.println(); 12450 if (!checkin) { 12451 pw.println("Features:"); 12452 } 12453 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12454 while (it.hasNext()) { 12455 String name = it.next(); 12456 if (!checkin) { 12457 pw.print(" "); 12458 } else { 12459 pw.print("feat,"); 12460 } 12461 pw.println(name); 12462 } 12463 } 12464 12465 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12466 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12467 : "Activity Resolver Table:", " ", packageName, 12468 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12469 dumpState.setTitlePrinted(true); 12470 } 12471 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12472 : "Receiver Resolver Table:", " ", packageName, 12473 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12474 dumpState.setTitlePrinted(true); 12475 } 12476 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12477 : "Service Resolver Table:", " ", packageName, 12478 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12479 dumpState.setTitlePrinted(true); 12480 } 12481 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12482 : "Provider Resolver Table:", " ", packageName, 12483 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12484 dumpState.setTitlePrinted(true); 12485 } 12486 } 12487 12488 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12489 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12490 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12491 int user = mSettings.mPreferredActivities.keyAt(i); 12492 if (pir.dump(pw, 12493 dumpState.getTitlePrinted() 12494 ? "\nPreferred Activities User " + user + ":" 12495 : "Preferred Activities User " + user + ":", " ", 12496 packageName, true, false)) { 12497 dumpState.setTitlePrinted(true); 12498 } 12499 } 12500 } 12501 12502 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12503 pw.flush(); 12504 FileOutputStream fout = new FileOutputStream(fd); 12505 BufferedOutputStream str = new BufferedOutputStream(fout); 12506 XmlSerializer serializer = new FastXmlSerializer(); 12507 try { 12508 serializer.setOutput(str, "utf-8"); 12509 serializer.startDocument(null, true); 12510 serializer.setFeature( 12511 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12512 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12513 serializer.endDocument(); 12514 serializer.flush(); 12515 } catch (IllegalArgumentException e) { 12516 pw.println("Failed writing: " + e); 12517 } catch (IllegalStateException e) { 12518 pw.println("Failed writing: " + e); 12519 } catch (IOException e) { 12520 pw.println("Failed writing: " + e); 12521 } 12522 } 12523 12524 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12525 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12526 if (packageName == null) { 12527 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12528 if (iperm == 0) { 12529 if (dumpState.onTitlePrinted()) 12530 pw.println(); 12531 pw.println("AppOp Permissions:"); 12532 } 12533 pw.print(" AppOp Permission "); 12534 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12535 pw.println(":"); 12536 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12537 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12538 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12539 } 12540 } 12541 } 12542 } 12543 12544 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12545 boolean printedSomething = false; 12546 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12547 if (packageName != null && !packageName.equals(p.info.packageName)) { 12548 continue; 12549 } 12550 if (!printedSomething) { 12551 if (dumpState.onTitlePrinted()) 12552 pw.println(); 12553 pw.println("Registered ContentProviders:"); 12554 printedSomething = true; 12555 } 12556 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12557 pw.print(" "); pw.println(p.toString()); 12558 } 12559 printedSomething = false; 12560 for (Map.Entry<String, PackageParser.Provider> entry : 12561 mProvidersByAuthority.entrySet()) { 12562 PackageParser.Provider p = entry.getValue(); 12563 if (packageName != null && !packageName.equals(p.info.packageName)) { 12564 continue; 12565 } 12566 if (!printedSomething) { 12567 if (dumpState.onTitlePrinted()) 12568 pw.println(); 12569 pw.println("ContentProvider Authorities:"); 12570 printedSomething = true; 12571 } 12572 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12573 pw.print(" "); pw.println(p.toString()); 12574 if (p.info != null && p.info.applicationInfo != null) { 12575 final String appInfo = p.info.applicationInfo.toString(); 12576 pw.print(" applicationInfo="); pw.println(appInfo); 12577 } 12578 } 12579 } 12580 12581 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12582 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12583 } 12584 12585 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12586 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12587 } 12588 12589 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12590 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 12591 } 12592 12593 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12594 // XXX should handle packageName != null by dumping only install data that 12595 // the given package is involved with. 12596 if (dumpState.onTitlePrinted()) pw.println(); 12597 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12598 } 12599 12600 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12601 if (dumpState.onTitlePrinted()) pw.println(); 12602 mSettings.dumpReadMessagesLPr(pw, dumpState); 12603 12604 pw.println(); 12605 pw.println("Package warning messages:"); 12606 BufferedReader in = null; 12607 String line = null; 12608 try { 12609 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12610 while ((line = in.readLine()) != null) { 12611 if (line.contains("ignored: updated version")) continue; 12612 pw.println(line); 12613 } 12614 } catch (IOException ignored) { 12615 } finally { 12616 IoUtils.closeQuietly(in); 12617 } 12618 } 12619 12620 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12621 BufferedReader in = null; 12622 String line = null; 12623 try { 12624 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12625 while ((line = in.readLine()) != null) { 12626 if (line.contains("ignored: updated version")) continue; 12627 pw.print("msg,"); 12628 pw.println(line); 12629 } 12630 } catch (IOException ignored) { 12631 } finally { 12632 IoUtils.closeQuietly(in); 12633 } 12634 } 12635 } 12636 } 12637 12638 // ------- apps on sdcard specific code ------- 12639 static final boolean DEBUG_SD_INSTALL = false; 12640 12641 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12642 12643 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12644 12645 private boolean mMediaMounted = false; 12646 12647 static String getEncryptKey() { 12648 try { 12649 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12650 SD_ENCRYPTION_KEYSTORE_NAME); 12651 if (sdEncKey == null) { 12652 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12653 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12654 if (sdEncKey == null) { 12655 Slog.e(TAG, "Failed to create encryption keys"); 12656 return null; 12657 } 12658 } 12659 return sdEncKey; 12660 } catch (NoSuchAlgorithmException nsae) { 12661 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12662 return null; 12663 } catch (IOException ioe) { 12664 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12665 return null; 12666 } 12667 } 12668 12669 /* 12670 * Update media status on PackageManager. 12671 */ 12672 @Override 12673 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12674 int callingUid = Binder.getCallingUid(); 12675 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12676 throw new SecurityException("Media status can only be updated by the system"); 12677 } 12678 // reader; this apparently protects mMediaMounted, but should probably 12679 // be a different lock in that case. 12680 synchronized (mPackages) { 12681 Log.i(TAG, "Updating external media status from " 12682 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12683 + (mediaStatus ? "mounted" : "unmounted")); 12684 if (DEBUG_SD_INSTALL) 12685 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12686 + ", mMediaMounted=" + mMediaMounted); 12687 if (mediaStatus == mMediaMounted) { 12688 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12689 : 0, -1); 12690 mHandler.sendMessage(msg); 12691 return; 12692 } 12693 mMediaMounted = mediaStatus; 12694 } 12695 // Queue up an async operation since the package installation may take a 12696 // little while. 12697 mHandler.post(new Runnable() { 12698 public void run() { 12699 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12700 } 12701 }); 12702 } 12703 12704 /** 12705 * Called by MountService when the initial ASECs to scan are available. 12706 * Should block until all the ASEC containers are finished being scanned. 12707 */ 12708 public void scanAvailableAsecs() { 12709 updateExternalMediaStatusInner(true, false, false); 12710 if (mShouldRestoreconData) { 12711 SELinuxMMAC.setRestoreconDone(); 12712 mShouldRestoreconData = false; 12713 } 12714 } 12715 12716 /* 12717 * Collect information of applications on external media, map them against 12718 * existing containers and update information based on current mount status. 12719 * Please note that we always have to report status if reportStatus has been 12720 * set to true especially when unloading packages. 12721 */ 12722 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12723 boolean externalStorage) { 12724 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12725 int[] uidArr = EmptyArray.INT; 12726 12727 final String[] list = PackageHelper.getSecureContainerList(); 12728 if (ArrayUtils.isEmpty(list)) { 12729 Log.i(TAG, "No secure containers found"); 12730 } else { 12731 // Process list of secure containers and categorize them 12732 // as active or stale based on their package internal state. 12733 12734 // reader 12735 synchronized (mPackages) { 12736 for (String cid : list) { 12737 // Leave stages untouched for now; installer service owns them 12738 if (PackageInstallerService.isStageName(cid)) continue; 12739 12740 if (DEBUG_SD_INSTALL) 12741 Log.i(TAG, "Processing container " + cid); 12742 String pkgName = getAsecPackageName(cid); 12743 if (pkgName == null) { 12744 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12745 continue; 12746 } 12747 if (DEBUG_SD_INSTALL) 12748 Log.i(TAG, "Looking for pkg : " + pkgName); 12749 12750 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12751 if (ps == null) { 12752 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12753 continue; 12754 } 12755 12756 /* 12757 * Skip packages that are not external if we're unmounting 12758 * external storage. 12759 */ 12760 if (externalStorage && !isMounted && !isExternal(ps)) { 12761 continue; 12762 } 12763 12764 final AsecInstallArgs args = new AsecInstallArgs(cid, 12765 getAppDexInstructionSets(ps), ps.isForwardLocked()); 12766 // The package status is changed only if the code path 12767 // matches between settings and the container id. 12768 if (ps.codePathString != null 12769 && ps.codePathString.startsWith(args.getCodePath())) { 12770 if (DEBUG_SD_INSTALL) { 12771 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12772 + " at code path: " + ps.codePathString); 12773 } 12774 12775 // We do have a valid package installed on sdcard 12776 processCids.put(args, ps.codePathString); 12777 final int uid = ps.appId; 12778 if (uid != -1) { 12779 uidArr = ArrayUtils.appendInt(uidArr, uid); 12780 } 12781 } else { 12782 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12783 + ps.codePathString); 12784 } 12785 } 12786 } 12787 12788 Arrays.sort(uidArr); 12789 } 12790 12791 // Process packages with valid entries. 12792 if (isMounted) { 12793 if (DEBUG_SD_INSTALL) 12794 Log.i(TAG, "Loading packages"); 12795 loadMediaPackages(processCids, uidArr); 12796 startCleaningPackages(); 12797 mInstallerService.onSecureContainersAvailable(); 12798 } else { 12799 if (DEBUG_SD_INSTALL) 12800 Log.i(TAG, "Unloading packages"); 12801 unloadMediaPackages(processCids, uidArr, reportStatus); 12802 } 12803 } 12804 12805 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12806 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12807 int size = pkgList.size(); 12808 if (size > 0) { 12809 // Send broadcasts here 12810 Bundle extras = new Bundle(); 12811 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12812 .toArray(new String[size])); 12813 if (uidArr != null) { 12814 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12815 } 12816 if (replacing) { 12817 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12818 } 12819 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12820 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12821 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12822 } 12823 } 12824 12825 /* 12826 * Look at potentially valid container ids from processCids If package 12827 * information doesn't match the one on record or package scanning fails, 12828 * the cid is added to list of removeCids. We currently don't delete stale 12829 * containers. 12830 */ 12831 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12832 ArrayList<String> pkgList = new ArrayList<String>(); 12833 Set<AsecInstallArgs> keys = processCids.keySet(); 12834 12835 for (AsecInstallArgs args : keys) { 12836 String codePath = processCids.get(args); 12837 if (DEBUG_SD_INSTALL) 12838 Log.i(TAG, "Loading container : " + args.cid); 12839 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12840 try { 12841 // Make sure there are no container errors first. 12842 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12843 Slog.e(TAG, "Failed to mount cid : " + args.cid 12844 + " when installing from sdcard"); 12845 continue; 12846 } 12847 // Check code path here. 12848 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12849 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12850 + " does not match one in settings " + codePath); 12851 continue; 12852 } 12853 // Parse package 12854 int parseFlags = mDefParseFlags; 12855 if (args.isExternal()) { 12856 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12857 } 12858 if (args.isFwdLocked()) { 12859 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12860 } 12861 12862 synchronized (mInstallLock) { 12863 PackageParser.Package pkg = null; 12864 try { 12865 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12866 } catch (PackageManagerException e) { 12867 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12868 } 12869 // Scan the package 12870 if (pkg != null) { 12871 /* 12872 * TODO why is the lock being held? doPostInstall is 12873 * called in other places without the lock. This needs 12874 * to be straightened out. 12875 */ 12876 // writer 12877 synchronized (mPackages) { 12878 retCode = PackageManager.INSTALL_SUCCEEDED; 12879 pkgList.add(pkg.packageName); 12880 // Post process args 12881 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12882 pkg.applicationInfo.uid); 12883 } 12884 } else { 12885 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12886 } 12887 } 12888 12889 } finally { 12890 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12891 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12892 } 12893 } 12894 } 12895 // writer 12896 synchronized (mPackages) { 12897 // If the platform SDK has changed since the last time we booted, 12898 // we need to re-grant app permission to catch any new ones that 12899 // appear. This is really a hack, and means that apps can in some 12900 // cases get permissions that the user didn't initially explicitly 12901 // allow... it would be nice to have some better way to handle 12902 // this situation. 12903 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12904 if (regrantPermissions) 12905 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12906 + mSdkVersion + "; regranting permissions for external storage"); 12907 mSettings.mExternalSdkPlatform = mSdkVersion; 12908 12909 // Make sure group IDs have been assigned, and any permission 12910 // changes in other apps are accounted for 12911 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12912 | (regrantPermissions 12913 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12914 : 0)); 12915 12916 mSettings.updateExternalDatabaseVersion(); 12917 12918 // can downgrade to reader 12919 // Persist settings 12920 mSettings.writeLPr(); 12921 } 12922 // Send a broadcast to let everyone know we are done processing 12923 if (pkgList.size() > 0) { 12924 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12925 } 12926 } 12927 12928 /* 12929 * Utility method to unload a list of specified containers 12930 */ 12931 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12932 // Just unmount all valid containers. 12933 for (AsecInstallArgs arg : cidArgs) { 12934 synchronized (mInstallLock) { 12935 arg.doPostDeleteLI(false); 12936 } 12937 } 12938 } 12939 12940 /* 12941 * Unload packages mounted on external media. This involves deleting package 12942 * data from internal structures, sending broadcasts about diabled packages, 12943 * gc'ing to free up references, unmounting all secure containers 12944 * corresponding to packages on external media, and posting a 12945 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12946 * that we always have to post this message if status has been requested no 12947 * matter what. 12948 */ 12949 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12950 final boolean reportStatus) { 12951 if (DEBUG_SD_INSTALL) 12952 Log.i(TAG, "unloading media packages"); 12953 ArrayList<String> pkgList = new ArrayList<String>(); 12954 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12955 final Set<AsecInstallArgs> keys = processCids.keySet(); 12956 for (AsecInstallArgs args : keys) { 12957 String pkgName = args.getPackageName(); 12958 if (DEBUG_SD_INSTALL) 12959 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12960 // Delete package internally 12961 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12962 synchronized (mInstallLock) { 12963 boolean res = deletePackageLI(pkgName, null, false, null, null, 12964 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12965 if (res) { 12966 pkgList.add(pkgName); 12967 } else { 12968 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12969 failedList.add(args); 12970 } 12971 } 12972 } 12973 12974 // reader 12975 synchronized (mPackages) { 12976 // We didn't update the settings after removing each package; 12977 // write them now for all packages. 12978 mSettings.writeLPr(); 12979 } 12980 12981 // We have to absolutely send UPDATED_MEDIA_STATUS only 12982 // after confirming that all the receivers processed the ordered 12983 // broadcast when packages get disabled, force a gc to clean things up. 12984 // and unload all the containers. 12985 if (pkgList.size() > 0) { 12986 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12987 new IIntentReceiver.Stub() { 12988 public void performReceive(Intent intent, int resultCode, String data, 12989 Bundle extras, boolean ordered, boolean sticky, 12990 int sendingUser) throws RemoteException { 12991 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12992 reportStatus ? 1 : 0, 1, keys); 12993 mHandler.sendMessage(msg); 12994 } 12995 }); 12996 } else { 12997 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12998 keys); 12999 mHandler.sendMessage(msg); 13000 } 13001 } 13002 13003 /** Binder call */ 13004 @Override 13005 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13006 final int flags) { 13007 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13008 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13009 int returnCode = PackageManager.MOVE_SUCCEEDED; 13010 int currInstallFlags = 0; 13011 int newInstallFlags = 0; 13012 13013 File codeFile = null; 13014 String installerPackageName = null; 13015 String packageAbiOverride = null; 13016 13017 // reader 13018 synchronized (mPackages) { 13019 final PackageParser.Package pkg = mPackages.get(packageName); 13020 final PackageSetting ps = mSettings.mPackages.get(packageName); 13021 if (pkg == null || ps == null) { 13022 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13023 } else { 13024 // Disable moving fwd locked apps and system packages 13025 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13026 Slog.w(TAG, "Cannot move system application"); 13027 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13028 } else if (pkg.mOperationPending) { 13029 Slog.w(TAG, "Attempt to move package which has pending operations"); 13030 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13031 } else { 13032 // Find install location first 13033 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13034 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13035 Slog.w(TAG, "Ambigous flags specified for move location."); 13036 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13037 } else { 13038 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13039 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13040 currInstallFlags = isExternal(pkg) 13041 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13042 13043 if (newInstallFlags == currInstallFlags) { 13044 Slog.w(TAG, "No move required. Trying to move to same location"); 13045 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13046 } else { 13047 if (pkg.isForwardLocked()) { 13048 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13049 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13050 } 13051 } 13052 } 13053 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13054 pkg.mOperationPending = true; 13055 } 13056 } 13057 13058 codeFile = new File(pkg.codePath); 13059 installerPackageName = ps.installerPackageName; 13060 packageAbiOverride = ps.cpuAbiOverrideString; 13061 } 13062 } 13063 13064 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13065 try { 13066 observer.packageMoved(packageName, returnCode); 13067 } catch (RemoteException ignored) { 13068 } 13069 return; 13070 } 13071 13072 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13073 @Override 13074 public void onUserActionRequired(Intent intent) throws RemoteException { 13075 throw new IllegalStateException(); 13076 } 13077 13078 @Override 13079 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13080 Bundle extras) throws RemoteException { 13081 Slog.d(TAG, "Install result for move: " 13082 + PackageManager.installStatusToString(returnCode, msg)); 13083 13084 // We usually have a new package now after the install, but if 13085 // we failed we need to clear the pending flag on the original 13086 // package object. 13087 synchronized (mPackages) { 13088 final PackageParser.Package pkg = mPackages.get(packageName); 13089 if (pkg != null) { 13090 pkg.mOperationPending = false; 13091 } 13092 } 13093 13094 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13095 switch (status) { 13096 case PackageInstaller.STATUS_SUCCESS: 13097 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13098 break; 13099 case PackageInstaller.STATUS_FAILURE_STORAGE: 13100 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13101 break; 13102 default: 13103 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13104 break; 13105 } 13106 } 13107 }; 13108 13109 // Treat a move like reinstalling an existing app, which ensures that we 13110 // process everythign uniformly, like unpacking native libraries. 13111 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13112 13113 final Message msg = mHandler.obtainMessage(INIT_COPY); 13114 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13115 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13116 installerPackageName, null, user, packageAbiOverride); 13117 mHandler.sendMessage(msg); 13118 } 13119 13120 @Override 13121 public boolean setInstallLocation(int loc) { 13122 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13123 null); 13124 if (getInstallLocation() == loc) { 13125 return true; 13126 } 13127 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13128 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13129 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13130 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13131 return true; 13132 } 13133 return false; 13134 } 13135 13136 @Override 13137 public int getInstallLocation() { 13138 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13139 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13140 PackageHelper.APP_INSTALL_AUTO); 13141 } 13142 13143 /** Called by UserManagerService */ 13144 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13145 mDirtyUsers.remove(userHandle); 13146 mSettings.removeUserLPw(userHandle); 13147 mPendingBroadcasts.remove(userHandle); 13148 if (mInstaller != null) { 13149 // Technically, we shouldn't be doing this with the package lock 13150 // held. However, this is very rare, and there is already so much 13151 // other disk I/O going on, that we'll let it slide for now. 13152 mInstaller.removeUserDataDirs(userHandle); 13153 } 13154 mUserNeedsBadging.delete(userHandle); 13155 removeUnusedPackagesLILPw(userManager, userHandle); 13156 } 13157 13158 /** 13159 * We're removing userHandle and would like to remove any downloaded packages 13160 * that are no longer in use by any other user. 13161 * @param userHandle the user being removed 13162 */ 13163 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13164 final boolean DEBUG_CLEAN_APKS = false; 13165 int [] users = userManager.getUserIdsLPr(); 13166 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13167 while (psit.hasNext()) { 13168 PackageSetting ps = psit.next(); 13169 if (ps.pkg == null) { 13170 continue; 13171 } 13172 final String packageName = ps.pkg.packageName; 13173 // Skip over if system app 13174 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13175 continue; 13176 } 13177 if (DEBUG_CLEAN_APKS) { 13178 Slog.i(TAG, "Checking package " + packageName); 13179 } 13180 boolean keep = false; 13181 for (int i = 0; i < users.length; i++) { 13182 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13183 keep = true; 13184 if (DEBUG_CLEAN_APKS) { 13185 Slog.i(TAG, " Keeping package " + packageName + " for user " 13186 + users[i]); 13187 } 13188 break; 13189 } 13190 } 13191 if (!keep) { 13192 if (DEBUG_CLEAN_APKS) { 13193 Slog.i(TAG, " Removing package " + packageName); 13194 } 13195 mHandler.post(new Runnable() { 13196 public void run() { 13197 deletePackageX(packageName, userHandle, 0); 13198 } //end run 13199 }); 13200 } 13201 } 13202 } 13203 13204 /** Called by UserManagerService */ 13205 void createNewUserLILPw(int userHandle, File path) { 13206 if (mInstaller != null) { 13207 mInstaller.createUserConfig(userHandle); 13208 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13209 } 13210 } 13211 13212 @Override 13213 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13214 mContext.enforceCallingOrSelfPermission( 13215 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13216 "Only package verification agents can read the verifier device identity"); 13217 13218 synchronized (mPackages) { 13219 return mSettings.getVerifierDeviceIdentityLPw(); 13220 } 13221 } 13222 13223 @Override 13224 public void setPermissionEnforced(String permission, boolean enforced) { 13225 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13226 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13227 synchronized (mPackages) { 13228 if (mSettings.mReadExternalStorageEnforced == null 13229 || mSettings.mReadExternalStorageEnforced != enforced) { 13230 mSettings.mReadExternalStorageEnforced = enforced; 13231 mSettings.writeLPr(); 13232 } 13233 } 13234 // kill any non-foreground processes so we restart them and 13235 // grant/revoke the GID. 13236 final IActivityManager am = ActivityManagerNative.getDefault(); 13237 if (am != null) { 13238 final long token = Binder.clearCallingIdentity(); 13239 try { 13240 am.killProcessesBelowForeground("setPermissionEnforcement"); 13241 } catch (RemoteException e) { 13242 } finally { 13243 Binder.restoreCallingIdentity(token); 13244 } 13245 } 13246 } else { 13247 throw new IllegalArgumentException("No selective enforcement for " + permission); 13248 } 13249 } 13250 13251 @Override 13252 @Deprecated 13253 public boolean isPermissionEnforced(String permission) { 13254 return true; 13255 } 13256 13257 @Override 13258 public boolean isStorageLow() { 13259 final long token = Binder.clearCallingIdentity(); 13260 try { 13261 final DeviceStorageMonitorInternal 13262 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13263 if (dsm != null) { 13264 return dsm.isMemoryLow(); 13265 } else { 13266 return false; 13267 } 13268 } finally { 13269 Binder.restoreCallingIdentity(token); 13270 } 13271 } 13272 13273 @Override 13274 public IPackageInstaller getPackageInstaller() { 13275 return mInstallerService; 13276 } 13277 13278 private boolean userNeedsBadging(int userId) { 13279 int index = mUserNeedsBadging.indexOfKey(userId); 13280 if (index < 0) { 13281 final UserInfo userInfo; 13282 final long token = Binder.clearCallingIdentity(); 13283 try { 13284 userInfo = sUserManager.getUserInfo(userId); 13285 } finally { 13286 Binder.restoreCallingIdentity(token); 13287 } 13288 final boolean b; 13289 if (userInfo != null && userInfo.isManagedProfile()) { 13290 b = true; 13291 } else { 13292 b = false; 13293 } 13294 mUserNeedsBadging.put(userId, b); 13295 return b; 13296 } 13297 return mUserNeedsBadging.valueAt(index); 13298 } 13299 13300 @Override 13301 public KeySet getKeySetByAlias(String packageName, String alias) { 13302 if (packageName == null || alias == null) { 13303 return null; 13304 } 13305 synchronized(mPackages) { 13306 final PackageParser.Package pkg = mPackages.get(packageName); 13307 if (pkg == null) { 13308 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13309 throw new IllegalArgumentException("Unknown package: " + packageName); 13310 } 13311 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13312 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13313 } 13314 } 13315 13316 @Override 13317 public KeySet getSigningKeySet(String packageName) { 13318 if (packageName == null) { 13319 return null; 13320 } 13321 synchronized(mPackages) { 13322 final PackageParser.Package pkg = mPackages.get(packageName); 13323 if (pkg == null) { 13324 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13325 throw new IllegalArgumentException("Unknown package: " + packageName); 13326 } 13327 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13328 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13329 throw new SecurityException("May not access signing KeySet of other apps."); 13330 } 13331 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13332 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13333 } 13334 } 13335 13336 @Override 13337 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13338 if (packageName == null || ks == null) { 13339 return false; 13340 } 13341 synchronized(mPackages) { 13342 final PackageParser.Package pkg = mPackages.get(packageName); 13343 if (pkg == null) { 13344 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13345 throw new IllegalArgumentException("Unknown package: " + packageName); 13346 } 13347 IBinder ksh = ks.getToken(); 13348 if (ksh instanceof KeySetHandle) { 13349 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13350 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13351 } 13352 return false; 13353 } 13354 } 13355 13356 @Override 13357 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13358 if (packageName == null || ks == null) { 13359 return false; 13360 } 13361 synchronized(mPackages) { 13362 final PackageParser.Package pkg = mPackages.get(packageName); 13363 if (pkg == null) { 13364 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13365 throw new IllegalArgumentException("Unknown package: " + packageName); 13366 } 13367 IBinder ksh = ks.getToken(); 13368 if (ksh instanceof KeySetHandle) { 13369 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13370 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13371 } 13372 return false; 13373 } 13374 } 13375 13376 public void getUsageStatsIfNoPackageUsageInfo() { 13377 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 13378 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 13379 if (usm == null) { 13380 throw new IllegalStateException("UsageStatsManager must be initialized"); 13381 } 13382 long now = System.currentTimeMillis(); 13383 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 13384 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 13385 String packageName = entry.getKey(); 13386 PackageParser.Package pkg = mPackages.get(packageName); 13387 if (pkg == null) { 13388 continue; 13389 } 13390 UsageStats usage = entry.getValue(); 13391 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 13392 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 13393 } 13394 } 13395 } 13396 13397 /** 13398 * Check and throw if the given before/after packages would be considered a 13399 * downgrade. 13400 */ 13401 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 13402 throws PackageManagerException { 13403 if (after.versionCode < before.mVersionCode) { 13404 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13405 "Update version code " + after.versionCode + " is older than current " 13406 + before.mVersionCode); 13407 } else if (after.versionCode == before.mVersionCode) { 13408 if (after.baseRevisionCode < before.baseRevisionCode) { 13409 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13410 "Update base revision code " + after.baseRevisionCode 13411 + " is older than current " + before.baseRevisionCode); 13412 } 13413 13414 if (!ArrayUtils.isEmpty(after.splitNames)) { 13415 for (int i = 0; i < after.splitNames.length; i++) { 13416 final String splitName = after.splitNames[i]; 13417 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 13418 if (j != -1) { 13419 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 13420 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13421 "Update split " + splitName + " revision code " 13422 + after.splitRevisionCodes[i] + " is older than current " 13423 + before.splitRevisionCodes[j]); 13424 } 13425 } 13426 } 13427 } 13428 } 13429 } 13430} 13431