PackageManagerService.java revision c5212217403696f81d2db220a1d9b22872600275
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_FORWARD_LOCK; 45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 46import static android.content.pm.PackageParser.isApkFile; 47import static android.os.Process.PACKAGE_INFO_GID; 48import static android.os.Process.SYSTEM_UID; 49import static android.system.OsConstants.O_CREAT; 50import static android.system.OsConstants.O_RDWR; 51import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 55import static com.android.internal.util.ArrayUtils.appendInt; 56import static com.android.internal.util.ArrayUtils.removeInt; 57 58import android.util.ArrayMap; 59 60import com.android.internal.R; 61import com.android.internal.app.IMediaContainerService; 62import com.android.internal.app.ResolverActivity; 63import com.android.internal.content.NativeLibraryHelper; 64import com.android.internal.content.PackageHelper; 65import com.android.internal.os.IParcelFileDescriptorFactory; 66import com.android.internal.util.ArrayUtils; 67import com.android.internal.util.FastPrintWriter; 68import com.android.internal.util.FastXmlSerializer; 69import com.android.internal.util.IndentingPrintWriter; 70import com.android.server.EventLogTags; 71import com.android.server.IntentResolver; 72import com.android.server.LocalServices; 73import com.android.server.ServiceThread; 74import com.android.server.SystemConfig; 75import com.android.server.Watchdog; 76import com.android.server.pm.Settings.DatabaseVersion; 77import com.android.server.storage.DeviceStorageMonitorInternal; 78 79import org.xmlpull.v1.XmlSerializer; 80 81import android.app.ActivityManager; 82import android.app.ActivityManagerNative; 83import android.app.IActivityManager; 84import android.app.admin.IDevicePolicyManager; 85import android.app.backup.IBackupManager; 86import android.content.BroadcastReceiver; 87import android.content.ComponentName; 88import android.content.Context; 89import android.content.IIntentReceiver; 90import android.content.Intent; 91import android.content.IntentFilter; 92import android.content.IntentSender; 93import android.content.IntentSender.SendIntentException; 94import android.content.ServiceConnection; 95import android.content.pm.ActivityInfo; 96import android.content.pm.ApplicationInfo; 97import android.content.pm.FeatureInfo; 98import android.content.pm.IPackageDataObserver; 99import android.content.pm.IPackageDeleteObserver; 100import android.content.pm.IPackageDeleteObserver2; 101import android.content.pm.IPackageInstallObserver2; 102import android.content.pm.IPackageInstaller; 103import android.content.pm.IPackageManager; 104import android.content.pm.IPackageMoveObserver; 105import android.content.pm.IPackageStatsObserver; 106import android.content.pm.InstrumentationInfo; 107import android.content.pm.ManifestDigest; 108import android.content.pm.PackageCleanItem; 109import android.content.pm.PackageInfo; 110import android.content.pm.PackageInfoLite; 111import android.content.pm.PackageInstaller; 112import android.content.pm.PackageManager; 113import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 114import android.content.pm.PackageParser.ActivityIntentInfo; 115import android.content.pm.PackageParser.PackageLite; 116import android.content.pm.PackageParser.PackageParserException; 117import android.content.pm.PackageParser; 118import android.content.pm.PackageStats; 119import android.content.pm.PackageUserState; 120import android.content.pm.ParceledListSlice; 121import android.content.pm.PermissionGroupInfo; 122import android.content.pm.PermissionInfo; 123import android.content.pm.ProviderInfo; 124import android.content.pm.ResolveInfo; 125import android.content.pm.ServiceInfo; 126import android.content.pm.Signature; 127import android.content.pm.UserInfo; 128import android.content.pm.VerificationParams; 129import android.content.pm.VerifierDeviceIdentity; 130import android.content.pm.VerifierInfo; 131import android.content.res.Resources; 132import android.hardware.display.DisplayManager; 133import android.net.Uri; 134import android.os.Binder; 135import android.os.Build; 136import android.os.Bundle; 137import android.os.Environment; 138import android.os.Environment.UserEnvironment; 139import android.os.storage.StorageManager; 140import android.os.FileUtils; 141import android.os.Handler; 142import android.os.IBinder; 143import android.os.Looper; 144import android.os.Message; 145import android.os.Parcel; 146import android.os.ParcelFileDescriptor; 147import android.os.Process; 148import android.os.RemoteException; 149import android.os.SELinux; 150import android.os.ServiceManager; 151import android.os.SystemClock; 152import android.os.SystemProperties; 153import android.os.UserHandle; 154import android.os.UserManager; 155import android.security.KeyStore; 156import android.security.SystemKeyStore; 157import android.system.ErrnoException; 158import android.system.Os; 159import android.system.StructStat; 160import android.text.TextUtils; 161import android.util.ArraySet; 162import android.util.AtomicFile; 163import android.util.DisplayMetrics; 164import android.util.EventLog; 165import android.util.ExceptionUtils; 166import android.util.Log; 167import android.util.LogPrinter; 168import android.util.PrintStreamPrinter; 169import android.util.Slog; 170import android.util.SparseArray; 171import android.util.SparseBooleanArray; 172import android.view.Display; 173 174import java.io.BufferedInputStream; 175import java.io.BufferedOutputStream; 176import java.io.File; 177import java.io.FileDescriptor; 178import java.io.FileInputStream; 179import java.io.FileNotFoundException; 180import java.io.FileOutputStream; 181import java.io.FilenameFilter; 182import java.io.IOException; 183import java.io.InputStream; 184import java.io.PrintWriter; 185import java.nio.charset.StandardCharsets; 186import java.security.NoSuchAlgorithmException; 187import java.security.PublicKey; 188import java.security.cert.CertificateEncodingException; 189import java.security.cert.CertificateException; 190import java.text.SimpleDateFormat; 191import java.util.ArrayList; 192import java.util.Arrays; 193import java.util.Collection; 194import java.util.Collections; 195import java.util.Comparator; 196import java.util.Date; 197import java.util.HashMap; 198import java.util.HashSet; 199import java.util.Iterator; 200import java.util.List; 201import java.util.Map; 202import java.util.Set; 203import java.util.concurrent.atomic.AtomicBoolean; 204import java.util.concurrent.atomic.AtomicLong; 205 206import dalvik.system.DexFile; 207import dalvik.system.StaleDexCacheError; 208import dalvik.system.VMRuntime; 209 210import libcore.io.IoUtils; 211import libcore.util.EmptyArray; 212 213/** 214 * Keep track of all those .apks everywhere. 215 * 216 * This is very central to the platform's security; please run the unit 217 * tests whenever making modifications here: 218 * 219mmm frameworks/base/tests/AndroidTests 220adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 221adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 222 * 223 * {@hide} 224 */ 225public class PackageManagerService extends IPackageManager.Stub { 226 static final String TAG = "PackageManager"; 227 static final boolean DEBUG_SETTINGS = false; 228 static final boolean DEBUG_PREFERRED = false; 229 static final boolean DEBUG_UPGRADE = false; 230 private static final boolean DEBUG_INSTALL = false; 231 private static final boolean DEBUG_REMOVE = false; 232 private static final boolean DEBUG_BROADCASTS = false; 233 private static final boolean DEBUG_SHOW_INFO = false; 234 private static final boolean DEBUG_PACKAGE_INFO = false; 235 private static final boolean DEBUG_INTENT_MATCHING = false; 236 private static final boolean DEBUG_PACKAGE_SCANNING = false; 237 private static final boolean DEBUG_VERIFY = false; 238 private static final boolean DEBUG_DEXOPT = false; 239 private static final boolean DEBUG_ABI_SELECTION = false; 240 241 private static final int RADIO_UID = Process.PHONE_UID; 242 private static final int LOG_UID = Process.LOG_UID; 243 private static final int NFC_UID = Process.NFC_UID; 244 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 245 private static final int SHELL_UID = Process.SHELL_UID; 246 247 // Cap the size of permission trees that 3rd party apps can define 248 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 249 250 // Suffix used during package installation when copying/moving 251 // package apks to install directory. 252 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 253 254 static final int SCAN_NO_DEX = 1<<1; 255 static final int SCAN_FORCE_DEX = 1<<2; 256 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 257 static final int SCAN_NEW_INSTALL = 1<<4; 258 static final int SCAN_NO_PATHS = 1<<5; 259 static final int SCAN_UPDATE_TIME = 1<<6; 260 static final int SCAN_DEFER_DEX = 1<<7; 261 static final int SCAN_BOOTING = 1<<8; 262 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 263 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 264 static final int SCAN_REPLACING = 1<<11; 265 266 static final int REMOVE_CHATTY = 1<<16; 267 268 /** 269 * Timeout (in milliseconds) after which the watchdog should declare that 270 * our handler thread is wedged. The usual default for such things is one 271 * minute but we sometimes do very lengthy I/O operations on this thread, 272 * such as installing multi-gigabyte applications, so ours needs to be longer. 273 */ 274 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 275 276 /** 277 * Whether verification is enabled by default. 278 */ 279 private static final boolean DEFAULT_VERIFY_ENABLE = true; 280 281 /** 282 * The default maximum time to wait for the verification agent to return in 283 * milliseconds. 284 */ 285 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 286 287 /** 288 * The default response for package verification timeout. 289 * 290 * This can be either PackageManager.VERIFICATION_ALLOW or 291 * PackageManager.VERIFICATION_REJECT. 292 */ 293 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 294 295 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 296 297 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 298 DEFAULT_CONTAINER_PACKAGE, 299 "com.android.defcontainer.DefaultContainerService"); 300 301 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 302 303 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 304 305 private static String sPreferredInstructionSet; 306 307 final ServiceThread mHandlerThread; 308 309 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 310 private static final String IDMAP_SUFFIX = "@idmap"; 311 312 final PackageHandler mHandler; 313 314 final int mSdkVersion = Build.VERSION.SDK_INT; 315 316 final Context mContext; 317 final boolean mFactoryTest; 318 final boolean mOnlyCore; 319 final DisplayMetrics mMetrics; 320 final int mDefParseFlags; 321 final String[] mSeparateProcesses; 322 323 // This is where all application persistent data goes. 324 final File mAppDataDir; 325 326 // This is where all application persistent data goes for secondary users. 327 final File mUserAppDataDir; 328 329 /** The location for ASEC container files on internal storage. */ 330 final String mAsecInternalPath; 331 332 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 333 // LOCK HELD. Can be called with mInstallLock held. 334 final Installer mInstaller; 335 336 /** Directory where installed third-party apps stored */ 337 final File mAppInstallDir; 338 339 /** 340 * Directory to which applications installed internally have their 341 * 32 bit native libraries copied. 342 */ 343 private File mAppLib32InstallDir; 344 345 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 346 // apps. 347 final File mDrmAppPrivateInstallDir; 348 349 // ---------------------------------------------------------------- 350 351 // Lock for state used when installing and doing other long running 352 // operations. Methods that must be called with this lock held have 353 // the suffix "LI". 354 final Object mInstallLock = new Object(); 355 356 // ---------------------------------------------------------------- 357 358 // Keys are String (package name), values are Package. This also serves 359 // as the lock for the global state. Methods that must be called with 360 // this lock held have the prefix "LP". 361 final HashMap<String, PackageParser.Package> mPackages = 362 new HashMap<String, PackageParser.Package>(); 363 364 // Tracks available target package names -> overlay package paths. 365 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 366 new HashMap<String, HashMap<String, PackageParser.Package>>(); 367 368 final Settings mSettings; 369 boolean mRestoredSettings; 370 371 // System configuration read by SystemConfig. 372 final int[] mGlobalGids; 373 final SparseArray<HashSet<String>> mSystemPermissions; 374 final HashMap<String, FeatureInfo> mAvailableFeatures; 375 376 // If mac_permissions.xml was found for seinfo labeling. 377 boolean mFoundPolicyFile; 378 379 // If a recursive restorecon of /data/data/<pkg> is needed. 380 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 381 382 public static final class SharedLibraryEntry { 383 public final String path; 384 public final String apk; 385 386 SharedLibraryEntry(String _path, String _apk) { 387 path = _path; 388 apk = _apk; 389 } 390 } 391 392 // Currently known shared libraries. 393 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 394 new HashMap<String, SharedLibraryEntry>(); 395 396 // All available activities, for your resolving pleasure. 397 final ActivityIntentResolver mActivities = 398 new ActivityIntentResolver(); 399 400 // All available receivers, for your resolving pleasure. 401 final ActivityIntentResolver mReceivers = 402 new ActivityIntentResolver(); 403 404 // All available services, for your resolving pleasure. 405 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 406 407 // All available providers, for your resolving pleasure. 408 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 409 410 // Mapping from provider base names (first directory in content URI codePath) 411 // to the provider information. 412 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 413 new HashMap<String, PackageParser.Provider>(); 414 415 // Mapping from instrumentation class names to info about them. 416 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 417 new HashMap<ComponentName, PackageParser.Instrumentation>(); 418 419 // Mapping from permission names to info about them. 420 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 421 new HashMap<String, PackageParser.PermissionGroup>(); 422 423 // Packages whose data we have transfered into another package, thus 424 // should no longer exist. 425 final HashSet<String> mTransferedPackages = new HashSet<String>(); 426 427 // Broadcast actions that are only available to the system. 428 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 429 430 /** List of packages waiting for verification. */ 431 final SparseArray<PackageVerificationState> mPendingVerification 432 = new SparseArray<PackageVerificationState>(); 433 434 /** Set of packages associated with each app op permission. */ 435 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 436 437 final PackageInstallerService mInstallerService; 438 439 HashSet<PackageParser.Package> mDeferredDexOpt = null; 440 441 // Cache of users who need badging. 442 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 443 444 /** Token for keys in mPendingVerification. */ 445 private int mPendingVerificationToken = 0; 446 447 boolean mSystemReady; 448 boolean mSafeMode; 449 boolean mHasSystemUidErrors; 450 451 ApplicationInfo mAndroidApplication; 452 final ActivityInfo mResolveActivity = new ActivityInfo(); 453 final ResolveInfo mResolveInfo = new ResolveInfo(); 454 ComponentName mResolveComponentName; 455 PackageParser.Package mPlatformPackage; 456 ComponentName mCustomResolverComponentName; 457 458 boolean mResolverReplaced = false; 459 460 // Set of pending broadcasts for aggregating enable/disable of components. 461 static class PendingPackageBroadcasts { 462 // for each user id, a map of <package name -> components within that package> 463 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 464 465 public PendingPackageBroadcasts() { 466 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 467 } 468 469 public ArrayList<String> get(int userId, String packageName) { 470 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 471 return packages.get(packageName); 472 } 473 474 public void put(int userId, String packageName, ArrayList<String> components) { 475 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 476 packages.put(packageName, components); 477 } 478 479 public void remove(int userId, String packageName) { 480 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 481 if (packages != null) { 482 packages.remove(packageName); 483 } 484 } 485 486 public void remove(int userId) { 487 mUidMap.remove(userId); 488 } 489 490 public int userIdCount() { 491 return mUidMap.size(); 492 } 493 494 public int userIdAt(int n) { 495 return mUidMap.keyAt(n); 496 } 497 498 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 499 return mUidMap.get(userId); 500 } 501 502 public int size() { 503 // total number of pending broadcast entries across all userIds 504 int num = 0; 505 for (int i = 0; i< mUidMap.size(); i++) { 506 num += mUidMap.valueAt(i).size(); 507 } 508 return num; 509 } 510 511 public void clear() { 512 mUidMap.clear(); 513 } 514 515 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 516 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 517 if (map == null) { 518 map = new HashMap<String, ArrayList<String>>(); 519 mUidMap.put(userId, map); 520 } 521 return map; 522 } 523 } 524 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 525 526 // Service Connection to remote media container service to copy 527 // package uri's from external media onto secure containers 528 // or internal storage. 529 private IMediaContainerService mContainerService = null; 530 531 static final int SEND_PENDING_BROADCAST = 1; 532 static final int MCS_BOUND = 3; 533 static final int END_COPY = 4; 534 static final int INIT_COPY = 5; 535 static final int MCS_UNBIND = 6; 536 static final int START_CLEANING_PACKAGE = 7; 537 static final int FIND_INSTALL_LOC = 8; 538 static final int POST_INSTALL = 9; 539 static final int MCS_RECONNECT = 10; 540 static final int MCS_GIVE_UP = 11; 541 static final int UPDATED_MEDIA_STATUS = 12; 542 static final int WRITE_SETTINGS = 13; 543 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 544 static final int PACKAGE_VERIFIED = 15; 545 static final int CHECK_PENDING_VERIFICATION = 16; 546 547 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 548 549 // Delay time in millisecs 550 static final int BROADCAST_DELAY = 10 * 1000; 551 552 static UserManagerService sUserManager; 553 554 // Stores a list of users whose package restrictions file needs to be updated 555 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 556 557 final private DefaultContainerConnection mDefContainerConn = 558 new DefaultContainerConnection(); 559 class DefaultContainerConnection implements ServiceConnection { 560 public void onServiceConnected(ComponentName name, IBinder service) { 561 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 562 IMediaContainerService imcs = 563 IMediaContainerService.Stub.asInterface(service); 564 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 565 } 566 567 public void onServiceDisconnected(ComponentName name) { 568 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 569 } 570 }; 571 572 // Recordkeeping of restore-after-install operations that are currently in flight 573 // between the Package Manager and the Backup Manager 574 class PostInstallData { 575 public InstallArgs args; 576 public PackageInstalledInfo res; 577 578 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 579 args = _a; 580 res = _r; 581 } 582 }; 583 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 584 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 585 586 private final String mRequiredVerifierPackage; 587 588 private final PackageUsage mPackageUsage = new PackageUsage(); 589 590 private class PackageUsage { 591 private static final int WRITE_INTERVAL 592 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 593 594 private final Object mFileLock = new Object(); 595 private final AtomicLong mLastWritten = new AtomicLong(0); 596 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 597 598 private boolean mIsHistoricalPackageUsageAvailable = true; 599 600 boolean isHistoricalPackageUsageAvailable() { 601 return mIsHistoricalPackageUsageAvailable; 602 } 603 604 void write(boolean force) { 605 if (force) { 606 writeInternal(); 607 return; 608 } 609 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 610 && !DEBUG_DEXOPT) { 611 return; 612 } 613 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 614 new Thread("PackageUsage_DiskWriter") { 615 @Override 616 public void run() { 617 try { 618 writeInternal(); 619 } finally { 620 mBackgroundWriteRunning.set(false); 621 } 622 } 623 }.start(); 624 } 625 } 626 627 private void writeInternal() { 628 synchronized (mPackages) { 629 synchronized (mFileLock) { 630 AtomicFile file = getFile(); 631 FileOutputStream f = null; 632 try { 633 f = file.startWrite(); 634 BufferedOutputStream out = new BufferedOutputStream(f); 635 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 636 StringBuilder sb = new StringBuilder(); 637 for (PackageParser.Package pkg : mPackages.values()) { 638 if (pkg.mLastPackageUsageTimeInMills == 0) { 639 continue; 640 } 641 sb.setLength(0); 642 sb.append(pkg.packageName); 643 sb.append(' '); 644 sb.append((long)pkg.mLastPackageUsageTimeInMills); 645 sb.append('\n'); 646 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 647 } 648 out.flush(); 649 file.finishWrite(f); 650 } catch (IOException e) { 651 if (f != null) { 652 file.failWrite(f); 653 } 654 Log.e(TAG, "Failed to write package usage times", e); 655 } 656 } 657 } 658 mLastWritten.set(SystemClock.elapsedRealtime()); 659 } 660 661 void readLP() { 662 synchronized (mFileLock) { 663 AtomicFile file = getFile(); 664 BufferedInputStream in = null; 665 try { 666 in = new BufferedInputStream(file.openRead()); 667 StringBuffer sb = new StringBuffer(); 668 while (true) { 669 String packageName = readToken(in, sb, ' '); 670 if (packageName == null) { 671 break; 672 } 673 String timeInMillisString = readToken(in, sb, '\n'); 674 if (timeInMillisString == null) { 675 throw new IOException("Failed to find last usage time for package " 676 + packageName); 677 } 678 PackageParser.Package pkg = mPackages.get(packageName); 679 if (pkg == null) { 680 continue; 681 } 682 long timeInMillis; 683 try { 684 timeInMillis = Long.parseLong(timeInMillisString.toString()); 685 } catch (NumberFormatException e) { 686 throw new IOException("Failed to parse " + timeInMillisString 687 + " as a long.", e); 688 } 689 pkg.mLastPackageUsageTimeInMills = timeInMillis; 690 } 691 } catch (FileNotFoundException expected) { 692 mIsHistoricalPackageUsageAvailable = false; 693 } catch (IOException e) { 694 Log.w(TAG, "Failed to read package usage times", e); 695 } finally { 696 IoUtils.closeQuietly(in); 697 } 698 } 699 mLastWritten.set(SystemClock.elapsedRealtime()); 700 } 701 702 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 703 throws IOException { 704 sb.setLength(0); 705 while (true) { 706 int ch = in.read(); 707 if (ch == -1) { 708 if (sb.length() == 0) { 709 return null; 710 } 711 throw new IOException("Unexpected EOF"); 712 } 713 if (ch == endOfToken) { 714 return sb.toString(); 715 } 716 sb.append((char)ch); 717 } 718 } 719 720 private AtomicFile getFile() { 721 File dataDir = Environment.getDataDirectory(); 722 File systemDir = new File(dataDir, "system"); 723 File fname = new File(systemDir, "package-usage.list"); 724 return new AtomicFile(fname); 725 } 726 } 727 728 class PackageHandler extends Handler { 729 private boolean mBound = false; 730 final ArrayList<HandlerParams> mPendingInstalls = 731 new ArrayList<HandlerParams>(); 732 733 private boolean connectToService() { 734 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 735 " DefaultContainerService"); 736 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 737 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 738 if (mContext.bindServiceAsUser(service, mDefContainerConn, 739 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 740 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 741 mBound = true; 742 return true; 743 } 744 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 745 return false; 746 } 747 748 private void disconnectService() { 749 mContainerService = null; 750 mBound = false; 751 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 752 mContext.unbindService(mDefContainerConn); 753 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 754 } 755 756 PackageHandler(Looper looper) { 757 super(looper); 758 } 759 760 public void handleMessage(Message msg) { 761 try { 762 doHandleMessage(msg); 763 } finally { 764 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 765 } 766 } 767 768 void doHandleMessage(Message msg) { 769 switch (msg.what) { 770 case INIT_COPY: { 771 HandlerParams params = (HandlerParams) msg.obj; 772 int idx = mPendingInstalls.size(); 773 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 774 // If a bind was already initiated we dont really 775 // need to do anything. The pending install 776 // will be processed later on. 777 if (!mBound) { 778 // If this is the only one pending we might 779 // have to bind to the service again. 780 if (!connectToService()) { 781 Slog.e(TAG, "Failed to bind to media container service"); 782 params.serviceError(); 783 return; 784 } else { 785 // Once we bind to the service, the first 786 // pending request will be processed. 787 mPendingInstalls.add(idx, params); 788 } 789 } else { 790 mPendingInstalls.add(idx, params); 791 // Already bound to the service. Just make 792 // sure we trigger off processing the first request. 793 if (idx == 0) { 794 mHandler.sendEmptyMessage(MCS_BOUND); 795 } 796 } 797 break; 798 } 799 case MCS_BOUND: { 800 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 801 if (msg.obj != null) { 802 mContainerService = (IMediaContainerService) msg.obj; 803 } 804 if (mContainerService == null) { 805 // Something seriously wrong. Bail out 806 Slog.e(TAG, "Cannot bind to media container service"); 807 for (HandlerParams params : mPendingInstalls) { 808 // Indicate service bind error 809 params.serviceError(); 810 } 811 mPendingInstalls.clear(); 812 } else if (mPendingInstalls.size() > 0) { 813 HandlerParams params = mPendingInstalls.get(0); 814 if (params != null) { 815 if (params.startCopy()) { 816 // We are done... look for more work or to 817 // go idle. 818 if (DEBUG_SD_INSTALL) Log.i(TAG, 819 "Checking for more work or unbind..."); 820 // Delete pending install 821 if (mPendingInstalls.size() > 0) { 822 mPendingInstalls.remove(0); 823 } 824 if (mPendingInstalls.size() == 0) { 825 if (mBound) { 826 if (DEBUG_SD_INSTALL) Log.i(TAG, 827 "Posting delayed MCS_UNBIND"); 828 removeMessages(MCS_UNBIND); 829 Message ubmsg = obtainMessage(MCS_UNBIND); 830 // Unbind after a little delay, to avoid 831 // continual thrashing. 832 sendMessageDelayed(ubmsg, 10000); 833 } 834 } else { 835 // There are more pending requests in queue. 836 // Just post MCS_BOUND message to trigger processing 837 // of next pending install. 838 if (DEBUG_SD_INSTALL) Log.i(TAG, 839 "Posting MCS_BOUND for next work"); 840 mHandler.sendEmptyMessage(MCS_BOUND); 841 } 842 } 843 } 844 } else { 845 // Should never happen ideally. 846 Slog.w(TAG, "Empty queue"); 847 } 848 break; 849 } 850 case MCS_RECONNECT: { 851 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 852 if (mPendingInstalls.size() > 0) { 853 if (mBound) { 854 disconnectService(); 855 } 856 if (!connectToService()) { 857 Slog.e(TAG, "Failed to bind to media container service"); 858 for (HandlerParams params : mPendingInstalls) { 859 // Indicate service bind error 860 params.serviceError(); 861 } 862 mPendingInstalls.clear(); 863 } 864 } 865 break; 866 } 867 case MCS_UNBIND: { 868 // If there is no actual work left, then time to unbind. 869 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 870 871 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 872 if (mBound) { 873 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 874 875 disconnectService(); 876 } 877 } else if (mPendingInstalls.size() > 0) { 878 // There are more pending requests in queue. 879 // Just post MCS_BOUND message to trigger processing 880 // of next pending install. 881 mHandler.sendEmptyMessage(MCS_BOUND); 882 } 883 884 break; 885 } 886 case MCS_GIVE_UP: { 887 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 888 mPendingInstalls.remove(0); 889 break; 890 } 891 case SEND_PENDING_BROADCAST: { 892 String packages[]; 893 ArrayList<String> components[]; 894 int size = 0; 895 int uids[]; 896 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 897 synchronized (mPackages) { 898 if (mPendingBroadcasts == null) { 899 return; 900 } 901 size = mPendingBroadcasts.size(); 902 if (size <= 0) { 903 // Nothing to be done. Just return 904 return; 905 } 906 packages = new String[size]; 907 components = new ArrayList[size]; 908 uids = new int[size]; 909 int i = 0; // filling out the above arrays 910 911 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 912 int packageUserId = mPendingBroadcasts.userIdAt(n); 913 Iterator<Map.Entry<String, ArrayList<String>>> it 914 = mPendingBroadcasts.packagesForUserId(packageUserId) 915 .entrySet().iterator(); 916 while (it.hasNext() && i < size) { 917 Map.Entry<String, ArrayList<String>> ent = it.next(); 918 packages[i] = ent.getKey(); 919 components[i] = ent.getValue(); 920 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 921 uids[i] = (ps != null) 922 ? UserHandle.getUid(packageUserId, ps.appId) 923 : -1; 924 i++; 925 } 926 } 927 size = i; 928 mPendingBroadcasts.clear(); 929 } 930 // Send broadcasts 931 for (int i = 0; i < size; i++) { 932 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 933 } 934 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 935 break; 936 } 937 case START_CLEANING_PACKAGE: { 938 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 939 final String packageName = (String)msg.obj; 940 final int userId = msg.arg1; 941 final boolean andCode = msg.arg2 != 0; 942 synchronized (mPackages) { 943 if (userId == UserHandle.USER_ALL) { 944 int[] users = sUserManager.getUserIds(); 945 for (int user : users) { 946 mSettings.addPackageToCleanLPw( 947 new PackageCleanItem(user, packageName, andCode)); 948 } 949 } else { 950 mSettings.addPackageToCleanLPw( 951 new PackageCleanItem(userId, packageName, andCode)); 952 } 953 } 954 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 955 startCleaningPackages(); 956 } break; 957 case POST_INSTALL: { 958 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 959 PostInstallData data = mRunningInstalls.get(msg.arg1); 960 mRunningInstalls.delete(msg.arg1); 961 boolean deleteOld = false; 962 963 if (data != null) { 964 InstallArgs args = data.args; 965 PackageInstalledInfo res = data.res; 966 967 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 968 res.removedInfo.sendBroadcast(false, true, false); 969 Bundle extras = new Bundle(1); 970 extras.putInt(Intent.EXTRA_UID, res.uid); 971 // Determine the set of users who are adding this 972 // package for the first time vs. those who are seeing 973 // an update. 974 int[] firstUsers; 975 int[] updateUsers = new int[0]; 976 if (res.origUsers == null || res.origUsers.length == 0) { 977 firstUsers = res.newUsers; 978 } else { 979 firstUsers = new int[0]; 980 for (int i=0; i<res.newUsers.length; i++) { 981 int user = res.newUsers[i]; 982 boolean isNew = true; 983 for (int j=0; j<res.origUsers.length; j++) { 984 if (res.origUsers[j] == user) { 985 isNew = false; 986 break; 987 } 988 } 989 if (isNew) { 990 int[] newFirst = new int[firstUsers.length+1]; 991 System.arraycopy(firstUsers, 0, newFirst, 0, 992 firstUsers.length); 993 newFirst[firstUsers.length] = user; 994 firstUsers = newFirst; 995 } else { 996 int[] newUpdate = new int[updateUsers.length+1]; 997 System.arraycopy(updateUsers, 0, newUpdate, 0, 998 updateUsers.length); 999 newUpdate[updateUsers.length] = user; 1000 updateUsers = newUpdate; 1001 } 1002 } 1003 } 1004 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1005 res.pkg.applicationInfo.packageName, 1006 extras, null, null, firstUsers); 1007 final boolean update = res.removedInfo.removedPackage != null; 1008 if (update) { 1009 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1010 } 1011 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1012 res.pkg.applicationInfo.packageName, 1013 extras, null, null, updateUsers); 1014 if (update) { 1015 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1016 res.pkg.applicationInfo.packageName, 1017 extras, null, null, updateUsers); 1018 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1019 null, null, 1020 res.pkg.applicationInfo.packageName, null, updateUsers); 1021 1022 // treat asec-hosted packages like removable media on upgrade 1023 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1024 if (DEBUG_INSTALL) { 1025 Slog.i(TAG, "upgrading pkg " + res.pkg 1026 + " is ASEC-hosted -> AVAILABLE"); 1027 } 1028 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1029 ArrayList<String> pkgList = new ArrayList<String>(1); 1030 pkgList.add(res.pkg.applicationInfo.packageName); 1031 sendResourcesChangedBroadcast(true, true, 1032 pkgList,uidArray, null); 1033 } 1034 } 1035 if (res.removedInfo.args != null) { 1036 // Remove the replaced package's older resources safely now 1037 deleteOld = true; 1038 } 1039 1040 // Log current value of "unknown sources" setting 1041 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1042 getUnknownSourcesSettings()); 1043 } 1044 // Force a gc to clear up things 1045 Runtime.getRuntime().gc(); 1046 // We delete after a gc for applications on sdcard. 1047 if (deleteOld) { 1048 synchronized (mInstallLock) { 1049 res.removedInfo.args.doPostDeleteLI(true); 1050 } 1051 } 1052 if (args.observer != null) { 1053 try { 1054 Bundle extras = extrasForInstallResult(res); 1055 args.observer.onPackageInstalled(res.name, res.returnCode, 1056 res.returnMsg, extras); 1057 } catch (RemoteException e) { 1058 Slog.i(TAG, "Observer no longer exists."); 1059 } 1060 } 1061 } else { 1062 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1063 } 1064 } break; 1065 case UPDATED_MEDIA_STATUS: { 1066 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1067 boolean reportStatus = msg.arg1 == 1; 1068 boolean doGc = msg.arg2 == 1; 1069 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1070 if (doGc) { 1071 // Force a gc to clear up stale containers. 1072 Runtime.getRuntime().gc(); 1073 } 1074 if (msg.obj != null) { 1075 @SuppressWarnings("unchecked") 1076 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1077 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1078 // Unload containers 1079 unloadAllContainers(args); 1080 } 1081 if (reportStatus) { 1082 try { 1083 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1084 PackageHelper.getMountService().finishMediaUpdate(); 1085 } catch (RemoteException e) { 1086 Log.e(TAG, "MountService not running?"); 1087 } 1088 } 1089 } break; 1090 case WRITE_SETTINGS: { 1091 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1092 synchronized (mPackages) { 1093 removeMessages(WRITE_SETTINGS); 1094 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1095 mSettings.writeLPr(); 1096 mDirtyUsers.clear(); 1097 } 1098 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1099 } break; 1100 case WRITE_PACKAGE_RESTRICTIONS: { 1101 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1102 synchronized (mPackages) { 1103 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1104 for (int userId : mDirtyUsers) { 1105 mSettings.writePackageRestrictionsLPr(userId); 1106 } 1107 mDirtyUsers.clear(); 1108 } 1109 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1110 } break; 1111 case CHECK_PENDING_VERIFICATION: { 1112 final int verificationId = msg.arg1; 1113 final PackageVerificationState state = mPendingVerification.get(verificationId); 1114 1115 if ((state != null) && !state.timeoutExtended()) { 1116 final InstallArgs args = state.getInstallArgs(); 1117 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1118 1119 Slog.i(TAG, "Verification timed out for " + originUri); 1120 mPendingVerification.remove(verificationId); 1121 1122 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1123 1124 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1125 Slog.i(TAG, "Continuing with installation of " + originUri); 1126 state.setVerifierResponse(Binder.getCallingUid(), 1127 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1128 broadcastPackageVerified(verificationId, originUri, 1129 PackageManager.VERIFICATION_ALLOW, 1130 state.getInstallArgs().getUser()); 1131 try { 1132 ret = args.copyApk(mContainerService, true); 1133 } catch (RemoteException e) { 1134 Slog.e(TAG, "Could not contact the ContainerService"); 1135 } 1136 } else { 1137 broadcastPackageVerified(verificationId, originUri, 1138 PackageManager.VERIFICATION_REJECT, 1139 state.getInstallArgs().getUser()); 1140 } 1141 1142 processPendingInstall(args, ret); 1143 mHandler.sendEmptyMessage(MCS_UNBIND); 1144 } 1145 break; 1146 } 1147 case PACKAGE_VERIFIED: { 1148 final int verificationId = msg.arg1; 1149 1150 final PackageVerificationState state = mPendingVerification.get(verificationId); 1151 if (state == null) { 1152 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1153 break; 1154 } 1155 1156 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1157 1158 state.setVerifierResponse(response.callerUid, response.code); 1159 1160 if (state.isVerificationComplete()) { 1161 mPendingVerification.remove(verificationId); 1162 1163 final InstallArgs args = state.getInstallArgs(); 1164 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1165 1166 int ret; 1167 if (state.isInstallAllowed()) { 1168 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1169 broadcastPackageVerified(verificationId, originUri, 1170 response.code, state.getInstallArgs().getUser()); 1171 try { 1172 ret = args.copyApk(mContainerService, true); 1173 } catch (RemoteException e) { 1174 Slog.e(TAG, "Could not contact the ContainerService"); 1175 } 1176 } else { 1177 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1178 } 1179 1180 processPendingInstall(args, ret); 1181 1182 mHandler.sendEmptyMessage(MCS_UNBIND); 1183 } 1184 1185 break; 1186 } 1187 } 1188 } 1189 } 1190 1191 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1192 Bundle extras = null; 1193 switch (res.returnCode) { 1194 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1195 extras = new Bundle(); 1196 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1197 res.origPermission); 1198 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1199 res.origPackage); 1200 break; 1201 } 1202 } 1203 return extras; 1204 } 1205 1206 void scheduleWriteSettingsLocked() { 1207 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1208 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1209 } 1210 } 1211 1212 void scheduleWritePackageRestrictionsLocked(int userId) { 1213 if (!sUserManager.exists(userId)) return; 1214 mDirtyUsers.add(userId); 1215 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1216 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1217 } 1218 } 1219 1220 public static final PackageManagerService main(Context context, Installer installer, 1221 boolean factoryTest, boolean onlyCore) { 1222 PackageManagerService m = new PackageManagerService(context, installer, 1223 factoryTest, onlyCore); 1224 ServiceManager.addService("package", m); 1225 return m; 1226 } 1227 1228 static String[] splitString(String str, char sep) { 1229 int count = 1; 1230 int i = 0; 1231 while ((i=str.indexOf(sep, i)) >= 0) { 1232 count++; 1233 i++; 1234 } 1235 1236 String[] res = new String[count]; 1237 i=0; 1238 count = 0; 1239 int lastI=0; 1240 while ((i=str.indexOf(sep, i)) >= 0) { 1241 res[count] = str.substring(lastI, i); 1242 count++; 1243 i++; 1244 lastI = i; 1245 } 1246 res[count] = str.substring(lastI, str.length()); 1247 return res; 1248 } 1249 1250 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1251 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1252 Context.DISPLAY_SERVICE); 1253 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1254 } 1255 1256 public PackageManagerService(Context context, Installer installer, 1257 boolean factoryTest, boolean onlyCore) { 1258 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1259 SystemClock.uptimeMillis()); 1260 1261 if (mSdkVersion <= 0) { 1262 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1263 } 1264 1265 mContext = context; 1266 mFactoryTest = factoryTest; 1267 mOnlyCore = onlyCore; 1268 mMetrics = new DisplayMetrics(); 1269 mSettings = new Settings(context); 1270 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1271 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1272 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1273 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1274 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1275 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1276 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1277 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1278 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1279 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1280 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1281 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1282 1283 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1284 if (separateProcesses != null && separateProcesses.length() > 0) { 1285 if ("*".equals(separateProcesses)) { 1286 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1287 mSeparateProcesses = null; 1288 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1289 } else { 1290 mDefParseFlags = 0; 1291 mSeparateProcesses = separateProcesses.split(","); 1292 Slog.w(TAG, "Running with debug.separate_processes: " 1293 + separateProcesses); 1294 } 1295 } else { 1296 mDefParseFlags = 0; 1297 mSeparateProcesses = null; 1298 } 1299 1300 mInstaller = installer; 1301 1302 getDefaultDisplayMetrics(context, mMetrics); 1303 1304 SystemConfig systemConfig = SystemConfig.getInstance(); 1305 mGlobalGids = systemConfig.getGlobalGids(); 1306 mSystemPermissions = systemConfig.getSystemPermissions(); 1307 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1308 1309 synchronized (mInstallLock) { 1310 // writer 1311 synchronized (mPackages) { 1312 mHandlerThread = new ServiceThread(TAG, 1313 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1314 mHandlerThread.start(); 1315 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1316 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1317 1318 File dataDir = Environment.getDataDirectory(); 1319 mAppDataDir = new File(dataDir, "data"); 1320 mAppInstallDir = new File(dataDir, "app"); 1321 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1322 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1323 mUserAppDataDir = new File(dataDir, "user"); 1324 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1325 1326 sUserManager = new UserManagerService(context, this, 1327 mInstallLock, mPackages); 1328 1329 // Propagate permission configuration in to package manager. 1330 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1331 = systemConfig.getPermissions(); 1332 for (int i=0; i<permConfig.size(); i++) { 1333 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1334 BasePermission bp = mSettings.mPermissions.get(perm.name); 1335 if (bp == null) { 1336 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1337 mSettings.mPermissions.put(perm.name, bp); 1338 } 1339 if (perm.gids != null) { 1340 bp.gids = appendInts(bp.gids, perm.gids); 1341 } 1342 } 1343 1344 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1345 for (int i=0; i<libConfig.size(); i++) { 1346 mSharedLibraries.put(libConfig.keyAt(i), 1347 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1348 } 1349 1350 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1351 1352 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1353 mSdkVersion, mOnlyCore); 1354 1355 String customResolverActivity = Resources.getSystem().getString( 1356 R.string.config_customResolverActivity); 1357 if (TextUtils.isEmpty(customResolverActivity)) { 1358 customResolverActivity = null; 1359 } else { 1360 mCustomResolverComponentName = ComponentName.unflattenFromString( 1361 customResolverActivity); 1362 } 1363 1364 long startTime = SystemClock.uptimeMillis(); 1365 1366 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1367 startTime); 1368 1369 // Set flag to monitor and not change apk file paths when 1370 // scanning install directories. 1371 int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1372 1373 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1374 1375 /** 1376 * Add everything in the in the boot class path to the 1377 * list of process files because dexopt will have been run 1378 * if necessary during zygote startup. 1379 */ 1380 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1381 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1382 1383 if (bootClassPath != null) { 1384 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1385 for (String element : bootClassPathElements) { 1386 alreadyDexOpted.add(element); 1387 } 1388 } else { 1389 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1390 } 1391 1392 if (systemServerClassPath != null) { 1393 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1394 for (String element : systemServerClassPathElements) { 1395 alreadyDexOpted.add(element); 1396 } 1397 } else { 1398 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1399 } 1400 1401 boolean didDexOptLibraryOrTool = false; 1402 1403 final List<String> allInstructionSets = getAllInstructionSets(); 1404 final String[] dexCodeInstructionSets = 1405 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1406 1407 /** 1408 * Ensure all external libraries have had dexopt run on them. 1409 */ 1410 if (mSharedLibraries.size() > 0) { 1411 // NOTE: For now, we're compiling these system "shared libraries" 1412 // (and framework jars) into all available architectures. It's possible 1413 // to compile them only when we come across an app that uses them (there's 1414 // already logic for that in scanPackageLI) but that adds some complexity. 1415 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1416 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1417 final String lib = libEntry.path; 1418 if (lib == null) { 1419 continue; 1420 } 1421 1422 try { 1423 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1424 dexCodeInstructionSet, 1425 false); 1426 if (dexoptRequired != DexFile.UP_TO_DATE) { 1427 alreadyDexOpted.add(lib); 1428 1429 // The list of "shared libraries" we have at this point is 1430 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1431 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1432 } else { 1433 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1434 } 1435 didDexOptLibraryOrTool = true; 1436 } 1437 } catch (FileNotFoundException e) { 1438 Slog.w(TAG, "Library not found: " + lib); 1439 } catch (IOException e) { 1440 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1441 + e.getMessage()); 1442 } 1443 } 1444 } 1445 } 1446 1447 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1448 1449 // Gross hack for now: we know this file doesn't contain any 1450 // code, so don't dexopt it to avoid the resulting log spew. 1451 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1452 1453 // Gross hack for now: we know this file is only part of 1454 // the boot class path for art, so don't dexopt it to 1455 // avoid the resulting log spew. 1456 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1457 1458 /** 1459 * And there are a number of commands implemented in Java, which 1460 * we currently need to do the dexopt on so that they can be 1461 * run from a non-root shell. 1462 */ 1463 String[] frameworkFiles = frameworkDir.list(); 1464 if (frameworkFiles != null) { 1465 // TODO: We could compile these only for the most preferred ABI. We should 1466 // first double check that the dex files for these commands are not referenced 1467 // by other system apps. 1468 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1469 for (int i=0; i<frameworkFiles.length; i++) { 1470 File libPath = new File(frameworkDir, frameworkFiles[i]); 1471 String path = libPath.getPath(); 1472 // Skip the file if we already did it. 1473 if (alreadyDexOpted.contains(path)) { 1474 continue; 1475 } 1476 // Skip the file if it is not a type we want to dexopt. 1477 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1478 continue; 1479 } 1480 try { 1481 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1482 dexCodeInstructionSet, 1483 false); 1484 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1485 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1486 didDexOptLibraryOrTool = true; 1487 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1488 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1489 didDexOptLibraryOrTool = true; 1490 } 1491 } catch (FileNotFoundException e) { 1492 Slog.w(TAG, "Jar not found: " + path); 1493 } catch (IOException e) { 1494 Slog.w(TAG, "Exception reading jar: " + path, e); 1495 } 1496 } 1497 } 1498 } 1499 1500 if (didDexOptLibraryOrTool) { 1501 // If we dexopted a library or tool, then something on the system has 1502 // changed. Consider this significant, and wipe away all other 1503 // existing dexopt files to ensure we don't leave any dangling around. 1504 // 1505 // TODO: This should be revisited because it isn't as good an indicator 1506 // as it used to be. It used to include the boot classpath but at some point 1507 // DexFile.isDexOptNeeded started returning false for the boot 1508 // class path files in all cases. It is very possible in a 1509 // small maintenance release update that the library and tool 1510 // jars may be unchanged but APK could be removed resulting in 1511 // unused dalvik-cache files. 1512 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1513 mInstaller.pruneDexCache(dexCodeInstructionSet); 1514 } 1515 1516 // Additionally, delete all dex files from the root directory 1517 // since there shouldn't be any there anyway, unless we're upgrading 1518 // from an older OS version or a build that contained the "old" style 1519 // flat scheme. 1520 mInstaller.pruneDexCache("."); 1521 } 1522 1523 // Collect vendor overlay packages. 1524 // (Do this before scanning any apps.) 1525 // For security and version matching reason, only consider 1526 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1527 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1528 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1529 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1530 1531 // Find base frameworks (resource packages without code). 1532 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1533 | PackageParser.PARSE_IS_SYSTEM_DIR 1534 | PackageParser.PARSE_IS_PRIVILEGED, 1535 scanFlags | SCAN_NO_DEX, 0); 1536 1537 // Collected privileged system packages. 1538 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1539 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1540 | PackageParser.PARSE_IS_SYSTEM_DIR 1541 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1542 1543 // Collect ordinary system packages. 1544 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1545 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1546 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1547 1548 // Collect all vendor packages. 1549 File vendorAppDir = new File("/vendor/app"); 1550 try { 1551 vendorAppDir = vendorAppDir.getCanonicalFile(); 1552 } catch (IOException e) { 1553 // failed to look up canonical path, continue with original one 1554 } 1555 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1556 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1557 1558 // Collect all OEM packages. 1559 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1560 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1561 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1562 1563 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1564 mInstaller.moveFiles(); 1565 1566 // Prune any system packages that no longer exist. 1567 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 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 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1595 + "; removing system app"); 1596 removePackageLI(ps, true); 1597 } 1598 1599 continue; 1600 } 1601 1602 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1603 psit.remove(); 1604 String msg = "System package " + ps.name 1605 + " no longer exists; wiping its data"; 1606 reportSettingsProblem(Log.WARN, msg); 1607 removeDataDirsLI(ps.name); 1608 } else { 1609 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1610 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1611 possiblyDeletedUpdatedSystemApps.add(ps.name); 1612 } 1613 } 1614 } 1615 } 1616 1617 //look for any incomplete package installations 1618 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1619 //clean up list 1620 for(int i = 0; i < deletePkgsList.size(); i++) { 1621 //clean up here 1622 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1623 } 1624 //delete tmp files 1625 deleteTempPackageFiles(); 1626 1627 // Remove any shared userIDs that have no associated packages 1628 mSettings.pruneSharedUsersLPw(); 1629 1630 if (!mOnlyCore) { 1631 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1632 SystemClock.uptimeMillis()); 1633 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1634 1635 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1636 scanFlags, 0); 1637 1638 /** 1639 * Remove disable package settings for any updated system 1640 * apps that were removed via an OTA. If they're not a 1641 * previously-updated app, remove them completely. 1642 * Otherwise, just revoke their system-level permissions. 1643 */ 1644 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1645 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1646 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1647 1648 String msg; 1649 if (deletedPkg == null) { 1650 msg = "Updated system package " + deletedAppName 1651 + " no longer exists; wiping its data"; 1652 removeDataDirsLI(deletedAppName); 1653 } else { 1654 msg = "Updated system app + " + deletedAppName 1655 + " no longer present; removing system privileges for " 1656 + deletedAppName; 1657 1658 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1659 1660 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1661 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1662 } 1663 reportSettingsProblem(Log.WARN, msg); 1664 } 1665 } 1666 1667 // Now that we know all of the shared libraries, update all clients to have 1668 // the correct library paths. 1669 updateAllSharedLibrariesLPw(); 1670 1671 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1672 // NOTE: We ignore potential failures here during a system scan (like 1673 // the rest of the commands above) because there's precious little we 1674 // can do about it. A settings error is reported, though. 1675 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1676 false /* force dexopt */, false /* defer dexopt */); 1677 } 1678 1679 // Now that we know all the packages we are keeping, 1680 // read and update their last usage times. 1681 mPackageUsage.readLP(); 1682 1683 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1684 SystemClock.uptimeMillis()); 1685 Slog.i(TAG, "Time to scan packages: " 1686 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1687 + " seconds"); 1688 1689 // If the platform SDK has changed since the last time we booted, 1690 // we need to re-grant app permission to catch any new ones that 1691 // appear. This is really a hack, and means that apps can in some 1692 // cases get permissions that the user didn't initially explicitly 1693 // allow... it would be nice to have some better way to handle 1694 // this situation. 1695 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1696 != mSdkVersion; 1697 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1698 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1699 + "; regranting permissions for internal storage"); 1700 mSettings.mInternalSdkPlatform = mSdkVersion; 1701 1702 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1703 | (regrantPermissions 1704 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1705 : 0)); 1706 1707 // If this is the first boot, and it is a normal boot, then 1708 // we need to initialize the default preferred apps. 1709 if (!mRestoredSettings && !onlyCore) { 1710 mSettings.readDefaultPreferredAppsLPw(this, 0); 1711 } 1712 1713 // If this is first boot after an OTA, and a normal boot, then 1714 // we need to clear code cache directories. 1715 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1716 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1717 for (String pkgName : mSettings.mPackages.keySet()) { 1718 deleteCodeCacheDirsLI(pkgName); 1719 } 1720 mSettings.mFingerprint = Build.FINGERPRINT; 1721 } 1722 1723 // All the changes are done during package scanning. 1724 mSettings.updateInternalDatabaseVersion(); 1725 1726 // can downgrade to reader 1727 mSettings.writeLPr(); 1728 1729 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1730 SystemClock.uptimeMillis()); 1731 1732 1733 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1734 } // synchronized (mPackages) 1735 } // synchronized (mInstallLock) 1736 1737 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1738 1739 // Now after opening every single application zip, make sure they 1740 // are all flushed. Not really needed, but keeps things nice and 1741 // tidy. 1742 Runtime.getRuntime().gc(); 1743 } 1744 1745 @Override 1746 public boolean isFirstBoot() { 1747 return !mRestoredSettings; 1748 } 1749 1750 @Override 1751 public boolean isOnlyCoreApps() { 1752 return mOnlyCore; 1753 } 1754 1755 private String getRequiredVerifierLPr() { 1756 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1757 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1758 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1759 1760 String requiredVerifier = null; 1761 1762 final int N = receivers.size(); 1763 for (int i = 0; i < N; i++) { 1764 final ResolveInfo info = receivers.get(i); 1765 1766 if (info.activityInfo == null) { 1767 continue; 1768 } 1769 1770 final String packageName = info.activityInfo.packageName; 1771 1772 final PackageSetting ps = mSettings.mPackages.get(packageName); 1773 if (ps == null) { 1774 continue; 1775 } 1776 1777 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1778 if (!gp.grantedPermissions 1779 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1780 continue; 1781 } 1782 1783 if (requiredVerifier != null) { 1784 throw new RuntimeException("There can be only one required verifier"); 1785 } 1786 1787 requiredVerifier = packageName; 1788 } 1789 1790 return requiredVerifier; 1791 } 1792 1793 @Override 1794 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1795 throws RemoteException { 1796 try { 1797 return super.onTransact(code, data, reply, flags); 1798 } catch (RuntimeException e) { 1799 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1800 Slog.wtf(TAG, "Package Manager Crash", e); 1801 } 1802 throw e; 1803 } 1804 } 1805 1806 void cleanupInstallFailedPackage(PackageSetting ps) { 1807 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1808 removeDataDirsLI(ps.name); 1809 1810 // TODO: try cleaning up codePath directory contents first, since it 1811 // might be a cluster 1812 1813 if (ps.codePath != null) { 1814 if (!ps.codePath.delete()) { 1815 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1816 } 1817 } 1818 if (ps.resourcePath != null) { 1819 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1820 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1821 } 1822 } 1823 mSettings.removePackageLPw(ps.name); 1824 } 1825 1826 static int[] appendInts(int[] cur, int[] add) { 1827 if (add == null) return cur; 1828 if (cur == null) return add; 1829 final int N = add.length; 1830 for (int i=0; i<N; i++) { 1831 cur = appendInt(cur, add[i]); 1832 } 1833 return cur; 1834 } 1835 1836 static int[] removeInts(int[] cur, int[] rem) { 1837 if (rem == null) return cur; 1838 if (cur == null) return cur; 1839 final int N = rem.length; 1840 for (int i=0; i<N; i++) { 1841 cur = removeInt(cur, rem[i]); 1842 } 1843 return cur; 1844 } 1845 1846 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1847 if (!sUserManager.exists(userId)) return null; 1848 final PackageSetting ps = (PackageSetting) p.mExtras; 1849 if (ps == null) { 1850 return null; 1851 } 1852 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1853 final PackageUserState state = ps.readUserState(userId); 1854 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1855 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1856 state, userId); 1857 } 1858 1859 @Override 1860 public boolean isPackageAvailable(String packageName, int userId) { 1861 if (!sUserManager.exists(userId)) return false; 1862 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1863 synchronized (mPackages) { 1864 PackageParser.Package p = mPackages.get(packageName); 1865 if (p != null) { 1866 final PackageSetting ps = (PackageSetting) p.mExtras; 1867 if (ps != null) { 1868 final PackageUserState state = ps.readUserState(userId); 1869 if (state != null) { 1870 return PackageParser.isAvailable(state); 1871 } 1872 } 1873 } 1874 } 1875 return false; 1876 } 1877 1878 @Override 1879 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1880 if (!sUserManager.exists(userId)) return null; 1881 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1882 // reader 1883 synchronized (mPackages) { 1884 PackageParser.Package p = mPackages.get(packageName); 1885 if (DEBUG_PACKAGE_INFO) 1886 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1887 if (p != null) { 1888 return generatePackageInfo(p, flags, userId); 1889 } 1890 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1891 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1892 } 1893 } 1894 return null; 1895 } 1896 1897 @Override 1898 public String[] currentToCanonicalPackageNames(String[] names) { 1899 String[] out = new String[names.length]; 1900 // reader 1901 synchronized (mPackages) { 1902 for (int i=names.length-1; i>=0; i--) { 1903 PackageSetting ps = mSettings.mPackages.get(names[i]); 1904 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1905 } 1906 } 1907 return out; 1908 } 1909 1910 @Override 1911 public String[] canonicalToCurrentPackageNames(String[] names) { 1912 String[] out = new String[names.length]; 1913 // reader 1914 synchronized (mPackages) { 1915 for (int i=names.length-1; i>=0; i--) { 1916 String cur = mSettings.mRenamedPackages.get(names[i]); 1917 out[i] = cur != null ? cur : names[i]; 1918 } 1919 } 1920 return out; 1921 } 1922 1923 @Override 1924 public int getPackageUid(String packageName, int userId) { 1925 if (!sUserManager.exists(userId)) return -1; 1926 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1927 // reader 1928 synchronized (mPackages) { 1929 PackageParser.Package p = mPackages.get(packageName); 1930 if(p != null) { 1931 return UserHandle.getUid(userId, p.applicationInfo.uid); 1932 } 1933 PackageSetting ps = mSettings.mPackages.get(packageName); 1934 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1935 return -1; 1936 } 1937 p = ps.pkg; 1938 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1939 } 1940 } 1941 1942 @Override 1943 public int[] getPackageGids(String packageName) { 1944 // reader 1945 synchronized (mPackages) { 1946 PackageParser.Package p = mPackages.get(packageName); 1947 if (DEBUG_PACKAGE_INFO) 1948 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1949 if (p != null) { 1950 final PackageSetting ps = (PackageSetting)p.mExtras; 1951 return ps.getGids(); 1952 } 1953 } 1954 // stupid thing to indicate an error. 1955 return new int[0]; 1956 } 1957 1958 static final PermissionInfo generatePermissionInfo( 1959 BasePermission bp, int flags) { 1960 if (bp.perm != null) { 1961 return PackageParser.generatePermissionInfo(bp.perm, flags); 1962 } 1963 PermissionInfo pi = new PermissionInfo(); 1964 pi.name = bp.name; 1965 pi.packageName = bp.sourcePackage; 1966 pi.nonLocalizedLabel = bp.name; 1967 pi.protectionLevel = bp.protectionLevel; 1968 return pi; 1969 } 1970 1971 @Override 1972 public PermissionInfo getPermissionInfo(String name, int flags) { 1973 // reader 1974 synchronized (mPackages) { 1975 final BasePermission p = mSettings.mPermissions.get(name); 1976 if (p != null) { 1977 return generatePermissionInfo(p, flags); 1978 } 1979 return null; 1980 } 1981 } 1982 1983 @Override 1984 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1985 // reader 1986 synchronized (mPackages) { 1987 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1988 for (BasePermission p : mSettings.mPermissions.values()) { 1989 if (group == null) { 1990 if (p.perm == null || p.perm.info.group == null) { 1991 out.add(generatePermissionInfo(p, flags)); 1992 } 1993 } else { 1994 if (p.perm != null && group.equals(p.perm.info.group)) { 1995 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1996 } 1997 } 1998 } 1999 2000 if (out.size() > 0) { 2001 return out; 2002 } 2003 return mPermissionGroups.containsKey(group) ? out : null; 2004 } 2005 } 2006 2007 @Override 2008 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2009 // reader 2010 synchronized (mPackages) { 2011 return PackageParser.generatePermissionGroupInfo( 2012 mPermissionGroups.get(name), flags); 2013 } 2014 } 2015 2016 @Override 2017 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2018 // reader 2019 synchronized (mPackages) { 2020 final int N = mPermissionGroups.size(); 2021 ArrayList<PermissionGroupInfo> out 2022 = new ArrayList<PermissionGroupInfo>(N); 2023 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2024 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2025 } 2026 return out; 2027 } 2028 } 2029 2030 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2031 int userId) { 2032 if (!sUserManager.exists(userId)) return null; 2033 PackageSetting ps = mSettings.mPackages.get(packageName); 2034 if (ps != null) { 2035 if (ps.pkg == null) { 2036 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2037 flags, userId); 2038 if (pInfo != null) { 2039 return pInfo.applicationInfo; 2040 } 2041 return null; 2042 } 2043 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2044 ps.readUserState(userId), userId); 2045 } 2046 return null; 2047 } 2048 2049 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2050 int userId) { 2051 if (!sUserManager.exists(userId)) return null; 2052 PackageSetting ps = mSettings.mPackages.get(packageName); 2053 if (ps != null) { 2054 PackageParser.Package pkg = ps.pkg; 2055 if (pkg == null) { 2056 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2057 return null; 2058 } 2059 // Only data remains, so we aren't worried about code paths 2060 pkg = new PackageParser.Package(packageName); 2061 pkg.applicationInfo.packageName = packageName; 2062 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2063 pkg.applicationInfo.dataDir = 2064 getDataPathForPackage(packageName, 0).getPath(); 2065 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2066 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2067 } 2068 return generatePackageInfo(pkg, flags, userId); 2069 } 2070 return null; 2071 } 2072 2073 @Override 2074 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2075 if (!sUserManager.exists(userId)) return null; 2076 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2077 // writer 2078 synchronized (mPackages) { 2079 PackageParser.Package p = mPackages.get(packageName); 2080 if (DEBUG_PACKAGE_INFO) Log.v( 2081 TAG, "getApplicationInfo " + packageName 2082 + ": " + p); 2083 if (p != null) { 2084 PackageSetting ps = mSettings.mPackages.get(packageName); 2085 if (ps == null) return null; 2086 // Note: isEnabledLP() does not apply here - always return info 2087 return PackageParser.generateApplicationInfo( 2088 p, flags, ps.readUserState(userId), userId); 2089 } 2090 if ("android".equals(packageName)||"system".equals(packageName)) { 2091 return mAndroidApplication; 2092 } 2093 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2094 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2095 } 2096 } 2097 return null; 2098 } 2099 2100 2101 @Override 2102 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2103 mContext.enforceCallingOrSelfPermission( 2104 android.Manifest.permission.CLEAR_APP_CACHE, null); 2105 // Queue up an async operation since clearing cache may take a little while. 2106 mHandler.post(new Runnable() { 2107 public void run() { 2108 mHandler.removeCallbacks(this); 2109 int retCode = -1; 2110 synchronized (mInstallLock) { 2111 retCode = mInstaller.freeCache(freeStorageSize); 2112 if (retCode < 0) { 2113 Slog.w(TAG, "Couldn't clear application caches"); 2114 } 2115 } 2116 if (observer != null) { 2117 try { 2118 observer.onRemoveCompleted(null, (retCode >= 0)); 2119 } catch (RemoteException e) { 2120 Slog.w(TAG, "RemoveException when invoking call back"); 2121 } 2122 } 2123 } 2124 }); 2125 } 2126 2127 @Override 2128 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2129 mContext.enforceCallingOrSelfPermission( 2130 android.Manifest.permission.CLEAR_APP_CACHE, null); 2131 // Queue up an async operation since clearing cache may take a little while. 2132 mHandler.post(new Runnable() { 2133 public void run() { 2134 mHandler.removeCallbacks(this); 2135 int retCode = -1; 2136 synchronized (mInstallLock) { 2137 retCode = mInstaller.freeCache(freeStorageSize); 2138 if (retCode < 0) { 2139 Slog.w(TAG, "Couldn't clear application caches"); 2140 } 2141 } 2142 if(pi != null) { 2143 try { 2144 // Callback via pending intent 2145 int code = (retCode >= 0) ? 1 : 0; 2146 pi.sendIntent(null, code, null, 2147 null, null); 2148 } catch (SendIntentException e1) { 2149 Slog.i(TAG, "Failed to send pending intent"); 2150 } 2151 } 2152 } 2153 }); 2154 } 2155 2156 void freeStorage(long freeStorageSize) throws IOException { 2157 synchronized (mInstallLock) { 2158 if (mInstaller.freeCache(freeStorageSize) < 0) { 2159 throw new IOException("Failed to free enough space"); 2160 } 2161 } 2162 } 2163 2164 @Override 2165 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2166 if (!sUserManager.exists(userId)) return null; 2167 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2168 synchronized (mPackages) { 2169 PackageParser.Activity a = mActivities.mActivities.get(component); 2170 2171 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2172 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2173 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2174 if (ps == null) return null; 2175 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2176 userId); 2177 } 2178 if (mResolveComponentName.equals(component)) { 2179 return mResolveActivity; 2180 } 2181 } 2182 return null; 2183 } 2184 2185 @Override 2186 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2187 String resolvedType) { 2188 synchronized (mPackages) { 2189 PackageParser.Activity a = mActivities.mActivities.get(component); 2190 if (a == null) { 2191 return false; 2192 } 2193 for (int i=0; i<a.intents.size(); i++) { 2194 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2195 intent.getData(), intent.getCategories(), TAG) >= 0) { 2196 return true; 2197 } 2198 } 2199 return false; 2200 } 2201 } 2202 2203 @Override 2204 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2205 if (!sUserManager.exists(userId)) return null; 2206 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2207 synchronized (mPackages) { 2208 PackageParser.Activity a = mReceivers.mActivities.get(component); 2209 if (DEBUG_PACKAGE_INFO) Log.v( 2210 TAG, "getReceiverInfo " + component + ": " + a); 2211 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2212 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2213 if (ps == null) return null; 2214 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2215 userId); 2216 } 2217 } 2218 return null; 2219 } 2220 2221 @Override 2222 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2223 if (!sUserManager.exists(userId)) return null; 2224 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2225 synchronized (mPackages) { 2226 PackageParser.Service s = mServices.mServices.get(component); 2227 if (DEBUG_PACKAGE_INFO) Log.v( 2228 TAG, "getServiceInfo " + component + ": " + s); 2229 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2230 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2231 if (ps == null) return null; 2232 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2233 userId); 2234 } 2235 } 2236 return null; 2237 } 2238 2239 @Override 2240 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2241 if (!sUserManager.exists(userId)) return null; 2242 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2243 synchronized (mPackages) { 2244 PackageParser.Provider p = mProviders.mProviders.get(component); 2245 if (DEBUG_PACKAGE_INFO) Log.v( 2246 TAG, "getProviderInfo " + component + ": " + p); 2247 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2248 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2249 if (ps == null) return null; 2250 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2251 userId); 2252 } 2253 } 2254 return null; 2255 } 2256 2257 @Override 2258 public String[] getSystemSharedLibraryNames() { 2259 Set<String> libSet; 2260 synchronized (mPackages) { 2261 libSet = mSharedLibraries.keySet(); 2262 int size = libSet.size(); 2263 if (size > 0) { 2264 String[] libs = new String[size]; 2265 libSet.toArray(libs); 2266 return libs; 2267 } 2268 } 2269 return null; 2270 } 2271 2272 @Override 2273 public FeatureInfo[] getSystemAvailableFeatures() { 2274 Collection<FeatureInfo> featSet; 2275 synchronized (mPackages) { 2276 featSet = mAvailableFeatures.values(); 2277 int size = featSet.size(); 2278 if (size > 0) { 2279 FeatureInfo[] features = new FeatureInfo[size+1]; 2280 featSet.toArray(features); 2281 FeatureInfo fi = new FeatureInfo(); 2282 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2283 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2284 features[size] = fi; 2285 return features; 2286 } 2287 } 2288 return null; 2289 } 2290 2291 @Override 2292 public boolean hasSystemFeature(String name) { 2293 synchronized (mPackages) { 2294 return mAvailableFeatures.containsKey(name); 2295 } 2296 } 2297 2298 private void checkValidCaller(int uid, int userId) { 2299 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2300 return; 2301 2302 throw new SecurityException("Caller uid=" + uid 2303 + " is not privileged to communicate with user=" + userId); 2304 } 2305 2306 @Override 2307 public int checkPermission(String permName, String pkgName) { 2308 synchronized (mPackages) { 2309 PackageParser.Package p = mPackages.get(pkgName); 2310 if (p != null && p.mExtras != null) { 2311 PackageSetting ps = (PackageSetting)p.mExtras; 2312 if (ps.sharedUser != null) { 2313 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2314 return PackageManager.PERMISSION_GRANTED; 2315 } 2316 } else if (ps.grantedPermissions.contains(permName)) { 2317 return PackageManager.PERMISSION_GRANTED; 2318 } 2319 } 2320 } 2321 return PackageManager.PERMISSION_DENIED; 2322 } 2323 2324 @Override 2325 public int checkUidPermission(String permName, int uid) { 2326 synchronized (mPackages) { 2327 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2328 if (obj != null) { 2329 GrantedPermissions gp = (GrantedPermissions)obj; 2330 if (gp.grantedPermissions.contains(permName)) { 2331 return PackageManager.PERMISSION_GRANTED; 2332 } 2333 } else { 2334 HashSet<String> perms = mSystemPermissions.get(uid); 2335 if (perms != null && perms.contains(permName)) { 2336 return PackageManager.PERMISSION_GRANTED; 2337 } 2338 } 2339 } 2340 return PackageManager.PERMISSION_DENIED; 2341 } 2342 2343 /** 2344 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2345 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2346 * @param message the message to log on security exception 2347 */ 2348 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2349 String message) { 2350 if (userId < 0) { 2351 throw new IllegalArgumentException("Invalid userId " + userId); 2352 } 2353 if (userId == UserHandle.getUserId(callingUid)) return; 2354 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2355 if (requireFullPermission) { 2356 mContext.enforceCallingOrSelfPermission( 2357 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2358 } else { 2359 try { 2360 mContext.enforceCallingOrSelfPermission( 2361 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2362 } catch (SecurityException se) { 2363 mContext.enforceCallingOrSelfPermission( 2364 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2365 } 2366 } 2367 } 2368 } 2369 2370 private BasePermission findPermissionTreeLP(String permName) { 2371 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2372 if (permName.startsWith(bp.name) && 2373 permName.length() > bp.name.length() && 2374 permName.charAt(bp.name.length()) == '.') { 2375 return bp; 2376 } 2377 } 2378 return null; 2379 } 2380 2381 private BasePermission checkPermissionTreeLP(String permName) { 2382 if (permName != null) { 2383 BasePermission bp = findPermissionTreeLP(permName); 2384 if (bp != null) { 2385 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2386 return bp; 2387 } 2388 throw new SecurityException("Calling uid " 2389 + Binder.getCallingUid() 2390 + " is not allowed to add to permission tree " 2391 + bp.name + " owned by uid " + bp.uid); 2392 } 2393 } 2394 throw new SecurityException("No permission tree found for " + permName); 2395 } 2396 2397 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2398 if (s1 == null) { 2399 return s2 == null; 2400 } 2401 if (s2 == null) { 2402 return false; 2403 } 2404 if (s1.getClass() != s2.getClass()) { 2405 return false; 2406 } 2407 return s1.equals(s2); 2408 } 2409 2410 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2411 if (pi1.icon != pi2.icon) return false; 2412 if (pi1.logo != pi2.logo) return false; 2413 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2414 if (!compareStrings(pi1.name, pi2.name)) return false; 2415 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2416 // We'll take care of setting this one. 2417 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2418 // These are not currently stored in settings. 2419 //if (!compareStrings(pi1.group, pi2.group)) return false; 2420 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2421 //if (pi1.labelRes != pi2.labelRes) return false; 2422 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2423 return true; 2424 } 2425 2426 int permissionInfoFootprint(PermissionInfo info) { 2427 int size = info.name.length(); 2428 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2429 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2430 return size; 2431 } 2432 2433 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2434 int size = 0; 2435 for (BasePermission perm : mSettings.mPermissions.values()) { 2436 if (perm.uid == tree.uid) { 2437 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2438 } 2439 } 2440 return size; 2441 } 2442 2443 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2444 // We calculate the max size of permissions defined by this uid and throw 2445 // if that plus the size of 'info' would exceed our stated maximum. 2446 if (tree.uid != Process.SYSTEM_UID) { 2447 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2448 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2449 throw new SecurityException("Permission tree size cap exceeded"); 2450 } 2451 } 2452 } 2453 2454 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2455 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2456 throw new SecurityException("Label must be specified in permission"); 2457 } 2458 BasePermission tree = checkPermissionTreeLP(info.name); 2459 BasePermission bp = mSettings.mPermissions.get(info.name); 2460 boolean added = bp == null; 2461 boolean changed = true; 2462 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2463 if (added) { 2464 enforcePermissionCapLocked(info, tree); 2465 bp = new BasePermission(info.name, tree.sourcePackage, 2466 BasePermission.TYPE_DYNAMIC); 2467 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2468 throw new SecurityException( 2469 "Not allowed to modify non-dynamic permission " 2470 + info.name); 2471 } else { 2472 if (bp.protectionLevel == fixedLevel 2473 && bp.perm.owner.equals(tree.perm.owner) 2474 && bp.uid == tree.uid 2475 && comparePermissionInfos(bp.perm.info, info)) { 2476 changed = false; 2477 } 2478 } 2479 bp.protectionLevel = fixedLevel; 2480 info = new PermissionInfo(info); 2481 info.protectionLevel = fixedLevel; 2482 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2483 bp.perm.info.packageName = tree.perm.info.packageName; 2484 bp.uid = tree.uid; 2485 if (added) { 2486 mSettings.mPermissions.put(info.name, bp); 2487 } 2488 if (changed) { 2489 if (!async) { 2490 mSettings.writeLPr(); 2491 } else { 2492 scheduleWriteSettingsLocked(); 2493 } 2494 } 2495 return added; 2496 } 2497 2498 @Override 2499 public boolean addPermission(PermissionInfo info) { 2500 synchronized (mPackages) { 2501 return addPermissionLocked(info, false); 2502 } 2503 } 2504 2505 @Override 2506 public boolean addPermissionAsync(PermissionInfo info) { 2507 synchronized (mPackages) { 2508 return addPermissionLocked(info, true); 2509 } 2510 } 2511 2512 @Override 2513 public void removePermission(String name) { 2514 synchronized (mPackages) { 2515 checkPermissionTreeLP(name); 2516 BasePermission bp = mSettings.mPermissions.get(name); 2517 if (bp != null) { 2518 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2519 throw new SecurityException( 2520 "Not allowed to modify non-dynamic permission " 2521 + name); 2522 } 2523 mSettings.mPermissions.remove(name); 2524 mSettings.writeLPr(); 2525 } 2526 } 2527 } 2528 2529 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2530 int index = pkg.requestedPermissions.indexOf(bp.name); 2531 if (index == -1) { 2532 throw new SecurityException("Package " + pkg.packageName 2533 + " has not requested permission " + bp.name); 2534 } 2535 boolean isNormal = 2536 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2537 == PermissionInfo.PROTECTION_NORMAL); 2538 boolean isDangerous = 2539 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2540 == PermissionInfo.PROTECTION_DANGEROUS); 2541 boolean isDevelopment = 2542 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2543 2544 if (!isNormal && !isDangerous && !isDevelopment) { 2545 throw new SecurityException("Permission " + bp.name 2546 + " is not a changeable permission type"); 2547 } 2548 2549 if (isNormal || isDangerous) { 2550 if (pkg.requestedPermissionsRequired.get(index)) { 2551 throw new SecurityException("Can't change " + bp.name 2552 + ". It is required by the application"); 2553 } 2554 } 2555 } 2556 2557 @Override 2558 public void grantPermission(String packageName, String permissionName) { 2559 mContext.enforceCallingOrSelfPermission( 2560 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2561 synchronized (mPackages) { 2562 final PackageParser.Package pkg = mPackages.get(packageName); 2563 if (pkg == null) { 2564 throw new IllegalArgumentException("Unknown package: " + packageName); 2565 } 2566 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2567 if (bp == null) { 2568 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2569 } 2570 2571 checkGrantRevokePermissions(pkg, bp); 2572 2573 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2574 if (ps == null) { 2575 return; 2576 } 2577 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2578 if (gp.grantedPermissions.add(permissionName)) { 2579 if (ps.haveGids) { 2580 gp.gids = appendInts(gp.gids, bp.gids); 2581 } 2582 mSettings.writeLPr(); 2583 } 2584 } 2585 } 2586 2587 @Override 2588 public void revokePermission(String packageName, String permissionName) { 2589 int changedAppId = -1; 2590 2591 synchronized (mPackages) { 2592 final PackageParser.Package pkg = mPackages.get(packageName); 2593 if (pkg == null) { 2594 throw new IllegalArgumentException("Unknown package: " + packageName); 2595 } 2596 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2597 mContext.enforceCallingOrSelfPermission( 2598 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2599 } 2600 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2601 if (bp == null) { 2602 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2603 } 2604 2605 checkGrantRevokePermissions(pkg, bp); 2606 2607 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2608 if (ps == null) { 2609 return; 2610 } 2611 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2612 if (gp.grantedPermissions.remove(permissionName)) { 2613 gp.grantedPermissions.remove(permissionName); 2614 if (ps.haveGids) { 2615 gp.gids = removeInts(gp.gids, bp.gids); 2616 } 2617 mSettings.writeLPr(); 2618 changedAppId = ps.appId; 2619 } 2620 } 2621 2622 if (changedAppId >= 0) { 2623 // We changed the perm on someone, kill its processes. 2624 IActivityManager am = ActivityManagerNative.getDefault(); 2625 if (am != null) { 2626 final int callingUserId = UserHandle.getCallingUserId(); 2627 final long ident = Binder.clearCallingIdentity(); 2628 try { 2629 //XXX we should only revoke for the calling user's app permissions, 2630 // but for now we impact all users. 2631 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2632 // "revoke " + permissionName); 2633 int[] users = sUserManager.getUserIds(); 2634 for (int user : users) { 2635 am.killUid(UserHandle.getUid(user, changedAppId), 2636 "revoke " + permissionName); 2637 } 2638 } catch (RemoteException e) { 2639 } finally { 2640 Binder.restoreCallingIdentity(ident); 2641 } 2642 } 2643 } 2644 } 2645 2646 @Override 2647 public boolean isProtectedBroadcast(String actionName) { 2648 synchronized (mPackages) { 2649 return mProtectedBroadcasts.contains(actionName); 2650 } 2651 } 2652 2653 @Override 2654 public int checkSignatures(String pkg1, String pkg2) { 2655 synchronized (mPackages) { 2656 final PackageParser.Package p1 = mPackages.get(pkg1); 2657 final PackageParser.Package p2 = mPackages.get(pkg2); 2658 if (p1 == null || p1.mExtras == null 2659 || p2 == null || p2.mExtras == null) { 2660 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2661 } 2662 return compareSignatures(p1.mSignatures, p2.mSignatures); 2663 } 2664 } 2665 2666 @Override 2667 public int checkUidSignatures(int uid1, int uid2) { 2668 // Map to base uids. 2669 uid1 = UserHandle.getAppId(uid1); 2670 uid2 = UserHandle.getAppId(uid2); 2671 // reader 2672 synchronized (mPackages) { 2673 Signature[] s1; 2674 Signature[] s2; 2675 Object obj = mSettings.getUserIdLPr(uid1); 2676 if (obj != null) { 2677 if (obj instanceof SharedUserSetting) { 2678 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2679 } else if (obj instanceof PackageSetting) { 2680 s1 = ((PackageSetting)obj).signatures.mSignatures; 2681 } else { 2682 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2683 } 2684 } else { 2685 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2686 } 2687 obj = mSettings.getUserIdLPr(uid2); 2688 if (obj != null) { 2689 if (obj instanceof SharedUserSetting) { 2690 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2691 } else if (obj instanceof PackageSetting) { 2692 s2 = ((PackageSetting)obj).signatures.mSignatures; 2693 } else { 2694 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2695 } 2696 } else { 2697 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2698 } 2699 return compareSignatures(s1, s2); 2700 } 2701 } 2702 2703 /** 2704 * Compares two sets of signatures. Returns: 2705 * <br /> 2706 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2707 * <br /> 2708 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2709 * <br /> 2710 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2711 * <br /> 2712 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2713 * <br /> 2714 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2715 */ 2716 static int compareSignatures(Signature[] s1, Signature[] s2) { 2717 if (s1 == null) { 2718 return s2 == null 2719 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2720 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2721 } 2722 2723 if (s2 == null) { 2724 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2725 } 2726 2727 if (s1.length != s2.length) { 2728 return PackageManager.SIGNATURE_NO_MATCH; 2729 } 2730 2731 // Since both signature sets are of size 1, we can compare without HashSets. 2732 if (s1.length == 1) { 2733 return s1[0].equals(s2[0]) ? 2734 PackageManager.SIGNATURE_MATCH : 2735 PackageManager.SIGNATURE_NO_MATCH; 2736 } 2737 2738 HashSet<Signature> set1 = new HashSet<Signature>(); 2739 for (Signature sig : s1) { 2740 set1.add(sig); 2741 } 2742 HashSet<Signature> set2 = new HashSet<Signature>(); 2743 for (Signature sig : s2) { 2744 set2.add(sig); 2745 } 2746 // Make sure s2 contains all signatures in s1. 2747 if (set1.equals(set2)) { 2748 return PackageManager.SIGNATURE_MATCH; 2749 } 2750 return PackageManager.SIGNATURE_NO_MATCH; 2751 } 2752 2753 /** 2754 * If the database version for this type of package (internal storage or 2755 * external storage) is less than the version where package signatures 2756 * were updated, return true. 2757 */ 2758 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2759 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2760 DatabaseVersion.SIGNATURE_END_ENTITY)) 2761 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2762 DatabaseVersion.SIGNATURE_END_ENTITY)); 2763 } 2764 2765 /** 2766 * Used for backward compatibility to make sure any packages with 2767 * certificate chains get upgraded to the new style. {@code existingSigs} 2768 * will be in the old format (since they were stored on disk from before the 2769 * system upgrade) and {@code scannedSigs} will be in the newer format. 2770 */ 2771 private int compareSignaturesCompat(PackageSignatures existingSigs, 2772 PackageParser.Package scannedPkg) { 2773 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2774 return PackageManager.SIGNATURE_NO_MATCH; 2775 } 2776 2777 HashSet<Signature> existingSet = new HashSet<Signature>(); 2778 for (Signature sig : existingSigs.mSignatures) { 2779 existingSet.add(sig); 2780 } 2781 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2782 for (Signature sig : scannedPkg.mSignatures) { 2783 try { 2784 Signature[] chainSignatures = sig.getChainSignatures(); 2785 for (Signature chainSig : chainSignatures) { 2786 scannedCompatSet.add(chainSig); 2787 } 2788 } catch (CertificateEncodingException e) { 2789 scannedCompatSet.add(sig); 2790 } 2791 } 2792 /* 2793 * Make sure the expanded scanned set contains all signatures in the 2794 * existing one. 2795 */ 2796 if (scannedCompatSet.equals(existingSet)) { 2797 // Migrate the old signatures to the new scheme. 2798 existingSigs.assignSignatures(scannedPkg.mSignatures); 2799 // The new KeySets will be re-added later in the scanning process. 2800 synchronized (mPackages) { 2801 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2802 } 2803 return PackageManager.SIGNATURE_MATCH; 2804 } 2805 return PackageManager.SIGNATURE_NO_MATCH; 2806 } 2807 2808 @Override 2809 public String[] getPackagesForUid(int uid) { 2810 uid = UserHandle.getAppId(uid); 2811 // reader 2812 synchronized (mPackages) { 2813 Object obj = mSettings.getUserIdLPr(uid); 2814 if (obj instanceof SharedUserSetting) { 2815 final SharedUserSetting sus = (SharedUserSetting) obj; 2816 final int N = sus.packages.size(); 2817 final String[] res = new String[N]; 2818 final Iterator<PackageSetting> it = sus.packages.iterator(); 2819 int i = 0; 2820 while (it.hasNext()) { 2821 res[i++] = it.next().name; 2822 } 2823 return res; 2824 } else if (obj instanceof PackageSetting) { 2825 final PackageSetting ps = (PackageSetting) obj; 2826 return new String[] { ps.name }; 2827 } 2828 } 2829 return null; 2830 } 2831 2832 @Override 2833 public String getNameForUid(int uid) { 2834 // reader 2835 synchronized (mPackages) { 2836 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2837 if (obj instanceof SharedUserSetting) { 2838 final SharedUserSetting sus = (SharedUserSetting) obj; 2839 return sus.name + ":" + sus.userId; 2840 } else if (obj instanceof PackageSetting) { 2841 final PackageSetting ps = (PackageSetting) obj; 2842 return ps.name; 2843 } 2844 } 2845 return null; 2846 } 2847 2848 @Override 2849 public int getUidForSharedUser(String sharedUserName) { 2850 if(sharedUserName == null) { 2851 return -1; 2852 } 2853 // reader 2854 synchronized (mPackages) { 2855 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2856 if (suid == null) { 2857 return -1; 2858 } 2859 return suid.userId; 2860 } 2861 } 2862 2863 @Override 2864 public int getFlagsForUid(int uid) { 2865 synchronized (mPackages) { 2866 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2867 if (obj instanceof SharedUserSetting) { 2868 final SharedUserSetting sus = (SharedUserSetting) obj; 2869 return sus.pkgFlags; 2870 } else if (obj instanceof PackageSetting) { 2871 final PackageSetting ps = (PackageSetting) obj; 2872 return ps.pkgFlags; 2873 } 2874 } 2875 return 0; 2876 } 2877 2878 @Override 2879 public String[] getAppOpPermissionPackages(String permissionName) { 2880 synchronized (mPackages) { 2881 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2882 if (pkgs == null) { 2883 return null; 2884 } 2885 return pkgs.toArray(new String[pkgs.size()]); 2886 } 2887 } 2888 2889 @Override 2890 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2891 int flags, int userId) { 2892 if (!sUserManager.exists(userId)) return null; 2893 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2894 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2895 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2896 } 2897 2898 @Override 2899 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2900 IntentFilter filter, int match, ComponentName activity) { 2901 final int userId = UserHandle.getCallingUserId(); 2902 if (DEBUG_PREFERRED) { 2903 Log.v(TAG, "setLastChosenActivity intent=" + intent 2904 + " resolvedType=" + resolvedType 2905 + " flags=" + flags 2906 + " filter=" + filter 2907 + " match=" + match 2908 + " activity=" + activity); 2909 filter.dump(new PrintStreamPrinter(System.out), " "); 2910 } 2911 intent.setComponent(null); 2912 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2913 // Find any earlier preferred or last chosen entries and nuke them 2914 findPreferredActivity(intent, resolvedType, 2915 flags, query, 0, false, true, false, userId); 2916 // Add the new activity as the last chosen for this filter 2917 addPreferredActivityInternal(filter, match, null, activity, false, userId, 2918 "Setting last chosen"); 2919 } 2920 2921 @Override 2922 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2923 final int userId = UserHandle.getCallingUserId(); 2924 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2925 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2926 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2927 false, false, false, userId); 2928 } 2929 2930 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2931 int flags, List<ResolveInfo> query, int userId) { 2932 if (query != null) { 2933 final int N = query.size(); 2934 if (N == 1) { 2935 return query.get(0); 2936 } else if (N > 1) { 2937 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2938 // If there is more than one activity with the same priority, 2939 // then let the user decide between them. 2940 ResolveInfo r0 = query.get(0); 2941 ResolveInfo r1 = query.get(1); 2942 if (DEBUG_INTENT_MATCHING || debug) { 2943 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2944 + r1.activityInfo.name + "=" + r1.priority); 2945 } 2946 // If the first activity has a higher priority, or a different 2947 // default, then it is always desireable to pick it. 2948 if (r0.priority != r1.priority 2949 || r0.preferredOrder != r1.preferredOrder 2950 || r0.isDefault != r1.isDefault) { 2951 return query.get(0); 2952 } 2953 // If we have saved a preference for a preferred activity for 2954 // this Intent, use that. 2955 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2956 flags, query, r0.priority, true, false, debug, userId); 2957 if (ri != null) { 2958 return ri; 2959 } 2960 if (userId != 0) { 2961 ri = new ResolveInfo(mResolveInfo); 2962 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2963 ri.activityInfo.applicationInfo = new ApplicationInfo( 2964 ri.activityInfo.applicationInfo); 2965 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2966 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2967 return ri; 2968 } 2969 return mResolveInfo; 2970 } 2971 } 2972 return null; 2973 } 2974 2975 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2976 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2977 final int N = query.size(); 2978 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2979 .get(userId); 2980 // Get the list of persistent preferred activities that handle the intent 2981 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2982 List<PersistentPreferredActivity> pprefs = ppir != null 2983 ? ppir.queryIntent(intent, resolvedType, 2984 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2985 : null; 2986 if (pprefs != null && pprefs.size() > 0) { 2987 final int M = pprefs.size(); 2988 for (int i=0; i<M; i++) { 2989 final PersistentPreferredActivity ppa = pprefs.get(i); 2990 if (DEBUG_PREFERRED || debug) { 2991 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2992 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2993 + "\n component=" + ppa.mComponent); 2994 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2995 } 2996 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2997 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2998 if (DEBUG_PREFERRED || debug) { 2999 Slog.v(TAG, "Found persistent preferred activity:"); 3000 if (ai != null) { 3001 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3002 } else { 3003 Slog.v(TAG, " null"); 3004 } 3005 } 3006 if (ai == null) { 3007 // This previously registered persistent preferred activity 3008 // component is no longer known. Ignore it and do NOT remove it. 3009 continue; 3010 } 3011 for (int j=0; j<N; j++) { 3012 final ResolveInfo ri = query.get(j); 3013 if (!ri.activityInfo.applicationInfo.packageName 3014 .equals(ai.applicationInfo.packageName)) { 3015 continue; 3016 } 3017 if (!ri.activityInfo.name.equals(ai.name)) { 3018 continue; 3019 } 3020 // Found a persistent preference that can handle the intent. 3021 if (DEBUG_PREFERRED || debug) { 3022 Slog.v(TAG, "Returning persistent preferred activity: " + 3023 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3024 } 3025 return ri; 3026 } 3027 } 3028 } 3029 return null; 3030 } 3031 3032 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3033 List<ResolveInfo> query, int priority, boolean always, 3034 boolean removeMatches, boolean debug, int userId) { 3035 if (!sUserManager.exists(userId)) return null; 3036 // writer 3037 synchronized (mPackages) { 3038 if (intent.getSelector() != null) { 3039 intent = intent.getSelector(); 3040 } 3041 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3042 3043 // Try to find a matching persistent preferred activity. 3044 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3045 debug, userId); 3046 3047 // If a persistent preferred activity matched, use it. 3048 if (pri != null) { 3049 return pri; 3050 } 3051 3052 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3053 // Get the list of preferred activities that handle the intent 3054 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3055 List<PreferredActivity> prefs = pir != null 3056 ? pir.queryIntent(intent, resolvedType, 3057 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3058 : null; 3059 if (prefs != null && prefs.size() > 0) { 3060 // First figure out how good the original match set is. 3061 // We will only allow preferred activities that came 3062 // from the same match quality. 3063 int match = 0; 3064 3065 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3066 3067 final int N = query.size(); 3068 for (int j=0; j<N; j++) { 3069 final ResolveInfo ri = query.get(j); 3070 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3071 + ": 0x" + Integer.toHexString(match)); 3072 if (ri.match > match) { 3073 match = ri.match; 3074 } 3075 } 3076 3077 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3078 + Integer.toHexString(match)); 3079 3080 match &= IntentFilter.MATCH_CATEGORY_MASK; 3081 final int M = prefs.size(); 3082 for (int i=0; i<M; i++) { 3083 final PreferredActivity pa = prefs.get(i); 3084 if (DEBUG_PREFERRED || debug) { 3085 Slog.v(TAG, "Checking PreferredActivity ds=" 3086 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3087 + "\n component=" + pa.mPref.mComponent); 3088 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3089 } 3090 if (pa.mPref.mMatch != match) { 3091 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3092 + Integer.toHexString(pa.mPref.mMatch)); 3093 continue; 3094 } 3095 // If it's not an "always" type preferred activity and that's what we're 3096 // looking for, skip it. 3097 if (always && !pa.mPref.mAlways) { 3098 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3099 continue; 3100 } 3101 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3102 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3103 if (DEBUG_PREFERRED || debug) { 3104 Slog.v(TAG, "Found preferred activity:"); 3105 if (ai != null) { 3106 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3107 } else { 3108 Slog.v(TAG, " null"); 3109 } 3110 } 3111 if (ai == null) { 3112 // This previously registered preferred activity 3113 // component is no longer known. Most likely an update 3114 // to the app was installed and in the new version this 3115 // component no longer exists. Clean it up by removing 3116 // it from the preferred activities list, and skip it. 3117 Slog.w(TAG, "Removing dangling preferred activity: " 3118 + pa.mPref.mComponent); 3119 pir.removeFilter(pa); 3120 continue; 3121 } 3122 for (int j=0; j<N; j++) { 3123 final ResolveInfo ri = query.get(j); 3124 if (!ri.activityInfo.applicationInfo.packageName 3125 .equals(ai.applicationInfo.packageName)) { 3126 continue; 3127 } 3128 if (!ri.activityInfo.name.equals(ai.name)) { 3129 continue; 3130 } 3131 3132 if (removeMatches) { 3133 pir.removeFilter(pa); 3134 if (DEBUG_PREFERRED) { 3135 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3136 } 3137 break; 3138 } 3139 3140 // Okay we found a previously set preferred or last chosen app. 3141 // If the result set is different from when this 3142 // was created, we need to clear it and re-ask the 3143 // user their preference, if we're looking for an "always" type entry. 3144 if (always && !pa.mPref.sameSet(query, priority)) { 3145 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3146 + intent + " type " + resolvedType); 3147 if (DEBUG_PREFERRED) { 3148 Slog.v(TAG, "Removing preferred activity since set changed " 3149 + pa.mPref.mComponent); 3150 } 3151 pir.removeFilter(pa); 3152 // Re-add the filter as a "last chosen" entry (!always) 3153 PreferredActivity lastChosen = new PreferredActivity( 3154 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3155 pir.addFilter(lastChosen); 3156 mSettings.writePackageRestrictionsLPr(userId); 3157 return null; 3158 } 3159 3160 // Yay! Either the set matched or we're looking for the last chosen 3161 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3162 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3163 mSettings.writePackageRestrictionsLPr(userId); 3164 return ri; 3165 } 3166 } 3167 } 3168 mSettings.writePackageRestrictionsLPr(userId); 3169 } 3170 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3171 return null; 3172 } 3173 3174 /* 3175 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3176 */ 3177 @Override 3178 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3179 int targetUserId) { 3180 mContext.enforceCallingOrSelfPermission( 3181 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3182 List<CrossProfileIntentFilter> matches = 3183 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3184 if (matches != null) { 3185 int size = matches.size(); 3186 for (int i = 0; i < size; i++) { 3187 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3188 } 3189 } 3190 ArrayList<String> packageNames = null; 3191 SparseArray<ArrayList<String>> fromSource = 3192 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3193 if (fromSource != null) { 3194 packageNames = fromSource.get(targetUserId); 3195 if (packageNames != null) { 3196 // We need the package name, so we try to resolve with the loosest flags possible 3197 List<ResolveInfo> resolveInfos = mActivities.queryIntent(intent, resolvedType, 3198 PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3199 int count = resolveInfos.size(); 3200 for (int i = 0; i < count; i++) { 3201 ResolveInfo resolveInfo = resolveInfos.get(i); 3202 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3203 return true; 3204 } 3205 } 3206 } 3207 } 3208 return false; 3209 } 3210 3211 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3212 String resolvedType, int userId) { 3213 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3214 if (resolver != null) { 3215 return resolver.queryIntent(intent, resolvedType, false, userId); 3216 } 3217 return null; 3218 } 3219 3220 @Override 3221 public List<ResolveInfo> queryIntentActivities(Intent intent, 3222 String resolvedType, int flags, int userId) { 3223 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3224 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3225 ComponentName comp = intent.getComponent(); 3226 if (comp == null) { 3227 if (intent.getSelector() != null) { 3228 intent = intent.getSelector(); 3229 comp = intent.getComponent(); 3230 } 3231 } 3232 3233 if (comp != null) { 3234 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3235 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3236 if (ai != null) { 3237 final ResolveInfo ri = new ResolveInfo(); 3238 ri.activityInfo = ai; 3239 list.add(ri); 3240 } 3241 return list; 3242 } 3243 3244 // reader 3245 synchronized (mPackages) { 3246 final String pkgName = intent.getPackage(); 3247 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3248 if (pkgName == null) { 3249 ResolveInfo resolveInfo = null; 3250 if (queryCrossProfile) { 3251 // Check if the intent needs to be forwarded to another user for this package 3252 ArrayList<ResolveInfo> crossProfileResult = 3253 queryIntentActivitiesCrossProfilePackage( 3254 intent, resolvedType, flags, userId); 3255 if (!crossProfileResult.isEmpty()) { 3256 // Skip the current profile 3257 return crossProfileResult; 3258 } 3259 List<CrossProfileIntentFilter> matchingFilters = 3260 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3261 // Check for results that need to skip the current profile. 3262 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3263 resolvedType, flags, userId); 3264 if (resolveInfo != null) { 3265 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3266 result.add(resolveInfo); 3267 return result; 3268 } 3269 // Check for cross profile results. 3270 resolveInfo = queryCrossProfileIntents( 3271 matchingFilters, intent, resolvedType, flags, userId); 3272 } 3273 // Check for results in the current profile. 3274 List<ResolveInfo> result = mActivities.queryIntent( 3275 intent, resolvedType, flags, userId); 3276 if (resolveInfo != null) { 3277 result.add(resolveInfo); 3278 Collections.sort(result, mResolvePrioritySorter); 3279 } 3280 return result; 3281 } 3282 final PackageParser.Package pkg = mPackages.get(pkgName); 3283 if (pkg != null) { 3284 if (queryCrossProfile) { 3285 ArrayList<ResolveInfo> crossProfileResult = 3286 queryIntentActivitiesCrossProfilePackage( 3287 intent, resolvedType, flags, userId, pkg, pkgName); 3288 if (!crossProfileResult.isEmpty()) { 3289 // Skip the current profile 3290 return crossProfileResult; 3291 } 3292 } 3293 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3294 pkg.activities, userId); 3295 } 3296 return new ArrayList<ResolveInfo>(); 3297 } 3298 } 3299 3300 private ResolveInfo querySkipCurrentProfileIntents( 3301 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3302 int flags, int sourceUserId) { 3303 if (matchingFilters != null) { 3304 int size = matchingFilters.size(); 3305 for (int i = 0; i < size; i ++) { 3306 CrossProfileIntentFilter filter = matchingFilters.get(i); 3307 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3308 // Checking if there are activities in the target user that can handle the 3309 // intent. 3310 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3311 flags, sourceUserId); 3312 if (resolveInfo != null) { 3313 return resolveInfo; 3314 } 3315 } 3316 } 3317 } 3318 return null; 3319 } 3320 3321 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3322 Intent intent, String resolvedType, int flags, int userId) { 3323 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3324 SparseArray<ArrayList<String>> sourceForwardingInfo = 3325 mSettings.mCrossProfilePackageInfo.get(userId); 3326 if (sourceForwardingInfo != null) { 3327 int NI = sourceForwardingInfo.size(); 3328 for (int i = 0; i < NI; i++) { 3329 int targetUserId = sourceForwardingInfo.keyAt(i); 3330 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3331 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3332 intent, resolvedType, flags, targetUserId); 3333 int NJ = resolveInfos.size(); 3334 for (int j = 0; j < NJ; j++) { 3335 ResolveInfo resolveInfo = resolveInfos.get(j); 3336 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3337 matchingResolveInfos.add(createForwardingResolveInfo( 3338 resolveInfo.filter, userId, targetUserId)); 3339 } 3340 } 3341 } 3342 } 3343 return matchingResolveInfos; 3344 } 3345 3346 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3347 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3348 String packageName) { 3349 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3350 SparseArray<ArrayList<String>> sourceForwardingInfo = 3351 mSettings.mCrossProfilePackageInfo.get(userId); 3352 if (sourceForwardingInfo != null) { 3353 int NI = sourceForwardingInfo.size(); 3354 for (int i = 0; i < NI; i++) { 3355 int targetUserId = sourceForwardingInfo.keyAt(i); 3356 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3357 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3358 intent, resolvedType, flags, pkg.activities, targetUserId); 3359 int NJ = resolveInfos.size(); 3360 for (int j = 0; j < NJ; j++) { 3361 ResolveInfo resolveInfo = resolveInfos.get(j); 3362 matchingResolveInfos.add(createForwardingResolveInfo( 3363 resolveInfo.filter, userId, targetUserId)); 3364 } 3365 } 3366 } 3367 } 3368 return matchingResolveInfos; 3369 } 3370 3371 // Return matching ResolveInfo if any for skip current profile intent filters. 3372 private ResolveInfo queryCrossProfileIntents( 3373 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3374 int flags, int sourceUserId) { 3375 if (matchingFilters != null) { 3376 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3377 // match the same intent. For performance reasons, it is better not to 3378 // run queryIntent twice for the same userId 3379 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3380 int size = matchingFilters.size(); 3381 for (int i = 0; i < size; i++) { 3382 CrossProfileIntentFilter filter = matchingFilters.get(i); 3383 int targetUserId = filter.getTargetUserId(); 3384 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3385 && !alreadyTriedUserIds.get(targetUserId)) { 3386 // Checking if there are activities in the target user that can handle the 3387 // intent. 3388 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3389 flags, sourceUserId); 3390 if (resolveInfo != null) return resolveInfo; 3391 alreadyTriedUserIds.put(targetUserId, true); 3392 } 3393 } 3394 } 3395 return null; 3396 } 3397 3398 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3399 String resolvedType, int flags, int sourceUserId) { 3400 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3401 resolvedType, flags, filter.getTargetUserId()); 3402 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3403 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3404 } 3405 return null; 3406 } 3407 3408 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3409 int sourceUserId, int targetUserId) { 3410 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3411 String className; 3412 if (targetUserId == UserHandle.USER_OWNER) { 3413 className = FORWARD_INTENT_TO_USER_OWNER; 3414 } else { 3415 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3416 } 3417 ComponentName forwardingActivityComponentName = new ComponentName( 3418 mAndroidApplication.packageName, className); 3419 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3420 sourceUserId); 3421 if (targetUserId == UserHandle.USER_OWNER) { 3422 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3423 forwardingResolveInfo.noResourceId = true; 3424 } 3425 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3426 forwardingResolveInfo.priority = 0; 3427 forwardingResolveInfo.preferredOrder = 0; 3428 forwardingResolveInfo.match = 0; 3429 forwardingResolveInfo.isDefault = true; 3430 forwardingResolveInfo.filter = filter; 3431 forwardingResolveInfo.targetUserId = targetUserId; 3432 return forwardingResolveInfo; 3433 } 3434 3435 @Override 3436 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3437 Intent[] specifics, String[] specificTypes, Intent intent, 3438 String resolvedType, int flags, int userId) { 3439 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3440 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3441 "query intent activity options"); 3442 final String resultsAction = intent.getAction(); 3443 3444 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3445 | PackageManager.GET_RESOLVED_FILTER, userId); 3446 3447 if (DEBUG_INTENT_MATCHING) { 3448 Log.v(TAG, "Query " + intent + ": " + results); 3449 } 3450 3451 int specificsPos = 0; 3452 int N; 3453 3454 // todo: note that the algorithm used here is O(N^2). This 3455 // isn't a problem in our current environment, but if we start running 3456 // into situations where we have more than 5 or 10 matches then this 3457 // should probably be changed to something smarter... 3458 3459 // First we go through and resolve each of the specific items 3460 // that were supplied, taking care of removing any corresponding 3461 // duplicate items in the generic resolve list. 3462 if (specifics != null) { 3463 for (int i=0; i<specifics.length; i++) { 3464 final Intent sintent = specifics[i]; 3465 if (sintent == null) { 3466 continue; 3467 } 3468 3469 if (DEBUG_INTENT_MATCHING) { 3470 Log.v(TAG, "Specific #" + i + ": " + sintent); 3471 } 3472 3473 String action = sintent.getAction(); 3474 if (resultsAction != null && resultsAction.equals(action)) { 3475 // If this action was explicitly requested, then don't 3476 // remove things that have it. 3477 action = null; 3478 } 3479 3480 ResolveInfo ri = null; 3481 ActivityInfo ai = null; 3482 3483 ComponentName comp = sintent.getComponent(); 3484 if (comp == null) { 3485 ri = resolveIntent( 3486 sintent, 3487 specificTypes != null ? specificTypes[i] : null, 3488 flags, userId); 3489 if (ri == null) { 3490 continue; 3491 } 3492 if (ri == mResolveInfo) { 3493 // ACK! Must do something better with this. 3494 } 3495 ai = ri.activityInfo; 3496 comp = new ComponentName(ai.applicationInfo.packageName, 3497 ai.name); 3498 } else { 3499 ai = getActivityInfo(comp, flags, userId); 3500 if (ai == null) { 3501 continue; 3502 } 3503 } 3504 3505 // Look for any generic query activities that are duplicates 3506 // of this specific one, and remove them from the results. 3507 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3508 N = results.size(); 3509 int j; 3510 for (j=specificsPos; j<N; j++) { 3511 ResolveInfo sri = results.get(j); 3512 if ((sri.activityInfo.name.equals(comp.getClassName()) 3513 && sri.activityInfo.applicationInfo.packageName.equals( 3514 comp.getPackageName())) 3515 || (action != null && sri.filter.matchAction(action))) { 3516 results.remove(j); 3517 if (DEBUG_INTENT_MATCHING) Log.v( 3518 TAG, "Removing duplicate item from " + j 3519 + " due to specific " + specificsPos); 3520 if (ri == null) { 3521 ri = sri; 3522 } 3523 j--; 3524 N--; 3525 } 3526 } 3527 3528 // Add this specific item to its proper place. 3529 if (ri == null) { 3530 ri = new ResolveInfo(); 3531 ri.activityInfo = ai; 3532 } 3533 results.add(specificsPos, ri); 3534 ri.specificIndex = i; 3535 specificsPos++; 3536 } 3537 } 3538 3539 // Now we go through the remaining generic results and remove any 3540 // duplicate actions that are found here. 3541 N = results.size(); 3542 for (int i=specificsPos; i<N-1; i++) { 3543 final ResolveInfo rii = results.get(i); 3544 if (rii.filter == null) { 3545 continue; 3546 } 3547 3548 // Iterate over all of the actions of this result's intent 3549 // filter... typically this should be just one. 3550 final Iterator<String> it = rii.filter.actionsIterator(); 3551 if (it == null) { 3552 continue; 3553 } 3554 while (it.hasNext()) { 3555 final String action = it.next(); 3556 if (resultsAction != null && resultsAction.equals(action)) { 3557 // If this action was explicitly requested, then don't 3558 // remove things that have it. 3559 continue; 3560 } 3561 for (int j=i+1; j<N; j++) { 3562 final ResolveInfo rij = results.get(j); 3563 if (rij.filter != null && rij.filter.hasAction(action)) { 3564 results.remove(j); 3565 if (DEBUG_INTENT_MATCHING) Log.v( 3566 TAG, "Removing duplicate item from " + j 3567 + " due to action " + action + " at " + i); 3568 j--; 3569 N--; 3570 } 3571 } 3572 } 3573 3574 // If the caller didn't request filter information, drop it now 3575 // so we don't have to marshall/unmarshall it. 3576 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3577 rii.filter = null; 3578 } 3579 } 3580 3581 // Filter out the caller activity if so requested. 3582 if (caller != null) { 3583 N = results.size(); 3584 for (int i=0; i<N; i++) { 3585 ActivityInfo ainfo = results.get(i).activityInfo; 3586 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3587 && caller.getClassName().equals(ainfo.name)) { 3588 results.remove(i); 3589 break; 3590 } 3591 } 3592 } 3593 3594 // If the caller didn't request filter information, 3595 // drop them now so we don't have to 3596 // marshall/unmarshall it. 3597 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3598 N = results.size(); 3599 for (int i=0; i<N; i++) { 3600 results.get(i).filter = null; 3601 } 3602 } 3603 3604 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3605 return results; 3606 } 3607 3608 @Override 3609 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3610 int userId) { 3611 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3612 ComponentName comp = intent.getComponent(); 3613 if (comp == null) { 3614 if (intent.getSelector() != null) { 3615 intent = intent.getSelector(); 3616 comp = intent.getComponent(); 3617 } 3618 } 3619 if (comp != null) { 3620 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3621 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3622 if (ai != null) { 3623 ResolveInfo ri = new ResolveInfo(); 3624 ri.activityInfo = ai; 3625 list.add(ri); 3626 } 3627 return list; 3628 } 3629 3630 // reader 3631 synchronized (mPackages) { 3632 String pkgName = intent.getPackage(); 3633 if (pkgName == null) { 3634 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3635 } 3636 final PackageParser.Package pkg = mPackages.get(pkgName); 3637 if (pkg != null) { 3638 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3639 userId); 3640 } 3641 return null; 3642 } 3643 } 3644 3645 @Override 3646 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3647 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3648 if (!sUserManager.exists(userId)) return null; 3649 if (query != null) { 3650 if (query.size() >= 1) { 3651 // If there is more than one service with the same priority, 3652 // just arbitrarily pick the first one. 3653 return query.get(0); 3654 } 3655 } 3656 return null; 3657 } 3658 3659 @Override 3660 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3661 int userId) { 3662 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3663 ComponentName comp = intent.getComponent(); 3664 if (comp == null) { 3665 if (intent.getSelector() != null) { 3666 intent = intent.getSelector(); 3667 comp = intent.getComponent(); 3668 } 3669 } 3670 if (comp != null) { 3671 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3672 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3673 if (si != null) { 3674 final ResolveInfo ri = new ResolveInfo(); 3675 ri.serviceInfo = si; 3676 list.add(ri); 3677 } 3678 return list; 3679 } 3680 3681 // reader 3682 synchronized (mPackages) { 3683 String pkgName = intent.getPackage(); 3684 if (pkgName == null) { 3685 return mServices.queryIntent(intent, resolvedType, flags, userId); 3686 } 3687 final PackageParser.Package pkg = mPackages.get(pkgName); 3688 if (pkg != null) { 3689 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3690 userId); 3691 } 3692 return null; 3693 } 3694 } 3695 3696 @Override 3697 public List<ResolveInfo> queryIntentContentProviders( 3698 Intent intent, String resolvedType, int flags, int userId) { 3699 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3700 ComponentName comp = intent.getComponent(); 3701 if (comp == null) { 3702 if (intent.getSelector() != null) { 3703 intent = intent.getSelector(); 3704 comp = intent.getComponent(); 3705 } 3706 } 3707 if (comp != null) { 3708 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3709 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3710 if (pi != null) { 3711 final ResolveInfo ri = new ResolveInfo(); 3712 ri.providerInfo = pi; 3713 list.add(ri); 3714 } 3715 return list; 3716 } 3717 3718 // reader 3719 synchronized (mPackages) { 3720 String pkgName = intent.getPackage(); 3721 if (pkgName == null) { 3722 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3723 } 3724 final PackageParser.Package pkg = mPackages.get(pkgName); 3725 if (pkg != null) { 3726 return mProviders.queryIntentForPackage( 3727 intent, resolvedType, flags, pkg.providers, userId); 3728 } 3729 return null; 3730 } 3731 } 3732 3733 @Override 3734 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3735 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3736 3737 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3738 3739 // writer 3740 synchronized (mPackages) { 3741 ArrayList<PackageInfo> list; 3742 if (listUninstalled) { 3743 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3744 for (PackageSetting ps : mSettings.mPackages.values()) { 3745 PackageInfo pi; 3746 if (ps.pkg != null) { 3747 pi = generatePackageInfo(ps.pkg, flags, userId); 3748 } else { 3749 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3750 } 3751 if (pi != null) { 3752 list.add(pi); 3753 } 3754 } 3755 } else { 3756 list = new ArrayList<PackageInfo>(mPackages.size()); 3757 for (PackageParser.Package p : mPackages.values()) { 3758 PackageInfo pi = generatePackageInfo(p, flags, userId); 3759 if (pi != null) { 3760 list.add(pi); 3761 } 3762 } 3763 } 3764 3765 return new ParceledListSlice<PackageInfo>(list); 3766 } 3767 } 3768 3769 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3770 String[] permissions, boolean[] tmp, int flags, int userId) { 3771 int numMatch = 0; 3772 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3773 for (int i=0; i<permissions.length; i++) { 3774 if (gp.grantedPermissions.contains(permissions[i])) { 3775 tmp[i] = true; 3776 numMatch++; 3777 } else { 3778 tmp[i] = false; 3779 } 3780 } 3781 if (numMatch == 0) { 3782 return; 3783 } 3784 PackageInfo pi; 3785 if (ps.pkg != null) { 3786 pi = generatePackageInfo(ps.pkg, flags, userId); 3787 } else { 3788 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3789 } 3790 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3791 if (numMatch == permissions.length) { 3792 pi.requestedPermissions = permissions; 3793 } else { 3794 pi.requestedPermissions = new String[numMatch]; 3795 numMatch = 0; 3796 for (int i=0; i<permissions.length; i++) { 3797 if (tmp[i]) { 3798 pi.requestedPermissions[numMatch] = permissions[i]; 3799 numMatch++; 3800 } 3801 } 3802 } 3803 } 3804 list.add(pi); 3805 } 3806 3807 @Override 3808 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3809 String[] permissions, int flags, int userId) { 3810 if (!sUserManager.exists(userId)) return null; 3811 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3812 3813 // writer 3814 synchronized (mPackages) { 3815 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3816 boolean[] tmpBools = new boolean[permissions.length]; 3817 if (listUninstalled) { 3818 for (PackageSetting ps : mSettings.mPackages.values()) { 3819 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3820 } 3821 } else { 3822 for (PackageParser.Package pkg : mPackages.values()) { 3823 PackageSetting ps = (PackageSetting)pkg.mExtras; 3824 if (ps != null) { 3825 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3826 userId); 3827 } 3828 } 3829 } 3830 3831 return new ParceledListSlice<PackageInfo>(list); 3832 } 3833 } 3834 3835 @Override 3836 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3837 if (!sUserManager.exists(userId)) return null; 3838 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3839 3840 // writer 3841 synchronized (mPackages) { 3842 ArrayList<ApplicationInfo> list; 3843 if (listUninstalled) { 3844 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3845 for (PackageSetting ps : mSettings.mPackages.values()) { 3846 ApplicationInfo ai; 3847 if (ps.pkg != null) { 3848 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3849 ps.readUserState(userId), userId); 3850 } else { 3851 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3852 } 3853 if (ai != null) { 3854 list.add(ai); 3855 } 3856 } 3857 } else { 3858 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3859 for (PackageParser.Package p : mPackages.values()) { 3860 if (p.mExtras != null) { 3861 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3862 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3863 if (ai != null) { 3864 list.add(ai); 3865 } 3866 } 3867 } 3868 } 3869 3870 return new ParceledListSlice<ApplicationInfo>(list); 3871 } 3872 } 3873 3874 public List<ApplicationInfo> getPersistentApplications(int flags) { 3875 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3876 3877 // reader 3878 synchronized (mPackages) { 3879 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3880 final int userId = UserHandle.getCallingUserId(); 3881 while (i.hasNext()) { 3882 final PackageParser.Package p = i.next(); 3883 if (p.applicationInfo != null 3884 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3885 && (!mSafeMode || isSystemApp(p))) { 3886 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3887 if (ps != null) { 3888 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3889 ps.readUserState(userId), userId); 3890 if (ai != null) { 3891 finalList.add(ai); 3892 } 3893 } 3894 } 3895 } 3896 } 3897 3898 return finalList; 3899 } 3900 3901 @Override 3902 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3903 if (!sUserManager.exists(userId)) return null; 3904 // reader 3905 synchronized (mPackages) { 3906 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3907 PackageSetting ps = provider != null 3908 ? mSettings.mPackages.get(provider.owner.packageName) 3909 : null; 3910 return ps != null 3911 && mSettings.isEnabledLPr(provider.info, flags, userId) 3912 && (!mSafeMode || (provider.info.applicationInfo.flags 3913 &ApplicationInfo.FLAG_SYSTEM) != 0) 3914 ? PackageParser.generateProviderInfo(provider, flags, 3915 ps.readUserState(userId), userId) 3916 : null; 3917 } 3918 } 3919 3920 /** 3921 * @deprecated 3922 */ 3923 @Deprecated 3924 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3925 // reader 3926 synchronized (mPackages) { 3927 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3928 .entrySet().iterator(); 3929 final int userId = UserHandle.getCallingUserId(); 3930 while (i.hasNext()) { 3931 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3932 PackageParser.Provider p = entry.getValue(); 3933 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3934 3935 if (ps != null && p.syncable 3936 && (!mSafeMode || (p.info.applicationInfo.flags 3937 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3938 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3939 ps.readUserState(userId), userId); 3940 if (info != null) { 3941 outNames.add(entry.getKey()); 3942 outInfo.add(info); 3943 } 3944 } 3945 } 3946 } 3947 } 3948 3949 @Override 3950 public List<ProviderInfo> queryContentProviders(String processName, 3951 int uid, int flags) { 3952 ArrayList<ProviderInfo> finalList = null; 3953 // reader 3954 synchronized (mPackages) { 3955 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3956 final int userId = processName != null ? 3957 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3958 while (i.hasNext()) { 3959 final PackageParser.Provider p = i.next(); 3960 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3961 if (ps != null && p.info.authority != null 3962 && (processName == null 3963 || (p.info.processName.equals(processName) 3964 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3965 && mSettings.isEnabledLPr(p.info, flags, userId) 3966 && (!mSafeMode 3967 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3968 if (finalList == null) { 3969 finalList = new ArrayList<ProviderInfo>(3); 3970 } 3971 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3972 ps.readUserState(userId), userId); 3973 if (info != null) { 3974 finalList.add(info); 3975 } 3976 } 3977 } 3978 } 3979 3980 if (finalList != null) { 3981 Collections.sort(finalList, mProviderInitOrderSorter); 3982 } 3983 3984 return finalList; 3985 } 3986 3987 @Override 3988 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3989 int flags) { 3990 // reader 3991 synchronized (mPackages) { 3992 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3993 return PackageParser.generateInstrumentationInfo(i, flags); 3994 } 3995 } 3996 3997 @Override 3998 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3999 int flags) { 4000 ArrayList<InstrumentationInfo> finalList = 4001 new ArrayList<InstrumentationInfo>(); 4002 4003 // reader 4004 synchronized (mPackages) { 4005 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4006 while (i.hasNext()) { 4007 final PackageParser.Instrumentation p = i.next(); 4008 if (targetPackage == null 4009 || targetPackage.equals(p.info.targetPackage)) { 4010 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4011 flags); 4012 if (ii != null) { 4013 finalList.add(ii); 4014 } 4015 } 4016 } 4017 } 4018 4019 return finalList; 4020 } 4021 4022 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4023 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4024 if (overlays == null) { 4025 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4026 return; 4027 } 4028 for (PackageParser.Package opkg : overlays.values()) { 4029 // Not much to do if idmap fails: we already logged the error 4030 // and we certainly don't want to abort installation of pkg simply 4031 // because an overlay didn't fit properly. For these reasons, 4032 // ignore the return value of createIdmapForPackagePairLI. 4033 createIdmapForPackagePairLI(pkg, opkg); 4034 } 4035 } 4036 4037 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4038 PackageParser.Package opkg) { 4039 if (!opkg.mTrustedOverlay) { 4040 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4041 opkg.baseCodePath + ": overlay not trusted"); 4042 return false; 4043 } 4044 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4045 if (overlaySet == null) { 4046 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4047 opkg.baseCodePath + " but target package has no known overlays"); 4048 return false; 4049 } 4050 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4051 // TODO: generate idmap for split APKs 4052 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4053 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4054 + opkg.baseCodePath); 4055 return false; 4056 } 4057 PackageParser.Package[] overlayArray = 4058 overlaySet.values().toArray(new PackageParser.Package[0]); 4059 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4060 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4061 return p1.mOverlayPriority - p2.mOverlayPriority; 4062 } 4063 }; 4064 Arrays.sort(overlayArray, cmp); 4065 4066 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4067 int i = 0; 4068 for (PackageParser.Package p : overlayArray) { 4069 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4070 } 4071 return true; 4072 } 4073 4074 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4075 final File[] files = dir.listFiles(); 4076 if (ArrayUtils.isEmpty(files)) { 4077 Log.d(TAG, "No files in app dir " + dir); 4078 return; 4079 } 4080 4081 if (DEBUG_PACKAGE_SCANNING) { 4082 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4083 + " flags=0x" + Integer.toHexString(parseFlags)); 4084 } 4085 4086 for (File file : files) { 4087 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4088 && !PackageInstallerService.isStageName(file.getName()); 4089 if (!isPackage) { 4090 // Ignore entries which are not packages 4091 continue; 4092 } 4093 try { 4094 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4095 scanFlags, currentTime, null); 4096 } catch (PackageManagerException e) { 4097 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4098 4099 // Delete invalid userdata apps 4100 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4101 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4102 Slog.w(TAG, "Deleting invalid package at " + file); 4103 if (file.isDirectory()) { 4104 FileUtils.deleteContents(file); 4105 } 4106 file.delete(); 4107 } 4108 } 4109 } 4110 } 4111 4112 private static File getSettingsProblemFile() { 4113 File dataDir = Environment.getDataDirectory(); 4114 File systemDir = new File(dataDir, "system"); 4115 File fname = new File(systemDir, "uiderrors.txt"); 4116 return fname; 4117 } 4118 4119 static void reportSettingsProblem(int priority, String msg) { 4120 try { 4121 File fname = getSettingsProblemFile(); 4122 FileOutputStream out = new FileOutputStream(fname, true); 4123 PrintWriter pw = new FastPrintWriter(out); 4124 SimpleDateFormat formatter = new SimpleDateFormat(); 4125 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4126 pw.println(dateString + ": " + msg); 4127 pw.close(); 4128 FileUtils.setPermissions( 4129 fname.toString(), 4130 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4131 -1, -1); 4132 } catch (java.io.IOException e) { 4133 } 4134 Slog.println(priority, TAG, msg); 4135 } 4136 4137 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4138 PackageParser.Package pkg, File srcFile, int parseFlags) 4139 throws PackageManagerException { 4140 if (ps != null 4141 && ps.codePath.equals(srcFile) 4142 && ps.timeStamp == srcFile.lastModified() 4143 && !isCompatSignatureUpdateNeeded(pkg)) { 4144 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4145 if (ps.signatures.mSignatures != null 4146 && ps.signatures.mSignatures.length != 0 4147 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4148 // Optimization: reuse the existing cached certificates 4149 // if the package appears to be unchanged. 4150 pkg.mSignatures = ps.signatures.mSignatures; 4151 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4152 synchronized (mPackages) { 4153 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4154 } 4155 return; 4156 } 4157 4158 Slog.w(TAG, "PackageSetting for " + ps.name 4159 + " is missing signatures. Collecting certs again to recover them."); 4160 } else { 4161 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4162 } 4163 4164 try { 4165 pp.collectCertificates(pkg, parseFlags); 4166 pp.collectManifestDigest(pkg); 4167 } catch (PackageParserException e) { 4168 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4169 + pkg.packageName + ": " + e.getMessage()); 4170 } 4171 } 4172 4173 /* 4174 * Scan a package and return the newly parsed package. 4175 * Returns null in case of errors and the error code is stored in mLastScanError 4176 */ 4177 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4178 long currentTime, UserHandle user) throws PackageManagerException { 4179 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4180 parseFlags |= mDefParseFlags; 4181 PackageParser pp = new PackageParser(); 4182 pp.setSeparateProcesses(mSeparateProcesses); 4183 pp.setOnlyCoreApps(mOnlyCore); 4184 pp.setDisplayMetrics(mMetrics); 4185 4186 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4187 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4188 } 4189 4190 final PackageParser.Package pkg; 4191 try { 4192 pkg = pp.parsePackage(scanFile, parseFlags); 4193 } catch (PackageParserException e) { 4194 throw new PackageManagerException(e.error, 4195 "Failed to scan " + scanFile + ": " + e.getMessage()); 4196 } 4197 4198 PackageSetting ps = null; 4199 PackageSetting updatedPkg; 4200 // reader 4201 synchronized (mPackages) { 4202 // Look to see if we already know about this package. 4203 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4204 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4205 // This package has been renamed to its original name. Let's 4206 // use that. 4207 ps = mSettings.peekPackageLPr(oldName); 4208 } 4209 // If there was no original package, see one for the real package name. 4210 if (ps == null) { 4211 ps = mSettings.peekPackageLPr(pkg.packageName); 4212 } 4213 // Check to see if this package could be hiding/updating a system 4214 // package. Must look for it either under the original or real 4215 // package name depending on our state. 4216 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4217 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4218 } 4219 boolean updatedPkgBetter = false; 4220 // First check if this is a system package that may involve an update 4221 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4222 if (ps != null && !ps.codePath.equals(scanFile)) { 4223 // The path has changed from what was last scanned... check the 4224 // version of the new path against what we have stored to determine 4225 // what to do. 4226 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4227 if (pkg.mVersionCode < ps.versionCode) { 4228 // The system package has been updated and the code path does not match 4229 // Ignore entry. Skip it. 4230 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4231 + " ignored: updated version " + ps.versionCode 4232 + " better than this " + pkg.mVersionCode); 4233 if (!updatedPkg.codePath.equals(scanFile)) { 4234 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4235 + ps.name + " changing from " + updatedPkg.codePathString 4236 + " to " + scanFile); 4237 updatedPkg.codePath = scanFile; 4238 updatedPkg.codePathString = scanFile.toString(); 4239 // This is the point at which we know that the system-disk APK 4240 // for this package has moved during a reboot (e.g. due to an OTA), 4241 // so we need to reevaluate it for privilege policy. 4242 if (locationIsPrivileged(scanFile)) { 4243 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4244 } 4245 } 4246 updatedPkg.pkg = pkg; 4247 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4248 } else { 4249 // The current app on the system partition is better than 4250 // what we have updated to on the data partition; switch 4251 // back to the system partition version. 4252 // At this point, its safely assumed that package installation for 4253 // apps in system partition will go through. If not there won't be a working 4254 // version of the app 4255 // writer 4256 synchronized (mPackages) { 4257 // Just remove the loaded entries from package lists. 4258 mPackages.remove(ps.name); 4259 } 4260 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4261 + "reverting from " + ps.codePathString 4262 + ": new version " + pkg.mVersionCode 4263 + " better than installed " + ps.versionCode); 4264 4265 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4266 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4267 getAppDexInstructionSets(ps)); 4268 synchronized (mInstallLock) { 4269 args.cleanUpResourcesLI(); 4270 } 4271 synchronized (mPackages) { 4272 mSettings.enableSystemPackageLPw(ps.name); 4273 } 4274 updatedPkgBetter = true; 4275 } 4276 } 4277 } 4278 4279 if (updatedPkg != null) { 4280 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4281 // initially 4282 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4283 4284 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4285 // flag set initially 4286 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4287 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4288 } 4289 } 4290 4291 // Verify certificates against what was last scanned 4292 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4293 4294 /* 4295 * A new system app appeared, but we already had a non-system one of the 4296 * same name installed earlier. 4297 */ 4298 boolean shouldHideSystemApp = false; 4299 if (updatedPkg == null && ps != null 4300 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4301 /* 4302 * Check to make sure the signatures match first. If they don't, 4303 * wipe the installed application and its data. 4304 */ 4305 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4306 != PackageManager.SIGNATURE_MATCH) { 4307 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4308 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4309 ps = null; 4310 } else { 4311 /* 4312 * If the newly-added system app is an older version than the 4313 * already installed version, hide it. It will be scanned later 4314 * and re-added like an update. 4315 */ 4316 if (pkg.mVersionCode < ps.versionCode) { 4317 shouldHideSystemApp = true; 4318 } else { 4319 /* 4320 * The newly found system app is a newer version that the 4321 * one previously installed. Simply remove the 4322 * already-installed application and replace it with our own 4323 * while keeping the application data. 4324 */ 4325 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4326 + ps.codePathString + ": new version " + pkg.mVersionCode 4327 + " better than installed " + ps.versionCode); 4328 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4329 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4330 getAppDexInstructionSets(ps)); 4331 synchronized (mInstallLock) { 4332 args.cleanUpResourcesLI(); 4333 } 4334 } 4335 } 4336 } 4337 4338 // The apk is forward locked (not public) if its code and resources 4339 // are kept in different files. (except for app in either system or 4340 // vendor path). 4341 // TODO grab this value from PackageSettings 4342 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4343 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4344 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4345 } 4346 } 4347 4348 // TODO: extend to support forward-locked splits 4349 String resourcePath = null; 4350 String baseResourcePath = null; 4351 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4352 if (ps != null && ps.resourcePathString != null) { 4353 resourcePath = ps.resourcePathString; 4354 baseResourcePath = ps.resourcePathString; 4355 } else { 4356 // Should not happen at all. Just log an error. 4357 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4358 } 4359 } else { 4360 resourcePath = pkg.codePath; 4361 baseResourcePath = pkg.baseCodePath; 4362 } 4363 4364 // Set application objects path explicitly. 4365 pkg.applicationInfo.setCodePath(pkg.codePath); 4366 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4367 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4368 pkg.applicationInfo.setResourcePath(resourcePath); 4369 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4370 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4371 4372 // Note that we invoke the following method only if we are about to unpack an application 4373 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4374 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4375 4376 /* 4377 * If the system app should be overridden by a previously installed 4378 * data, hide the system app now and let the /data/app scan pick it up 4379 * again. 4380 */ 4381 if (shouldHideSystemApp) { 4382 synchronized (mPackages) { 4383 /* 4384 * We have to grant systems permissions before we hide, because 4385 * grantPermissions will assume the package update is trying to 4386 * expand its permissions. 4387 */ 4388 grantPermissionsLPw(pkg, true); 4389 mSettings.disableSystemPackageLPw(pkg.packageName); 4390 } 4391 } 4392 4393 return scannedPkg; 4394 } 4395 4396 private static String fixProcessName(String defProcessName, 4397 String processName, int uid) { 4398 if (processName == null) { 4399 return defProcessName; 4400 } 4401 return processName; 4402 } 4403 4404 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4405 throws PackageManagerException { 4406 if (pkgSetting.signatures.mSignatures != null) { 4407 // Already existing package. Make sure signatures match 4408 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4409 == PackageManager.SIGNATURE_MATCH; 4410 if (!match) { 4411 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4412 == PackageManager.SIGNATURE_MATCH; 4413 } 4414 if (!match) { 4415 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4416 + pkg.packageName + " signatures do not match the " 4417 + "previously installed version; ignoring!"); 4418 } 4419 } 4420 4421 // Check for shared user signatures 4422 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4423 // Already existing package. Make sure signatures match 4424 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4425 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4426 if (!match) { 4427 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4428 == PackageManager.SIGNATURE_MATCH; 4429 } 4430 if (!match) { 4431 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4432 "Package " + pkg.packageName 4433 + " has no signatures that match those in shared user " 4434 + pkgSetting.sharedUser.name + "; ignoring!"); 4435 } 4436 } 4437 } 4438 4439 /** 4440 * Enforces that only the system UID or root's UID can call a method exposed 4441 * via Binder. 4442 * 4443 * @param message used as message if SecurityException is thrown 4444 * @throws SecurityException if the caller is not system or root 4445 */ 4446 private static final void enforceSystemOrRoot(String message) { 4447 final int uid = Binder.getCallingUid(); 4448 if (uid != Process.SYSTEM_UID && uid != 0) { 4449 throw new SecurityException(message); 4450 } 4451 } 4452 4453 @Override 4454 public void performBootDexOpt() { 4455 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4456 4457 final HashSet<PackageParser.Package> pkgs; 4458 synchronized (mPackages) { 4459 pkgs = mDeferredDexOpt; 4460 mDeferredDexOpt = null; 4461 } 4462 4463 if (pkgs != null) { 4464 // Filter out packages that aren't recently used. 4465 // 4466 // The exception is first boot of a non-eng device, which 4467 // should do a full dexopt. 4468 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4469 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4470 // TODO: add a property to control this? 4471 long dexOptLRUThresholdInMinutes; 4472 if (eng) { 4473 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4474 } else { 4475 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4476 } 4477 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4478 4479 int total = pkgs.size(); 4480 int skipped = 0; 4481 long now = System.currentTimeMillis(); 4482 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4483 PackageParser.Package pkg = i.next(); 4484 long then = pkg.mLastPackageUsageTimeInMills; 4485 if (then + dexOptLRUThresholdInMills < now) { 4486 if (DEBUG_DEXOPT) { 4487 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4488 ((then == 0) ? "never" : new Date(then))); 4489 } 4490 i.remove(); 4491 skipped++; 4492 } 4493 } 4494 if (DEBUG_DEXOPT) { 4495 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4496 } 4497 } 4498 4499 int i = 0; 4500 for (PackageParser.Package pkg : pkgs) { 4501 i++; 4502 if (DEBUG_DEXOPT) { 4503 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4504 + ": " + pkg.packageName); 4505 } 4506 if (!isFirstBoot()) { 4507 try { 4508 ActivityManagerNative.getDefault().showBootMessage( 4509 mContext.getResources().getString( 4510 R.string.android_upgrading_apk, 4511 i, pkgs.size()), true); 4512 } catch (RemoteException e) { 4513 } 4514 } 4515 PackageParser.Package p = pkg; 4516 synchronized (mInstallLock) { 4517 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4518 true /* include dependencies */); 4519 } 4520 } 4521 } 4522 } 4523 4524 @Override 4525 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4526 return performDexOpt(packageName, instructionSet, true); 4527 } 4528 4529 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4530 if (info.primaryCpuAbi == null) { 4531 return getPreferredInstructionSet(); 4532 } 4533 4534 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4535 } 4536 4537 public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) { 4538 PackageParser.Package p; 4539 final String targetInstructionSet; 4540 synchronized (mPackages) { 4541 p = mPackages.get(packageName); 4542 if (p == null) { 4543 return false; 4544 } 4545 if (updateUsage) { 4546 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4547 } 4548 mPackageUsage.write(false); 4549 4550 targetInstructionSet = instructionSet != null ? instructionSet : 4551 getPrimaryInstructionSet(p.applicationInfo); 4552 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4553 return false; 4554 } 4555 } 4556 4557 synchronized (mInstallLock) { 4558 final String[] instructionSets = new String[] { targetInstructionSet }; 4559 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4560 true /* include dependencies */) == DEX_OPT_PERFORMED; 4561 } 4562 } 4563 4564 public HashSet<String> getPackagesThatNeedDexOpt() { 4565 HashSet<String> pkgs = null; 4566 synchronized (mPackages) { 4567 for (PackageParser.Package p : mPackages.values()) { 4568 if (DEBUG_DEXOPT) { 4569 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4570 } 4571 if (!p.mDexOptPerformed.isEmpty()) { 4572 continue; 4573 } 4574 if (pkgs == null) { 4575 pkgs = new HashSet<String>(); 4576 } 4577 pkgs.add(p.packageName); 4578 } 4579 } 4580 return pkgs; 4581 } 4582 4583 public void shutdown() { 4584 mPackageUsage.write(true); 4585 } 4586 4587 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4588 boolean forceDex, boolean defer, HashSet<String> done) { 4589 for (int i=0; i<libs.size(); i++) { 4590 PackageParser.Package libPkg; 4591 String libName; 4592 synchronized (mPackages) { 4593 libName = libs.get(i); 4594 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4595 if (lib != null && lib.apk != null) { 4596 libPkg = mPackages.get(lib.apk); 4597 } else { 4598 libPkg = null; 4599 } 4600 } 4601 if (libPkg != null && !done.contains(libName)) { 4602 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4603 } 4604 } 4605 } 4606 4607 static final int DEX_OPT_SKIPPED = 0; 4608 static final int DEX_OPT_PERFORMED = 1; 4609 static final int DEX_OPT_DEFERRED = 2; 4610 static final int DEX_OPT_FAILED = -1; 4611 4612 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4613 boolean forceDex, boolean defer, HashSet<String> done) { 4614 final String[] instructionSets = targetInstructionSets != null ? 4615 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4616 4617 if (done != null) { 4618 done.add(pkg.packageName); 4619 if (pkg.usesLibraries != null) { 4620 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4621 } 4622 if (pkg.usesOptionalLibraries != null) { 4623 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4624 } 4625 } 4626 4627 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4628 return DEX_OPT_SKIPPED; 4629 } 4630 4631 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4632 4633 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4634 boolean performedDexOpt = false; 4635 // There are three basic cases here: 4636 // 1.) we need to dexopt, either because we are forced or it is needed 4637 // 2.) we are defering a needed dexopt 4638 // 3.) we are skipping an unneeded dexopt 4639 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4640 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4641 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4642 continue; 4643 } 4644 4645 for (String path : paths) { 4646 try { 4647 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4648 // patckage or the one we find does not match the image checksum (i.e. it was 4649 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4650 // odex file and it matches the checksum of the image but not its base address, 4651 // meaning we need to move it. 4652 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4653 pkg.packageName, dexCodeInstructionSet, defer); 4654 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4655 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4656 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4657 + " vmSafeMode=" + vmSafeMode); 4658 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4659 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4660 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4661 4662 if (ret < 0) { 4663 // Don't bother running dexopt again if we failed, it will probably 4664 // just result in an error again. Also, don't bother dexopting for other 4665 // paths & ISAs. 4666 return DEX_OPT_FAILED; 4667 } 4668 4669 performedDexOpt = true; 4670 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4671 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4672 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4673 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4674 pkg.packageName, dexCodeInstructionSet); 4675 4676 if (ret < 0) { 4677 // Don't bother running patchoat again if we failed, it will probably 4678 // just result in an error again. Also, don't bother dexopting for other 4679 // paths & ISAs. 4680 return DEX_OPT_FAILED; 4681 } 4682 4683 performedDexOpt = true; 4684 } 4685 4686 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4687 // paths and instruction sets. We'll deal with them all together when we process 4688 // our list of deferred dexopts. 4689 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4690 if (mDeferredDexOpt == null) { 4691 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4692 } 4693 mDeferredDexOpt.add(pkg); 4694 return DEX_OPT_DEFERRED; 4695 } 4696 } catch (FileNotFoundException e) { 4697 Slog.w(TAG, "Apk not found for dexopt: " + path); 4698 return DEX_OPT_FAILED; 4699 } catch (IOException e) { 4700 Slog.w(TAG, "IOException reading apk: " + path, e); 4701 return DEX_OPT_FAILED; 4702 } catch (StaleDexCacheError e) { 4703 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4704 return DEX_OPT_FAILED; 4705 } catch (Exception e) { 4706 Slog.w(TAG, "Exception when doing dexopt : ", e); 4707 return DEX_OPT_FAILED; 4708 } 4709 } 4710 4711 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4712 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4713 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4714 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4715 // it. 4716 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4717 } 4718 4719 // If we've gotten here, we're sure that no error occurred and that we haven't 4720 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4721 // we've skipped all of them because they are up to date. In both cases this 4722 // package doesn't need dexopt any longer. 4723 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4724 } 4725 4726 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4727 if (info.primaryCpuAbi != null) { 4728 if (info.secondaryCpuAbi != null) { 4729 return new String[] { 4730 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4731 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4732 } else { 4733 return new String[] { 4734 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4735 } 4736 } 4737 4738 return new String[] { getPreferredInstructionSet() }; 4739 } 4740 4741 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4742 if (ps.primaryCpuAbiString != null) { 4743 if (ps.secondaryCpuAbiString != null) { 4744 return new String[] { 4745 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4746 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4747 } else { 4748 return new String[] { 4749 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4750 } 4751 } 4752 4753 return new String[] { getPreferredInstructionSet() }; 4754 } 4755 4756 private static String getPreferredInstructionSet() { 4757 if (sPreferredInstructionSet == null) { 4758 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4759 } 4760 4761 return sPreferredInstructionSet; 4762 } 4763 4764 private static List<String> getAllInstructionSets() { 4765 final String[] allAbis = Build.SUPPORTED_ABIS; 4766 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4767 4768 for (String abi : allAbis) { 4769 final String instructionSet = VMRuntime.getInstructionSet(abi); 4770 if (!allInstructionSets.contains(instructionSet)) { 4771 allInstructionSets.add(instructionSet); 4772 } 4773 } 4774 4775 return allInstructionSets; 4776 } 4777 4778 /** 4779 * Returns the instruction set that should be used to compile dex code. In the presence of 4780 * a native bridge this might be different than the one shared libraries use. 4781 */ 4782 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4783 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4784 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4785 } 4786 4787 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4788 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4789 for (String instructionSet : instructionSets) { 4790 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4791 } 4792 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4793 } 4794 4795 @Override 4796 public void forceDexOpt(String packageName) { 4797 enforceSystemOrRoot("forceDexOpt"); 4798 4799 PackageParser.Package pkg; 4800 synchronized (mPackages) { 4801 pkg = mPackages.get(packageName); 4802 if (pkg == null) { 4803 throw new IllegalArgumentException("Missing package: " + packageName); 4804 } 4805 } 4806 4807 synchronized (mInstallLock) { 4808 final String[] instructionSets = new String[] { 4809 getPrimaryInstructionSet(pkg.applicationInfo) }; 4810 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4811 if (res != DEX_OPT_PERFORMED) { 4812 throw new IllegalStateException("Failed to dexopt: " + res); 4813 } 4814 } 4815 } 4816 4817 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4818 boolean forceDex, boolean defer, boolean inclDependencies) { 4819 HashSet<String> done; 4820 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4821 done = new HashSet<String>(); 4822 done.add(pkg.packageName); 4823 } else { 4824 done = null; 4825 } 4826 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4827 } 4828 4829 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4830 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4831 Slog.w(TAG, "Unable to update from " + oldPkg.name 4832 + " to " + newPkg.packageName 4833 + ": old package not in system partition"); 4834 return false; 4835 } else if (mPackages.get(oldPkg.name) != null) { 4836 Slog.w(TAG, "Unable to update from " + oldPkg.name 4837 + " to " + newPkg.packageName 4838 + ": old package still exists"); 4839 return false; 4840 } 4841 return true; 4842 } 4843 4844 File getDataPathForUser(int userId) { 4845 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4846 } 4847 4848 private File getDataPathForPackage(String packageName, int userId) { 4849 /* 4850 * Until we fully support multiple users, return the directory we 4851 * previously would have. The PackageManagerTests will need to be 4852 * revised when this is changed back.. 4853 */ 4854 if (userId == 0) { 4855 return new File(mAppDataDir, packageName); 4856 } else { 4857 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4858 + File.separator + packageName); 4859 } 4860 } 4861 4862 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4863 int[] users = sUserManager.getUserIds(); 4864 int res = mInstaller.install(packageName, uid, uid, seinfo); 4865 if (res < 0) { 4866 return res; 4867 } 4868 for (int user : users) { 4869 if (user != 0) { 4870 res = mInstaller.createUserData(packageName, 4871 UserHandle.getUid(user, uid), user, seinfo); 4872 if (res < 0) { 4873 return res; 4874 } 4875 } 4876 } 4877 return res; 4878 } 4879 4880 private int removeDataDirsLI(String packageName) { 4881 int[] users = sUserManager.getUserIds(); 4882 int res = 0; 4883 for (int user : users) { 4884 int resInner = mInstaller.remove(packageName, user); 4885 if (resInner < 0) { 4886 res = resInner; 4887 } 4888 } 4889 4890 return res; 4891 } 4892 4893 private int deleteCodeCacheDirsLI(String packageName) { 4894 int[] users = sUserManager.getUserIds(); 4895 int res = 0; 4896 for (int user : users) { 4897 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4898 if (resInner < 0) { 4899 res = resInner; 4900 } 4901 } 4902 return res; 4903 } 4904 4905 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4906 PackageParser.Package changingLib) { 4907 if (file.path != null) { 4908 usesLibraryFiles.add(file.path); 4909 return; 4910 } 4911 PackageParser.Package p = mPackages.get(file.apk); 4912 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4913 // If we are doing this while in the middle of updating a library apk, 4914 // then we need to make sure to use that new apk for determining the 4915 // dependencies here. (We haven't yet finished committing the new apk 4916 // to the package manager state.) 4917 if (p == null || p.packageName.equals(changingLib.packageName)) { 4918 p = changingLib; 4919 } 4920 } 4921 if (p != null) { 4922 usesLibraryFiles.addAll(p.getAllCodePaths()); 4923 } 4924 } 4925 4926 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4927 PackageParser.Package changingLib) throws PackageManagerException { 4928 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4929 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4930 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4931 for (int i=0; i<N; i++) { 4932 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4933 if (file == null) { 4934 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4935 "Package " + pkg.packageName + " requires unavailable shared library " 4936 + pkg.usesLibraries.get(i) + "; failing!"); 4937 } 4938 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4939 } 4940 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4941 for (int i=0; i<N; i++) { 4942 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4943 if (file == null) { 4944 Slog.w(TAG, "Package " + pkg.packageName 4945 + " desires unavailable shared library " 4946 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4947 } else { 4948 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4949 } 4950 } 4951 N = usesLibraryFiles.size(); 4952 if (N > 0) { 4953 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4954 } else { 4955 pkg.usesLibraryFiles = null; 4956 } 4957 } 4958 } 4959 4960 private static boolean hasString(List<String> list, List<String> which) { 4961 if (list == null) { 4962 return false; 4963 } 4964 for (int i=list.size()-1; i>=0; i--) { 4965 for (int j=which.size()-1; j>=0; j--) { 4966 if (which.get(j).equals(list.get(i))) { 4967 return true; 4968 } 4969 } 4970 } 4971 return false; 4972 } 4973 4974 private void updateAllSharedLibrariesLPw() { 4975 for (PackageParser.Package pkg : mPackages.values()) { 4976 try { 4977 updateSharedLibrariesLPw(pkg, null); 4978 } catch (PackageManagerException e) { 4979 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4980 } 4981 } 4982 } 4983 4984 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4985 PackageParser.Package changingPkg) { 4986 ArrayList<PackageParser.Package> res = null; 4987 for (PackageParser.Package pkg : mPackages.values()) { 4988 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4989 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4990 if (res == null) { 4991 res = new ArrayList<PackageParser.Package>(); 4992 } 4993 res.add(pkg); 4994 try { 4995 updateSharedLibrariesLPw(pkg, changingPkg); 4996 } catch (PackageManagerException e) { 4997 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4998 } 4999 } 5000 } 5001 return res; 5002 } 5003 5004 /** 5005 * Derive the value of the {@code cpuAbiOverride} based on the provided 5006 * value and an optional stored value from the package settings. 5007 */ 5008 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5009 String cpuAbiOverride = null; 5010 5011 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5012 cpuAbiOverride = null; 5013 } else if (abiOverride != null) { 5014 cpuAbiOverride = abiOverride; 5015 } else if (settings != null) { 5016 cpuAbiOverride = settings.cpuAbiOverrideString; 5017 } 5018 5019 return cpuAbiOverride; 5020 } 5021 5022 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5023 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5024 final File scanFile = new File(pkg.codePath); 5025 if (pkg.applicationInfo.getCodePath() == null || 5026 pkg.applicationInfo.getResourcePath() == null) { 5027 // Bail out. The resource and code paths haven't been set. 5028 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5029 "Code and resource paths haven't been set correctly"); 5030 } 5031 5032 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5033 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5034 } 5035 5036 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5037 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5038 } 5039 5040 if (mCustomResolverComponentName != null && 5041 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5042 setUpCustomResolverActivity(pkg); 5043 } 5044 5045 if (pkg.packageName.equals("android")) { 5046 synchronized (mPackages) { 5047 if (mAndroidApplication != null) { 5048 Slog.w(TAG, "*************************************************"); 5049 Slog.w(TAG, "Core android package being redefined. Skipping."); 5050 Slog.w(TAG, " file=" + scanFile); 5051 Slog.w(TAG, "*************************************************"); 5052 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5053 "Core android package being redefined. Skipping."); 5054 } 5055 5056 // Set up information for our fall-back user intent resolution activity. 5057 mPlatformPackage = pkg; 5058 pkg.mVersionCode = mSdkVersion; 5059 mAndroidApplication = pkg.applicationInfo; 5060 5061 if (!mResolverReplaced) { 5062 mResolveActivity.applicationInfo = mAndroidApplication; 5063 mResolveActivity.name = ResolverActivity.class.getName(); 5064 mResolveActivity.packageName = mAndroidApplication.packageName; 5065 mResolveActivity.processName = "system:ui"; 5066 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5067 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5068 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5069 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5070 mResolveActivity.exported = true; 5071 mResolveActivity.enabled = true; 5072 mResolveInfo.activityInfo = mResolveActivity; 5073 mResolveInfo.priority = 0; 5074 mResolveInfo.preferredOrder = 0; 5075 mResolveInfo.match = 0; 5076 mResolveComponentName = new ComponentName( 5077 mAndroidApplication.packageName, mResolveActivity.name); 5078 } 5079 } 5080 } 5081 5082 if (DEBUG_PACKAGE_SCANNING) { 5083 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5084 Log.d(TAG, "Scanning package " + pkg.packageName); 5085 } 5086 5087 if (mPackages.containsKey(pkg.packageName) 5088 || mSharedLibraries.containsKey(pkg.packageName)) { 5089 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5090 "Application package " + pkg.packageName 5091 + " already installed. Skipping duplicate."); 5092 } 5093 5094 // Initialize package source and resource directories 5095 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5096 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5097 5098 SharedUserSetting suid = null; 5099 PackageSetting pkgSetting = null; 5100 5101 if (!isSystemApp(pkg)) { 5102 // Only system apps can use these features. 5103 pkg.mOriginalPackages = null; 5104 pkg.mRealPackage = null; 5105 pkg.mAdoptPermissions = null; 5106 } 5107 5108 // writer 5109 synchronized (mPackages) { 5110 if (pkg.mSharedUserId != null) { 5111 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5112 if (suid == null) { 5113 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5114 "Creating application package " + pkg.packageName 5115 + " for shared user failed"); 5116 } 5117 if (DEBUG_PACKAGE_SCANNING) { 5118 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5119 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5120 + "): packages=" + suid.packages); 5121 } 5122 } 5123 5124 // Check if we are renaming from an original package name. 5125 PackageSetting origPackage = null; 5126 String realName = null; 5127 if (pkg.mOriginalPackages != null) { 5128 // This package may need to be renamed to a previously 5129 // installed name. Let's check on that... 5130 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5131 if (pkg.mOriginalPackages.contains(renamed)) { 5132 // This package had originally been installed as the 5133 // original name, and we have already taken care of 5134 // transitioning to the new one. Just update the new 5135 // one to continue using the old name. 5136 realName = pkg.mRealPackage; 5137 if (!pkg.packageName.equals(renamed)) { 5138 // Callers into this function may have already taken 5139 // care of renaming the package; only do it here if 5140 // it is not already done. 5141 pkg.setPackageName(renamed); 5142 } 5143 5144 } else { 5145 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5146 if ((origPackage = mSettings.peekPackageLPr( 5147 pkg.mOriginalPackages.get(i))) != null) { 5148 // We do have the package already installed under its 5149 // original name... should we use it? 5150 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5151 // New package is not compatible with original. 5152 origPackage = null; 5153 continue; 5154 } else if (origPackage.sharedUser != null) { 5155 // Make sure uid is compatible between packages. 5156 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5157 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5158 + " to " + pkg.packageName + ": old uid " 5159 + origPackage.sharedUser.name 5160 + " differs from " + pkg.mSharedUserId); 5161 origPackage = null; 5162 continue; 5163 } 5164 } else { 5165 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5166 + pkg.packageName + " to old name " + origPackage.name); 5167 } 5168 break; 5169 } 5170 } 5171 } 5172 } 5173 5174 if (mTransferedPackages.contains(pkg.packageName)) { 5175 Slog.w(TAG, "Package " + pkg.packageName 5176 + " was transferred to another, but its .apk remains"); 5177 } 5178 5179 // Just create the setting, don't add it yet. For already existing packages 5180 // the PkgSetting exists already and doesn't have to be created. 5181 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5182 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5183 pkg.applicationInfo.primaryCpuAbi, 5184 pkg.applicationInfo.secondaryCpuAbi, 5185 pkg.applicationInfo.flags, user, false); 5186 if (pkgSetting == null) { 5187 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5188 "Creating application package " + pkg.packageName + " failed"); 5189 } 5190 5191 if (pkgSetting.origPackage != null) { 5192 // If we are first transitioning from an original package, 5193 // fix up the new package's name now. We need to do this after 5194 // looking up the package under its new name, so getPackageLP 5195 // can take care of fiddling things correctly. 5196 pkg.setPackageName(origPackage.name); 5197 5198 // File a report about this. 5199 String msg = "New package " + pkgSetting.realName 5200 + " renamed to replace old package " + pkgSetting.name; 5201 reportSettingsProblem(Log.WARN, msg); 5202 5203 // Make a note of it. 5204 mTransferedPackages.add(origPackage.name); 5205 5206 // No longer need to retain this. 5207 pkgSetting.origPackage = null; 5208 } 5209 5210 if (realName != null) { 5211 // Make a note of it. 5212 mTransferedPackages.add(pkg.packageName); 5213 } 5214 5215 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5216 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5217 } 5218 5219 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5220 // Check all shared libraries and map to their actual file path. 5221 // We only do this here for apps not on a system dir, because those 5222 // are the only ones that can fail an install due to this. We 5223 // will take care of the system apps by updating all of their 5224 // library paths after the scan is done. 5225 updateSharedLibrariesLPw(pkg, null); 5226 } 5227 5228 if (mFoundPolicyFile) { 5229 SELinuxMMAC.assignSeinfoValue(pkg); 5230 } 5231 5232 pkg.applicationInfo.uid = pkgSetting.appId; 5233 pkg.mExtras = pkgSetting; 5234 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5235 try { 5236 verifySignaturesLP(pkgSetting, pkg); 5237 } catch (PackageManagerException e) { 5238 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5239 throw e; 5240 } 5241 // The signature has changed, but this package is in the system 5242 // image... let's recover! 5243 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5244 // However... if this package is part of a shared user, but it 5245 // doesn't match the signature of the shared user, let's fail. 5246 // What this means is that you can't change the signatures 5247 // associated with an overall shared user, which doesn't seem all 5248 // that unreasonable. 5249 if (pkgSetting.sharedUser != null) { 5250 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5251 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5252 throw new PackageManagerException( 5253 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5254 "Signature mismatch for shared user : " 5255 + pkgSetting.sharedUser); 5256 } 5257 } 5258 // File a report about this. 5259 String msg = "System package " + pkg.packageName 5260 + " signature changed; retaining data."; 5261 reportSettingsProblem(Log.WARN, msg); 5262 } 5263 } else { 5264 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5265 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5266 + pkg.packageName + " upgrade keys do not match the " 5267 + "previously installed version"); 5268 } else { 5269 // signatures may have changed as result of upgrade 5270 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5271 } 5272 } 5273 // Verify that this new package doesn't have any content providers 5274 // that conflict with existing packages. Only do this if the 5275 // package isn't already installed, since we don't want to break 5276 // things that are installed. 5277 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5278 final int N = pkg.providers.size(); 5279 int i; 5280 for (i=0; i<N; i++) { 5281 PackageParser.Provider p = pkg.providers.get(i); 5282 if (p.info.authority != null) { 5283 String names[] = p.info.authority.split(";"); 5284 for (int j = 0; j < names.length; j++) { 5285 if (mProvidersByAuthority.containsKey(names[j])) { 5286 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5287 final String otherPackageName = 5288 ((other != null && other.getComponentName() != null) ? 5289 other.getComponentName().getPackageName() : "?"); 5290 throw new PackageManagerException( 5291 INSTALL_FAILED_CONFLICTING_PROVIDER, 5292 "Can't install because provider name " + names[j] 5293 + " (in package " + pkg.applicationInfo.packageName 5294 + ") is already used by " + otherPackageName); 5295 } 5296 } 5297 } 5298 } 5299 } 5300 5301 if (pkg.mAdoptPermissions != null) { 5302 // This package wants to adopt ownership of permissions from 5303 // another package. 5304 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5305 final String origName = pkg.mAdoptPermissions.get(i); 5306 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5307 if (orig != null) { 5308 if (verifyPackageUpdateLPr(orig, pkg)) { 5309 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5310 + pkg.packageName); 5311 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5312 } 5313 } 5314 } 5315 } 5316 } 5317 5318 final String pkgName = pkg.packageName; 5319 5320 final long scanFileTime = scanFile.lastModified(); 5321 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5322 pkg.applicationInfo.processName = fixProcessName( 5323 pkg.applicationInfo.packageName, 5324 pkg.applicationInfo.processName, 5325 pkg.applicationInfo.uid); 5326 5327 File dataPath; 5328 if (mPlatformPackage == pkg) { 5329 // The system package is special. 5330 dataPath = new File (Environment.getDataDirectory(), "system"); 5331 pkg.applicationInfo.dataDir = dataPath.getPath(); 5332 5333 } else { 5334 // This is a normal package, need to make its data directory. 5335 dataPath = getDataPathForPackage(pkg.packageName, 0); 5336 5337 boolean uidError = false; 5338 5339 if (dataPath.exists()) { 5340 int currentUid = 0; 5341 try { 5342 StructStat stat = Os.stat(dataPath.getPath()); 5343 currentUid = stat.st_uid; 5344 } catch (ErrnoException e) { 5345 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5346 } 5347 5348 // If we have mismatched owners for the data path, we have a problem. 5349 if (currentUid != pkg.applicationInfo.uid) { 5350 boolean recovered = false; 5351 if (currentUid == 0) { 5352 // The directory somehow became owned by root. Wow. 5353 // This is probably because the system was stopped while 5354 // installd was in the middle of messing with its libs 5355 // directory. Ask installd to fix that. 5356 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5357 pkg.applicationInfo.uid); 5358 if (ret >= 0) { 5359 recovered = true; 5360 String msg = "Package " + pkg.packageName 5361 + " unexpectedly changed to uid 0; recovered to " + 5362 + pkg.applicationInfo.uid; 5363 reportSettingsProblem(Log.WARN, msg); 5364 } 5365 } 5366 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5367 || (scanFlags&SCAN_BOOTING) != 0)) { 5368 // If this is a system app, we can at least delete its 5369 // current data so the application will still work. 5370 int ret = removeDataDirsLI(pkgName); 5371 if (ret >= 0) { 5372 // TODO: Kill the processes first 5373 // Old data gone! 5374 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5375 ? "System package " : "Third party package "; 5376 String msg = prefix + pkg.packageName 5377 + " has changed from uid: " 5378 + currentUid + " to " 5379 + pkg.applicationInfo.uid + "; old data erased"; 5380 reportSettingsProblem(Log.WARN, msg); 5381 recovered = true; 5382 5383 // And now re-install the app. 5384 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5385 pkg.applicationInfo.seinfo); 5386 if (ret == -1) { 5387 // Ack should not happen! 5388 msg = prefix + pkg.packageName 5389 + " could not have data directory re-created after delete."; 5390 reportSettingsProblem(Log.WARN, msg); 5391 throw new PackageManagerException( 5392 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5393 } 5394 } 5395 if (!recovered) { 5396 mHasSystemUidErrors = true; 5397 } 5398 } else if (!recovered) { 5399 // If we allow this install to proceed, we will be broken. 5400 // Abort, abort! 5401 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5402 "scanPackageLI"); 5403 } 5404 if (!recovered) { 5405 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5406 + pkg.applicationInfo.uid + "/fs_" 5407 + currentUid; 5408 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5409 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5410 String msg = "Package " + pkg.packageName 5411 + " has mismatched uid: " 5412 + currentUid + " on disk, " 5413 + pkg.applicationInfo.uid + " in settings"; 5414 // writer 5415 synchronized (mPackages) { 5416 mSettings.mReadMessages.append(msg); 5417 mSettings.mReadMessages.append('\n'); 5418 uidError = true; 5419 if (!pkgSetting.uidError) { 5420 reportSettingsProblem(Log.ERROR, msg); 5421 } 5422 } 5423 } 5424 } 5425 pkg.applicationInfo.dataDir = dataPath.getPath(); 5426 if (mShouldRestoreconData) { 5427 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5428 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5429 pkg.applicationInfo.uid); 5430 } 5431 } else { 5432 if (DEBUG_PACKAGE_SCANNING) { 5433 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5434 Log.v(TAG, "Want this data dir: " + dataPath); 5435 } 5436 //invoke installer to do the actual installation 5437 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5438 pkg.applicationInfo.seinfo); 5439 if (ret < 0) { 5440 // Error from installer 5441 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5442 "Unable to create data dirs [errorCode=" + ret + "]"); 5443 } 5444 5445 if (dataPath.exists()) { 5446 pkg.applicationInfo.dataDir = dataPath.getPath(); 5447 } else { 5448 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5449 pkg.applicationInfo.dataDir = null; 5450 } 5451 } 5452 5453 pkgSetting.uidError = uidError; 5454 } 5455 5456 final String path = scanFile.getPath(); 5457 final String codePath = pkg.applicationInfo.getCodePath(); 5458 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5459 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5460 setBundledAppAbisAndRoots(pkg, pkgSetting); 5461 5462 // If we haven't found any native libraries for the app, check if it has 5463 // renderscript code. We'll need to force the app to 32 bit if it has 5464 // renderscript bitcode. 5465 if (pkg.applicationInfo.primaryCpuAbi == null 5466 && pkg.applicationInfo.secondaryCpuAbi == null 5467 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5468 NativeLibraryHelper.Handle handle = null; 5469 try { 5470 handle = NativeLibraryHelper.Handle.create(scanFile); 5471 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5472 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5473 } 5474 } catch (IOException ioe) { 5475 Slog.w(TAG, "Error scanning system app : " + ioe); 5476 } finally { 5477 IoUtils.closeQuietly(handle); 5478 } 5479 } 5480 5481 setNativeLibraryPaths(pkg); 5482 } else { 5483 // TODO: We can probably be smarter about this stuff. For installed apps, 5484 // we can calculate this information at install time once and for all. For 5485 // system apps, we can probably assume that this information doesn't change 5486 // after the first boot scan. As things stand, we do lots of unnecessary work. 5487 5488 // Give ourselves some initial paths; we'll come back for another 5489 // pass once we've determined ABI below. 5490 setNativeLibraryPaths(pkg); 5491 5492 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5493 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5494 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5495 5496 NativeLibraryHelper.Handle handle = null; 5497 try { 5498 handle = NativeLibraryHelper.Handle.create(scanFile); 5499 // TODO(multiArch): This can be null for apps that didn't go through the 5500 // usual installation process. We can calculate it again, like we 5501 // do during install time. 5502 // 5503 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5504 // unnecessary. 5505 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5506 5507 // Null out the abis so that they can be recalculated. 5508 pkg.applicationInfo.primaryCpuAbi = null; 5509 pkg.applicationInfo.secondaryCpuAbi = null; 5510 if (isMultiArch(pkg.applicationInfo)) { 5511 // Warn if we've set an abiOverride for multi-lib packages.. 5512 // By definition, we need to copy both 32 and 64 bit libraries for 5513 // such packages. 5514 if (pkg.cpuAbiOverride != null 5515 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5516 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5517 } 5518 5519 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5520 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5521 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5522 if (isAsec) { 5523 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5524 } else { 5525 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5526 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5527 useIsaSpecificSubdirs); 5528 } 5529 } 5530 5531 maybeThrowExceptionForMultiArchCopy( 5532 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5533 5534 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5535 if (isAsec) { 5536 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5537 } else { 5538 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5539 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5540 useIsaSpecificSubdirs); 5541 } 5542 } 5543 5544 maybeThrowExceptionForMultiArchCopy( 5545 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5546 5547 if (abi64 >= 0) { 5548 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5549 } 5550 5551 if (abi32 >= 0) { 5552 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5553 if (abi64 >= 0) { 5554 pkg.applicationInfo.secondaryCpuAbi = abi; 5555 } else { 5556 pkg.applicationInfo.primaryCpuAbi = abi; 5557 } 5558 } 5559 } else { 5560 String[] abiList = (cpuAbiOverride != null) ? 5561 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5562 5563 // Enable gross and lame hacks for apps that are built with old 5564 // SDK tools. We must scan their APKs for renderscript bitcode and 5565 // not launch them if it's present. Don't bother checking on devices 5566 // that don't have 64 bit support. 5567 boolean needsRenderScriptOverride = false; 5568 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5569 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5570 abiList = Build.SUPPORTED_32_BIT_ABIS; 5571 needsRenderScriptOverride = true; 5572 } 5573 5574 final int copyRet; 5575 if (isAsec) { 5576 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5577 } else { 5578 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5579 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5580 } 5581 5582 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5583 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5584 "Error unpackaging native libs for app, errorCode=" + copyRet); 5585 } 5586 5587 if (copyRet >= 0) { 5588 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5589 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5590 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5591 } else if (needsRenderScriptOverride) { 5592 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5593 } 5594 } 5595 } catch (IOException ioe) { 5596 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5597 } finally { 5598 IoUtils.closeQuietly(handle); 5599 } 5600 5601 // Now that we've calculated the ABIs and determined if it's an internal app, 5602 // we will go ahead and populate the nativeLibraryPath. 5603 setNativeLibraryPaths(pkg); 5604 5605 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5606 final int[] userIds = sUserManager.getUserIds(); 5607 synchronized (mInstallLock) { 5608 // Create a native library symlink only if we have native libraries 5609 // and if the native libraries are 32 bit libraries. We do not provide 5610 // this symlink for 64 bit libraries. 5611 if (pkg.applicationInfo.primaryCpuAbi != null && 5612 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5613 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5614 for (int userId : userIds) { 5615 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5616 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5617 "Failed linking native library dir (user=" + userId + ")"); 5618 } 5619 } 5620 } 5621 } 5622 } 5623 5624 // This is a special case for the "system" package, where the ABI is 5625 // dictated by the zygote configuration (and init.rc). We should keep track 5626 // of this ABI so that we can deal with "normal" applications that run under 5627 // the same UID correctly. 5628 if (mPlatformPackage == pkg) { 5629 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5630 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5631 } 5632 5633 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5634 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5635 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5636 // Copy the derived override back to the parsed package, so that we can 5637 // update the package settings accordingly. 5638 pkg.cpuAbiOverride = cpuAbiOverride; 5639 5640 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5641 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5642 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5643 5644 // Push the derived path down into PackageSettings so we know what to 5645 // clean up at uninstall time. 5646 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5647 5648 if (DEBUG_ABI_SELECTION) { 5649 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5650 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5651 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5652 } 5653 5654 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5655 // We don't do this here during boot because we can do it all 5656 // at once after scanning all existing packages. 5657 // 5658 // We also do this *before* we perform dexopt on this package, so that 5659 // we can avoid redundant dexopts, and also to make sure we've got the 5660 // code and package path correct. 5661 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5662 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5663 } 5664 5665 if ((scanFlags&SCAN_NO_DEX) == 0) { 5666 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false) 5667 == DEX_OPT_FAILED) { 5668 if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5669 removeDataDirsLI(pkg.packageName); 5670 } 5671 5672 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5673 } 5674 } 5675 5676 if (mFactoryTest && pkg.requestedPermissions.contains( 5677 android.Manifest.permission.FACTORY_TEST)) { 5678 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5679 } 5680 5681 ArrayList<PackageParser.Package> clientLibPkgs = null; 5682 5683 // writer 5684 synchronized (mPackages) { 5685 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5686 // Only system apps can add new shared libraries. 5687 if (pkg.libraryNames != null) { 5688 for (int i=0; i<pkg.libraryNames.size(); i++) { 5689 String name = pkg.libraryNames.get(i); 5690 boolean allowed = false; 5691 if (isUpdatedSystemApp(pkg)) { 5692 // New library entries can only be added through the 5693 // system image. This is important to get rid of a lot 5694 // of nasty edge cases: for example if we allowed a non- 5695 // system update of the app to add a library, then uninstalling 5696 // the update would make the library go away, and assumptions 5697 // we made such as through app install filtering would now 5698 // have allowed apps on the device which aren't compatible 5699 // with it. Better to just have the restriction here, be 5700 // conservative, and create many fewer cases that can negatively 5701 // impact the user experience. 5702 final PackageSetting sysPs = mSettings 5703 .getDisabledSystemPkgLPr(pkg.packageName); 5704 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5705 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5706 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5707 allowed = true; 5708 allowed = true; 5709 break; 5710 } 5711 } 5712 } 5713 } else { 5714 allowed = true; 5715 } 5716 if (allowed) { 5717 if (!mSharedLibraries.containsKey(name)) { 5718 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5719 } else if (!name.equals(pkg.packageName)) { 5720 Slog.w(TAG, "Package " + pkg.packageName + " library " 5721 + name + " already exists; skipping"); 5722 } 5723 } else { 5724 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5725 + name + " that is not declared on system image; skipping"); 5726 } 5727 } 5728 if ((scanFlags&SCAN_BOOTING) == 0) { 5729 // If we are not booting, we need to update any applications 5730 // that are clients of our shared library. If we are booting, 5731 // this will all be done once the scan is complete. 5732 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5733 } 5734 } 5735 } 5736 } 5737 5738 // We also need to dexopt any apps that are dependent on this library. Note that 5739 // if these fail, we should abort the install since installing the library will 5740 // result in some apps being broken. 5741 if (clientLibPkgs != null) { 5742 if ((scanFlags&SCAN_NO_DEX) == 0) { 5743 for (int i=0; i<clientLibPkgs.size(); i++) { 5744 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5745 if (performDexOptLI(clientPkg, null /* instruction sets */, 5746 forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false) 5747 == DEX_OPT_FAILED) { 5748 if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5749 removeDataDirsLI(pkg.packageName); 5750 } 5751 5752 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5753 "scanPackageLI failed to dexopt clientLibPkgs"); 5754 } 5755 } 5756 } 5757 } 5758 5759 // Request the ActivityManager to kill the process(only for existing packages) 5760 // so that we do not end up in a confused state while the user is still using the older 5761 // version of the application while the new one gets installed. 5762 if ((scanFlags & SCAN_REPLACING) != 0) { 5763 killApplication(pkg.applicationInfo.packageName, 5764 pkg.applicationInfo.uid, "update pkg"); 5765 } 5766 5767 // Also need to kill any apps that are dependent on the library. 5768 if (clientLibPkgs != null) { 5769 for (int i=0; i<clientLibPkgs.size(); i++) { 5770 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5771 killApplication(clientPkg.applicationInfo.packageName, 5772 clientPkg.applicationInfo.uid, "update lib"); 5773 } 5774 } 5775 5776 // writer 5777 synchronized (mPackages) { 5778 // We don't expect installation to fail beyond this point 5779 5780 // Add the new setting to mSettings 5781 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5782 // Add the new setting to mPackages 5783 mPackages.put(pkg.applicationInfo.packageName, pkg); 5784 // Make sure we don't accidentally delete its data. 5785 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5786 while (iter.hasNext()) { 5787 PackageCleanItem item = iter.next(); 5788 if (pkgName.equals(item.packageName)) { 5789 iter.remove(); 5790 } 5791 } 5792 5793 // Take care of first install / last update times. 5794 if (currentTime != 0) { 5795 if (pkgSetting.firstInstallTime == 0) { 5796 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5797 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5798 pkgSetting.lastUpdateTime = currentTime; 5799 } 5800 } else if (pkgSetting.firstInstallTime == 0) { 5801 // We need *something*. Take time time stamp of the file. 5802 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5803 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5804 if (scanFileTime != pkgSetting.timeStamp) { 5805 // A package on the system image has changed; consider this 5806 // to be an update. 5807 pkgSetting.lastUpdateTime = scanFileTime; 5808 } 5809 } 5810 5811 // Add the package's KeySets to the global KeySetManagerService 5812 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5813 try { 5814 // Old KeySetData no longer valid. 5815 ksms.removeAppKeySetDataLPw(pkg.packageName); 5816 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5817 if (pkg.mKeySetMapping != null) { 5818 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5819 pkg.mKeySetMapping.entrySet()) { 5820 if (entry.getValue() != null) { 5821 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5822 entry.getValue(), entry.getKey()); 5823 } 5824 } 5825 if (pkg.mUpgradeKeySets != null) { 5826 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5827 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5828 } 5829 } 5830 } 5831 } catch (NullPointerException e) { 5832 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5833 } catch (IllegalArgumentException e) { 5834 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5835 } 5836 5837 int N = pkg.providers.size(); 5838 StringBuilder r = null; 5839 int i; 5840 for (i=0; i<N; i++) { 5841 PackageParser.Provider p = pkg.providers.get(i); 5842 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5843 p.info.processName, pkg.applicationInfo.uid); 5844 mProviders.addProvider(p); 5845 p.syncable = p.info.isSyncable; 5846 if (p.info.authority != null) { 5847 String names[] = p.info.authority.split(";"); 5848 p.info.authority = null; 5849 for (int j = 0; j < names.length; j++) { 5850 if (j == 1 && p.syncable) { 5851 // We only want the first authority for a provider to possibly be 5852 // syncable, so if we already added this provider using a different 5853 // authority clear the syncable flag. We copy the provider before 5854 // changing it because the mProviders object contains a reference 5855 // to a provider that we don't want to change. 5856 // Only do this for the second authority since the resulting provider 5857 // object can be the same for all future authorities for this provider. 5858 p = new PackageParser.Provider(p); 5859 p.syncable = false; 5860 } 5861 if (!mProvidersByAuthority.containsKey(names[j])) { 5862 mProvidersByAuthority.put(names[j], p); 5863 if (p.info.authority == null) { 5864 p.info.authority = names[j]; 5865 } else { 5866 p.info.authority = p.info.authority + ";" + names[j]; 5867 } 5868 if (DEBUG_PACKAGE_SCANNING) { 5869 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5870 Log.d(TAG, "Registered content provider: " + names[j] 5871 + ", className = " + p.info.name + ", isSyncable = " 5872 + p.info.isSyncable); 5873 } 5874 } else { 5875 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5876 Slog.w(TAG, "Skipping provider name " + names[j] + 5877 " (in package " + pkg.applicationInfo.packageName + 5878 "): name already used by " 5879 + ((other != null && other.getComponentName() != null) 5880 ? other.getComponentName().getPackageName() : "?")); 5881 } 5882 } 5883 } 5884 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5885 if (r == null) { 5886 r = new StringBuilder(256); 5887 } else { 5888 r.append(' '); 5889 } 5890 r.append(p.info.name); 5891 } 5892 } 5893 if (r != null) { 5894 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5895 } 5896 5897 N = pkg.services.size(); 5898 r = null; 5899 for (i=0; i<N; i++) { 5900 PackageParser.Service s = pkg.services.get(i); 5901 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5902 s.info.processName, pkg.applicationInfo.uid); 5903 mServices.addService(s); 5904 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5905 if (r == null) { 5906 r = new StringBuilder(256); 5907 } else { 5908 r.append(' '); 5909 } 5910 r.append(s.info.name); 5911 } 5912 } 5913 if (r != null) { 5914 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5915 } 5916 5917 N = pkg.receivers.size(); 5918 r = null; 5919 for (i=0; i<N; i++) { 5920 PackageParser.Activity a = pkg.receivers.get(i); 5921 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5922 a.info.processName, pkg.applicationInfo.uid); 5923 mReceivers.addActivity(a, "receiver"); 5924 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5925 if (r == null) { 5926 r = new StringBuilder(256); 5927 } else { 5928 r.append(' '); 5929 } 5930 r.append(a.info.name); 5931 } 5932 } 5933 if (r != null) { 5934 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5935 } 5936 5937 N = pkg.activities.size(); 5938 r = null; 5939 for (i=0; i<N; i++) { 5940 PackageParser.Activity a = pkg.activities.get(i); 5941 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5942 a.info.processName, pkg.applicationInfo.uid); 5943 mActivities.addActivity(a, "activity"); 5944 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5945 if (r == null) { 5946 r = new StringBuilder(256); 5947 } else { 5948 r.append(' '); 5949 } 5950 r.append(a.info.name); 5951 } 5952 } 5953 if (r != null) { 5954 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5955 } 5956 5957 N = pkg.permissionGroups.size(); 5958 r = null; 5959 for (i=0; i<N; i++) { 5960 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5961 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5962 if (cur == null) { 5963 mPermissionGroups.put(pg.info.name, pg); 5964 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5965 if (r == null) { 5966 r = new StringBuilder(256); 5967 } else { 5968 r.append(' '); 5969 } 5970 r.append(pg.info.name); 5971 } 5972 } else { 5973 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5974 + pg.info.packageName + " ignored: original from " 5975 + cur.info.packageName); 5976 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5977 if (r == null) { 5978 r = new StringBuilder(256); 5979 } else { 5980 r.append(' '); 5981 } 5982 r.append("DUP:"); 5983 r.append(pg.info.name); 5984 } 5985 } 5986 } 5987 if (r != null) { 5988 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5989 } 5990 5991 N = pkg.permissions.size(); 5992 r = null; 5993 for (i=0; i<N; i++) { 5994 PackageParser.Permission p = pkg.permissions.get(i); 5995 HashMap<String, BasePermission> permissionMap = 5996 p.tree ? mSettings.mPermissionTrees 5997 : mSettings.mPermissions; 5998 p.group = mPermissionGroups.get(p.info.group); 5999 if (p.info.group == null || p.group != null) { 6000 BasePermission bp = permissionMap.get(p.info.name); 6001 if (bp == null) { 6002 bp = new BasePermission(p.info.name, p.info.packageName, 6003 BasePermission.TYPE_NORMAL); 6004 permissionMap.put(p.info.name, bp); 6005 } 6006 if (bp.perm == null) { 6007 if (bp.sourcePackage != null 6008 && !bp.sourcePackage.equals(p.info.packageName)) { 6009 // If this is a permission that was formerly defined by a non-system 6010 // app, but is now defined by a system app (following an upgrade), 6011 // discard the previous declaration and consider the system's to be 6012 // canonical. 6013 if (isSystemApp(p.owner)) { 6014 String msg = "New decl " + p.owner + " of permission " 6015 + p.info.name + " is system"; 6016 reportSettingsProblem(Log.WARN, msg); 6017 bp.sourcePackage = null; 6018 } 6019 } 6020 if (bp.sourcePackage == null 6021 || bp.sourcePackage.equals(p.info.packageName)) { 6022 BasePermission tree = findPermissionTreeLP(p.info.name); 6023 if (tree == null 6024 || tree.sourcePackage.equals(p.info.packageName)) { 6025 bp.packageSetting = pkgSetting; 6026 bp.perm = p; 6027 bp.uid = pkg.applicationInfo.uid; 6028 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6029 if (r == null) { 6030 r = new StringBuilder(256); 6031 } else { 6032 r.append(' '); 6033 } 6034 r.append(p.info.name); 6035 } 6036 } else { 6037 Slog.w(TAG, "Permission " + p.info.name + " from package " 6038 + p.info.packageName + " ignored: base tree " 6039 + tree.name + " is from package " 6040 + tree.sourcePackage); 6041 } 6042 } else { 6043 Slog.w(TAG, "Permission " + p.info.name + " from package " 6044 + p.info.packageName + " ignored: original from " 6045 + bp.sourcePackage); 6046 } 6047 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6048 if (r == null) { 6049 r = new StringBuilder(256); 6050 } else { 6051 r.append(' '); 6052 } 6053 r.append("DUP:"); 6054 r.append(p.info.name); 6055 } 6056 if (bp.perm == p) { 6057 bp.protectionLevel = p.info.protectionLevel; 6058 } 6059 } else { 6060 Slog.w(TAG, "Permission " + p.info.name + " from package " 6061 + p.info.packageName + " ignored: no group " 6062 + p.group); 6063 } 6064 } 6065 if (r != null) { 6066 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6067 } 6068 6069 N = pkg.instrumentation.size(); 6070 r = null; 6071 for (i=0; i<N; i++) { 6072 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6073 a.info.packageName = pkg.applicationInfo.packageName; 6074 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6075 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6076 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6077 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6078 a.info.dataDir = pkg.applicationInfo.dataDir; 6079 6080 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6081 // need other information about the application, like the ABI and what not ? 6082 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6083 mInstrumentation.put(a.getComponentName(), a); 6084 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6085 if (r == null) { 6086 r = new StringBuilder(256); 6087 } else { 6088 r.append(' '); 6089 } 6090 r.append(a.info.name); 6091 } 6092 } 6093 if (r != null) { 6094 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6095 } 6096 6097 if (pkg.protectedBroadcasts != null) { 6098 N = pkg.protectedBroadcasts.size(); 6099 for (i=0; i<N; i++) { 6100 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6101 } 6102 } 6103 6104 pkgSetting.setTimeStamp(scanFileTime); 6105 6106 // Create idmap files for pairs of (packages, overlay packages). 6107 // Note: "android", ie framework-res.apk, is handled by native layers. 6108 if (pkg.mOverlayTarget != null) { 6109 // This is an overlay package. 6110 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6111 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6112 mOverlays.put(pkg.mOverlayTarget, 6113 new HashMap<String, PackageParser.Package>()); 6114 } 6115 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6116 map.put(pkg.packageName, pkg); 6117 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6118 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6119 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6120 "scanPackageLI failed to createIdmap"); 6121 } 6122 } 6123 } else if (mOverlays.containsKey(pkg.packageName) && 6124 !pkg.packageName.equals("android")) { 6125 // This is a regular package, with one or more known overlay packages. 6126 createIdmapsForPackageLI(pkg); 6127 } 6128 } 6129 6130 return pkg; 6131 } 6132 6133 /** 6134 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6135 * i.e, so that all packages can be run inside a single process if required. 6136 * 6137 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6138 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6139 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6140 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6141 * updating a package that belongs to a shared user. 6142 * 6143 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6144 * adds unnecessary complexity. 6145 */ 6146 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6147 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6148 String requiredInstructionSet = null; 6149 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6150 requiredInstructionSet = VMRuntime.getInstructionSet( 6151 scannedPackage.applicationInfo.primaryCpuAbi); 6152 } 6153 6154 PackageSetting requirer = null; 6155 for (PackageSetting ps : packagesForUser) { 6156 // If packagesForUser contains scannedPackage, we skip it. This will happen 6157 // when scannedPackage is an update of an existing package. Without this check, 6158 // we will never be able to change the ABI of any package belonging to a shared 6159 // user, even if it's compatible with other packages. 6160 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6161 if (ps.primaryCpuAbiString == null) { 6162 continue; 6163 } 6164 6165 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6166 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6167 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6168 // this but there's not much we can do. 6169 String errorMessage = "Instruction set mismatch, " 6170 + ((requirer == null) ? "[caller]" : requirer) 6171 + " requires " + requiredInstructionSet + " whereas " + ps 6172 + " requires " + instructionSet; 6173 Slog.w(TAG, errorMessage); 6174 } 6175 6176 if (requiredInstructionSet == null) { 6177 requiredInstructionSet = instructionSet; 6178 requirer = ps; 6179 } 6180 } 6181 } 6182 6183 if (requiredInstructionSet != null) { 6184 String adjustedAbi; 6185 if (requirer != null) { 6186 // requirer != null implies that either scannedPackage was null or that scannedPackage 6187 // did not require an ABI, in which case we have to adjust scannedPackage to match 6188 // the ABI of the set (which is the same as requirer's ABI) 6189 adjustedAbi = requirer.primaryCpuAbiString; 6190 if (scannedPackage != null) { 6191 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6192 } 6193 } else { 6194 // requirer == null implies that we're updating all ABIs in the set to 6195 // match scannedPackage. 6196 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6197 } 6198 6199 for (PackageSetting ps : packagesForUser) { 6200 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6201 if (ps.primaryCpuAbiString != null) { 6202 continue; 6203 } 6204 6205 ps.primaryCpuAbiString = adjustedAbi; 6206 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6207 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6208 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6209 6210 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6211 deferDexOpt, true) == DEX_OPT_FAILED) { 6212 ps.primaryCpuAbiString = null; 6213 ps.pkg.applicationInfo.primaryCpuAbi = null; 6214 return; 6215 } else { 6216 mInstaller.rmdex(ps.codePathString, 6217 getDexCodeInstructionSet(getPreferredInstructionSet())); 6218 } 6219 } 6220 } 6221 } 6222 } 6223 } 6224 6225 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6226 synchronized (mPackages) { 6227 mResolverReplaced = true; 6228 // Set up information for custom user intent resolution activity. 6229 mResolveActivity.applicationInfo = pkg.applicationInfo; 6230 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6231 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6232 mResolveActivity.processName = null; 6233 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6234 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6235 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6236 mResolveActivity.theme = 0; 6237 mResolveActivity.exported = true; 6238 mResolveActivity.enabled = true; 6239 mResolveInfo.activityInfo = mResolveActivity; 6240 mResolveInfo.priority = 0; 6241 mResolveInfo.preferredOrder = 0; 6242 mResolveInfo.match = 0; 6243 mResolveComponentName = mCustomResolverComponentName; 6244 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6245 mResolveComponentName); 6246 } 6247 } 6248 6249 private static String calculateBundledApkRoot(final String codePathString) { 6250 final File codePath = new File(codePathString); 6251 final File codeRoot; 6252 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6253 codeRoot = Environment.getRootDirectory(); 6254 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6255 codeRoot = Environment.getOemDirectory(); 6256 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6257 codeRoot = Environment.getVendorDirectory(); 6258 } else { 6259 // Unrecognized code path; take its top real segment as the apk root: 6260 // e.g. /something/app/blah.apk => /something 6261 try { 6262 File f = codePath.getCanonicalFile(); 6263 File parent = f.getParentFile(); // non-null because codePath is a file 6264 File tmp; 6265 while ((tmp = parent.getParentFile()) != null) { 6266 f = parent; 6267 parent = tmp; 6268 } 6269 codeRoot = f; 6270 Slog.w(TAG, "Unrecognized code path " 6271 + codePath + " - using " + codeRoot); 6272 } catch (IOException e) { 6273 // Can't canonicalize the code path -- shenanigans? 6274 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6275 return Environment.getRootDirectory().getPath(); 6276 } 6277 } 6278 return codeRoot.getPath(); 6279 } 6280 6281 /** 6282 * Derive and set the location of native libraries for the given package, 6283 * which varies depending on where and how the package was installed. 6284 */ 6285 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6286 final ApplicationInfo info = pkg.applicationInfo; 6287 final String codePath = pkg.codePath; 6288 final File codeFile = new File(codePath); 6289 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6290 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6291 6292 info.nativeLibraryRootDir = null; 6293 info.nativeLibraryRootRequiresIsa = false; 6294 info.nativeLibraryDir = null; 6295 info.secondaryNativeLibraryDir = null; 6296 6297 if (isApkFile(codeFile)) { 6298 // Monolithic install 6299 if (bundledApp) { 6300 // If "/system/lib64/apkname" exists, assume that is the per-package 6301 // native library directory to use; otherwise use "/system/lib/apkname". 6302 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6303 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6304 getPrimaryInstructionSet(info)); 6305 6306 // This is a bundled system app so choose the path based on the ABI. 6307 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6308 // is just the default path. 6309 final String apkName = deriveCodePathName(codePath); 6310 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6311 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6312 apkName).getAbsolutePath(); 6313 6314 if (info.secondaryCpuAbi != null) { 6315 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6316 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6317 secondaryLibDir, apkName).getAbsolutePath(); 6318 } 6319 } else if (asecApp) { 6320 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6321 .getAbsolutePath(); 6322 } else { 6323 final String apkName = deriveCodePathName(codePath); 6324 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6325 .getAbsolutePath(); 6326 } 6327 6328 info.nativeLibraryRootRequiresIsa = false; 6329 info.nativeLibraryDir = info.nativeLibraryRootDir; 6330 } else { 6331 // Cluster install 6332 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6333 info.nativeLibraryRootRequiresIsa = true; 6334 6335 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6336 getPrimaryInstructionSet(info)).getAbsolutePath(); 6337 6338 if (info.secondaryCpuAbi != null) { 6339 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6340 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6341 } 6342 } 6343 } 6344 6345 /** 6346 * Calculate the abis and roots for a bundled app. These can uniquely 6347 * be determined from the contents of the system partition, i.e whether 6348 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6349 * of this information, and instead assume that the system was built 6350 * sensibly. 6351 */ 6352 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6353 PackageSetting pkgSetting) { 6354 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6355 6356 // If "/system/lib64/apkname" exists, assume that is the per-package 6357 // native library directory to use; otherwise use "/system/lib/apkname". 6358 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6359 setBundledAppAbi(pkg, apkRoot, apkName); 6360 // pkgSetting might be null during rescan following uninstall of updates 6361 // to a bundled app, so accommodate that possibility. The settings in 6362 // that case will be established later from the parsed package. 6363 // 6364 // If the settings aren't null, sync them up with what we've just derived. 6365 // note that apkRoot isn't stored in the package settings. 6366 if (pkgSetting != null) { 6367 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6368 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6369 } 6370 } 6371 6372 /** 6373 * Deduces the ABI of a bundled app and sets the relevant fields on the 6374 * parsed pkg object. 6375 * 6376 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6377 * under which system libraries are installed. 6378 * @param apkName the name of the installed package. 6379 */ 6380 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6381 final File codeFile = new File(pkg.codePath); 6382 6383 final boolean has64BitLibs; 6384 final boolean has32BitLibs; 6385 if (isApkFile(codeFile)) { 6386 // Monolithic install 6387 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6388 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6389 } else { 6390 // Cluster install 6391 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6392 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6393 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6394 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6395 has64BitLibs = (new File(rootDir, isa)).exists(); 6396 } else { 6397 has64BitLibs = false; 6398 } 6399 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6400 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6401 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6402 has32BitLibs = (new File(rootDir, isa)).exists(); 6403 } else { 6404 has32BitLibs = false; 6405 } 6406 } 6407 6408 if (has64BitLibs && !has32BitLibs) { 6409 // The package has 64 bit libs, but not 32 bit libs. Its primary 6410 // ABI should be 64 bit. We can safely assume here that the bundled 6411 // native libraries correspond to the most preferred ABI in the list. 6412 6413 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6414 pkg.applicationInfo.secondaryCpuAbi = null; 6415 } else if (has32BitLibs && !has64BitLibs) { 6416 // The package has 32 bit libs but not 64 bit libs. Its primary 6417 // ABI should be 32 bit. 6418 6419 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6420 pkg.applicationInfo.secondaryCpuAbi = null; 6421 } else if (has32BitLibs && has64BitLibs) { 6422 // The application has both 64 and 32 bit bundled libraries. We check 6423 // here that the app declares multiArch support, and warn if it doesn't. 6424 // 6425 // We will be lenient here and record both ABIs. The primary will be the 6426 // ABI that's higher on the list, i.e, a device that's configured to prefer 6427 // 64 bit apps will see a 64 bit primary ABI, 6428 6429 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6430 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6431 } 6432 6433 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6434 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6435 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6436 } else { 6437 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6438 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6439 } 6440 } else { 6441 pkg.applicationInfo.primaryCpuAbi = null; 6442 pkg.applicationInfo.secondaryCpuAbi = null; 6443 } 6444 } 6445 6446 private void killApplication(String pkgName, int appId, String reason) { 6447 // Request the ActivityManager to kill the process(only for existing packages) 6448 // so that we do not end up in a confused state while the user is still using the older 6449 // version of the application while the new one gets installed. 6450 IActivityManager am = ActivityManagerNative.getDefault(); 6451 if (am != null) { 6452 try { 6453 am.killApplicationWithAppId(pkgName, appId, reason); 6454 } catch (RemoteException e) { 6455 } 6456 } 6457 } 6458 6459 void removePackageLI(PackageSetting ps, boolean chatty) { 6460 if (DEBUG_INSTALL) { 6461 if (chatty) 6462 Log.d(TAG, "Removing package " + ps.name); 6463 } 6464 6465 // writer 6466 synchronized (mPackages) { 6467 mPackages.remove(ps.name); 6468 final PackageParser.Package pkg = ps.pkg; 6469 if (pkg != null) { 6470 cleanPackageDataStructuresLILPw(pkg, chatty); 6471 } 6472 } 6473 } 6474 6475 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6476 if (DEBUG_INSTALL) { 6477 if (chatty) 6478 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6479 } 6480 6481 // writer 6482 synchronized (mPackages) { 6483 mPackages.remove(pkg.applicationInfo.packageName); 6484 cleanPackageDataStructuresLILPw(pkg, chatty); 6485 } 6486 } 6487 6488 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6489 int N = pkg.providers.size(); 6490 StringBuilder r = null; 6491 int i; 6492 for (i=0; i<N; i++) { 6493 PackageParser.Provider p = pkg.providers.get(i); 6494 mProviders.removeProvider(p); 6495 if (p.info.authority == null) { 6496 6497 /* There was another ContentProvider with this authority when 6498 * this app was installed so this authority is null, 6499 * Ignore it as we don't have to unregister the provider. 6500 */ 6501 continue; 6502 } 6503 String names[] = p.info.authority.split(";"); 6504 for (int j = 0; j < names.length; j++) { 6505 if (mProvidersByAuthority.get(names[j]) == p) { 6506 mProvidersByAuthority.remove(names[j]); 6507 if (DEBUG_REMOVE) { 6508 if (chatty) 6509 Log.d(TAG, "Unregistered content provider: " + names[j] 6510 + ", className = " + p.info.name + ", isSyncable = " 6511 + p.info.isSyncable); 6512 } 6513 } 6514 } 6515 if (DEBUG_REMOVE && chatty) { 6516 if (r == null) { 6517 r = new StringBuilder(256); 6518 } else { 6519 r.append(' '); 6520 } 6521 r.append(p.info.name); 6522 } 6523 } 6524 if (r != null) { 6525 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6526 } 6527 6528 N = pkg.services.size(); 6529 r = null; 6530 for (i=0; i<N; i++) { 6531 PackageParser.Service s = pkg.services.get(i); 6532 mServices.removeService(s); 6533 if (chatty) { 6534 if (r == null) { 6535 r = new StringBuilder(256); 6536 } else { 6537 r.append(' '); 6538 } 6539 r.append(s.info.name); 6540 } 6541 } 6542 if (r != null) { 6543 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6544 } 6545 6546 N = pkg.receivers.size(); 6547 r = null; 6548 for (i=0; i<N; i++) { 6549 PackageParser.Activity a = pkg.receivers.get(i); 6550 mReceivers.removeActivity(a, "receiver"); 6551 if (DEBUG_REMOVE && chatty) { 6552 if (r == null) { 6553 r = new StringBuilder(256); 6554 } else { 6555 r.append(' '); 6556 } 6557 r.append(a.info.name); 6558 } 6559 } 6560 if (r != null) { 6561 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6562 } 6563 6564 N = pkg.activities.size(); 6565 r = null; 6566 for (i=0; i<N; i++) { 6567 PackageParser.Activity a = pkg.activities.get(i); 6568 mActivities.removeActivity(a, "activity"); 6569 if (DEBUG_REMOVE && chatty) { 6570 if (r == null) { 6571 r = new StringBuilder(256); 6572 } else { 6573 r.append(' '); 6574 } 6575 r.append(a.info.name); 6576 } 6577 } 6578 if (r != null) { 6579 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6580 } 6581 6582 N = pkg.permissions.size(); 6583 r = null; 6584 for (i=0; i<N; i++) { 6585 PackageParser.Permission p = pkg.permissions.get(i); 6586 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6587 if (bp == null) { 6588 bp = mSettings.mPermissionTrees.get(p.info.name); 6589 } 6590 if (bp != null && bp.perm == p) { 6591 bp.perm = null; 6592 if (DEBUG_REMOVE && chatty) { 6593 if (r == null) { 6594 r = new StringBuilder(256); 6595 } else { 6596 r.append(' '); 6597 } 6598 r.append(p.info.name); 6599 } 6600 } 6601 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6602 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6603 if (appOpPerms != null) { 6604 appOpPerms.remove(pkg.packageName); 6605 } 6606 } 6607 } 6608 if (r != null) { 6609 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6610 } 6611 6612 N = pkg.requestedPermissions.size(); 6613 r = null; 6614 for (i=0; i<N; i++) { 6615 String perm = pkg.requestedPermissions.get(i); 6616 BasePermission bp = mSettings.mPermissions.get(perm); 6617 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6618 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6619 if (appOpPerms != null) { 6620 appOpPerms.remove(pkg.packageName); 6621 if (appOpPerms.isEmpty()) { 6622 mAppOpPermissionPackages.remove(perm); 6623 } 6624 } 6625 } 6626 } 6627 if (r != null) { 6628 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6629 } 6630 6631 N = pkg.instrumentation.size(); 6632 r = null; 6633 for (i=0; i<N; i++) { 6634 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6635 mInstrumentation.remove(a.getComponentName()); 6636 if (DEBUG_REMOVE && chatty) { 6637 if (r == null) { 6638 r = new StringBuilder(256); 6639 } else { 6640 r.append(' '); 6641 } 6642 r.append(a.info.name); 6643 } 6644 } 6645 if (r != null) { 6646 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6647 } 6648 6649 r = null; 6650 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6651 // Only system apps can hold shared libraries. 6652 if (pkg.libraryNames != null) { 6653 for (i=0; i<pkg.libraryNames.size(); i++) { 6654 String name = pkg.libraryNames.get(i); 6655 SharedLibraryEntry cur = mSharedLibraries.get(name); 6656 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6657 mSharedLibraries.remove(name); 6658 if (DEBUG_REMOVE && chatty) { 6659 if (r == null) { 6660 r = new StringBuilder(256); 6661 } else { 6662 r.append(' '); 6663 } 6664 r.append(name); 6665 } 6666 } 6667 } 6668 } 6669 } 6670 if (r != null) { 6671 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6672 } 6673 } 6674 6675 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6676 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6677 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6678 return true; 6679 } 6680 } 6681 return false; 6682 } 6683 6684 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6685 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6686 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6687 6688 private void updatePermissionsLPw(String changingPkg, 6689 PackageParser.Package pkgInfo, int flags) { 6690 // Make sure there are no dangling permission trees. 6691 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6692 while (it.hasNext()) { 6693 final BasePermission bp = it.next(); 6694 if (bp.packageSetting == null) { 6695 // We may not yet have parsed the package, so just see if 6696 // we still know about its settings. 6697 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6698 } 6699 if (bp.packageSetting == null) { 6700 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6701 + " from package " + bp.sourcePackage); 6702 it.remove(); 6703 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6704 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6705 Slog.i(TAG, "Removing old permission tree: " + bp.name 6706 + " from package " + bp.sourcePackage); 6707 flags |= UPDATE_PERMISSIONS_ALL; 6708 it.remove(); 6709 } 6710 } 6711 } 6712 6713 // Make sure all dynamic permissions have been assigned to a package, 6714 // and make sure there are no dangling permissions. 6715 it = mSettings.mPermissions.values().iterator(); 6716 while (it.hasNext()) { 6717 final BasePermission bp = it.next(); 6718 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6719 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6720 + bp.name + " pkg=" + bp.sourcePackage 6721 + " info=" + bp.pendingInfo); 6722 if (bp.packageSetting == null && bp.pendingInfo != null) { 6723 final BasePermission tree = findPermissionTreeLP(bp.name); 6724 if (tree != null && tree.perm != null) { 6725 bp.packageSetting = tree.packageSetting; 6726 bp.perm = new PackageParser.Permission(tree.perm.owner, 6727 new PermissionInfo(bp.pendingInfo)); 6728 bp.perm.info.packageName = tree.perm.info.packageName; 6729 bp.perm.info.name = bp.name; 6730 bp.uid = tree.uid; 6731 } 6732 } 6733 } 6734 if (bp.packageSetting == null) { 6735 // We may not yet have parsed the package, so just see if 6736 // we still know about its settings. 6737 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6738 } 6739 if (bp.packageSetting == null) { 6740 Slog.w(TAG, "Removing dangling permission: " + bp.name 6741 + " from package " + bp.sourcePackage); 6742 it.remove(); 6743 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6744 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6745 Slog.i(TAG, "Removing old permission: " + bp.name 6746 + " from package " + bp.sourcePackage); 6747 flags |= UPDATE_PERMISSIONS_ALL; 6748 it.remove(); 6749 } 6750 } 6751 } 6752 6753 // Now update the permissions for all packages, in particular 6754 // replace the granted permissions of the system packages. 6755 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6756 for (PackageParser.Package pkg : mPackages.values()) { 6757 if (pkg != pkgInfo) { 6758 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6759 } 6760 } 6761 } 6762 6763 if (pkgInfo != null) { 6764 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6765 } 6766 } 6767 6768 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6769 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6770 if (ps == null) { 6771 return; 6772 } 6773 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6774 HashSet<String> origPermissions = gp.grantedPermissions; 6775 boolean changedPermission = false; 6776 6777 if (replace) { 6778 ps.permissionsFixed = false; 6779 if (gp == ps) { 6780 origPermissions = new HashSet<String>(gp.grantedPermissions); 6781 gp.grantedPermissions.clear(); 6782 gp.gids = mGlobalGids; 6783 } 6784 } 6785 6786 if (gp.gids == null) { 6787 gp.gids = mGlobalGids; 6788 } 6789 6790 final int N = pkg.requestedPermissions.size(); 6791 for (int i=0; i<N; i++) { 6792 final String name = pkg.requestedPermissions.get(i); 6793 final boolean required = pkg.requestedPermissionsRequired.get(i); 6794 final BasePermission bp = mSettings.mPermissions.get(name); 6795 if (DEBUG_INSTALL) { 6796 if (gp != ps) { 6797 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6798 } 6799 } 6800 6801 if (bp == null || bp.packageSetting == null) { 6802 Slog.w(TAG, "Unknown permission " + name 6803 + " in package " + pkg.packageName); 6804 continue; 6805 } 6806 6807 final String perm = bp.name; 6808 boolean allowed; 6809 boolean allowedSig = false; 6810 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6811 // Keep track of app op permissions. 6812 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6813 if (pkgs == null) { 6814 pkgs = new ArraySet<>(); 6815 mAppOpPermissionPackages.put(bp.name, pkgs); 6816 } 6817 pkgs.add(pkg.packageName); 6818 } 6819 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6820 if (level == PermissionInfo.PROTECTION_NORMAL 6821 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6822 // We grant a normal or dangerous permission if any of the following 6823 // are true: 6824 // 1) The permission is required 6825 // 2) The permission is optional, but was granted in the past 6826 // 3) The permission is optional, but was requested by an 6827 // app in /system (not /data) 6828 // 6829 // Otherwise, reject the permission. 6830 allowed = (required || origPermissions.contains(perm) 6831 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6832 } else if (bp.packageSetting == null) { 6833 // This permission is invalid; skip it. 6834 allowed = false; 6835 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6836 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6837 if (allowed) { 6838 allowedSig = true; 6839 } 6840 } else { 6841 allowed = false; 6842 } 6843 if (DEBUG_INSTALL) { 6844 if (gp != ps) { 6845 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6846 } 6847 } 6848 if (allowed) { 6849 if (!isSystemApp(ps) && ps.permissionsFixed) { 6850 // If this is an existing, non-system package, then 6851 // we can't add any new permissions to it. 6852 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6853 // Except... if this is a permission that was added 6854 // to the platform (note: need to only do this when 6855 // updating the platform). 6856 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6857 } 6858 } 6859 if (allowed) { 6860 if (!gp.grantedPermissions.contains(perm)) { 6861 changedPermission = true; 6862 gp.grantedPermissions.add(perm); 6863 gp.gids = appendInts(gp.gids, bp.gids); 6864 } else if (!ps.haveGids) { 6865 gp.gids = appendInts(gp.gids, bp.gids); 6866 } 6867 } else { 6868 Slog.w(TAG, "Not granting permission " + perm 6869 + " to package " + pkg.packageName 6870 + " because it was previously installed without"); 6871 } 6872 } else { 6873 if (gp.grantedPermissions.remove(perm)) { 6874 changedPermission = true; 6875 gp.gids = removeInts(gp.gids, bp.gids); 6876 Slog.i(TAG, "Un-granting permission " + perm 6877 + " from package " + pkg.packageName 6878 + " (protectionLevel=" + bp.protectionLevel 6879 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6880 + ")"); 6881 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6882 // Don't print warning for app op permissions, since it is fine for them 6883 // not to be granted, there is a UI for the user to decide. 6884 Slog.w(TAG, "Not granting permission " + perm 6885 + " to package " + pkg.packageName 6886 + " (protectionLevel=" + bp.protectionLevel 6887 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6888 + ")"); 6889 } 6890 } 6891 } 6892 6893 if ((changedPermission || replace) && !ps.permissionsFixed && 6894 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6895 // This is the first that we have heard about this package, so the 6896 // permissions we have now selected are fixed until explicitly 6897 // changed. 6898 ps.permissionsFixed = true; 6899 } 6900 ps.haveGids = true; 6901 } 6902 6903 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6904 boolean allowed = false; 6905 final int NP = PackageParser.NEW_PERMISSIONS.length; 6906 for (int ip=0; ip<NP; ip++) { 6907 final PackageParser.NewPermissionInfo npi 6908 = PackageParser.NEW_PERMISSIONS[ip]; 6909 if (npi.name.equals(perm) 6910 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6911 allowed = true; 6912 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6913 + pkg.packageName); 6914 break; 6915 } 6916 } 6917 return allowed; 6918 } 6919 6920 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6921 BasePermission bp, HashSet<String> origPermissions) { 6922 boolean allowed; 6923 allowed = (compareSignatures( 6924 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6925 == PackageManager.SIGNATURE_MATCH) 6926 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6927 == PackageManager.SIGNATURE_MATCH); 6928 if (!allowed && (bp.protectionLevel 6929 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6930 if (isSystemApp(pkg)) { 6931 // For updated system applications, a system permission 6932 // is granted only if it had been defined by the original application. 6933 if (isUpdatedSystemApp(pkg)) { 6934 final PackageSetting sysPs = mSettings 6935 .getDisabledSystemPkgLPr(pkg.packageName); 6936 final GrantedPermissions origGp = sysPs.sharedUser != null 6937 ? sysPs.sharedUser : sysPs; 6938 6939 if (origGp.grantedPermissions.contains(perm)) { 6940 // If the original was granted this permission, we take 6941 // that grant decision as read and propagate it to the 6942 // update. 6943 allowed = true; 6944 } else { 6945 // The system apk may have been updated with an older 6946 // version of the one on the data partition, but which 6947 // granted a new system permission that it didn't have 6948 // before. In this case we do want to allow the app to 6949 // now get the new permission if the ancestral apk is 6950 // privileged to get it. 6951 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6952 for (int j=0; 6953 j<sysPs.pkg.requestedPermissions.size(); j++) { 6954 if (perm.equals( 6955 sysPs.pkg.requestedPermissions.get(j))) { 6956 allowed = true; 6957 break; 6958 } 6959 } 6960 } 6961 } 6962 } else { 6963 allowed = isPrivilegedApp(pkg); 6964 } 6965 } 6966 } 6967 if (!allowed && (bp.protectionLevel 6968 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6969 // For development permissions, a development permission 6970 // is granted only if it was already granted. 6971 allowed = origPermissions.contains(perm); 6972 } 6973 return allowed; 6974 } 6975 6976 final class ActivityIntentResolver 6977 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6978 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6979 boolean defaultOnly, int userId) { 6980 if (!sUserManager.exists(userId)) return null; 6981 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6982 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6983 } 6984 6985 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6986 int userId) { 6987 if (!sUserManager.exists(userId)) return null; 6988 mFlags = flags; 6989 return super.queryIntent(intent, resolvedType, 6990 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6991 } 6992 6993 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6994 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6995 if (!sUserManager.exists(userId)) return null; 6996 if (packageActivities == null) { 6997 return null; 6998 } 6999 mFlags = flags; 7000 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7001 final int N = packageActivities.size(); 7002 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7003 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7004 7005 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7006 for (int i = 0; i < N; ++i) { 7007 intentFilters = packageActivities.get(i).intents; 7008 if (intentFilters != null && intentFilters.size() > 0) { 7009 PackageParser.ActivityIntentInfo[] array = 7010 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7011 intentFilters.toArray(array); 7012 listCut.add(array); 7013 } 7014 } 7015 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7016 } 7017 7018 public final void addActivity(PackageParser.Activity a, String type) { 7019 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7020 mActivities.put(a.getComponentName(), a); 7021 if (DEBUG_SHOW_INFO) 7022 Log.v( 7023 TAG, " " + type + " " + 7024 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7025 if (DEBUG_SHOW_INFO) 7026 Log.v(TAG, " Class=" + a.info.name); 7027 final int NI = a.intents.size(); 7028 for (int j=0; j<NI; j++) { 7029 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7030 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7031 intent.setPriority(0); 7032 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7033 + a.className + " with priority > 0, forcing to 0"); 7034 } 7035 if (DEBUG_SHOW_INFO) { 7036 Log.v(TAG, " IntentFilter:"); 7037 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7038 } 7039 if (!intent.debugCheck()) { 7040 Log.w(TAG, "==> For Activity " + a.info.name); 7041 } 7042 addFilter(intent); 7043 } 7044 } 7045 7046 public final void removeActivity(PackageParser.Activity a, String type) { 7047 mActivities.remove(a.getComponentName()); 7048 if (DEBUG_SHOW_INFO) { 7049 Log.v(TAG, " " + type + " " 7050 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7051 : a.info.name) + ":"); 7052 Log.v(TAG, " Class=" + a.info.name); 7053 } 7054 final int NI = a.intents.size(); 7055 for (int j=0; j<NI; j++) { 7056 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7057 if (DEBUG_SHOW_INFO) { 7058 Log.v(TAG, " IntentFilter:"); 7059 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7060 } 7061 removeFilter(intent); 7062 } 7063 } 7064 7065 @Override 7066 protected boolean allowFilterResult( 7067 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7068 ActivityInfo filterAi = filter.activity.info; 7069 for (int i=dest.size()-1; i>=0; i--) { 7070 ActivityInfo destAi = dest.get(i).activityInfo; 7071 if (destAi.name == filterAi.name 7072 && destAi.packageName == filterAi.packageName) { 7073 return false; 7074 } 7075 } 7076 return true; 7077 } 7078 7079 @Override 7080 protected ActivityIntentInfo[] newArray(int size) { 7081 return new ActivityIntentInfo[size]; 7082 } 7083 7084 @Override 7085 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7086 if (!sUserManager.exists(userId)) return true; 7087 PackageParser.Package p = filter.activity.owner; 7088 if (p != null) { 7089 PackageSetting ps = (PackageSetting)p.mExtras; 7090 if (ps != null) { 7091 // System apps are never considered stopped for purposes of 7092 // filtering, because there may be no way for the user to 7093 // actually re-launch them. 7094 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7095 && ps.getStopped(userId); 7096 } 7097 } 7098 return false; 7099 } 7100 7101 @Override 7102 protected boolean isPackageForFilter(String packageName, 7103 PackageParser.ActivityIntentInfo info) { 7104 return packageName.equals(info.activity.owner.packageName); 7105 } 7106 7107 @Override 7108 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7109 int match, int userId) { 7110 if (!sUserManager.exists(userId)) return null; 7111 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7112 return null; 7113 } 7114 final PackageParser.Activity activity = info.activity; 7115 if (mSafeMode && (activity.info.applicationInfo.flags 7116 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7117 return null; 7118 } 7119 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7120 if (ps == null) { 7121 return null; 7122 } 7123 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7124 ps.readUserState(userId), userId); 7125 if (ai == null) { 7126 return null; 7127 } 7128 final ResolveInfo res = new ResolveInfo(); 7129 res.activityInfo = ai; 7130 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7131 res.filter = info; 7132 } 7133 res.priority = info.getPriority(); 7134 res.preferredOrder = activity.owner.mPreferredOrder; 7135 //System.out.println("Result: " + res.activityInfo.className + 7136 // " = " + res.priority); 7137 res.match = match; 7138 res.isDefault = info.hasDefault; 7139 res.labelRes = info.labelRes; 7140 res.nonLocalizedLabel = info.nonLocalizedLabel; 7141 if (userNeedsBadging(userId)) { 7142 res.noResourceId = true; 7143 } else { 7144 res.icon = info.icon; 7145 } 7146 res.system = isSystemApp(res.activityInfo.applicationInfo); 7147 return res; 7148 } 7149 7150 @Override 7151 protected void sortResults(List<ResolveInfo> results) { 7152 Collections.sort(results, mResolvePrioritySorter); 7153 } 7154 7155 @Override 7156 protected void dumpFilter(PrintWriter out, String prefix, 7157 PackageParser.ActivityIntentInfo filter) { 7158 out.print(prefix); out.print( 7159 Integer.toHexString(System.identityHashCode(filter.activity))); 7160 out.print(' '); 7161 filter.activity.printComponentShortName(out); 7162 out.print(" filter "); 7163 out.println(Integer.toHexString(System.identityHashCode(filter))); 7164 } 7165 7166// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7167// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7168// final List<ResolveInfo> retList = Lists.newArrayList(); 7169// while (i.hasNext()) { 7170// final ResolveInfo resolveInfo = i.next(); 7171// if (isEnabledLP(resolveInfo.activityInfo)) { 7172// retList.add(resolveInfo); 7173// } 7174// } 7175// return retList; 7176// } 7177 7178 // Keys are String (activity class name), values are Activity. 7179 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7180 = new HashMap<ComponentName, PackageParser.Activity>(); 7181 private int mFlags; 7182 } 7183 7184 private final class ServiceIntentResolver 7185 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7186 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7187 boolean defaultOnly, int userId) { 7188 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7189 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7190 } 7191 7192 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7193 int userId) { 7194 if (!sUserManager.exists(userId)) return null; 7195 mFlags = flags; 7196 return super.queryIntent(intent, resolvedType, 7197 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7198 } 7199 7200 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7201 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7202 if (!sUserManager.exists(userId)) return null; 7203 if (packageServices == null) { 7204 return null; 7205 } 7206 mFlags = flags; 7207 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7208 final int N = packageServices.size(); 7209 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7210 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7211 7212 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7213 for (int i = 0; i < N; ++i) { 7214 intentFilters = packageServices.get(i).intents; 7215 if (intentFilters != null && intentFilters.size() > 0) { 7216 PackageParser.ServiceIntentInfo[] array = 7217 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7218 intentFilters.toArray(array); 7219 listCut.add(array); 7220 } 7221 } 7222 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7223 } 7224 7225 public final void addService(PackageParser.Service s) { 7226 mServices.put(s.getComponentName(), s); 7227 if (DEBUG_SHOW_INFO) { 7228 Log.v(TAG, " " 7229 + (s.info.nonLocalizedLabel != null 7230 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7231 Log.v(TAG, " Class=" + s.info.name); 7232 } 7233 final int NI = s.intents.size(); 7234 int j; 7235 for (j=0; j<NI; j++) { 7236 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7237 if (DEBUG_SHOW_INFO) { 7238 Log.v(TAG, " IntentFilter:"); 7239 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7240 } 7241 if (!intent.debugCheck()) { 7242 Log.w(TAG, "==> For Service " + s.info.name); 7243 } 7244 addFilter(intent); 7245 } 7246 } 7247 7248 public final void removeService(PackageParser.Service s) { 7249 mServices.remove(s.getComponentName()); 7250 if (DEBUG_SHOW_INFO) { 7251 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7252 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7253 Log.v(TAG, " Class=" + s.info.name); 7254 } 7255 final int NI = s.intents.size(); 7256 int j; 7257 for (j=0; j<NI; j++) { 7258 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7259 if (DEBUG_SHOW_INFO) { 7260 Log.v(TAG, " IntentFilter:"); 7261 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7262 } 7263 removeFilter(intent); 7264 } 7265 } 7266 7267 @Override 7268 protected boolean allowFilterResult( 7269 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7270 ServiceInfo filterSi = filter.service.info; 7271 for (int i=dest.size()-1; i>=0; i--) { 7272 ServiceInfo destAi = dest.get(i).serviceInfo; 7273 if (destAi.name == filterSi.name 7274 && destAi.packageName == filterSi.packageName) { 7275 return false; 7276 } 7277 } 7278 return true; 7279 } 7280 7281 @Override 7282 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7283 return new PackageParser.ServiceIntentInfo[size]; 7284 } 7285 7286 @Override 7287 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7288 if (!sUserManager.exists(userId)) return true; 7289 PackageParser.Package p = filter.service.owner; 7290 if (p != null) { 7291 PackageSetting ps = (PackageSetting)p.mExtras; 7292 if (ps != null) { 7293 // System apps are never considered stopped for purposes of 7294 // filtering, because there may be no way for the user to 7295 // actually re-launch them. 7296 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7297 && ps.getStopped(userId); 7298 } 7299 } 7300 return false; 7301 } 7302 7303 @Override 7304 protected boolean isPackageForFilter(String packageName, 7305 PackageParser.ServiceIntentInfo info) { 7306 return packageName.equals(info.service.owner.packageName); 7307 } 7308 7309 @Override 7310 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7311 int match, int userId) { 7312 if (!sUserManager.exists(userId)) return null; 7313 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7314 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7315 return null; 7316 } 7317 final PackageParser.Service service = info.service; 7318 if (mSafeMode && (service.info.applicationInfo.flags 7319 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7320 return null; 7321 } 7322 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7323 if (ps == null) { 7324 return null; 7325 } 7326 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7327 ps.readUserState(userId), userId); 7328 if (si == null) { 7329 return null; 7330 } 7331 final ResolveInfo res = new ResolveInfo(); 7332 res.serviceInfo = si; 7333 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7334 res.filter = filter; 7335 } 7336 res.priority = info.getPriority(); 7337 res.preferredOrder = service.owner.mPreferredOrder; 7338 //System.out.println("Result: " + res.activityInfo.className + 7339 // " = " + res.priority); 7340 res.match = match; 7341 res.isDefault = info.hasDefault; 7342 res.labelRes = info.labelRes; 7343 res.nonLocalizedLabel = info.nonLocalizedLabel; 7344 res.icon = info.icon; 7345 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7346 return res; 7347 } 7348 7349 @Override 7350 protected void sortResults(List<ResolveInfo> results) { 7351 Collections.sort(results, mResolvePrioritySorter); 7352 } 7353 7354 @Override 7355 protected void dumpFilter(PrintWriter out, String prefix, 7356 PackageParser.ServiceIntentInfo filter) { 7357 out.print(prefix); out.print( 7358 Integer.toHexString(System.identityHashCode(filter.service))); 7359 out.print(' '); 7360 filter.service.printComponentShortName(out); 7361 out.print(" filter "); 7362 out.println(Integer.toHexString(System.identityHashCode(filter))); 7363 } 7364 7365// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7366// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7367// final List<ResolveInfo> retList = Lists.newArrayList(); 7368// while (i.hasNext()) { 7369// final ResolveInfo resolveInfo = (ResolveInfo) i; 7370// if (isEnabledLP(resolveInfo.serviceInfo)) { 7371// retList.add(resolveInfo); 7372// } 7373// } 7374// return retList; 7375// } 7376 7377 // Keys are String (activity class name), values are Activity. 7378 private final HashMap<ComponentName, PackageParser.Service> mServices 7379 = new HashMap<ComponentName, PackageParser.Service>(); 7380 private int mFlags; 7381 }; 7382 7383 private final class ProviderIntentResolver 7384 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7385 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7386 boolean defaultOnly, int userId) { 7387 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7388 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7389 } 7390 7391 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7392 int userId) { 7393 if (!sUserManager.exists(userId)) 7394 return null; 7395 mFlags = flags; 7396 return super.queryIntent(intent, resolvedType, 7397 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7398 } 7399 7400 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7401 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7402 if (!sUserManager.exists(userId)) 7403 return null; 7404 if (packageProviders == null) { 7405 return null; 7406 } 7407 mFlags = flags; 7408 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7409 final int N = packageProviders.size(); 7410 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7411 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7412 7413 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7414 for (int i = 0; i < N; ++i) { 7415 intentFilters = packageProviders.get(i).intents; 7416 if (intentFilters != null && intentFilters.size() > 0) { 7417 PackageParser.ProviderIntentInfo[] array = 7418 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7419 intentFilters.toArray(array); 7420 listCut.add(array); 7421 } 7422 } 7423 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7424 } 7425 7426 public final void addProvider(PackageParser.Provider p) { 7427 if (mProviders.containsKey(p.getComponentName())) { 7428 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7429 return; 7430 } 7431 7432 mProviders.put(p.getComponentName(), p); 7433 if (DEBUG_SHOW_INFO) { 7434 Log.v(TAG, " " 7435 + (p.info.nonLocalizedLabel != null 7436 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7437 Log.v(TAG, " Class=" + p.info.name); 7438 } 7439 final int NI = p.intents.size(); 7440 int j; 7441 for (j = 0; j < NI; j++) { 7442 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7443 if (DEBUG_SHOW_INFO) { 7444 Log.v(TAG, " IntentFilter:"); 7445 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7446 } 7447 if (!intent.debugCheck()) { 7448 Log.w(TAG, "==> For Provider " + p.info.name); 7449 } 7450 addFilter(intent); 7451 } 7452 } 7453 7454 public final void removeProvider(PackageParser.Provider p) { 7455 mProviders.remove(p.getComponentName()); 7456 if (DEBUG_SHOW_INFO) { 7457 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7458 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7459 Log.v(TAG, " Class=" + p.info.name); 7460 } 7461 final int NI = p.intents.size(); 7462 int j; 7463 for (j = 0; j < NI; j++) { 7464 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7465 if (DEBUG_SHOW_INFO) { 7466 Log.v(TAG, " IntentFilter:"); 7467 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7468 } 7469 removeFilter(intent); 7470 } 7471 } 7472 7473 @Override 7474 protected boolean allowFilterResult( 7475 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7476 ProviderInfo filterPi = filter.provider.info; 7477 for (int i = dest.size() - 1; i >= 0; i--) { 7478 ProviderInfo destPi = dest.get(i).providerInfo; 7479 if (destPi.name == filterPi.name 7480 && destPi.packageName == filterPi.packageName) { 7481 return false; 7482 } 7483 } 7484 return true; 7485 } 7486 7487 @Override 7488 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7489 return new PackageParser.ProviderIntentInfo[size]; 7490 } 7491 7492 @Override 7493 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7494 if (!sUserManager.exists(userId)) 7495 return true; 7496 PackageParser.Package p = filter.provider.owner; 7497 if (p != null) { 7498 PackageSetting ps = (PackageSetting) p.mExtras; 7499 if (ps != null) { 7500 // System apps are never considered stopped for purposes of 7501 // filtering, because there may be no way for the user to 7502 // actually re-launch them. 7503 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7504 && ps.getStopped(userId); 7505 } 7506 } 7507 return false; 7508 } 7509 7510 @Override 7511 protected boolean isPackageForFilter(String packageName, 7512 PackageParser.ProviderIntentInfo info) { 7513 return packageName.equals(info.provider.owner.packageName); 7514 } 7515 7516 @Override 7517 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7518 int match, int userId) { 7519 if (!sUserManager.exists(userId)) 7520 return null; 7521 final PackageParser.ProviderIntentInfo info = filter; 7522 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7523 return null; 7524 } 7525 final PackageParser.Provider provider = info.provider; 7526 if (mSafeMode && (provider.info.applicationInfo.flags 7527 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7528 return null; 7529 } 7530 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7531 if (ps == null) { 7532 return null; 7533 } 7534 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7535 ps.readUserState(userId), userId); 7536 if (pi == null) { 7537 return null; 7538 } 7539 final ResolveInfo res = new ResolveInfo(); 7540 res.providerInfo = pi; 7541 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7542 res.filter = filter; 7543 } 7544 res.priority = info.getPriority(); 7545 res.preferredOrder = provider.owner.mPreferredOrder; 7546 res.match = match; 7547 res.isDefault = info.hasDefault; 7548 res.labelRes = info.labelRes; 7549 res.nonLocalizedLabel = info.nonLocalizedLabel; 7550 res.icon = info.icon; 7551 res.system = isSystemApp(res.providerInfo.applicationInfo); 7552 return res; 7553 } 7554 7555 @Override 7556 protected void sortResults(List<ResolveInfo> results) { 7557 Collections.sort(results, mResolvePrioritySorter); 7558 } 7559 7560 @Override 7561 protected void dumpFilter(PrintWriter out, String prefix, 7562 PackageParser.ProviderIntentInfo filter) { 7563 out.print(prefix); 7564 out.print( 7565 Integer.toHexString(System.identityHashCode(filter.provider))); 7566 out.print(' '); 7567 filter.provider.printComponentShortName(out); 7568 out.print(" filter "); 7569 out.println(Integer.toHexString(System.identityHashCode(filter))); 7570 } 7571 7572 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7573 = new HashMap<ComponentName, PackageParser.Provider>(); 7574 private int mFlags; 7575 }; 7576 7577 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7578 new Comparator<ResolveInfo>() { 7579 public int compare(ResolveInfo r1, ResolveInfo r2) { 7580 int v1 = r1.priority; 7581 int v2 = r2.priority; 7582 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7583 if (v1 != v2) { 7584 return (v1 > v2) ? -1 : 1; 7585 } 7586 v1 = r1.preferredOrder; 7587 v2 = r2.preferredOrder; 7588 if (v1 != v2) { 7589 return (v1 > v2) ? -1 : 1; 7590 } 7591 if (r1.isDefault != r2.isDefault) { 7592 return r1.isDefault ? -1 : 1; 7593 } 7594 v1 = r1.match; 7595 v2 = r2.match; 7596 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7597 if (v1 != v2) { 7598 return (v1 > v2) ? -1 : 1; 7599 } 7600 if (r1.system != r2.system) { 7601 return r1.system ? -1 : 1; 7602 } 7603 return 0; 7604 } 7605 }; 7606 7607 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7608 new Comparator<ProviderInfo>() { 7609 public int compare(ProviderInfo p1, ProviderInfo p2) { 7610 final int v1 = p1.initOrder; 7611 final int v2 = p2.initOrder; 7612 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7613 } 7614 }; 7615 7616 static final void sendPackageBroadcast(String action, String pkg, 7617 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7618 int[] userIds) { 7619 IActivityManager am = ActivityManagerNative.getDefault(); 7620 if (am != null) { 7621 try { 7622 if (userIds == null) { 7623 userIds = am.getRunningUserIds(); 7624 } 7625 for (int id : userIds) { 7626 final Intent intent = new Intent(action, 7627 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7628 if (extras != null) { 7629 intent.putExtras(extras); 7630 } 7631 if (targetPkg != null) { 7632 intent.setPackage(targetPkg); 7633 } 7634 // Modify the UID when posting to other users 7635 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7636 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7637 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7638 intent.putExtra(Intent.EXTRA_UID, uid); 7639 } 7640 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7641 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7642 if (DEBUG_BROADCASTS) { 7643 RuntimeException here = new RuntimeException("here"); 7644 here.fillInStackTrace(); 7645 Slog.d(TAG, "Sending to user " + id + ": " 7646 + intent.toShortString(false, true, false, false) 7647 + " " + intent.getExtras(), here); 7648 } 7649 am.broadcastIntent(null, intent, null, finishedReceiver, 7650 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7651 finishedReceiver != null, false, id); 7652 } 7653 } catch (RemoteException ex) { 7654 } 7655 } 7656 } 7657 7658 /** 7659 * Check if the external storage media is available. This is true if there 7660 * is a mounted external storage medium or if the external storage is 7661 * emulated. 7662 */ 7663 private boolean isExternalMediaAvailable() { 7664 return mMediaMounted || Environment.isExternalStorageEmulated(); 7665 } 7666 7667 @Override 7668 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7669 // writer 7670 synchronized (mPackages) { 7671 if (!isExternalMediaAvailable()) { 7672 // If the external storage is no longer mounted at this point, 7673 // the caller may not have been able to delete all of this 7674 // packages files and can not delete any more. Bail. 7675 return null; 7676 } 7677 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7678 if (lastPackage != null) { 7679 pkgs.remove(lastPackage); 7680 } 7681 if (pkgs.size() > 0) { 7682 return pkgs.get(0); 7683 } 7684 } 7685 return null; 7686 } 7687 7688 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7689 if (false) { 7690 RuntimeException here = new RuntimeException("here"); 7691 here.fillInStackTrace(); 7692 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7693 + " andCode=" + andCode, here); 7694 } 7695 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7696 userId, andCode ? 1 : 0, packageName)); 7697 } 7698 7699 void startCleaningPackages() { 7700 // reader 7701 synchronized (mPackages) { 7702 if (!isExternalMediaAvailable()) { 7703 return; 7704 } 7705 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7706 return; 7707 } 7708 } 7709 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7710 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7711 IActivityManager am = ActivityManagerNative.getDefault(); 7712 if (am != null) { 7713 try { 7714 am.startService(null, intent, null, UserHandle.USER_OWNER); 7715 } catch (RemoteException e) { 7716 } 7717 } 7718 } 7719 7720 @Override 7721 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7722 int installFlags, String installerPackageName, VerificationParams verificationParams, 7723 String packageAbiOverride) { 7724 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7725 null); 7726 7727 final File originFile = new File(originPath); 7728 final int uid = Binder.getCallingUid(); 7729 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7730 try { 7731 if (observer != null) { 7732 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7733 } 7734 } catch (RemoteException re) { 7735 } 7736 return; 7737 } 7738 7739 UserHandle user; 7740 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7741 user = UserHandle.ALL; 7742 } else { 7743 user = new UserHandle(UserHandle.getUserId(uid)); 7744 } 7745 7746 final int filteredInstallFlags; 7747 if (uid == Process.SHELL_UID || uid == 0) { 7748 if (DEBUG_INSTALL) { 7749 Slog.v(TAG, "Install from ADB"); 7750 } 7751 filteredInstallFlags = installFlags | PackageManager.INSTALL_FROM_ADB; 7752 } else { 7753 filteredInstallFlags = installFlags & ~PackageManager.INSTALL_FROM_ADB; 7754 } 7755 7756 verificationParams.setInstallerUid(uid); 7757 7758 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7759 7760 final Message msg = mHandler.obtainMessage(INIT_COPY); 7761 msg.obj = new InstallParams(origin, observer, filteredInstallFlags, 7762 installerPackageName, verificationParams, user, packageAbiOverride); 7763 mHandler.sendMessage(msg); 7764 } 7765 7766 void installStage(String packageName, File stagedDir, String stagedCid, 7767 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7768 String installerPackageName, int installerUid, UserHandle user) { 7769 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7770 params.referrerUri, installerUid, null); 7771 7772 final OriginInfo origin; 7773 if (stagedDir != null) { 7774 origin = OriginInfo.fromStagedFile(stagedDir); 7775 } else { 7776 origin = OriginInfo.fromStagedContainer(stagedCid); 7777 } 7778 7779 final Message msg = mHandler.obtainMessage(INIT_COPY); 7780 msg.obj = new InstallParams(origin, observer, params.installFlags, 7781 installerPackageName, verifParams, user, params.abiOverride); 7782 mHandler.sendMessage(msg); 7783 } 7784 7785 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7786 Bundle extras = new Bundle(1); 7787 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7788 7789 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7790 packageName, extras, null, null, new int[] {userId}); 7791 try { 7792 IActivityManager am = ActivityManagerNative.getDefault(); 7793 final boolean isSystem = 7794 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7795 if (isSystem && am.isUserRunning(userId, false)) { 7796 // The just-installed/enabled app is bundled on the system, so presumed 7797 // to be able to run automatically without needing an explicit launch. 7798 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7799 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7800 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7801 .setPackage(packageName); 7802 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7803 android.app.AppOpsManager.OP_NONE, false, false, userId); 7804 } 7805 } catch (RemoteException e) { 7806 // shouldn't happen 7807 Slog.w(TAG, "Unable to bootstrap installed package", e); 7808 } 7809 } 7810 7811 @Override 7812 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7813 int userId) { 7814 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7815 PackageSetting pkgSetting; 7816 final int uid = Binder.getCallingUid(); 7817 if (UserHandle.getUserId(uid) != userId) { 7818 mContext.enforceCallingOrSelfPermission( 7819 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7820 "setApplicationHiddenSetting for user " + userId); 7821 } 7822 7823 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7824 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7825 return false; 7826 } 7827 7828 long callingId = Binder.clearCallingIdentity(); 7829 try { 7830 boolean sendAdded = false; 7831 boolean sendRemoved = false; 7832 // writer 7833 synchronized (mPackages) { 7834 pkgSetting = mSettings.mPackages.get(packageName); 7835 if (pkgSetting == null) { 7836 return false; 7837 } 7838 if (pkgSetting.getHidden(userId) != hidden) { 7839 pkgSetting.setHidden(hidden, userId); 7840 mSettings.writePackageRestrictionsLPr(userId); 7841 if (hidden) { 7842 sendRemoved = true; 7843 } else { 7844 sendAdded = true; 7845 } 7846 } 7847 } 7848 if (sendAdded) { 7849 sendPackageAddedForUser(packageName, pkgSetting, userId); 7850 return true; 7851 } 7852 if (sendRemoved) { 7853 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7854 "hiding pkg"); 7855 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7856 } 7857 } finally { 7858 Binder.restoreCallingIdentity(callingId); 7859 } 7860 return false; 7861 } 7862 7863 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7864 int userId) { 7865 final PackageRemovedInfo info = new PackageRemovedInfo(); 7866 info.removedPackage = packageName; 7867 info.removedUsers = new int[] {userId}; 7868 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7869 info.sendBroadcast(false, false, false); 7870 } 7871 7872 /** 7873 * Returns true if application is not found or there was an error. Otherwise it returns 7874 * the hidden state of the package for the given user. 7875 */ 7876 @Override 7877 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7878 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7879 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7880 "getApplicationHidden for user " + userId); 7881 PackageSetting pkgSetting; 7882 long callingId = Binder.clearCallingIdentity(); 7883 try { 7884 // writer 7885 synchronized (mPackages) { 7886 pkgSetting = mSettings.mPackages.get(packageName); 7887 if (pkgSetting == null) { 7888 return true; 7889 } 7890 return pkgSetting.getHidden(userId); 7891 } 7892 } finally { 7893 Binder.restoreCallingIdentity(callingId); 7894 } 7895 } 7896 7897 /** 7898 * @hide 7899 */ 7900 @Override 7901 public int installExistingPackageAsUser(String packageName, int userId) { 7902 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7903 null); 7904 PackageSetting pkgSetting; 7905 final int uid = Binder.getCallingUid(); 7906 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7907 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7908 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7909 } 7910 7911 long callingId = Binder.clearCallingIdentity(); 7912 try { 7913 boolean sendAdded = false; 7914 Bundle extras = new Bundle(1); 7915 7916 // writer 7917 synchronized (mPackages) { 7918 pkgSetting = mSettings.mPackages.get(packageName); 7919 if (pkgSetting == null) { 7920 return PackageManager.INSTALL_FAILED_INVALID_URI; 7921 } 7922 if (!pkgSetting.getInstalled(userId)) { 7923 pkgSetting.setInstalled(true, userId); 7924 pkgSetting.setHidden(false, userId); 7925 mSettings.writePackageRestrictionsLPr(userId); 7926 sendAdded = true; 7927 } 7928 } 7929 7930 if (sendAdded) { 7931 sendPackageAddedForUser(packageName, pkgSetting, userId); 7932 } 7933 } finally { 7934 Binder.restoreCallingIdentity(callingId); 7935 } 7936 7937 return PackageManager.INSTALL_SUCCEEDED; 7938 } 7939 7940 boolean isUserRestricted(int userId, String restrictionKey) { 7941 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7942 if (restrictions.getBoolean(restrictionKey, false)) { 7943 Log.w(TAG, "User is restricted: " + restrictionKey); 7944 return true; 7945 } 7946 return false; 7947 } 7948 7949 @Override 7950 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7951 mContext.enforceCallingOrSelfPermission( 7952 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7953 "Only package verification agents can verify applications"); 7954 7955 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7956 final PackageVerificationResponse response = new PackageVerificationResponse( 7957 verificationCode, Binder.getCallingUid()); 7958 msg.arg1 = id; 7959 msg.obj = response; 7960 mHandler.sendMessage(msg); 7961 } 7962 7963 @Override 7964 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7965 long millisecondsToDelay) { 7966 mContext.enforceCallingOrSelfPermission( 7967 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7968 "Only package verification agents can extend verification timeouts"); 7969 7970 final PackageVerificationState state = mPendingVerification.get(id); 7971 final PackageVerificationResponse response = new PackageVerificationResponse( 7972 verificationCodeAtTimeout, Binder.getCallingUid()); 7973 7974 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7975 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7976 } 7977 if (millisecondsToDelay < 0) { 7978 millisecondsToDelay = 0; 7979 } 7980 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7981 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7982 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7983 } 7984 7985 if ((state != null) && !state.timeoutExtended()) { 7986 state.extendTimeout(); 7987 7988 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7989 msg.arg1 = id; 7990 msg.obj = response; 7991 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7992 } 7993 } 7994 7995 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7996 int verificationCode, UserHandle user) { 7997 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7998 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7999 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8000 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8001 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8002 8003 mContext.sendBroadcastAsUser(intent, user, 8004 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8005 } 8006 8007 private ComponentName matchComponentForVerifier(String packageName, 8008 List<ResolveInfo> receivers) { 8009 ActivityInfo targetReceiver = null; 8010 8011 final int NR = receivers.size(); 8012 for (int i = 0; i < NR; i++) { 8013 final ResolveInfo info = receivers.get(i); 8014 if (info.activityInfo == null) { 8015 continue; 8016 } 8017 8018 if (packageName.equals(info.activityInfo.packageName)) { 8019 targetReceiver = info.activityInfo; 8020 break; 8021 } 8022 } 8023 8024 if (targetReceiver == null) { 8025 return null; 8026 } 8027 8028 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8029 } 8030 8031 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8032 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8033 if (pkgInfo.verifiers.length == 0) { 8034 return null; 8035 } 8036 8037 final int N = pkgInfo.verifiers.length; 8038 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8039 for (int i = 0; i < N; i++) { 8040 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8041 8042 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8043 receivers); 8044 if (comp == null) { 8045 continue; 8046 } 8047 8048 final int verifierUid = getUidForVerifier(verifierInfo); 8049 if (verifierUid == -1) { 8050 continue; 8051 } 8052 8053 if (DEBUG_VERIFY) { 8054 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8055 + " with the correct signature"); 8056 } 8057 sufficientVerifiers.add(comp); 8058 verificationState.addSufficientVerifier(verifierUid); 8059 } 8060 8061 return sufficientVerifiers; 8062 } 8063 8064 private int getUidForVerifier(VerifierInfo verifierInfo) { 8065 synchronized (mPackages) { 8066 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8067 if (pkg == null) { 8068 return -1; 8069 } else if (pkg.mSignatures.length != 1) { 8070 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8071 + " has more than one signature; ignoring"); 8072 return -1; 8073 } 8074 8075 /* 8076 * If the public key of the package's signature does not match 8077 * our expected public key, then this is a different package and 8078 * we should skip. 8079 */ 8080 8081 final byte[] expectedPublicKey; 8082 try { 8083 final Signature verifierSig = pkg.mSignatures[0]; 8084 final PublicKey publicKey = verifierSig.getPublicKey(); 8085 expectedPublicKey = publicKey.getEncoded(); 8086 } catch (CertificateException e) { 8087 return -1; 8088 } 8089 8090 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8091 8092 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8093 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8094 + " does not have the expected public key; ignoring"); 8095 return -1; 8096 } 8097 8098 return pkg.applicationInfo.uid; 8099 } 8100 } 8101 8102 @Override 8103 public void finishPackageInstall(int token) { 8104 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8105 8106 if (DEBUG_INSTALL) { 8107 Slog.v(TAG, "BM finishing package install for " + token); 8108 } 8109 8110 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8111 mHandler.sendMessage(msg); 8112 } 8113 8114 /** 8115 * Get the verification agent timeout. 8116 * 8117 * @return verification timeout in milliseconds 8118 */ 8119 private long getVerificationTimeout() { 8120 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8121 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8122 DEFAULT_VERIFICATION_TIMEOUT); 8123 } 8124 8125 /** 8126 * Get the default verification agent response code. 8127 * 8128 * @return default verification response code 8129 */ 8130 private int getDefaultVerificationResponse() { 8131 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8132 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8133 DEFAULT_VERIFICATION_RESPONSE); 8134 } 8135 8136 /** 8137 * Check whether or not package verification has been enabled. 8138 * 8139 * @return true if verification should be performed 8140 */ 8141 private boolean isVerificationEnabled(int userId, int installFlags) { 8142 if (!DEFAULT_VERIFY_ENABLE) { 8143 return false; 8144 } 8145 8146 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8147 8148 // Check if installing from ADB 8149 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8150 // Do not run verification in a test harness environment 8151 if (ActivityManager.isRunningInTestHarness()) { 8152 return false; 8153 } 8154 if (ensureVerifyAppsEnabled) { 8155 return true; 8156 } 8157 // Check if the developer does not want package verification for ADB installs 8158 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8159 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8160 return false; 8161 } 8162 } 8163 8164 if (ensureVerifyAppsEnabled) { 8165 return true; 8166 } 8167 8168 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8169 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8170 } 8171 8172 /** 8173 * Get the "allow unknown sources" setting. 8174 * 8175 * @return the current "allow unknown sources" setting 8176 */ 8177 private int getUnknownSourcesSettings() { 8178 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8179 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8180 -1); 8181 } 8182 8183 @Override 8184 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8185 final int uid = Binder.getCallingUid(); 8186 // writer 8187 synchronized (mPackages) { 8188 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8189 if (targetPackageSetting == null) { 8190 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8191 } 8192 8193 PackageSetting installerPackageSetting; 8194 if (installerPackageName != null) { 8195 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8196 if (installerPackageSetting == null) { 8197 throw new IllegalArgumentException("Unknown installer package: " 8198 + installerPackageName); 8199 } 8200 } else { 8201 installerPackageSetting = null; 8202 } 8203 8204 Signature[] callerSignature; 8205 Object obj = mSettings.getUserIdLPr(uid); 8206 if (obj != null) { 8207 if (obj instanceof SharedUserSetting) { 8208 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8209 } else if (obj instanceof PackageSetting) { 8210 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8211 } else { 8212 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8213 } 8214 } else { 8215 throw new SecurityException("Unknown calling uid " + uid); 8216 } 8217 8218 // Verify: can't set installerPackageName to a package that is 8219 // not signed with the same cert as the caller. 8220 if (installerPackageSetting != null) { 8221 if (compareSignatures(callerSignature, 8222 installerPackageSetting.signatures.mSignatures) 8223 != PackageManager.SIGNATURE_MATCH) { 8224 throw new SecurityException( 8225 "Caller does not have same cert as new installer package " 8226 + installerPackageName); 8227 } 8228 } 8229 8230 // Verify: if target already has an installer package, it must 8231 // be signed with the same cert as the caller. 8232 if (targetPackageSetting.installerPackageName != null) { 8233 PackageSetting setting = mSettings.mPackages.get( 8234 targetPackageSetting.installerPackageName); 8235 // If the currently set package isn't valid, then it's always 8236 // okay to change it. 8237 if (setting != null) { 8238 if (compareSignatures(callerSignature, 8239 setting.signatures.mSignatures) 8240 != PackageManager.SIGNATURE_MATCH) { 8241 throw new SecurityException( 8242 "Caller does not have same cert as old installer package " 8243 + targetPackageSetting.installerPackageName); 8244 } 8245 } 8246 } 8247 8248 // Okay! 8249 targetPackageSetting.installerPackageName = installerPackageName; 8250 scheduleWriteSettingsLocked(); 8251 } 8252 } 8253 8254 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8255 // Queue up an async operation since the package installation may take a little while. 8256 mHandler.post(new Runnable() { 8257 public void run() { 8258 mHandler.removeCallbacks(this); 8259 // Result object to be returned 8260 PackageInstalledInfo res = new PackageInstalledInfo(); 8261 res.returnCode = currentStatus; 8262 res.uid = -1; 8263 res.pkg = null; 8264 res.removedInfo = new PackageRemovedInfo(); 8265 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8266 args.doPreInstall(res.returnCode); 8267 synchronized (mInstallLock) { 8268 installPackageLI(args, res); 8269 } 8270 args.doPostInstall(res.returnCode, res.uid); 8271 } 8272 8273 // A restore should be performed at this point if (a) the install 8274 // succeeded, (b) the operation is not an update, and (c) the new 8275 // package has not opted out of backup participation. 8276 final boolean update = res.removedInfo.removedPackage != null; 8277 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8278 boolean doRestore = !update 8279 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8280 8281 // Set up the post-install work request bookkeeping. This will be used 8282 // and cleaned up by the post-install event handling regardless of whether 8283 // there's a restore pass performed. Token values are >= 1. 8284 int token; 8285 if (mNextInstallToken < 0) mNextInstallToken = 1; 8286 token = mNextInstallToken++; 8287 8288 PostInstallData data = new PostInstallData(args, res); 8289 mRunningInstalls.put(token, data); 8290 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8291 8292 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8293 // Pass responsibility to the Backup Manager. It will perform a 8294 // restore if appropriate, then pass responsibility back to the 8295 // Package Manager to run the post-install observer callbacks 8296 // and broadcasts. 8297 IBackupManager bm = IBackupManager.Stub.asInterface( 8298 ServiceManager.getService(Context.BACKUP_SERVICE)); 8299 if (bm != null) { 8300 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8301 + " to BM for possible restore"); 8302 try { 8303 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8304 } catch (RemoteException e) { 8305 // can't happen; the backup manager is local 8306 } catch (Exception e) { 8307 Slog.e(TAG, "Exception trying to enqueue restore", e); 8308 doRestore = false; 8309 } 8310 } else { 8311 Slog.e(TAG, "Backup Manager not found!"); 8312 doRestore = false; 8313 } 8314 } 8315 8316 if (!doRestore) { 8317 // No restore possible, or the Backup Manager was mysteriously not 8318 // available -- just fire the post-install work request directly. 8319 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8320 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8321 mHandler.sendMessage(msg); 8322 } 8323 } 8324 }); 8325 } 8326 8327 private abstract class HandlerParams { 8328 private static final int MAX_RETRIES = 4; 8329 8330 /** 8331 * Number of times startCopy() has been attempted and had a non-fatal 8332 * error. 8333 */ 8334 private int mRetries = 0; 8335 8336 /** User handle for the user requesting the information or installation. */ 8337 private final UserHandle mUser; 8338 8339 HandlerParams(UserHandle user) { 8340 mUser = user; 8341 } 8342 8343 UserHandle getUser() { 8344 return mUser; 8345 } 8346 8347 final boolean startCopy() { 8348 boolean res; 8349 try { 8350 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8351 8352 if (++mRetries > MAX_RETRIES) { 8353 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8354 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8355 handleServiceError(); 8356 return false; 8357 } else { 8358 handleStartCopy(); 8359 res = true; 8360 } 8361 } catch (RemoteException e) { 8362 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8363 mHandler.sendEmptyMessage(MCS_RECONNECT); 8364 res = false; 8365 } 8366 handleReturnCode(); 8367 return res; 8368 } 8369 8370 final void serviceError() { 8371 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8372 handleServiceError(); 8373 handleReturnCode(); 8374 } 8375 8376 abstract void handleStartCopy() throws RemoteException; 8377 abstract void handleServiceError(); 8378 abstract void handleReturnCode(); 8379 } 8380 8381 class MeasureParams extends HandlerParams { 8382 private final PackageStats mStats; 8383 private boolean mSuccess; 8384 8385 private final IPackageStatsObserver mObserver; 8386 8387 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8388 super(new UserHandle(stats.userHandle)); 8389 mObserver = observer; 8390 mStats = stats; 8391 } 8392 8393 @Override 8394 public String toString() { 8395 return "MeasureParams{" 8396 + Integer.toHexString(System.identityHashCode(this)) 8397 + " " + mStats.packageName + "}"; 8398 } 8399 8400 @Override 8401 void handleStartCopy() throws RemoteException { 8402 synchronized (mInstallLock) { 8403 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8404 } 8405 8406 if (mSuccess) { 8407 final boolean mounted; 8408 if (Environment.isExternalStorageEmulated()) { 8409 mounted = true; 8410 } else { 8411 final String status = Environment.getExternalStorageState(); 8412 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8413 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8414 } 8415 8416 if (mounted) { 8417 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8418 8419 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8420 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8421 8422 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8423 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8424 8425 // Always subtract cache size, since it's a subdirectory 8426 mStats.externalDataSize -= mStats.externalCacheSize; 8427 8428 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8429 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8430 8431 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8432 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8433 } 8434 } 8435 } 8436 8437 @Override 8438 void handleReturnCode() { 8439 if (mObserver != null) { 8440 try { 8441 mObserver.onGetStatsCompleted(mStats, mSuccess); 8442 } catch (RemoteException e) { 8443 Slog.i(TAG, "Observer no longer exists."); 8444 } 8445 } 8446 } 8447 8448 @Override 8449 void handleServiceError() { 8450 Slog.e(TAG, "Could not measure application " + mStats.packageName 8451 + " external storage"); 8452 } 8453 } 8454 8455 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8456 throws RemoteException { 8457 long result = 0; 8458 for (File path : paths) { 8459 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8460 } 8461 return result; 8462 } 8463 8464 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8465 for (File path : paths) { 8466 try { 8467 mcs.clearDirectory(path.getAbsolutePath()); 8468 } catch (RemoteException e) { 8469 } 8470 } 8471 } 8472 8473 static class OriginInfo { 8474 /** 8475 * Location where install is coming from, before it has been 8476 * copied/renamed into place. This could be a single monolithic APK 8477 * file, or a cluster directory. This location may be untrusted. 8478 */ 8479 final File file; 8480 final String cid; 8481 8482 /** 8483 * Flag indicating that {@link #file} or {@link #cid} has already been 8484 * staged, meaning downstream users don't need to defensively copy the 8485 * contents. 8486 */ 8487 final boolean staged; 8488 8489 /** 8490 * Flag indicating that {@link #file} or {@link #cid} is an already 8491 * installed app that is being moved. 8492 */ 8493 final boolean existing; 8494 8495 final String resolvedPath; 8496 final File resolvedFile; 8497 8498 static OriginInfo fromNothing() { 8499 return new OriginInfo(null, null, false, false); 8500 } 8501 8502 static OriginInfo fromUntrustedFile(File file) { 8503 return new OriginInfo(file, null, false, false); 8504 } 8505 8506 static OriginInfo fromExistingFile(File file) { 8507 return new OriginInfo(file, null, false, true); 8508 } 8509 8510 static OriginInfo fromStagedFile(File file) { 8511 return new OriginInfo(file, null, true, false); 8512 } 8513 8514 static OriginInfo fromStagedContainer(String cid) { 8515 return new OriginInfo(null, cid, true, false); 8516 } 8517 8518 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8519 this.file = file; 8520 this.cid = cid; 8521 this.staged = staged; 8522 this.existing = existing; 8523 8524 if (cid != null) { 8525 resolvedPath = PackageHelper.getSdDir(cid); 8526 resolvedFile = new File(resolvedPath); 8527 } else if (file != null) { 8528 resolvedPath = file.getAbsolutePath(); 8529 resolvedFile = file; 8530 } else { 8531 resolvedPath = null; 8532 resolvedFile = null; 8533 } 8534 } 8535 } 8536 8537 class InstallParams extends HandlerParams { 8538 final OriginInfo origin; 8539 final IPackageInstallObserver2 observer; 8540 int installFlags; 8541 final String installerPackageName; 8542 final VerificationParams verificationParams; 8543 private InstallArgs mArgs; 8544 private int mRet; 8545 final String packageAbiOverride; 8546 8547 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8548 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8549 String packageAbiOverride) { 8550 super(user); 8551 this.origin = origin; 8552 this.observer = observer; 8553 this.installFlags = installFlags; 8554 this.installerPackageName = installerPackageName; 8555 this.verificationParams = verificationParams; 8556 this.packageAbiOverride = packageAbiOverride; 8557 } 8558 8559 @Override 8560 public String toString() { 8561 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8562 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8563 } 8564 8565 public ManifestDigest getManifestDigest() { 8566 if (verificationParams == null) { 8567 return null; 8568 } 8569 return verificationParams.getManifestDigest(); 8570 } 8571 8572 private int installLocationPolicy(PackageInfoLite pkgLite) { 8573 String packageName = pkgLite.packageName; 8574 int installLocation = pkgLite.installLocation; 8575 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8576 // reader 8577 synchronized (mPackages) { 8578 PackageParser.Package pkg = mPackages.get(packageName); 8579 if (pkg != null) { 8580 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8581 // Check for downgrading. 8582 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8583 if (pkgLite.versionCode < pkg.mVersionCode) { 8584 Slog.w(TAG, "Can't install update of " + packageName 8585 + " update version " + pkgLite.versionCode 8586 + " is older than installed version " 8587 + pkg.mVersionCode); 8588 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8589 } 8590 } 8591 // Check for updated system application. 8592 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8593 if (onSd) { 8594 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8595 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8596 } 8597 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8598 } else { 8599 if (onSd) { 8600 // Install flag overrides everything. 8601 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8602 } 8603 // If current upgrade specifies particular preference 8604 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8605 // Application explicitly specified internal. 8606 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8607 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8608 // App explictly prefers external. Let policy decide 8609 } else { 8610 // Prefer previous location 8611 if (isExternal(pkg)) { 8612 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8613 } 8614 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8615 } 8616 } 8617 } else { 8618 // Invalid install. Return error code 8619 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8620 } 8621 } 8622 } 8623 // All the special cases have been taken care of. 8624 // Return result based on recommended install location. 8625 if (onSd) { 8626 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8627 } 8628 return pkgLite.recommendedInstallLocation; 8629 } 8630 8631 /* 8632 * Invoke remote method to get package information and install 8633 * location values. Override install location based on default 8634 * policy if needed and then create install arguments based 8635 * on the install location. 8636 */ 8637 public void handleStartCopy() throws RemoteException { 8638 int ret = PackageManager.INSTALL_SUCCEEDED; 8639 8640 // If we're already staged, we've firmly committed to an install location 8641 if (origin.staged) { 8642 if (origin.file != null) { 8643 installFlags |= PackageManager.INSTALL_INTERNAL; 8644 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8645 } else if (origin.cid != null) { 8646 installFlags |= PackageManager.INSTALL_EXTERNAL; 8647 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8648 } else { 8649 throw new IllegalStateException("Invalid stage location"); 8650 } 8651 } 8652 8653 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8654 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8655 8656 PackageInfoLite pkgLite = null; 8657 8658 if (onInt && onSd) { 8659 // Check if both bits are set. 8660 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8661 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8662 } else { 8663 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8664 packageAbiOverride); 8665 8666 /* 8667 * If we have too little free space, try to free cache 8668 * before giving up. 8669 */ 8670 if (!origin.staged && pkgLite.recommendedInstallLocation 8671 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8672 // TODO: focus freeing disk space on the target device 8673 final StorageManager storage = StorageManager.from(mContext); 8674 final long lowThreshold = storage.getStorageLowBytes( 8675 Environment.getDataDirectory()); 8676 8677 final long sizeBytes = mContainerService.calculateInstalledSize( 8678 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8679 8680 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8681 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8682 installFlags, packageAbiOverride); 8683 } 8684 8685 /* 8686 * The cache free must have deleted the file we 8687 * downloaded to install. 8688 * 8689 * TODO: fix the "freeCache" call to not delete 8690 * the file we care about. 8691 */ 8692 if (pkgLite.recommendedInstallLocation 8693 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8694 pkgLite.recommendedInstallLocation 8695 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8696 } 8697 } 8698 } 8699 8700 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8701 int loc = pkgLite.recommendedInstallLocation; 8702 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8703 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8704 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8705 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8706 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8707 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8708 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8709 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8710 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8711 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8712 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8713 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8714 } else { 8715 // Override with defaults if needed. 8716 loc = installLocationPolicy(pkgLite); 8717 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8718 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8719 } else if (!onSd && !onInt) { 8720 // Override install location with flags 8721 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8722 // Set the flag to install on external media. 8723 installFlags |= PackageManager.INSTALL_EXTERNAL; 8724 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8725 } else { 8726 // Make sure the flag for installing on external 8727 // media is unset 8728 installFlags |= PackageManager.INSTALL_INTERNAL; 8729 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8730 } 8731 } 8732 } 8733 } 8734 8735 final InstallArgs args = createInstallArgs(this); 8736 mArgs = args; 8737 8738 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8739 /* 8740 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8741 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8742 */ 8743 int userIdentifier = getUser().getIdentifier(); 8744 if (userIdentifier == UserHandle.USER_ALL 8745 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8746 userIdentifier = UserHandle.USER_OWNER; 8747 } 8748 8749 /* 8750 * Determine if we have any installed package verifiers. If we 8751 * do, then we'll defer to them to verify the packages. 8752 */ 8753 final int requiredUid = mRequiredVerifierPackage == null ? -1 8754 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8755 if (!origin.existing && requiredUid != -1 8756 && isVerificationEnabled(userIdentifier, installFlags)) { 8757 final Intent verification = new Intent( 8758 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8759 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8760 PACKAGE_MIME_TYPE); 8761 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8762 8763 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8764 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8765 0 /* TODO: Which userId? */); 8766 8767 if (DEBUG_VERIFY) { 8768 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8769 + verification.toString() + " with " + pkgLite.verifiers.length 8770 + " optional verifiers"); 8771 } 8772 8773 final int verificationId = mPendingVerificationToken++; 8774 8775 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8776 8777 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8778 installerPackageName); 8779 8780 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8781 installFlags); 8782 8783 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8784 pkgLite.packageName); 8785 8786 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8787 pkgLite.versionCode); 8788 8789 if (verificationParams != null) { 8790 if (verificationParams.getVerificationURI() != null) { 8791 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8792 verificationParams.getVerificationURI()); 8793 } 8794 if (verificationParams.getOriginatingURI() != null) { 8795 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8796 verificationParams.getOriginatingURI()); 8797 } 8798 if (verificationParams.getReferrer() != null) { 8799 verification.putExtra(Intent.EXTRA_REFERRER, 8800 verificationParams.getReferrer()); 8801 } 8802 if (verificationParams.getOriginatingUid() >= 0) { 8803 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8804 verificationParams.getOriginatingUid()); 8805 } 8806 if (verificationParams.getInstallerUid() >= 0) { 8807 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8808 verificationParams.getInstallerUid()); 8809 } 8810 } 8811 8812 final PackageVerificationState verificationState = new PackageVerificationState( 8813 requiredUid, args); 8814 8815 mPendingVerification.append(verificationId, verificationState); 8816 8817 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8818 receivers, verificationState); 8819 8820 /* 8821 * If any sufficient verifiers were listed in the package 8822 * manifest, attempt to ask them. 8823 */ 8824 if (sufficientVerifiers != null) { 8825 final int N = sufficientVerifiers.size(); 8826 if (N == 0) { 8827 Slog.i(TAG, "Additional verifiers required, but none installed."); 8828 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8829 } else { 8830 for (int i = 0; i < N; i++) { 8831 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8832 8833 final Intent sufficientIntent = new Intent(verification); 8834 sufficientIntent.setComponent(verifierComponent); 8835 8836 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8837 } 8838 } 8839 } 8840 8841 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8842 mRequiredVerifierPackage, receivers); 8843 if (ret == PackageManager.INSTALL_SUCCEEDED 8844 && mRequiredVerifierPackage != null) { 8845 /* 8846 * Send the intent to the required verification agent, 8847 * but only start the verification timeout after the 8848 * target BroadcastReceivers have run. 8849 */ 8850 verification.setComponent(requiredVerifierComponent); 8851 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8852 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8853 new BroadcastReceiver() { 8854 @Override 8855 public void onReceive(Context context, Intent intent) { 8856 final Message msg = mHandler 8857 .obtainMessage(CHECK_PENDING_VERIFICATION); 8858 msg.arg1 = verificationId; 8859 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8860 } 8861 }, null, 0, null, null); 8862 8863 /* 8864 * We don't want the copy to proceed until verification 8865 * succeeds, so null out this field. 8866 */ 8867 mArgs = null; 8868 } 8869 } else { 8870 /* 8871 * No package verification is enabled, so immediately start 8872 * the remote call to initiate copy using temporary file. 8873 */ 8874 ret = args.copyApk(mContainerService, true); 8875 } 8876 } 8877 8878 mRet = ret; 8879 } 8880 8881 @Override 8882 void handleReturnCode() { 8883 // If mArgs is null, then MCS couldn't be reached. When it 8884 // reconnects, it will try again to install. At that point, this 8885 // will succeed. 8886 if (mArgs != null) { 8887 processPendingInstall(mArgs, mRet); 8888 } 8889 } 8890 8891 @Override 8892 void handleServiceError() { 8893 mArgs = createInstallArgs(this); 8894 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8895 } 8896 8897 public boolean isForwardLocked() { 8898 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8899 } 8900 } 8901 8902 /** 8903 * Used during creation of InstallArgs 8904 * 8905 * @param installFlags package installation flags 8906 * @return true if should be installed on external storage 8907 */ 8908 private static boolean installOnSd(int installFlags) { 8909 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 8910 return false; 8911 } 8912 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 8913 return true; 8914 } 8915 return false; 8916 } 8917 8918 /** 8919 * Used during creation of InstallArgs 8920 * 8921 * @param installFlags package installation flags 8922 * @return true if should be installed as forward locked 8923 */ 8924 private static boolean installForwardLocked(int installFlags) { 8925 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8926 } 8927 8928 private InstallArgs createInstallArgs(InstallParams params) { 8929 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 8930 return new AsecInstallArgs(params); 8931 } else { 8932 return new FileInstallArgs(params); 8933 } 8934 } 8935 8936 /** 8937 * Create args that describe an existing installed package. Typically used 8938 * when cleaning up old installs, or used as a move source. 8939 */ 8940 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 8941 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 8942 final boolean isInAsec; 8943 if (installOnSd(installFlags)) { 8944 /* Apps on SD card are always in ASEC containers. */ 8945 isInAsec = true; 8946 } else if (installForwardLocked(installFlags) 8947 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8948 /* 8949 * Forward-locked apps are only in ASEC containers if they're the 8950 * new style 8951 */ 8952 isInAsec = true; 8953 } else { 8954 isInAsec = false; 8955 } 8956 8957 if (isInAsec) { 8958 return new AsecInstallArgs(codePath, instructionSets, 8959 installOnSd(installFlags), installForwardLocked(installFlags)); 8960 } else { 8961 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 8962 instructionSets); 8963 } 8964 } 8965 8966 static abstract class InstallArgs { 8967 /** @see InstallParams#origin */ 8968 final OriginInfo origin; 8969 8970 final IPackageInstallObserver2 observer; 8971 // Always refers to PackageManager flags only 8972 final int installFlags; 8973 final String installerPackageName; 8974 final ManifestDigest manifestDigest; 8975 final UserHandle user; 8976 final String abiOverride; 8977 8978 // The list of instruction sets supported by this app. This is currently 8979 // only used during the rmdex() phase to clean up resources. We can get rid of this 8980 // if we move dex files under the common app path. 8981 /* nullable */ String[] instructionSets; 8982 8983 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8984 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 8985 String[] instructionSets, String abiOverride) { 8986 this.origin = origin; 8987 this.installFlags = installFlags; 8988 this.observer = observer; 8989 this.installerPackageName = installerPackageName; 8990 this.manifestDigest = manifestDigest; 8991 this.user = user; 8992 this.instructionSets = instructionSets; 8993 this.abiOverride = abiOverride; 8994 } 8995 8996 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 8997 abstract int doPreInstall(int status); 8998 8999 /** 9000 * Rename package into final resting place. All paths on the given 9001 * scanned package should be updated to reflect the rename. 9002 */ 9003 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9004 abstract int doPostInstall(int status, int uid); 9005 9006 /** @see PackageSettingBase#codePathString */ 9007 abstract String getCodePath(); 9008 /** @see PackageSettingBase#resourcePathString */ 9009 abstract String getResourcePath(); 9010 abstract String getLegacyNativeLibraryPath(); 9011 9012 // Need installer lock especially for dex file removal. 9013 abstract void cleanUpResourcesLI(); 9014 abstract boolean doPostDeleteLI(boolean delete); 9015 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9016 9017 /** 9018 * Called before the source arguments are copied. This is used mostly 9019 * for MoveParams when it needs to read the source file to put it in the 9020 * destination. 9021 */ 9022 int doPreCopy() { 9023 return PackageManager.INSTALL_SUCCEEDED; 9024 } 9025 9026 /** 9027 * Called after the source arguments are copied. This is used mostly for 9028 * MoveParams when it needs to read the source file to put it in the 9029 * destination. 9030 * 9031 * @return 9032 */ 9033 int doPostCopy(int uid) { 9034 return PackageManager.INSTALL_SUCCEEDED; 9035 } 9036 9037 protected boolean isFwdLocked() { 9038 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9039 } 9040 9041 protected boolean isExternal() { 9042 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9043 } 9044 9045 UserHandle getUser() { 9046 return user; 9047 } 9048 } 9049 9050 /** 9051 * Logic to handle installation of non-ASEC applications, including copying 9052 * and renaming logic. 9053 */ 9054 class FileInstallArgs extends InstallArgs { 9055 private File codeFile; 9056 private File resourceFile; 9057 private File legacyNativeLibraryPath; 9058 9059 // Example topology: 9060 // /data/app/com.example/base.apk 9061 // /data/app/com.example/split_foo.apk 9062 // /data/app/com.example/lib/arm/libfoo.so 9063 // /data/app/com.example/lib/arm64/libfoo.so 9064 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9065 9066 /** New install */ 9067 FileInstallArgs(InstallParams params) { 9068 super(params.origin, params.observer, params.installFlags, 9069 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9070 null /* instruction sets */, params.packageAbiOverride); 9071 if (isFwdLocked()) { 9072 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9073 } 9074 } 9075 9076 /** Existing install */ 9077 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9078 String[] instructionSets) { 9079 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9080 this.codeFile = (codePath != null) ? new File(codePath) : null; 9081 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9082 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9083 new File(legacyNativeLibraryPath) : null; 9084 } 9085 9086 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9087 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9088 isFwdLocked(), abiOverride); 9089 9090 final StorageManager storage = StorageManager.from(mContext); 9091 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9092 } 9093 9094 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9095 if (origin.staged) { 9096 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9097 codeFile = origin.file; 9098 resourceFile = origin.file; 9099 return PackageManager.INSTALL_SUCCEEDED; 9100 } 9101 9102 try { 9103 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9104 codeFile = tempDir; 9105 resourceFile = tempDir; 9106 } catch (IOException e) { 9107 Slog.w(TAG, "Failed to create copy file: " + e); 9108 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9109 } 9110 9111 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9112 @Override 9113 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9114 if (!FileUtils.isValidExtFilename(name)) { 9115 throw new IllegalArgumentException("Invalid filename: " + name); 9116 } 9117 try { 9118 final File file = new File(codeFile, name); 9119 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9120 O_RDWR | O_CREAT, 0644); 9121 Os.chmod(file.getAbsolutePath(), 0644); 9122 return new ParcelFileDescriptor(fd); 9123 } catch (ErrnoException e) { 9124 throw new RemoteException("Failed to open: " + e.getMessage()); 9125 } 9126 } 9127 }; 9128 9129 int ret = PackageManager.INSTALL_SUCCEEDED; 9130 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9131 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9132 Slog.e(TAG, "Failed to copy package"); 9133 return ret; 9134 } 9135 9136 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9137 NativeLibraryHelper.Handle handle = null; 9138 try { 9139 handle = NativeLibraryHelper.Handle.create(codeFile); 9140 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9141 abiOverride); 9142 } catch (IOException e) { 9143 Slog.e(TAG, "Copying native libraries failed", e); 9144 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9145 } finally { 9146 IoUtils.closeQuietly(handle); 9147 } 9148 9149 return ret; 9150 } 9151 9152 int doPreInstall(int status) { 9153 if (status != PackageManager.INSTALL_SUCCEEDED) { 9154 cleanUp(); 9155 } 9156 return status; 9157 } 9158 9159 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9160 if (status != PackageManager.INSTALL_SUCCEEDED) { 9161 cleanUp(); 9162 return false; 9163 } else { 9164 final File beforeCodeFile = codeFile; 9165 final File afterCodeFile = getNextCodePath(pkg.packageName); 9166 9167 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9168 try { 9169 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9170 } catch (ErrnoException e) { 9171 Slog.d(TAG, "Failed to rename", e); 9172 return false; 9173 } 9174 9175 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9176 Slog.d(TAG, "Failed to restorecon"); 9177 return false; 9178 } 9179 9180 // Reflect the rename internally 9181 codeFile = afterCodeFile; 9182 resourceFile = afterCodeFile; 9183 9184 // Reflect the rename in scanned details 9185 pkg.codePath = afterCodeFile.getAbsolutePath(); 9186 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9187 pkg.baseCodePath); 9188 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9189 pkg.splitCodePaths); 9190 9191 // Reflect the rename in app info 9192 pkg.applicationInfo.setCodePath(pkg.codePath); 9193 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9194 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9195 pkg.applicationInfo.setResourcePath(pkg.codePath); 9196 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9197 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9198 9199 return true; 9200 } 9201 } 9202 9203 int doPostInstall(int status, int uid) { 9204 if (status != PackageManager.INSTALL_SUCCEEDED) { 9205 cleanUp(); 9206 } 9207 return status; 9208 } 9209 9210 @Override 9211 String getCodePath() { 9212 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9213 } 9214 9215 @Override 9216 String getResourcePath() { 9217 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9218 } 9219 9220 @Override 9221 String getLegacyNativeLibraryPath() { 9222 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9223 } 9224 9225 private boolean cleanUp() { 9226 if (codeFile == null || !codeFile.exists()) { 9227 return false; 9228 } 9229 9230 if (codeFile.isDirectory()) { 9231 FileUtils.deleteContents(codeFile); 9232 } 9233 codeFile.delete(); 9234 9235 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9236 resourceFile.delete(); 9237 } 9238 9239 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9240 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9241 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9242 } 9243 legacyNativeLibraryPath.delete(); 9244 } 9245 9246 return true; 9247 } 9248 9249 void cleanUpResourcesLI() { 9250 // Try enumerating all code paths before deleting 9251 List<String> allCodePaths = Collections.EMPTY_LIST; 9252 if (codeFile != null && codeFile.exists()) { 9253 try { 9254 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9255 allCodePaths = pkg.getAllCodePaths(); 9256 } catch (PackageParserException e) { 9257 // Ignored; we tried our best 9258 } 9259 } 9260 9261 cleanUp(); 9262 9263 if (!allCodePaths.isEmpty()) { 9264 if (instructionSets == null) { 9265 throw new IllegalStateException("instructionSet == null"); 9266 } 9267 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9268 for (String codePath : allCodePaths) { 9269 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9270 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9271 if (retCode < 0) { 9272 Slog.w(TAG, "Couldn't remove dex file for package: " 9273 + " at location " + codePath + ", retcode=" + retCode); 9274 // we don't consider this to be a failure of the core package deletion 9275 } 9276 } 9277 } 9278 } 9279 } 9280 9281 boolean doPostDeleteLI(boolean delete) { 9282 // XXX err, shouldn't we respect the delete flag? 9283 cleanUpResourcesLI(); 9284 return true; 9285 } 9286 } 9287 9288 private boolean isAsecExternal(String cid) { 9289 final String asecPath = PackageHelper.getSdFilesystem(cid); 9290 return !asecPath.startsWith(mAsecInternalPath); 9291 } 9292 9293 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9294 PackageManagerException { 9295 if (copyRet < 0) { 9296 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9297 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9298 throw new PackageManagerException(copyRet, message); 9299 } 9300 } 9301 } 9302 9303 /** 9304 * Extract the MountService "container ID" from the full code path of an 9305 * .apk. 9306 */ 9307 static String cidFromCodePath(String fullCodePath) { 9308 int eidx = fullCodePath.lastIndexOf("/"); 9309 String subStr1 = fullCodePath.substring(0, eidx); 9310 int sidx = subStr1.lastIndexOf("/"); 9311 return subStr1.substring(sidx+1, eidx); 9312 } 9313 9314 /** 9315 * Logic to handle installation of ASEC applications, including copying and 9316 * renaming logic. 9317 */ 9318 class AsecInstallArgs extends InstallArgs { 9319 static final String RES_FILE_NAME = "pkg.apk"; 9320 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9321 9322 String cid; 9323 String packagePath; 9324 String resourcePath; 9325 String legacyNativeLibraryDir; 9326 9327 /** New install */ 9328 AsecInstallArgs(InstallParams params) { 9329 super(params.origin, params.observer, params.installFlags, 9330 params.installerPackageName, params.getManifestDigest(), 9331 params.getUser(), null /* instruction sets */, 9332 params.packageAbiOverride); 9333 } 9334 9335 /** Existing install */ 9336 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9337 boolean isExternal, boolean isForwardLocked) { 9338 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9339 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9340 instructionSets, null); 9341 // Hackily pretend we're still looking at a full code path 9342 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9343 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9344 } 9345 9346 // Extract cid from fullCodePath 9347 int eidx = fullCodePath.lastIndexOf("/"); 9348 String subStr1 = fullCodePath.substring(0, eidx); 9349 int sidx = subStr1.lastIndexOf("/"); 9350 cid = subStr1.substring(sidx+1, eidx); 9351 setMountPath(subStr1); 9352 } 9353 9354 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9355 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9356 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9357 instructionSets, null); 9358 this.cid = cid; 9359 setMountPath(PackageHelper.getSdDir(cid)); 9360 } 9361 9362 void createCopyFile() { 9363 cid = mInstallerService.allocateExternalStageCidLegacy(); 9364 } 9365 9366 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9367 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9368 abiOverride); 9369 9370 final File target; 9371 if (isExternal()) { 9372 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9373 } else { 9374 target = Environment.getDataDirectory(); 9375 } 9376 9377 final StorageManager storage = StorageManager.from(mContext); 9378 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9379 } 9380 9381 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9382 if (origin.staged) { 9383 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9384 cid = origin.cid; 9385 setMountPath(PackageHelper.getSdDir(cid)); 9386 return PackageManager.INSTALL_SUCCEEDED; 9387 } 9388 9389 if (temp) { 9390 createCopyFile(); 9391 } else { 9392 /* 9393 * Pre-emptively destroy the container since it's destroyed if 9394 * copying fails due to it existing anyway. 9395 */ 9396 PackageHelper.destroySdDir(cid); 9397 } 9398 9399 final String newMountPath = imcs.copyPackageToContainer( 9400 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9401 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9402 9403 if (newMountPath != null) { 9404 setMountPath(newMountPath); 9405 return PackageManager.INSTALL_SUCCEEDED; 9406 } else { 9407 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9408 } 9409 } 9410 9411 @Override 9412 String getCodePath() { 9413 return packagePath; 9414 } 9415 9416 @Override 9417 String getResourcePath() { 9418 return resourcePath; 9419 } 9420 9421 @Override 9422 String getLegacyNativeLibraryPath() { 9423 return legacyNativeLibraryDir; 9424 } 9425 9426 int doPreInstall(int status) { 9427 if (status != PackageManager.INSTALL_SUCCEEDED) { 9428 // Destroy container 9429 PackageHelper.destroySdDir(cid); 9430 } else { 9431 boolean mounted = PackageHelper.isContainerMounted(cid); 9432 if (!mounted) { 9433 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9434 Process.SYSTEM_UID); 9435 if (newMountPath != null) { 9436 setMountPath(newMountPath); 9437 } else { 9438 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9439 } 9440 } 9441 } 9442 return status; 9443 } 9444 9445 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9446 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9447 String newMountPath = null; 9448 if (PackageHelper.isContainerMounted(cid)) { 9449 // Unmount the container 9450 if (!PackageHelper.unMountSdDir(cid)) { 9451 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9452 return false; 9453 } 9454 } 9455 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9456 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9457 " which might be stale. Will try to clean up."); 9458 // Clean up the stale container and proceed to recreate. 9459 if (!PackageHelper.destroySdDir(newCacheId)) { 9460 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9461 return false; 9462 } 9463 // Successfully cleaned up stale container. Try to rename again. 9464 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9465 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9466 + " inspite of cleaning it up."); 9467 return false; 9468 } 9469 } 9470 if (!PackageHelper.isContainerMounted(newCacheId)) { 9471 Slog.w(TAG, "Mounting container " + newCacheId); 9472 newMountPath = PackageHelper.mountSdDir(newCacheId, 9473 getEncryptKey(), Process.SYSTEM_UID); 9474 } else { 9475 newMountPath = PackageHelper.getSdDir(newCacheId); 9476 } 9477 if (newMountPath == null) { 9478 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9479 return false; 9480 } 9481 Log.i(TAG, "Succesfully renamed " + cid + 9482 " to " + newCacheId + 9483 " at new path: " + newMountPath); 9484 cid = newCacheId; 9485 9486 final File beforeCodeFile = new File(packagePath); 9487 setMountPath(newMountPath); 9488 final File afterCodeFile = new File(packagePath); 9489 9490 // Reflect the rename in scanned details 9491 pkg.codePath = afterCodeFile.getAbsolutePath(); 9492 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9493 pkg.baseCodePath); 9494 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9495 pkg.splitCodePaths); 9496 9497 // Reflect the rename in app info 9498 pkg.applicationInfo.setCodePath(pkg.codePath); 9499 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9500 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9501 pkg.applicationInfo.setResourcePath(pkg.codePath); 9502 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9503 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9504 9505 return true; 9506 } 9507 9508 private void setMountPath(String mountPath) { 9509 final File mountFile = new File(mountPath); 9510 9511 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9512 if (monolithicFile.exists()) { 9513 packagePath = monolithicFile.getAbsolutePath(); 9514 if (isFwdLocked()) { 9515 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9516 } else { 9517 resourcePath = packagePath; 9518 } 9519 } else { 9520 packagePath = mountFile.getAbsolutePath(); 9521 resourcePath = packagePath; 9522 } 9523 9524 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9525 } 9526 9527 int doPostInstall(int status, int uid) { 9528 if (status != PackageManager.INSTALL_SUCCEEDED) { 9529 cleanUp(); 9530 } else { 9531 final int groupOwner; 9532 final String protectedFile; 9533 if (isFwdLocked()) { 9534 groupOwner = UserHandle.getSharedAppGid(uid); 9535 protectedFile = RES_FILE_NAME; 9536 } else { 9537 groupOwner = -1; 9538 protectedFile = null; 9539 } 9540 9541 if (uid < Process.FIRST_APPLICATION_UID 9542 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9543 Slog.e(TAG, "Failed to finalize " + cid); 9544 PackageHelper.destroySdDir(cid); 9545 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9546 } 9547 9548 boolean mounted = PackageHelper.isContainerMounted(cid); 9549 if (!mounted) { 9550 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9551 } 9552 } 9553 return status; 9554 } 9555 9556 private void cleanUp() { 9557 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9558 9559 // Destroy secure container 9560 PackageHelper.destroySdDir(cid); 9561 } 9562 9563 private List<String> getAllCodePaths() { 9564 final File codeFile = new File(getCodePath()); 9565 if (codeFile != null && codeFile.exists()) { 9566 try { 9567 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9568 return pkg.getAllCodePaths(); 9569 } catch (PackageParserException e) { 9570 // Ignored; we tried our best 9571 } 9572 } 9573 return Collections.EMPTY_LIST; 9574 } 9575 9576 void cleanUpResourcesLI() { 9577 // Enumerate all code paths before deleting 9578 cleanUpResourcesLI(getAllCodePaths()); 9579 } 9580 9581 private void cleanUpResourcesLI(List<String> allCodePaths) { 9582 cleanUp(); 9583 9584 if (!allCodePaths.isEmpty()) { 9585 if (instructionSets == null) { 9586 throw new IllegalStateException("instructionSet == null"); 9587 } 9588 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9589 for (String codePath : allCodePaths) { 9590 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9591 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9592 if (retCode < 0) { 9593 Slog.w(TAG, "Couldn't remove dex file for package: " 9594 + " at location " + codePath + ", retcode=" + retCode); 9595 // we don't consider this to be a failure of the core package deletion 9596 } 9597 } 9598 } 9599 } 9600 } 9601 9602 boolean matchContainer(String app) { 9603 if (cid.startsWith(app)) { 9604 return true; 9605 } 9606 return false; 9607 } 9608 9609 String getPackageName() { 9610 return getAsecPackageName(cid); 9611 } 9612 9613 boolean doPostDeleteLI(boolean delete) { 9614 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9615 final List<String> allCodePaths = getAllCodePaths(); 9616 boolean mounted = PackageHelper.isContainerMounted(cid); 9617 if (mounted) { 9618 // Unmount first 9619 if (PackageHelper.unMountSdDir(cid)) { 9620 mounted = false; 9621 } 9622 } 9623 if (!mounted && delete) { 9624 cleanUpResourcesLI(allCodePaths); 9625 } 9626 return !mounted; 9627 } 9628 9629 @Override 9630 int doPreCopy() { 9631 if (isFwdLocked()) { 9632 if (!PackageHelper.fixSdPermissions(cid, 9633 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9634 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9635 } 9636 } 9637 9638 return PackageManager.INSTALL_SUCCEEDED; 9639 } 9640 9641 @Override 9642 int doPostCopy(int uid) { 9643 if (isFwdLocked()) { 9644 if (uid < Process.FIRST_APPLICATION_UID 9645 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9646 RES_FILE_NAME)) { 9647 Slog.e(TAG, "Failed to finalize " + cid); 9648 PackageHelper.destroySdDir(cid); 9649 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9650 } 9651 } 9652 9653 return PackageManager.INSTALL_SUCCEEDED; 9654 } 9655 } 9656 9657 static String getAsecPackageName(String packageCid) { 9658 int idx = packageCid.lastIndexOf("-"); 9659 if (idx == -1) { 9660 return packageCid; 9661 } 9662 return packageCid.substring(0, idx); 9663 } 9664 9665 // Utility method used to create code paths based on package name and available index. 9666 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9667 String idxStr = ""; 9668 int idx = 1; 9669 // Fall back to default value of idx=1 if prefix is not 9670 // part of oldCodePath 9671 if (oldCodePath != null) { 9672 String subStr = oldCodePath; 9673 // Drop the suffix right away 9674 if (suffix != null && subStr.endsWith(suffix)) { 9675 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9676 } 9677 // If oldCodePath already contains prefix find out the 9678 // ending index to either increment or decrement. 9679 int sidx = subStr.lastIndexOf(prefix); 9680 if (sidx != -1) { 9681 subStr = subStr.substring(sidx + prefix.length()); 9682 if (subStr != null) { 9683 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9684 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9685 } 9686 try { 9687 idx = Integer.parseInt(subStr); 9688 if (idx <= 1) { 9689 idx++; 9690 } else { 9691 idx--; 9692 } 9693 } catch(NumberFormatException e) { 9694 } 9695 } 9696 } 9697 } 9698 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9699 return prefix + idxStr; 9700 } 9701 9702 private File getNextCodePath(String packageName) { 9703 int suffix = 1; 9704 File result; 9705 do { 9706 result = new File(mAppInstallDir, packageName + "-" + suffix); 9707 suffix++; 9708 } while (result.exists()); 9709 return result; 9710 } 9711 9712 // Utility method used to ignore ADD/REMOVE events 9713 // by directory observer. 9714 private static boolean ignoreCodePath(String fullPathStr) { 9715 String apkName = deriveCodePathName(fullPathStr); 9716 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9717 if (idx != -1 && ((idx+1) < apkName.length())) { 9718 // Make sure the package ends with a numeral 9719 String version = apkName.substring(idx+1); 9720 try { 9721 Integer.parseInt(version); 9722 return true; 9723 } catch (NumberFormatException e) {} 9724 } 9725 return false; 9726 } 9727 9728 // Utility method that returns the relative package path with respect 9729 // to the installation directory. Like say for /data/data/com.test-1.apk 9730 // string com.test-1 is returned. 9731 static String deriveCodePathName(String codePath) { 9732 if (codePath == null) { 9733 return null; 9734 } 9735 final File codeFile = new File(codePath); 9736 final String name = codeFile.getName(); 9737 if (codeFile.isDirectory()) { 9738 return name; 9739 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9740 final int lastDot = name.lastIndexOf('.'); 9741 return name.substring(0, lastDot); 9742 } else { 9743 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9744 return null; 9745 } 9746 } 9747 9748 class PackageInstalledInfo { 9749 String name; 9750 int uid; 9751 // The set of users that originally had this package installed. 9752 int[] origUsers; 9753 // The set of users that now have this package installed. 9754 int[] newUsers; 9755 PackageParser.Package pkg; 9756 int returnCode; 9757 String returnMsg; 9758 PackageRemovedInfo removedInfo; 9759 9760 public void setError(int code, String msg) { 9761 returnCode = code; 9762 returnMsg = msg; 9763 Slog.w(TAG, msg); 9764 } 9765 9766 public void setError(String msg, PackageParserException e) { 9767 returnCode = e.error; 9768 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9769 Slog.w(TAG, msg, e); 9770 } 9771 9772 public void setError(String msg, PackageManagerException e) { 9773 returnCode = e.error; 9774 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9775 Slog.w(TAG, msg, e); 9776 } 9777 9778 // In some error cases we want to convey more info back to the observer 9779 String origPackage; 9780 String origPermission; 9781 } 9782 9783 /* 9784 * Install a non-existing package. 9785 */ 9786 private void installNewPackageLI(PackageParser.Package pkg, 9787 int parseFlags, int scanFlags, UserHandle user, 9788 String installerPackageName, PackageInstalledInfo res) { 9789 // Remember this for later, in case we need to rollback this install 9790 String pkgName = pkg.packageName; 9791 9792 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9793 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9794 synchronized(mPackages) { 9795 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9796 // A package with the same name is already installed, though 9797 // it has been renamed to an older name. The package we 9798 // are trying to install should be installed as an update to 9799 // the existing one, but that has not been requested, so bail. 9800 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9801 + " without first uninstalling package running as " 9802 + mSettings.mRenamedPackages.get(pkgName)); 9803 return; 9804 } 9805 if (mPackages.containsKey(pkgName)) { 9806 // Don't allow installation over an existing package with the same name. 9807 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9808 + " without first uninstalling."); 9809 return; 9810 } 9811 } 9812 9813 try { 9814 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9815 System.currentTimeMillis(), user); 9816 9817 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9818 // delete the partially installed application. the data directory will have to be 9819 // restored if it was already existing 9820 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9821 // remove package from internal structures. Note that we want deletePackageX to 9822 // delete the package data and cache directories that it created in 9823 // scanPackageLocked, unless those directories existed before we even tried to 9824 // install. 9825 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9826 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9827 res.removedInfo, true); 9828 } 9829 9830 } catch (PackageManagerException e) { 9831 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9832 } 9833 } 9834 9835 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9836 // Upgrade keysets are being used. Determine if new package has a superset of the 9837 // required keys. 9838 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9839 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9840 for (int i = 0; i < upgradeKeySets.length; i++) { 9841 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9842 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9843 return true; 9844 } 9845 } 9846 return false; 9847 } 9848 9849 private void replacePackageLI(PackageParser.Package pkg, 9850 int parseFlags, int scanFlags, UserHandle user, 9851 String installerPackageName, PackageInstalledInfo res) { 9852 PackageParser.Package oldPackage; 9853 String pkgName = pkg.packageName; 9854 int[] allUsers; 9855 boolean[] perUserInstalled; 9856 9857 // First find the old package info and check signatures 9858 synchronized(mPackages) { 9859 oldPackage = mPackages.get(pkgName); 9860 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9861 PackageSetting ps = mSettings.mPackages.get(pkgName); 9862 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9863 // default to original signature matching 9864 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9865 != PackageManager.SIGNATURE_MATCH) { 9866 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9867 "New package has a different signature: " + pkgName); 9868 return; 9869 } 9870 } else { 9871 if(!checkUpgradeKeySetLP(ps, pkg)) { 9872 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9873 "New package not signed by keys specified by upgrade-keysets: " 9874 + pkgName); 9875 return; 9876 } 9877 } 9878 9879 // In case of rollback, remember per-user/profile install state 9880 allUsers = sUserManager.getUserIds(); 9881 perUserInstalled = new boolean[allUsers.length]; 9882 for (int i = 0; i < allUsers.length; i++) { 9883 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9884 } 9885 } 9886 9887 boolean sysPkg = (isSystemApp(oldPackage)); 9888 if (sysPkg) { 9889 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9890 user, allUsers, perUserInstalled, installerPackageName, res); 9891 } else { 9892 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9893 user, allUsers, perUserInstalled, installerPackageName, res); 9894 } 9895 } 9896 9897 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9898 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9899 int[] allUsers, boolean[] perUserInstalled, 9900 String installerPackageName, PackageInstalledInfo res) { 9901 String pkgName = deletedPackage.packageName; 9902 boolean deletedPkg = true; 9903 boolean updatedSettings = false; 9904 9905 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9906 + deletedPackage); 9907 long origUpdateTime; 9908 if (pkg.mExtras != null) { 9909 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9910 } else { 9911 origUpdateTime = 0; 9912 } 9913 9914 // First delete the existing package while retaining the data directory 9915 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9916 res.removedInfo, true)) { 9917 // If the existing package wasn't successfully deleted 9918 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 9919 deletedPkg = false; 9920 } else { 9921 // Successfully deleted the old package; proceed with replace. 9922 9923 // If deleted package lived in a container, give users a chance to 9924 // relinquish resources before killing. 9925 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 9926 if (DEBUG_INSTALL) { 9927 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 9928 } 9929 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 9930 final ArrayList<String> pkgList = new ArrayList<String>(1); 9931 pkgList.add(deletedPackage.applicationInfo.packageName); 9932 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 9933 } 9934 9935 deleteCodeCacheDirsLI(pkgName); 9936 try { 9937 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 9938 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 9939 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9940 updatedSettings = true; 9941 } catch (PackageManagerException e) { 9942 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9943 } 9944 } 9945 9946 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9947 // remove package from internal structures. Note that we want deletePackageX to 9948 // delete the package data and cache directories that it created in 9949 // scanPackageLocked, unless those directories existed before we even tried to 9950 // install. 9951 if(updatedSettings) { 9952 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9953 deletePackageLI( 9954 pkgName, null, true, allUsers, perUserInstalled, 9955 PackageManager.DELETE_KEEP_DATA, 9956 res.removedInfo, true); 9957 } 9958 // Since we failed to install the new package we need to restore the old 9959 // package that we deleted. 9960 if (deletedPkg) { 9961 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9962 File restoreFile = new File(deletedPackage.codePath); 9963 // Parse old package 9964 boolean oldOnSd = isExternal(deletedPackage); 9965 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9966 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9967 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9968 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 9969 try { 9970 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 9971 } catch (PackageManagerException e) { 9972 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 9973 + e.getMessage()); 9974 return; 9975 } 9976 // Restore of old package succeeded. Update permissions. 9977 // writer 9978 synchronized (mPackages) { 9979 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9980 UPDATE_PERMISSIONS_ALL); 9981 // can downgrade to reader 9982 mSettings.writeLPr(); 9983 } 9984 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9985 } 9986 } 9987 } 9988 9989 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9990 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9991 int[] allUsers, boolean[] perUserInstalled, 9992 String installerPackageName, PackageInstalledInfo res) { 9993 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9994 + ", old=" + deletedPackage); 9995 boolean updatedSettings = false; 9996 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 9997 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9998 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9999 } 10000 String packageName = deletedPackage.packageName; 10001 if (packageName == null) { 10002 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10003 "Attempt to delete null packageName."); 10004 return; 10005 } 10006 PackageParser.Package oldPkg; 10007 PackageSetting oldPkgSetting; 10008 // reader 10009 synchronized (mPackages) { 10010 oldPkg = mPackages.get(packageName); 10011 oldPkgSetting = mSettings.mPackages.get(packageName); 10012 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10013 (oldPkgSetting == null)) { 10014 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10015 "Couldn't find package:" + packageName + " information"); 10016 return; 10017 } 10018 } 10019 10020 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10021 10022 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10023 res.removedInfo.removedPackage = packageName; 10024 // Remove existing system package 10025 removePackageLI(oldPkgSetting, true); 10026 // writer 10027 synchronized (mPackages) { 10028 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10029 // We didn't need to disable the .apk as a current system package, 10030 // which means we are replacing another update that is already 10031 // installed. We need to make sure to delete the older one's .apk. 10032 res.removedInfo.args = createInstallArgsForExisting(0, 10033 deletedPackage.applicationInfo.getCodePath(), 10034 deletedPackage.applicationInfo.getResourcePath(), 10035 deletedPackage.applicationInfo.nativeLibraryRootDir, 10036 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10037 } else { 10038 res.removedInfo.args = null; 10039 } 10040 } 10041 10042 // Successfully disabled the old package. Now proceed with re-installation 10043 deleteCodeCacheDirsLI(packageName); 10044 10045 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10046 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10047 10048 PackageParser.Package newPackage = null; 10049 try { 10050 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10051 if (newPackage.mExtras != null) { 10052 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10053 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10054 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10055 10056 // is the update attempting to change shared user? that isn't going to work... 10057 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10058 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10059 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10060 + " to " + newPkgSetting.sharedUser); 10061 updatedSettings = true; 10062 } 10063 } 10064 10065 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10066 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10067 updatedSettings = true; 10068 } 10069 10070 } catch (PackageManagerException e) { 10071 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10072 } 10073 10074 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10075 // Re installation failed. Restore old information 10076 // Remove new pkg information 10077 if (newPackage != null) { 10078 removeInstalledPackageLI(newPackage, true); 10079 } 10080 // Add back the old system package 10081 try { 10082 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10083 } catch (PackageManagerException e) { 10084 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10085 } 10086 // Restore the old system information in Settings 10087 synchronized(mPackages) { 10088 if (updatedSettings) { 10089 mSettings.enableSystemPackageLPw(packageName); 10090 mSettings.setInstallerPackageName(packageName, 10091 oldPkgSetting.installerPackageName); 10092 } 10093 mSettings.writeLPr(); 10094 } 10095 } 10096 } 10097 10098 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10099 int[] allUsers, boolean[] perUserInstalled, 10100 PackageInstalledInfo res) { 10101 String pkgName = newPackage.packageName; 10102 synchronized (mPackages) { 10103 //write settings. the installStatus will be incomplete at this stage. 10104 //note that the new package setting would have already been 10105 //added to mPackages. It hasn't been persisted yet. 10106 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10107 mSettings.writeLPr(); 10108 } 10109 10110 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10111 10112 synchronized (mPackages) { 10113 updatePermissionsLPw(newPackage.packageName, newPackage, 10114 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10115 ? UPDATE_PERMISSIONS_ALL : 0)); 10116 // For system-bundled packages, we assume that installing an upgraded version 10117 // of the package implies that the user actually wants to run that new code, 10118 // so we enable the package. 10119 if (isSystemApp(newPackage)) { 10120 // NB: implicit assumption that system package upgrades apply to all users 10121 if (DEBUG_INSTALL) { 10122 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10123 } 10124 PackageSetting ps = mSettings.mPackages.get(pkgName); 10125 if (ps != null) { 10126 if (res.origUsers != null) { 10127 for (int userHandle : res.origUsers) { 10128 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10129 userHandle, installerPackageName); 10130 } 10131 } 10132 // Also convey the prior install/uninstall state 10133 if (allUsers != null && perUserInstalled != null) { 10134 for (int i = 0; i < allUsers.length; i++) { 10135 if (DEBUG_INSTALL) { 10136 Slog.d(TAG, " user " + allUsers[i] 10137 + " => " + perUserInstalled[i]); 10138 } 10139 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10140 } 10141 // these install state changes will be persisted in the 10142 // upcoming call to mSettings.writeLPr(). 10143 } 10144 } 10145 } 10146 res.name = pkgName; 10147 res.uid = newPackage.applicationInfo.uid; 10148 res.pkg = newPackage; 10149 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10150 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10151 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10152 //to update install status 10153 mSettings.writeLPr(); 10154 } 10155 } 10156 10157 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10158 final int installFlags = args.installFlags; 10159 String installerPackageName = args.installerPackageName; 10160 File tmpPackageFile = new File(args.getCodePath()); 10161 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10162 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10163 boolean replace = false; 10164 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10165 // Result object to be returned 10166 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10167 10168 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10169 // Retrieve PackageSettings and parse package 10170 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10171 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10172 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10173 PackageParser pp = new PackageParser(); 10174 pp.setSeparateProcesses(mSeparateProcesses); 10175 pp.setDisplayMetrics(mMetrics); 10176 10177 final PackageParser.Package pkg; 10178 try { 10179 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10180 } catch (PackageParserException e) { 10181 res.setError("Failed parse during installPackageLI", e); 10182 return; 10183 } 10184 10185 // Mark that we have an install time CPU ABI override. 10186 pkg.cpuAbiOverride = args.abiOverride; 10187 10188 String pkgName = res.name = pkg.packageName; 10189 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10190 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10191 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10192 return; 10193 } 10194 } 10195 10196 try { 10197 pp.collectCertificates(pkg, parseFlags); 10198 pp.collectManifestDigest(pkg); 10199 } catch (PackageParserException e) { 10200 res.setError("Failed collect during installPackageLI", e); 10201 return; 10202 } 10203 10204 /* If the installer passed in a manifest digest, compare it now. */ 10205 if (args.manifestDigest != null) { 10206 if (DEBUG_INSTALL) { 10207 final String parsedManifest = pkg.manifestDigest == null ? "null" 10208 : pkg.manifestDigest.toString(); 10209 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10210 + parsedManifest); 10211 } 10212 10213 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10214 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10215 return; 10216 } 10217 } else if (DEBUG_INSTALL) { 10218 final String parsedManifest = pkg.manifestDigest == null 10219 ? "null" : pkg.manifestDigest.toString(); 10220 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10221 } 10222 10223 // Get rid of all references to package scan path via parser. 10224 pp = null; 10225 String oldCodePath = null; 10226 boolean systemApp = false; 10227 synchronized (mPackages) { 10228 // Check whether the newly-scanned package wants to define an already-defined perm 10229 int N = pkg.permissions.size(); 10230 for (int i = N-1; i >= 0; i--) { 10231 PackageParser.Permission perm = pkg.permissions.get(i); 10232 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10233 if (bp != null) { 10234 // If the defining package is signed with our cert, it's okay. This 10235 // also includes the "updating the same package" case, of course. 10236 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10237 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10238 // If the owning package is the system itself, we log but allow 10239 // install to proceed; we fail the install on all other permission 10240 // redefinitions. 10241 if (!bp.sourcePackage.equals("android")) { 10242 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10243 + pkg.packageName + " attempting to redeclare permission " 10244 + perm.info.name + " already owned by " + bp.sourcePackage); 10245 res.origPermission = perm.info.name; 10246 res.origPackage = bp.sourcePackage; 10247 return; 10248 } else { 10249 Slog.w(TAG, "Package " + pkg.packageName 10250 + " attempting to redeclare system permission " 10251 + perm.info.name + "; ignoring new declaration"); 10252 pkg.permissions.remove(i); 10253 } 10254 } 10255 } 10256 } 10257 10258 // Check if installing already existing package 10259 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10260 String oldName = mSettings.mRenamedPackages.get(pkgName); 10261 if (pkg.mOriginalPackages != null 10262 && pkg.mOriginalPackages.contains(oldName) 10263 && mPackages.containsKey(oldName)) { 10264 // This package is derived from an original package, 10265 // and this device has been updating from that original 10266 // name. We must continue using the original name, so 10267 // rename the new package here. 10268 pkg.setPackageName(oldName); 10269 pkgName = pkg.packageName; 10270 replace = true; 10271 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10272 + oldName + " pkgName=" + pkgName); 10273 } else if (mPackages.containsKey(pkgName)) { 10274 // This package, under its official name, already exists 10275 // on the device; we should replace it. 10276 replace = true; 10277 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10278 } 10279 } 10280 PackageSetting ps = mSettings.mPackages.get(pkgName); 10281 if (ps != null) { 10282 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10283 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10284 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10285 systemApp = (ps.pkg.applicationInfo.flags & 10286 ApplicationInfo.FLAG_SYSTEM) != 0; 10287 } 10288 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10289 } 10290 } 10291 10292 if (systemApp && onSd) { 10293 // Disable updates to system apps on sdcard 10294 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10295 "Cannot install updates to system apps on sdcard"); 10296 return; 10297 } 10298 10299 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10300 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10301 return; 10302 } 10303 10304 if (replace) { 10305 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10306 installerPackageName, res); 10307 } else { 10308 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10309 args.user, installerPackageName, res); 10310 } 10311 synchronized (mPackages) { 10312 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10313 if (ps != null) { 10314 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10315 } 10316 } 10317 } 10318 10319 private static boolean isForwardLocked(PackageParser.Package pkg) { 10320 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10321 } 10322 10323 private static boolean isForwardLocked(ApplicationInfo info) { 10324 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10325 } 10326 10327 private boolean isForwardLocked(PackageSetting ps) { 10328 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10329 } 10330 10331 private static boolean isMultiArch(PackageSetting ps) { 10332 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10333 } 10334 10335 private static boolean isMultiArch(ApplicationInfo info) { 10336 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10337 } 10338 10339 private static boolean isExternal(PackageParser.Package pkg) { 10340 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10341 } 10342 10343 private static boolean isExternal(PackageSetting ps) { 10344 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10345 } 10346 10347 private static boolean isExternal(ApplicationInfo info) { 10348 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10349 } 10350 10351 private static boolean isSystemApp(PackageParser.Package pkg) { 10352 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10353 } 10354 10355 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10356 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10357 } 10358 10359 private static boolean isSystemApp(ApplicationInfo info) { 10360 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10361 } 10362 10363 private static boolean isSystemApp(PackageSetting ps) { 10364 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10365 } 10366 10367 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10368 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10369 } 10370 10371 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10372 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10373 } 10374 10375 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10376 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10377 } 10378 10379 private int packageFlagsToInstallFlags(PackageSetting ps) { 10380 int installFlags = 0; 10381 if (isExternal(ps)) { 10382 installFlags |= PackageManager.INSTALL_EXTERNAL; 10383 } 10384 if (isForwardLocked(ps)) { 10385 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10386 } 10387 return installFlags; 10388 } 10389 10390 private void deleteTempPackageFiles() { 10391 final FilenameFilter filter = new FilenameFilter() { 10392 public boolean accept(File dir, String name) { 10393 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10394 } 10395 }; 10396 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10397 file.delete(); 10398 } 10399 } 10400 10401 @Override 10402 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10403 int flags) { 10404 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10405 flags); 10406 } 10407 10408 @Override 10409 public void deletePackage(final String packageName, 10410 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10411 mContext.enforceCallingOrSelfPermission( 10412 android.Manifest.permission.DELETE_PACKAGES, null); 10413 final int uid = Binder.getCallingUid(); 10414 if (UserHandle.getUserId(uid) != userId) { 10415 mContext.enforceCallingPermission( 10416 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10417 "deletePackage for user " + userId); 10418 } 10419 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10420 try { 10421 observer.onPackageDeleted(packageName, 10422 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10423 } catch (RemoteException re) { 10424 } 10425 return; 10426 } 10427 10428 boolean uninstallBlocked = false; 10429 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10430 int[] users = sUserManager.getUserIds(); 10431 for (int i = 0; i < users.length; ++i) { 10432 if (getBlockUninstallForUser(packageName, users[i])) { 10433 uninstallBlocked = true; 10434 break; 10435 } 10436 } 10437 } else { 10438 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10439 } 10440 if (uninstallBlocked) { 10441 try { 10442 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10443 null); 10444 } catch (RemoteException re) { 10445 } 10446 return; 10447 } 10448 10449 if (DEBUG_REMOVE) { 10450 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10451 } 10452 // Queue up an async operation since the package deletion may take a little while. 10453 mHandler.post(new Runnable() { 10454 public void run() { 10455 mHandler.removeCallbacks(this); 10456 final int returnCode = deletePackageX(packageName, userId, flags); 10457 if (observer != null) { 10458 try { 10459 observer.onPackageDeleted(packageName, returnCode, null); 10460 } catch (RemoteException e) { 10461 Log.i(TAG, "Observer no longer exists."); 10462 } //end catch 10463 } //end if 10464 } //end run 10465 }); 10466 } 10467 10468 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10469 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10470 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10471 try { 10472 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10473 || dpm.isDeviceOwner(packageName))) { 10474 return true; 10475 } 10476 } catch (RemoteException e) { 10477 } 10478 return false; 10479 } 10480 10481 /** 10482 * This method is an internal method that could be get invoked either 10483 * to delete an installed package or to clean up a failed installation. 10484 * After deleting an installed package, a broadcast is sent to notify any 10485 * listeners that the package has been installed. For cleaning up a failed 10486 * installation, the broadcast is not necessary since the package's 10487 * installation wouldn't have sent the initial broadcast either 10488 * The key steps in deleting a package are 10489 * deleting the package information in internal structures like mPackages, 10490 * deleting the packages base directories through installd 10491 * updating mSettings to reflect current status 10492 * persisting settings for later use 10493 * sending a broadcast if necessary 10494 */ 10495 private int deletePackageX(String packageName, int userId, int flags) { 10496 final PackageRemovedInfo info = new PackageRemovedInfo(); 10497 final boolean res; 10498 10499 if (isPackageDeviceAdmin(packageName, userId)) { 10500 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10501 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10502 } 10503 10504 boolean removedForAllUsers = false; 10505 boolean systemUpdate = false; 10506 10507 // for the uninstall-updates case and restricted profiles, remember the per- 10508 // userhandle installed state 10509 int[] allUsers; 10510 boolean[] perUserInstalled; 10511 synchronized (mPackages) { 10512 PackageSetting ps = mSettings.mPackages.get(packageName); 10513 allUsers = sUserManager.getUserIds(); 10514 perUserInstalled = new boolean[allUsers.length]; 10515 for (int i = 0; i < allUsers.length; i++) { 10516 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10517 } 10518 } 10519 10520 synchronized (mInstallLock) { 10521 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10522 res = deletePackageLI(packageName, 10523 (flags & PackageManager.DELETE_ALL_USERS) != 0 10524 ? UserHandle.ALL : new UserHandle(userId), 10525 true, allUsers, perUserInstalled, 10526 flags | REMOVE_CHATTY, info, true); 10527 systemUpdate = info.isRemovedPackageSystemUpdate; 10528 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10529 removedForAllUsers = true; 10530 } 10531 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10532 + " removedForAllUsers=" + removedForAllUsers); 10533 } 10534 10535 if (res) { 10536 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10537 10538 // If the removed package was a system update, the old system package 10539 // was re-enabled; we need to broadcast this information 10540 if (systemUpdate) { 10541 Bundle extras = new Bundle(1); 10542 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10543 ? info.removedAppId : info.uid); 10544 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10545 10546 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10547 extras, null, null, null); 10548 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10549 extras, null, null, null); 10550 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10551 null, packageName, null, null); 10552 } 10553 } 10554 // Force a gc here. 10555 Runtime.getRuntime().gc(); 10556 // Delete the resources here after sending the broadcast to let 10557 // other processes clean up before deleting resources. 10558 if (info.args != null) { 10559 synchronized (mInstallLock) { 10560 info.args.doPostDeleteLI(true); 10561 } 10562 } 10563 10564 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10565 } 10566 10567 static class PackageRemovedInfo { 10568 String removedPackage; 10569 int uid = -1; 10570 int removedAppId = -1; 10571 int[] removedUsers = null; 10572 boolean isRemovedPackageSystemUpdate = false; 10573 // Clean up resources deleted packages. 10574 InstallArgs args = null; 10575 10576 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10577 Bundle extras = new Bundle(1); 10578 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10579 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10580 if (replacing) { 10581 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10582 } 10583 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10584 if (removedPackage != null) { 10585 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10586 extras, null, null, removedUsers); 10587 if (fullRemove && !replacing) { 10588 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10589 extras, null, null, removedUsers); 10590 } 10591 } 10592 if (removedAppId >= 0) { 10593 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10594 removedUsers); 10595 } 10596 } 10597 } 10598 10599 /* 10600 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10601 * flag is not set, the data directory is removed as well. 10602 * make sure this flag is set for partially installed apps. If not its meaningless to 10603 * delete a partially installed application. 10604 */ 10605 private void removePackageDataLI(PackageSetting ps, 10606 int[] allUserHandles, boolean[] perUserInstalled, 10607 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10608 String packageName = ps.name; 10609 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10610 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10611 // Retrieve object to delete permissions for shared user later on 10612 final PackageSetting deletedPs; 10613 // reader 10614 synchronized (mPackages) { 10615 deletedPs = mSettings.mPackages.get(packageName); 10616 if (outInfo != null) { 10617 outInfo.removedPackage = packageName; 10618 outInfo.removedUsers = deletedPs != null 10619 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10620 : null; 10621 } 10622 } 10623 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10624 removeDataDirsLI(packageName); 10625 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10626 } 10627 // writer 10628 synchronized (mPackages) { 10629 if (deletedPs != null) { 10630 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10631 if (outInfo != null) { 10632 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10633 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10634 } 10635 if (deletedPs != null) { 10636 updatePermissionsLPw(deletedPs.name, null, 0); 10637 if (deletedPs.sharedUser != null) { 10638 // remove permissions associated with package 10639 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10640 } 10641 } 10642 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10643 } 10644 // make sure to preserve per-user disabled state if this removal was just 10645 // a downgrade of a system app to the factory package 10646 if (allUserHandles != null && perUserInstalled != null) { 10647 if (DEBUG_REMOVE) { 10648 Slog.d(TAG, "Propagating install state across downgrade"); 10649 } 10650 for (int i = 0; i < allUserHandles.length; i++) { 10651 if (DEBUG_REMOVE) { 10652 Slog.d(TAG, " user " + allUserHandles[i] 10653 + " => " + perUserInstalled[i]); 10654 } 10655 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10656 } 10657 } 10658 } 10659 // can downgrade to reader 10660 if (writeSettings) { 10661 // Save settings now 10662 mSettings.writeLPr(); 10663 } 10664 } 10665 if (outInfo != null) { 10666 // A user ID was deleted here. Go through all users and remove it 10667 // from KeyStore. 10668 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10669 } 10670 } 10671 10672 static boolean locationIsPrivileged(File path) { 10673 try { 10674 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10675 .getCanonicalPath(); 10676 return path.getCanonicalPath().startsWith(privilegedAppDir); 10677 } catch (IOException e) { 10678 Slog.e(TAG, "Unable to access code path " + path); 10679 } 10680 return false; 10681 } 10682 10683 /* 10684 * Tries to delete system package. 10685 */ 10686 private boolean deleteSystemPackageLI(PackageSetting newPs, 10687 int[] allUserHandles, boolean[] perUserInstalled, 10688 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10689 final boolean applyUserRestrictions 10690 = (allUserHandles != null) && (perUserInstalled != null); 10691 PackageSetting disabledPs = null; 10692 // Confirm if the system package has been updated 10693 // An updated system app can be deleted. This will also have to restore 10694 // the system pkg from system partition 10695 // reader 10696 synchronized (mPackages) { 10697 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10698 } 10699 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10700 + " disabledPs=" + disabledPs); 10701 if (disabledPs == null) { 10702 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10703 return false; 10704 } else if (DEBUG_REMOVE) { 10705 Slog.d(TAG, "Deleting system pkg from data partition"); 10706 } 10707 if (DEBUG_REMOVE) { 10708 if (applyUserRestrictions) { 10709 Slog.d(TAG, "Remembering install states:"); 10710 for (int i = 0; i < allUserHandles.length; i++) { 10711 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10712 } 10713 } 10714 } 10715 // Delete the updated package 10716 outInfo.isRemovedPackageSystemUpdate = true; 10717 if (disabledPs.versionCode < newPs.versionCode) { 10718 // Delete data for downgrades 10719 flags &= ~PackageManager.DELETE_KEEP_DATA; 10720 } else { 10721 // Preserve data by setting flag 10722 flags |= PackageManager.DELETE_KEEP_DATA; 10723 } 10724 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10725 allUserHandles, perUserInstalled, outInfo, writeSettings); 10726 if (!ret) { 10727 return false; 10728 } 10729 // writer 10730 synchronized (mPackages) { 10731 // Reinstate the old system package 10732 mSettings.enableSystemPackageLPw(newPs.name); 10733 // Remove any native libraries from the upgraded package. 10734 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10735 } 10736 // Install the system package 10737 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10738 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10739 if (locationIsPrivileged(disabledPs.codePath)) { 10740 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10741 } 10742 10743 final PackageParser.Package newPkg; 10744 try { 10745 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10746 } catch (PackageManagerException e) { 10747 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10748 return false; 10749 } 10750 10751 // writer 10752 synchronized (mPackages) { 10753 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10754 updatePermissionsLPw(newPkg.packageName, newPkg, 10755 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10756 if (applyUserRestrictions) { 10757 if (DEBUG_REMOVE) { 10758 Slog.d(TAG, "Propagating install state across reinstall"); 10759 } 10760 for (int i = 0; i < allUserHandles.length; i++) { 10761 if (DEBUG_REMOVE) { 10762 Slog.d(TAG, " user " + allUserHandles[i] 10763 + " => " + perUserInstalled[i]); 10764 } 10765 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10766 } 10767 // Regardless of writeSettings we need to ensure that this restriction 10768 // state propagation is persisted 10769 mSettings.writeAllUsersPackageRestrictionsLPr(); 10770 } 10771 // can downgrade to reader here 10772 if (writeSettings) { 10773 mSettings.writeLPr(); 10774 } 10775 } 10776 return true; 10777 } 10778 10779 private boolean deleteInstalledPackageLI(PackageSetting ps, 10780 boolean deleteCodeAndResources, int flags, 10781 int[] allUserHandles, boolean[] perUserInstalled, 10782 PackageRemovedInfo outInfo, boolean writeSettings) { 10783 if (outInfo != null) { 10784 outInfo.uid = ps.appId; 10785 } 10786 10787 // Delete package data from internal structures and also remove data if flag is set 10788 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10789 10790 // Delete application code and resources 10791 if (deleteCodeAndResources && (outInfo != null)) { 10792 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10793 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10794 getAppDexInstructionSets(ps)); 10795 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10796 } 10797 return true; 10798 } 10799 10800 @Override 10801 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10802 int userId) { 10803 mContext.enforceCallingOrSelfPermission( 10804 android.Manifest.permission.DELETE_PACKAGES, null); 10805 synchronized (mPackages) { 10806 PackageSetting ps = mSettings.mPackages.get(packageName); 10807 if (ps == null) { 10808 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10809 return false; 10810 } 10811 if (!ps.getInstalled(userId)) { 10812 // Can't block uninstall for an app that is not installed or enabled. 10813 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10814 return false; 10815 } 10816 ps.setBlockUninstall(blockUninstall, userId); 10817 mSettings.writePackageRestrictionsLPr(userId); 10818 } 10819 return true; 10820 } 10821 10822 @Override 10823 public boolean getBlockUninstallForUser(String packageName, int userId) { 10824 synchronized (mPackages) { 10825 PackageSetting ps = mSettings.mPackages.get(packageName); 10826 if (ps == null) { 10827 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10828 return false; 10829 } 10830 return ps.getBlockUninstall(userId); 10831 } 10832 } 10833 10834 /* 10835 * This method handles package deletion in general 10836 */ 10837 private boolean deletePackageLI(String packageName, UserHandle user, 10838 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10839 int flags, PackageRemovedInfo outInfo, 10840 boolean writeSettings) { 10841 if (packageName == null) { 10842 Slog.w(TAG, "Attempt to delete null packageName."); 10843 return false; 10844 } 10845 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10846 PackageSetting ps; 10847 boolean dataOnly = false; 10848 int removeUser = -1; 10849 int appId = -1; 10850 synchronized (mPackages) { 10851 ps = mSettings.mPackages.get(packageName); 10852 if (ps == null) { 10853 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10854 return false; 10855 } 10856 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10857 && user.getIdentifier() != UserHandle.USER_ALL) { 10858 // The caller is asking that the package only be deleted for a single 10859 // user. To do this, we just mark its uninstalled state and delete 10860 // its data. If this is a system app, we only allow this to happen if 10861 // they have set the special DELETE_SYSTEM_APP which requests different 10862 // semantics than normal for uninstalling system apps. 10863 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10864 ps.setUserState(user.getIdentifier(), 10865 COMPONENT_ENABLED_STATE_DEFAULT, 10866 false, //installed 10867 true, //stopped 10868 true, //notLaunched 10869 false, //hidden 10870 null, null, null, 10871 false // blockUninstall 10872 ); 10873 if (!isSystemApp(ps)) { 10874 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10875 // Other user still have this package installed, so all 10876 // we need to do is clear this user's data and save that 10877 // it is uninstalled. 10878 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10879 removeUser = user.getIdentifier(); 10880 appId = ps.appId; 10881 mSettings.writePackageRestrictionsLPr(removeUser); 10882 } else { 10883 // We need to set it back to 'installed' so the uninstall 10884 // broadcasts will be sent correctly. 10885 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10886 ps.setInstalled(true, user.getIdentifier()); 10887 } 10888 } else { 10889 // This is a system app, so we assume that the 10890 // other users still have this package installed, so all 10891 // we need to do is clear this user's data and save that 10892 // it is uninstalled. 10893 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10894 removeUser = user.getIdentifier(); 10895 appId = ps.appId; 10896 mSettings.writePackageRestrictionsLPr(removeUser); 10897 } 10898 } 10899 } 10900 10901 if (removeUser >= 0) { 10902 // From above, we determined that we are deleting this only 10903 // for a single user. Continue the work here. 10904 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10905 if (outInfo != null) { 10906 outInfo.removedPackage = packageName; 10907 outInfo.removedAppId = appId; 10908 outInfo.removedUsers = new int[] {removeUser}; 10909 } 10910 mInstaller.clearUserData(packageName, removeUser); 10911 removeKeystoreDataIfNeeded(removeUser, appId); 10912 schedulePackageCleaning(packageName, removeUser, false); 10913 return true; 10914 } 10915 10916 if (dataOnly) { 10917 // Delete application data first 10918 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10919 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10920 return true; 10921 } 10922 10923 boolean ret = false; 10924 if (isSystemApp(ps)) { 10925 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10926 // When an updated system application is deleted we delete the existing resources as well and 10927 // fall back to existing code in system partition 10928 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10929 flags, outInfo, writeSettings); 10930 } else { 10931 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10932 // Kill application pre-emptively especially for apps on sd. 10933 killApplication(packageName, ps.appId, "uninstall pkg"); 10934 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10935 allUserHandles, perUserInstalled, 10936 outInfo, writeSettings); 10937 } 10938 10939 return ret; 10940 } 10941 10942 private final class ClearStorageConnection implements ServiceConnection { 10943 IMediaContainerService mContainerService; 10944 10945 @Override 10946 public void onServiceConnected(ComponentName name, IBinder service) { 10947 synchronized (this) { 10948 mContainerService = IMediaContainerService.Stub.asInterface(service); 10949 notifyAll(); 10950 } 10951 } 10952 10953 @Override 10954 public void onServiceDisconnected(ComponentName name) { 10955 } 10956 } 10957 10958 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10959 final boolean mounted; 10960 if (Environment.isExternalStorageEmulated()) { 10961 mounted = true; 10962 } else { 10963 final String status = Environment.getExternalStorageState(); 10964 10965 mounted = status.equals(Environment.MEDIA_MOUNTED) 10966 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10967 } 10968 10969 if (!mounted) { 10970 return; 10971 } 10972 10973 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10974 int[] users; 10975 if (userId == UserHandle.USER_ALL) { 10976 users = sUserManager.getUserIds(); 10977 } else { 10978 users = new int[] { userId }; 10979 } 10980 final ClearStorageConnection conn = new ClearStorageConnection(); 10981 if (mContext.bindServiceAsUser( 10982 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10983 try { 10984 for (int curUser : users) { 10985 long timeout = SystemClock.uptimeMillis() + 5000; 10986 synchronized (conn) { 10987 long now = SystemClock.uptimeMillis(); 10988 while (conn.mContainerService == null && now < timeout) { 10989 try { 10990 conn.wait(timeout - now); 10991 } catch (InterruptedException e) { 10992 } 10993 } 10994 } 10995 if (conn.mContainerService == null) { 10996 return; 10997 } 10998 10999 final UserEnvironment userEnv = new UserEnvironment(curUser); 11000 clearDirectory(conn.mContainerService, 11001 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11002 if (allData) { 11003 clearDirectory(conn.mContainerService, 11004 userEnv.buildExternalStorageAppDataDirs(packageName)); 11005 clearDirectory(conn.mContainerService, 11006 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11007 } 11008 } 11009 } finally { 11010 mContext.unbindService(conn); 11011 } 11012 } 11013 } 11014 11015 @Override 11016 public void clearApplicationUserData(final String packageName, 11017 final IPackageDataObserver observer, final int userId) { 11018 mContext.enforceCallingOrSelfPermission( 11019 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11020 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11021 // Queue up an async operation since the package deletion may take a little while. 11022 mHandler.post(new Runnable() { 11023 public void run() { 11024 mHandler.removeCallbacks(this); 11025 final boolean succeeded; 11026 synchronized (mInstallLock) { 11027 succeeded = clearApplicationUserDataLI(packageName, userId); 11028 } 11029 clearExternalStorageDataSync(packageName, userId, true); 11030 if (succeeded) { 11031 // invoke DeviceStorageMonitor's update method to clear any notifications 11032 DeviceStorageMonitorInternal 11033 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11034 if (dsm != null) { 11035 dsm.checkMemory(); 11036 } 11037 } 11038 if(observer != null) { 11039 try { 11040 observer.onRemoveCompleted(packageName, succeeded); 11041 } catch (RemoteException e) { 11042 Log.i(TAG, "Observer no longer exists."); 11043 } 11044 } //end if observer 11045 } //end run 11046 }); 11047 } 11048 11049 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11050 if (packageName == null) { 11051 Slog.w(TAG, "Attempt to delete null packageName."); 11052 return false; 11053 } 11054 PackageParser.Package pkg; 11055 boolean dataOnly = false; 11056 final int appId; 11057 synchronized (mPackages) { 11058 pkg = mPackages.get(packageName); 11059 if (pkg == null) { 11060 dataOnly = true; 11061 PackageSetting ps = mSettings.mPackages.get(packageName); 11062 if ((ps == null) || (ps.pkg == null)) { 11063 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11064 return false; 11065 } 11066 pkg = ps.pkg; 11067 } 11068 if (!dataOnly) { 11069 // need to check this only for fully installed applications 11070 if (pkg == null) { 11071 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11072 return false; 11073 } 11074 final ApplicationInfo applicationInfo = pkg.applicationInfo; 11075 if (applicationInfo == null) { 11076 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11077 return false; 11078 } 11079 } 11080 if (pkg != null && pkg.applicationInfo != null) { 11081 appId = pkg.applicationInfo.uid; 11082 } else { 11083 appId = -1; 11084 } 11085 } 11086 int retCode = mInstaller.clearUserData(packageName, userId); 11087 if (retCode < 0) { 11088 Slog.w(TAG, "Couldn't remove cache files for package: " 11089 + packageName); 11090 return false; 11091 } 11092 removeKeystoreDataIfNeeded(userId, appId); 11093 11094 // Create a native library symlink only if we have native libraries 11095 // and if the native libraries are 32 bit libraries. We do not provide 11096 // this symlink for 64 bit libraries. 11097 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11098 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11099 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11100 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11101 Slog.w(TAG, "Failed linking native library dir"); 11102 return false; 11103 } 11104 } 11105 11106 return true; 11107 } 11108 11109 /** 11110 * Remove entries from the keystore daemon. Will only remove it if the 11111 * {@code appId} is valid. 11112 */ 11113 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11114 if (appId < 0) { 11115 return; 11116 } 11117 11118 final KeyStore keyStore = KeyStore.getInstance(); 11119 if (keyStore != null) { 11120 if (userId == UserHandle.USER_ALL) { 11121 for (final int individual : sUserManager.getUserIds()) { 11122 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11123 } 11124 } else { 11125 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11126 } 11127 } else { 11128 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11129 } 11130 } 11131 11132 @Override 11133 public void deleteApplicationCacheFiles(final String packageName, 11134 final IPackageDataObserver observer) { 11135 mContext.enforceCallingOrSelfPermission( 11136 android.Manifest.permission.DELETE_CACHE_FILES, null); 11137 // Queue up an async operation since the package deletion may take a little while. 11138 final int userId = UserHandle.getCallingUserId(); 11139 mHandler.post(new Runnable() { 11140 public void run() { 11141 mHandler.removeCallbacks(this); 11142 final boolean succeded; 11143 synchronized (mInstallLock) { 11144 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11145 } 11146 clearExternalStorageDataSync(packageName, userId, false); 11147 if(observer != null) { 11148 try { 11149 observer.onRemoveCompleted(packageName, succeded); 11150 } catch (RemoteException e) { 11151 Log.i(TAG, "Observer no longer exists."); 11152 } 11153 } //end if observer 11154 } //end run 11155 }); 11156 } 11157 11158 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11159 if (packageName == null) { 11160 Slog.w(TAG, "Attempt to delete null packageName."); 11161 return false; 11162 } 11163 PackageParser.Package p; 11164 synchronized (mPackages) { 11165 p = mPackages.get(packageName); 11166 } 11167 if (p == null) { 11168 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11169 return false; 11170 } 11171 final ApplicationInfo applicationInfo = p.applicationInfo; 11172 if (applicationInfo == null) { 11173 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11174 return false; 11175 } 11176 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11177 if (retCode < 0) { 11178 Slog.w(TAG, "Couldn't remove cache files for package: " 11179 + packageName + " u" + userId); 11180 return false; 11181 } 11182 return true; 11183 } 11184 11185 @Override 11186 public void getPackageSizeInfo(final String packageName, int userHandle, 11187 final IPackageStatsObserver observer) { 11188 mContext.enforceCallingOrSelfPermission( 11189 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11190 if (packageName == null) { 11191 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11192 } 11193 11194 PackageStats stats = new PackageStats(packageName, userHandle); 11195 11196 /* 11197 * Queue up an async operation since the package measurement may take a 11198 * little while. 11199 */ 11200 Message msg = mHandler.obtainMessage(INIT_COPY); 11201 msg.obj = new MeasureParams(stats, observer); 11202 mHandler.sendMessage(msg); 11203 } 11204 11205 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11206 PackageStats pStats) { 11207 if (packageName == null) { 11208 Slog.w(TAG, "Attempt to get size of null packageName."); 11209 return false; 11210 } 11211 PackageParser.Package p; 11212 boolean dataOnly = false; 11213 String libDirRoot = null; 11214 String asecPath = null; 11215 PackageSetting ps = null; 11216 synchronized (mPackages) { 11217 p = mPackages.get(packageName); 11218 ps = mSettings.mPackages.get(packageName); 11219 if(p == null) { 11220 dataOnly = true; 11221 if((ps == null) || (ps.pkg == null)) { 11222 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11223 return false; 11224 } 11225 p = ps.pkg; 11226 } 11227 if (ps != null) { 11228 libDirRoot = ps.legacyNativeLibraryPathString; 11229 } 11230 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11231 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11232 if (secureContainerId != null) { 11233 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11234 } 11235 } 11236 } 11237 String publicSrcDir = null; 11238 if(!dataOnly) { 11239 final ApplicationInfo applicationInfo = p.applicationInfo; 11240 if (applicationInfo == null) { 11241 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11242 return false; 11243 } 11244 if (isForwardLocked(p)) { 11245 publicSrcDir = applicationInfo.getBaseResourcePath(); 11246 } 11247 } 11248 // TODO: extend to measure size of split APKs 11249 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11250 // not just the first level. 11251 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11252 // just the primary. 11253 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11254 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11255 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11256 if (res < 0) { 11257 return false; 11258 } 11259 11260 // Fix-up for forward-locked applications in ASEC containers. 11261 if (!isExternal(p)) { 11262 pStats.codeSize += pStats.externalCodeSize; 11263 pStats.externalCodeSize = 0L; 11264 } 11265 11266 return true; 11267 } 11268 11269 11270 @Override 11271 public void addPackageToPreferred(String packageName) { 11272 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11273 } 11274 11275 @Override 11276 public void removePackageFromPreferred(String packageName) { 11277 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11278 } 11279 11280 @Override 11281 public List<PackageInfo> getPreferredPackages(int flags) { 11282 return new ArrayList<PackageInfo>(); 11283 } 11284 11285 private int getUidTargetSdkVersionLockedLPr(int uid) { 11286 Object obj = mSettings.getUserIdLPr(uid); 11287 if (obj instanceof SharedUserSetting) { 11288 final SharedUserSetting sus = (SharedUserSetting) obj; 11289 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11290 final Iterator<PackageSetting> it = sus.packages.iterator(); 11291 while (it.hasNext()) { 11292 final PackageSetting ps = it.next(); 11293 if (ps.pkg != null) { 11294 int v = ps.pkg.applicationInfo.targetSdkVersion; 11295 if (v < vers) vers = v; 11296 } 11297 } 11298 return vers; 11299 } else if (obj instanceof PackageSetting) { 11300 final PackageSetting ps = (PackageSetting) obj; 11301 if (ps.pkg != null) { 11302 return ps.pkg.applicationInfo.targetSdkVersion; 11303 } 11304 } 11305 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11306 } 11307 11308 @Override 11309 public void addPreferredActivity(IntentFilter filter, int match, 11310 ComponentName[] set, ComponentName activity, int userId) { 11311 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11312 "Adding preferred"); 11313 } 11314 11315 private void addPreferredActivityInternal(IntentFilter filter, int match, 11316 ComponentName[] set, ComponentName activity, boolean always, int userId, 11317 String opname) { 11318 // writer 11319 int callingUid = Binder.getCallingUid(); 11320 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11321 if (filter.countActions() == 0) { 11322 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11323 return; 11324 } 11325 synchronized (mPackages) { 11326 if (mContext.checkCallingOrSelfPermission( 11327 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11328 != PackageManager.PERMISSION_GRANTED) { 11329 if (getUidTargetSdkVersionLockedLPr(callingUid) 11330 < Build.VERSION_CODES.FROYO) { 11331 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11332 + callingUid); 11333 return; 11334 } 11335 mContext.enforceCallingOrSelfPermission( 11336 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11337 } 11338 11339 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11340 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11341 + userId + ":"); 11342 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11343 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11344 mSettings.writePackageRestrictionsLPr(userId); 11345 } 11346 } 11347 11348 @Override 11349 public void replacePreferredActivity(IntentFilter filter, int match, 11350 ComponentName[] set, ComponentName activity, int userId) { 11351 if (filter.countActions() != 1) { 11352 throw new IllegalArgumentException( 11353 "replacePreferredActivity expects filter to have only 1 action."); 11354 } 11355 if (filter.countDataAuthorities() != 0 11356 || filter.countDataPaths() != 0 11357 || filter.countDataSchemes() > 1 11358 || filter.countDataTypes() != 0) { 11359 throw new IllegalArgumentException( 11360 "replacePreferredActivity expects filter to have no data authorities, " + 11361 "paths, or types; and at most one scheme."); 11362 } 11363 11364 final int callingUid = Binder.getCallingUid(); 11365 enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity"); 11366 synchronized (mPackages) { 11367 if (mContext.checkCallingOrSelfPermission( 11368 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11369 != PackageManager.PERMISSION_GRANTED) { 11370 if (getUidTargetSdkVersionLockedLPr(callingUid) 11371 < Build.VERSION_CODES.FROYO) { 11372 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11373 + Binder.getCallingUid()); 11374 return; 11375 } 11376 mContext.enforceCallingOrSelfPermission( 11377 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11378 } 11379 11380 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11381 if (pir != null) { 11382 // Get all of the existing entries that exactly match this filter. 11383 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11384 if (existing != null && existing.size() == 1) { 11385 PreferredActivity cur = existing.get(0); 11386 if (DEBUG_PREFERRED) { 11387 Slog.i(TAG, "Checking replace of preferred:"); 11388 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11389 if (!cur.mPref.mAlways) { 11390 Slog.i(TAG, " -- CUR; not mAlways!"); 11391 } else { 11392 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11393 Slog.i(TAG, " -- CUR: mSet=" 11394 + Arrays.toString(cur.mPref.mSetComponents)); 11395 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11396 Slog.i(TAG, " -- NEW: mMatch=" 11397 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11398 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11399 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11400 } 11401 } 11402 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11403 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11404 && cur.mPref.sameSet(set)) { 11405 if (DEBUG_PREFERRED) { 11406 Slog.i(TAG, "Replacing with same preferred activity " 11407 + cur.mPref.mShortComponent + " for user " 11408 + userId + ":"); 11409 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11410 } else { 11411 Slog.i(TAG, "Replacing with same preferred activity " 11412 + cur.mPref.mShortComponent + " for user " 11413 + userId); 11414 } 11415 return; 11416 } 11417 } 11418 11419 if (existing != null) { 11420 if (DEBUG_PREFERRED) { 11421 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11422 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11423 } 11424 for (int i = 0; i < existing.size(); i++) { 11425 PreferredActivity pa = existing.get(i); 11426 if (DEBUG_PREFERRED) { 11427 Slog.i(TAG, "Removing existing preferred activity " 11428 + pa.mPref.mComponent + ":"); 11429 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11430 } 11431 pir.removeFilter(pa); 11432 } 11433 } 11434 } 11435 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11436 "Replacing preferred"); 11437 } 11438 } 11439 11440 @Override 11441 public void clearPackagePreferredActivities(String packageName) { 11442 final int uid = Binder.getCallingUid(); 11443 // writer 11444 synchronized (mPackages) { 11445 PackageParser.Package pkg = mPackages.get(packageName); 11446 if (pkg == null || pkg.applicationInfo.uid != uid) { 11447 if (mContext.checkCallingOrSelfPermission( 11448 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11449 != PackageManager.PERMISSION_GRANTED) { 11450 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11451 < Build.VERSION_CODES.FROYO) { 11452 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11453 + Binder.getCallingUid()); 11454 return; 11455 } 11456 mContext.enforceCallingOrSelfPermission( 11457 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11458 } 11459 } 11460 11461 int user = UserHandle.getCallingUserId(); 11462 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11463 mSettings.writePackageRestrictionsLPr(user); 11464 scheduleWriteSettingsLocked(); 11465 } 11466 } 11467 } 11468 11469 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11470 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11471 ArrayList<PreferredActivity> removed = null; 11472 boolean changed = false; 11473 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11474 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11475 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11476 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11477 continue; 11478 } 11479 Iterator<PreferredActivity> it = pir.filterIterator(); 11480 while (it.hasNext()) { 11481 PreferredActivity pa = it.next(); 11482 // Mark entry for removal only if it matches the package name 11483 // and the entry is of type "always". 11484 if (packageName == null || 11485 (pa.mPref.mComponent.getPackageName().equals(packageName) 11486 && pa.mPref.mAlways)) { 11487 if (removed == null) { 11488 removed = new ArrayList<PreferredActivity>(); 11489 } 11490 removed.add(pa); 11491 } 11492 } 11493 if (removed != null) { 11494 for (int j=0; j<removed.size(); j++) { 11495 PreferredActivity pa = removed.get(j); 11496 pir.removeFilter(pa); 11497 } 11498 changed = true; 11499 } 11500 } 11501 return changed; 11502 } 11503 11504 @Override 11505 public void resetPreferredActivities(int userId) { 11506 mContext.enforceCallingOrSelfPermission( 11507 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11508 // writer 11509 synchronized (mPackages) { 11510 int user = UserHandle.getCallingUserId(); 11511 clearPackagePreferredActivitiesLPw(null, user); 11512 mSettings.readDefaultPreferredAppsLPw(this, user); 11513 mSettings.writePackageRestrictionsLPr(user); 11514 scheduleWriteSettingsLocked(); 11515 } 11516 } 11517 11518 @Override 11519 public int getPreferredActivities(List<IntentFilter> outFilters, 11520 List<ComponentName> outActivities, String packageName) { 11521 11522 int num = 0; 11523 final int userId = UserHandle.getCallingUserId(); 11524 // reader 11525 synchronized (mPackages) { 11526 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11527 if (pir != null) { 11528 final Iterator<PreferredActivity> it = pir.filterIterator(); 11529 while (it.hasNext()) { 11530 final PreferredActivity pa = it.next(); 11531 if (packageName == null 11532 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11533 && pa.mPref.mAlways)) { 11534 if (outFilters != null) { 11535 outFilters.add(new IntentFilter(pa)); 11536 } 11537 if (outActivities != null) { 11538 outActivities.add(pa.mPref.mComponent); 11539 } 11540 } 11541 } 11542 } 11543 } 11544 11545 return num; 11546 } 11547 11548 @Override 11549 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11550 int userId) { 11551 int callingUid = Binder.getCallingUid(); 11552 if (callingUid != Process.SYSTEM_UID) { 11553 throw new SecurityException( 11554 "addPersistentPreferredActivity can only be run by the system"); 11555 } 11556 if (filter.countActions() == 0) { 11557 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11558 return; 11559 } 11560 synchronized (mPackages) { 11561 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11562 " :"); 11563 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11564 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11565 new PersistentPreferredActivity(filter, activity)); 11566 mSettings.writePackageRestrictionsLPr(userId); 11567 } 11568 } 11569 11570 @Override 11571 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11572 int callingUid = Binder.getCallingUid(); 11573 if (callingUid != Process.SYSTEM_UID) { 11574 throw new SecurityException( 11575 "clearPackagePersistentPreferredActivities can only be run by the system"); 11576 } 11577 ArrayList<PersistentPreferredActivity> removed = null; 11578 boolean changed = false; 11579 synchronized (mPackages) { 11580 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11581 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11582 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11583 .valueAt(i); 11584 if (userId != thisUserId) { 11585 continue; 11586 } 11587 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11588 while (it.hasNext()) { 11589 PersistentPreferredActivity ppa = it.next(); 11590 // Mark entry for removal only if it matches the package name. 11591 if (ppa.mComponent.getPackageName().equals(packageName)) { 11592 if (removed == null) { 11593 removed = new ArrayList<PersistentPreferredActivity>(); 11594 } 11595 removed.add(ppa); 11596 } 11597 } 11598 if (removed != null) { 11599 for (int j=0; j<removed.size(); j++) { 11600 PersistentPreferredActivity ppa = removed.get(j); 11601 ppir.removeFilter(ppa); 11602 } 11603 changed = true; 11604 } 11605 } 11606 11607 if (changed) { 11608 mSettings.writePackageRestrictionsLPr(userId); 11609 } 11610 } 11611 } 11612 11613 @Override 11614 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11615 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11616 mContext.enforceCallingOrSelfPermission( 11617 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11618 int callingUid = Binder.getCallingUid(); 11619 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11620 if (intentFilter.countActions() == 0) { 11621 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11622 return; 11623 } 11624 synchronized (mPackages) { 11625 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11626 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11627 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11628 mSettings.writePackageRestrictionsLPr(sourceUserId); 11629 } 11630 } 11631 11632 @Override 11633 public void addCrossProfileIntentsForPackage(String packageName, 11634 int sourceUserId, int targetUserId) { 11635 mContext.enforceCallingOrSelfPermission( 11636 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11637 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11638 mSettings.writePackageRestrictionsLPr(sourceUserId); 11639 } 11640 11641 @Override 11642 public void removeCrossProfileIntentsForPackage(String packageName, 11643 int sourceUserId, int targetUserId) { 11644 mContext.enforceCallingOrSelfPermission( 11645 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11646 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11647 mSettings.writePackageRestrictionsLPr(sourceUserId); 11648 } 11649 11650 @Override 11651 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11652 int ownerUserId) { 11653 mContext.enforceCallingOrSelfPermission( 11654 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11655 int callingUid = Binder.getCallingUid(); 11656 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11657 int callingUserId = UserHandle.getUserId(callingUid); 11658 synchronized (mPackages) { 11659 CrossProfileIntentResolver resolver = 11660 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11661 HashSet<CrossProfileIntentFilter> set = 11662 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11663 for (CrossProfileIntentFilter filter : set) { 11664 if (filter.getOwnerPackage().equals(ownerPackage) 11665 && filter.getOwnerUserId() == callingUserId) { 11666 resolver.removeFilter(filter); 11667 } 11668 } 11669 mSettings.writePackageRestrictionsLPr(sourceUserId); 11670 } 11671 } 11672 11673 // Enforcing that callingUid is owning pkg on userId 11674 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11675 // The system owns everything. 11676 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11677 return; 11678 } 11679 int callingUserId = UserHandle.getUserId(callingUid); 11680 if (callingUserId != userId) { 11681 throw new SecurityException("calling uid " + callingUid 11682 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11683 + callingUserId); 11684 } 11685 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11686 if (pi == null) { 11687 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11688 + callingUserId); 11689 } 11690 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11691 throw new SecurityException("Calling uid " + callingUid 11692 + " does not own package " + pkg); 11693 } 11694 } 11695 11696 @Override 11697 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11698 Intent intent = new Intent(Intent.ACTION_MAIN); 11699 intent.addCategory(Intent.CATEGORY_HOME); 11700 11701 final int callingUserId = UserHandle.getCallingUserId(); 11702 List<ResolveInfo> list = queryIntentActivities(intent, null, 11703 PackageManager.GET_META_DATA, callingUserId); 11704 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11705 true, false, false, callingUserId); 11706 11707 allHomeCandidates.clear(); 11708 if (list != null) { 11709 for (ResolveInfo ri : list) { 11710 allHomeCandidates.add(ri); 11711 } 11712 } 11713 return (preferred == null || preferred.activityInfo == null) 11714 ? null 11715 : new ComponentName(preferred.activityInfo.packageName, 11716 preferred.activityInfo.name); 11717 } 11718 11719 /** 11720 * Check if calling UID is the current home app. This handles both the case 11721 * where the user has selected a specific home app, and where there is only 11722 * one home app. 11723 */ 11724 public boolean checkCallerIsHomeApp() { 11725 final Intent intent = new Intent(Intent.ACTION_MAIN); 11726 intent.addCategory(Intent.CATEGORY_HOME); 11727 11728 final int callingUid = Binder.getCallingUid(); 11729 final int callingUserId = UserHandle.getCallingUserId(); 11730 final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId); 11731 final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true, 11732 false, false, callingUserId); 11733 11734 if (preferredHome != null) { 11735 if (callingUid == preferredHome.activityInfo.applicationInfo.uid) { 11736 return true; 11737 } 11738 } else { 11739 for (ResolveInfo info : allHomes) { 11740 if (callingUid == info.activityInfo.applicationInfo.uid) { 11741 return true; 11742 } 11743 } 11744 } 11745 11746 return false; 11747 } 11748 11749 /** 11750 * Enforce that calling UID is the current home app. This handles both the 11751 * case where the user has selected a specific home app, and where there is 11752 * only one home app. 11753 */ 11754 public void enforceCallerIsHomeApp() { 11755 if (!checkCallerIsHomeApp()) { 11756 throw new SecurityException("Caller is not currently selected home app"); 11757 } 11758 } 11759 11760 @Override 11761 public void setApplicationEnabledSetting(String appPackageName, 11762 int newState, int flags, int userId, String callingPackage) { 11763 if (!sUserManager.exists(userId)) return; 11764 if (callingPackage == null) { 11765 callingPackage = Integer.toString(Binder.getCallingUid()); 11766 } 11767 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11768 } 11769 11770 @Override 11771 public void setComponentEnabledSetting(ComponentName componentName, 11772 int newState, int flags, int userId) { 11773 if (!sUserManager.exists(userId)) return; 11774 setEnabledSetting(componentName.getPackageName(), 11775 componentName.getClassName(), newState, flags, userId, null); 11776 } 11777 11778 private void setEnabledSetting(final String packageName, String className, int newState, 11779 final int flags, int userId, String callingPackage) { 11780 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11781 || newState == COMPONENT_ENABLED_STATE_ENABLED 11782 || newState == COMPONENT_ENABLED_STATE_DISABLED 11783 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11784 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11785 throw new IllegalArgumentException("Invalid new component state: " 11786 + newState); 11787 } 11788 PackageSetting pkgSetting; 11789 final int uid = Binder.getCallingUid(); 11790 final int permission = mContext.checkCallingOrSelfPermission( 11791 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11792 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11793 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11794 boolean sendNow = false; 11795 boolean isApp = (className == null); 11796 String componentName = isApp ? packageName : className; 11797 int packageUid = -1; 11798 ArrayList<String> components; 11799 11800 // writer 11801 synchronized (mPackages) { 11802 pkgSetting = mSettings.mPackages.get(packageName); 11803 if (pkgSetting == null) { 11804 if (className == null) { 11805 throw new IllegalArgumentException( 11806 "Unknown package: " + packageName); 11807 } 11808 throw new IllegalArgumentException( 11809 "Unknown component: " + packageName 11810 + "/" + className); 11811 } 11812 // Allow root and verify that userId is not being specified by a different user 11813 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11814 throw new SecurityException( 11815 "Permission Denial: attempt to change component state from pid=" 11816 + Binder.getCallingPid() 11817 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11818 } 11819 if (className == null) { 11820 // We're dealing with an application/package level state change 11821 if (pkgSetting.getEnabled(userId) == newState) { 11822 // Nothing to do 11823 return; 11824 } 11825 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11826 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11827 // Don't care about who enables an app. 11828 callingPackage = null; 11829 } 11830 pkgSetting.setEnabled(newState, userId, callingPackage); 11831 // pkgSetting.pkg.mSetEnabled = newState; 11832 } else { 11833 // We're dealing with a component level state change 11834 // First, verify that this is a valid class name. 11835 PackageParser.Package pkg = pkgSetting.pkg; 11836 if (pkg == null || !pkg.hasComponentClassName(className)) { 11837 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11838 throw new IllegalArgumentException("Component class " + className 11839 + " does not exist in " + packageName); 11840 } else { 11841 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11842 + className + " does not exist in " + packageName); 11843 } 11844 } 11845 switch (newState) { 11846 case COMPONENT_ENABLED_STATE_ENABLED: 11847 if (!pkgSetting.enableComponentLPw(className, userId)) { 11848 return; 11849 } 11850 break; 11851 case COMPONENT_ENABLED_STATE_DISABLED: 11852 if (!pkgSetting.disableComponentLPw(className, userId)) { 11853 return; 11854 } 11855 break; 11856 case COMPONENT_ENABLED_STATE_DEFAULT: 11857 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11858 return; 11859 } 11860 break; 11861 default: 11862 Slog.e(TAG, "Invalid new component state: " + newState); 11863 return; 11864 } 11865 } 11866 mSettings.writePackageRestrictionsLPr(userId); 11867 components = mPendingBroadcasts.get(userId, packageName); 11868 final boolean newPackage = components == null; 11869 if (newPackage) { 11870 components = new ArrayList<String>(); 11871 } 11872 if (!components.contains(componentName)) { 11873 components.add(componentName); 11874 } 11875 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11876 sendNow = true; 11877 // Purge entry from pending broadcast list if another one exists already 11878 // since we are sending one right away. 11879 mPendingBroadcasts.remove(userId, packageName); 11880 } else { 11881 if (newPackage) { 11882 mPendingBroadcasts.put(userId, packageName, components); 11883 } 11884 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11885 // Schedule a message 11886 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11887 } 11888 } 11889 } 11890 11891 long callingId = Binder.clearCallingIdentity(); 11892 try { 11893 if (sendNow) { 11894 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11895 sendPackageChangedBroadcast(packageName, 11896 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11897 } 11898 } finally { 11899 Binder.restoreCallingIdentity(callingId); 11900 } 11901 } 11902 11903 private void sendPackageChangedBroadcast(String packageName, 11904 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11905 if (DEBUG_INSTALL) 11906 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11907 + componentNames); 11908 Bundle extras = new Bundle(4); 11909 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11910 String nameList[] = new String[componentNames.size()]; 11911 componentNames.toArray(nameList); 11912 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11913 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11914 extras.putInt(Intent.EXTRA_UID, packageUid); 11915 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11916 new int[] {UserHandle.getUserId(packageUid)}); 11917 } 11918 11919 @Override 11920 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11921 if (!sUserManager.exists(userId)) return; 11922 final int uid = Binder.getCallingUid(); 11923 final int permission = mContext.checkCallingOrSelfPermission( 11924 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11925 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11926 enforceCrossUserPermission(uid, userId, true, "stop package"); 11927 // writer 11928 synchronized (mPackages) { 11929 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11930 uid, userId)) { 11931 scheduleWritePackageRestrictionsLocked(userId); 11932 } 11933 } 11934 } 11935 11936 @Override 11937 public String getInstallerPackageName(String packageName) { 11938 // reader 11939 synchronized (mPackages) { 11940 return mSettings.getInstallerPackageNameLPr(packageName); 11941 } 11942 } 11943 11944 @Override 11945 public int getApplicationEnabledSetting(String packageName, int userId) { 11946 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11947 int uid = Binder.getCallingUid(); 11948 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11949 // reader 11950 synchronized (mPackages) { 11951 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11952 } 11953 } 11954 11955 @Override 11956 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11957 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11958 int uid = Binder.getCallingUid(); 11959 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11960 // reader 11961 synchronized (mPackages) { 11962 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11963 } 11964 } 11965 11966 @Override 11967 public void enterSafeMode() { 11968 enforceSystemOrRoot("Only the system can request entering safe mode"); 11969 11970 if (!mSystemReady) { 11971 mSafeMode = true; 11972 } 11973 } 11974 11975 @Override 11976 public void systemReady() { 11977 mSystemReady = true; 11978 11979 // Read the compatibilty setting when the system is ready. 11980 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11981 mContext.getContentResolver(), 11982 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11983 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11984 if (DEBUG_SETTINGS) { 11985 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11986 } 11987 11988 synchronized (mPackages) { 11989 // Verify that all of the preferred activity components actually 11990 // exist. It is possible for applications to be updated and at 11991 // that point remove a previously declared activity component that 11992 // had been set as a preferred activity. We try to clean this up 11993 // the next time we encounter that preferred activity, but it is 11994 // possible for the user flow to never be able to return to that 11995 // situation so here we do a sanity check to make sure we haven't 11996 // left any junk around. 11997 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11998 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11999 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12000 removed.clear(); 12001 for (PreferredActivity pa : pir.filterSet()) { 12002 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12003 removed.add(pa); 12004 } 12005 } 12006 if (removed.size() > 0) { 12007 for (int r=0; r<removed.size(); r++) { 12008 PreferredActivity pa = removed.get(r); 12009 Slog.w(TAG, "Removing dangling preferred activity: " 12010 + pa.mPref.mComponent); 12011 pir.removeFilter(pa); 12012 } 12013 mSettings.writePackageRestrictionsLPr( 12014 mSettings.mPreferredActivities.keyAt(i)); 12015 } 12016 } 12017 } 12018 sUserManager.systemReady(); 12019 } 12020 12021 @Override 12022 public boolean isSafeMode() { 12023 return mSafeMode; 12024 } 12025 12026 @Override 12027 public boolean hasSystemUidErrors() { 12028 return mHasSystemUidErrors; 12029 } 12030 12031 static String arrayToString(int[] array) { 12032 StringBuffer buf = new StringBuffer(128); 12033 buf.append('['); 12034 if (array != null) { 12035 for (int i=0; i<array.length; i++) { 12036 if (i > 0) buf.append(", "); 12037 buf.append(array[i]); 12038 } 12039 } 12040 buf.append(']'); 12041 return buf.toString(); 12042 } 12043 12044 static class DumpState { 12045 public static final int DUMP_LIBS = 1 << 0; 12046 public static final int DUMP_FEATURES = 1 << 1; 12047 public static final int DUMP_RESOLVERS = 1 << 2; 12048 public static final int DUMP_PERMISSIONS = 1 << 3; 12049 public static final int DUMP_PACKAGES = 1 << 4; 12050 public static final int DUMP_SHARED_USERS = 1 << 5; 12051 public static final int DUMP_MESSAGES = 1 << 6; 12052 public static final int DUMP_PROVIDERS = 1 << 7; 12053 public static final int DUMP_VERIFIERS = 1 << 8; 12054 public static final int DUMP_PREFERRED = 1 << 9; 12055 public static final int DUMP_PREFERRED_XML = 1 << 10; 12056 public static final int DUMP_KEYSETS = 1 << 11; 12057 public static final int DUMP_VERSION = 1 << 12; 12058 public static final int DUMP_INSTALLS = 1 << 13; 12059 12060 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12061 12062 private int mTypes; 12063 12064 private int mOptions; 12065 12066 private boolean mTitlePrinted; 12067 12068 private SharedUserSetting mSharedUser; 12069 12070 public boolean isDumping(int type) { 12071 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12072 return true; 12073 } 12074 12075 return (mTypes & type) != 0; 12076 } 12077 12078 public void setDump(int type) { 12079 mTypes |= type; 12080 } 12081 12082 public boolean isOptionEnabled(int option) { 12083 return (mOptions & option) != 0; 12084 } 12085 12086 public void setOptionEnabled(int option) { 12087 mOptions |= option; 12088 } 12089 12090 public boolean onTitlePrinted() { 12091 final boolean printed = mTitlePrinted; 12092 mTitlePrinted = true; 12093 return printed; 12094 } 12095 12096 public boolean getTitlePrinted() { 12097 return mTitlePrinted; 12098 } 12099 12100 public void setTitlePrinted(boolean enabled) { 12101 mTitlePrinted = enabled; 12102 } 12103 12104 public SharedUserSetting getSharedUser() { 12105 return mSharedUser; 12106 } 12107 12108 public void setSharedUser(SharedUserSetting user) { 12109 mSharedUser = user; 12110 } 12111 } 12112 12113 @Override 12114 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12115 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12116 != PackageManager.PERMISSION_GRANTED) { 12117 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12118 + Binder.getCallingPid() 12119 + ", uid=" + Binder.getCallingUid() 12120 + " without permission " 12121 + android.Manifest.permission.DUMP); 12122 return; 12123 } 12124 12125 DumpState dumpState = new DumpState(); 12126 boolean fullPreferred = false; 12127 boolean checkin = false; 12128 12129 String packageName = null; 12130 12131 int opti = 0; 12132 while (opti < args.length) { 12133 String opt = args[opti]; 12134 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12135 break; 12136 } 12137 opti++; 12138 if ("-a".equals(opt)) { 12139 // Right now we only know how to print all. 12140 } else if ("-h".equals(opt)) { 12141 pw.println("Package manager dump options:"); 12142 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12143 pw.println(" --checkin: dump for a checkin"); 12144 pw.println(" -f: print details of intent filters"); 12145 pw.println(" -h: print this help"); 12146 pw.println(" cmd may be one of:"); 12147 pw.println(" l[ibraries]: list known shared libraries"); 12148 pw.println(" f[ibraries]: list device features"); 12149 pw.println(" k[eysets]: print known keysets"); 12150 pw.println(" r[esolvers]: dump intent resolvers"); 12151 pw.println(" perm[issions]: dump permissions"); 12152 pw.println(" pref[erred]: print preferred package settings"); 12153 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12154 pw.println(" prov[iders]: dump content providers"); 12155 pw.println(" p[ackages]: dump installed packages"); 12156 pw.println(" s[hared-users]: dump shared user IDs"); 12157 pw.println(" m[essages]: print collected runtime messages"); 12158 pw.println(" v[erifiers]: print package verifier info"); 12159 pw.println(" version: print database version info"); 12160 pw.println(" write: write current settings now"); 12161 pw.println(" <package.name>: info about given package"); 12162 pw.println(" installs: details about install sessions"); 12163 return; 12164 } else if ("--checkin".equals(opt)) { 12165 checkin = true; 12166 } else if ("-f".equals(opt)) { 12167 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12168 } else { 12169 pw.println("Unknown argument: " + opt + "; use -h for help"); 12170 } 12171 } 12172 12173 // Is the caller requesting to dump a particular piece of data? 12174 if (opti < args.length) { 12175 String cmd = args[opti]; 12176 opti++; 12177 // Is this a package name? 12178 if ("android".equals(cmd) || cmd.contains(".")) { 12179 packageName = cmd; 12180 // When dumping a single package, we always dump all of its 12181 // filter information since the amount of data will be reasonable. 12182 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12183 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12184 dumpState.setDump(DumpState.DUMP_LIBS); 12185 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12186 dumpState.setDump(DumpState.DUMP_FEATURES); 12187 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12188 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12189 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12190 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12191 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12192 dumpState.setDump(DumpState.DUMP_PREFERRED); 12193 } else if ("preferred-xml".equals(cmd)) { 12194 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12195 if (opti < args.length && "--full".equals(args[opti])) { 12196 fullPreferred = true; 12197 opti++; 12198 } 12199 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12200 dumpState.setDump(DumpState.DUMP_PACKAGES); 12201 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12202 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12203 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12204 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12205 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12206 dumpState.setDump(DumpState.DUMP_MESSAGES); 12207 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12208 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12209 } else if ("version".equals(cmd)) { 12210 dumpState.setDump(DumpState.DUMP_VERSION); 12211 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12212 dumpState.setDump(DumpState.DUMP_KEYSETS); 12213 } else if ("write".equals(cmd)) { 12214 synchronized (mPackages) { 12215 mSettings.writeLPr(); 12216 pw.println("Settings written."); 12217 return; 12218 } 12219 } else if ("installs".equals(cmd)) { 12220 dumpState.setDump(DumpState.DUMP_INSTALLS); 12221 } 12222 } 12223 12224 if (checkin) { 12225 pw.println("vers,1"); 12226 } 12227 12228 // reader 12229 synchronized (mPackages) { 12230 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12231 if (!checkin) { 12232 if (dumpState.onTitlePrinted()) 12233 pw.println(); 12234 pw.println("Database versions:"); 12235 pw.print(" SDK Version:"); 12236 pw.print(" internal="); 12237 pw.print(mSettings.mInternalSdkPlatform); 12238 pw.print(" external="); 12239 pw.println(mSettings.mExternalSdkPlatform); 12240 pw.print(" DB Version:"); 12241 pw.print(" internal="); 12242 pw.print(mSettings.mInternalDatabaseVersion); 12243 pw.print(" external="); 12244 pw.println(mSettings.mExternalDatabaseVersion); 12245 } 12246 } 12247 12248 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12249 if (!checkin) { 12250 if (dumpState.onTitlePrinted()) 12251 pw.println(); 12252 pw.println("Verifiers:"); 12253 pw.print(" Required: "); 12254 pw.print(mRequiredVerifierPackage); 12255 pw.print(" (uid="); 12256 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12257 pw.println(")"); 12258 } else if (mRequiredVerifierPackage != null) { 12259 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12260 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12261 } 12262 } 12263 12264 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12265 boolean printedHeader = false; 12266 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12267 while (it.hasNext()) { 12268 String name = it.next(); 12269 SharedLibraryEntry ent = mSharedLibraries.get(name); 12270 if (!checkin) { 12271 if (!printedHeader) { 12272 if (dumpState.onTitlePrinted()) 12273 pw.println(); 12274 pw.println("Libraries:"); 12275 printedHeader = true; 12276 } 12277 pw.print(" "); 12278 } else { 12279 pw.print("lib,"); 12280 } 12281 pw.print(name); 12282 if (!checkin) { 12283 pw.print(" -> "); 12284 } 12285 if (ent.path != null) { 12286 if (!checkin) { 12287 pw.print("(jar) "); 12288 pw.print(ent.path); 12289 } else { 12290 pw.print(",jar,"); 12291 pw.print(ent.path); 12292 } 12293 } else { 12294 if (!checkin) { 12295 pw.print("(apk) "); 12296 pw.print(ent.apk); 12297 } else { 12298 pw.print(",apk,"); 12299 pw.print(ent.apk); 12300 } 12301 } 12302 pw.println(); 12303 } 12304 } 12305 12306 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12307 if (dumpState.onTitlePrinted()) 12308 pw.println(); 12309 if (!checkin) { 12310 pw.println("Features:"); 12311 } 12312 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12313 while (it.hasNext()) { 12314 String name = it.next(); 12315 if (!checkin) { 12316 pw.print(" "); 12317 } else { 12318 pw.print("feat,"); 12319 } 12320 pw.println(name); 12321 } 12322 } 12323 12324 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12325 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12326 : "Activity Resolver Table:", " ", packageName, 12327 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12328 dumpState.setTitlePrinted(true); 12329 } 12330 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12331 : "Receiver Resolver Table:", " ", packageName, 12332 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12333 dumpState.setTitlePrinted(true); 12334 } 12335 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12336 : "Service Resolver Table:", " ", packageName, 12337 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12338 dumpState.setTitlePrinted(true); 12339 } 12340 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12341 : "Provider Resolver Table:", " ", packageName, 12342 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12343 dumpState.setTitlePrinted(true); 12344 } 12345 } 12346 12347 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12348 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12349 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12350 int user = mSettings.mPreferredActivities.keyAt(i); 12351 if (pir.dump(pw, 12352 dumpState.getTitlePrinted() 12353 ? "\nPreferred Activities User " + user + ":" 12354 : "Preferred Activities User " + user + ":", " ", 12355 packageName, true)) { 12356 dumpState.setTitlePrinted(true); 12357 } 12358 } 12359 } 12360 12361 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12362 pw.flush(); 12363 FileOutputStream fout = new FileOutputStream(fd); 12364 BufferedOutputStream str = new BufferedOutputStream(fout); 12365 XmlSerializer serializer = new FastXmlSerializer(); 12366 try { 12367 serializer.setOutput(str, "utf-8"); 12368 serializer.startDocument(null, true); 12369 serializer.setFeature( 12370 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12371 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12372 serializer.endDocument(); 12373 serializer.flush(); 12374 } catch (IllegalArgumentException e) { 12375 pw.println("Failed writing: " + e); 12376 } catch (IllegalStateException e) { 12377 pw.println("Failed writing: " + e); 12378 } catch (IOException e) { 12379 pw.println("Failed writing: " + e); 12380 } 12381 } 12382 12383 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12384 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12385 if (packageName == null) { 12386 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12387 if (iperm == 0) { 12388 if (dumpState.onTitlePrinted()) 12389 pw.println(); 12390 pw.println("AppOp Permissions:"); 12391 } 12392 pw.print(" AppOp Permission "); 12393 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12394 pw.println(":"); 12395 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12396 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12397 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12398 } 12399 } 12400 } 12401 } 12402 12403 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12404 boolean printedSomething = false; 12405 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12406 if (packageName != null && !packageName.equals(p.info.packageName)) { 12407 continue; 12408 } 12409 if (!printedSomething) { 12410 if (dumpState.onTitlePrinted()) 12411 pw.println(); 12412 pw.println("Registered ContentProviders:"); 12413 printedSomething = true; 12414 } 12415 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12416 pw.print(" "); pw.println(p.toString()); 12417 } 12418 printedSomething = false; 12419 for (Map.Entry<String, PackageParser.Provider> entry : 12420 mProvidersByAuthority.entrySet()) { 12421 PackageParser.Provider p = entry.getValue(); 12422 if (packageName != null && !packageName.equals(p.info.packageName)) { 12423 continue; 12424 } 12425 if (!printedSomething) { 12426 if (dumpState.onTitlePrinted()) 12427 pw.println(); 12428 pw.println("ContentProvider Authorities:"); 12429 printedSomething = true; 12430 } 12431 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12432 pw.print(" "); pw.println(p.toString()); 12433 if (p.info != null && p.info.applicationInfo != null) { 12434 final String appInfo = p.info.applicationInfo.toString(); 12435 pw.print(" applicationInfo="); pw.println(appInfo); 12436 } 12437 } 12438 } 12439 12440 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12441 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12442 } 12443 12444 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12445 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12446 } 12447 12448 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12449 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12450 } 12451 12452 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12453 if (dumpState.onTitlePrinted()) pw.println(); 12454 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12455 } 12456 12457 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12458 if (dumpState.onTitlePrinted()) pw.println(); 12459 mSettings.dumpReadMessagesLPr(pw, dumpState); 12460 12461 pw.println(); 12462 pw.println("Package warning messages:"); 12463 final File fname = getSettingsProblemFile(); 12464 FileInputStream in = null; 12465 try { 12466 in = new FileInputStream(fname); 12467 final int avail = in.available(); 12468 final byte[] data = new byte[avail]; 12469 in.read(data); 12470 pw.print(new String(data)); 12471 } catch (FileNotFoundException e) { 12472 } catch (IOException e) { 12473 } finally { 12474 if (in != null) { 12475 try { 12476 in.close(); 12477 } catch (IOException e) { 12478 } 12479 } 12480 } 12481 } 12482 } 12483 } 12484 12485 // ------- apps on sdcard specific code ------- 12486 static final boolean DEBUG_SD_INSTALL = false; 12487 12488 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12489 12490 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12491 12492 private boolean mMediaMounted = false; 12493 12494 static String getEncryptKey() { 12495 try { 12496 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12497 SD_ENCRYPTION_KEYSTORE_NAME); 12498 if (sdEncKey == null) { 12499 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12500 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12501 if (sdEncKey == null) { 12502 Slog.e(TAG, "Failed to create encryption keys"); 12503 return null; 12504 } 12505 } 12506 return sdEncKey; 12507 } catch (NoSuchAlgorithmException nsae) { 12508 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12509 return null; 12510 } catch (IOException ioe) { 12511 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12512 return null; 12513 } 12514 } 12515 12516 /* 12517 * Update media status on PackageManager. 12518 */ 12519 @Override 12520 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12521 int callingUid = Binder.getCallingUid(); 12522 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12523 throw new SecurityException("Media status can only be updated by the system"); 12524 } 12525 // reader; this apparently protects mMediaMounted, but should probably 12526 // be a different lock in that case. 12527 synchronized (mPackages) { 12528 Log.i(TAG, "Updating external media status from " 12529 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12530 + (mediaStatus ? "mounted" : "unmounted")); 12531 if (DEBUG_SD_INSTALL) 12532 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12533 + ", mMediaMounted=" + mMediaMounted); 12534 if (mediaStatus == mMediaMounted) { 12535 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12536 : 0, -1); 12537 mHandler.sendMessage(msg); 12538 return; 12539 } 12540 mMediaMounted = mediaStatus; 12541 } 12542 // Queue up an async operation since the package installation may take a 12543 // little while. 12544 mHandler.post(new Runnable() { 12545 public void run() { 12546 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12547 } 12548 }); 12549 } 12550 12551 /** 12552 * Called by MountService when the initial ASECs to scan are available. 12553 * Should block until all the ASEC containers are finished being scanned. 12554 */ 12555 public void scanAvailableAsecs() { 12556 updateExternalMediaStatusInner(true, false, false); 12557 if (mShouldRestoreconData) { 12558 SELinuxMMAC.setRestoreconDone(); 12559 mShouldRestoreconData = false; 12560 } 12561 } 12562 12563 /* 12564 * Collect information of applications on external media, map them against 12565 * existing containers and update information based on current mount status. 12566 * Please note that we always have to report status if reportStatus has been 12567 * set to true especially when unloading packages. 12568 */ 12569 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12570 boolean externalStorage) { 12571 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12572 int[] uidArr = EmptyArray.INT; 12573 12574 final String[] list = PackageHelper.getSecureContainerList(); 12575 if (ArrayUtils.isEmpty(list)) { 12576 Log.i(TAG, "No secure containers found"); 12577 } else { 12578 // Process list of secure containers and categorize them 12579 // as active or stale based on their package internal state. 12580 12581 // reader 12582 synchronized (mPackages) { 12583 for (String cid : list) { 12584 // Leave stages untouched for now; installer service owns them 12585 if (PackageInstallerService.isStageName(cid)) continue; 12586 12587 if (DEBUG_SD_INSTALL) 12588 Log.i(TAG, "Processing container " + cid); 12589 String pkgName = getAsecPackageName(cid); 12590 if (pkgName == null) { 12591 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12592 continue; 12593 } 12594 if (DEBUG_SD_INSTALL) 12595 Log.i(TAG, "Looking for pkg : " + pkgName); 12596 12597 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12598 if (ps == null) { 12599 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12600 continue; 12601 } 12602 12603 /* 12604 * Skip packages that are not external if we're unmounting 12605 * external storage. 12606 */ 12607 if (externalStorage && !isMounted && !isExternal(ps)) { 12608 continue; 12609 } 12610 12611 final AsecInstallArgs args = new AsecInstallArgs(cid, 12612 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12613 // The package status is changed only if the code path 12614 // matches between settings and the container id. 12615 if (ps.codePathString != null 12616 && ps.codePathString.startsWith(args.getCodePath())) { 12617 if (DEBUG_SD_INSTALL) { 12618 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12619 + " at code path: " + ps.codePathString); 12620 } 12621 12622 // We do have a valid package installed on sdcard 12623 processCids.put(args, ps.codePathString); 12624 final int uid = ps.appId; 12625 if (uid != -1) { 12626 uidArr = ArrayUtils.appendInt(uidArr, uid); 12627 } 12628 } else { 12629 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12630 + ps.codePathString); 12631 } 12632 } 12633 } 12634 12635 Arrays.sort(uidArr); 12636 } 12637 12638 // Process packages with valid entries. 12639 if (isMounted) { 12640 if (DEBUG_SD_INSTALL) 12641 Log.i(TAG, "Loading packages"); 12642 loadMediaPackages(processCids, uidArr); 12643 startCleaningPackages(); 12644 mInstallerService.onSecureContainersAvailable(); 12645 } else { 12646 if (DEBUG_SD_INSTALL) 12647 Log.i(TAG, "Unloading packages"); 12648 unloadMediaPackages(processCids, uidArr, reportStatus); 12649 } 12650 } 12651 12652 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12653 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12654 int size = pkgList.size(); 12655 if (size > 0) { 12656 // Send broadcasts here 12657 Bundle extras = new Bundle(); 12658 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12659 .toArray(new String[size])); 12660 if (uidArr != null) { 12661 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12662 } 12663 if (replacing) { 12664 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12665 } 12666 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12667 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12668 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12669 } 12670 } 12671 12672 /* 12673 * Look at potentially valid container ids from processCids If package 12674 * information doesn't match the one on record or package scanning fails, 12675 * the cid is added to list of removeCids. We currently don't delete stale 12676 * containers. 12677 */ 12678 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12679 ArrayList<String> pkgList = new ArrayList<String>(); 12680 Set<AsecInstallArgs> keys = processCids.keySet(); 12681 12682 for (AsecInstallArgs args : keys) { 12683 String codePath = processCids.get(args); 12684 if (DEBUG_SD_INSTALL) 12685 Log.i(TAG, "Loading container : " + args.cid); 12686 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12687 try { 12688 // Make sure there are no container errors first. 12689 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12690 Slog.e(TAG, "Failed to mount cid : " + args.cid 12691 + " when installing from sdcard"); 12692 continue; 12693 } 12694 // Check code path here. 12695 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12696 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12697 + " does not match one in settings " + codePath); 12698 continue; 12699 } 12700 // Parse package 12701 int parseFlags = mDefParseFlags; 12702 if (args.isExternal()) { 12703 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12704 } 12705 if (args.isFwdLocked()) { 12706 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12707 } 12708 12709 synchronized (mInstallLock) { 12710 PackageParser.Package pkg = null; 12711 try { 12712 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12713 } catch (PackageManagerException e) { 12714 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12715 } 12716 // Scan the package 12717 if (pkg != null) { 12718 /* 12719 * TODO why is the lock being held? doPostInstall is 12720 * called in other places without the lock. This needs 12721 * to be straightened out. 12722 */ 12723 // writer 12724 synchronized (mPackages) { 12725 retCode = PackageManager.INSTALL_SUCCEEDED; 12726 pkgList.add(pkg.packageName); 12727 // Post process args 12728 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12729 pkg.applicationInfo.uid); 12730 } 12731 } else { 12732 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12733 } 12734 } 12735 12736 } finally { 12737 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12738 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12739 } 12740 } 12741 } 12742 // writer 12743 synchronized (mPackages) { 12744 // If the platform SDK has changed since the last time we booted, 12745 // we need to re-grant app permission to catch any new ones that 12746 // appear. This is really a hack, and means that apps can in some 12747 // cases get permissions that the user didn't initially explicitly 12748 // allow... it would be nice to have some better way to handle 12749 // this situation. 12750 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12751 if (regrantPermissions) 12752 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12753 + mSdkVersion + "; regranting permissions for external storage"); 12754 mSettings.mExternalSdkPlatform = mSdkVersion; 12755 12756 // Make sure group IDs have been assigned, and any permission 12757 // changes in other apps are accounted for 12758 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12759 | (regrantPermissions 12760 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12761 : 0)); 12762 12763 mSettings.updateExternalDatabaseVersion(); 12764 12765 // can downgrade to reader 12766 // Persist settings 12767 mSettings.writeLPr(); 12768 } 12769 // Send a broadcast to let everyone know we are done processing 12770 if (pkgList.size() > 0) { 12771 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12772 } 12773 } 12774 12775 /* 12776 * Utility method to unload a list of specified containers 12777 */ 12778 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12779 // Just unmount all valid containers. 12780 for (AsecInstallArgs arg : cidArgs) { 12781 synchronized (mInstallLock) { 12782 arg.doPostDeleteLI(false); 12783 } 12784 } 12785 } 12786 12787 /* 12788 * Unload packages mounted on external media. This involves deleting package 12789 * data from internal structures, sending broadcasts about diabled packages, 12790 * gc'ing to free up references, unmounting all secure containers 12791 * corresponding to packages on external media, and posting a 12792 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12793 * that we always have to post this message if status has been requested no 12794 * matter what. 12795 */ 12796 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12797 final boolean reportStatus) { 12798 if (DEBUG_SD_INSTALL) 12799 Log.i(TAG, "unloading media packages"); 12800 ArrayList<String> pkgList = new ArrayList<String>(); 12801 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12802 final Set<AsecInstallArgs> keys = processCids.keySet(); 12803 for (AsecInstallArgs args : keys) { 12804 String pkgName = args.getPackageName(); 12805 if (DEBUG_SD_INSTALL) 12806 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12807 // Delete package internally 12808 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12809 synchronized (mInstallLock) { 12810 boolean res = deletePackageLI(pkgName, null, false, null, null, 12811 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12812 if (res) { 12813 pkgList.add(pkgName); 12814 } else { 12815 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12816 failedList.add(args); 12817 } 12818 } 12819 } 12820 12821 // reader 12822 synchronized (mPackages) { 12823 // We didn't update the settings after removing each package; 12824 // write them now for all packages. 12825 mSettings.writeLPr(); 12826 } 12827 12828 // We have to absolutely send UPDATED_MEDIA_STATUS only 12829 // after confirming that all the receivers processed the ordered 12830 // broadcast when packages get disabled, force a gc to clean things up. 12831 // and unload all the containers. 12832 if (pkgList.size() > 0) { 12833 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12834 new IIntentReceiver.Stub() { 12835 public void performReceive(Intent intent, int resultCode, String data, 12836 Bundle extras, boolean ordered, boolean sticky, 12837 int sendingUser) throws RemoteException { 12838 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12839 reportStatus ? 1 : 0, 1, keys); 12840 mHandler.sendMessage(msg); 12841 } 12842 }); 12843 } else { 12844 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12845 keys); 12846 mHandler.sendMessage(msg); 12847 } 12848 } 12849 12850 /** Binder call */ 12851 @Override 12852 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12853 final int flags) { 12854 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12855 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12856 int returnCode = PackageManager.MOVE_SUCCEEDED; 12857 int currInstallFlags = 0; 12858 int newInstallFlags = 0; 12859 12860 File codeFile = null; 12861 String installerPackageName = null; 12862 String packageAbiOverride = null; 12863 12864 // reader 12865 synchronized (mPackages) { 12866 final PackageParser.Package pkg = mPackages.get(packageName); 12867 final PackageSetting ps = mSettings.mPackages.get(packageName); 12868 if (pkg == null || ps == null) { 12869 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12870 } else { 12871 // Disable moving fwd locked apps and system packages 12872 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12873 Slog.w(TAG, "Cannot move system application"); 12874 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12875 } else if (pkg.mOperationPending) { 12876 Slog.w(TAG, "Attempt to move package which has pending operations"); 12877 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12878 } else { 12879 // Find install location first 12880 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12881 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12882 Slog.w(TAG, "Ambigous flags specified for move location."); 12883 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12884 } else { 12885 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12886 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12887 currInstallFlags = isExternal(pkg) 12888 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12889 12890 if (newInstallFlags == currInstallFlags) { 12891 Slog.w(TAG, "No move required. Trying to move to same location"); 12892 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12893 } else { 12894 if (isForwardLocked(pkg)) { 12895 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12896 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12897 } 12898 } 12899 } 12900 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12901 pkg.mOperationPending = true; 12902 } 12903 } 12904 12905 codeFile = new File(pkg.codePath); 12906 installerPackageName = ps.installerPackageName; 12907 packageAbiOverride = ps.cpuAbiOverrideString; 12908 } 12909 } 12910 12911 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12912 try { 12913 observer.packageMoved(packageName, returnCode); 12914 } catch (RemoteException ignored) { 12915 } 12916 return; 12917 } 12918 12919 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 12920 @Override 12921 public void onUserActionRequired(Intent intent) throws RemoteException { 12922 throw new IllegalStateException(); 12923 } 12924 12925 @Override 12926 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 12927 Bundle extras) throws RemoteException { 12928 Slog.d(TAG, "Install result for move: " 12929 + PackageManager.installStatusToString(returnCode, msg)); 12930 12931 // We usually have a new package now after the install, but if 12932 // we failed we need to clear the pending flag on the original 12933 // package object. 12934 synchronized (mPackages) { 12935 final PackageParser.Package pkg = mPackages.get(packageName); 12936 if (pkg != null) { 12937 pkg.mOperationPending = false; 12938 } 12939 } 12940 12941 final int status = PackageManager.installStatusToPublicStatus(returnCode); 12942 switch (status) { 12943 case PackageInstaller.STATUS_SUCCESS: 12944 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 12945 break; 12946 case PackageInstaller.STATUS_FAILURE_STORAGE: 12947 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 12948 break; 12949 default: 12950 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 12951 break; 12952 } 12953 } 12954 }; 12955 12956 // Treat a move like reinstalling an existing app, which ensures that we 12957 // process everythign uniformly, like unpacking native libraries. 12958 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 12959 12960 final Message msg = mHandler.obtainMessage(INIT_COPY); 12961 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 12962 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 12963 installerPackageName, null, user, packageAbiOverride); 12964 mHandler.sendMessage(msg); 12965 } 12966 12967 @Override 12968 public boolean setInstallLocation(int loc) { 12969 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12970 null); 12971 if (getInstallLocation() == loc) { 12972 return true; 12973 } 12974 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12975 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12976 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12977 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12978 return true; 12979 } 12980 return false; 12981 } 12982 12983 @Override 12984 public int getInstallLocation() { 12985 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12986 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12987 PackageHelper.APP_INSTALL_AUTO); 12988 } 12989 12990 /** Called by UserManagerService */ 12991 void cleanUpUserLILPw(int userHandle) { 12992 mDirtyUsers.remove(userHandle); 12993 mSettings.removeUserLPw(userHandle); 12994 mPendingBroadcasts.remove(userHandle); 12995 if (mInstaller != null) { 12996 // Technically, we shouldn't be doing this with the package lock 12997 // held. However, this is very rare, and there is already so much 12998 // other disk I/O going on, that we'll let it slide for now. 12999 mInstaller.removeUserDataDirs(userHandle); 13000 } 13001 mUserNeedsBadging.delete(userHandle); 13002 } 13003 13004 /** Called by UserManagerService */ 13005 void createNewUserLILPw(int userHandle, File path) { 13006 if (mInstaller != null) { 13007 mInstaller.createUserConfig(userHandle); 13008 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13009 } 13010 } 13011 13012 @Override 13013 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13014 mContext.enforceCallingOrSelfPermission( 13015 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13016 "Only package verification agents can read the verifier device identity"); 13017 13018 synchronized (mPackages) { 13019 return mSettings.getVerifierDeviceIdentityLPw(); 13020 } 13021 } 13022 13023 @Override 13024 public void setPermissionEnforced(String permission, boolean enforced) { 13025 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13026 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13027 synchronized (mPackages) { 13028 if (mSettings.mReadExternalStorageEnforced == null 13029 || mSettings.mReadExternalStorageEnforced != enforced) { 13030 mSettings.mReadExternalStorageEnforced = enforced; 13031 mSettings.writeLPr(); 13032 } 13033 } 13034 // kill any non-foreground processes so we restart them and 13035 // grant/revoke the GID. 13036 final IActivityManager am = ActivityManagerNative.getDefault(); 13037 if (am != null) { 13038 final long token = Binder.clearCallingIdentity(); 13039 try { 13040 am.killProcessesBelowForeground("setPermissionEnforcement"); 13041 } catch (RemoteException e) { 13042 } finally { 13043 Binder.restoreCallingIdentity(token); 13044 } 13045 } 13046 } else { 13047 throw new IllegalArgumentException("No selective enforcement for " + permission); 13048 } 13049 } 13050 13051 @Override 13052 @Deprecated 13053 public boolean isPermissionEnforced(String permission) { 13054 return true; 13055 } 13056 13057 @Override 13058 public boolean isStorageLow() { 13059 final long token = Binder.clearCallingIdentity(); 13060 try { 13061 final DeviceStorageMonitorInternal 13062 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13063 if (dsm != null) { 13064 return dsm.isMemoryLow(); 13065 } else { 13066 return false; 13067 } 13068 } finally { 13069 Binder.restoreCallingIdentity(token); 13070 } 13071 } 13072 13073 @Override 13074 public IPackageInstaller getPackageInstaller() { 13075 return mInstallerService; 13076 } 13077 13078 private boolean userNeedsBadging(int userId) { 13079 int index = mUserNeedsBadging.indexOfKey(userId); 13080 if (index < 0) { 13081 final UserInfo userInfo; 13082 final long token = Binder.clearCallingIdentity(); 13083 try { 13084 userInfo = sUserManager.getUserInfo(userId); 13085 } finally { 13086 Binder.restoreCallingIdentity(token); 13087 } 13088 final boolean b; 13089 if (userInfo != null && userInfo.isManagedProfile()) { 13090 b = true; 13091 } else { 13092 b = false; 13093 } 13094 mUserNeedsBadging.put(userId, b); 13095 return b; 13096 } 13097 return mUserNeedsBadging.valueAt(index); 13098 } 13099 13100 @Override 13101 public KeySetHandle getKeySetByAlias(String packageName, String alias) { 13102 if (packageName == null || alias == null) { 13103 return null; 13104 } 13105 synchronized(mPackages) { 13106 final PackageParser.Package pkg = mPackages.get(packageName); 13107 if (pkg == null) { 13108 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13109 throw new IllegalArgumentException("Unknown package: " + packageName); 13110 } 13111 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13112 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13113 throw new SecurityException("May not access KeySets defined by" 13114 + " aliases in other applications."); 13115 } 13116 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13117 return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias); 13118 } 13119 } 13120 13121 @Override 13122 public KeySetHandle getSigningKeySet(String packageName) { 13123 if (packageName == null) { 13124 return null; 13125 } 13126 synchronized(mPackages) { 13127 final PackageParser.Package pkg = mPackages.get(packageName); 13128 if (pkg == null) { 13129 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13130 throw new IllegalArgumentException("Unknown package: " + packageName); 13131 } 13132 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13133 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13134 throw new SecurityException("May not access signing KeySet of other apps."); 13135 } 13136 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13137 return ksms.getSigningKeySetByPackageNameLPr(packageName); 13138 } 13139 } 13140 13141 @Override 13142 public boolean isPackageSignedByKeySet(String packageName, IBinder ks) { 13143 if (packageName == null || ks == null) { 13144 return false; 13145 } 13146 synchronized(mPackages) { 13147 final PackageParser.Package pkg = mPackages.get(packageName); 13148 if (pkg == null) { 13149 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13150 throw new IllegalArgumentException("Unknown package: " + packageName); 13151 } 13152 if (ks instanceof KeySetHandle) { 13153 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13154 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks); 13155 } 13156 return false; 13157 } 13158 } 13159 13160 @Override 13161 public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) { 13162 if (packageName == null || ks == null) { 13163 return false; 13164 } 13165 synchronized(mPackages) { 13166 final PackageParser.Package pkg = mPackages.get(packageName); 13167 if (pkg == null) { 13168 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13169 throw new IllegalArgumentException("Unknown package: " + packageName); 13170 } 13171 if (ks instanceof KeySetHandle) { 13172 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13173 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks); 13174 } 13175 return false; 13176 } 13177 } 13178} 13179