PackageManagerService.java revision 381d94b712605112b35d7f70064b0d18bd877877
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 List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4632 boolean performedDexOpt = false; 4633 // There are three basic cases here: 4634 // 1.) we need to dexopt, either because we are forced or it is needed 4635 // 2.) we are defering a needed dexopt 4636 // 3.) we are skipping an unneeded dexopt 4637 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4638 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4639 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4640 continue; 4641 } 4642 4643 for (String path : paths) { 4644 try { 4645 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4646 // patckage or the one we find does not match the image checksum (i.e. it was 4647 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4648 // odex file and it matches the checksum of the image but not its base address, 4649 // meaning we need to move it. 4650 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4651 pkg.packageName, dexCodeInstructionSet, defer); 4652 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4653 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4654 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet); 4655 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4656 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4657 pkg.packageName, dexCodeInstructionSet); 4658 4659 if (ret < 0) { 4660 // Don't bother running dexopt again if we failed, it will probably 4661 // just result in an error again. Also, don't bother dexopting for other 4662 // paths & ISAs. 4663 return DEX_OPT_FAILED; 4664 } 4665 4666 performedDexOpt = true; 4667 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4668 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4669 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4670 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4671 pkg.packageName, dexCodeInstructionSet); 4672 4673 if (ret < 0) { 4674 // Don't bother running patchoat again if we failed, it will probably 4675 // just result in an error again. Also, don't bother dexopting for other 4676 // paths & ISAs. 4677 return DEX_OPT_FAILED; 4678 } 4679 4680 performedDexOpt = true; 4681 } 4682 4683 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4684 // paths and instruction sets. We'll deal with them all together when we process 4685 // our list of deferred dexopts. 4686 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4687 if (mDeferredDexOpt == null) { 4688 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4689 } 4690 mDeferredDexOpt.add(pkg); 4691 return DEX_OPT_DEFERRED; 4692 } 4693 } catch (FileNotFoundException e) { 4694 Slog.w(TAG, "Apk not found for dexopt: " + path); 4695 return DEX_OPT_FAILED; 4696 } catch (IOException e) { 4697 Slog.w(TAG, "IOException reading apk: " + path, e); 4698 return DEX_OPT_FAILED; 4699 } catch (StaleDexCacheError e) { 4700 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4701 return DEX_OPT_FAILED; 4702 } catch (Exception e) { 4703 Slog.w(TAG, "Exception when doing dexopt : ", e); 4704 return DEX_OPT_FAILED; 4705 } 4706 } 4707 4708 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4709 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4710 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4711 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4712 // it. 4713 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4714 } 4715 4716 // If we've gotten here, we're sure that no error occurred and that we haven't 4717 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4718 // we've skipped all of them because they are up to date. In both cases this 4719 // package doesn't need dexopt any longer. 4720 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4721 } 4722 4723 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4724 if (info.primaryCpuAbi != null) { 4725 if (info.secondaryCpuAbi != null) { 4726 return new String[] { 4727 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4728 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4729 } else { 4730 return new String[] { 4731 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4732 } 4733 } 4734 4735 return new String[] { getPreferredInstructionSet() }; 4736 } 4737 4738 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4739 if (ps.primaryCpuAbiString != null) { 4740 if (ps.secondaryCpuAbiString != null) { 4741 return new String[] { 4742 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4743 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4744 } else { 4745 return new String[] { 4746 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4747 } 4748 } 4749 4750 return new String[] { getPreferredInstructionSet() }; 4751 } 4752 4753 private static String getPreferredInstructionSet() { 4754 if (sPreferredInstructionSet == null) { 4755 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4756 } 4757 4758 return sPreferredInstructionSet; 4759 } 4760 4761 private static List<String> getAllInstructionSets() { 4762 final String[] allAbis = Build.SUPPORTED_ABIS; 4763 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4764 4765 for (String abi : allAbis) { 4766 final String instructionSet = VMRuntime.getInstructionSet(abi); 4767 if (!allInstructionSets.contains(instructionSet)) { 4768 allInstructionSets.add(instructionSet); 4769 } 4770 } 4771 4772 return allInstructionSets; 4773 } 4774 4775 /** 4776 * Returns the instruction set that should be used to compile dex code. In the presence of 4777 * a native bridge this might be different than the one shared libraries use. 4778 */ 4779 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4780 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4781 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4782 } 4783 4784 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4785 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4786 for (String instructionSet : instructionSets) { 4787 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4788 } 4789 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4790 } 4791 4792 @Override 4793 public void forceDexOpt(String packageName) { 4794 enforceSystemOrRoot("forceDexOpt"); 4795 4796 PackageParser.Package pkg; 4797 synchronized (mPackages) { 4798 pkg = mPackages.get(packageName); 4799 if (pkg == null) { 4800 throw new IllegalArgumentException("Missing package: " + packageName); 4801 } 4802 } 4803 4804 synchronized (mInstallLock) { 4805 final String[] instructionSets = new String[] { 4806 getPrimaryInstructionSet(pkg.applicationInfo) }; 4807 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4808 if (res != DEX_OPT_PERFORMED) { 4809 throw new IllegalStateException("Failed to dexopt: " + res); 4810 } 4811 } 4812 } 4813 4814 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4815 boolean forceDex, boolean defer, boolean inclDependencies) { 4816 HashSet<String> done; 4817 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4818 done = new HashSet<String>(); 4819 done.add(pkg.packageName); 4820 } else { 4821 done = null; 4822 } 4823 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4824 } 4825 4826 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4827 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4828 Slog.w(TAG, "Unable to update from " + oldPkg.name 4829 + " to " + newPkg.packageName 4830 + ": old package not in system partition"); 4831 return false; 4832 } else if (mPackages.get(oldPkg.name) != null) { 4833 Slog.w(TAG, "Unable to update from " + oldPkg.name 4834 + " to " + newPkg.packageName 4835 + ": old package still exists"); 4836 return false; 4837 } 4838 return true; 4839 } 4840 4841 File getDataPathForUser(int userId) { 4842 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4843 } 4844 4845 private File getDataPathForPackage(String packageName, int userId) { 4846 /* 4847 * Until we fully support multiple users, return the directory we 4848 * previously would have. The PackageManagerTests will need to be 4849 * revised when this is changed back.. 4850 */ 4851 if (userId == 0) { 4852 return new File(mAppDataDir, packageName); 4853 } else { 4854 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4855 + File.separator + packageName); 4856 } 4857 } 4858 4859 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4860 int[] users = sUserManager.getUserIds(); 4861 int res = mInstaller.install(packageName, uid, uid, seinfo); 4862 if (res < 0) { 4863 return res; 4864 } 4865 for (int user : users) { 4866 if (user != 0) { 4867 res = mInstaller.createUserData(packageName, 4868 UserHandle.getUid(user, uid), user, seinfo); 4869 if (res < 0) { 4870 return res; 4871 } 4872 } 4873 } 4874 return res; 4875 } 4876 4877 private int removeDataDirsLI(String packageName) { 4878 int[] users = sUserManager.getUserIds(); 4879 int res = 0; 4880 for (int user : users) { 4881 int resInner = mInstaller.remove(packageName, user); 4882 if (resInner < 0) { 4883 res = resInner; 4884 } 4885 } 4886 4887 return res; 4888 } 4889 4890 private int deleteCodeCacheDirsLI(String packageName) { 4891 int[] users = sUserManager.getUserIds(); 4892 int res = 0; 4893 for (int user : users) { 4894 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4895 if (resInner < 0) { 4896 res = resInner; 4897 } 4898 } 4899 return res; 4900 } 4901 4902 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4903 PackageParser.Package changingLib) { 4904 if (file.path != null) { 4905 usesLibraryFiles.add(file.path); 4906 return; 4907 } 4908 PackageParser.Package p = mPackages.get(file.apk); 4909 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4910 // If we are doing this while in the middle of updating a library apk, 4911 // then we need to make sure to use that new apk for determining the 4912 // dependencies here. (We haven't yet finished committing the new apk 4913 // to the package manager state.) 4914 if (p == null || p.packageName.equals(changingLib.packageName)) { 4915 p = changingLib; 4916 } 4917 } 4918 if (p != null) { 4919 usesLibraryFiles.addAll(p.getAllCodePaths()); 4920 } 4921 } 4922 4923 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4924 PackageParser.Package changingLib) throws PackageManagerException { 4925 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4926 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4927 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4928 for (int i=0; i<N; i++) { 4929 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4930 if (file == null) { 4931 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4932 "Package " + pkg.packageName + " requires unavailable shared library " 4933 + pkg.usesLibraries.get(i) + "; failing!"); 4934 } 4935 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4936 } 4937 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4938 for (int i=0; i<N; i++) { 4939 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4940 if (file == null) { 4941 Slog.w(TAG, "Package " + pkg.packageName 4942 + " desires unavailable shared library " 4943 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4944 } else { 4945 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4946 } 4947 } 4948 N = usesLibraryFiles.size(); 4949 if (N > 0) { 4950 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4951 } else { 4952 pkg.usesLibraryFiles = null; 4953 } 4954 } 4955 } 4956 4957 private static boolean hasString(List<String> list, List<String> which) { 4958 if (list == null) { 4959 return false; 4960 } 4961 for (int i=list.size()-1; i>=0; i--) { 4962 for (int j=which.size()-1; j>=0; j--) { 4963 if (which.get(j).equals(list.get(i))) { 4964 return true; 4965 } 4966 } 4967 } 4968 return false; 4969 } 4970 4971 private void updateAllSharedLibrariesLPw() { 4972 for (PackageParser.Package pkg : mPackages.values()) { 4973 try { 4974 updateSharedLibrariesLPw(pkg, null); 4975 } catch (PackageManagerException e) { 4976 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4977 } 4978 } 4979 } 4980 4981 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4982 PackageParser.Package changingPkg) { 4983 ArrayList<PackageParser.Package> res = null; 4984 for (PackageParser.Package pkg : mPackages.values()) { 4985 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4986 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4987 if (res == null) { 4988 res = new ArrayList<PackageParser.Package>(); 4989 } 4990 res.add(pkg); 4991 try { 4992 updateSharedLibrariesLPw(pkg, changingPkg); 4993 } catch (PackageManagerException e) { 4994 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4995 } 4996 } 4997 } 4998 return res; 4999 } 5000 5001 /** 5002 * Derive the value of the {@code cpuAbiOverride} based on the provided 5003 * value and an optional stored value from the package settings. 5004 */ 5005 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5006 String cpuAbiOverride = null; 5007 5008 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5009 cpuAbiOverride = null; 5010 } else if (abiOverride != null) { 5011 cpuAbiOverride = abiOverride; 5012 } else if (settings != null) { 5013 cpuAbiOverride = settings.cpuAbiOverrideString; 5014 } 5015 5016 return cpuAbiOverride; 5017 } 5018 5019 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5020 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5021 final File scanFile = new File(pkg.codePath); 5022 if (pkg.applicationInfo.getCodePath() == null || 5023 pkg.applicationInfo.getResourcePath() == null) { 5024 // Bail out. The resource and code paths haven't been set. 5025 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5026 "Code and resource paths haven't been set correctly"); 5027 } 5028 5029 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5030 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5031 } 5032 5033 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5034 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5035 } 5036 5037 if (mCustomResolverComponentName != null && 5038 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5039 setUpCustomResolverActivity(pkg); 5040 } 5041 5042 if (pkg.packageName.equals("android")) { 5043 synchronized (mPackages) { 5044 if (mAndroidApplication != null) { 5045 Slog.w(TAG, "*************************************************"); 5046 Slog.w(TAG, "Core android package being redefined. Skipping."); 5047 Slog.w(TAG, " file=" + scanFile); 5048 Slog.w(TAG, "*************************************************"); 5049 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5050 "Core android package being redefined. Skipping."); 5051 } 5052 5053 // Set up information for our fall-back user intent resolution activity. 5054 mPlatformPackage = pkg; 5055 pkg.mVersionCode = mSdkVersion; 5056 mAndroidApplication = pkg.applicationInfo; 5057 5058 if (!mResolverReplaced) { 5059 mResolveActivity.applicationInfo = mAndroidApplication; 5060 mResolveActivity.name = ResolverActivity.class.getName(); 5061 mResolveActivity.packageName = mAndroidApplication.packageName; 5062 mResolveActivity.processName = "system:ui"; 5063 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5064 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5065 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5066 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5067 mResolveActivity.exported = true; 5068 mResolveActivity.enabled = true; 5069 mResolveInfo.activityInfo = mResolveActivity; 5070 mResolveInfo.priority = 0; 5071 mResolveInfo.preferredOrder = 0; 5072 mResolveInfo.match = 0; 5073 mResolveComponentName = new ComponentName( 5074 mAndroidApplication.packageName, mResolveActivity.name); 5075 } 5076 } 5077 } 5078 5079 if (DEBUG_PACKAGE_SCANNING) { 5080 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5081 Log.d(TAG, "Scanning package " + pkg.packageName); 5082 } 5083 5084 if (mPackages.containsKey(pkg.packageName) 5085 || mSharedLibraries.containsKey(pkg.packageName)) { 5086 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5087 "Application package " + pkg.packageName 5088 + " already installed. Skipping duplicate."); 5089 } 5090 5091 // Initialize package source and resource directories 5092 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5093 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5094 5095 SharedUserSetting suid = null; 5096 PackageSetting pkgSetting = null; 5097 5098 if (!isSystemApp(pkg)) { 5099 // Only system apps can use these features. 5100 pkg.mOriginalPackages = null; 5101 pkg.mRealPackage = null; 5102 pkg.mAdoptPermissions = null; 5103 } 5104 5105 // writer 5106 synchronized (mPackages) { 5107 if (pkg.mSharedUserId != null) { 5108 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5109 if (suid == null) { 5110 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5111 "Creating application package " + pkg.packageName 5112 + " for shared user failed"); 5113 } 5114 if (DEBUG_PACKAGE_SCANNING) { 5115 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5116 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5117 + "): packages=" + suid.packages); 5118 } 5119 } 5120 5121 // Check if we are renaming from an original package name. 5122 PackageSetting origPackage = null; 5123 String realName = null; 5124 if (pkg.mOriginalPackages != null) { 5125 // This package may need to be renamed to a previously 5126 // installed name. Let's check on that... 5127 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5128 if (pkg.mOriginalPackages.contains(renamed)) { 5129 // This package had originally been installed as the 5130 // original name, and we have already taken care of 5131 // transitioning to the new one. Just update the new 5132 // one to continue using the old name. 5133 realName = pkg.mRealPackage; 5134 if (!pkg.packageName.equals(renamed)) { 5135 // Callers into this function may have already taken 5136 // care of renaming the package; only do it here if 5137 // it is not already done. 5138 pkg.setPackageName(renamed); 5139 } 5140 5141 } else { 5142 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5143 if ((origPackage = mSettings.peekPackageLPr( 5144 pkg.mOriginalPackages.get(i))) != null) { 5145 // We do have the package already installed under its 5146 // original name... should we use it? 5147 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5148 // New package is not compatible with original. 5149 origPackage = null; 5150 continue; 5151 } else if (origPackage.sharedUser != null) { 5152 // Make sure uid is compatible between packages. 5153 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5154 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5155 + " to " + pkg.packageName + ": old uid " 5156 + origPackage.sharedUser.name 5157 + " differs from " + pkg.mSharedUserId); 5158 origPackage = null; 5159 continue; 5160 } 5161 } else { 5162 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5163 + pkg.packageName + " to old name " + origPackage.name); 5164 } 5165 break; 5166 } 5167 } 5168 } 5169 } 5170 5171 if (mTransferedPackages.contains(pkg.packageName)) { 5172 Slog.w(TAG, "Package " + pkg.packageName 5173 + " was transferred to another, but its .apk remains"); 5174 } 5175 5176 // Just create the setting, don't add it yet. For already existing packages 5177 // the PkgSetting exists already and doesn't have to be created. 5178 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5179 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5180 pkg.applicationInfo.primaryCpuAbi, 5181 pkg.applicationInfo.secondaryCpuAbi, 5182 pkg.applicationInfo.flags, user, false); 5183 if (pkgSetting == null) { 5184 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5185 "Creating application package " + pkg.packageName + " failed"); 5186 } 5187 5188 if (pkgSetting.origPackage != null) { 5189 // If we are first transitioning from an original package, 5190 // fix up the new package's name now. We need to do this after 5191 // looking up the package under its new name, so getPackageLP 5192 // can take care of fiddling things correctly. 5193 pkg.setPackageName(origPackage.name); 5194 5195 // File a report about this. 5196 String msg = "New package " + pkgSetting.realName 5197 + " renamed to replace old package " + pkgSetting.name; 5198 reportSettingsProblem(Log.WARN, msg); 5199 5200 // Make a note of it. 5201 mTransferedPackages.add(origPackage.name); 5202 5203 // No longer need to retain this. 5204 pkgSetting.origPackage = null; 5205 } 5206 5207 if (realName != null) { 5208 // Make a note of it. 5209 mTransferedPackages.add(pkg.packageName); 5210 } 5211 5212 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5213 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5214 } 5215 5216 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5217 // Check all shared libraries and map to their actual file path. 5218 // We only do this here for apps not on a system dir, because those 5219 // are the only ones that can fail an install due to this. We 5220 // will take care of the system apps by updating all of their 5221 // library paths after the scan is done. 5222 updateSharedLibrariesLPw(pkg, null); 5223 } 5224 5225 if (mFoundPolicyFile) { 5226 SELinuxMMAC.assignSeinfoValue(pkg); 5227 } 5228 5229 pkg.applicationInfo.uid = pkgSetting.appId; 5230 pkg.mExtras = pkgSetting; 5231 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5232 try { 5233 verifySignaturesLP(pkgSetting, pkg); 5234 } catch (PackageManagerException e) { 5235 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5236 throw e; 5237 } 5238 // The signature has changed, but this package is in the system 5239 // image... let's recover! 5240 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5241 // However... if this package is part of a shared user, but it 5242 // doesn't match the signature of the shared user, let's fail. 5243 // What this means is that you can't change the signatures 5244 // associated with an overall shared user, which doesn't seem all 5245 // that unreasonable. 5246 if (pkgSetting.sharedUser != null) { 5247 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5248 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5249 throw new PackageManagerException( 5250 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5251 "Signature mismatch for shared user : " 5252 + pkgSetting.sharedUser); 5253 } 5254 } 5255 // File a report about this. 5256 String msg = "System package " + pkg.packageName 5257 + " signature changed; retaining data."; 5258 reportSettingsProblem(Log.WARN, msg); 5259 } 5260 } else { 5261 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5262 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5263 + pkg.packageName + " upgrade keys do not match the " 5264 + "previously installed version"); 5265 } else { 5266 // signatures may have changed as result of upgrade 5267 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5268 } 5269 } 5270 // Verify that this new package doesn't have any content providers 5271 // that conflict with existing packages. Only do this if the 5272 // package isn't already installed, since we don't want to break 5273 // things that are installed. 5274 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5275 final int N = pkg.providers.size(); 5276 int i; 5277 for (i=0; i<N; i++) { 5278 PackageParser.Provider p = pkg.providers.get(i); 5279 if (p.info.authority != null) { 5280 String names[] = p.info.authority.split(";"); 5281 for (int j = 0; j < names.length; j++) { 5282 if (mProvidersByAuthority.containsKey(names[j])) { 5283 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5284 final String otherPackageName = 5285 ((other != null && other.getComponentName() != null) ? 5286 other.getComponentName().getPackageName() : "?"); 5287 throw new PackageManagerException( 5288 INSTALL_FAILED_CONFLICTING_PROVIDER, 5289 "Can't install because provider name " + names[j] 5290 + " (in package " + pkg.applicationInfo.packageName 5291 + ") is already used by " + otherPackageName); 5292 } 5293 } 5294 } 5295 } 5296 } 5297 5298 if (pkg.mAdoptPermissions != null) { 5299 // This package wants to adopt ownership of permissions from 5300 // another package. 5301 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5302 final String origName = pkg.mAdoptPermissions.get(i); 5303 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5304 if (orig != null) { 5305 if (verifyPackageUpdateLPr(orig, pkg)) { 5306 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5307 + pkg.packageName); 5308 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5309 } 5310 } 5311 } 5312 } 5313 } 5314 5315 final String pkgName = pkg.packageName; 5316 5317 final long scanFileTime = scanFile.lastModified(); 5318 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5319 pkg.applicationInfo.processName = fixProcessName( 5320 pkg.applicationInfo.packageName, 5321 pkg.applicationInfo.processName, 5322 pkg.applicationInfo.uid); 5323 5324 File dataPath; 5325 if (mPlatformPackage == pkg) { 5326 // The system package is special. 5327 dataPath = new File (Environment.getDataDirectory(), "system"); 5328 pkg.applicationInfo.dataDir = dataPath.getPath(); 5329 5330 } else { 5331 // This is a normal package, need to make its data directory. 5332 dataPath = getDataPathForPackage(pkg.packageName, 0); 5333 5334 boolean uidError = false; 5335 5336 if (dataPath.exists()) { 5337 int currentUid = 0; 5338 try { 5339 StructStat stat = Os.stat(dataPath.getPath()); 5340 currentUid = stat.st_uid; 5341 } catch (ErrnoException e) { 5342 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5343 } 5344 5345 // If we have mismatched owners for the data path, we have a problem. 5346 if (currentUid != pkg.applicationInfo.uid) { 5347 boolean recovered = false; 5348 if (currentUid == 0) { 5349 // The directory somehow became owned by root. Wow. 5350 // This is probably because the system was stopped while 5351 // installd was in the middle of messing with its libs 5352 // directory. Ask installd to fix that. 5353 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5354 pkg.applicationInfo.uid); 5355 if (ret >= 0) { 5356 recovered = true; 5357 String msg = "Package " + pkg.packageName 5358 + " unexpectedly changed to uid 0; recovered to " + 5359 + pkg.applicationInfo.uid; 5360 reportSettingsProblem(Log.WARN, msg); 5361 } 5362 } 5363 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5364 || (scanFlags&SCAN_BOOTING) != 0)) { 5365 // If this is a system app, we can at least delete its 5366 // current data so the application will still work. 5367 int ret = removeDataDirsLI(pkgName); 5368 if (ret >= 0) { 5369 // TODO: Kill the processes first 5370 // Old data gone! 5371 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5372 ? "System package " : "Third party package "; 5373 String msg = prefix + pkg.packageName 5374 + " has changed from uid: " 5375 + currentUid + " to " 5376 + pkg.applicationInfo.uid + "; old data erased"; 5377 reportSettingsProblem(Log.WARN, msg); 5378 recovered = true; 5379 5380 // And now re-install the app. 5381 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5382 pkg.applicationInfo.seinfo); 5383 if (ret == -1) { 5384 // Ack should not happen! 5385 msg = prefix + pkg.packageName 5386 + " could not have data directory re-created after delete."; 5387 reportSettingsProblem(Log.WARN, msg); 5388 throw new PackageManagerException( 5389 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5390 } 5391 } 5392 if (!recovered) { 5393 mHasSystemUidErrors = true; 5394 } 5395 } else if (!recovered) { 5396 // If we allow this install to proceed, we will be broken. 5397 // Abort, abort! 5398 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5399 "scanPackageLI"); 5400 } 5401 if (!recovered) { 5402 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5403 + pkg.applicationInfo.uid + "/fs_" 5404 + currentUid; 5405 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5406 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5407 String msg = "Package " + pkg.packageName 5408 + " has mismatched uid: " 5409 + currentUid + " on disk, " 5410 + pkg.applicationInfo.uid + " in settings"; 5411 // writer 5412 synchronized (mPackages) { 5413 mSettings.mReadMessages.append(msg); 5414 mSettings.mReadMessages.append('\n'); 5415 uidError = true; 5416 if (!pkgSetting.uidError) { 5417 reportSettingsProblem(Log.ERROR, msg); 5418 } 5419 } 5420 } 5421 } 5422 pkg.applicationInfo.dataDir = dataPath.getPath(); 5423 if (mShouldRestoreconData) { 5424 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5425 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5426 pkg.applicationInfo.uid); 5427 } 5428 } else { 5429 if (DEBUG_PACKAGE_SCANNING) { 5430 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5431 Log.v(TAG, "Want this data dir: " + dataPath); 5432 } 5433 //invoke installer to do the actual installation 5434 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5435 pkg.applicationInfo.seinfo); 5436 if (ret < 0) { 5437 // Error from installer 5438 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5439 "Unable to create data dirs [errorCode=" + ret + "]"); 5440 } 5441 5442 if (dataPath.exists()) { 5443 pkg.applicationInfo.dataDir = dataPath.getPath(); 5444 } else { 5445 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5446 pkg.applicationInfo.dataDir = null; 5447 } 5448 } 5449 5450 pkgSetting.uidError = uidError; 5451 } 5452 5453 final String path = scanFile.getPath(); 5454 final String codePath = pkg.applicationInfo.getCodePath(); 5455 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5456 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5457 setBundledAppAbisAndRoots(pkg, pkgSetting); 5458 5459 // If we haven't found any native libraries for the app, check if it has 5460 // renderscript code. We'll need to force the app to 32 bit if it has 5461 // renderscript bitcode. 5462 if (pkg.applicationInfo.primaryCpuAbi == null 5463 && pkg.applicationInfo.secondaryCpuAbi == null 5464 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5465 NativeLibraryHelper.Handle handle = null; 5466 try { 5467 handle = NativeLibraryHelper.Handle.create(scanFile); 5468 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5469 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5470 } 5471 } catch (IOException ioe) { 5472 Slog.w(TAG, "Error scanning system app : " + ioe); 5473 } finally { 5474 IoUtils.closeQuietly(handle); 5475 } 5476 } 5477 5478 setNativeLibraryPaths(pkg); 5479 } else { 5480 // TODO: We can probably be smarter about this stuff. For installed apps, 5481 // we can calculate this information at install time once and for all. For 5482 // system apps, we can probably assume that this information doesn't change 5483 // after the first boot scan. As things stand, we do lots of unnecessary work. 5484 5485 // Give ourselves some initial paths; we'll come back for another 5486 // pass once we've determined ABI below. 5487 setNativeLibraryPaths(pkg); 5488 5489 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5490 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5491 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5492 5493 NativeLibraryHelper.Handle handle = null; 5494 try { 5495 handle = NativeLibraryHelper.Handle.create(scanFile); 5496 // TODO(multiArch): This can be null for apps that didn't go through the 5497 // usual installation process. We can calculate it again, like we 5498 // do during install time. 5499 // 5500 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5501 // unnecessary. 5502 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5503 5504 // Null out the abis so that they can be recalculated. 5505 pkg.applicationInfo.primaryCpuAbi = null; 5506 pkg.applicationInfo.secondaryCpuAbi = null; 5507 if (isMultiArch(pkg.applicationInfo)) { 5508 // Warn if we've set an abiOverride for multi-lib packages.. 5509 // By definition, we need to copy both 32 and 64 bit libraries for 5510 // such packages. 5511 if (pkg.cpuAbiOverride != null 5512 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5513 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5514 } 5515 5516 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5517 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5518 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5519 if (isAsec) { 5520 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5521 } else { 5522 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5523 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5524 useIsaSpecificSubdirs); 5525 } 5526 } 5527 5528 maybeThrowExceptionForMultiArchCopy( 5529 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5530 5531 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5532 if (isAsec) { 5533 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5534 } else { 5535 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5536 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5537 useIsaSpecificSubdirs); 5538 } 5539 } 5540 5541 maybeThrowExceptionForMultiArchCopy( 5542 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5543 5544 if (abi64 >= 0) { 5545 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5546 } 5547 5548 if (abi32 >= 0) { 5549 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5550 if (abi64 >= 0) { 5551 pkg.applicationInfo.secondaryCpuAbi = abi; 5552 } else { 5553 pkg.applicationInfo.primaryCpuAbi = abi; 5554 } 5555 } 5556 } else { 5557 String[] abiList = (cpuAbiOverride != null) ? 5558 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5559 5560 // Enable gross and lame hacks for apps that are built with old 5561 // SDK tools. We must scan their APKs for renderscript bitcode and 5562 // not launch them if it's present. Don't bother checking on devices 5563 // that don't have 64 bit support. 5564 boolean needsRenderScriptOverride = false; 5565 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5566 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5567 abiList = Build.SUPPORTED_32_BIT_ABIS; 5568 needsRenderScriptOverride = true; 5569 } 5570 5571 final int copyRet; 5572 if (isAsec) { 5573 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5574 } else { 5575 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5576 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5577 } 5578 5579 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5580 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5581 "Error unpackaging native libs for app, errorCode=" + copyRet); 5582 } 5583 5584 if (copyRet >= 0) { 5585 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5586 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5587 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5588 } else if (needsRenderScriptOverride) { 5589 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5590 } 5591 } 5592 } catch (IOException ioe) { 5593 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5594 } finally { 5595 IoUtils.closeQuietly(handle); 5596 } 5597 5598 // Now that we've calculated the ABIs and determined if it's an internal app, 5599 // we will go ahead and populate the nativeLibraryPath. 5600 setNativeLibraryPaths(pkg); 5601 5602 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5603 final int[] userIds = sUserManager.getUserIds(); 5604 synchronized (mInstallLock) { 5605 // Create a native library symlink only if we have native libraries 5606 // and if the native libraries are 32 bit libraries. We do not provide 5607 // this symlink for 64 bit libraries. 5608 if (pkg.applicationInfo.primaryCpuAbi != null && 5609 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5610 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5611 for (int userId : userIds) { 5612 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5613 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5614 "Failed linking native library dir (user=" + userId + ")"); 5615 } 5616 } 5617 } 5618 } 5619 } 5620 5621 // This is a special case for the "system" package, where the ABI is 5622 // dictated by the zygote configuration (and init.rc). We should keep track 5623 // of this ABI so that we can deal with "normal" applications that run under 5624 // the same UID correctly. 5625 if (mPlatformPackage == pkg) { 5626 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5627 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5628 } 5629 5630 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5631 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5632 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5633 // Copy the derived override back to the parsed package, so that we can 5634 // update the package settings accordingly. 5635 pkg.cpuAbiOverride = cpuAbiOverride; 5636 5637 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5638 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5639 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5640 5641 // Push the derived path down into PackageSettings so we know what to 5642 // clean up at uninstall time. 5643 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5644 5645 if (DEBUG_ABI_SELECTION) { 5646 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5647 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5648 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5649 } 5650 5651 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5652 // We don't do this here during boot because we can do it all 5653 // at once after scanning all existing packages. 5654 // 5655 // We also do this *before* we perform dexopt on this package, so that 5656 // we can avoid redundant dexopts, and also to make sure we've got the 5657 // code and package path correct. 5658 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5659 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5660 } 5661 5662 if ((scanFlags&SCAN_NO_DEX) == 0) { 5663 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false) 5664 == DEX_OPT_FAILED) { 5665 if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5666 removeDataDirsLI(pkg.packageName); 5667 } 5668 5669 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5670 } 5671 } 5672 5673 if (mFactoryTest && pkg.requestedPermissions.contains( 5674 android.Manifest.permission.FACTORY_TEST)) { 5675 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5676 } 5677 5678 ArrayList<PackageParser.Package> clientLibPkgs = null; 5679 5680 // writer 5681 synchronized (mPackages) { 5682 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5683 // Only system apps can add new shared libraries. 5684 if (pkg.libraryNames != null) { 5685 for (int i=0; i<pkg.libraryNames.size(); i++) { 5686 String name = pkg.libraryNames.get(i); 5687 boolean allowed = false; 5688 if (isUpdatedSystemApp(pkg)) { 5689 // New library entries can only be added through the 5690 // system image. This is important to get rid of a lot 5691 // of nasty edge cases: for example if we allowed a non- 5692 // system update of the app to add a library, then uninstalling 5693 // the update would make the library go away, and assumptions 5694 // we made such as through app install filtering would now 5695 // have allowed apps on the device which aren't compatible 5696 // with it. Better to just have the restriction here, be 5697 // conservative, and create many fewer cases that can negatively 5698 // impact the user experience. 5699 final PackageSetting sysPs = mSettings 5700 .getDisabledSystemPkgLPr(pkg.packageName); 5701 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5702 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5703 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5704 allowed = true; 5705 allowed = true; 5706 break; 5707 } 5708 } 5709 } 5710 } else { 5711 allowed = true; 5712 } 5713 if (allowed) { 5714 if (!mSharedLibraries.containsKey(name)) { 5715 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5716 } else if (!name.equals(pkg.packageName)) { 5717 Slog.w(TAG, "Package " + pkg.packageName + " library " 5718 + name + " already exists; skipping"); 5719 } 5720 } else { 5721 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5722 + name + " that is not declared on system image; skipping"); 5723 } 5724 } 5725 if ((scanFlags&SCAN_BOOTING) == 0) { 5726 // If we are not booting, we need to update any applications 5727 // that are clients of our shared library. If we are booting, 5728 // this will all be done once the scan is complete. 5729 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5730 } 5731 } 5732 } 5733 } 5734 5735 // We also need to dexopt any apps that are dependent on this library. Note that 5736 // if these fail, we should abort the install since installing the library will 5737 // result in some apps being broken. 5738 if (clientLibPkgs != null) { 5739 if ((scanFlags&SCAN_NO_DEX) == 0) { 5740 for (int i=0; i<clientLibPkgs.size(); i++) { 5741 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5742 if (performDexOptLI(clientPkg, null /* instruction sets */, 5743 forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false) 5744 == DEX_OPT_FAILED) { 5745 if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5746 removeDataDirsLI(pkg.packageName); 5747 } 5748 5749 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5750 "scanPackageLI failed to dexopt clientLibPkgs"); 5751 } 5752 } 5753 } 5754 } 5755 5756 // Request the ActivityManager to kill the process(only for existing packages) 5757 // so that we do not end up in a confused state while the user is still using the older 5758 // version of the application while the new one gets installed. 5759 if ((scanFlags & SCAN_REPLACING) != 0) { 5760 killApplication(pkg.applicationInfo.packageName, 5761 pkg.applicationInfo.uid, "update pkg"); 5762 } 5763 5764 // Also need to kill any apps that are dependent on the library. 5765 if (clientLibPkgs != null) { 5766 for (int i=0; i<clientLibPkgs.size(); i++) { 5767 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5768 killApplication(clientPkg.applicationInfo.packageName, 5769 clientPkg.applicationInfo.uid, "update lib"); 5770 } 5771 } 5772 5773 // writer 5774 synchronized (mPackages) { 5775 // We don't expect installation to fail beyond this point 5776 5777 // Add the new setting to mSettings 5778 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5779 // Add the new setting to mPackages 5780 mPackages.put(pkg.applicationInfo.packageName, pkg); 5781 // Make sure we don't accidentally delete its data. 5782 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5783 while (iter.hasNext()) { 5784 PackageCleanItem item = iter.next(); 5785 if (pkgName.equals(item.packageName)) { 5786 iter.remove(); 5787 } 5788 } 5789 5790 // Take care of first install / last update times. 5791 if (currentTime != 0) { 5792 if (pkgSetting.firstInstallTime == 0) { 5793 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5794 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5795 pkgSetting.lastUpdateTime = currentTime; 5796 } 5797 } else if (pkgSetting.firstInstallTime == 0) { 5798 // We need *something*. Take time time stamp of the file. 5799 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5800 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5801 if (scanFileTime != pkgSetting.timeStamp) { 5802 // A package on the system image has changed; consider this 5803 // to be an update. 5804 pkgSetting.lastUpdateTime = scanFileTime; 5805 } 5806 } 5807 5808 // Add the package's KeySets to the global KeySetManagerService 5809 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5810 try { 5811 // Old KeySetData no longer valid. 5812 ksms.removeAppKeySetDataLPw(pkg.packageName); 5813 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5814 if (pkg.mKeySetMapping != null) { 5815 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5816 pkg.mKeySetMapping.entrySet()) { 5817 if (entry.getValue() != null) { 5818 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5819 entry.getValue(), entry.getKey()); 5820 } 5821 } 5822 if (pkg.mUpgradeKeySets != null) { 5823 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5824 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5825 } 5826 } 5827 } 5828 } catch (NullPointerException e) { 5829 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5830 } catch (IllegalArgumentException e) { 5831 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5832 } 5833 5834 int N = pkg.providers.size(); 5835 StringBuilder r = null; 5836 int i; 5837 for (i=0; i<N; i++) { 5838 PackageParser.Provider p = pkg.providers.get(i); 5839 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5840 p.info.processName, pkg.applicationInfo.uid); 5841 mProviders.addProvider(p); 5842 p.syncable = p.info.isSyncable; 5843 if (p.info.authority != null) { 5844 String names[] = p.info.authority.split(";"); 5845 p.info.authority = null; 5846 for (int j = 0; j < names.length; j++) { 5847 if (j == 1 && p.syncable) { 5848 // We only want the first authority for a provider to possibly be 5849 // syncable, so if we already added this provider using a different 5850 // authority clear the syncable flag. We copy the provider before 5851 // changing it because the mProviders object contains a reference 5852 // to a provider that we don't want to change. 5853 // Only do this for the second authority since the resulting provider 5854 // object can be the same for all future authorities for this provider. 5855 p = new PackageParser.Provider(p); 5856 p.syncable = false; 5857 } 5858 if (!mProvidersByAuthority.containsKey(names[j])) { 5859 mProvidersByAuthority.put(names[j], p); 5860 if (p.info.authority == null) { 5861 p.info.authority = names[j]; 5862 } else { 5863 p.info.authority = p.info.authority + ";" + names[j]; 5864 } 5865 if (DEBUG_PACKAGE_SCANNING) { 5866 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5867 Log.d(TAG, "Registered content provider: " + names[j] 5868 + ", className = " + p.info.name + ", isSyncable = " 5869 + p.info.isSyncable); 5870 } 5871 } else { 5872 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5873 Slog.w(TAG, "Skipping provider name " + names[j] + 5874 " (in package " + pkg.applicationInfo.packageName + 5875 "): name already used by " 5876 + ((other != null && other.getComponentName() != null) 5877 ? other.getComponentName().getPackageName() : "?")); 5878 } 5879 } 5880 } 5881 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5882 if (r == null) { 5883 r = new StringBuilder(256); 5884 } else { 5885 r.append(' '); 5886 } 5887 r.append(p.info.name); 5888 } 5889 } 5890 if (r != null) { 5891 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5892 } 5893 5894 N = pkg.services.size(); 5895 r = null; 5896 for (i=0; i<N; i++) { 5897 PackageParser.Service s = pkg.services.get(i); 5898 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5899 s.info.processName, pkg.applicationInfo.uid); 5900 mServices.addService(s); 5901 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5902 if (r == null) { 5903 r = new StringBuilder(256); 5904 } else { 5905 r.append(' '); 5906 } 5907 r.append(s.info.name); 5908 } 5909 } 5910 if (r != null) { 5911 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5912 } 5913 5914 N = pkg.receivers.size(); 5915 r = null; 5916 for (i=0; i<N; i++) { 5917 PackageParser.Activity a = pkg.receivers.get(i); 5918 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5919 a.info.processName, pkg.applicationInfo.uid); 5920 mReceivers.addActivity(a, "receiver"); 5921 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5922 if (r == null) { 5923 r = new StringBuilder(256); 5924 } else { 5925 r.append(' '); 5926 } 5927 r.append(a.info.name); 5928 } 5929 } 5930 if (r != null) { 5931 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5932 } 5933 5934 N = pkg.activities.size(); 5935 r = null; 5936 for (i=0; i<N; i++) { 5937 PackageParser.Activity a = pkg.activities.get(i); 5938 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5939 a.info.processName, pkg.applicationInfo.uid); 5940 mActivities.addActivity(a, "activity"); 5941 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5942 if (r == null) { 5943 r = new StringBuilder(256); 5944 } else { 5945 r.append(' '); 5946 } 5947 r.append(a.info.name); 5948 } 5949 } 5950 if (r != null) { 5951 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5952 } 5953 5954 N = pkg.permissionGroups.size(); 5955 r = null; 5956 for (i=0; i<N; i++) { 5957 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5958 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5959 if (cur == null) { 5960 mPermissionGroups.put(pg.info.name, pg); 5961 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5962 if (r == null) { 5963 r = new StringBuilder(256); 5964 } else { 5965 r.append(' '); 5966 } 5967 r.append(pg.info.name); 5968 } 5969 } else { 5970 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5971 + pg.info.packageName + " ignored: original from " 5972 + cur.info.packageName); 5973 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5974 if (r == null) { 5975 r = new StringBuilder(256); 5976 } else { 5977 r.append(' '); 5978 } 5979 r.append("DUP:"); 5980 r.append(pg.info.name); 5981 } 5982 } 5983 } 5984 if (r != null) { 5985 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5986 } 5987 5988 N = pkg.permissions.size(); 5989 r = null; 5990 for (i=0; i<N; i++) { 5991 PackageParser.Permission p = pkg.permissions.get(i); 5992 HashMap<String, BasePermission> permissionMap = 5993 p.tree ? mSettings.mPermissionTrees 5994 : mSettings.mPermissions; 5995 p.group = mPermissionGroups.get(p.info.group); 5996 if (p.info.group == null || p.group != null) { 5997 BasePermission bp = permissionMap.get(p.info.name); 5998 if (bp == null) { 5999 bp = new BasePermission(p.info.name, p.info.packageName, 6000 BasePermission.TYPE_NORMAL); 6001 permissionMap.put(p.info.name, bp); 6002 } 6003 if (bp.perm == null) { 6004 if (bp.sourcePackage != null 6005 && !bp.sourcePackage.equals(p.info.packageName)) { 6006 // If this is a permission that was formerly defined by a non-system 6007 // app, but is now defined by a system app (following an upgrade), 6008 // discard the previous declaration and consider the system's to be 6009 // canonical. 6010 if (isSystemApp(p.owner)) { 6011 String msg = "New decl " + p.owner + " of permission " 6012 + p.info.name + " is system"; 6013 reportSettingsProblem(Log.WARN, msg); 6014 bp.sourcePackage = null; 6015 } 6016 } 6017 if (bp.sourcePackage == null 6018 || bp.sourcePackage.equals(p.info.packageName)) { 6019 BasePermission tree = findPermissionTreeLP(p.info.name); 6020 if (tree == null 6021 || tree.sourcePackage.equals(p.info.packageName)) { 6022 bp.packageSetting = pkgSetting; 6023 bp.perm = p; 6024 bp.uid = pkg.applicationInfo.uid; 6025 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6026 if (r == null) { 6027 r = new StringBuilder(256); 6028 } else { 6029 r.append(' '); 6030 } 6031 r.append(p.info.name); 6032 } 6033 } else { 6034 Slog.w(TAG, "Permission " + p.info.name + " from package " 6035 + p.info.packageName + " ignored: base tree " 6036 + tree.name + " is from package " 6037 + tree.sourcePackage); 6038 } 6039 } else { 6040 Slog.w(TAG, "Permission " + p.info.name + " from package " 6041 + p.info.packageName + " ignored: original from " 6042 + bp.sourcePackage); 6043 } 6044 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6045 if (r == null) { 6046 r = new StringBuilder(256); 6047 } else { 6048 r.append(' '); 6049 } 6050 r.append("DUP:"); 6051 r.append(p.info.name); 6052 } 6053 if (bp.perm == p) { 6054 bp.protectionLevel = p.info.protectionLevel; 6055 } 6056 } else { 6057 Slog.w(TAG, "Permission " + p.info.name + " from package " 6058 + p.info.packageName + " ignored: no group " 6059 + p.group); 6060 } 6061 } 6062 if (r != null) { 6063 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6064 } 6065 6066 N = pkg.instrumentation.size(); 6067 r = null; 6068 for (i=0; i<N; i++) { 6069 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6070 a.info.packageName = pkg.applicationInfo.packageName; 6071 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6072 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6073 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6074 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6075 a.info.dataDir = pkg.applicationInfo.dataDir; 6076 6077 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6078 // need other information about the application, like the ABI and what not ? 6079 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6080 mInstrumentation.put(a.getComponentName(), a); 6081 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6082 if (r == null) { 6083 r = new StringBuilder(256); 6084 } else { 6085 r.append(' '); 6086 } 6087 r.append(a.info.name); 6088 } 6089 } 6090 if (r != null) { 6091 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6092 } 6093 6094 if (pkg.protectedBroadcasts != null) { 6095 N = pkg.protectedBroadcasts.size(); 6096 for (i=0; i<N; i++) { 6097 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6098 } 6099 } 6100 6101 pkgSetting.setTimeStamp(scanFileTime); 6102 6103 // Create idmap files for pairs of (packages, overlay packages). 6104 // Note: "android", ie framework-res.apk, is handled by native layers. 6105 if (pkg.mOverlayTarget != null) { 6106 // This is an overlay package. 6107 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6108 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6109 mOverlays.put(pkg.mOverlayTarget, 6110 new HashMap<String, PackageParser.Package>()); 6111 } 6112 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6113 map.put(pkg.packageName, pkg); 6114 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6115 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6116 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6117 "scanPackageLI failed to createIdmap"); 6118 } 6119 } 6120 } else if (mOverlays.containsKey(pkg.packageName) && 6121 !pkg.packageName.equals("android")) { 6122 // This is a regular package, with one or more known overlay packages. 6123 createIdmapsForPackageLI(pkg); 6124 } 6125 } 6126 6127 return pkg; 6128 } 6129 6130 /** 6131 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6132 * i.e, so that all packages can be run inside a single process if required. 6133 * 6134 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6135 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6136 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6137 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6138 * updating a package that belongs to a shared user. 6139 * 6140 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6141 * adds unnecessary complexity. 6142 */ 6143 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6144 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6145 String requiredInstructionSet = null; 6146 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6147 requiredInstructionSet = VMRuntime.getInstructionSet( 6148 scannedPackage.applicationInfo.primaryCpuAbi); 6149 } 6150 6151 PackageSetting requirer = null; 6152 for (PackageSetting ps : packagesForUser) { 6153 // If packagesForUser contains scannedPackage, we skip it. This will happen 6154 // when scannedPackage is an update of an existing package. Without this check, 6155 // we will never be able to change the ABI of any package belonging to a shared 6156 // user, even if it's compatible with other packages. 6157 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6158 if (ps.primaryCpuAbiString == null) { 6159 continue; 6160 } 6161 6162 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6163 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6164 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6165 // this but there's not much we can do. 6166 String errorMessage = "Instruction set mismatch, " 6167 + ((requirer == null) ? "[caller]" : requirer) 6168 + " requires " + requiredInstructionSet + " whereas " + ps 6169 + " requires " + instructionSet; 6170 Slog.w(TAG, errorMessage); 6171 } 6172 6173 if (requiredInstructionSet == null) { 6174 requiredInstructionSet = instructionSet; 6175 requirer = ps; 6176 } 6177 } 6178 } 6179 6180 if (requiredInstructionSet != null) { 6181 String adjustedAbi; 6182 if (requirer != null) { 6183 // requirer != null implies that either scannedPackage was null or that scannedPackage 6184 // did not require an ABI, in which case we have to adjust scannedPackage to match 6185 // the ABI of the set (which is the same as requirer's ABI) 6186 adjustedAbi = requirer.primaryCpuAbiString; 6187 if (scannedPackage != null) { 6188 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6189 } 6190 } else { 6191 // requirer == null implies that we're updating all ABIs in the set to 6192 // match scannedPackage. 6193 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6194 } 6195 6196 for (PackageSetting ps : packagesForUser) { 6197 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6198 if (ps.primaryCpuAbiString != null) { 6199 continue; 6200 } 6201 6202 ps.primaryCpuAbiString = adjustedAbi; 6203 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6204 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6205 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6206 6207 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6208 deferDexOpt, true) == DEX_OPT_FAILED) { 6209 ps.primaryCpuAbiString = null; 6210 ps.pkg.applicationInfo.primaryCpuAbi = null; 6211 return; 6212 } else { 6213 mInstaller.rmdex(ps.codePathString, 6214 getDexCodeInstructionSet(getPreferredInstructionSet())); 6215 } 6216 } 6217 } 6218 } 6219 } 6220 } 6221 6222 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6223 synchronized (mPackages) { 6224 mResolverReplaced = true; 6225 // Set up information for custom user intent resolution activity. 6226 mResolveActivity.applicationInfo = pkg.applicationInfo; 6227 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6228 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6229 mResolveActivity.processName = null; 6230 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6231 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6232 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6233 mResolveActivity.theme = 0; 6234 mResolveActivity.exported = true; 6235 mResolveActivity.enabled = true; 6236 mResolveInfo.activityInfo = mResolveActivity; 6237 mResolveInfo.priority = 0; 6238 mResolveInfo.preferredOrder = 0; 6239 mResolveInfo.match = 0; 6240 mResolveComponentName = mCustomResolverComponentName; 6241 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6242 mResolveComponentName); 6243 } 6244 } 6245 6246 private static String calculateBundledApkRoot(final String codePathString) { 6247 final File codePath = new File(codePathString); 6248 final File codeRoot; 6249 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6250 codeRoot = Environment.getRootDirectory(); 6251 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6252 codeRoot = Environment.getOemDirectory(); 6253 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6254 codeRoot = Environment.getVendorDirectory(); 6255 } else { 6256 // Unrecognized code path; take its top real segment as the apk root: 6257 // e.g. /something/app/blah.apk => /something 6258 try { 6259 File f = codePath.getCanonicalFile(); 6260 File parent = f.getParentFile(); // non-null because codePath is a file 6261 File tmp; 6262 while ((tmp = parent.getParentFile()) != null) { 6263 f = parent; 6264 parent = tmp; 6265 } 6266 codeRoot = f; 6267 Slog.w(TAG, "Unrecognized code path " 6268 + codePath + " - using " + codeRoot); 6269 } catch (IOException e) { 6270 // Can't canonicalize the code path -- shenanigans? 6271 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6272 return Environment.getRootDirectory().getPath(); 6273 } 6274 } 6275 return codeRoot.getPath(); 6276 } 6277 6278 /** 6279 * Derive and set the location of native libraries for the given package, 6280 * which varies depending on where and how the package was installed. 6281 */ 6282 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6283 final ApplicationInfo info = pkg.applicationInfo; 6284 final String codePath = pkg.codePath; 6285 final File codeFile = new File(codePath); 6286 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6287 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6288 6289 info.nativeLibraryRootDir = null; 6290 info.nativeLibraryRootRequiresIsa = false; 6291 info.nativeLibraryDir = null; 6292 info.secondaryNativeLibraryDir = null; 6293 6294 if (isApkFile(codeFile)) { 6295 // Monolithic install 6296 if (bundledApp) { 6297 // If "/system/lib64/apkname" exists, assume that is the per-package 6298 // native library directory to use; otherwise use "/system/lib/apkname". 6299 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6300 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6301 getPrimaryInstructionSet(info)); 6302 6303 // This is a bundled system app so choose the path based on the ABI. 6304 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6305 // is just the default path. 6306 final String apkName = deriveCodePathName(codePath); 6307 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6308 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6309 apkName).getAbsolutePath(); 6310 6311 if (info.secondaryCpuAbi != null) { 6312 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6313 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6314 secondaryLibDir, apkName).getAbsolutePath(); 6315 } 6316 } else if (asecApp) { 6317 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6318 .getAbsolutePath(); 6319 } else { 6320 final String apkName = deriveCodePathName(codePath); 6321 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6322 .getAbsolutePath(); 6323 } 6324 6325 info.nativeLibraryRootRequiresIsa = false; 6326 info.nativeLibraryDir = info.nativeLibraryRootDir; 6327 } else { 6328 // Cluster install 6329 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6330 info.nativeLibraryRootRequiresIsa = true; 6331 6332 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6333 getPrimaryInstructionSet(info)).getAbsolutePath(); 6334 6335 if (info.secondaryCpuAbi != null) { 6336 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6337 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6338 } 6339 } 6340 } 6341 6342 /** 6343 * Calculate the abis and roots for a bundled app. These can uniquely 6344 * be determined from the contents of the system partition, i.e whether 6345 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6346 * of this information, and instead assume that the system was built 6347 * sensibly. 6348 */ 6349 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6350 PackageSetting pkgSetting) { 6351 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6352 6353 // If "/system/lib64/apkname" exists, assume that is the per-package 6354 // native library directory to use; otherwise use "/system/lib/apkname". 6355 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6356 setBundledAppAbi(pkg, apkRoot, apkName); 6357 // pkgSetting might be null during rescan following uninstall of updates 6358 // to a bundled app, so accommodate that possibility. The settings in 6359 // that case will be established later from the parsed package. 6360 // 6361 // If the settings aren't null, sync them up with what we've just derived. 6362 // note that apkRoot isn't stored in the package settings. 6363 if (pkgSetting != null) { 6364 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6365 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6366 } 6367 } 6368 6369 /** 6370 * Deduces the ABI of a bundled app and sets the relevant fields on the 6371 * parsed pkg object. 6372 * 6373 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6374 * under which system libraries are installed. 6375 * @param apkName the name of the installed package. 6376 */ 6377 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6378 final File codeFile = new File(pkg.codePath); 6379 6380 final boolean has64BitLibs; 6381 final boolean has32BitLibs; 6382 if (isApkFile(codeFile)) { 6383 // Monolithic install 6384 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6385 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6386 } else { 6387 // Cluster install 6388 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6389 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6390 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6391 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6392 has64BitLibs = (new File(rootDir, isa)).exists(); 6393 } else { 6394 has64BitLibs = false; 6395 } 6396 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6397 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6398 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6399 has32BitLibs = (new File(rootDir, isa)).exists(); 6400 } else { 6401 has32BitLibs = false; 6402 } 6403 } 6404 6405 if (has64BitLibs && !has32BitLibs) { 6406 // The package has 64 bit libs, but not 32 bit libs. Its primary 6407 // ABI should be 64 bit. We can safely assume here that the bundled 6408 // native libraries correspond to the most preferred ABI in the list. 6409 6410 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6411 pkg.applicationInfo.secondaryCpuAbi = null; 6412 } else if (has32BitLibs && !has64BitLibs) { 6413 // The package has 32 bit libs but not 64 bit libs. Its primary 6414 // ABI should be 32 bit. 6415 6416 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6417 pkg.applicationInfo.secondaryCpuAbi = null; 6418 } else if (has32BitLibs && has64BitLibs) { 6419 // The application has both 64 and 32 bit bundled libraries. We check 6420 // here that the app declares multiArch support, and warn if it doesn't. 6421 // 6422 // We will be lenient here and record both ABIs. The primary will be the 6423 // ABI that's higher on the list, i.e, a device that's configured to prefer 6424 // 64 bit apps will see a 64 bit primary ABI, 6425 6426 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6427 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6428 } 6429 6430 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6431 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6432 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6433 } else { 6434 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6435 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6436 } 6437 } else { 6438 pkg.applicationInfo.primaryCpuAbi = null; 6439 pkg.applicationInfo.secondaryCpuAbi = null; 6440 } 6441 } 6442 6443 private void killApplication(String pkgName, int appId, String reason) { 6444 // Request the ActivityManager to kill the process(only for existing packages) 6445 // so that we do not end up in a confused state while the user is still using the older 6446 // version of the application while the new one gets installed. 6447 IActivityManager am = ActivityManagerNative.getDefault(); 6448 if (am != null) { 6449 try { 6450 am.killApplicationWithAppId(pkgName, appId, reason); 6451 } catch (RemoteException e) { 6452 } 6453 } 6454 } 6455 6456 void removePackageLI(PackageSetting ps, boolean chatty) { 6457 if (DEBUG_INSTALL) { 6458 if (chatty) 6459 Log.d(TAG, "Removing package " + ps.name); 6460 } 6461 6462 // writer 6463 synchronized (mPackages) { 6464 mPackages.remove(ps.name); 6465 final PackageParser.Package pkg = ps.pkg; 6466 if (pkg != null) { 6467 cleanPackageDataStructuresLILPw(pkg, chatty); 6468 } 6469 } 6470 } 6471 6472 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6473 if (DEBUG_INSTALL) { 6474 if (chatty) 6475 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6476 } 6477 6478 // writer 6479 synchronized (mPackages) { 6480 mPackages.remove(pkg.applicationInfo.packageName); 6481 cleanPackageDataStructuresLILPw(pkg, chatty); 6482 } 6483 } 6484 6485 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6486 int N = pkg.providers.size(); 6487 StringBuilder r = null; 6488 int i; 6489 for (i=0; i<N; i++) { 6490 PackageParser.Provider p = pkg.providers.get(i); 6491 mProviders.removeProvider(p); 6492 if (p.info.authority == null) { 6493 6494 /* There was another ContentProvider with this authority when 6495 * this app was installed so this authority is null, 6496 * Ignore it as we don't have to unregister the provider. 6497 */ 6498 continue; 6499 } 6500 String names[] = p.info.authority.split(";"); 6501 for (int j = 0; j < names.length; j++) { 6502 if (mProvidersByAuthority.get(names[j]) == p) { 6503 mProvidersByAuthority.remove(names[j]); 6504 if (DEBUG_REMOVE) { 6505 if (chatty) 6506 Log.d(TAG, "Unregistered content provider: " + names[j] 6507 + ", className = " + p.info.name + ", isSyncable = " 6508 + p.info.isSyncable); 6509 } 6510 } 6511 } 6512 if (DEBUG_REMOVE && chatty) { 6513 if (r == null) { 6514 r = new StringBuilder(256); 6515 } else { 6516 r.append(' '); 6517 } 6518 r.append(p.info.name); 6519 } 6520 } 6521 if (r != null) { 6522 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6523 } 6524 6525 N = pkg.services.size(); 6526 r = null; 6527 for (i=0; i<N; i++) { 6528 PackageParser.Service s = pkg.services.get(i); 6529 mServices.removeService(s); 6530 if (chatty) { 6531 if (r == null) { 6532 r = new StringBuilder(256); 6533 } else { 6534 r.append(' '); 6535 } 6536 r.append(s.info.name); 6537 } 6538 } 6539 if (r != null) { 6540 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6541 } 6542 6543 N = pkg.receivers.size(); 6544 r = null; 6545 for (i=0; i<N; i++) { 6546 PackageParser.Activity a = pkg.receivers.get(i); 6547 mReceivers.removeActivity(a, "receiver"); 6548 if (DEBUG_REMOVE && chatty) { 6549 if (r == null) { 6550 r = new StringBuilder(256); 6551 } else { 6552 r.append(' '); 6553 } 6554 r.append(a.info.name); 6555 } 6556 } 6557 if (r != null) { 6558 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6559 } 6560 6561 N = pkg.activities.size(); 6562 r = null; 6563 for (i=0; i<N; i++) { 6564 PackageParser.Activity a = pkg.activities.get(i); 6565 mActivities.removeActivity(a, "activity"); 6566 if (DEBUG_REMOVE && chatty) { 6567 if (r == null) { 6568 r = new StringBuilder(256); 6569 } else { 6570 r.append(' '); 6571 } 6572 r.append(a.info.name); 6573 } 6574 } 6575 if (r != null) { 6576 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6577 } 6578 6579 N = pkg.permissions.size(); 6580 r = null; 6581 for (i=0; i<N; i++) { 6582 PackageParser.Permission p = pkg.permissions.get(i); 6583 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6584 if (bp == null) { 6585 bp = mSettings.mPermissionTrees.get(p.info.name); 6586 } 6587 if (bp != null && bp.perm == p) { 6588 bp.perm = null; 6589 if (DEBUG_REMOVE && chatty) { 6590 if (r == null) { 6591 r = new StringBuilder(256); 6592 } else { 6593 r.append(' '); 6594 } 6595 r.append(p.info.name); 6596 } 6597 } 6598 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6599 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6600 if (appOpPerms != null) { 6601 appOpPerms.remove(pkg.packageName); 6602 } 6603 } 6604 } 6605 if (r != null) { 6606 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6607 } 6608 6609 N = pkg.requestedPermissions.size(); 6610 r = null; 6611 for (i=0; i<N; i++) { 6612 String perm = pkg.requestedPermissions.get(i); 6613 BasePermission bp = mSettings.mPermissions.get(perm); 6614 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6615 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6616 if (appOpPerms != null) { 6617 appOpPerms.remove(pkg.packageName); 6618 if (appOpPerms.isEmpty()) { 6619 mAppOpPermissionPackages.remove(perm); 6620 } 6621 } 6622 } 6623 } 6624 if (r != null) { 6625 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6626 } 6627 6628 N = pkg.instrumentation.size(); 6629 r = null; 6630 for (i=0; i<N; i++) { 6631 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6632 mInstrumentation.remove(a.getComponentName()); 6633 if (DEBUG_REMOVE && chatty) { 6634 if (r == null) { 6635 r = new StringBuilder(256); 6636 } else { 6637 r.append(' '); 6638 } 6639 r.append(a.info.name); 6640 } 6641 } 6642 if (r != null) { 6643 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6644 } 6645 6646 r = null; 6647 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6648 // Only system apps can hold shared libraries. 6649 if (pkg.libraryNames != null) { 6650 for (i=0; i<pkg.libraryNames.size(); i++) { 6651 String name = pkg.libraryNames.get(i); 6652 SharedLibraryEntry cur = mSharedLibraries.get(name); 6653 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6654 mSharedLibraries.remove(name); 6655 if (DEBUG_REMOVE && chatty) { 6656 if (r == null) { 6657 r = new StringBuilder(256); 6658 } else { 6659 r.append(' '); 6660 } 6661 r.append(name); 6662 } 6663 } 6664 } 6665 } 6666 } 6667 if (r != null) { 6668 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6669 } 6670 } 6671 6672 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6673 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6674 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6675 return true; 6676 } 6677 } 6678 return false; 6679 } 6680 6681 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6682 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6683 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6684 6685 private void updatePermissionsLPw(String changingPkg, 6686 PackageParser.Package pkgInfo, int flags) { 6687 // Make sure there are no dangling permission trees. 6688 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6689 while (it.hasNext()) { 6690 final BasePermission bp = it.next(); 6691 if (bp.packageSetting == null) { 6692 // We may not yet have parsed the package, so just see if 6693 // we still know about its settings. 6694 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6695 } 6696 if (bp.packageSetting == null) { 6697 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6698 + " from package " + bp.sourcePackage); 6699 it.remove(); 6700 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6701 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6702 Slog.i(TAG, "Removing old permission tree: " + bp.name 6703 + " from package " + bp.sourcePackage); 6704 flags |= UPDATE_PERMISSIONS_ALL; 6705 it.remove(); 6706 } 6707 } 6708 } 6709 6710 // Make sure all dynamic permissions have been assigned to a package, 6711 // and make sure there are no dangling permissions. 6712 it = mSettings.mPermissions.values().iterator(); 6713 while (it.hasNext()) { 6714 final BasePermission bp = it.next(); 6715 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6716 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6717 + bp.name + " pkg=" + bp.sourcePackage 6718 + " info=" + bp.pendingInfo); 6719 if (bp.packageSetting == null && bp.pendingInfo != null) { 6720 final BasePermission tree = findPermissionTreeLP(bp.name); 6721 if (tree != null && tree.perm != null) { 6722 bp.packageSetting = tree.packageSetting; 6723 bp.perm = new PackageParser.Permission(tree.perm.owner, 6724 new PermissionInfo(bp.pendingInfo)); 6725 bp.perm.info.packageName = tree.perm.info.packageName; 6726 bp.perm.info.name = bp.name; 6727 bp.uid = tree.uid; 6728 } 6729 } 6730 } 6731 if (bp.packageSetting == null) { 6732 // We may not yet have parsed the package, so just see if 6733 // we still know about its settings. 6734 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6735 } 6736 if (bp.packageSetting == null) { 6737 Slog.w(TAG, "Removing dangling permission: " + bp.name 6738 + " from package " + bp.sourcePackage); 6739 it.remove(); 6740 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6741 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6742 Slog.i(TAG, "Removing old permission: " + bp.name 6743 + " from package " + bp.sourcePackage); 6744 flags |= UPDATE_PERMISSIONS_ALL; 6745 it.remove(); 6746 } 6747 } 6748 } 6749 6750 // Now update the permissions for all packages, in particular 6751 // replace the granted permissions of the system packages. 6752 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6753 for (PackageParser.Package pkg : mPackages.values()) { 6754 if (pkg != pkgInfo) { 6755 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6756 } 6757 } 6758 } 6759 6760 if (pkgInfo != null) { 6761 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6762 } 6763 } 6764 6765 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6766 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6767 if (ps == null) { 6768 return; 6769 } 6770 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6771 HashSet<String> origPermissions = gp.grantedPermissions; 6772 boolean changedPermission = false; 6773 6774 if (replace) { 6775 ps.permissionsFixed = false; 6776 if (gp == ps) { 6777 origPermissions = new HashSet<String>(gp.grantedPermissions); 6778 gp.grantedPermissions.clear(); 6779 gp.gids = mGlobalGids; 6780 } 6781 } 6782 6783 if (gp.gids == null) { 6784 gp.gids = mGlobalGids; 6785 } 6786 6787 final int N = pkg.requestedPermissions.size(); 6788 for (int i=0; i<N; i++) { 6789 final String name = pkg.requestedPermissions.get(i); 6790 final boolean required = pkg.requestedPermissionsRequired.get(i); 6791 final BasePermission bp = mSettings.mPermissions.get(name); 6792 if (DEBUG_INSTALL) { 6793 if (gp != ps) { 6794 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6795 } 6796 } 6797 6798 if (bp == null || bp.packageSetting == null) { 6799 Slog.w(TAG, "Unknown permission " + name 6800 + " in package " + pkg.packageName); 6801 continue; 6802 } 6803 6804 final String perm = bp.name; 6805 boolean allowed; 6806 boolean allowedSig = false; 6807 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6808 // Keep track of app op permissions. 6809 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6810 if (pkgs == null) { 6811 pkgs = new ArraySet<>(); 6812 mAppOpPermissionPackages.put(bp.name, pkgs); 6813 } 6814 pkgs.add(pkg.packageName); 6815 } 6816 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6817 if (level == PermissionInfo.PROTECTION_NORMAL 6818 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6819 // We grant a normal or dangerous permission if any of the following 6820 // are true: 6821 // 1) The permission is required 6822 // 2) The permission is optional, but was granted in the past 6823 // 3) The permission is optional, but was requested by an 6824 // app in /system (not /data) 6825 // 6826 // Otherwise, reject the permission. 6827 allowed = (required || origPermissions.contains(perm) 6828 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6829 } else if (bp.packageSetting == null) { 6830 // This permission is invalid; skip it. 6831 allowed = false; 6832 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6833 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6834 if (allowed) { 6835 allowedSig = true; 6836 } 6837 } else { 6838 allowed = false; 6839 } 6840 if (DEBUG_INSTALL) { 6841 if (gp != ps) { 6842 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6843 } 6844 } 6845 if (allowed) { 6846 if (!isSystemApp(ps) && ps.permissionsFixed) { 6847 // If this is an existing, non-system package, then 6848 // we can't add any new permissions to it. 6849 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6850 // Except... if this is a permission that was added 6851 // to the platform (note: need to only do this when 6852 // updating the platform). 6853 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6854 } 6855 } 6856 if (allowed) { 6857 if (!gp.grantedPermissions.contains(perm)) { 6858 changedPermission = true; 6859 gp.grantedPermissions.add(perm); 6860 gp.gids = appendInts(gp.gids, bp.gids); 6861 } else if (!ps.haveGids) { 6862 gp.gids = appendInts(gp.gids, bp.gids); 6863 } 6864 } else { 6865 Slog.w(TAG, "Not granting permission " + perm 6866 + " to package " + pkg.packageName 6867 + " because it was previously installed without"); 6868 } 6869 } else { 6870 if (gp.grantedPermissions.remove(perm)) { 6871 changedPermission = true; 6872 gp.gids = removeInts(gp.gids, bp.gids); 6873 Slog.i(TAG, "Un-granting permission " + perm 6874 + " from package " + pkg.packageName 6875 + " (protectionLevel=" + bp.protectionLevel 6876 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6877 + ")"); 6878 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6879 // Don't print warning for app op permissions, since it is fine for them 6880 // not to be granted, there is a UI for the user to decide. 6881 Slog.w(TAG, "Not granting permission " + perm 6882 + " to package " + pkg.packageName 6883 + " (protectionLevel=" + bp.protectionLevel 6884 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6885 + ")"); 6886 } 6887 } 6888 } 6889 6890 if ((changedPermission || replace) && !ps.permissionsFixed && 6891 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6892 // This is the first that we have heard about this package, so the 6893 // permissions we have now selected are fixed until explicitly 6894 // changed. 6895 ps.permissionsFixed = true; 6896 } 6897 ps.haveGids = true; 6898 } 6899 6900 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6901 boolean allowed = false; 6902 final int NP = PackageParser.NEW_PERMISSIONS.length; 6903 for (int ip=0; ip<NP; ip++) { 6904 final PackageParser.NewPermissionInfo npi 6905 = PackageParser.NEW_PERMISSIONS[ip]; 6906 if (npi.name.equals(perm) 6907 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6908 allowed = true; 6909 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6910 + pkg.packageName); 6911 break; 6912 } 6913 } 6914 return allowed; 6915 } 6916 6917 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6918 BasePermission bp, HashSet<String> origPermissions) { 6919 boolean allowed; 6920 allowed = (compareSignatures( 6921 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6922 == PackageManager.SIGNATURE_MATCH) 6923 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6924 == PackageManager.SIGNATURE_MATCH); 6925 if (!allowed && (bp.protectionLevel 6926 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6927 if (isSystemApp(pkg)) { 6928 // For updated system applications, a system permission 6929 // is granted only if it had been defined by the original application. 6930 if (isUpdatedSystemApp(pkg)) { 6931 final PackageSetting sysPs = mSettings 6932 .getDisabledSystemPkgLPr(pkg.packageName); 6933 final GrantedPermissions origGp = sysPs.sharedUser != null 6934 ? sysPs.sharedUser : sysPs; 6935 6936 if (origGp.grantedPermissions.contains(perm)) { 6937 // If the original was granted this permission, we take 6938 // that grant decision as read and propagate it to the 6939 // update. 6940 allowed = true; 6941 } else { 6942 // The system apk may have been updated with an older 6943 // version of the one on the data partition, but which 6944 // granted a new system permission that it didn't have 6945 // before. In this case we do want to allow the app to 6946 // now get the new permission if the ancestral apk is 6947 // privileged to get it. 6948 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6949 for (int j=0; 6950 j<sysPs.pkg.requestedPermissions.size(); j++) { 6951 if (perm.equals( 6952 sysPs.pkg.requestedPermissions.get(j))) { 6953 allowed = true; 6954 break; 6955 } 6956 } 6957 } 6958 } 6959 } else { 6960 allowed = isPrivilegedApp(pkg); 6961 } 6962 } 6963 } 6964 if (!allowed && (bp.protectionLevel 6965 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6966 // For development permissions, a development permission 6967 // is granted only if it was already granted. 6968 allowed = origPermissions.contains(perm); 6969 } 6970 return allowed; 6971 } 6972 6973 final class ActivityIntentResolver 6974 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6975 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6976 boolean defaultOnly, int userId) { 6977 if (!sUserManager.exists(userId)) return null; 6978 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6979 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6980 } 6981 6982 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6983 int userId) { 6984 if (!sUserManager.exists(userId)) return null; 6985 mFlags = flags; 6986 return super.queryIntent(intent, resolvedType, 6987 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6988 } 6989 6990 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6991 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6992 if (!sUserManager.exists(userId)) return null; 6993 if (packageActivities == null) { 6994 return null; 6995 } 6996 mFlags = flags; 6997 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6998 final int N = packageActivities.size(); 6999 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7000 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7001 7002 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7003 for (int i = 0; i < N; ++i) { 7004 intentFilters = packageActivities.get(i).intents; 7005 if (intentFilters != null && intentFilters.size() > 0) { 7006 PackageParser.ActivityIntentInfo[] array = 7007 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7008 intentFilters.toArray(array); 7009 listCut.add(array); 7010 } 7011 } 7012 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7013 } 7014 7015 public final void addActivity(PackageParser.Activity a, String type) { 7016 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7017 mActivities.put(a.getComponentName(), a); 7018 if (DEBUG_SHOW_INFO) 7019 Log.v( 7020 TAG, " " + type + " " + 7021 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7022 if (DEBUG_SHOW_INFO) 7023 Log.v(TAG, " Class=" + a.info.name); 7024 final int NI = a.intents.size(); 7025 for (int j=0; j<NI; j++) { 7026 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7027 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7028 intent.setPriority(0); 7029 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7030 + a.className + " with priority > 0, forcing to 0"); 7031 } 7032 if (DEBUG_SHOW_INFO) { 7033 Log.v(TAG, " IntentFilter:"); 7034 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7035 } 7036 if (!intent.debugCheck()) { 7037 Log.w(TAG, "==> For Activity " + a.info.name); 7038 } 7039 addFilter(intent); 7040 } 7041 } 7042 7043 public final void removeActivity(PackageParser.Activity a, String type) { 7044 mActivities.remove(a.getComponentName()); 7045 if (DEBUG_SHOW_INFO) { 7046 Log.v(TAG, " " + type + " " 7047 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7048 : a.info.name) + ":"); 7049 Log.v(TAG, " Class=" + a.info.name); 7050 } 7051 final int NI = a.intents.size(); 7052 for (int j=0; j<NI; j++) { 7053 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7054 if (DEBUG_SHOW_INFO) { 7055 Log.v(TAG, " IntentFilter:"); 7056 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7057 } 7058 removeFilter(intent); 7059 } 7060 } 7061 7062 @Override 7063 protected boolean allowFilterResult( 7064 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7065 ActivityInfo filterAi = filter.activity.info; 7066 for (int i=dest.size()-1; i>=0; i--) { 7067 ActivityInfo destAi = dest.get(i).activityInfo; 7068 if (destAi.name == filterAi.name 7069 && destAi.packageName == filterAi.packageName) { 7070 return false; 7071 } 7072 } 7073 return true; 7074 } 7075 7076 @Override 7077 protected ActivityIntentInfo[] newArray(int size) { 7078 return new ActivityIntentInfo[size]; 7079 } 7080 7081 @Override 7082 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7083 if (!sUserManager.exists(userId)) return true; 7084 PackageParser.Package p = filter.activity.owner; 7085 if (p != null) { 7086 PackageSetting ps = (PackageSetting)p.mExtras; 7087 if (ps != null) { 7088 // System apps are never considered stopped for purposes of 7089 // filtering, because there may be no way for the user to 7090 // actually re-launch them. 7091 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7092 && ps.getStopped(userId); 7093 } 7094 } 7095 return false; 7096 } 7097 7098 @Override 7099 protected boolean isPackageForFilter(String packageName, 7100 PackageParser.ActivityIntentInfo info) { 7101 return packageName.equals(info.activity.owner.packageName); 7102 } 7103 7104 @Override 7105 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7106 int match, int userId) { 7107 if (!sUserManager.exists(userId)) return null; 7108 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7109 return null; 7110 } 7111 final PackageParser.Activity activity = info.activity; 7112 if (mSafeMode && (activity.info.applicationInfo.flags 7113 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7114 return null; 7115 } 7116 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7117 if (ps == null) { 7118 return null; 7119 } 7120 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7121 ps.readUserState(userId), userId); 7122 if (ai == null) { 7123 return null; 7124 } 7125 final ResolveInfo res = new ResolveInfo(); 7126 res.activityInfo = ai; 7127 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7128 res.filter = info; 7129 } 7130 res.priority = info.getPriority(); 7131 res.preferredOrder = activity.owner.mPreferredOrder; 7132 //System.out.println("Result: " + res.activityInfo.className + 7133 // " = " + res.priority); 7134 res.match = match; 7135 res.isDefault = info.hasDefault; 7136 res.labelRes = info.labelRes; 7137 res.nonLocalizedLabel = info.nonLocalizedLabel; 7138 if (userNeedsBadging(userId)) { 7139 res.noResourceId = true; 7140 } else { 7141 res.icon = info.icon; 7142 } 7143 res.system = isSystemApp(res.activityInfo.applicationInfo); 7144 return res; 7145 } 7146 7147 @Override 7148 protected void sortResults(List<ResolveInfo> results) { 7149 Collections.sort(results, mResolvePrioritySorter); 7150 } 7151 7152 @Override 7153 protected void dumpFilter(PrintWriter out, String prefix, 7154 PackageParser.ActivityIntentInfo filter) { 7155 out.print(prefix); out.print( 7156 Integer.toHexString(System.identityHashCode(filter.activity))); 7157 out.print(' '); 7158 filter.activity.printComponentShortName(out); 7159 out.print(" filter "); 7160 out.println(Integer.toHexString(System.identityHashCode(filter))); 7161 } 7162 7163// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7164// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7165// final List<ResolveInfo> retList = Lists.newArrayList(); 7166// while (i.hasNext()) { 7167// final ResolveInfo resolveInfo = i.next(); 7168// if (isEnabledLP(resolveInfo.activityInfo)) { 7169// retList.add(resolveInfo); 7170// } 7171// } 7172// return retList; 7173// } 7174 7175 // Keys are String (activity class name), values are Activity. 7176 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7177 = new HashMap<ComponentName, PackageParser.Activity>(); 7178 private int mFlags; 7179 } 7180 7181 private final class ServiceIntentResolver 7182 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7183 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7184 boolean defaultOnly, int userId) { 7185 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7186 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7187 } 7188 7189 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7190 int userId) { 7191 if (!sUserManager.exists(userId)) return null; 7192 mFlags = flags; 7193 return super.queryIntent(intent, resolvedType, 7194 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7195 } 7196 7197 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7198 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7199 if (!sUserManager.exists(userId)) return null; 7200 if (packageServices == null) { 7201 return null; 7202 } 7203 mFlags = flags; 7204 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7205 final int N = packageServices.size(); 7206 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7207 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7208 7209 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7210 for (int i = 0; i < N; ++i) { 7211 intentFilters = packageServices.get(i).intents; 7212 if (intentFilters != null && intentFilters.size() > 0) { 7213 PackageParser.ServiceIntentInfo[] array = 7214 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7215 intentFilters.toArray(array); 7216 listCut.add(array); 7217 } 7218 } 7219 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7220 } 7221 7222 public final void addService(PackageParser.Service s) { 7223 mServices.put(s.getComponentName(), s); 7224 if (DEBUG_SHOW_INFO) { 7225 Log.v(TAG, " " 7226 + (s.info.nonLocalizedLabel != null 7227 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7228 Log.v(TAG, " Class=" + s.info.name); 7229 } 7230 final int NI = s.intents.size(); 7231 int j; 7232 for (j=0; j<NI; j++) { 7233 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7234 if (DEBUG_SHOW_INFO) { 7235 Log.v(TAG, " IntentFilter:"); 7236 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7237 } 7238 if (!intent.debugCheck()) { 7239 Log.w(TAG, "==> For Service " + s.info.name); 7240 } 7241 addFilter(intent); 7242 } 7243 } 7244 7245 public final void removeService(PackageParser.Service s) { 7246 mServices.remove(s.getComponentName()); 7247 if (DEBUG_SHOW_INFO) { 7248 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7249 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7250 Log.v(TAG, " Class=" + s.info.name); 7251 } 7252 final int NI = s.intents.size(); 7253 int j; 7254 for (j=0; j<NI; j++) { 7255 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7256 if (DEBUG_SHOW_INFO) { 7257 Log.v(TAG, " IntentFilter:"); 7258 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7259 } 7260 removeFilter(intent); 7261 } 7262 } 7263 7264 @Override 7265 protected boolean allowFilterResult( 7266 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7267 ServiceInfo filterSi = filter.service.info; 7268 for (int i=dest.size()-1; i>=0; i--) { 7269 ServiceInfo destAi = dest.get(i).serviceInfo; 7270 if (destAi.name == filterSi.name 7271 && destAi.packageName == filterSi.packageName) { 7272 return false; 7273 } 7274 } 7275 return true; 7276 } 7277 7278 @Override 7279 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7280 return new PackageParser.ServiceIntentInfo[size]; 7281 } 7282 7283 @Override 7284 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7285 if (!sUserManager.exists(userId)) return true; 7286 PackageParser.Package p = filter.service.owner; 7287 if (p != null) { 7288 PackageSetting ps = (PackageSetting)p.mExtras; 7289 if (ps != null) { 7290 // System apps are never considered stopped for purposes of 7291 // filtering, because there may be no way for the user to 7292 // actually re-launch them. 7293 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7294 && ps.getStopped(userId); 7295 } 7296 } 7297 return false; 7298 } 7299 7300 @Override 7301 protected boolean isPackageForFilter(String packageName, 7302 PackageParser.ServiceIntentInfo info) { 7303 return packageName.equals(info.service.owner.packageName); 7304 } 7305 7306 @Override 7307 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7308 int match, int userId) { 7309 if (!sUserManager.exists(userId)) return null; 7310 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7311 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7312 return null; 7313 } 7314 final PackageParser.Service service = info.service; 7315 if (mSafeMode && (service.info.applicationInfo.flags 7316 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7317 return null; 7318 } 7319 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7320 if (ps == null) { 7321 return null; 7322 } 7323 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7324 ps.readUserState(userId), userId); 7325 if (si == null) { 7326 return null; 7327 } 7328 final ResolveInfo res = new ResolveInfo(); 7329 res.serviceInfo = si; 7330 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7331 res.filter = filter; 7332 } 7333 res.priority = info.getPriority(); 7334 res.preferredOrder = service.owner.mPreferredOrder; 7335 //System.out.println("Result: " + res.activityInfo.className + 7336 // " = " + res.priority); 7337 res.match = match; 7338 res.isDefault = info.hasDefault; 7339 res.labelRes = info.labelRes; 7340 res.nonLocalizedLabel = info.nonLocalizedLabel; 7341 res.icon = info.icon; 7342 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7343 return res; 7344 } 7345 7346 @Override 7347 protected void sortResults(List<ResolveInfo> results) { 7348 Collections.sort(results, mResolvePrioritySorter); 7349 } 7350 7351 @Override 7352 protected void dumpFilter(PrintWriter out, String prefix, 7353 PackageParser.ServiceIntentInfo filter) { 7354 out.print(prefix); out.print( 7355 Integer.toHexString(System.identityHashCode(filter.service))); 7356 out.print(' '); 7357 filter.service.printComponentShortName(out); 7358 out.print(" filter "); 7359 out.println(Integer.toHexString(System.identityHashCode(filter))); 7360 } 7361 7362// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7363// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7364// final List<ResolveInfo> retList = Lists.newArrayList(); 7365// while (i.hasNext()) { 7366// final ResolveInfo resolveInfo = (ResolveInfo) i; 7367// if (isEnabledLP(resolveInfo.serviceInfo)) { 7368// retList.add(resolveInfo); 7369// } 7370// } 7371// return retList; 7372// } 7373 7374 // Keys are String (activity class name), values are Activity. 7375 private final HashMap<ComponentName, PackageParser.Service> mServices 7376 = new HashMap<ComponentName, PackageParser.Service>(); 7377 private int mFlags; 7378 }; 7379 7380 private final class ProviderIntentResolver 7381 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7382 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7383 boolean defaultOnly, int userId) { 7384 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7385 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7386 } 7387 7388 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7389 int userId) { 7390 if (!sUserManager.exists(userId)) 7391 return null; 7392 mFlags = flags; 7393 return super.queryIntent(intent, resolvedType, 7394 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7395 } 7396 7397 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7398 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7399 if (!sUserManager.exists(userId)) 7400 return null; 7401 if (packageProviders == null) { 7402 return null; 7403 } 7404 mFlags = flags; 7405 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7406 final int N = packageProviders.size(); 7407 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7408 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7409 7410 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7411 for (int i = 0; i < N; ++i) { 7412 intentFilters = packageProviders.get(i).intents; 7413 if (intentFilters != null && intentFilters.size() > 0) { 7414 PackageParser.ProviderIntentInfo[] array = 7415 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7416 intentFilters.toArray(array); 7417 listCut.add(array); 7418 } 7419 } 7420 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7421 } 7422 7423 public final void addProvider(PackageParser.Provider p) { 7424 if (mProviders.containsKey(p.getComponentName())) { 7425 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7426 return; 7427 } 7428 7429 mProviders.put(p.getComponentName(), p); 7430 if (DEBUG_SHOW_INFO) { 7431 Log.v(TAG, " " 7432 + (p.info.nonLocalizedLabel != null 7433 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7434 Log.v(TAG, " Class=" + p.info.name); 7435 } 7436 final int NI = p.intents.size(); 7437 int j; 7438 for (j = 0; j < NI; j++) { 7439 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7440 if (DEBUG_SHOW_INFO) { 7441 Log.v(TAG, " IntentFilter:"); 7442 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7443 } 7444 if (!intent.debugCheck()) { 7445 Log.w(TAG, "==> For Provider " + p.info.name); 7446 } 7447 addFilter(intent); 7448 } 7449 } 7450 7451 public final void removeProvider(PackageParser.Provider p) { 7452 mProviders.remove(p.getComponentName()); 7453 if (DEBUG_SHOW_INFO) { 7454 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7455 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7456 Log.v(TAG, " Class=" + p.info.name); 7457 } 7458 final int NI = p.intents.size(); 7459 int j; 7460 for (j = 0; j < NI; j++) { 7461 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7462 if (DEBUG_SHOW_INFO) { 7463 Log.v(TAG, " IntentFilter:"); 7464 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7465 } 7466 removeFilter(intent); 7467 } 7468 } 7469 7470 @Override 7471 protected boolean allowFilterResult( 7472 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7473 ProviderInfo filterPi = filter.provider.info; 7474 for (int i = dest.size() - 1; i >= 0; i--) { 7475 ProviderInfo destPi = dest.get(i).providerInfo; 7476 if (destPi.name == filterPi.name 7477 && destPi.packageName == filterPi.packageName) { 7478 return false; 7479 } 7480 } 7481 return true; 7482 } 7483 7484 @Override 7485 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7486 return new PackageParser.ProviderIntentInfo[size]; 7487 } 7488 7489 @Override 7490 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7491 if (!sUserManager.exists(userId)) 7492 return true; 7493 PackageParser.Package p = filter.provider.owner; 7494 if (p != null) { 7495 PackageSetting ps = (PackageSetting) p.mExtras; 7496 if (ps != null) { 7497 // System apps are never considered stopped for purposes of 7498 // filtering, because there may be no way for the user to 7499 // actually re-launch them. 7500 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7501 && ps.getStopped(userId); 7502 } 7503 } 7504 return false; 7505 } 7506 7507 @Override 7508 protected boolean isPackageForFilter(String packageName, 7509 PackageParser.ProviderIntentInfo info) { 7510 return packageName.equals(info.provider.owner.packageName); 7511 } 7512 7513 @Override 7514 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7515 int match, int userId) { 7516 if (!sUserManager.exists(userId)) 7517 return null; 7518 final PackageParser.ProviderIntentInfo info = filter; 7519 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7520 return null; 7521 } 7522 final PackageParser.Provider provider = info.provider; 7523 if (mSafeMode && (provider.info.applicationInfo.flags 7524 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7525 return null; 7526 } 7527 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7528 if (ps == null) { 7529 return null; 7530 } 7531 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7532 ps.readUserState(userId), userId); 7533 if (pi == null) { 7534 return null; 7535 } 7536 final ResolveInfo res = new ResolveInfo(); 7537 res.providerInfo = pi; 7538 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7539 res.filter = filter; 7540 } 7541 res.priority = info.getPriority(); 7542 res.preferredOrder = provider.owner.mPreferredOrder; 7543 res.match = match; 7544 res.isDefault = info.hasDefault; 7545 res.labelRes = info.labelRes; 7546 res.nonLocalizedLabel = info.nonLocalizedLabel; 7547 res.icon = info.icon; 7548 res.system = isSystemApp(res.providerInfo.applicationInfo); 7549 return res; 7550 } 7551 7552 @Override 7553 protected void sortResults(List<ResolveInfo> results) { 7554 Collections.sort(results, mResolvePrioritySorter); 7555 } 7556 7557 @Override 7558 protected void dumpFilter(PrintWriter out, String prefix, 7559 PackageParser.ProviderIntentInfo filter) { 7560 out.print(prefix); 7561 out.print( 7562 Integer.toHexString(System.identityHashCode(filter.provider))); 7563 out.print(' '); 7564 filter.provider.printComponentShortName(out); 7565 out.print(" filter "); 7566 out.println(Integer.toHexString(System.identityHashCode(filter))); 7567 } 7568 7569 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7570 = new HashMap<ComponentName, PackageParser.Provider>(); 7571 private int mFlags; 7572 }; 7573 7574 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7575 new Comparator<ResolveInfo>() { 7576 public int compare(ResolveInfo r1, ResolveInfo r2) { 7577 int v1 = r1.priority; 7578 int v2 = r2.priority; 7579 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7580 if (v1 != v2) { 7581 return (v1 > v2) ? -1 : 1; 7582 } 7583 v1 = r1.preferredOrder; 7584 v2 = r2.preferredOrder; 7585 if (v1 != v2) { 7586 return (v1 > v2) ? -1 : 1; 7587 } 7588 if (r1.isDefault != r2.isDefault) { 7589 return r1.isDefault ? -1 : 1; 7590 } 7591 v1 = r1.match; 7592 v2 = r2.match; 7593 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7594 if (v1 != v2) { 7595 return (v1 > v2) ? -1 : 1; 7596 } 7597 if (r1.system != r2.system) { 7598 return r1.system ? -1 : 1; 7599 } 7600 return 0; 7601 } 7602 }; 7603 7604 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7605 new Comparator<ProviderInfo>() { 7606 public int compare(ProviderInfo p1, ProviderInfo p2) { 7607 final int v1 = p1.initOrder; 7608 final int v2 = p2.initOrder; 7609 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7610 } 7611 }; 7612 7613 static final void sendPackageBroadcast(String action, String pkg, 7614 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7615 int[] userIds) { 7616 IActivityManager am = ActivityManagerNative.getDefault(); 7617 if (am != null) { 7618 try { 7619 if (userIds == null) { 7620 userIds = am.getRunningUserIds(); 7621 } 7622 for (int id : userIds) { 7623 final Intent intent = new Intent(action, 7624 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7625 if (extras != null) { 7626 intent.putExtras(extras); 7627 } 7628 if (targetPkg != null) { 7629 intent.setPackage(targetPkg); 7630 } 7631 // Modify the UID when posting to other users 7632 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7633 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7634 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7635 intent.putExtra(Intent.EXTRA_UID, uid); 7636 } 7637 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7638 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7639 if (DEBUG_BROADCASTS) { 7640 RuntimeException here = new RuntimeException("here"); 7641 here.fillInStackTrace(); 7642 Slog.d(TAG, "Sending to user " + id + ": " 7643 + intent.toShortString(false, true, false, false) 7644 + " " + intent.getExtras(), here); 7645 } 7646 am.broadcastIntent(null, intent, null, finishedReceiver, 7647 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7648 finishedReceiver != null, false, id); 7649 } 7650 } catch (RemoteException ex) { 7651 } 7652 } 7653 } 7654 7655 /** 7656 * Check if the external storage media is available. This is true if there 7657 * is a mounted external storage medium or if the external storage is 7658 * emulated. 7659 */ 7660 private boolean isExternalMediaAvailable() { 7661 return mMediaMounted || Environment.isExternalStorageEmulated(); 7662 } 7663 7664 @Override 7665 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7666 // writer 7667 synchronized (mPackages) { 7668 if (!isExternalMediaAvailable()) { 7669 // If the external storage is no longer mounted at this point, 7670 // the caller may not have been able to delete all of this 7671 // packages files and can not delete any more. Bail. 7672 return null; 7673 } 7674 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7675 if (lastPackage != null) { 7676 pkgs.remove(lastPackage); 7677 } 7678 if (pkgs.size() > 0) { 7679 return pkgs.get(0); 7680 } 7681 } 7682 return null; 7683 } 7684 7685 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7686 if (false) { 7687 RuntimeException here = new RuntimeException("here"); 7688 here.fillInStackTrace(); 7689 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7690 + " andCode=" + andCode, here); 7691 } 7692 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7693 userId, andCode ? 1 : 0, packageName)); 7694 } 7695 7696 void startCleaningPackages() { 7697 // reader 7698 synchronized (mPackages) { 7699 if (!isExternalMediaAvailable()) { 7700 return; 7701 } 7702 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7703 return; 7704 } 7705 } 7706 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7707 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7708 IActivityManager am = ActivityManagerNative.getDefault(); 7709 if (am != null) { 7710 try { 7711 am.startService(null, intent, null, UserHandle.USER_OWNER); 7712 } catch (RemoteException e) { 7713 } 7714 } 7715 } 7716 7717 @Override 7718 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7719 int installFlags, String installerPackageName, VerificationParams verificationParams, 7720 String packageAbiOverride) { 7721 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7722 null); 7723 7724 final File originFile = new File(originPath); 7725 final int uid = Binder.getCallingUid(); 7726 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7727 try { 7728 if (observer != null) { 7729 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7730 } 7731 } catch (RemoteException re) { 7732 } 7733 return; 7734 } 7735 7736 UserHandle user; 7737 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7738 user = UserHandle.ALL; 7739 } else { 7740 user = new UserHandle(UserHandle.getUserId(uid)); 7741 } 7742 7743 final int filteredInstallFlags; 7744 if (uid == Process.SHELL_UID || uid == 0) { 7745 if (DEBUG_INSTALL) { 7746 Slog.v(TAG, "Install from ADB"); 7747 } 7748 filteredInstallFlags = installFlags | PackageManager.INSTALL_FROM_ADB; 7749 } else { 7750 filteredInstallFlags = installFlags & ~PackageManager.INSTALL_FROM_ADB; 7751 } 7752 7753 verificationParams.setInstallerUid(uid); 7754 7755 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7756 7757 final Message msg = mHandler.obtainMessage(INIT_COPY); 7758 msg.obj = new InstallParams(origin, observer, filteredInstallFlags, 7759 installerPackageName, verificationParams, user, packageAbiOverride); 7760 mHandler.sendMessage(msg); 7761 } 7762 7763 void installStage(String packageName, File stagedDir, String stagedCid, 7764 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7765 String installerPackageName, int installerUid, UserHandle user) { 7766 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7767 params.referrerUri, installerUid, null); 7768 7769 final OriginInfo origin; 7770 if (stagedDir != null) { 7771 origin = OriginInfo.fromStagedFile(stagedDir); 7772 } else { 7773 origin = OriginInfo.fromStagedContainer(stagedCid); 7774 } 7775 7776 final Message msg = mHandler.obtainMessage(INIT_COPY); 7777 msg.obj = new InstallParams(origin, observer, params.installFlags, 7778 installerPackageName, verifParams, user, params.abiOverride); 7779 mHandler.sendMessage(msg); 7780 } 7781 7782 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7783 Bundle extras = new Bundle(1); 7784 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7785 7786 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7787 packageName, extras, null, null, new int[] {userId}); 7788 try { 7789 IActivityManager am = ActivityManagerNative.getDefault(); 7790 final boolean isSystem = 7791 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7792 if (isSystem && am.isUserRunning(userId, false)) { 7793 // The just-installed/enabled app is bundled on the system, so presumed 7794 // to be able to run automatically without needing an explicit launch. 7795 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7796 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7797 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7798 .setPackage(packageName); 7799 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7800 android.app.AppOpsManager.OP_NONE, false, false, userId); 7801 } 7802 } catch (RemoteException e) { 7803 // shouldn't happen 7804 Slog.w(TAG, "Unable to bootstrap installed package", e); 7805 } 7806 } 7807 7808 @Override 7809 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7810 int userId) { 7811 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7812 PackageSetting pkgSetting; 7813 final int uid = Binder.getCallingUid(); 7814 if (UserHandle.getUserId(uid) != userId) { 7815 mContext.enforceCallingOrSelfPermission( 7816 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7817 "setApplicationHiddenSetting for user " + userId); 7818 } 7819 7820 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7821 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7822 return false; 7823 } 7824 7825 long callingId = Binder.clearCallingIdentity(); 7826 try { 7827 boolean sendAdded = false; 7828 boolean sendRemoved = false; 7829 // writer 7830 synchronized (mPackages) { 7831 pkgSetting = mSettings.mPackages.get(packageName); 7832 if (pkgSetting == null) { 7833 return false; 7834 } 7835 if (pkgSetting.getHidden(userId) != hidden) { 7836 pkgSetting.setHidden(hidden, userId); 7837 mSettings.writePackageRestrictionsLPr(userId); 7838 if (hidden) { 7839 sendRemoved = true; 7840 } else { 7841 sendAdded = true; 7842 } 7843 } 7844 } 7845 if (sendAdded) { 7846 sendPackageAddedForUser(packageName, pkgSetting, userId); 7847 return true; 7848 } 7849 if (sendRemoved) { 7850 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7851 "hiding pkg"); 7852 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7853 } 7854 } finally { 7855 Binder.restoreCallingIdentity(callingId); 7856 } 7857 return false; 7858 } 7859 7860 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7861 int userId) { 7862 final PackageRemovedInfo info = new PackageRemovedInfo(); 7863 info.removedPackage = packageName; 7864 info.removedUsers = new int[] {userId}; 7865 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7866 info.sendBroadcast(false, false, false); 7867 } 7868 7869 /** 7870 * Returns true if application is not found or there was an error. Otherwise it returns 7871 * the hidden state of the package for the given user. 7872 */ 7873 @Override 7874 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7875 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7876 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7877 "getApplicationHidden for user " + userId); 7878 PackageSetting pkgSetting; 7879 long callingId = Binder.clearCallingIdentity(); 7880 try { 7881 // writer 7882 synchronized (mPackages) { 7883 pkgSetting = mSettings.mPackages.get(packageName); 7884 if (pkgSetting == null) { 7885 return true; 7886 } 7887 return pkgSetting.getHidden(userId); 7888 } 7889 } finally { 7890 Binder.restoreCallingIdentity(callingId); 7891 } 7892 } 7893 7894 /** 7895 * @hide 7896 */ 7897 @Override 7898 public int installExistingPackageAsUser(String packageName, int userId) { 7899 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7900 null); 7901 PackageSetting pkgSetting; 7902 final int uid = Binder.getCallingUid(); 7903 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7904 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7905 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7906 } 7907 7908 long callingId = Binder.clearCallingIdentity(); 7909 try { 7910 boolean sendAdded = false; 7911 Bundle extras = new Bundle(1); 7912 7913 // writer 7914 synchronized (mPackages) { 7915 pkgSetting = mSettings.mPackages.get(packageName); 7916 if (pkgSetting == null) { 7917 return PackageManager.INSTALL_FAILED_INVALID_URI; 7918 } 7919 if (!pkgSetting.getInstalled(userId)) { 7920 pkgSetting.setInstalled(true, userId); 7921 pkgSetting.setHidden(false, userId); 7922 mSettings.writePackageRestrictionsLPr(userId); 7923 sendAdded = true; 7924 } 7925 } 7926 7927 if (sendAdded) { 7928 sendPackageAddedForUser(packageName, pkgSetting, userId); 7929 } 7930 } finally { 7931 Binder.restoreCallingIdentity(callingId); 7932 } 7933 7934 return PackageManager.INSTALL_SUCCEEDED; 7935 } 7936 7937 boolean isUserRestricted(int userId, String restrictionKey) { 7938 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7939 if (restrictions.getBoolean(restrictionKey, false)) { 7940 Log.w(TAG, "User is restricted: " + restrictionKey); 7941 return true; 7942 } 7943 return false; 7944 } 7945 7946 @Override 7947 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7948 mContext.enforceCallingOrSelfPermission( 7949 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7950 "Only package verification agents can verify applications"); 7951 7952 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7953 final PackageVerificationResponse response = new PackageVerificationResponse( 7954 verificationCode, Binder.getCallingUid()); 7955 msg.arg1 = id; 7956 msg.obj = response; 7957 mHandler.sendMessage(msg); 7958 } 7959 7960 @Override 7961 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7962 long millisecondsToDelay) { 7963 mContext.enforceCallingOrSelfPermission( 7964 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7965 "Only package verification agents can extend verification timeouts"); 7966 7967 final PackageVerificationState state = mPendingVerification.get(id); 7968 final PackageVerificationResponse response = new PackageVerificationResponse( 7969 verificationCodeAtTimeout, Binder.getCallingUid()); 7970 7971 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7972 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7973 } 7974 if (millisecondsToDelay < 0) { 7975 millisecondsToDelay = 0; 7976 } 7977 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7978 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7979 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7980 } 7981 7982 if ((state != null) && !state.timeoutExtended()) { 7983 state.extendTimeout(); 7984 7985 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7986 msg.arg1 = id; 7987 msg.obj = response; 7988 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7989 } 7990 } 7991 7992 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7993 int verificationCode, UserHandle user) { 7994 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7995 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7996 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7997 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7998 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7999 8000 mContext.sendBroadcastAsUser(intent, user, 8001 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8002 } 8003 8004 private ComponentName matchComponentForVerifier(String packageName, 8005 List<ResolveInfo> receivers) { 8006 ActivityInfo targetReceiver = null; 8007 8008 final int NR = receivers.size(); 8009 for (int i = 0; i < NR; i++) { 8010 final ResolveInfo info = receivers.get(i); 8011 if (info.activityInfo == null) { 8012 continue; 8013 } 8014 8015 if (packageName.equals(info.activityInfo.packageName)) { 8016 targetReceiver = info.activityInfo; 8017 break; 8018 } 8019 } 8020 8021 if (targetReceiver == null) { 8022 return null; 8023 } 8024 8025 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8026 } 8027 8028 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8029 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8030 if (pkgInfo.verifiers.length == 0) { 8031 return null; 8032 } 8033 8034 final int N = pkgInfo.verifiers.length; 8035 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8036 for (int i = 0; i < N; i++) { 8037 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8038 8039 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8040 receivers); 8041 if (comp == null) { 8042 continue; 8043 } 8044 8045 final int verifierUid = getUidForVerifier(verifierInfo); 8046 if (verifierUid == -1) { 8047 continue; 8048 } 8049 8050 if (DEBUG_VERIFY) { 8051 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8052 + " with the correct signature"); 8053 } 8054 sufficientVerifiers.add(comp); 8055 verificationState.addSufficientVerifier(verifierUid); 8056 } 8057 8058 return sufficientVerifiers; 8059 } 8060 8061 private int getUidForVerifier(VerifierInfo verifierInfo) { 8062 synchronized (mPackages) { 8063 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8064 if (pkg == null) { 8065 return -1; 8066 } else if (pkg.mSignatures.length != 1) { 8067 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8068 + " has more than one signature; ignoring"); 8069 return -1; 8070 } 8071 8072 /* 8073 * If the public key of the package's signature does not match 8074 * our expected public key, then this is a different package and 8075 * we should skip. 8076 */ 8077 8078 final byte[] expectedPublicKey; 8079 try { 8080 final Signature verifierSig = pkg.mSignatures[0]; 8081 final PublicKey publicKey = verifierSig.getPublicKey(); 8082 expectedPublicKey = publicKey.getEncoded(); 8083 } catch (CertificateException e) { 8084 return -1; 8085 } 8086 8087 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8088 8089 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8090 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8091 + " does not have the expected public key; ignoring"); 8092 return -1; 8093 } 8094 8095 return pkg.applicationInfo.uid; 8096 } 8097 } 8098 8099 @Override 8100 public void finishPackageInstall(int token) { 8101 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8102 8103 if (DEBUG_INSTALL) { 8104 Slog.v(TAG, "BM finishing package install for " + token); 8105 } 8106 8107 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8108 mHandler.sendMessage(msg); 8109 } 8110 8111 /** 8112 * Get the verification agent timeout. 8113 * 8114 * @return verification timeout in milliseconds 8115 */ 8116 private long getVerificationTimeout() { 8117 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8118 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8119 DEFAULT_VERIFICATION_TIMEOUT); 8120 } 8121 8122 /** 8123 * Get the default verification agent response code. 8124 * 8125 * @return default verification response code 8126 */ 8127 private int getDefaultVerificationResponse() { 8128 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8129 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8130 DEFAULT_VERIFICATION_RESPONSE); 8131 } 8132 8133 /** 8134 * Check whether or not package verification has been enabled. 8135 * 8136 * @return true if verification should be performed 8137 */ 8138 private boolean isVerificationEnabled(int userId, int installFlags) { 8139 if (!DEFAULT_VERIFY_ENABLE) { 8140 return false; 8141 } 8142 8143 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8144 8145 // Check if installing from ADB 8146 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8147 // Do not run verification in a test harness environment 8148 if (ActivityManager.isRunningInTestHarness()) { 8149 return false; 8150 } 8151 if (ensureVerifyAppsEnabled) { 8152 return true; 8153 } 8154 // Check if the developer does not want package verification for ADB installs 8155 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8156 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8157 return false; 8158 } 8159 } 8160 8161 if (ensureVerifyAppsEnabled) { 8162 return true; 8163 } 8164 8165 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8166 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8167 } 8168 8169 /** 8170 * Get the "allow unknown sources" setting. 8171 * 8172 * @return the current "allow unknown sources" setting 8173 */ 8174 private int getUnknownSourcesSettings() { 8175 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8176 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8177 -1); 8178 } 8179 8180 @Override 8181 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8182 final int uid = Binder.getCallingUid(); 8183 // writer 8184 synchronized (mPackages) { 8185 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8186 if (targetPackageSetting == null) { 8187 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8188 } 8189 8190 PackageSetting installerPackageSetting; 8191 if (installerPackageName != null) { 8192 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8193 if (installerPackageSetting == null) { 8194 throw new IllegalArgumentException("Unknown installer package: " 8195 + installerPackageName); 8196 } 8197 } else { 8198 installerPackageSetting = null; 8199 } 8200 8201 Signature[] callerSignature; 8202 Object obj = mSettings.getUserIdLPr(uid); 8203 if (obj != null) { 8204 if (obj instanceof SharedUserSetting) { 8205 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8206 } else if (obj instanceof PackageSetting) { 8207 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8208 } else { 8209 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8210 } 8211 } else { 8212 throw new SecurityException("Unknown calling uid " + uid); 8213 } 8214 8215 // Verify: can't set installerPackageName to a package that is 8216 // not signed with the same cert as the caller. 8217 if (installerPackageSetting != null) { 8218 if (compareSignatures(callerSignature, 8219 installerPackageSetting.signatures.mSignatures) 8220 != PackageManager.SIGNATURE_MATCH) { 8221 throw new SecurityException( 8222 "Caller does not have same cert as new installer package " 8223 + installerPackageName); 8224 } 8225 } 8226 8227 // Verify: if target already has an installer package, it must 8228 // be signed with the same cert as the caller. 8229 if (targetPackageSetting.installerPackageName != null) { 8230 PackageSetting setting = mSettings.mPackages.get( 8231 targetPackageSetting.installerPackageName); 8232 // If the currently set package isn't valid, then it's always 8233 // okay to change it. 8234 if (setting != null) { 8235 if (compareSignatures(callerSignature, 8236 setting.signatures.mSignatures) 8237 != PackageManager.SIGNATURE_MATCH) { 8238 throw new SecurityException( 8239 "Caller does not have same cert as old installer package " 8240 + targetPackageSetting.installerPackageName); 8241 } 8242 } 8243 } 8244 8245 // Okay! 8246 targetPackageSetting.installerPackageName = installerPackageName; 8247 scheduleWriteSettingsLocked(); 8248 } 8249 } 8250 8251 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8252 // Queue up an async operation since the package installation may take a little while. 8253 mHandler.post(new Runnable() { 8254 public void run() { 8255 mHandler.removeCallbacks(this); 8256 // Result object to be returned 8257 PackageInstalledInfo res = new PackageInstalledInfo(); 8258 res.returnCode = currentStatus; 8259 res.uid = -1; 8260 res.pkg = null; 8261 res.removedInfo = new PackageRemovedInfo(); 8262 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8263 args.doPreInstall(res.returnCode); 8264 synchronized (mInstallLock) { 8265 installPackageLI(args, res); 8266 } 8267 args.doPostInstall(res.returnCode, res.uid); 8268 } 8269 8270 // A restore should be performed at this point if (a) the install 8271 // succeeded, (b) the operation is not an update, and (c) the new 8272 // package has not opted out of backup participation. 8273 final boolean update = res.removedInfo.removedPackage != null; 8274 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8275 boolean doRestore = !update 8276 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8277 8278 // Set up the post-install work request bookkeeping. This will be used 8279 // and cleaned up by the post-install event handling regardless of whether 8280 // there's a restore pass performed. Token values are >= 1. 8281 int token; 8282 if (mNextInstallToken < 0) mNextInstallToken = 1; 8283 token = mNextInstallToken++; 8284 8285 PostInstallData data = new PostInstallData(args, res); 8286 mRunningInstalls.put(token, data); 8287 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8288 8289 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8290 // Pass responsibility to the Backup Manager. It will perform a 8291 // restore if appropriate, then pass responsibility back to the 8292 // Package Manager to run the post-install observer callbacks 8293 // and broadcasts. 8294 IBackupManager bm = IBackupManager.Stub.asInterface( 8295 ServiceManager.getService(Context.BACKUP_SERVICE)); 8296 if (bm != null) { 8297 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8298 + " to BM for possible restore"); 8299 try { 8300 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8301 } catch (RemoteException e) { 8302 // can't happen; the backup manager is local 8303 } catch (Exception e) { 8304 Slog.e(TAG, "Exception trying to enqueue restore", e); 8305 doRestore = false; 8306 } 8307 } else { 8308 Slog.e(TAG, "Backup Manager not found!"); 8309 doRestore = false; 8310 } 8311 } 8312 8313 if (!doRestore) { 8314 // No restore possible, or the Backup Manager was mysteriously not 8315 // available -- just fire the post-install work request directly. 8316 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8317 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8318 mHandler.sendMessage(msg); 8319 } 8320 } 8321 }); 8322 } 8323 8324 private abstract class HandlerParams { 8325 private static final int MAX_RETRIES = 4; 8326 8327 /** 8328 * Number of times startCopy() has been attempted and had a non-fatal 8329 * error. 8330 */ 8331 private int mRetries = 0; 8332 8333 /** User handle for the user requesting the information or installation. */ 8334 private final UserHandle mUser; 8335 8336 HandlerParams(UserHandle user) { 8337 mUser = user; 8338 } 8339 8340 UserHandle getUser() { 8341 return mUser; 8342 } 8343 8344 final boolean startCopy() { 8345 boolean res; 8346 try { 8347 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8348 8349 if (++mRetries > MAX_RETRIES) { 8350 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8351 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8352 handleServiceError(); 8353 return false; 8354 } else { 8355 handleStartCopy(); 8356 res = true; 8357 } 8358 } catch (RemoteException e) { 8359 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8360 mHandler.sendEmptyMessage(MCS_RECONNECT); 8361 res = false; 8362 } 8363 handleReturnCode(); 8364 return res; 8365 } 8366 8367 final void serviceError() { 8368 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8369 handleServiceError(); 8370 handleReturnCode(); 8371 } 8372 8373 abstract void handleStartCopy() throws RemoteException; 8374 abstract void handleServiceError(); 8375 abstract void handleReturnCode(); 8376 } 8377 8378 class MeasureParams extends HandlerParams { 8379 private final PackageStats mStats; 8380 private boolean mSuccess; 8381 8382 private final IPackageStatsObserver mObserver; 8383 8384 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8385 super(new UserHandle(stats.userHandle)); 8386 mObserver = observer; 8387 mStats = stats; 8388 } 8389 8390 @Override 8391 public String toString() { 8392 return "MeasureParams{" 8393 + Integer.toHexString(System.identityHashCode(this)) 8394 + " " + mStats.packageName + "}"; 8395 } 8396 8397 @Override 8398 void handleStartCopy() throws RemoteException { 8399 synchronized (mInstallLock) { 8400 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8401 } 8402 8403 if (mSuccess) { 8404 final boolean mounted; 8405 if (Environment.isExternalStorageEmulated()) { 8406 mounted = true; 8407 } else { 8408 final String status = Environment.getExternalStorageState(); 8409 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8410 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8411 } 8412 8413 if (mounted) { 8414 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8415 8416 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8417 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8418 8419 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8420 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8421 8422 // Always subtract cache size, since it's a subdirectory 8423 mStats.externalDataSize -= mStats.externalCacheSize; 8424 8425 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8426 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8427 8428 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8429 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8430 } 8431 } 8432 } 8433 8434 @Override 8435 void handleReturnCode() { 8436 if (mObserver != null) { 8437 try { 8438 mObserver.onGetStatsCompleted(mStats, mSuccess); 8439 } catch (RemoteException e) { 8440 Slog.i(TAG, "Observer no longer exists."); 8441 } 8442 } 8443 } 8444 8445 @Override 8446 void handleServiceError() { 8447 Slog.e(TAG, "Could not measure application " + mStats.packageName 8448 + " external storage"); 8449 } 8450 } 8451 8452 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8453 throws RemoteException { 8454 long result = 0; 8455 for (File path : paths) { 8456 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8457 } 8458 return result; 8459 } 8460 8461 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8462 for (File path : paths) { 8463 try { 8464 mcs.clearDirectory(path.getAbsolutePath()); 8465 } catch (RemoteException e) { 8466 } 8467 } 8468 } 8469 8470 static class OriginInfo { 8471 /** 8472 * Location where install is coming from, before it has been 8473 * copied/renamed into place. This could be a single monolithic APK 8474 * file, or a cluster directory. This location may be untrusted. 8475 */ 8476 final File file; 8477 final String cid; 8478 8479 /** 8480 * Flag indicating that {@link #file} or {@link #cid} has already been 8481 * staged, meaning downstream users don't need to defensively copy the 8482 * contents. 8483 */ 8484 final boolean staged; 8485 8486 /** 8487 * Flag indicating that {@link #file} or {@link #cid} is an already 8488 * installed app that is being moved. 8489 */ 8490 final boolean existing; 8491 8492 final String resolvedPath; 8493 final File resolvedFile; 8494 8495 static OriginInfo fromNothing() { 8496 return new OriginInfo(null, null, false, false); 8497 } 8498 8499 static OriginInfo fromUntrustedFile(File file) { 8500 return new OriginInfo(file, null, false, false); 8501 } 8502 8503 static OriginInfo fromExistingFile(File file) { 8504 return new OriginInfo(file, null, false, true); 8505 } 8506 8507 static OriginInfo fromStagedFile(File file) { 8508 return new OriginInfo(file, null, true, false); 8509 } 8510 8511 static OriginInfo fromStagedContainer(String cid) { 8512 return new OriginInfo(null, cid, true, false); 8513 } 8514 8515 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8516 this.file = file; 8517 this.cid = cid; 8518 this.staged = staged; 8519 this.existing = existing; 8520 8521 if (cid != null) { 8522 resolvedPath = PackageHelper.getSdDir(cid); 8523 resolvedFile = new File(resolvedPath); 8524 } else if (file != null) { 8525 resolvedPath = file.getAbsolutePath(); 8526 resolvedFile = file; 8527 } else { 8528 resolvedPath = null; 8529 resolvedFile = null; 8530 } 8531 } 8532 } 8533 8534 class InstallParams extends HandlerParams { 8535 final OriginInfo origin; 8536 final IPackageInstallObserver2 observer; 8537 int installFlags; 8538 final String installerPackageName; 8539 final VerificationParams verificationParams; 8540 private InstallArgs mArgs; 8541 private int mRet; 8542 final String packageAbiOverride; 8543 8544 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8545 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8546 String packageAbiOverride) { 8547 super(user); 8548 this.origin = origin; 8549 this.observer = observer; 8550 this.installFlags = installFlags; 8551 this.installerPackageName = installerPackageName; 8552 this.verificationParams = verificationParams; 8553 this.packageAbiOverride = packageAbiOverride; 8554 } 8555 8556 @Override 8557 public String toString() { 8558 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8559 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8560 } 8561 8562 public ManifestDigest getManifestDigest() { 8563 if (verificationParams == null) { 8564 return null; 8565 } 8566 return verificationParams.getManifestDigest(); 8567 } 8568 8569 private int installLocationPolicy(PackageInfoLite pkgLite) { 8570 String packageName = pkgLite.packageName; 8571 int installLocation = pkgLite.installLocation; 8572 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8573 // reader 8574 synchronized (mPackages) { 8575 PackageParser.Package pkg = mPackages.get(packageName); 8576 if (pkg != null) { 8577 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8578 // Check for downgrading. 8579 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8580 if (pkgLite.versionCode < pkg.mVersionCode) { 8581 Slog.w(TAG, "Can't install update of " + packageName 8582 + " update version " + pkgLite.versionCode 8583 + " is older than installed version " 8584 + pkg.mVersionCode); 8585 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8586 } 8587 } 8588 // Check for updated system application. 8589 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8590 if (onSd) { 8591 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8592 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8593 } 8594 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8595 } else { 8596 if (onSd) { 8597 // Install flag overrides everything. 8598 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8599 } 8600 // If current upgrade specifies particular preference 8601 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8602 // Application explicitly specified internal. 8603 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8604 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8605 // App explictly prefers external. Let policy decide 8606 } else { 8607 // Prefer previous location 8608 if (isExternal(pkg)) { 8609 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8610 } 8611 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8612 } 8613 } 8614 } else { 8615 // Invalid install. Return error code 8616 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8617 } 8618 } 8619 } 8620 // All the special cases have been taken care of. 8621 // Return result based on recommended install location. 8622 if (onSd) { 8623 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8624 } 8625 return pkgLite.recommendedInstallLocation; 8626 } 8627 8628 /* 8629 * Invoke remote method to get package information and install 8630 * location values. Override install location based on default 8631 * policy if needed and then create install arguments based 8632 * on the install location. 8633 */ 8634 public void handleStartCopy() throws RemoteException { 8635 int ret = PackageManager.INSTALL_SUCCEEDED; 8636 8637 // If we're already staged, we've firmly committed to an install location 8638 if (origin.staged) { 8639 if (origin.file != null) { 8640 installFlags |= PackageManager.INSTALL_INTERNAL; 8641 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8642 } else if (origin.cid != null) { 8643 installFlags |= PackageManager.INSTALL_EXTERNAL; 8644 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8645 } else { 8646 throw new IllegalStateException("Invalid stage location"); 8647 } 8648 } 8649 8650 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8651 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8652 8653 PackageInfoLite pkgLite = null; 8654 8655 if (onInt && onSd) { 8656 // Check if both bits are set. 8657 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8658 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8659 } else { 8660 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8661 packageAbiOverride); 8662 8663 /* 8664 * If we have too little free space, try to free cache 8665 * before giving up. 8666 */ 8667 if (!origin.staged && pkgLite.recommendedInstallLocation 8668 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8669 // TODO: focus freeing disk space on the target device 8670 final StorageManager storage = StorageManager.from(mContext); 8671 final long lowThreshold = storage.getStorageLowBytes( 8672 Environment.getDataDirectory()); 8673 8674 final long sizeBytes = mContainerService.calculateInstalledSize( 8675 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8676 8677 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8678 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8679 installFlags, packageAbiOverride); 8680 } 8681 8682 /* 8683 * The cache free must have deleted the file we 8684 * downloaded to install. 8685 * 8686 * TODO: fix the "freeCache" call to not delete 8687 * the file we care about. 8688 */ 8689 if (pkgLite.recommendedInstallLocation 8690 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8691 pkgLite.recommendedInstallLocation 8692 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8693 } 8694 } 8695 } 8696 8697 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8698 int loc = pkgLite.recommendedInstallLocation; 8699 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8700 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8701 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8702 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8703 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8704 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8705 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8706 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8707 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8708 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8709 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8710 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8711 } else { 8712 // Override with defaults if needed. 8713 loc = installLocationPolicy(pkgLite); 8714 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8715 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8716 } else if (!onSd && !onInt) { 8717 // Override install location with flags 8718 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8719 // Set the flag to install on external media. 8720 installFlags |= PackageManager.INSTALL_EXTERNAL; 8721 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8722 } else { 8723 // Make sure the flag for installing on external 8724 // media is unset 8725 installFlags |= PackageManager.INSTALL_INTERNAL; 8726 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8727 } 8728 } 8729 } 8730 } 8731 8732 final InstallArgs args = createInstallArgs(this); 8733 mArgs = args; 8734 8735 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8736 /* 8737 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8738 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8739 */ 8740 int userIdentifier = getUser().getIdentifier(); 8741 if (userIdentifier == UserHandle.USER_ALL 8742 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8743 userIdentifier = UserHandle.USER_OWNER; 8744 } 8745 8746 /* 8747 * Determine if we have any installed package verifiers. If we 8748 * do, then we'll defer to them to verify the packages. 8749 */ 8750 final int requiredUid = mRequiredVerifierPackage == null ? -1 8751 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8752 if (!origin.existing && requiredUid != -1 8753 && isVerificationEnabled(userIdentifier, installFlags)) { 8754 final Intent verification = new Intent( 8755 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8756 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8757 PACKAGE_MIME_TYPE); 8758 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8759 8760 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8761 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8762 0 /* TODO: Which userId? */); 8763 8764 if (DEBUG_VERIFY) { 8765 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8766 + verification.toString() + " with " + pkgLite.verifiers.length 8767 + " optional verifiers"); 8768 } 8769 8770 final int verificationId = mPendingVerificationToken++; 8771 8772 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8773 8774 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8775 installerPackageName); 8776 8777 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8778 installFlags); 8779 8780 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8781 pkgLite.packageName); 8782 8783 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8784 pkgLite.versionCode); 8785 8786 if (verificationParams != null) { 8787 if (verificationParams.getVerificationURI() != null) { 8788 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8789 verificationParams.getVerificationURI()); 8790 } 8791 if (verificationParams.getOriginatingURI() != null) { 8792 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8793 verificationParams.getOriginatingURI()); 8794 } 8795 if (verificationParams.getReferrer() != null) { 8796 verification.putExtra(Intent.EXTRA_REFERRER, 8797 verificationParams.getReferrer()); 8798 } 8799 if (verificationParams.getOriginatingUid() >= 0) { 8800 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8801 verificationParams.getOriginatingUid()); 8802 } 8803 if (verificationParams.getInstallerUid() >= 0) { 8804 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8805 verificationParams.getInstallerUid()); 8806 } 8807 } 8808 8809 final PackageVerificationState verificationState = new PackageVerificationState( 8810 requiredUid, args); 8811 8812 mPendingVerification.append(verificationId, verificationState); 8813 8814 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8815 receivers, verificationState); 8816 8817 /* 8818 * If any sufficient verifiers were listed in the package 8819 * manifest, attempt to ask them. 8820 */ 8821 if (sufficientVerifiers != null) { 8822 final int N = sufficientVerifiers.size(); 8823 if (N == 0) { 8824 Slog.i(TAG, "Additional verifiers required, but none installed."); 8825 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8826 } else { 8827 for (int i = 0; i < N; i++) { 8828 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8829 8830 final Intent sufficientIntent = new Intent(verification); 8831 sufficientIntent.setComponent(verifierComponent); 8832 8833 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8834 } 8835 } 8836 } 8837 8838 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8839 mRequiredVerifierPackage, receivers); 8840 if (ret == PackageManager.INSTALL_SUCCEEDED 8841 && mRequiredVerifierPackage != null) { 8842 /* 8843 * Send the intent to the required verification agent, 8844 * but only start the verification timeout after the 8845 * target BroadcastReceivers have run. 8846 */ 8847 verification.setComponent(requiredVerifierComponent); 8848 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8849 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8850 new BroadcastReceiver() { 8851 @Override 8852 public void onReceive(Context context, Intent intent) { 8853 final Message msg = mHandler 8854 .obtainMessage(CHECK_PENDING_VERIFICATION); 8855 msg.arg1 = verificationId; 8856 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8857 } 8858 }, null, 0, null, null); 8859 8860 /* 8861 * We don't want the copy to proceed until verification 8862 * succeeds, so null out this field. 8863 */ 8864 mArgs = null; 8865 } 8866 } else { 8867 /* 8868 * No package verification is enabled, so immediately start 8869 * the remote call to initiate copy using temporary file. 8870 */ 8871 ret = args.copyApk(mContainerService, true); 8872 } 8873 } 8874 8875 mRet = ret; 8876 } 8877 8878 @Override 8879 void handleReturnCode() { 8880 // If mArgs is null, then MCS couldn't be reached. When it 8881 // reconnects, it will try again to install. At that point, this 8882 // will succeed. 8883 if (mArgs != null) { 8884 processPendingInstall(mArgs, mRet); 8885 } 8886 } 8887 8888 @Override 8889 void handleServiceError() { 8890 mArgs = createInstallArgs(this); 8891 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8892 } 8893 8894 public boolean isForwardLocked() { 8895 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8896 } 8897 } 8898 8899 /** 8900 * Used during creation of InstallArgs 8901 * 8902 * @param installFlags package installation flags 8903 * @return true if should be installed on external storage 8904 */ 8905 private static boolean installOnSd(int installFlags) { 8906 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 8907 return false; 8908 } 8909 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 8910 return true; 8911 } 8912 return false; 8913 } 8914 8915 /** 8916 * Used during creation of InstallArgs 8917 * 8918 * @param installFlags package installation flags 8919 * @return true if should be installed as forward locked 8920 */ 8921 private static boolean installForwardLocked(int installFlags) { 8922 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8923 } 8924 8925 private InstallArgs createInstallArgs(InstallParams params) { 8926 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 8927 return new AsecInstallArgs(params); 8928 } else { 8929 return new FileInstallArgs(params); 8930 } 8931 } 8932 8933 /** 8934 * Create args that describe an existing installed package. Typically used 8935 * when cleaning up old installs, or used as a move source. 8936 */ 8937 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 8938 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 8939 final boolean isInAsec; 8940 if (installOnSd(installFlags)) { 8941 /* Apps on SD card are always in ASEC containers. */ 8942 isInAsec = true; 8943 } else if (installForwardLocked(installFlags) 8944 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8945 /* 8946 * Forward-locked apps are only in ASEC containers if they're the 8947 * new style 8948 */ 8949 isInAsec = true; 8950 } else { 8951 isInAsec = false; 8952 } 8953 8954 if (isInAsec) { 8955 return new AsecInstallArgs(codePath, instructionSets, 8956 installOnSd(installFlags), installForwardLocked(installFlags)); 8957 } else { 8958 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 8959 instructionSets); 8960 } 8961 } 8962 8963 static abstract class InstallArgs { 8964 /** @see InstallParams#origin */ 8965 final OriginInfo origin; 8966 8967 final IPackageInstallObserver2 observer; 8968 // Always refers to PackageManager flags only 8969 final int installFlags; 8970 final String installerPackageName; 8971 final ManifestDigest manifestDigest; 8972 final UserHandle user; 8973 final String abiOverride; 8974 8975 // The list of instruction sets supported by this app. This is currently 8976 // only used during the rmdex() phase to clean up resources. We can get rid of this 8977 // if we move dex files under the common app path. 8978 /* nullable */ String[] instructionSets; 8979 8980 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8981 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 8982 String[] instructionSets, String abiOverride) { 8983 this.origin = origin; 8984 this.installFlags = installFlags; 8985 this.observer = observer; 8986 this.installerPackageName = installerPackageName; 8987 this.manifestDigest = manifestDigest; 8988 this.user = user; 8989 this.instructionSets = instructionSets; 8990 this.abiOverride = abiOverride; 8991 } 8992 8993 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 8994 abstract int doPreInstall(int status); 8995 8996 /** 8997 * Rename package into final resting place. All paths on the given 8998 * scanned package should be updated to reflect the rename. 8999 */ 9000 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9001 abstract int doPostInstall(int status, int uid); 9002 9003 /** @see PackageSettingBase#codePathString */ 9004 abstract String getCodePath(); 9005 /** @see PackageSettingBase#resourcePathString */ 9006 abstract String getResourcePath(); 9007 abstract String getLegacyNativeLibraryPath(); 9008 9009 // Need installer lock especially for dex file removal. 9010 abstract void cleanUpResourcesLI(); 9011 abstract boolean doPostDeleteLI(boolean delete); 9012 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9013 9014 /** 9015 * Called before the source arguments are copied. This is used mostly 9016 * for MoveParams when it needs to read the source file to put it in the 9017 * destination. 9018 */ 9019 int doPreCopy() { 9020 return PackageManager.INSTALL_SUCCEEDED; 9021 } 9022 9023 /** 9024 * Called after the source arguments are copied. This is used mostly for 9025 * MoveParams when it needs to read the source file to put it in the 9026 * destination. 9027 * 9028 * @return 9029 */ 9030 int doPostCopy(int uid) { 9031 return PackageManager.INSTALL_SUCCEEDED; 9032 } 9033 9034 protected boolean isFwdLocked() { 9035 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9036 } 9037 9038 protected boolean isExternal() { 9039 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9040 } 9041 9042 UserHandle getUser() { 9043 return user; 9044 } 9045 } 9046 9047 /** 9048 * Logic to handle installation of non-ASEC applications, including copying 9049 * and renaming logic. 9050 */ 9051 class FileInstallArgs extends InstallArgs { 9052 private File codeFile; 9053 private File resourceFile; 9054 private File legacyNativeLibraryPath; 9055 9056 // Example topology: 9057 // /data/app/com.example/base.apk 9058 // /data/app/com.example/split_foo.apk 9059 // /data/app/com.example/lib/arm/libfoo.so 9060 // /data/app/com.example/lib/arm64/libfoo.so 9061 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9062 9063 /** New install */ 9064 FileInstallArgs(InstallParams params) { 9065 super(params.origin, params.observer, params.installFlags, 9066 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9067 null /* instruction sets */, params.packageAbiOverride); 9068 if (isFwdLocked()) { 9069 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9070 } 9071 } 9072 9073 /** Existing install */ 9074 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9075 String[] instructionSets) { 9076 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9077 this.codeFile = (codePath != null) ? new File(codePath) : null; 9078 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9079 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9080 new File(legacyNativeLibraryPath) : null; 9081 } 9082 9083 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9084 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9085 isFwdLocked(), abiOverride); 9086 9087 final StorageManager storage = StorageManager.from(mContext); 9088 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9089 } 9090 9091 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9092 if (origin.staged) { 9093 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9094 codeFile = origin.file; 9095 resourceFile = origin.file; 9096 return PackageManager.INSTALL_SUCCEEDED; 9097 } 9098 9099 try { 9100 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9101 codeFile = tempDir; 9102 resourceFile = tempDir; 9103 } catch (IOException e) { 9104 Slog.w(TAG, "Failed to create copy file: " + e); 9105 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9106 } 9107 9108 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9109 @Override 9110 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9111 if (!FileUtils.isValidExtFilename(name)) { 9112 throw new IllegalArgumentException("Invalid filename: " + name); 9113 } 9114 try { 9115 final File file = new File(codeFile, name); 9116 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9117 O_RDWR | O_CREAT, 0644); 9118 Os.chmod(file.getAbsolutePath(), 0644); 9119 return new ParcelFileDescriptor(fd); 9120 } catch (ErrnoException e) { 9121 throw new RemoteException("Failed to open: " + e.getMessage()); 9122 } 9123 } 9124 }; 9125 9126 int ret = PackageManager.INSTALL_SUCCEEDED; 9127 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9128 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9129 Slog.e(TAG, "Failed to copy package"); 9130 return ret; 9131 } 9132 9133 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9134 NativeLibraryHelper.Handle handle = null; 9135 try { 9136 handle = NativeLibraryHelper.Handle.create(codeFile); 9137 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9138 abiOverride); 9139 } catch (IOException e) { 9140 Slog.e(TAG, "Copying native libraries failed", e); 9141 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9142 } finally { 9143 IoUtils.closeQuietly(handle); 9144 } 9145 9146 return ret; 9147 } 9148 9149 int doPreInstall(int status) { 9150 if (status != PackageManager.INSTALL_SUCCEEDED) { 9151 cleanUp(); 9152 } 9153 return status; 9154 } 9155 9156 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9157 if (status != PackageManager.INSTALL_SUCCEEDED) { 9158 cleanUp(); 9159 return false; 9160 } else { 9161 final File beforeCodeFile = codeFile; 9162 final File afterCodeFile = getNextCodePath(pkg.packageName); 9163 9164 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9165 try { 9166 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9167 } catch (ErrnoException e) { 9168 Slog.d(TAG, "Failed to rename", e); 9169 return false; 9170 } 9171 9172 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9173 Slog.d(TAG, "Failed to restorecon"); 9174 return false; 9175 } 9176 9177 // Reflect the rename internally 9178 codeFile = afterCodeFile; 9179 resourceFile = afterCodeFile; 9180 9181 // Reflect the rename in scanned details 9182 pkg.codePath = afterCodeFile.getAbsolutePath(); 9183 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9184 pkg.baseCodePath); 9185 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9186 pkg.splitCodePaths); 9187 9188 // Reflect the rename in app info 9189 pkg.applicationInfo.setCodePath(pkg.codePath); 9190 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9191 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9192 pkg.applicationInfo.setResourcePath(pkg.codePath); 9193 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9194 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9195 9196 return true; 9197 } 9198 } 9199 9200 int doPostInstall(int status, int uid) { 9201 if (status != PackageManager.INSTALL_SUCCEEDED) { 9202 cleanUp(); 9203 } 9204 return status; 9205 } 9206 9207 @Override 9208 String getCodePath() { 9209 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9210 } 9211 9212 @Override 9213 String getResourcePath() { 9214 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9215 } 9216 9217 @Override 9218 String getLegacyNativeLibraryPath() { 9219 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9220 } 9221 9222 private boolean cleanUp() { 9223 if (codeFile == null || !codeFile.exists()) { 9224 return false; 9225 } 9226 9227 if (codeFile.isDirectory()) { 9228 FileUtils.deleteContents(codeFile); 9229 } 9230 codeFile.delete(); 9231 9232 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9233 resourceFile.delete(); 9234 } 9235 9236 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9237 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9238 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9239 } 9240 legacyNativeLibraryPath.delete(); 9241 } 9242 9243 return true; 9244 } 9245 9246 void cleanUpResourcesLI() { 9247 // Try enumerating all code paths before deleting 9248 List<String> allCodePaths = Collections.EMPTY_LIST; 9249 if (codeFile != null && codeFile.exists()) { 9250 try { 9251 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9252 allCodePaths = pkg.getAllCodePaths(); 9253 } catch (PackageParserException e) { 9254 // Ignored; we tried our best 9255 } 9256 } 9257 9258 cleanUp(); 9259 9260 if (!allCodePaths.isEmpty()) { 9261 if (instructionSets == null) { 9262 throw new IllegalStateException("instructionSet == null"); 9263 } 9264 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9265 for (String codePath : allCodePaths) { 9266 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9267 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9268 if (retCode < 0) { 9269 Slog.w(TAG, "Couldn't remove dex file for package: " 9270 + " at location " + codePath + ", retcode=" + retCode); 9271 // we don't consider this to be a failure of the core package deletion 9272 } 9273 } 9274 } 9275 } 9276 } 9277 9278 boolean doPostDeleteLI(boolean delete) { 9279 // XXX err, shouldn't we respect the delete flag? 9280 cleanUpResourcesLI(); 9281 return true; 9282 } 9283 } 9284 9285 private boolean isAsecExternal(String cid) { 9286 final String asecPath = PackageHelper.getSdFilesystem(cid); 9287 return !asecPath.startsWith(mAsecInternalPath); 9288 } 9289 9290 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9291 PackageManagerException { 9292 if (copyRet < 0) { 9293 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9294 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9295 throw new PackageManagerException(copyRet, message); 9296 } 9297 } 9298 } 9299 9300 /** 9301 * Extract the MountService "container ID" from the full code path of an 9302 * .apk. 9303 */ 9304 static String cidFromCodePath(String fullCodePath) { 9305 int eidx = fullCodePath.lastIndexOf("/"); 9306 String subStr1 = fullCodePath.substring(0, eidx); 9307 int sidx = subStr1.lastIndexOf("/"); 9308 return subStr1.substring(sidx+1, eidx); 9309 } 9310 9311 /** 9312 * Logic to handle installation of ASEC applications, including copying and 9313 * renaming logic. 9314 */ 9315 class AsecInstallArgs extends InstallArgs { 9316 static final String RES_FILE_NAME = "pkg.apk"; 9317 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9318 9319 String cid; 9320 String packagePath; 9321 String resourcePath; 9322 String legacyNativeLibraryDir; 9323 9324 /** New install */ 9325 AsecInstallArgs(InstallParams params) { 9326 super(params.origin, params.observer, params.installFlags, 9327 params.installerPackageName, params.getManifestDigest(), 9328 params.getUser(), null /* instruction sets */, 9329 params.packageAbiOverride); 9330 } 9331 9332 /** Existing install */ 9333 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9334 boolean isExternal, boolean isForwardLocked) { 9335 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9336 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9337 instructionSets, null); 9338 // Hackily pretend we're still looking at a full code path 9339 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9340 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9341 } 9342 9343 // Extract cid from fullCodePath 9344 int eidx = fullCodePath.lastIndexOf("/"); 9345 String subStr1 = fullCodePath.substring(0, eidx); 9346 int sidx = subStr1.lastIndexOf("/"); 9347 cid = subStr1.substring(sidx+1, eidx); 9348 setMountPath(subStr1); 9349 } 9350 9351 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9352 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9353 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9354 instructionSets, null); 9355 this.cid = cid; 9356 setMountPath(PackageHelper.getSdDir(cid)); 9357 } 9358 9359 void createCopyFile() { 9360 cid = mInstallerService.allocateExternalStageCidLegacy(); 9361 } 9362 9363 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9364 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9365 abiOverride); 9366 9367 final File target; 9368 if (isExternal()) { 9369 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9370 } else { 9371 target = Environment.getDataDirectory(); 9372 } 9373 9374 final StorageManager storage = StorageManager.from(mContext); 9375 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9376 } 9377 9378 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9379 if (origin.staged) { 9380 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9381 cid = origin.cid; 9382 setMountPath(PackageHelper.getSdDir(cid)); 9383 return PackageManager.INSTALL_SUCCEEDED; 9384 } 9385 9386 if (temp) { 9387 createCopyFile(); 9388 } else { 9389 /* 9390 * Pre-emptively destroy the container since it's destroyed if 9391 * copying fails due to it existing anyway. 9392 */ 9393 PackageHelper.destroySdDir(cid); 9394 } 9395 9396 final String newMountPath = imcs.copyPackageToContainer( 9397 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9398 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9399 9400 if (newMountPath != null) { 9401 setMountPath(newMountPath); 9402 return PackageManager.INSTALL_SUCCEEDED; 9403 } else { 9404 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9405 } 9406 } 9407 9408 @Override 9409 String getCodePath() { 9410 return packagePath; 9411 } 9412 9413 @Override 9414 String getResourcePath() { 9415 return resourcePath; 9416 } 9417 9418 @Override 9419 String getLegacyNativeLibraryPath() { 9420 return legacyNativeLibraryDir; 9421 } 9422 9423 int doPreInstall(int status) { 9424 if (status != PackageManager.INSTALL_SUCCEEDED) { 9425 // Destroy container 9426 PackageHelper.destroySdDir(cid); 9427 } else { 9428 boolean mounted = PackageHelper.isContainerMounted(cid); 9429 if (!mounted) { 9430 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9431 Process.SYSTEM_UID); 9432 if (newMountPath != null) { 9433 setMountPath(newMountPath); 9434 } else { 9435 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9436 } 9437 } 9438 } 9439 return status; 9440 } 9441 9442 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9443 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9444 String newMountPath = null; 9445 if (PackageHelper.isContainerMounted(cid)) { 9446 // Unmount the container 9447 if (!PackageHelper.unMountSdDir(cid)) { 9448 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9449 return false; 9450 } 9451 } 9452 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9453 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9454 " which might be stale. Will try to clean up."); 9455 // Clean up the stale container and proceed to recreate. 9456 if (!PackageHelper.destroySdDir(newCacheId)) { 9457 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9458 return false; 9459 } 9460 // Successfully cleaned up stale container. Try to rename again. 9461 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9462 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9463 + " inspite of cleaning it up."); 9464 return false; 9465 } 9466 } 9467 if (!PackageHelper.isContainerMounted(newCacheId)) { 9468 Slog.w(TAG, "Mounting container " + newCacheId); 9469 newMountPath = PackageHelper.mountSdDir(newCacheId, 9470 getEncryptKey(), Process.SYSTEM_UID); 9471 } else { 9472 newMountPath = PackageHelper.getSdDir(newCacheId); 9473 } 9474 if (newMountPath == null) { 9475 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9476 return false; 9477 } 9478 Log.i(TAG, "Succesfully renamed " + cid + 9479 " to " + newCacheId + 9480 " at new path: " + newMountPath); 9481 cid = newCacheId; 9482 9483 final File beforeCodeFile = new File(packagePath); 9484 setMountPath(newMountPath); 9485 final File afterCodeFile = new File(packagePath); 9486 9487 // Reflect the rename in scanned details 9488 pkg.codePath = afterCodeFile.getAbsolutePath(); 9489 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9490 pkg.baseCodePath); 9491 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9492 pkg.splitCodePaths); 9493 9494 // Reflect the rename in app info 9495 pkg.applicationInfo.setCodePath(pkg.codePath); 9496 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9497 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9498 pkg.applicationInfo.setResourcePath(pkg.codePath); 9499 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9500 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9501 9502 return true; 9503 } 9504 9505 private void setMountPath(String mountPath) { 9506 final File mountFile = new File(mountPath); 9507 9508 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9509 if (monolithicFile.exists()) { 9510 packagePath = monolithicFile.getAbsolutePath(); 9511 if (isFwdLocked()) { 9512 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9513 } else { 9514 resourcePath = packagePath; 9515 } 9516 } else { 9517 packagePath = mountFile.getAbsolutePath(); 9518 resourcePath = packagePath; 9519 } 9520 9521 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9522 } 9523 9524 int doPostInstall(int status, int uid) { 9525 if (status != PackageManager.INSTALL_SUCCEEDED) { 9526 cleanUp(); 9527 } else { 9528 final int groupOwner; 9529 final String protectedFile; 9530 if (isFwdLocked()) { 9531 groupOwner = UserHandle.getSharedAppGid(uid); 9532 protectedFile = RES_FILE_NAME; 9533 } else { 9534 groupOwner = -1; 9535 protectedFile = null; 9536 } 9537 9538 if (uid < Process.FIRST_APPLICATION_UID 9539 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9540 Slog.e(TAG, "Failed to finalize " + cid); 9541 PackageHelper.destroySdDir(cid); 9542 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9543 } 9544 9545 boolean mounted = PackageHelper.isContainerMounted(cid); 9546 if (!mounted) { 9547 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9548 } 9549 } 9550 return status; 9551 } 9552 9553 private void cleanUp() { 9554 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9555 9556 // Destroy secure container 9557 PackageHelper.destroySdDir(cid); 9558 } 9559 9560 private List<String> getAllCodePaths() { 9561 final File codeFile = new File(getCodePath()); 9562 if (codeFile != null && codeFile.exists()) { 9563 try { 9564 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9565 return pkg.getAllCodePaths(); 9566 } catch (PackageParserException e) { 9567 // Ignored; we tried our best 9568 } 9569 } 9570 return Collections.EMPTY_LIST; 9571 } 9572 9573 void cleanUpResourcesLI() { 9574 // Enumerate all code paths before deleting 9575 cleanUpResourcesLI(getAllCodePaths()); 9576 } 9577 9578 private void cleanUpResourcesLI(List<String> allCodePaths) { 9579 cleanUp(); 9580 9581 if (!allCodePaths.isEmpty()) { 9582 if (instructionSets == null) { 9583 throw new IllegalStateException("instructionSet == null"); 9584 } 9585 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9586 for (String codePath : allCodePaths) { 9587 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9588 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9589 if (retCode < 0) { 9590 Slog.w(TAG, "Couldn't remove dex file for package: " 9591 + " at location " + codePath + ", retcode=" + retCode); 9592 // we don't consider this to be a failure of the core package deletion 9593 } 9594 } 9595 } 9596 } 9597 } 9598 9599 boolean matchContainer(String app) { 9600 if (cid.startsWith(app)) { 9601 return true; 9602 } 9603 return false; 9604 } 9605 9606 String getPackageName() { 9607 return getAsecPackageName(cid); 9608 } 9609 9610 boolean doPostDeleteLI(boolean delete) { 9611 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9612 final List<String> allCodePaths = getAllCodePaths(); 9613 boolean mounted = PackageHelper.isContainerMounted(cid); 9614 if (mounted) { 9615 // Unmount first 9616 if (PackageHelper.unMountSdDir(cid)) { 9617 mounted = false; 9618 } 9619 } 9620 if (!mounted && delete) { 9621 cleanUpResourcesLI(allCodePaths); 9622 } 9623 return !mounted; 9624 } 9625 9626 @Override 9627 int doPreCopy() { 9628 if (isFwdLocked()) { 9629 if (!PackageHelper.fixSdPermissions(cid, 9630 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9631 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9632 } 9633 } 9634 9635 return PackageManager.INSTALL_SUCCEEDED; 9636 } 9637 9638 @Override 9639 int doPostCopy(int uid) { 9640 if (isFwdLocked()) { 9641 if (uid < Process.FIRST_APPLICATION_UID 9642 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9643 RES_FILE_NAME)) { 9644 Slog.e(TAG, "Failed to finalize " + cid); 9645 PackageHelper.destroySdDir(cid); 9646 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9647 } 9648 } 9649 9650 return PackageManager.INSTALL_SUCCEEDED; 9651 } 9652 } 9653 9654 static String getAsecPackageName(String packageCid) { 9655 int idx = packageCid.lastIndexOf("-"); 9656 if (idx == -1) { 9657 return packageCid; 9658 } 9659 return packageCid.substring(0, idx); 9660 } 9661 9662 // Utility method used to create code paths based on package name and available index. 9663 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9664 String idxStr = ""; 9665 int idx = 1; 9666 // Fall back to default value of idx=1 if prefix is not 9667 // part of oldCodePath 9668 if (oldCodePath != null) { 9669 String subStr = oldCodePath; 9670 // Drop the suffix right away 9671 if (suffix != null && subStr.endsWith(suffix)) { 9672 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9673 } 9674 // If oldCodePath already contains prefix find out the 9675 // ending index to either increment or decrement. 9676 int sidx = subStr.lastIndexOf(prefix); 9677 if (sidx != -1) { 9678 subStr = subStr.substring(sidx + prefix.length()); 9679 if (subStr != null) { 9680 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9681 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9682 } 9683 try { 9684 idx = Integer.parseInt(subStr); 9685 if (idx <= 1) { 9686 idx++; 9687 } else { 9688 idx--; 9689 } 9690 } catch(NumberFormatException e) { 9691 } 9692 } 9693 } 9694 } 9695 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9696 return prefix + idxStr; 9697 } 9698 9699 private File getNextCodePath(String packageName) { 9700 int suffix = 1; 9701 File result; 9702 do { 9703 result = new File(mAppInstallDir, packageName + "-" + suffix); 9704 suffix++; 9705 } while (result.exists()); 9706 return result; 9707 } 9708 9709 // Utility method used to ignore ADD/REMOVE events 9710 // by directory observer. 9711 private static boolean ignoreCodePath(String fullPathStr) { 9712 String apkName = deriveCodePathName(fullPathStr); 9713 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9714 if (idx != -1 && ((idx+1) < apkName.length())) { 9715 // Make sure the package ends with a numeral 9716 String version = apkName.substring(idx+1); 9717 try { 9718 Integer.parseInt(version); 9719 return true; 9720 } catch (NumberFormatException e) {} 9721 } 9722 return false; 9723 } 9724 9725 // Utility method that returns the relative package path with respect 9726 // to the installation directory. Like say for /data/data/com.test-1.apk 9727 // string com.test-1 is returned. 9728 static String deriveCodePathName(String codePath) { 9729 if (codePath == null) { 9730 return null; 9731 } 9732 final File codeFile = new File(codePath); 9733 final String name = codeFile.getName(); 9734 if (codeFile.isDirectory()) { 9735 return name; 9736 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9737 final int lastDot = name.lastIndexOf('.'); 9738 return name.substring(0, lastDot); 9739 } else { 9740 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9741 return null; 9742 } 9743 } 9744 9745 class PackageInstalledInfo { 9746 String name; 9747 int uid; 9748 // The set of users that originally had this package installed. 9749 int[] origUsers; 9750 // The set of users that now have this package installed. 9751 int[] newUsers; 9752 PackageParser.Package pkg; 9753 int returnCode; 9754 String returnMsg; 9755 PackageRemovedInfo removedInfo; 9756 9757 public void setError(int code, String msg) { 9758 returnCode = code; 9759 returnMsg = msg; 9760 Slog.w(TAG, msg); 9761 } 9762 9763 public void setError(String msg, PackageParserException e) { 9764 returnCode = e.error; 9765 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9766 Slog.w(TAG, msg, e); 9767 } 9768 9769 public void setError(String msg, PackageManagerException e) { 9770 returnCode = e.error; 9771 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9772 Slog.w(TAG, msg, e); 9773 } 9774 9775 // In some error cases we want to convey more info back to the observer 9776 String origPackage; 9777 String origPermission; 9778 } 9779 9780 /* 9781 * Install a non-existing package. 9782 */ 9783 private void installNewPackageLI(PackageParser.Package pkg, 9784 int parseFlags, int scanFlags, UserHandle user, 9785 String installerPackageName, PackageInstalledInfo res) { 9786 // Remember this for later, in case we need to rollback this install 9787 String pkgName = pkg.packageName; 9788 9789 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9790 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9791 synchronized(mPackages) { 9792 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9793 // A package with the same name is already installed, though 9794 // it has been renamed to an older name. The package we 9795 // are trying to install should be installed as an update to 9796 // the existing one, but that has not been requested, so bail. 9797 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9798 + " without first uninstalling package running as " 9799 + mSettings.mRenamedPackages.get(pkgName)); 9800 return; 9801 } 9802 if (mPackages.containsKey(pkgName)) { 9803 // Don't allow installation over an existing package with the same name. 9804 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9805 + " without first uninstalling."); 9806 return; 9807 } 9808 } 9809 9810 try { 9811 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9812 System.currentTimeMillis(), user); 9813 9814 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9815 // delete the partially installed application. the data directory will have to be 9816 // restored if it was already existing 9817 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9818 // remove package from internal structures. Note that we want deletePackageX to 9819 // delete the package data and cache directories that it created in 9820 // scanPackageLocked, unless those directories existed before we even tried to 9821 // install. 9822 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9823 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9824 res.removedInfo, true); 9825 } 9826 9827 } catch (PackageManagerException e) { 9828 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9829 } 9830 } 9831 9832 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9833 // Upgrade keysets are being used. Determine if new package has a superset of the 9834 // required keys. 9835 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9836 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9837 for (int i = 0; i < upgradeKeySets.length; i++) { 9838 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9839 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9840 return true; 9841 } 9842 } 9843 return false; 9844 } 9845 9846 private void replacePackageLI(PackageParser.Package pkg, 9847 int parseFlags, int scanFlags, UserHandle user, 9848 String installerPackageName, PackageInstalledInfo res) { 9849 PackageParser.Package oldPackage; 9850 String pkgName = pkg.packageName; 9851 int[] allUsers; 9852 boolean[] perUserInstalled; 9853 9854 // First find the old package info and check signatures 9855 synchronized(mPackages) { 9856 oldPackage = mPackages.get(pkgName); 9857 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9858 PackageSetting ps = mSettings.mPackages.get(pkgName); 9859 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9860 // default to original signature matching 9861 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9862 != PackageManager.SIGNATURE_MATCH) { 9863 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9864 "New package has a different signature: " + pkgName); 9865 return; 9866 } 9867 } else { 9868 if(!checkUpgradeKeySetLP(ps, pkg)) { 9869 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9870 "New package not signed by keys specified by upgrade-keysets: " 9871 + pkgName); 9872 return; 9873 } 9874 } 9875 9876 // In case of rollback, remember per-user/profile install state 9877 allUsers = sUserManager.getUserIds(); 9878 perUserInstalled = new boolean[allUsers.length]; 9879 for (int i = 0; i < allUsers.length; i++) { 9880 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9881 } 9882 } 9883 9884 boolean sysPkg = (isSystemApp(oldPackage)); 9885 if (sysPkg) { 9886 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9887 user, allUsers, perUserInstalled, installerPackageName, res); 9888 } else { 9889 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9890 user, allUsers, perUserInstalled, installerPackageName, res); 9891 } 9892 } 9893 9894 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9895 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9896 int[] allUsers, boolean[] perUserInstalled, 9897 String installerPackageName, PackageInstalledInfo res) { 9898 String pkgName = deletedPackage.packageName; 9899 boolean deletedPkg = true; 9900 boolean updatedSettings = false; 9901 9902 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9903 + deletedPackage); 9904 long origUpdateTime; 9905 if (pkg.mExtras != null) { 9906 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9907 } else { 9908 origUpdateTime = 0; 9909 } 9910 9911 // First delete the existing package while retaining the data directory 9912 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9913 res.removedInfo, true)) { 9914 // If the existing package wasn't successfully deleted 9915 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 9916 deletedPkg = false; 9917 } else { 9918 // Successfully deleted the old package; proceed with replace. 9919 9920 // If deleted package lived in a container, give users a chance to 9921 // relinquish resources before killing. 9922 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 9923 if (DEBUG_INSTALL) { 9924 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 9925 } 9926 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 9927 final ArrayList<String> pkgList = new ArrayList<String>(1); 9928 pkgList.add(deletedPackage.applicationInfo.packageName); 9929 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 9930 } 9931 9932 deleteCodeCacheDirsLI(pkgName); 9933 try { 9934 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 9935 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 9936 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9937 updatedSettings = true; 9938 } catch (PackageManagerException e) { 9939 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9940 } 9941 } 9942 9943 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9944 // remove package from internal structures. Note that we want deletePackageX to 9945 // delete the package data and cache directories that it created in 9946 // scanPackageLocked, unless those directories existed before we even tried to 9947 // install. 9948 if(updatedSettings) { 9949 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9950 deletePackageLI( 9951 pkgName, null, true, allUsers, perUserInstalled, 9952 PackageManager.DELETE_KEEP_DATA, 9953 res.removedInfo, true); 9954 } 9955 // Since we failed to install the new package we need to restore the old 9956 // package that we deleted. 9957 if (deletedPkg) { 9958 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9959 File restoreFile = new File(deletedPackage.codePath); 9960 // Parse old package 9961 boolean oldOnSd = isExternal(deletedPackage); 9962 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9963 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9964 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9965 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 9966 try { 9967 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 9968 } catch (PackageManagerException e) { 9969 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 9970 + e.getMessage()); 9971 return; 9972 } 9973 // Restore of old package succeeded. Update permissions. 9974 // writer 9975 synchronized (mPackages) { 9976 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9977 UPDATE_PERMISSIONS_ALL); 9978 // can downgrade to reader 9979 mSettings.writeLPr(); 9980 } 9981 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9982 } 9983 } 9984 } 9985 9986 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9987 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9988 int[] allUsers, boolean[] perUserInstalled, 9989 String installerPackageName, PackageInstalledInfo res) { 9990 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9991 + ", old=" + deletedPackage); 9992 boolean updatedSettings = false; 9993 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 9994 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9995 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9996 } 9997 String packageName = deletedPackage.packageName; 9998 if (packageName == null) { 9999 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10000 "Attempt to delete null packageName."); 10001 return; 10002 } 10003 PackageParser.Package oldPkg; 10004 PackageSetting oldPkgSetting; 10005 // reader 10006 synchronized (mPackages) { 10007 oldPkg = mPackages.get(packageName); 10008 oldPkgSetting = mSettings.mPackages.get(packageName); 10009 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10010 (oldPkgSetting == null)) { 10011 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10012 "Couldn't find package:" + packageName + " information"); 10013 return; 10014 } 10015 } 10016 10017 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10018 10019 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10020 res.removedInfo.removedPackage = packageName; 10021 // Remove existing system package 10022 removePackageLI(oldPkgSetting, true); 10023 // writer 10024 synchronized (mPackages) { 10025 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10026 // We didn't need to disable the .apk as a current system package, 10027 // which means we are replacing another update that is already 10028 // installed. We need to make sure to delete the older one's .apk. 10029 res.removedInfo.args = createInstallArgsForExisting(0, 10030 deletedPackage.applicationInfo.getCodePath(), 10031 deletedPackage.applicationInfo.getResourcePath(), 10032 deletedPackage.applicationInfo.nativeLibraryRootDir, 10033 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10034 } else { 10035 res.removedInfo.args = null; 10036 } 10037 } 10038 10039 // Successfully disabled the old package. Now proceed with re-installation 10040 deleteCodeCacheDirsLI(packageName); 10041 10042 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10043 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10044 10045 PackageParser.Package newPackage = null; 10046 try { 10047 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10048 if (newPackage.mExtras != null) { 10049 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10050 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10051 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10052 10053 // is the update attempting to change shared user? that isn't going to work... 10054 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10055 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10056 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10057 + " to " + newPkgSetting.sharedUser); 10058 updatedSettings = true; 10059 } 10060 } 10061 10062 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10063 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10064 updatedSettings = true; 10065 } 10066 10067 } catch (PackageManagerException e) { 10068 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10069 } 10070 10071 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10072 // Re installation failed. Restore old information 10073 // Remove new pkg information 10074 if (newPackage != null) { 10075 removeInstalledPackageLI(newPackage, true); 10076 } 10077 // Add back the old system package 10078 try { 10079 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10080 } catch (PackageManagerException e) { 10081 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10082 } 10083 // Restore the old system information in Settings 10084 synchronized(mPackages) { 10085 if (updatedSettings) { 10086 mSettings.enableSystemPackageLPw(packageName); 10087 mSettings.setInstallerPackageName(packageName, 10088 oldPkgSetting.installerPackageName); 10089 } 10090 mSettings.writeLPr(); 10091 } 10092 } 10093 } 10094 10095 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10096 int[] allUsers, boolean[] perUserInstalled, 10097 PackageInstalledInfo res) { 10098 String pkgName = newPackage.packageName; 10099 synchronized (mPackages) { 10100 //write settings. the installStatus will be incomplete at this stage. 10101 //note that the new package setting would have already been 10102 //added to mPackages. It hasn't been persisted yet. 10103 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10104 mSettings.writeLPr(); 10105 } 10106 10107 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10108 10109 synchronized (mPackages) { 10110 updatePermissionsLPw(newPackage.packageName, newPackage, 10111 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10112 ? UPDATE_PERMISSIONS_ALL : 0)); 10113 // For system-bundled packages, we assume that installing an upgraded version 10114 // of the package implies that the user actually wants to run that new code, 10115 // so we enable the package. 10116 if (isSystemApp(newPackage)) { 10117 // NB: implicit assumption that system package upgrades apply to all users 10118 if (DEBUG_INSTALL) { 10119 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10120 } 10121 PackageSetting ps = mSettings.mPackages.get(pkgName); 10122 if (ps != null) { 10123 if (res.origUsers != null) { 10124 for (int userHandle : res.origUsers) { 10125 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10126 userHandle, installerPackageName); 10127 } 10128 } 10129 // Also convey the prior install/uninstall state 10130 if (allUsers != null && perUserInstalled != null) { 10131 for (int i = 0; i < allUsers.length; i++) { 10132 if (DEBUG_INSTALL) { 10133 Slog.d(TAG, " user " + allUsers[i] 10134 + " => " + perUserInstalled[i]); 10135 } 10136 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10137 } 10138 // these install state changes will be persisted in the 10139 // upcoming call to mSettings.writeLPr(). 10140 } 10141 } 10142 } 10143 res.name = pkgName; 10144 res.uid = newPackage.applicationInfo.uid; 10145 res.pkg = newPackage; 10146 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10147 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10148 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10149 //to update install status 10150 mSettings.writeLPr(); 10151 } 10152 } 10153 10154 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10155 final int installFlags = args.installFlags; 10156 String installerPackageName = args.installerPackageName; 10157 File tmpPackageFile = new File(args.getCodePath()); 10158 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10159 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10160 boolean replace = false; 10161 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10162 // Result object to be returned 10163 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10164 10165 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10166 // Retrieve PackageSettings and parse package 10167 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10168 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10169 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10170 PackageParser pp = new PackageParser(); 10171 pp.setSeparateProcesses(mSeparateProcesses); 10172 pp.setDisplayMetrics(mMetrics); 10173 10174 final PackageParser.Package pkg; 10175 try { 10176 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10177 } catch (PackageParserException e) { 10178 res.setError("Failed parse during installPackageLI", e); 10179 return; 10180 } 10181 10182 // Mark that we have an install time CPU ABI override. 10183 pkg.cpuAbiOverride = args.abiOverride; 10184 10185 String pkgName = res.name = pkg.packageName; 10186 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10187 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10188 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10189 return; 10190 } 10191 } 10192 10193 try { 10194 pp.collectCertificates(pkg, parseFlags); 10195 pp.collectManifestDigest(pkg); 10196 } catch (PackageParserException e) { 10197 res.setError("Failed collect during installPackageLI", e); 10198 return; 10199 } 10200 10201 /* If the installer passed in a manifest digest, compare it now. */ 10202 if (args.manifestDigest != null) { 10203 if (DEBUG_INSTALL) { 10204 final String parsedManifest = pkg.manifestDigest == null ? "null" 10205 : pkg.manifestDigest.toString(); 10206 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10207 + parsedManifest); 10208 } 10209 10210 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10211 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10212 return; 10213 } 10214 } else if (DEBUG_INSTALL) { 10215 final String parsedManifest = pkg.manifestDigest == null 10216 ? "null" : pkg.manifestDigest.toString(); 10217 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10218 } 10219 10220 // Get rid of all references to package scan path via parser. 10221 pp = null; 10222 String oldCodePath = null; 10223 boolean systemApp = false; 10224 synchronized (mPackages) { 10225 // Check whether the newly-scanned package wants to define an already-defined perm 10226 int N = pkg.permissions.size(); 10227 for (int i = N-1; i >= 0; i--) { 10228 PackageParser.Permission perm = pkg.permissions.get(i); 10229 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10230 if (bp != null) { 10231 // If the defining package is signed with our cert, it's okay. This 10232 // also includes the "updating the same package" case, of course. 10233 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10234 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10235 // If the owning package is the system itself, we log but allow 10236 // install to proceed; we fail the install on all other permission 10237 // redefinitions. 10238 if (!bp.sourcePackage.equals("android")) { 10239 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10240 + pkg.packageName + " attempting to redeclare permission " 10241 + perm.info.name + " already owned by " + bp.sourcePackage); 10242 res.origPermission = perm.info.name; 10243 res.origPackage = bp.sourcePackage; 10244 return; 10245 } else { 10246 Slog.w(TAG, "Package " + pkg.packageName 10247 + " attempting to redeclare system permission " 10248 + perm.info.name + "; ignoring new declaration"); 10249 pkg.permissions.remove(i); 10250 } 10251 } 10252 } 10253 } 10254 10255 // Check if installing already existing package 10256 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10257 String oldName = mSettings.mRenamedPackages.get(pkgName); 10258 if (pkg.mOriginalPackages != null 10259 && pkg.mOriginalPackages.contains(oldName) 10260 && mPackages.containsKey(oldName)) { 10261 // This package is derived from an original package, 10262 // and this device has been updating from that original 10263 // name. We must continue using the original name, so 10264 // rename the new package here. 10265 pkg.setPackageName(oldName); 10266 pkgName = pkg.packageName; 10267 replace = true; 10268 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10269 + oldName + " pkgName=" + pkgName); 10270 } else if (mPackages.containsKey(pkgName)) { 10271 // This package, under its official name, already exists 10272 // on the device; we should replace it. 10273 replace = true; 10274 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10275 } 10276 } 10277 PackageSetting ps = mSettings.mPackages.get(pkgName); 10278 if (ps != null) { 10279 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10280 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10281 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10282 systemApp = (ps.pkg.applicationInfo.flags & 10283 ApplicationInfo.FLAG_SYSTEM) != 0; 10284 } 10285 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10286 } 10287 } 10288 10289 if (systemApp && onSd) { 10290 // Disable updates to system apps on sdcard 10291 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10292 "Cannot install updates to system apps on sdcard"); 10293 return; 10294 } 10295 10296 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10297 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10298 return; 10299 } 10300 10301 if (replace) { 10302 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10303 installerPackageName, res); 10304 } else { 10305 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10306 args.user, installerPackageName, res); 10307 } 10308 synchronized (mPackages) { 10309 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10310 if (ps != null) { 10311 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10312 } 10313 } 10314 } 10315 10316 private static boolean isForwardLocked(PackageParser.Package pkg) { 10317 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10318 } 10319 10320 private static boolean isForwardLocked(ApplicationInfo info) { 10321 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10322 } 10323 10324 private boolean isForwardLocked(PackageSetting ps) { 10325 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10326 } 10327 10328 private static boolean isMultiArch(PackageSetting ps) { 10329 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10330 } 10331 10332 private static boolean isMultiArch(ApplicationInfo info) { 10333 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10334 } 10335 10336 private static boolean isExternal(PackageParser.Package pkg) { 10337 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10338 } 10339 10340 private static boolean isExternal(PackageSetting ps) { 10341 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10342 } 10343 10344 private static boolean isExternal(ApplicationInfo info) { 10345 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10346 } 10347 10348 private static boolean isSystemApp(PackageParser.Package pkg) { 10349 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10350 } 10351 10352 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10353 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10354 } 10355 10356 private static boolean isSystemApp(ApplicationInfo info) { 10357 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10358 } 10359 10360 private static boolean isSystemApp(PackageSetting ps) { 10361 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10362 } 10363 10364 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10365 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10366 } 10367 10368 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10369 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10370 } 10371 10372 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10373 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10374 } 10375 10376 private int packageFlagsToInstallFlags(PackageSetting ps) { 10377 int installFlags = 0; 10378 if (isExternal(ps)) { 10379 installFlags |= PackageManager.INSTALL_EXTERNAL; 10380 } 10381 if (isForwardLocked(ps)) { 10382 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10383 } 10384 return installFlags; 10385 } 10386 10387 private void deleteTempPackageFiles() { 10388 final FilenameFilter filter = new FilenameFilter() { 10389 public boolean accept(File dir, String name) { 10390 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10391 } 10392 }; 10393 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10394 file.delete(); 10395 } 10396 } 10397 10398 @Override 10399 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10400 int flags) { 10401 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10402 flags); 10403 } 10404 10405 @Override 10406 public void deletePackage(final String packageName, 10407 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10408 mContext.enforceCallingOrSelfPermission( 10409 android.Manifest.permission.DELETE_PACKAGES, null); 10410 final int uid = Binder.getCallingUid(); 10411 if (UserHandle.getUserId(uid) != userId) { 10412 mContext.enforceCallingPermission( 10413 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10414 "deletePackage for user " + userId); 10415 } 10416 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10417 try { 10418 observer.onPackageDeleted(packageName, 10419 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10420 } catch (RemoteException re) { 10421 } 10422 return; 10423 } 10424 10425 boolean uninstallBlocked = false; 10426 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10427 int[] users = sUserManager.getUserIds(); 10428 for (int i = 0; i < users.length; ++i) { 10429 if (getBlockUninstallForUser(packageName, users[i])) { 10430 uninstallBlocked = true; 10431 break; 10432 } 10433 } 10434 } else { 10435 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10436 } 10437 if (uninstallBlocked) { 10438 try { 10439 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10440 null); 10441 } catch (RemoteException re) { 10442 } 10443 return; 10444 } 10445 10446 if (DEBUG_REMOVE) { 10447 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10448 } 10449 // Queue up an async operation since the package deletion may take a little while. 10450 mHandler.post(new Runnable() { 10451 public void run() { 10452 mHandler.removeCallbacks(this); 10453 final int returnCode = deletePackageX(packageName, userId, flags); 10454 if (observer != null) { 10455 try { 10456 observer.onPackageDeleted(packageName, returnCode, null); 10457 } catch (RemoteException e) { 10458 Log.i(TAG, "Observer no longer exists."); 10459 } //end catch 10460 } //end if 10461 } //end run 10462 }); 10463 } 10464 10465 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10466 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10467 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10468 try { 10469 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10470 || dpm.isDeviceOwner(packageName))) { 10471 return true; 10472 } 10473 } catch (RemoteException e) { 10474 } 10475 return false; 10476 } 10477 10478 /** 10479 * This method is an internal method that could be get invoked either 10480 * to delete an installed package or to clean up a failed installation. 10481 * After deleting an installed package, a broadcast is sent to notify any 10482 * listeners that the package has been installed. For cleaning up a failed 10483 * installation, the broadcast is not necessary since the package's 10484 * installation wouldn't have sent the initial broadcast either 10485 * The key steps in deleting a package are 10486 * deleting the package information in internal structures like mPackages, 10487 * deleting the packages base directories through installd 10488 * updating mSettings to reflect current status 10489 * persisting settings for later use 10490 * sending a broadcast if necessary 10491 */ 10492 private int deletePackageX(String packageName, int userId, int flags) { 10493 final PackageRemovedInfo info = new PackageRemovedInfo(); 10494 final boolean res; 10495 10496 if (isPackageDeviceAdmin(packageName, userId)) { 10497 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10498 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10499 } 10500 10501 boolean removedForAllUsers = false; 10502 boolean systemUpdate = false; 10503 10504 // for the uninstall-updates case and restricted profiles, remember the per- 10505 // userhandle installed state 10506 int[] allUsers; 10507 boolean[] perUserInstalled; 10508 synchronized (mPackages) { 10509 PackageSetting ps = mSettings.mPackages.get(packageName); 10510 allUsers = sUserManager.getUserIds(); 10511 perUserInstalled = new boolean[allUsers.length]; 10512 for (int i = 0; i < allUsers.length; i++) { 10513 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10514 } 10515 } 10516 10517 synchronized (mInstallLock) { 10518 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10519 res = deletePackageLI(packageName, 10520 (flags & PackageManager.DELETE_ALL_USERS) != 0 10521 ? UserHandle.ALL : new UserHandle(userId), 10522 true, allUsers, perUserInstalled, 10523 flags | REMOVE_CHATTY, info, true); 10524 systemUpdate = info.isRemovedPackageSystemUpdate; 10525 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10526 removedForAllUsers = true; 10527 } 10528 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10529 + " removedForAllUsers=" + removedForAllUsers); 10530 } 10531 10532 if (res) { 10533 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10534 10535 // If the removed package was a system update, the old system package 10536 // was re-enabled; we need to broadcast this information 10537 if (systemUpdate) { 10538 Bundle extras = new Bundle(1); 10539 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10540 ? info.removedAppId : info.uid); 10541 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10542 10543 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10544 extras, null, null, null); 10545 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10546 extras, null, null, null); 10547 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10548 null, packageName, null, null); 10549 } 10550 } 10551 // Force a gc here. 10552 Runtime.getRuntime().gc(); 10553 // Delete the resources here after sending the broadcast to let 10554 // other processes clean up before deleting resources. 10555 if (info.args != null) { 10556 synchronized (mInstallLock) { 10557 info.args.doPostDeleteLI(true); 10558 } 10559 } 10560 10561 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10562 } 10563 10564 static class PackageRemovedInfo { 10565 String removedPackage; 10566 int uid = -1; 10567 int removedAppId = -1; 10568 int[] removedUsers = null; 10569 boolean isRemovedPackageSystemUpdate = false; 10570 // Clean up resources deleted packages. 10571 InstallArgs args = null; 10572 10573 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10574 Bundle extras = new Bundle(1); 10575 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10576 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10577 if (replacing) { 10578 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10579 } 10580 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10581 if (removedPackage != null) { 10582 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10583 extras, null, null, removedUsers); 10584 if (fullRemove && !replacing) { 10585 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10586 extras, null, null, removedUsers); 10587 } 10588 } 10589 if (removedAppId >= 0) { 10590 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10591 removedUsers); 10592 } 10593 } 10594 } 10595 10596 /* 10597 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10598 * flag is not set, the data directory is removed as well. 10599 * make sure this flag is set for partially installed apps. If not its meaningless to 10600 * delete a partially installed application. 10601 */ 10602 private void removePackageDataLI(PackageSetting ps, 10603 int[] allUserHandles, boolean[] perUserInstalled, 10604 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10605 String packageName = ps.name; 10606 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10607 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10608 // Retrieve object to delete permissions for shared user later on 10609 final PackageSetting deletedPs; 10610 // reader 10611 synchronized (mPackages) { 10612 deletedPs = mSettings.mPackages.get(packageName); 10613 if (outInfo != null) { 10614 outInfo.removedPackage = packageName; 10615 outInfo.removedUsers = deletedPs != null 10616 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10617 : null; 10618 } 10619 } 10620 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10621 removeDataDirsLI(packageName); 10622 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10623 } 10624 // writer 10625 synchronized (mPackages) { 10626 if (deletedPs != null) { 10627 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10628 if (outInfo != null) { 10629 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10630 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10631 } 10632 if (deletedPs != null) { 10633 updatePermissionsLPw(deletedPs.name, null, 0); 10634 if (deletedPs.sharedUser != null) { 10635 // remove permissions associated with package 10636 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10637 } 10638 } 10639 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10640 } 10641 // make sure to preserve per-user disabled state if this removal was just 10642 // a downgrade of a system app to the factory package 10643 if (allUserHandles != null && perUserInstalled != null) { 10644 if (DEBUG_REMOVE) { 10645 Slog.d(TAG, "Propagating install state across downgrade"); 10646 } 10647 for (int i = 0; i < allUserHandles.length; i++) { 10648 if (DEBUG_REMOVE) { 10649 Slog.d(TAG, " user " + allUserHandles[i] 10650 + " => " + perUserInstalled[i]); 10651 } 10652 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10653 } 10654 } 10655 } 10656 // can downgrade to reader 10657 if (writeSettings) { 10658 // Save settings now 10659 mSettings.writeLPr(); 10660 } 10661 } 10662 if (outInfo != null) { 10663 // A user ID was deleted here. Go through all users and remove it 10664 // from KeyStore. 10665 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10666 } 10667 } 10668 10669 static boolean locationIsPrivileged(File path) { 10670 try { 10671 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10672 .getCanonicalPath(); 10673 return path.getCanonicalPath().startsWith(privilegedAppDir); 10674 } catch (IOException e) { 10675 Slog.e(TAG, "Unable to access code path " + path); 10676 } 10677 return false; 10678 } 10679 10680 /* 10681 * Tries to delete system package. 10682 */ 10683 private boolean deleteSystemPackageLI(PackageSetting newPs, 10684 int[] allUserHandles, boolean[] perUserInstalled, 10685 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10686 final boolean applyUserRestrictions 10687 = (allUserHandles != null) && (perUserInstalled != null); 10688 PackageSetting disabledPs = null; 10689 // Confirm if the system package has been updated 10690 // An updated system app can be deleted. This will also have to restore 10691 // the system pkg from system partition 10692 // reader 10693 synchronized (mPackages) { 10694 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10695 } 10696 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10697 + " disabledPs=" + disabledPs); 10698 if (disabledPs == null) { 10699 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10700 return false; 10701 } else if (DEBUG_REMOVE) { 10702 Slog.d(TAG, "Deleting system pkg from data partition"); 10703 } 10704 if (DEBUG_REMOVE) { 10705 if (applyUserRestrictions) { 10706 Slog.d(TAG, "Remembering install states:"); 10707 for (int i = 0; i < allUserHandles.length; i++) { 10708 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10709 } 10710 } 10711 } 10712 // Delete the updated package 10713 outInfo.isRemovedPackageSystemUpdate = true; 10714 if (disabledPs.versionCode < newPs.versionCode) { 10715 // Delete data for downgrades 10716 flags &= ~PackageManager.DELETE_KEEP_DATA; 10717 } else { 10718 // Preserve data by setting flag 10719 flags |= PackageManager.DELETE_KEEP_DATA; 10720 } 10721 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10722 allUserHandles, perUserInstalled, outInfo, writeSettings); 10723 if (!ret) { 10724 return false; 10725 } 10726 // writer 10727 synchronized (mPackages) { 10728 // Reinstate the old system package 10729 mSettings.enableSystemPackageLPw(newPs.name); 10730 // Remove any native libraries from the upgraded package. 10731 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10732 } 10733 // Install the system package 10734 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10735 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10736 if (locationIsPrivileged(disabledPs.codePath)) { 10737 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10738 } 10739 10740 final PackageParser.Package newPkg; 10741 try { 10742 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10743 } catch (PackageManagerException e) { 10744 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10745 return false; 10746 } 10747 10748 // writer 10749 synchronized (mPackages) { 10750 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10751 updatePermissionsLPw(newPkg.packageName, newPkg, 10752 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10753 if (applyUserRestrictions) { 10754 if (DEBUG_REMOVE) { 10755 Slog.d(TAG, "Propagating install state across reinstall"); 10756 } 10757 for (int i = 0; i < allUserHandles.length; i++) { 10758 if (DEBUG_REMOVE) { 10759 Slog.d(TAG, " user " + allUserHandles[i] 10760 + " => " + perUserInstalled[i]); 10761 } 10762 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10763 } 10764 // Regardless of writeSettings we need to ensure that this restriction 10765 // state propagation is persisted 10766 mSettings.writeAllUsersPackageRestrictionsLPr(); 10767 } 10768 // can downgrade to reader here 10769 if (writeSettings) { 10770 mSettings.writeLPr(); 10771 } 10772 } 10773 return true; 10774 } 10775 10776 private boolean deleteInstalledPackageLI(PackageSetting ps, 10777 boolean deleteCodeAndResources, int flags, 10778 int[] allUserHandles, boolean[] perUserInstalled, 10779 PackageRemovedInfo outInfo, boolean writeSettings) { 10780 if (outInfo != null) { 10781 outInfo.uid = ps.appId; 10782 } 10783 10784 // Delete package data from internal structures and also remove data if flag is set 10785 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10786 10787 // Delete application code and resources 10788 if (deleteCodeAndResources && (outInfo != null)) { 10789 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10790 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10791 getAppDexInstructionSets(ps)); 10792 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10793 } 10794 return true; 10795 } 10796 10797 @Override 10798 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10799 int userId) { 10800 mContext.enforceCallingOrSelfPermission( 10801 android.Manifest.permission.DELETE_PACKAGES, null); 10802 synchronized (mPackages) { 10803 PackageSetting ps = mSettings.mPackages.get(packageName); 10804 if (ps == null) { 10805 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10806 return false; 10807 } 10808 if (!ps.getInstalled(userId)) { 10809 // Can't block uninstall for an app that is not installed or enabled. 10810 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10811 return false; 10812 } 10813 ps.setBlockUninstall(blockUninstall, userId); 10814 mSettings.writePackageRestrictionsLPr(userId); 10815 } 10816 return true; 10817 } 10818 10819 @Override 10820 public boolean getBlockUninstallForUser(String packageName, int userId) { 10821 synchronized (mPackages) { 10822 PackageSetting ps = mSettings.mPackages.get(packageName); 10823 if (ps == null) { 10824 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10825 return false; 10826 } 10827 return ps.getBlockUninstall(userId); 10828 } 10829 } 10830 10831 /* 10832 * This method handles package deletion in general 10833 */ 10834 private boolean deletePackageLI(String packageName, UserHandle user, 10835 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10836 int flags, PackageRemovedInfo outInfo, 10837 boolean writeSettings) { 10838 if (packageName == null) { 10839 Slog.w(TAG, "Attempt to delete null packageName."); 10840 return false; 10841 } 10842 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10843 PackageSetting ps; 10844 boolean dataOnly = false; 10845 int removeUser = -1; 10846 int appId = -1; 10847 synchronized (mPackages) { 10848 ps = mSettings.mPackages.get(packageName); 10849 if (ps == null) { 10850 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10851 return false; 10852 } 10853 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10854 && user.getIdentifier() != UserHandle.USER_ALL) { 10855 // The caller is asking that the package only be deleted for a single 10856 // user. To do this, we just mark its uninstalled state and delete 10857 // its data. If this is a system app, we only allow this to happen if 10858 // they have set the special DELETE_SYSTEM_APP which requests different 10859 // semantics than normal for uninstalling system apps. 10860 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10861 ps.setUserState(user.getIdentifier(), 10862 COMPONENT_ENABLED_STATE_DEFAULT, 10863 false, //installed 10864 true, //stopped 10865 true, //notLaunched 10866 false, //hidden 10867 null, null, null, 10868 false // blockUninstall 10869 ); 10870 if (!isSystemApp(ps)) { 10871 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10872 // Other user still have this package installed, so all 10873 // we need to do is clear this user's data and save that 10874 // it is uninstalled. 10875 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10876 removeUser = user.getIdentifier(); 10877 appId = ps.appId; 10878 mSettings.writePackageRestrictionsLPr(removeUser); 10879 } else { 10880 // We need to set it back to 'installed' so the uninstall 10881 // broadcasts will be sent correctly. 10882 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10883 ps.setInstalled(true, user.getIdentifier()); 10884 } 10885 } else { 10886 // This is a system app, so we assume that the 10887 // other users still have this package installed, so all 10888 // we need to do is clear this user's data and save that 10889 // it is uninstalled. 10890 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10891 removeUser = user.getIdentifier(); 10892 appId = ps.appId; 10893 mSettings.writePackageRestrictionsLPr(removeUser); 10894 } 10895 } 10896 } 10897 10898 if (removeUser >= 0) { 10899 // From above, we determined that we are deleting this only 10900 // for a single user. Continue the work here. 10901 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10902 if (outInfo != null) { 10903 outInfo.removedPackage = packageName; 10904 outInfo.removedAppId = appId; 10905 outInfo.removedUsers = new int[] {removeUser}; 10906 } 10907 mInstaller.clearUserData(packageName, removeUser); 10908 removeKeystoreDataIfNeeded(removeUser, appId); 10909 schedulePackageCleaning(packageName, removeUser, false); 10910 return true; 10911 } 10912 10913 if (dataOnly) { 10914 // Delete application data first 10915 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10916 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10917 return true; 10918 } 10919 10920 boolean ret = false; 10921 if (isSystemApp(ps)) { 10922 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10923 // When an updated system application is deleted we delete the existing resources as well and 10924 // fall back to existing code in system partition 10925 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10926 flags, outInfo, writeSettings); 10927 } else { 10928 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10929 // Kill application pre-emptively especially for apps on sd. 10930 killApplication(packageName, ps.appId, "uninstall pkg"); 10931 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10932 allUserHandles, perUserInstalled, 10933 outInfo, writeSettings); 10934 } 10935 10936 return ret; 10937 } 10938 10939 private final class ClearStorageConnection implements ServiceConnection { 10940 IMediaContainerService mContainerService; 10941 10942 @Override 10943 public void onServiceConnected(ComponentName name, IBinder service) { 10944 synchronized (this) { 10945 mContainerService = IMediaContainerService.Stub.asInterface(service); 10946 notifyAll(); 10947 } 10948 } 10949 10950 @Override 10951 public void onServiceDisconnected(ComponentName name) { 10952 } 10953 } 10954 10955 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10956 final boolean mounted; 10957 if (Environment.isExternalStorageEmulated()) { 10958 mounted = true; 10959 } else { 10960 final String status = Environment.getExternalStorageState(); 10961 10962 mounted = status.equals(Environment.MEDIA_MOUNTED) 10963 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10964 } 10965 10966 if (!mounted) { 10967 return; 10968 } 10969 10970 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10971 int[] users; 10972 if (userId == UserHandle.USER_ALL) { 10973 users = sUserManager.getUserIds(); 10974 } else { 10975 users = new int[] { userId }; 10976 } 10977 final ClearStorageConnection conn = new ClearStorageConnection(); 10978 if (mContext.bindServiceAsUser( 10979 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10980 try { 10981 for (int curUser : users) { 10982 long timeout = SystemClock.uptimeMillis() + 5000; 10983 synchronized (conn) { 10984 long now = SystemClock.uptimeMillis(); 10985 while (conn.mContainerService == null && now < timeout) { 10986 try { 10987 conn.wait(timeout - now); 10988 } catch (InterruptedException e) { 10989 } 10990 } 10991 } 10992 if (conn.mContainerService == null) { 10993 return; 10994 } 10995 10996 final UserEnvironment userEnv = new UserEnvironment(curUser); 10997 clearDirectory(conn.mContainerService, 10998 userEnv.buildExternalStorageAppCacheDirs(packageName)); 10999 if (allData) { 11000 clearDirectory(conn.mContainerService, 11001 userEnv.buildExternalStorageAppDataDirs(packageName)); 11002 clearDirectory(conn.mContainerService, 11003 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11004 } 11005 } 11006 } finally { 11007 mContext.unbindService(conn); 11008 } 11009 } 11010 } 11011 11012 @Override 11013 public void clearApplicationUserData(final String packageName, 11014 final IPackageDataObserver observer, final int userId) { 11015 mContext.enforceCallingOrSelfPermission( 11016 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11017 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11018 // Queue up an async operation since the package deletion may take a little while. 11019 mHandler.post(new Runnable() { 11020 public void run() { 11021 mHandler.removeCallbacks(this); 11022 final boolean succeeded; 11023 synchronized (mInstallLock) { 11024 succeeded = clearApplicationUserDataLI(packageName, userId); 11025 } 11026 clearExternalStorageDataSync(packageName, userId, true); 11027 if (succeeded) { 11028 // invoke DeviceStorageMonitor's update method to clear any notifications 11029 DeviceStorageMonitorInternal 11030 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11031 if (dsm != null) { 11032 dsm.checkMemory(); 11033 } 11034 } 11035 if(observer != null) { 11036 try { 11037 observer.onRemoveCompleted(packageName, succeeded); 11038 } catch (RemoteException e) { 11039 Log.i(TAG, "Observer no longer exists."); 11040 } 11041 } //end if observer 11042 } //end run 11043 }); 11044 } 11045 11046 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11047 if (packageName == null) { 11048 Slog.w(TAG, "Attempt to delete null packageName."); 11049 return false; 11050 } 11051 PackageParser.Package p; 11052 boolean dataOnly = false; 11053 final int appId; 11054 synchronized (mPackages) { 11055 p = mPackages.get(packageName); 11056 if (p == null) { 11057 dataOnly = true; 11058 PackageSetting ps = mSettings.mPackages.get(packageName); 11059 if ((ps == null) || (ps.pkg == null)) { 11060 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11061 return false; 11062 } 11063 p = ps.pkg; 11064 } 11065 if (!dataOnly) { 11066 // need to check this only for fully installed applications 11067 if (p == null) { 11068 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11069 return false; 11070 } 11071 final ApplicationInfo applicationInfo = p.applicationInfo; 11072 if (applicationInfo == null) { 11073 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11074 return false; 11075 } 11076 } 11077 if (p != null && p.applicationInfo != null) { 11078 appId = p.applicationInfo.uid; 11079 } else { 11080 appId = -1; 11081 } 11082 } 11083 int retCode = mInstaller.clearUserData(packageName, userId); 11084 if (retCode < 0) { 11085 Slog.w(TAG, "Couldn't remove cache files for package: " 11086 + packageName); 11087 return false; 11088 } 11089 removeKeystoreDataIfNeeded(userId, appId); 11090 return true; 11091 } 11092 11093 /** 11094 * Remove entries from the keystore daemon. Will only remove it if the 11095 * {@code appId} is valid. 11096 */ 11097 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11098 if (appId < 0) { 11099 return; 11100 } 11101 11102 final KeyStore keyStore = KeyStore.getInstance(); 11103 if (keyStore != null) { 11104 if (userId == UserHandle.USER_ALL) { 11105 for (final int individual : sUserManager.getUserIds()) { 11106 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11107 } 11108 } else { 11109 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11110 } 11111 } else { 11112 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11113 } 11114 } 11115 11116 @Override 11117 public void deleteApplicationCacheFiles(final String packageName, 11118 final IPackageDataObserver observer) { 11119 mContext.enforceCallingOrSelfPermission( 11120 android.Manifest.permission.DELETE_CACHE_FILES, null); 11121 // Queue up an async operation since the package deletion may take a little while. 11122 final int userId = UserHandle.getCallingUserId(); 11123 mHandler.post(new Runnable() { 11124 public void run() { 11125 mHandler.removeCallbacks(this); 11126 final boolean succeded; 11127 synchronized (mInstallLock) { 11128 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11129 } 11130 clearExternalStorageDataSync(packageName, userId, false); 11131 if(observer != null) { 11132 try { 11133 observer.onRemoveCompleted(packageName, succeded); 11134 } catch (RemoteException e) { 11135 Log.i(TAG, "Observer no longer exists."); 11136 } 11137 } //end if observer 11138 } //end run 11139 }); 11140 } 11141 11142 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11143 if (packageName == null) { 11144 Slog.w(TAG, "Attempt to delete null packageName."); 11145 return false; 11146 } 11147 PackageParser.Package p; 11148 synchronized (mPackages) { 11149 p = mPackages.get(packageName); 11150 } 11151 if (p == null) { 11152 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11153 return false; 11154 } 11155 final ApplicationInfo applicationInfo = p.applicationInfo; 11156 if (applicationInfo == null) { 11157 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11158 return false; 11159 } 11160 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11161 if (retCode < 0) { 11162 Slog.w(TAG, "Couldn't remove cache files for package: " 11163 + packageName + " u" + userId); 11164 return false; 11165 } 11166 return true; 11167 } 11168 11169 @Override 11170 public void getPackageSizeInfo(final String packageName, int userHandle, 11171 final IPackageStatsObserver observer) { 11172 mContext.enforceCallingOrSelfPermission( 11173 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11174 if (packageName == null) { 11175 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11176 } 11177 11178 PackageStats stats = new PackageStats(packageName, userHandle); 11179 11180 /* 11181 * Queue up an async operation since the package measurement may take a 11182 * little while. 11183 */ 11184 Message msg = mHandler.obtainMessage(INIT_COPY); 11185 msg.obj = new MeasureParams(stats, observer); 11186 mHandler.sendMessage(msg); 11187 } 11188 11189 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11190 PackageStats pStats) { 11191 if (packageName == null) { 11192 Slog.w(TAG, "Attempt to get size of null packageName."); 11193 return false; 11194 } 11195 PackageParser.Package p; 11196 boolean dataOnly = false; 11197 String libDirRoot = null; 11198 String asecPath = null; 11199 PackageSetting ps = null; 11200 synchronized (mPackages) { 11201 p = mPackages.get(packageName); 11202 ps = mSettings.mPackages.get(packageName); 11203 if(p == null) { 11204 dataOnly = true; 11205 if((ps == null) || (ps.pkg == null)) { 11206 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11207 return false; 11208 } 11209 p = ps.pkg; 11210 } 11211 if (ps != null) { 11212 libDirRoot = ps.legacyNativeLibraryPathString; 11213 } 11214 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11215 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11216 if (secureContainerId != null) { 11217 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11218 } 11219 } 11220 } 11221 String publicSrcDir = null; 11222 if(!dataOnly) { 11223 final ApplicationInfo applicationInfo = p.applicationInfo; 11224 if (applicationInfo == null) { 11225 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11226 return false; 11227 } 11228 if (isForwardLocked(p)) { 11229 publicSrcDir = applicationInfo.getBaseResourcePath(); 11230 } 11231 } 11232 // TODO: extend to measure size of split APKs 11233 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11234 // not just the first level. 11235 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11236 // just the primary. 11237 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11238 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11239 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11240 if (res < 0) { 11241 return false; 11242 } 11243 11244 // Fix-up for forward-locked applications in ASEC containers. 11245 if (!isExternal(p)) { 11246 pStats.codeSize += pStats.externalCodeSize; 11247 pStats.externalCodeSize = 0L; 11248 } 11249 11250 return true; 11251 } 11252 11253 11254 @Override 11255 public void addPackageToPreferred(String packageName) { 11256 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11257 } 11258 11259 @Override 11260 public void removePackageFromPreferred(String packageName) { 11261 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11262 } 11263 11264 @Override 11265 public List<PackageInfo> getPreferredPackages(int flags) { 11266 return new ArrayList<PackageInfo>(); 11267 } 11268 11269 private int getUidTargetSdkVersionLockedLPr(int uid) { 11270 Object obj = mSettings.getUserIdLPr(uid); 11271 if (obj instanceof SharedUserSetting) { 11272 final SharedUserSetting sus = (SharedUserSetting) obj; 11273 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11274 final Iterator<PackageSetting> it = sus.packages.iterator(); 11275 while (it.hasNext()) { 11276 final PackageSetting ps = it.next(); 11277 if (ps.pkg != null) { 11278 int v = ps.pkg.applicationInfo.targetSdkVersion; 11279 if (v < vers) vers = v; 11280 } 11281 } 11282 return vers; 11283 } else if (obj instanceof PackageSetting) { 11284 final PackageSetting ps = (PackageSetting) obj; 11285 if (ps.pkg != null) { 11286 return ps.pkg.applicationInfo.targetSdkVersion; 11287 } 11288 } 11289 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11290 } 11291 11292 @Override 11293 public void addPreferredActivity(IntentFilter filter, int match, 11294 ComponentName[] set, ComponentName activity, int userId) { 11295 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11296 "Adding preferred"); 11297 } 11298 11299 private void addPreferredActivityInternal(IntentFilter filter, int match, 11300 ComponentName[] set, ComponentName activity, boolean always, int userId, 11301 String opname) { 11302 // writer 11303 int callingUid = Binder.getCallingUid(); 11304 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11305 if (filter.countActions() == 0) { 11306 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11307 return; 11308 } 11309 synchronized (mPackages) { 11310 if (mContext.checkCallingOrSelfPermission( 11311 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11312 != PackageManager.PERMISSION_GRANTED) { 11313 if (getUidTargetSdkVersionLockedLPr(callingUid) 11314 < Build.VERSION_CODES.FROYO) { 11315 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11316 + callingUid); 11317 return; 11318 } 11319 mContext.enforceCallingOrSelfPermission( 11320 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11321 } 11322 11323 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11324 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11325 + userId + ":"); 11326 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11327 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11328 mSettings.writePackageRestrictionsLPr(userId); 11329 } 11330 } 11331 11332 @Override 11333 public void replacePreferredActivity(IntentFilter filter, int match, 11334 ComponentName[] set, ComponentName activity, int userId) { 11335 if (filter.countActions() != 1) { 11336 throw new IllegalArgumentException( 11337 "replacePreferredActivity expects filter to have only 1 action."); 11338 } 11339 if (filter.countDataAuthorities() != 0 11340 || filter.countDataPaths() != 0 11341 || filter.countDataSchemes() > 1 11342 || filter.countDataTypes() != 0) { 11343 throw new IllegalArgumentException( 11344 "replacePreferredActivity expects filter to have no data authorities, " + 11345 "paths, or types; and at most one scheme."); 11346 } 11347 11348 final int callingUid = Binder.getCallingUid(); 11349 enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity"); 11350 synchronized (mPackages) { 11351 if (mContext.checkCallingOrSelfPermission( 11352 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11353 != PackageManager.PERMISSION_GRANTED) { 11354 if (getUidTargetSdkVersionLockedLPr(callingUid) 11355 < Build.VERSION_CODES.FROYO) { 11356 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11357 + Binder.getCallingUid()); 11358 return; 11359 } 11360 mContext.enforceCallingOrSelfPermission( 11361 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11362 } 11363 11364 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11365 if (pir != null) { 11366 // Get all of the existing entries that exactly match this filter. 11367 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11368 if (existing != null && existing.size() == 1) { 11369 PreferredActivity cur = existing.get(0); 11370 if (DEBUG_PREFERRED) { 11371 Slog.i(TAG, "Checking replace of preferred:"); 11372 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11373 if (!cur.mPref.mAlways) { 11374 Slog.i(TAG, " -- CUR; not mAlways!"); 11375 } else { 11376 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11377 Slog.i(TAG, " -- CUR: mSet=" 11378 + Arrays.toString(cur.mPref.mSetComponents)); 11379 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11380 Slog.i(TAG, " -- NEW: mMatch=" 11381 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11382 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11383 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11384 } 11385 } 11386 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11387 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11388 && cur.mPref.sameSet(set)) { 11389 if (DEBUG_PREFERRED) { 11390 Slog.i(TAG, "Replacing with same preferred activity " 11391 + cur.mPref.mShortComponent + " for user " 11392 + userId + ":"); 11393 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11394 } else { 11395 Slog.i(TAG, "Replacing with same preferred activity " 11396 + cur.mPref.mShortComponent + " for user " 11397 + userId); 11398 } 11399 return; 11400 } 11401 } 11402 11403 if (existing != null) { 11404 if (DEBUG_PREFERRED) { 11405 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11406 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11407 } 11408 for (int i = 0; i < existing.size(); i++) { 11409 PreferredActivity pa = existing.get(i); 11410 if (DEBUG_PREFERRED) { 11411 Slog.i(TAG, "Removing existing preferred activity " 11412 + pa.mPref.mComponent + ":"); 11413 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11414 } 11415 pir.removeFilter(pa); 11416 } 11417 } 11418 } 11419 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11420 "Replacing preferred"); 11421 } 11422 } 11423 11424 @Override 11425 public void clearPackagePreferredActivities(String packageName) { 11426 final int uid = Binder.getCallingUid(); 11427 // writer 11428 synchronized (mPackages) { 11429 PackageParser.Package pkg = mPackages.get(packageName); 11430 if (pkg == null || pkg.applicationInfo.uid != uid) { 11431 if (mContext.checkCallingOrSelfPermission( 11432 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11433 != PackageManager.PERMISSION_GRANTED) { 11434 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11435 < Build.VERSION_CODES.FROYO) { 11436 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11437 + Binder.getCallingUid()); 11438 return; 11439 } 11440 mContext.enforceCallingOrSelfPermission( 11441 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11442 } 11443 } 11444 11445 int user = UserHandle.getCallingUserId(); 11446 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11447 mSettings.writePackageRestrictionsLPr(user); 11448 scheduleWriteSettingsLocked(); 11449 } 11450 } 11451 } 11452 11453 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11454 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11455 ArrayList<PreferredActivity> removed = null; 11456 boolean changed = false; 11457 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11458 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11459 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11460 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11461 continue; 11462 } 11463 Iterator<PreferredActivity> it = pir.filterIterator(); 11464 while (it.hasNext()) { 11465 PreferredActivity pa = it.next(); 11466 // Mark entry for removal only if it matches the package name 11467 // and the entry is of type "always". 11468 if (packageName == null || 11469 (pa.mPref.mComponent.getPackageName().equals(packageName) 11470 && pa.mPref.mAlways)) { 11471 if (removed == null) { 11472 removed = new ArrayList<PreferredActivity>(); 11473 } 11474 removed.add(pa); 11475 } 11476 } 11477 if (removed != null) { 11478 for (int j=0; j<removed.size(); j++) { 11479 PreferredActivity pa = removed.get(j); 11480 pir.removeFilter(pa); 11481 } 11482 changed = true; 11483 } 11484 } 11485 return changed; 11486 } 11487 11488 @Override 11489 public void resetPreferredActivities(int userId) { 11490 mContext.enforceCallingOrSelfPermission( 11491 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11492 // writer 11493 synchronized (mPackages) { 11494 int user = UserHandle.getCallingUserId(); 11495 clearPackagePreferredActivitiesLPw(null, user); 11496 mSettings.readDefaultPreferredAppsLPw(this, user); 11497 mSettings.writePackageRestrictionsLPr(user); 11498 scheduleWriteSettingsLocked(); 11499 } 11500 } 11501 11502 @Override 11503 public int getPreferredActivities(List<IntentFilter> outFilters, 11504 List<ComponentName> outActivities, String packageName) { 11505 11506 int num = 0; 11507 final int userId = UserHandle.getCallingUserId(); 11508 // reader 11509 synchronized (mPackages) { 11510 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11511 if (pir != null) { 11512 final Iterator<PreferredActivity> it = pir.filterIterator(); 11513 while (it.hasNext()) { 11514 final PreferredActivity pa = it.next(); 11515 if (packageName == null 11516 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11517 && pa.mPref.mAlways)) { 11518 if (outFilters != null) { 11519 outFilters.add(new IntentFilter(pa)); 11520 } 11521 if (outActivities != null) { 11522 outActivities.add(pa.mPref.mComponent); 11523 } 11524 } 11525 } 11526 } 11527 } 11528 11529 return num; 11530 } 11531 11532 @Override 11533 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11534 int userId) { 11535 int callingUid = Binder.getCallingUid(); 11536 if (callingUid != Process.SYSTEM_UID) { 11537 throw new SecurityException( 11538 "addPersistentPreferredActivity can only be run by the system"); 11539 } 11540 if (filter.countActions() == 0) { 11541 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11542 return; 11543 } 11544 synchronized (mPackages) { 11545 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11546 " :"); 11547 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11548 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11549 new PersistentPreferredActivity(filter, activity)); 11550 mSettings.writePackageRestrictionsLPr(userId); 11551 } 11552 } 11553 11554 @Override 11555 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11556 int callingUid = Binder.getCallingUid(); 11557 if (callingUid != Process.SYSTEM_UID) { 11558 throw new SecurityException( 11559 "clearPackagePersistentPreferredActivities can only be run by the system"); 11560 } 11561 ArrayList<PersistentPreferredActivity> removed = null; 11562 boolean changed = false; 11563 synchronized (mPackages) { 11564 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11565 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11566 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11567 .valueAt(i); 11568 if (userId != thisUserId) { 11569 continue; 11570 } 11571 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11572 while (it.hasNext()) { 11573 PersistentPreferredActivity ppa = it.next(); 11574 // Mark entry for removal only if it matches the package name. 11575 if (ppa.mComponent.getPackageName().equals(packageName)) { 11576 if (removed == null) { 11577 removed = new ArrayList<PersistentPreferredActivity>(); 11578 } 11579 removed.add(ppa); 11580 } 11581 } 11582 if (removed != null) { 11583 for (int j=0; j<removed.size(); j++) { 11584 PersistentPreferredActivity ppa = removed.get(j); 11585 ppir.removeFilter(ppa); 11586 } 11587 changed = true; 11588 } 11589 } 11590 11591 if (changed) { 11592 mSettings.writePackageRestrictionsLPr(userId); 11593 } 11594 } 11595 } 11596 11597 @Override 11598 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11599 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11600 mContext.enforceCallingOrSelfPermission( 11601 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11602 int callingUid = Binder.getCallingUid(); 11603 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11604 if (intentFilter.countActions() == 0) { 11605 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11606 return; 11607 } 11608 synchronized (mPackages) { 11609 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11610 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11611 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11612 mSettings.writePackageRestrictionsLPr(sourceUserId); 11613 } 11614 } 11615 11616 @Override 11617 public void addCrossProfileIntentsForPackage(String packageName, 11618 int sourceUserId, int targetUserId) { 11619 mContext.enforceCallingOrSelfPermission( 11620 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11621 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11622 mSettings.writePackageRestrictionsLPr(sourceUserId); 11623 } 11624 11625 @Override 11626 public void removeCrossProfileIntentsForPackage(String packageName, 11627 int sourceUserId, int targetUserId) { 11628 mContext.enforceCallingOrSelfPermission( 11629 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11630 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11631 mSettings.writePackageRestrictionsLPr(sourceUserId); 11632 } 11633 11634 @Override 11635 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11636 int ownerUserId) { 11637 mContext.enforceCallingOrSelfPermission( 11638 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11639 int callingUid = Binder.getCallingUid(); 11640 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11641 int callingUserId = UserHandle.getUserId(callingUid); 11642 synchronized (mPackages) { 11643 CrossProfileIntentResolver resolver = 11644 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11645 HashSet<CrossProfileIntentFilter> set = 11646 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11647 for (CrossProfileIntentFilter filter : set) { 11648 if (filter.getOwnerPackage().equals(ownerPackage) 11649 && filter.getOwnerUserId() == callingUserId) { 11650 resolver.removeFilter(filter); 11651 } 11652 } 11653 mSettings.writePackageRestrictionsLPr(sourceUserId); 11654 } 11655 } 11656 11657 // Enforcing that callingUid is owning pkg on userId 11658 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11659 // The system owns everything. 11660 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11661 return; 11662 } 11663 int callingUserId = UserHandle.getUserId(callingUid); 11664 if (callingUserId != userId) { 11665 throw new SecurityException("calling uid " + callingUid 11666 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11667 + callingUserId); 11668 } 11669 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11670 if (pi == null) { 11671 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11672 + callingUserId); 11673 } 11674 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11675 throw new SecurityException("Calling uid " + callingUid 11676 + " does not own package " + pkg); 11677 } 11678 } 11679 11680 @Override 11681 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11682 Intent intent = new Intent(Intent.ACTION_MAIN); 11683 intent.addCategory(Intent.CATEGORY_HOME); 11684 11685 final int callingUserId = UserHandle.getCallingUserId(); 11686 List<ResolveInfo> list = queryIntentActivities(intent, null, 11687 PackageManager.GET_META_DATA, callingUserId); 11688 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11689 true, false, false, callingUserId); 11690 11691 allHomeCandidates.clear(); 11692 if (list != null) { 11693 for (ResolveInfo ri : list) { 11694 allHomeCandidates.add(ri); 11695 } 11696 } 11697 return (preferred == null || preferred.activityInfo == null) 11698 ? null 11699 : new ComponentName(preferred.activityInfo.packageName, 11700 preferred.activityInfo.name); 11701 } 11702 11703 /** 11704 * Check if calling UID is the current home app. This handles both the case 11705 * where the user has selected a specific home app, and where there is only 11706 * one home app. 11707 */ 11708 public boolean checkCallerIsHomeApp() { 11709 final Intent intent = new Intent(Intent.ACTION_MAIN); 11710 intent.addCategory(Intent.CATEGORY_HOME); 11711 11712 final int callingUid = Binder.getCallingUid(); 11713 final int callingUserId = UserHandle.getCallingUserId(); 11714 final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId); 11715 final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true, 11716 false, false, callingUserId); 11717 11718 if (preferredHome != null) { 11719 if (callingUid == preferredHome.activityInfo.applicationInfo.uid) { 11720 return true; 11721 } 11722 } else { 11723 for (ResolveInfo info : allHomes) { 11724 if (callingUid == info.activityInfo.applicationInfo.uid) { 11725 return true; 11726 } 11727 } 11728 } 11729 11730 return false; 11731 } 11732 11733 /** 11734 * Enforce that calling UID is the current home app. This handles both the 11735 * case where the user has selected a specific home app, and where there is 11736 * only one home app. 11737 */ 11738 public void enforceCallerIsHomeApp() { 11739 if (!checkCallerIsHomeApp()) { 11740 throw new SecurityException("Caller is not currently selected home app"); 11741 } 11742 } 11743 11744 @Override 11745 public void setApplicationEnabledSetting(String appPackageName, 11746 int newState, int flags, int userId, String callingPackage) { 11747 if (!sUserManager.exists(userId)) return; 11748 if (callingPackage == null) { 11749 callingPackage = Integer.toString(Binder.getCallingUid()); 11750 } 11751 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11752 } 11753 11754 @Override 11755 public void setComponentEnabledSetting(ComponentName componentName, 11756 int newState, int flags, int userId) { 11757 if (!sUserManager.exists(userId)) return; 11758 setEnabledSetting(componentName.getPackageName(), 11759 componentName.getClassName(), newState, flags, userId, null); 11760 } 11761 11762 private void setEnabledSetting(final String packageName, String className, int newState, 11763 final int flags, int userId, String callingPackage) { 11764 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11765 || newState == COMPONENT_ENABLED_STATE_ENABLED 11766 || newState == COMPONENT_ENABLED_STATE_DISABLED 11767 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11768 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11769 throw new IllegalArgumentException("Invalid new component state: " 11770 + newState); 11771 } 11772 PackageSetting pkgSetting; 11773 final int uid = Binder.getCallingUid(); 11774 final int permission = mContext.checkCallingOrSelfPermission( 11775 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11776 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11777 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11778 boolean sendNow = false; 11779 boolean isApp = (className == null); 11780 String componentName = isApp ? packageName : className; 11781 int packageUid = -1; 11782 ArrayList<String> components; 11783 11784 // writer 11785 synchronized (mPackages) { 11786 pkgSetting = mSettings.mPackages.get(packageName); 11787 if (pkgSetting == null) { 11788 if (className == null) { 11789 throw new IllegalArgumentException( 11790 "Unknown package: " + packageName); 11791 } 11792 throw new IllegalArgumentException( 11793 "Unknown component: " + packageName 11794 + "/" + className); 11795 } 11796 // Allow root and verify that userId is not being specified by a different user 11797 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11798 throw new SecurityException( 11799 "Permission Denial: attempt to change component state from pid=" 11800 + Binder.getCallingPid() 11801 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11802 } 11803 if (className == null) { 11804 // We're dealing with an application/package level state change 11805 if (pkgSetting.getEnabled(userId) == newState) { 11806 // Nothing to do 11807 return; 11808 } 11809 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11810 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11811 // Don't care about who enables an app. 11812 callingPackage = null; 11813 } 11814 pkgSetting.setEnabled(newState, userId, callingPackage); 11815 // pkgSetting.pkg.mSetEnabled = newState; 11816 } else { 11817 // We're dealing with a component level state change 11818 // First, verify that this is a valid class name. 11819 PackageParser.Package pkg = pkgSetting.pkg; 11820 if (pkg == null || !pkg.hasComponentClassName(className)) { 11821 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11822 throw new IllegalArgumentException("Component class " + className 11823 + " does not exist in " + packageName); 11824 } else { 11825 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11826 + className + " does not exist in " + packageName); 11827 } 11828 } 11829 switch (newState) { 11830 case COMPONENT_ENABLED_STATE_ENABLED: 11831 if (!pkgSetting.enableComponentLPw(className, userId)) { 11832 return; 11833 } 11834 break; 11835 case COMPONENT_ENABLED_STATE_DISABLED: 11836 if (!pkgSetting.disableComponentLPw(className, userId)) { 11837 return; 11838 } 11839 break; 11840 case COMPONENT_ENABLED_STATE_DEFAULT: 11841 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11842 return; 11843 } 11844 break; 11845 default: 11846 Slog.e(TAG, "Invalid new component state: " + newState); 11847 return; 11848 } 11849 } 11850 mSettings.writePackageRestrictionsLPr(userId); 11851 components = mPendingBroadcasts.get(userId, packageName); 11852 final boolean newPackage = components == null; 11853 if (newPackage) { 11854 components = new ArrayList<String>(); 11855 } 11856 if (!components.contains(componentName)) { 11857 components.add(componentName); 11858 } 11859 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11860 sendNow = true; 11861 // Purge entry from pending broadcast list if another one exists already 11862 // since we are sending one right away. 11863 mPendingBroadcasts.remove(userId, packageName); 11864 } else { 11865 if (newPackage) { 11866 mPendingBroadcasts.put(userId, packageName, components); 11867 } 11868 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11869 // Schedule a message 11870 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11871 } 11872 } 11873 } 11874 11875 long callingId = Binder.clearCallingIdentity(); 11876 try { 11877 if (sendNow) { 11878 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11879 sendPackageChangedBroadcast(packageName, 11880 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11881 } 11882 } finally { 11883 Binder.restoreCallingIdentity(callingId); 11884 } 11885 } 11886 11887 private void sendPackageChangedBroadcast(String packageName, 11888 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11889 if (DEBUG_INSTALL) 11890 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11891 + componentNames); 11892 Bundle extras = new Bundle(4); 11893 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11894 String nameList[] = new String[componentNames.size()]; 11895 componentNames.toArray(nameList); 11896 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11897 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11898 extras.putInt(Intent.EXTRA_UID, packageUid); 11899 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11900 new int[] {UserHandle.getUserId(packageUid)}); 11901 } 11902 11903 @Override 11904 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11905 if (!sUserManager.exists(userId)) return; 11906 final int uid = Binder.getCallingUid(); 11907 final int permission = mContext.checkCallingOrSelfPermission( 11908 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11909 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11910 enforceCrossUserPermission(uid, userId, true, "stop package"); 11911 // writer 11912 synchronized (mPackages) { 11913 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11914 uid, userId)) { 11915 scheduleWritePackageRestrictionsLocked(userId); 11916 } 11917 } 11918 } 11919 11920 @Override 11921 public String getInstallerPackageName(String packageName) { 11922 // reader 11923 synchronized (mPackages) { 11924 return mSettings.getInstallerPackageNameLPr(packageName); 11925 } 11926 } 11927 11928 @Override 11929 public int getApplicationEnabledSetting(String packageName, int userId) { 11930 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11931 int uid = Binder.getCallingUid(); 11932 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11933 // reader 11934 synchronized (mPackages) { 11935 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11936 } 11937 } 11938 11939 @Override 11940 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11941 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11942 int uid = Binder.getCallingUid(); 11943 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11944 // reader 11945 synchronized (mPackages) { 11946 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11947 } 11948 } 11949 11950 @Override 11951 public void enterSafeMode() { 11952 enforceSystemOrRoot("Only the system can request entering safe mode"); 11953 11954 if (!mSystemReady) { 11955 mSafeMode = true; 11956 } 11957 } 11958 11959 @Override 11960 public void systemReady() { 11961 mSystemReady = true; 11962 11963 // Read the compatibilty setting when the system is ready. 11964 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11965 mContext.getContentResolver(), 11966 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11967 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11968 if (DEBUG_SETTINGS) { 11969 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11970 } 11971 11972 synchronized (mPackages) { 11973 // Verify that all of the preferred activity components actually 11974 // exist. It is possible for applications to be updated and at 11975 // that point remove a previously declared activity component that 11976 // had been set as a preferred activity. We try to clean this up 11977 // the next time we encounter that preferred activity, but it is 11978 // possible for the user flow to never be able to return to that 11979 // situation so here we do a sanity check to make sure we haven't 11980 // left any junk around. 11981 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11982 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11983 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11984 removed.clear(); 11985 for (PreferredActivity pa : pir.filterSet()) { 11986 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11987 removed.add(pa); 11988 } 11989 } 11990 if (removed.size() > 0) { 11991 for (int r=0; r<removed.size(); r++) { 11992 PreferredActivity pa = removed.get(r); 11993 Slog.w(TAG, "Removing dangling preferred activity: " 11994 + pa.mPref.mComponent); 11995 pir.removeFilter(pa); 11996 } 11997 mSettings.writePackageRestrictionsLPr( 11998 mSettings.mPreferredActivities.keyAt(i)); 11999 } 12000 } 12001 } 12002 sUserManager.systemReady(); 12003 } 12004 12005 @Override 12006 public boolean isSafeMode() { 12007 return mSafeMode; 12008 } 12009 12010 @Override 12011 public boolean hasSystemUidErrors() { 12012 return mHasSystemUidErrors; 12013 } 12014 12015 static String arrayToString(int[] array) { 12016 StringBuffer buf = new StringBuffer(128); 12017 buf.append('['); 12018 if (array != null) { 12019 for (int i=0; i<array.length; i++) { 12020 if (i > 0) buf.append(", "); 12021 buf.append(array[i]); 12022 } 12023 } 12024 buf.append(']'); 12025 return buf.toString(); 12026 } 12027 12028 static class DumpState { 12029 public static final int DUMP_LIBS = 1 << 0; 12030 public static final int DUMP_FEATURES = 1 << 1; 12031 public static final int DUMP_RESOLVERS = 1 << 2; 12032 public static final int DUMP_PERMISSIONS = 1 << 3; 12033 public static final int DUMP_PACKAGES = 1 << 4; 12034 public static final int DUMP_SHARED_USERS = 1 << 5; 12035 public static final int DUMP_MESSAGES = 1 << 6; 12036 public static final int DUMP_PROVIDERS = 1 << 7; 12037 public static final int DUMP_VERIFIERS = 1 << 8; 12038 public static final int DUMP_PREFERRED = 1 << 9; 12039 public static final int DUMP_PREFERRED_XML = 1 << 10; 12040 public static final int DUMP_KEYSETS = 1 << 11; 12041 public static final int DUMP_VERSION = 1 << 12; 12042 public static final int DUMP_INSTALLS = 1 << 13; 12043 12044 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12045 12046 private int mTypes; 12047 12048 private int mOptions; 12049 12050 private boolean mTitlePrinted; 12051 12052 private SharedUserSetting mSharedUser; 12053 12054 public boolean isDumping(int type) { 12055 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12056 return true; 12057 } 12058 12059 return (mTypes & type) != 0; 12060 } 12061 12062 public void setDump(int type) { 12063 mTypes |= type; 12064 } 12065 12066 public boolean isOptionEnabled(int option) { 12067 return (mOptions & option) != 0; 12068 } 12069 12070 public void setOptionEnabled(int option) { 12071 mOptions |= option; 12072 } 12073 12074 public boolean onTitlePrinted() { 12075 final boolean printed = mTitlePrinted; 12076 mTitlePrinted = true; 12077 return printed; 12078 } 12079 12080 public boolean getTitlePrinted() { 12081 return mTitlePrinted; 12082 } 12083 12084 public void setTitlePrinted(boolean enabled) { 12085 mTitlePrinted = enabled; 12086 } 12087 12088 public SharedUserSetting getSharedUser() { 12089 return mSharedUser; 12090 } 12091 12092 public void setSharedUser(SharedUserSetting user) { 12093 mSharedUser = user; 12094 } 12095 } 12096 12097 @Override 12098 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12099 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12100 != PackageManager.PERMISSION_GRANTED) { 12101 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12102 + Binder.getCallingPid() 12103 + ", uid=" + Binder.getCallingUid() 12104 + " without permission " 12105 + android.Manifest.permission.DUMP); 12106 return; 12107 } 12108 12109 DumpState dumpState = new DumpState(); 12110 boolean fullPreferred = false; 12111 boolean checkin = false; 12112 12113 String packageName = null; 12114 12115 int opti = 0; 12116 while (opti < args.length) { 12117 String opt = args[opti]; 12118 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12119 break; 12120 } 12121 opti++; 12122 if ("-a".equals(opt)) { 12123 // Right now we only know how to print all. 12124 } else if ("-h".equals(opt)) { 12125 pw.println("Package manager dump options:"); 12126 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12127 pw.println(" --checkin: dump for a checkin"); 12128 pw.println(" -f: print details of intent filters"); 12129 pw.println(" -h: print this help"); 12130 pw.println(" cmd may be one of:"); 12131 pw.println(" l[ibraries]: list known shared libraries"); 12132 pw.println(" f[ibraries]: list device features"); 12133 pw.println(" k[eysets]: print known keysets"); 12134 pw.println(" r[esolvers]: dump intent resolvers"); 12135 pw.println(" perm[issions]: dump permissions"); 12136 pw.println(" pref[erred]: print preferred package settings"); 12137 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12138 pw.println(" prov[iders]: dump content providers"); 12139 pw.println(" p[ackages]: dump installed packages"); 12140 pw.println(" s[hared-users]: dump shared user IDs"); 12141 pw.println(" m[essages]: print collected runtime messages"); 12142 pw.println(" v[erifiers]: print package verifier info"); 12143 pw.println(" version: print database version info"); 12144 pw.println(" write: write current settings now"); 12145 pw.println(" <package.name>: info about given package"); 12146 pw.println(" installs: details about install sessions"); 12147 return; 12148 } else if ("--checkin".equals(opt)) { 12149 checkin = true; 12150 } else if ("-f".equals(opt)) { 12151 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12152 } else { 12153 pw.println("Unknown argument: " + opt + "; use -h for help"); 12154 } 12155 } 12156 12157 // Is the caller requesting to dump a particular piece of data? 12158 if (opti < args.length) { 12159 String cmd = args[opti]; 12160 opti++; 12161 // Is this a package name? 12162 if ("android".equals(cmd) || cmd.contains(".")) { 12163 packageName = cmd; 12164 // When dumping a single package, we always dump all of its 12165 // filter information since the amount of data will be reasonable. 12166 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12167 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12168 dumpState.setDump(DumpState.DUMP_LIBS); 12169 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12170 dumpState.setDump(DumpState.DUMP_FEATURES); 12171 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12172 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12173 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12174 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12175 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12176 dumpState.setDump(DumpState.DUMP_PREFERRED); 12177 } else if ("preferred-xml".equals(cmd)) { 12178 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12179 if (opti < args.length && "--full".equals(args[opti])) { 12180 fullPreferred = true; 12181 opti++; 12182 } 12183 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12184 dumpState.setDump(DumpState.DUMP_PACKAGES); 12185 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12186 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12187 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12188 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12189 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12190 dumpState.setDump(DumpState.DUMP_MESSAGES); 12191 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12192 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12193 } else if ("version".equals(cmd)) { 12194 dumpState.setDump(DumpState.DUMP_VERSION); 12195 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12196 dumpState.setDump(DumpState.DUMP_KEYSETS); 12197 } else if ("write".equals(cmd)) { 12198 synchronized (mPackages) { 12199 mSettings.writeLPr(); 12200 pw.println("Settings written."); 12201 return; 12202 } 12203 } else if ("installs".equals(cmd)) { 12204 dumpState.setDump(DumpState.DUMP_INSTALLS); 12205 } 12206 } 12207 12208 if (checkin) { 12209 pw.println("vers,1"); 12210 } 12211 12212 // reader 12213 synchronized (mPackages) { 12214 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12215 if (!checkin) { 12216 if (dumpState.onTitlePrinted()) 12217 pw.println(); 12218 pw.println("Database versions:"); 12219 pw.print(" SDK Version:"); 12220 pw.print(" internal="); 12221 pw.print(mSettings.mInternalSdkPlatform); 12222 pw.print(" external="); 12223 pw.println(mSettings.mExternalSdkPlatform); 12224 pw.print(" DB Version:"); 12225 pw.print(" internal="); 12226 pw.print(mSettings.mInternalDatabaseVersion); 12227 pw.print(" external="); 12228 pw.println(mSettings.mExternalDatabaseVersion); 12229 } 12230 } 12231 12232 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12233 if (!checkin) { 12234 if (dumpState.onTitlePrinted()) 12235 pw.println(); 12236 pw.println("Verifiers:"); 12237 pw.print(" Required: "); 12238 pw.print(mRequiredVerifierPackage); 12239 pw.print(" (uid="); 12240 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12241 pw.println(")"); 12242 } else if (mRequiredVerifierPackage != null) { 12243 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12244 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12245 } 12246 } 12247 12248 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12249 boolean printedHeader = false; 12250 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12251 while (it.hasNext()) { 12252 String name = it.next(); 12253 SharedLibraryEntry ent = mSharedLibraries.get(name); 12254 if (!checkin) { 12255 if (!printedHeader) { 12256 if (dumpState.onTitlePrinted()) 12257 pw.println(); 12258 pw.println("Libraries:"); 12259 printedHeader = true; 12260 } 12261 pw.print(" "); 12262 } else { 12263 pw.print("lib,"); 12264 } 12265 pw.print(name); 12266 if (!checkin) { 12267 pw.print(" -> "); 12268 } 12269 if (ent.path != null) { 12270 if (!checkin) { 12271 pw.print("(jar) "); 12272 pw.print(ent.path); 12273 } else { 12274 pw.print(",jar,"); 12275 pw.print(ent.path); 12276 } 12277 } else { 12278 if (!checkin) { 12279 pw.print("(apk) "); 12280 pw.print(ent.apk); 12281 } else { 12282 pw.print(",apk,"); 12283 pw.print(ent.apk); 12284 } 12285 } 12286 pw.println(); 12287 } 12288 } 12289 12290 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12291 if (dumpState.onTitlePrinted()) 12292 pw.println(); 12293 if (!checkin) { 12294 pw.println("Features:"); 12295 } 12296 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12297 while (it.hasNext()) { 12298 String name = it.next(); 12299 if (!checkin) { 12300 pw.print(" "); 12301 } else { 12302 pw.print("feat,"); 12303 } 12304 pw.println(name); 12305 } 12306 } 12307 12308 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12309 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12310 : "Activity Resolver Table:", " ", packageName, 12311 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12312 dumpState.setTitlePrinted(true); 12313 } 12314 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12315 : "Receiver Resolver Table:", " ", packageName, 12316 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12317 dumpState.setTitlePrinted(true); 12318 } 12319 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12320 : "Service Resolver Table:", " ", packageName, 12321 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12322 dumpState.setTitlePrinted(true); 12323 } 12324 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12325 : "Provider Resolver Table:", " ", packageName, 12326 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12327 dumpState.setTitlePrinted(true); 12328 } 12329 } 12330 12331 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12332 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12333 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12334 int user = mSettings.mPreferredActivities.keyAt(i); 12335 if (pir.dump(pw, 12336 dumpState.getTitlePrinted() 12337 ? "\nPreferred Activities User " + user + ":" 12338 : "Preferred Activities User " + user + ":", " ", 12339 packageName, true)) { 12340 dumpState.setTitlePrinted(true); 12341 } 12342 } 12343 } 12344 12345 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12346 pw.flush(); 12347 FileOutputStream fout = new FileOutputStream(fd); 12348 BufferedOutputStream str = new BufferedOutputStream(fout); 12349 XmlSerializer serializer = new FastXmlSerializer(); 12350 try { 12351 serializer.setOutput(str, "utf-8"); 12352 serializer.startDocument(null, true); 12353 serializer.setFeature( 12354 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12355 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12356 serializer.endDocument(); 12357 serializer.flush(); 12358 } catch (IllegalArgumentException e) { 12359 pw.println("Failed writing: " + e); 12360 } catch (IllegalStateException e) { 12361 pw.println("Failed writing: " + e); 12362 } catch (IOException e) { 12363 pw.println("Failed writing: " + e); 12364 } 12365 } 12366 12367 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12368 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12369 if (packageName == null) { 12370 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12371 if (iperm == 0) { 12372 if (dumpState.onTitlePrinted()) 12373 pw.println(); 12374 pw.println("AppOp Permissions:"); 12375 } 12376 pw.print(" AppOp Permission "); 12377 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12378 pw.println(":"); 12379 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12380 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12381 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12382 } 12383 } 12384 } 12385 } 12386 12387 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12388 boolean printedSomething = false; 12389 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12390 if (packageName != null && !packageName.equals(p.info.packageName)) { 12391 continue; 12392 } 12393 if (!printedSomething) { 12394 if (dumpState.onTitlePrinted()) 12395 pw.println(); 12396 pw.println("Registered ContentProviders:"); 12397 printedSomething = true; 12398 } 12399 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12400 pw.print(" "); pw.println(p.toString()); 12401 } 12402 printedSomething = false; 12403 for (Map.Entry<String, PackageParser.Provider> entry : 12404 mProvidersByAuthority.entrySet()) { 12405 PackageParser.Provider p = entry.getValue(); 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("ContentProvider Authorities:"); 12413 printedSomething = true; 12414 } 12415 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12416 pw.print(" "); pw.println(p.toString()); 12417 if (p.info != null && p.info.applicationInfo != null) { 12418 final String appInfo = p.info.applicationInfo.toString(); 12419 pw.print(" applicationInfo="); pw.println(appInfo); 12420 } 12421 } 12422 } 12423 12424 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12425 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12426 } 12427 12428 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12429 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12430 } 12431 12432 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12433 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12434 } 12435 12436 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12437 if (dumpState.onTitlePrinted()) pw.println(); 12438 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12439 } 12440 12441 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12442 if (dumpState.onTitlePrinted()) pw.println(); 12443 mSettings.dumpReadMessagesLPr(pw, dumpState); 12444 12445 pw.println(); 12446 pw.println("Package warning messages:"); 12447 final File fname = getSettingsProblemFile(); 12448 FileInputStream in = null; 12449 try { 12450 in = new FileInputStream(fname); 12451 final int avail = in.available(); 12452 final byte[] data = new byte[avail]; 12453 in.read(data); 12454 pw.print(new String(data)); 12455 } catch (FileNotFoundException e) { 12456 } catch (IOException e) { 12457 } finally { 12458 if (in != null) { 12459 try { 12460 in.close(); 12461 } catch (IOException e) { 12462 } 12463 } 12464 } 12465 } 12466 } 12467 } 12468 12469 // ------- apps on sdcard specific code ------- 12470 static final boolean DEBUG_SD_INSTALL = false; 12471 12472 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12473 12474 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12475 12476 private boolean mMediaMounted = false; 12477 12478 static String getEncryptKey() { 12479 try { 12480 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12481 SD_ENCRYPTION_KEYSTORE_NAME); 12482 if (sdEncKey == null) { 12483 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12484 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12485 if (sdEncKey == null) { 12486 Slog.e(TAG, "Failed to create encryption keys"); 12487 return null; 12488 } 12489 } 12490 return sdEncKey; 12491 } catch (NoSuchAlgorithmException nsae) { 12492 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12493 return null; 12494 } catch (IOException ioe) { 12495 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12496 return null; 12497 } 12498 } 12499 12500 /* 12501 * Update media status on PackageManager. 12502 */ 12503 @Override 12504 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12505 int callingUid = Binder.getCallingUid(); 12506 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12507 throw new SecurityException("Media status can only be updated by the system"); 12508 } 12509 // reader; this apparently protects mMediaMounted, but should probably 12510 // be a different lock in that case. 12511 synchronized (mPackages) { 12512 Log.i(TAG, "Updating external media status from " 12513 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12514 + (mediaStatus ? "mounted" : "unmounted")); 12515 if (DEBUG_SD_INSTALL) 12516 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12517 + ", mMediaMounted=" + mMediaMounted); 12518 if (mediaStatus == mMediaMounted) { 12519 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12520 : 0, -1); 12521 mHandler.sendMessage(msg); 12522 return; 12523 } 12524 mMediaMounted = mediaStatus; 12525 } 12526 // Queue up an async operation since the package installation may take a 12527 // little while. 12528 mHandler.post(new Runnable() { 12529 public void run() { 12530 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12531 } 12532 }); 12533 } 12534 12535 /** 12536 * Called by MountService when the initial ASECs to scan are available. 12537 * Should block until all the ASEC containers are finished being scanned. 12538 */ 12539 public void scanAvailableAsecs() { 12540 updateExternalMediaStatusInner(true, false, false); 12541 if (mShouldRestoreconData) { 12542 SELinuxMMAC.setRestoreconDone(); 12543 mShouldRestoreconData = false; 12544 } 12545 } 12546 12547 /* 12548 * Collect information of applications on external media, map them against 12549 * existing containers and update information based on current mount status. 12550 * Please note that we always have to report status if reportStatus has been 12551 * set to true especially when unloading packages. 12552 */ 12553 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12554 boolean externalStorage) { 12555 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12556 int[] uidArr = EmptyArray.INT; 12557 12558 final String[] list = PackageHelper.getSecureContainerList(); 12559 if (ArrayUtils.isEmpty(list)) { 12560 Log.i(TAG, "No secure containers found"); 12561 } else { 12562 // Process list of secure containers and categorize them 12563 // as active or stale based on their package internal state. 12564 12565 // reader 12566 synchronized (mPackages) { 12567 for (String cid : list) { 12568 // Leave stages untouched for now; installer service owns them 12569 if (PackageInstallerService.isStageName(cid)) continue; 12570 12571 if (DEBUG_SD_INSTALL) 12572 Log.i(TAG, "Processing container " + cid); 12573 String pkgName = getAsecPackageName(cid); 12574 if (pkgName == null) { 12575 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12576 continue; 12577 } 12578 if (DEBUG_SD_INSTALL) 12579 Log.i(TAG, "Looking for pkg : " + pkgName); 12580 12581 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12582 if (ps == null) { 12583 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12584 continue; 12585 } 12586 12587 /* 12588 * Skip packages that are not external if we're unmounting 12589 * external storage. 12590 */ 12591 if (externalStorage && !isMounted && !isExternal(ps)) { 12592 continue; 12593 } 12594 12595 final AsecInstallArgs args = new AsecInstallArgs(cid, 12596 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12597 // The package status is changed only if the code path 12598 // matches between settings and the container id. 12599 if (ps.codePathString != null 12600 && ps.codePathString.startsWith(args.getCodePath())) { 12601 if (DEBUG_SD_INSTALL) { 12602 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12603 + " at code path: " + ps.codePathString); 12604 } 12605 12606 // We do have a valid package installed on sdcard 12607 processCids.put(args, ps.codePathString); 12608 final int uid = ps.appId; 12609 if (uid != -1) { 12610 uidArr = ArrayUtils.appendInt(uidArr, uid); 12611 } 12612 } else { 12613 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12614 + ps.codePathString); 12615 } 12616 } 12617 } 12618 12619 Arrays.sort(uidArr); 12620 } 12621 12622 // Process packages with valid entries. 12623 if (isMounted) { 12624 if (DEBUG_SD_INSTALL) 12625 Log.i(TAG, "Loading packages"); 12626 loadMediaPackages(processCids, uidArr); 12627 startCleaningPackages(); 12628 mInstallerService.onSecureContainersAvailable(); 12629 } else { 12630 if (DEBUG_SD_INSTALL) 12631 Log.i(TAG, "Unloading packages"); 12632 unloadMediaPackages(processCids, uidArr, reportStatus); 12633 } 12634 } 12635 12636 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12637 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12638 int size = pkgList.size(); 12639 if (size > 0) { 12640 // Send broadcasts here 12641 Bundle extras = new Bundle(); 12642 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12643 .toArray(new String[size])); 12644 if (uidArr != null) { 12645 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12646 } 12647 if (replacing) { 12648 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12649 } 12650 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12651 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12652 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12653 } 12654 } 12655 12656 /* 12657 * Look at potentially valid container ids from processCids If package 12658 * information doesn't match the one on record or package scanning fails, 12659 * the cid is added to list of removeCids. We currently don't delete stale 12660 * containers. 12661 */ 12662 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12663 ArrayList<String> pkgList = new ArrayList<String>(); 12664 Set<AsecInstallArgs> keys = processCids.keySet(); 12665 12666 for (AsecInstallArgs args : keys) { 12667 String codePath = processCids.get(args); 12668 if (DEBUG_SD_INSTALL) 12669 Log.i(TAG, "Loading container : " + args.cid); 12670 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12671 try { 12672 // Make sure there are no container errors first. 12673 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12674 Slog.e(TAG, "Failed to mount cid : " + args.cid 12675 + " when installing from sdcard"); 12676 continue; 12677 } 12678 // Check code path here. 12679 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12680 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12681 + " does not match one in settings " + codePath); 12682 continue; 12683 } 12684 // Parse package 12685 int parseFlags = mDefParseFlags; 12686 if (args.isExternal()) { 12687 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12688 } 12689 if (args.isFwdLocked()) { 12690 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12691 } 12692 12693 synchronized (mInstallLock) { 12694 PackageParser.Package pkg = null; 12695 try { 12696 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12697 } catch (PackageManagerException e) { 12698 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12699 } 12700 // Scan the package 12701 if (pkg != null) { 12702 /* 12703 * TODO why is the lock being held? doPostInstall is 12704 * called in other places without the lock. This needs 12705 * to be straightened out. 12706 */ 12707 // writer 12708 synchronized (mPackages) { 12709 retCode = PackageManager.INSTALL_SUCCEEDED; 12710 pkgList.add(pkg.packageName); 12711 // Post process args 12712 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12713 pkg.applicationInfo.uid); 12714 } 12715 } else { 12716 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12717 } 12718 } 12719 12720 } finally { 12721 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12722 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12723 } 12724 } 12725 } 12726 // writer 12727 synchronized (mPackages) { 12728 // If the platform SDK has changed since the last time we booted, 12729 // we need to re-grant app permission to catch any new ones that 12730 // appear. This is really a hack, and means that apps can in some 12731 // cases get permissions that the user didn't initially explicitly 12732 // allow... it would be nice to have some better way to handle 12733 // this situation. 12734 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12735 if (regrantPermissions) 12736 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12737 + mSdkVersion + "; regranting permissions for external storage"); 12738 mSettings.mExternalSdkPlatform = mSdkVersion; 12739 12740 // Make sure group IDs have been assigned, and any permission 12741 // changes in other apps are accounted for 12742 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12743 | (regrantPermissions 12744 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12745 : 0)); 12746 12747 mSettings.updateExternalDatabaseVersion(); 12748 12749 // can downgrade to reader 12750 // Persist settings 12751 mSettings.writeLPr(); 12752 } 12753 // Send a broadcast to let everyone know we are done processing 12754 if (pkgList.size() > 0) { 12755 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12756 } 12757 } 12758 12759 /* 12760 * Utility method to unload a list of specified containers 12761 */ 12762 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12763 // Just unmount all valid containers. 12764 for (AsecInstallArgs arg : cidArgs) { 12765 synchronized (mInstallLock) { 12766 arg.doPostDeleteLI(false); 12767 } 12768 } 12769 } 12770 12771 /* 12772 * Unload packages mounted on external media. This involves deleting package 12773 * data from internal structures, sending broadcasts about diabled packages, 12774 * gc'ing to free up references, unmounting all secure containers 12775 * corresponding to packages on external media, and posting a 12776 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12777 * that we always have to post this message if status has been requested no 12778 * matter what. 12779 */ 12780 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12781 final boolean reportStatus) { 12782 if (DEBUG_SD_INSTALL) 12783 Log.i(TAG, "unloading media packages"); 12784 ArrayList<String> pkgList = new ArrayList<String>(); 12785 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12786 final Set<AsecInstallArgs> keys = processCids.keySet(); 12787 for (AsecInstallArgs args : keys) { 12788 String pkgName = args.getPackageName(); 12789 if (DEBUG_SD_INSTALL) 12790 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12791 // Delete package internally 12792 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12793 synchronized (mInstallLock) { 12794 boolean res = deletePackageLI(pkgName, null, false, null, null, 12795 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12796 if (res) { 12797 pkgList.add(pkgName); 12798 } else { 12799 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12800 failedList.add(args); 12801 } 12802 } 12803 } 12804 12805 // reader 12806 synchronized (mPackages) { 12807 // We didn't update the settings after removing each package; 12808 // write them now for all packages. 12809 mSettings.writeLPr(); 12810 } 12811 12812 // We have to absolutely send UPDATED_MEDIA_STATUS only 12813 // after confirming that all the receivers processed the ordered 12814 // broadcast when packages get disabled, force a gc to clean things up. 12815 // and unload all the containers. 12816 if (pkgList.size() > 0) { 12817 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12818 new IIntentReceiver.Stub() { 12819 public void performReceive(Intent intent, int resultCode, String data, 12820 Bundle extras, boolean ordered, boolean sticky, 12821 int sendingUser) throws RemoteException { 12822 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12823 reportStatus ? 1 : 0, 1, keys); 12824 mHandler.sendMessage(msg); 12825 } 12826 }); 12827 } else { 12828 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12829 keys); 12830 mHandler.sendMessage(msg); 12831 } 12832 } 12833 12834 /** Binder call */ 12835 @Override 12836 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12837 final int flags) { 12838 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12839 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12840 int returnCode = PackageManager.MOVE_SUCCEEDED; 12841 int currInstallFlags = 0; 12842 int newInstallFlags = 0; 12843 12844 File codeFile = null; 12845 String installerPackageName = null; 12846 String packageAbiOverride = null; 12847 12848 // reader 12849 synchronized (mPackages) { 12850 final PackageParser.Package pkg = mPackages.get(packageName); 12851 final PackageSetting ps = mSettings.mPackages.get(packageName); 12852 if (pkg == null || ps == null) { 12853 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12854 } else { 12855 // Disable moving fwd locked apps and system packages 12856 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12857 Slog.w(TAG, "Cannot move system application"); 12858 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12859 } else if (pkg.mOperationPending) { 12860 Slog.w(TAG, "Attempt to move package which has pending operations"); 12861 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12862 } else { 12863 // Find install location first 12864 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12865 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12866 Slog.w(TAG, "Ambigous flags specified for move location."); 12867 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12868 } else { 12869 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12870 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12871 currInstallFlags = isExternal(pkg) 12872 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12873 12874 if (newInstallFlags == currInstallFlags) { 12875 Slog.w(TAG, "No move required. Trying to move to same location"); 12876 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12877 } else { 12878 if (isForwardLocked(pkg)) { 12879 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12880 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12881 } 12882 } 12883 } 12884 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12885 pkg.mOperationPending = true; 12886 } 12887 } 12888 12889 codeFile = new File(pkg.codePath); 12890 installerPackageName = ps.installerPackageName; 12891 packageAbiOverride = ps.cpuAbiOverrideString; 12892 } 12893 } 12894 12895 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12896 try { 12897 observer.packageMoved(packageName, returnCode); 12898 } catch (RemoteException ignored) { 12899 } 12900 return; 12901 } 12902 12903 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 12904 @Override 12905 public void onUserActionRequired(Intent intent) throws RemoteException { 12906 throw new IllegalStateException(); 12907 } 12908 12909 @Override 12910 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 12911 Bundle extras) throws RemoteException { 12912 Slog.d(TAG, "Install result for move: " 12913 + PackageManager.installStatusToString(returnCode, msg)); 12914 final int status = PackageManager.installStatusToPublicStatus(returnCode); 12915 switch (status) { 12916 case PackageInstaller.STATUS_SUCCESS: 12917 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 12918 break; 12919 case PackageInstaller.STATUS_FAILURE_STORAGE: 12920 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 12921 break; 12922 default: 12923 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 12924 break; 12925 } 12926 } 12927 }; 12928 12929 // Treat a move like reinstalling an existing app, which ensures that we 12930 // process everythign uniformly, like unpacking native libraries. 12931 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 12932 12933 final Message msg = mHandler.obtainMessage(INIT_COPY); 12934 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 12935 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 12936 installerPackageName, null, user, packageAbiOverride); 12937 mHandler.sendMessage(msg); 12938 } 12939 12940 @Override 12941 public boolean setInstallLocation(int loc) { 12942 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12943 null); 12944 if (getInstallLocation() == loc) { 12945 return true; 12946 } 12947 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12948 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12949 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12950 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12951 return true; 12952 } 12953 return false; 12954 } 12955 12956 @Override 12957 public int getInstallLocation() { 12958 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12959 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12960 PackageHelper.APP_INSTALL_AUTO); 12961 } 12962 12963 /** Called by UserManagerService */ 12964 void cleanUpUserLILPw(int userHandle) { 12965 mDirtyUsers.remove(userHandle); 12966 mSettings.removeUserLPw(userHandle); 12967 mPendingBroadcasts.remove(userHandle); 12968 if (mInstaller != null) { 12969 // Technically, we shouldn't be doing this with the package lock 12970 // held. However, this is very rare, and there is already so much 12971 // other disk I/O going on, that we'll let it slide for now. 12972 mInstaller.removeUserDataDirs(userHandle); 12973 } 12974 mUserNeedsBadging.delete(userHandle); 12975 } 12976 12977 /** Called by UserManagerService */ 12978 void createNewUserLILPw(int userHandle, File path) { 12979 if (mInstaller != null) { 12980 mInstaller.createUserConfig(userHandle); 12981 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 12982 } 12983 } 12984 12985 @Override 12986 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 12987 mContext.enforceCallingOrSelfPermission( 12988 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12989 "Only package verification agents can read the verifier device identity"); 12990 12991 synchronized (mPackages) { 12992 return mSettings.getVerifierDeviceIdentityLPw(); 12993 } 12994 } 12995 12996 @Override 12997 public void setPermissionEnforced(String permission, boolean enforced) { 12998 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 12999 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13000 synchronized (mPackages) { 13001 if (mSettings.mReadExternalStorageEnforced == null 13002 || mSettings.mReadExternalStorageEnforced != enforced) { 13003 mSettings.mReadExternalStorageEnforced = enforced; 13004 mSettings.writeLPr(); 13005 } 13006 } 13007 // kill any non-foreground processes so we restart them and 13008 // grant/revoke the GID. 13009 final IActivityManager am = ActivityManagerNative.getDefault(); 13010 if (am != null) { 13011 final long token = Binder.clearCallingIdentity(); 13012 try { 13013 am.killProcessesBelowForeground("setPermissionEnforcement"); 13014 } catch (RemoteException e) { 13015 } finally { 13016 Binder.restoreCallingIdentity(token); 13017 } 13018 } 13019 } else { 13020 throw new IllegalArgumentException("No selective enforcement for " + permission); 13021 } 13022 } 13023 13024 @Override 13025 @Deprecated 13026 public boolean isPermissionEnforced(String permission) { 13027 return true; 13028 } 13029 13030 @Override 13031 public boolean isStorageLow() { 13032 final long token = Binder.clearCallingIdentity(); 13033 try { 13034 final DeviceStorageMonitorInternal 13035 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13036 if (dsm != null) { 13037 return dsm.isMemoryLow(); 13038 } else { 13039 return false; 13040 } 13041 } finally { 13042 Binder.restoreCallingIdentity(token); 13043 } 13044 } 13045 13046 @Override 13047 public IPackageInstaller getPackageInstaller() { 13048 return mInstallerService; 13049 } 13050 13051 private boolean userNeedsBadging(int userId) { 13052 int index = mUserNeedsBadging.indexOfKey(userId); 13053 if (index < 0) { 13054 final UserInfo userInfo; 13055 final long token = Binder.clearCallingIdentity(); 13056 try { 13057 userInfo = sUserManager.getUserInfo(userId); 13058 } finally { 13059 Binder.restoreCallingIdentity(token); 13060 } 13061 final boolean b; 13062 if (userInfo != null && userInfo.isManagedProfile()) { 13063 b = true; 13064 } else { 13065 b = false; 13066 } 13067 mUserNeedsBadging.put(userId, b); 13068 return b; 13069 } 13070 return mUserNeedsBadging.valueAt(index); 13071 } 13072 13073 @Override 13074 public KeySetHandle getKeySetByAlias(String packageName, String alias) { 13075 if (packageName == null || alias == null) { 13076 return null; 13077 } 13078 synchronized(mPackages) { 13079 final PackageParser.Package pkg = mPackages.get(packageName); 13080 if (pkg == null) { 13081 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13082 throw new IllegalArgumentException("Unknown package: " + packageName); 13083 } 13084 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13085 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13086 throw new SecurityException("May not access KeySets defined by" 13087 + " aliases in other applications."); 13088 } 13089 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13090 return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias); 13091 } 13092 } 13093 13094 @Override 13095 public KeySetHandle getSigningKeySet(String packageName) { 13096 if (packageName == null) { 13097 return null; 13098 } 13099 synchronized(mPackages) { 13100 final PackageParser.Package pkg = mPackages.get(packageName); 13101 if (pkg == null) { 13102 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13103 throw new IllegalArgumentException("Unknown package: " + packageName); 13104 } 13105 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13106 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13107 throw new SecurityException("May not access signing KeySet of other apps."); 13108 } 13109 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13110 return ksms.getSigningKeySetByPackageNameLPr(packageName); 13111 } 13112 } 13113 13114 @Override 13115 public boolean isPackageSignedByKeySet(String packageName, IBinder ks) { 13116 if (packageName == null || ks == null) { 13117 return false; 13118 } 13119 synchronized(mPackages) { 13120 final PackageParser.Package pkg = mPackages.get(packageName); 13121 if (pkg == null) { 13122 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13123 throw new IllegalArgumentException("Unknown package: " + packageName); 13124 } 13125 if (ks instanceof KeySetHandle) { 13126 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13127 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks); 13128 } 13129 return false; 13130 } 13131 } 13132 13133 @Override 13134 public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) { 13135 if (packageName == null || ks == null) { 13136 return false; 13137 } 13138 synchronized(mPackages) { 13139 final PackageParser.Package pkg = mPackages.get(packageName); 13140 if (pkg == null) { 13141 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13142 throw new IllegalArgumentException("Unknown package: " + packageName); 13143 } 13144 if (ks instanceof KeySetHandle) { 13145 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13146 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks); 13147 } 13148 return false; 13149 } 13150 } 13151} 13152