PackageManagerService.java revision d9a6475c9c4825b2d8fc5ea09b9de54ad4f91ee3
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.Manifest.permission.INSTALL_PACKAGES; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.os.Process.PACKAGE_INFO_GID; 28import static android.os.Process.SYSTEM_UID; 29import static android.system.OsConstants.S_IRGRP; 30import static android.system.OsConstants.S_IROTH; 31import static android.system.OsConstants.S_IRWXU; 32import static android.system.OsConstants.S_IXGRP; 33import static android.system.OsConstants.S_IXOTH; 34import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 35import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 36import static com.android.internal.util.ArrayUtils.appendInt; 37import static com.android.internal.util.ArrayUtils.removeInt; 38 39import com.android.internal.R; 40import com.android.internal.app.IMediaContainerService; 41import com.android.internal.app.ResolverActivity; 42import com.android.internal.content.NativeLibraryHelper; 43import com.android.internal.content.PackageHelper; 44import com.android.internal.util.FastPrintWriter; 45import com.android.internal.util.FastXmlSerializer; 46import com.android.internal.util.XmlUtils; 47import com.android.server.EventLogTags; 48import com.android.server.IntentResolver; 49import com.android.server.LocalServices; 50import com.android.server.ServiceThread; 51import com.android.server.Watchdog; 52import com.android.server.pm.Settings.DatabaseVersion; 53import com.android.server.storage.DeviceStorageMonitorInternal; 54import com.android.server.storage.DeviceStorageMonitorInternal; 55 56import org.xmlpull.v1.XmlPullParser; 57import org.xmlpull.v1.XmlPullParserException; 58import org.xmlpull.v1.XmlSerializer; 59 60import android.app.ActivityManager; 61import android.app.ActivityManagerNative; 62import android.app.IActivityManager; 63import android.app.PackageInstallObserver; 64import android.app.admin.IDevicePolicyManager; 65import android.app.backup.IBackupManager; 66import android.content.BroadcastReceiver; 67import android.content.ComponentName; 68import android.content.Context; 69import android.content.IIntentReceiver; 70import android.content.Intent; 71import android.content.IntentFilter; 72import android.content.IntentSender; 73import android.content.IntentSender.SendIntentException; 74import android.content.ServiceConnection; 75import android.content.pm.ActivityInfo; 76import android.content.pm.ApplicationInfo; 77import android.content.pm.ContainerEncryptionParams; 78import android.content.pm.FeatureInfo; 79import android.content.pm.IPackageDataObserver; 80import android.content.pm.IPackageDeleteObserver; 81import android.content.pm.IPackageInstallObserver; 82import android.content.pm.IPackageInstallObserver2; 83import android.content.pm.IPackageInstaller; 84import android.content.pm.IPackageManager; 85import android.content.pm.IPackageMoveObserver; 86import android.content.pm.IPackageStatsObserver; 87import android.content.pm.InstrumentationInfo; 88import android.content.pm.ManifestDigest; 89import android.content.pm.PackageCleanItem; 90import android.content.pm.PackageInfo; 91import android.content.pm.PackageInfoLite; 92import android.content.pm.PackageInstallerParams; 93import android.content.pm.PackageManager; 94import android.content.pm.PackageParser.ActivityIntentInfo; 95import android.content.pm.PackageParser; 96import android.content.pm.PackageStats; 97import android.content.pm.PackageUserState; 98import android.content.pm.ParceledListSlice; 99import android.content.pm.PermissionGroupInfo; 100import android.content.pm.PermissionInfo; 101import android.content.pm.ProviderInfo; 102import android.content.pm.ResolveInfo; 103import android.content.pm.ServiceInfo; 104import android.content.pm.Signature; 105import android.content.pm.VerificationParams; 106import android.content.pm.VerifierDeviceIdentity; 107import android.content.pm.VerifierInfo; 108import android.content.res.Resources; 109import android.hardware.display.DisplayManager; 110import android.net.Uri; 111import android.os.Binder; 112import android.os.Build; 113import android.os.Bundle; 114import android.os.Environment; 115import android.os.Environment.UserEnvironment; 116import android.os.FileObserver; 117import android.os.FileUtils; 118import android.os.Handler; 119import android.os.IBinder; 120import android.os.Looper; 121import android.os.Message; 122import android.os.Parcel; 123import android.os.ParcelFileDescriptor; 124import android.os.Process; 125import android.os.RemoteException; 126import android.os.SELinux; 127import android.os.ServiceManager; 128import android.os.SystemClock; 129import android.os.SystemProperties; 130import android.os.UserHandle; 131import android.os.UserManager; 132import android.security.KeyStore; 133import android.security.SystemKeyStore; 134import android.system.ErrnoException; 135import android.system.Os; 136import android.system.StructStat; 137import android.text.TextUtils; 138import android.util.AtomicFile; 139import android.util.DisplayMetrics; 140import android.util.EventLog; 141import android.util.Log; 142import android.util.LogPrinter; 143import android.util.PrintStreamPrinter; 144import android.util.Slog; 145import android.util.SparseArray; 146import android.util.Xml; 147import android.view.Display; 148 149import java.io.BufferedInputStream; 150import java.io.BufferedOutputStream; 151import java.io.File; 152import java.io.FileDescriptor; 153import java.io.FileInputStream; 154import java.io.FileNotFoundException; 155import java.io.FileOutputStream; 156import java.io.FileReader; 157import java.io.FilenameFilter; 158import java.io.IOException; 159import java.io.InputStream; 160import java.io.PrintWriter; 161import java.nio.charset.StandardCharsets; 162import java.security.NoSuchAlgorithmException; 163import java.security.PublicKey; 164import java.security.cert.CertificateEncodingException; 165import java.security.cert.CertificateException; 166import java.text.SimpleDateFormat; 167import java.util.ArrayList; 168import java.util.Arrays; 169import java.util.Collection; 170import java.util.Collections; 171import java.util.Comparator; 172import java.util.Date; 173import java.util.HashMap; 174import java.util.HashSet; 175import java.util.Iterator; 176import java.util.List; 177import java.util.Map; 178import java.util.Set; 179import java.util.concurrent.atomic.AtomicBoolean; 180import java.util.concurrent.atomic.AtomicLong; 181 182import dalvik.system.DexFile; 183import dalvik.system.StaleDexCacheError; 184import dalvik.system.VMRuntime; 185 186import libcore.io.IoUtils; 187 188/** 189 * Keep track of all those .apks everywhere. 190 * 191 * This is very central to the platform's security; please run the unit 192 * tests whenever making modifications here: 193 * 194mmm frameworks/base/tests/AndroidTests 195adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 196adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 197 * 198 * {@hide} 199 */ 200public class PackageManagerService extends IPackageManager.Stub { 201 static final String TAG = "PackageManager"; 202 static final boolean DEBUG_SETTINGS = false; 203 static final boolean DEBUG_PREFERRED = false; 204 static final boolean DEBUG_UPGRADE = false; 205 private static final boolean DEBUG_INSTALL = false; 206 private static final boolean DEBUG_REMOVE = false; 207 private static final boolean DEBUG_BROADCASTS = false; 208 private static final boolean DEBUG_SHOW_INFO = false; 209 private static final boolean DEBUG_PACKAGE_INFO = false; 210 private static final boolean DEBUG_INTENT_MATCHING = false; 211 private static final boolean DEBUG_PACKAGE_SCANNING = false; 212 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 213 private static final boolean DEBUG_VERIFY = false; 214 private static final boolean DEBUG_DEXOPT = false; 215 216 private static final int RADIO_UID = Process.PHONE_UID; 217 private static final int LOG_UID = Process.LOG_UID; 218 private static final int NFC_UID = Process.NFC_UID; 219 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 220 private static final int SHELL_UID = Process.SHELL_UID; 221 222 // Cap the size of permission trees that 3rd party apps can define 223 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 224 225 private static final int REMOVE_EVENTS = 226 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 227 private static final int ADD_EVENTS = 228 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 229 230 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 231 // Suffix used during package installation when copying/moving 232 // package apks to install directory. 233 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 234 235 static final int SCAN_MONITOR = 1<<0; 236 static final int SCAN_NO_DEX = 1<<1; 237 static final int SCAN_FORCE_DEX = 1<<2; 238 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 239 static final int SCAN_NEW_INSTALL = 1<<4; 240 static final int SCAN_NO_PATHS = 1<<5; 241 static final int SCAN_UPDATE_TIME = 1<<6; 242 static final int SCAN_DEFER_DEX = 1<<7; 243 static final int SCAN_BOOTING = 1<<8; 244 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 245 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 246 247 static final int REMOVE_CHATTY = 1<<16; 248 249 /** 250 * Timeout (in milliseconds) after which the watchdog should declare that 251 * our handler thread is wedged. The usual default for such things is one 252 * minute but we sometimes do very lengthy I/O operations on this thread, 253 * such as installing multi-gigabyte applications, so ours needs to be longer. 254 */ 255 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 256 257 /** 258 * Whether verification is enabled by default. 259 */ 260 private static final boolean DEFAULT_VERIFY_ENABLE = true; 261 262 /** 263 * The default maximum time to wait for the verification agent to return in 264 * milliseconds. 265 */ 266 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 267 268 /** 269 * The default response for package verification timeout. 270 * 271 * This can be either PackageManager.VERIFICATION_ALLOW or 272 * PackageManager.VERIFICATION_REJECT. 273 */ 274 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 275 276 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 277 278 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 279 DEFAULT_CONTAINER_PACKAGE, 280 "com.android.defcontainer.DefaultContainerService"); 281 282 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 283 284 private static final String LIB_DIR_NAME = "lib"; 285 private static final String LIB64_DIR_NAME = "lib64"; 286 287 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 288 289 static final String mTempContainerPrefix = "smdl2tmp"; 290 291 private static String sPreferredInstructionSet; 292 293 final ServiceThread mHandlerThread; 294 295 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 296 private static final String IDMAP_SUFFIX = "@idmap"; 297 298 final PackageHandler mHandler; 299 300 final int mSdkVersion = Build.VERSION.SDK_INT; 301 302 final Context mContext; 303 final boolean mFactoryTest; 304 final boolean mOnlyCore; 305 final DisplayMetrics mMetrics; 306 final int mDefParseFlags; 307 final String[] mSeparateProcesses; 308 309 // This is where all application persistent data goes. 310 final File mAppDataDir; 311 312 // This is where all application persistent data goes for secondary users. 313 final File mUserAppDataDir; 314 315 /** The location for ASEC container files on internal storage. */ 316 final String mAsecInternalPath; 317 318 // This is the object monitoring the framework dir. 319 final FileObserver mFrameworkInstallObserver; 320 321 // This is the object monitoring the system app dir. 322 final FileObserver mSystemInstallObserver; 323 324 // This is the object monitoring the privileged system app dir. 325 final FileObserver mPrivilegedInstallObserver; 326 327 // This is the object monitoring the vendor app dir. 328 final FileObserver mVendorInstallObserver; 329 330 // This is the object monitoring the vendor overlay package dir. 331 final FileObserver mVendorOverlayInstallObserver; 332 333 // This is the object monitoring the OEM app dir. 334 final FileObserver mOemInstallObserver; 335 336 // This is the object monitoring mAppInstallDir. 337 final FileObserver mAppInstallObserver; 338 339 // This is the object monitoring mDrmAppPrivateInstallDir. 340 final FileObserver mDrmAppInstallObserver; 341 342 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 343 // LOCK HELD. Can be called with mInstallLock held. 344 final Installer mInstaller; 345 346 final File mAppInstallDir; 347 348 /** 349 * Directory to which applications installed internally have native 350 * libraries copied. 351 */ 352 private File mAppLibInstallDir; 353 354 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 355 // apps. 356 final File mDrmAppPrivateInstallDir; 357 358 final File mAppStagingDir; 359 360 // ---------------------------------------------------------------- 361 362 // Lock for state used when installing and doing other long running 363 // operations. Methods that must be called with this lock held have 364 // the suffix "LI". 365 final Object mInstallLock = new Object(); 366 367 // These are the directories in the 3rd party applications installed dir 368 // that we have currently loaded packages from. Keys are the application's 369 // installed zip file (absolute codePath), and values are Package. 370 final HashMap<String, PackageParser.Package> mAppDirs = 371 new HashMap<String, PackageParser.Package>(); 372 373 // Information for the parser to write more useful error messages. 374 int mLastScanError; 375 376 // ---------------------------------------------------------------- 377 378 // Keys are String (package name), values are Package. This also serves 379 // as the lock for the global state. Methods that must be called with 380 // this lock held have the prefix "LP". 381 final HashMap<String, PackageParser.Package> mPackages = 382 new HashMap<String, PackageParser.Package>(); 383 384 // Tracks available target package names -> overlay package paths. 385 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 386 new HashMap<String, HashMap<String, PackageParser.Package>>(); 387 388 final Settings mSettings; 389 boolean mRestoredSettings; 390 391 // Group-ids that are given to all packages as read from etc/permissions/*.xml. 392 int[] mGlobalGids; 393 394 // These are the built-in uid -> permission mappings that were read from the 395 // etc/permissions.xml file. 396 final SparseArray<HashSet<String>> mSystemPermissions = 397 new SparseArray<HashSet<String>>(); 398 399 static final class SharedLibraryEntry { 400 final String path; 401 final String apk; 402 403 SharedLibraryEntry(String _path, String _apk) { 404 path = _path; 405 apk = _apk; 406 } 407 } 408 409 // These are the built-in shared libraries that were read from the 410 // etc/permissions.xml file. 411 final HashMap<String, SharedLibraryEntry> mSharedLibraries 412 = new HashMap<String, SharedLibraryEntry>(); 413 414 // Temporary for building the final shared libraries for an .apk. 415 String[] mTmpSharedLibraries = null; 416 417 // These are the features this devices supports that were read from the 418 // etc/permissions.xml file. 419 final HashMap<String, FeatureInfo> mAvailableFeatures = 420 new HashMap<String, FeatureInfo>(); 421 422 // If mac_permissions.xml was found for seinfo labeling. 423 boolean mFoundPolicyFile; 424 425 // If a recursive restorecon of /data/data/<pkg> is needed. 426 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 427 428 // All available activities, for your resolving pleasure. 429 final ActivityIntentResolver mActivities = 430 new ActivityIntentResolver(); 431 432 // All available receivers, for your resolving pleasure. 433 final ActivityIntentResolver mReceivers = 434 new ActivityIntentResolver(); 435 436 // All available services, for your resolving pleasure. 437 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 438 439 // All available providers, for your resolving pleasure. 440 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 441 442 // Mapping from provider base names (first directory in content URI codePath) 443 // to the provider information. 444 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 445 new HashMap<String, PackageParser.Provider>(); 446 447 // Mapping from instrumentation class names to info about them. 448 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 449 new HashMap<ComponentName, PackageParser.Instrumentation>(); 450 451 // Mapping from permission names to info about them. 452 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 453 new HashMap<String, PackageParser.PermissionGroup>(); 454 455 // Packages whose data we have transfered into another package, thus 456 // should no longer exist. 457 final HashSet<String> mTransferedPackages = new HashSet<String>(); 458 459 // Broadcast actions that are only available to the system. 460 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 461 462 /** List of packages waiting for verification. */ 463 final SparseArray<PackageVerificationState> mPendingVerification 464 = new SparseArray<PackageVerificationState>(); 465 466 final PackageInstallerService mInstallerService; 467 468 HashSet<PackageParser.Package> mDeferredDexOpt = null; 469 470 /** Token for keys in mPendingVerification. */ 471 private int mPendingVerificationToken = 0; 472 473 boolean mSystemReady; 474 boolean mSafeMode; 475 boolean mHasSystemUidErrors; 476 477 ApplicationInfo mAndroidApplication; 478 final ActivityInfo mResolveActivity = new ActivityInfo(); 479 final ResolveInfo mResolveInfo = new ResolveInfo(); 480 ComponentName mResolveComponentName; 481 PackageParser.Package mPlatformPackage; 482 ComponentName mCustomResolverComponentName; 483 484 boolean mResolverReplaced = false; 485 486 // Set of pending broadcasts for aggregating enable/disable of components. 487 static class PendingPackageBroadcasts { 488 // for each user id, a map of <package name -> components within that package> 489 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 490 491 public PendingPackageBroadcasts() { 492 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 493 } 494 495 public ArrayList<String> get(int userId, String packageName) { 496 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 497 return packages.get(packageName); 498 } 499 500 public void put(int userId, String packageName, ArrayList<String> components) { 501 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 502 packages.put(packageName, components); 503 } 504 505 public void remove(int userId, String packageName) { 506 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 507 if (packages != null) { 508 packages.remove(packageName); 509 } 510 } 511 512 public void remove(int userId) { 513 mUidMap.remove(userId); 514 } 515 516 public int userIdCount() { 517 return mUidMap.size(); 518 } 519 520 public int userIdAt(int n) { 521 return mUidMap.keyAt(n); 522 } 523 524 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 525 return mUidMap.get(userId); 526 } 527 528 public int size() { 529 // total number of pending broadcast entries across all userIds 530 int num = 0; 531 for (int i = 0; i< mUidMap.size(); i++) { 532 num += mUidMap.valueAt(i).size(); 533 } 534 return num; 535 } 536 537 public void clear() { 538 mUidMap.clear(); 539 } 540 541 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 542 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 543 if (map == null) { 544 map = new HashMap<String, ArrayList<String>>(); 545 mUidMap.put(userId, map); 546 } 547 return map; 548 } 549 } 550 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 551 552 // Service Connection to remote media container service to copy 553 // package uri's from external media onto secure containers 554 // or internal storage. 555 private IMediaContainerService mContainerService = null; 556 557 static final int SEND_PENDING_BROADCAST = 1; 558 static final int MCS_BOUND = 3; 559 static final int END_COPY = 4; 560 static final int INIT_COPY = 5; 561 static final int MCS_UNBIND = 6; 562 static final int START_CLEANING_PACKAGE = 7; 563 static final int FIND_INSTALL_LOC = 8; 564 static final int POST_INSTALL = 9; 565 static final int MCS_RECONNECT = 10; 566 static final int MCS_GIVE_UP = 11; 567 static final int UPDATED_MEDIA_STATUS = 12; 568 static final int WRITE_SETTINGS = 13; 569 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 570 static final int PACKAGE_VERIFIED = 15; 571 static final int CHECK_PENDING_VERIFICATION = 16; 572 573 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 574 575 // Delay time in millisecs 576 static final int BROADCAST_DELAY = 10 * 1000; 577 578 static UserManagerService sUserManager; 579 580 // Stores a list of users whose package restrictions file needs to be updated 581 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 582 583 final private DefaultContainerConnection mDefContainerConn = 584 new DefaultContainerConnection(); 585 class DefaultContainerConnection implements ServiceConnection { 586 public void onServiceConnected(ComponentName name, IBinder service) { 587 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 588 IMediaContainerService imcs = 589 IMediaContainerService.Stub.asInterface(service); 590 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 591 } 592 593 public void onServiceDisconnected(ComponentName name) { 594 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 595 } 596 }; 597 598 // Recordkeeping of restore-after-install operations that are currently in flight 599 // between the Package Manager and the Backup Manager 600 class PostInstallData { 601 public InstallArgs args; 602 public PackageInstalledInfo res; 603 604 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 605 args = _a; 606 res = _r; 607 } 608 }; 609 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 610 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 611 612 private final String mRequiredVerifierPackage; 613 614 private final PackageUsage mPackageUsage = new PackageUsage(); 615 616 private class PackageUsage { 617 private static final int WRITE_INTERVAL 618 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 619 620 private final Object mFileLock = new Object(); 621 private final AtomicLong mLastWritten = new AtomicLong(0); 622 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 623 624 private boolean mIsFirstBoot = false; 625 626 boolean isFirstBoot() { 627 return mIsFirstBoot; 628 } 629 630 void write(boolean force) { 631 if (force) { 632 writeInternal(); 633 return; 634 } 635 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 636 && !DEBUG_DEXOPT) { 637 return; 638 } 639 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 640 new Thread("PackageUsage_DiskWriter") { 641 @Override 642 public void run() { 643 try { 644 writeInternal(); 645 } finally { 646 mBackgroundWriteRunning.set(false); 647 } 648 } 649 }.start(); 650 } 651 } 652 653 private void writeInternal() { 654 synchronized (mPackages) { 655 synchronized (mFileLock) { 656 AtomicFile file = getFile(); 657 FileOutputStream f = null; 658 try { 659 f = file.startWrite(); 660 BufferedOutputStream out = new BufferedOutputStream(f); 661 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 662 StringBuilder sb = new StringBuilder(); 663 for (PackageParser.Package pkg : mPackages.values()) { 664 if (pkg.mLastPackageUsageTimeInMills == 0) { 665 continue; 666 } 667 sb.setLength(0); 668 sb.append(pkg.packageName); 669 sb.append(' '); 670 sb.append((long)pkg.mLastPackageUsageTimeInMills); 671 sb.append('\n'); 672 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 673 } 674 out.flush(); 675 file.finishWrite(f); 676 } catch (IOException e) { 677 if (f != null) { 678 file.failWrite(f); 679 } 680 Log.e(TAG, "Failed to write package usage times", e); 681 } 682 } 683 } 684 mLastWritten.set(SystemClock.elapsedRealtime()); 685 } 686 687 void readLP() { 688 synchronized (mFileLock) { 689 AtomicFile file = getFile(); 690 BufferedInputStream in = null; 691 try { 692 in = new BufferedInputStream(file.openRead()); 693 StringBuffer sb = new StringBuffer(); 694 while (true) { 695 String packageName = readToken(in, sb, ' '); 696 if (packageName == null) { 697 break; 698 } 699 String timeInMillisString = readToken(in, sb, '\n'); 700 if (timeInMillisString == null) { 701 throw new IOException("Failed to find last usage time for package " 702 + packageName); 703 } 704 PackageParser.Package pkg = mPackages.get(packageName); 705 if (pkg == null) { 706 continue; 707 } 708 long timeInMillis; 709 try { 710 timeInMillis = Long.parseLong(timeInMillisString.toString()); 711 } catch (NumberFormatException e) { 712 throw new IOException("Failed to parse " + timeInMillisString 713 + " as a long.", e); 714 } 715 pkg.mLastPackageUsageTimeInMills = timeInMillis; 716 } 717 } catch (FileNotFoundException expected) { 718 mIsFirstBoot = true; 719 } catch (IOException e) { 720 Log.w(TAG, "Failed to read package usage times", e); 721 } finally { 722 IoUtils.closeQuietly(in); 723 } 724 } 725 mLastWritten.set(SystemClock.elapsedRealtime()); 726 } 727 728 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 729 throws IOException { 730 sb.setLength(0); 731 while (true) { 732 int ch = in.read(); 733 if (ch == -1) { 734 if (sb.length() == 0) { 735 return null; 736 } 737 throw new IOException("Unexpected EOF"); 738 } 739 if (ch == endOfToken) { 740 return sb.toString(); 741 } 742 sb.append((char)ch); 743 } 744 } 745 746 private AtomicFile getFile() { 747 File dataDir = Environment.getDataDirectory(); 748 File systemDir = new File(dataDir, "system"); 749 File fname = new File(systemDir, "package-usage.list"); 750 return new AtomicFile(fname); 751 } 752 } 753 754 class PackageHandler extends Handler { 755 private boolean mBound = false; 756 final ArrayList<HandlerParams> mPendingInstalls = 757 new ArrayList<HandlerParams>(); 758 759 private boolean connectToService() { 760 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 761 " DefaultContainerService"); 762 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 763 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 764 if (mContext.bindServiceAsUser(service, mDefContainerConn, 765 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 766 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 767 mBound = true; 768 return true; 769 } 770 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 771 return false; 772 } 773 774 private void disconnectService() { 775 mContainerService = null; 776 mBound = false; 777 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 778 mContext.unbindService(mDefContainerConn); 779 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 780 } 781 782 PackageHandler(Looper looper) { 783 super(looper); 784 } 785 786 public void handleMessage(Message msg) { 787 try { 788 doHandleMessage(msg); 789 } finally { 790 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 791 } 792 } 793 794 void doHandleMessage(Message msg) { 795 switch (msg.what) { 796 case INIT_COPY: { 797 HandlerParams params = (HandlerParams) msg.obj; 798 int idx = mPendingInstalls.size(); 799 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 800 // If a bind was already initiated we dont really 801 // need to do anything. The pending install 802 // will be processed later on. 803 if (!mBound) { 804 // If this is the only one pending we might 805 // have to bind to the service again. 806 if (!connectToService()) { 807 Slog.e(TAG, "Failed to bind to media container service"); 808 params.serviceError(); 809 return; 810 } else { 811 // Once we bind to the service, the first 812 // pending request will be processed. 813 mPendingInstalls.add(idx, params); 814 } 815 } else { 816 mPendingInstalls.add(idx, params); 817 // Already bound to the service. Just make 818 // sure we trigger off processing the first request. 819 if (idx == 0) { 820 mHandler.sendEmptyMessage(MCS_BOUND); 821 } 822 } 823 break; 824 } 825 case MCS_BOUND: { 826 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 827 if (msg.obj != null) { 828 mContainerService = (IMediaContainerService) msg.obj; 829 } 830 if (mContainerService == null) { 831 // Something seriously wrong. Bail out 832 Slog.e(TAG, "Cannot bind to media container service"); 833 for (HandlerParams params : mPendingInstalls) { 834 // Indicate service bind error 835 params.serviceError(); 836 } 837 mPendingInstalls.clear(); 838 } else if (mPendingInstalls.size() > 0) { 839 HandlerParams params = mPendingInstalls.get(0); 840 if (params != null) { 841 if (params.startCopy()) { 842 // We are done... look for more work or to 843 // go idle. 844 if (DEBUG_SD_INSTALL) Log.i(TAG, 845 "Checking for more work or unbind..."); 846 // Delete pending install 847 if (mPendingInstalls.size() > 0) { 848 mPendingInstalls.remove(0); 849 } 850 if (mPendingInstalls.size() == 0) { 851 if (mBound) { 852 if (DEBUG_SD_INSTALL) Log.i(TAG, 853 "Posting delayed MCS_UNBIND"); 854 removeMessages(MCS_UNBIND); 855 Message ubmsg = obtainMessage(MCS_UNBIND); 856 // Unbind after a little delay, to avoid 857 // continual thrashing. 858 sendMessageDelayed(ubmsg, 10000); 859 } 860 } else { 861 // There are more pending requests in queue. 862 // Just post MCS_BOUND message to trigger processing 863 // of next pending install. 864 if (DEBUG_SD_INSTALL) Log.i(TAG, 865 "Posting MCS_BOUND for next work"); 866 mHandler.sendEmptyMessage(MCS_BOUND); 867 } 868 } 869 } 870 } else { 871 // Should never happen ideally. 872 Slog.w(TAG, "Empty queue"); 873 } 874 break; 875 } 876 case MCS_RECONNECT: { 877 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 878 if (mPendingInstalls.size() > 0) { 879 if (mBound) { 880 disconnectService(); 881 } 882 if (!connectToService()) { 883 Slog.e(TAG, "Failed to bind to media container service"); 884 for (HandlerParams params : mPendingInstalls) { 885 // Indicate service bind error 886 params.serviceError(); 887 } 888 mPendingInstalls.clear(); 889 } 890 } 891 break; 892 } 893 case MCS_UNBIND: { 894 // If there is no actual work left, then time to unbind. 895 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 896 897 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 898 if (mBound) { 899 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 900 901 disconnectService(); 902 } 903 } else if (mPendingInstalls.size() > 0) { 904 // There are more pending requests in queue. 905 // Just post MCS_BOUND message to trigger processing 906 // of next pending install. 907 mHandler.sendEmptyMessage(MCS_BOUND); 908 } 909 910 break; 911 } 912 case MCS_GIVE_UP: { 913 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 914 mPendingInstalls.remove(0); 915 break; 916 } 917 case SEND_PENDING_BROADCAST: { 918 String packages[]; 919 ArrayList<String> components[]; 920 int size = 0; 921 int uids[]; 922 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 923 synchronized (mPackages) { 924 if (mPendingBroadcasts == null) { 925 return; 926 } 927 size = mPendingBroadcasts.size(); 928 if (size <= 0) { 929 // Nothing to be done. Just return 930 return; 931 } 932 packages = new String[size]; 933 components = new ArrayList[size]; 934 uids = new int[size]; 935 int i = 0; // filling out the above arrays 936 937 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 938 int packageUserId = mPendingBroadcasts.userIdAt(n); 939 Iterator<Map.Entry<String, ArrayList<String>>> it 940 = mPendingBroadcasts.packagesForUserId(packageUserId) 941 .entrySet().iterator(); 942 while (it.hasNext() && i < size) { 943 Map.Entry<String, ArrayList<String>> ent = it.next(); 944 packages[i] = ent.getKey(); 945 components[i] = ent.getValue(); 946 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 947 uids[i] = (ps != null) 948 ? UserHandle.getUid(packageUserId, ps.appId) 949 : -1; 950 i++; 951 } 952 } 953 size = i; 954 mPendingBroadcasts.clear(); 955 } 956 // Send broadcasts 957 for (int i = 0; i < size; i++) { 958 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 959 } 960 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 961 break; 962 } 963 case START_CLEANING_PACKAGE: { 964 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 965 final String packageName = (String)msg.obj; 966 final int userId = msg.arg1; 967 final boolean andCode = msg.arg2 != 0; 968 synchronized (mPackages) { 969 if (userId == UserHandle.USER_ALL) { 970 int[] users = sUserManager.getUserIds(); 971 for (int user : users) { 972 mSettings.addPackageToCleanLPw( 973 new PackageCleanItem(user, packageName, andCode)); 974 } 975 } else { 976 mSettings.addPackageToCleanLPw( 977 new PackageCleanItem(userId, packageName, andCode)); 978 } 979 } 980 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 981 startCleaningPackages(); 982 } break; 983 case POST_INSTALL: { 984 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 985 PostInstallData data = mRunningInstalls.get(msg.arg1); 986 mRunningInstalls.delete(msg.arg1); 987 boolean deleteOld = false; 988 989 if (data != null) { 990 InstallArgs args = data.args; 991 PackageInstalledInfo res = data.res; 992 993 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 994 res.removedInfo.sendBroadcast(false, true, false); 995 Bundle extras = new Bundle(1); 996 extras.putInt(Intent.EXTRA_UID, res.uid); 997 // Determine the set of users who are adding this 998 // package for the first time vs. those who are seeing 999 // an update. 1000 int[] firstUsers; 1001 int[] updateUsers = new int[0]; 1002 if (res.origUsers == null || res.origUsers.length == 0) { 1003 firstUsers = res.newUsers; 1004 } else { 1005 firstUsers = new int[0]; 1006 for (int i=0; i<res.newUsers.length; i++) { 1007 int user = res.newUsers[i]; 1008 boolean isNew = true; 1009 for (int j=0; j<res.origUsers.length; j++) { 1010 if (res.origUsers[j] == user) { 1011 isNew = false; 1012 break; 1013 } 1014 } 1015 if (isNew) { 1016 int[] newFirst = new int[firstUsers.length+1]; 1017 System.arraycopy(firstUsers, 0, newFirst, 0, 1018 firstUsers.length); 1019 newFirst[firstUsers.length] = user; 1020 firstUsers = newFirst; 1021 } else { 1022 int[] newUpdate = new int[updateUsers.length+1]; 1023 System.arraycopy(updateUsers, 0, newUpdate, 0, 1024 updateUsers.length); 1025 newUpdate[updateUsers.length] = user; 1026 updateUsers = newUpdate; 1027 } 1028 } 1029 } 1030 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1031 res.pkg.applicationInfo.packageName, 1032 extras, null, null, firstUsers); 1033 final boolean update = res.removedInfo.removedPackage != null; 1034 if (update) { 1035 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1036 } 1037 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1038 res.pkg.applicationInfo.packageName, 1039 extras, null, null, updateUsers); 1040 if (update) { 1041 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1042 res.pkg.applicationInfo.packageName, 1043 extras, null, null, updateUsers); 1044 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1045 null, null, 1046 res.pkg.applicationInfo.packageName, null, updateUsers); 1047 1048 // treat asec-hosted packages like removable media on upgrade 1049 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1050 if (DEBUG_INSTALL) { 1051 Slog.i(TAG, "upgrading pkg " + res.pkg 1052 + " is ASEC-hosted -> AVAILABLE"); 1053 } 1054 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1055 ArrayList<String> pkgList = new ArrayList<String>(1); 1056 pkgList.add(res.pkg.applicationInfo.packageName); 1057 sendResourcesChangedBroadcast(true, true, 1058 pkgList,uidArray, null); 1059 } 1060 } 1061 if (res.removedInfo.args != null) { 1062 // Remove the replaced package's older resources safely now 1063 deleteOld = true; 1064 } 1065 1066 // Log current value of "unknown sources" setting 1067 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1068 getUnknownSourcesSettings()); 1069 } 1070 // Force a gc to clear up things 1071 Runtime.getRuntime().gc(); 1072 // We delete after a gc for applications on sdcard. 1073 if (deleteOld) { 1074 synchronized (mInstallLock) { 1075 res.removedInfo.args.doPostDeleteLI(true); 1076 } 1077 } 1078 if (args.observer != null) { 1079 try { 1080 args.observer.packageInstalled(res.name, res.returnCode); 1081 } catch (RemoteException e) { 1082 Slog.i(TAG, "Observer no longer exists."); 1083 } 1084 } 1085 if (args.observer2 != null) { 1086 try { 1087 Bundle extras = extrasForInstallResult(res); 1088 args.observer2.packageInstalled(res.name, extras, res.returnCode); 1089 } catch (RemoteException e) { 1090 Slog.i(TAG, "Observer no longer exists."); 1091 } 1092 } 1093 } else { 1094 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1095 } 1096 } break; 1097 case UPDATED_MEDIA_STATUS: { 1098 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1099 boolean reportStatus = msg.arg1 == 1; 1100 boolean doGc = msg.arg2 == 1; 1101 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1102 if (doGc) { 1103 // Force a gc to clear up stale containers. 1104 Runtime.getRuntime().gc(); 1105 } 1106 if (msg.obj != null) { 1107 @SuppressWarnings("unchecked") 1108 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1109 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1110 // Unload containers 1111 unloadAllContainers(args); 1112 } 1113 if (reportStatus) { 1114 try { 1115 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1116 PackageHelper.getMountService().finishMediaUpdate(); 1117 } catch (RemoteException e) { 1118 Log.e(TAG, "MountService not running?"); 1119 } 1120 } 1121 } break; 1122 case WRITE_SETTINGS: { 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1124 synchronized (mPackages) { 1125 removeMessages(WRITE_SETTINGS); 1126 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1127 mSettings.writeLPr(); 1128 mDirtyUsers.clear(); 1129 } 1130 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1131 } break; 1132 case WRITE_PACKAGE_RESTRICTIONS: { 1133 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1134 synchronized (mPackages) { 1135 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1136 for (int userId : mDirtyUsers) { 1137 mSettings.writePackageRestrictionsLPr(userId); 1138 } 1139 mDirtyUsers.clear(); 1140 } 1141 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1142 } break; 1143 case CHECK_PENDING_VERIFICATION: { 1144 final int verificationId = msg.arg1; 1145 final PackageVerificationState state = mPendingVerification.get(verificationId); 1146 1147 if ((state != null) && !state.timeoutExtended()) { 1148 final InstallArgs args = state.getInstallArgs(); 1149 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString()); 1150 mPendingVerification.remove(verificationId); 1151 1152 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1153 1154 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1155 Slog.i(TAG, "Continuing with installation of " 1156 + args.packageURI.toString()); 1157 state.setVerifierResponse(Binder.getCallingUid(), 1158 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1159 broadcastPackageVerified(verificationId, args.packageURI, 1160 PackageManager.VERIFICATION_ALLOW, 1161 state.getInstallArgs().getUser()); 1162 try { 1163 ret = args.copyApk(mContainerService, true); 1164 } catch (RemoteException e) { 1165 Slog.e(TAG, "Could not contact the ContainerService"); 1166 } 1167 } else { 1168 broadcastPackageVerified(verificationId, args.packageURI, 1169 PackageManager.VERIFICATION_REJECT, 1170 state.getInstallArgs().getUser()); 1171 } 1172 1173 processPendingInstall(args, ret); 1174 mHandler.sendEmptyMessage(MCS_UNBIND); 1175 } 1176 break; 1177 } 1178 case PACKAGE_VERIFIED: { 1179 final int verificationId = msg.arg1; 1180 1181 final PackageVerificationState state = mPendingVerification.get(verificationId); 1182 if (state == null) { 1183 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1184 break; 1185 } 1186 1187 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1188 1189 state.setVerifierResponse(response.callerUid, response.code); 1190 1191 if (state.isVerificationComplete()) { 1192 mPendingVerification.remove(verificationId); 1193 1194 final InstallArgs args = state.getInstallArgs(); 1195 1196 int ret; 1197 if (state.isInstallAllowed()) { 1198 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1199 broadcastPackageVerified(verificationId, args.packageURI, 1200 response.code, state.getInstallArgs().getUser()); 1201 try { 1202 ret = args.copyApk(mContainerService, true); 1203 } catch (RemoteException e) { 1204 Slog.e(TAG, "Could not contact the ContainerService"); 1205 } 1206 } else { 1207 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1208 } 1209 1210 processPendingInstall(args, ret); 1211 1212 mHandler.sendEmptyMessage(MCS_UNBIND); 1213 } 1214 1215 break; 1216 } 1217 } 1218 } 1219 } 1220 1221 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1222 Bundle extras = null; 1223 switch (res.returnCode) { 1224 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1225 extras = new Bundle(); 1226 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1227 res.origPermission); 1228 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1229 res.origPackage); 1230 break; 1231 } 1232 } 1233 return extras; 1234 } 1235 1236 void scheduleWriteSettingsLocked() { 1237 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1238 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1239 } 1240 } 1241 1242 void scheduleWritePackageRestrictionsLocked(int userId) { 1243 if (!sUserManager.exists(userId)) return; 1244 mDirtyUsers.add(userId); 1245 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1246 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1247 } 1248 } 1249 1250 public static final IPackageManager main(Context context, Installer installer, 1251 boolean factoryTest, boolean onlyCore) { 1252 PackageManagerService m = new PackageManagerService(context, installer, 1253 factoryTest, onlyCore); 1254 ServiceManager.addService("package", m); 1255 return m; 1256 } 1257 1258 static String[] splitString(String str, char sep) { 1259 int count = 1; 1260 int i = 0; 1261 while ((i=str.indexOf(sep, i)) >= 0) { 1262 count++; 1263 i++; 1264 } 1265 1266 String[] res = new String[count]; 1267 i=0; 1268 count = 0; 1269 int lastI=0; 1270 while ((i=str.indexOf(sep, i)) >= 0) { 1271 res[count] = str.substring(lastI, i); 1272 count++; 1273 i++; 1274 lastI = i; 1275 } 1276 res[count] = str.substring(lastI, str.length()); 1277 return res; 1278 } 1279 1280 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1281 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1282 Context.DISPLAY_SERVICE); 1283 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1284 } 1285 1286 public PackageManagerService(Context context, Installer installer, 1287 boolean factoryTest, boolean onlyCore) { 1288 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1289 SystemClock.uptimeMillis()); 1290 1291 if (mSdkVersion <= 0) { 1292 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1293 } 1294 1295 mContext = context; 1296 mFactoryTest = factoryTest; 1297 mOnlyCore = onlyCore; 1298 mMetrics = new DisplayMetrics(); 1299 mSettings = new Settings(context); 1300 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1301 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1302 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1303 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1304 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1305 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1306 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1307 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1308 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1309 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1310 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1311 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1312 1313 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1314 if (separateProcesses != null && separateProcesses.length() > 0) { 1315 if ("*".equals(separateProcesses)) { 1316 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1317 mSeparateProcesses = null; 1318 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1319 } else { 1320 mDefParseFlags = 0; 1321 mSeparateProcesses = separateProcesses.split(","); 1322 Slog.w(TAG, "Running with debug.separate_processes: " 1323 + separateProcesses); 1324 } 1325 } else { 1326 mDefParseFlags = 0; 1327 mSeparateProcesses = null; 1328 } 1329 1330 mInstaller = installer; 1331 1332 getDefaultDisplayMetrics(context, mMetrics); 1333 1334 synchronized (mInstallLock) { 1335 // writer 1336 synchronized (mPackages) { 1337 mHandlerThread = new ServiceThread(TAG, 1338 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1339 mHandlerThread.start(); 1340 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1341 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1342 1343 File dataDir = Environment.getDataDirectory(); 1344 mAppDataDir = new File(dataDir, "data"); 1345 mAppInstallDir = new File(dataDir, "app"); 1346 mAppLibInstallDir = new File(dataDir, "app-lib"); 1347 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1348 mUserAppDataDir = new File(dataDir, "user"); 1349 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1350 mAppStagingDir = new File(dataDir, "app-staging"); 1351 1352 sUserManager = new UserManagerService(context, this, 1353 mInstallLock, mPackages); 1354 1355 // Read permissions and features from system 1356 readPermissions(Environment.buildPath( 1357 Environment.getRootDirectory(), "etc", "permissions"), false); 1358 // Only read features from OEM 1359 readPermissions(Environment.buildPath( 1360 Environment.getOemDirectory(), "etc", "permissions"), true); 1361 1362 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1363 1364 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1365 mSdkVersion, mOnlyCore); 1366 1367 String customResolverActivity = Resources.getSystem().getString( 1368 R.string.config_customResolverActivity); 1369 if (TextUtils.isEmpty(customResolverActivity)) { 1370 customResolverActivity = null; 1371 } else { 1372 mCustomResolverComponentName = ComponentName.unflattenFromString( 1373 customResolverActivity); 1374 } 1375 1376 long startTime = SystemClock.uptimeMillis(); 1377 1378 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1379 startTime); 1380 1381 // Set flag to monitor and not change apk file paths when 1382 // scanning install directories. 1383 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1384 1385 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1386 1387 /** 1388 * Add everything in the in the boot class path to the 1389 * list of process files because dexopt will have been run 1390 * if necessary during zygote startup. 1391 */ 1392 String bootClassPath = System.getProperty("java.boot.class.path"); 1393 if (bootClassPath != null) { 1394 String[] paths = splitString(bootClassPath, ':'); 1395 for (int i=0; i<paths.length; i++) { 1396 alreadyDexOpted.add(paths[i]); 1397 } 1398 } else { 1399 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1400 } 1401 1402 boolean didDexOptLibraryOrTool = false; 1403 1404 final List<String> instructionSets = getAllInstructionSets(); 1405 1406 /** 1407 * Ensure all external libraries have had dexopt run on them. 1408 */ 1409 if (mSharedLibraries.size() > 0) { 1410 // NOTE: For now, we're compiling these system "shared libraries" 1411 // (and framework jars) into all available architectures. It's possible 1412 // to compile them only when we come across an app that uses them (there's 1413 // already logic for that in scanPackageLI) but that adds some complexity. 1414 for (String instructionSet : instructionSets) { 1415 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1416 final String lib = libEntry.path; 1417 if (lib == null) { 1418 continue; 1419 } 1420 1421 try { 1422 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1423 alreadyDexOpted.add(lib); 1424 1425 // The list of "shared libraries" we have at this point is 1426 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1427 didDexOptLibraryOrTool = true; 1428 } 1429 } catch (FileNotFoundException e) { 1430 Slog.w(TAG, "Library not found: " + lib); 1431 } catch (IOException e) { 1432 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1433 + e.getMessage()); 1434 } 1435 } 1436 } 1437 } 1438 1439 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1440 1441 // Gross hack for now: we know this file doesn't contain any 1442 // code, so don't dexopt it to avoid the resulting log spew. 1443 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1444 1445 // Gross hack for now: we know this file is only part of 1446 // the boot class path for art, so don't dexopt it to 1447 // avoid the resulting log spew. 1448 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1449 1450 /** 1451 * And there are a number of commands implemented in Java, which 1452 * we currently need to do the dexopt on so that they can be 1453 * run from a non-root shell. 1454 */ 1455 String[] frameworkFiles = frameworkDir.list(); 1456 if (frameworkFiles != null) { 1457 // TODO: We could compile these only for the most preferred ABI. We should 1458 // first double check that the dex files for these commands are not referenced 1459 // by other system apps. 1460 for (String instructionSet : instructionSets) { 1461 for (int i=0; i<frameworkFiles.length; i++) { 1462 File libPath = new File(frameworkDir, frameworkFiles[i]); 1463 String path = libPath.getPath(); 1464 // Skip the file if we already did it. 1465 if (alreadyDexOpted.contains(path)) { 1466 continue; 1467 } 1468 // Skip the file if it is not a type we want to dexopt. 1469 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1470 continue; 1471 } 1472 try { 1473 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1474 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1475 didDexOptLibraryOrTool = true; 1476 } 1477 } catch (FileNotFoundException e) { 1478 Slog.w(TAG, "Jar not found: " + path); 1479 } catch (IOException e) { 1480 Slog.w(TAG, "Exception reading jar: " + path, e); 1481 } 1482 } 1483 } 1484 } 1485 1486 if (didDexOptLibraryOrTool) { 1487 pruneDexFiles(new File(dataDir, "dalvik-cache")); 1488 } 1489 1490 // Collect vendor overlay packages. 1491 // (Do this before scanning any apps.) 1492 // For security and version matching reason, only consider 1493 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1494 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1495 mVendorOverlayInstallObserver = new AppDirObserver( 1496 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1497 mVendorOverlayInstallObserver.startWatching(); 1498 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1499 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1500 1501 // Find base frameworks (resource packages without code). 1502 mFrameworkInstallObserver = new AppDirObserver( 1503 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1504 mFrameworkInstallObserver.startWatching(); 1505 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1506 | PackageParser.PARSE_IS_SYSTEM_DIR 1507 | PackageParser.PARSE_IS_PRIVILEGED, 1508 scanMode | SCAN_NO_DEX, 0); 1509 1510 // Collected privileged system packages. 1511 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1512 mPrivilegedInstallObserver = new AppDirObserver( 1513 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1514 mPrivilegedInstallObserver.startWatching(); 1515 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1516 | PackageParser.PARSE_IS_SYSTEM_DIR 1517 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1518 1519 // Collect ordinary system packages. 1520 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1521 mSystemInstallObserver = new AppDirObserver( 1522 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1523 mSystemInstallObserver.startWatching(); 1524 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1525 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1526 1527 // Collect all vendor packages. 1528 File vendorAppDir = new File("/vendor/app"); 1529 try { 1530 vendorAppDir = vendorAppDir.getCanonicalFile(); 1531 } catch (IOException e) { 1532 // failed to look up canonical path, continue with original one 1533 } 1534 mVendorInstallObserver = new AppDirObserver( 1535 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1536 mVendorInstallObserver.startWatching(); 1537 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1538 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1539 1540 // Collect all OEM packages. 1541 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1542 mOemInstallObserver = new AppDirObserver( 1543 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1544 mOemInstallObserver.startWatching(); 1545 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1546 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1547 1548 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1549 mInstaller.moveFiles(); 1550 1551 // Prune any system packages that no longer exist. 1552 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1553 if (!mOnlyCore) { 1554 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1555 while (psit.hasNext()) { 1556 PackageSetting ps = psit.next(); 1557 1558 /* 1559 * If this is not a system app, it can't be a 1560 * disable system app. 1561 */ 1562 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1563 continue; 1564 } 1565 1566 /* 1567 * If the package is scanned, it's not erased. 1568 */ 1569 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1570 if (scannedPkg != null) { 1571 /* 1572 * If the system app is both scanned and in the 1573 * disabled packages list, then it must have been 1574 * added via OTA. Remove it from the currently 1575 * scanned package so the previously user-installed 1576 * application can be scanned. 1577 */ 1578 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1579 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1580 + "; removing system app"); 1581 removePackageLI(ps, true); 1582 } 1583 1584 continue; 1585 } 1586 1587 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1588 psit.remove(); 1589 String msg = "System package " + ps.name 1590 + " no longer exists; wiping its data"; 1591 reportSettingsProblem(Log.WARN, msg); 1592 removeDataDirsLI(ps.name); 1593 } else { 1594 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1595 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1596 possiblyDeletedUpdatedSystemApps.add(ps.name); 1597 } 1598 } 1599 } 1600 } 1601 1602 //look for any incomplete package installations 1603 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1604 //clean up list 1605 for(int i = 0; i < deletePkgsList.size(); i++) { 1606 //clean up here 1607 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1608 } 1609 //delete tmp files 1610 deleteTempPackageFiles(); 1611 1612 // Remove any shared userIDs that have no associated packages 1613 mSettings.pruneSharedUsersLPw(); 1614 1615 if (!mOnlyCore) { 1616 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1617 SystemClock.uptimeMillis()); 1618 mAppInstallObserver = new AppDirObserver( 1619 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1620 mAppInstallObserver.startWatching(); 1621 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1622 1623 mDrmAppInstallObserver = new AppDirObserver( 1624 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1625 mDrmAppInstallObserver.startWatching(); 1626 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1627 scanMode, 0); 1628 1629 /** 1630 * Remove disable package settings for any updated system 1631 * apps that were removed via an OTA. If they're not a 1632 * previously-updated app, remove them completely. 1633 * Otherwise, just revoke their system-level permissions. 1634 */ 1635 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1636 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1637 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1638 1639 String msg; 1640 if (deletedPkg == null) { 1641 msg = "Updated system package " + deletedAppName 1642 + " no longer exists; wiping its data"; 1643 removeDataDirsLI(deletedAppName); 1644 } else { 1645 msg = "Updated system app + " + deletedAppName 1646 + " no longer present; removing system privileges for " 1647 + deletedAppName; 1648 1649 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1650 1651 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1652 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1653 } 1654 reportSettingsProblem(Log.WARN, msg); 1655 } 1656 } else { 1657 mAppInstallObserver = null; 1658 mDrmAppInstallObserver = null; 1659 } 1660 1661 // Now that we know all of the shared libraries, update all clients to have 1662 // the correct library paths. 1663 updateAllSharedLibrariesLPw(); 1664 1665 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1666 // NOTE: We ignore potential failures here during a system scan (like 1667 // the rest of the commands above) because there's precious little we 1668 // can do about it. A settings error is reported, though. 1669 adjustCpuAbisForSharedUserLPw(setting.packages, null, 1670 false /* force dexopt */, false /* defer dexopt */); 1671 } 1672 1673 // Now that we know all the packages we are keeping, 1674 // read and update their last usage times. 1675 mPackageUsage.readLP(); 1676 1677 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1678 SystemClock.uptimeMillis()); 1679 Slog.i(TAG, "Time to scan packages: " 1680 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1681 + " seconds"); 1682 1683 // If the platform SDK has changed since the last time we booted, 1684 // we need to re-grant app permission to catch any new ones that 1685 // appear. This is really a hack, and means that apps can in some 1686 // cases get permissions that the user didn't initially explicitly 1687 // allow... it would be nice to have some better way to handle 1688 // this situation. 1689 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1690 != mSdkVersion; 1691 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1692 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1693 + "; regranting permissions for internal storage"); 1694 mSettings.mInternalSdkPlatform = mSdkVersion; 1695 1696 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1697 | (regrantPermissions 1698 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1699 : 0)); 1700 1701 // If this is the first boot, and it is a normal boot, then 1702 // we need to initialize the default preferred apps. 1703 if (!mRestoredSettings && !onlyCore) { 1704 mSettings.readDefaultPreferredAppsLPw(this, 0); 1705 } 1706 1707 // All the changes are done during package scanning. 1708 mSettings.updateInternalDatabaseVersion(); 1709 1710 // can downgrade to reader 1711 mSettings.writeLPr(); 1712 1713 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1714 SystemClock.uptimeMillis()); 1715 1716 1717 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1718 } // synchronized (mPackages) 1719 } // synchronized (mInstallLock) 1720 1721 mInstallerService = new PackageInstallerService(context, this, mAppStagingDir); 1722 1723 // Now after opening every single application zip, make sure they 1724 // are all flushed. Not really needed, but keeps things nice and 1725 // tidy. 1726 Runtime.getRuntime().gc(); 1727 } 1728 1729 private static void pruneDexFiles(File cacheDir) { 1730 // If we had to do a dexopt of one of the previous 1731 // things, then something on the system has changed. 1732 // Consider this significant, and wipe away all other 1733 // existing dexopt files to ensure we don't leave any 1734 // dangling around. 1735 // 1736 // Additionally, delete all dex files from the root directory 1737 // since there shouldn't be any there anyway. 1738 // 1739 // Note: This isn't as good an indicator as it used to be. It 1740 // used to include the boot classpath but at some point 1741 // DexFile.isDexOptNeeded started returning false for the boot 1742 // class path files in all cases. It is very possible in a 1743 // small maintenance release update that the library and tool 1744 // jars may be unchanged but APK could be removed resulting in 1745 // unused dalvik-cache files. 1746 File[] files = cacheDir.listFiles(); 1747 if (files != null) { 1748 for (File file : files) { 1749 if (!file.isDirectory()) { 1750 Slog.i(TAG, "Pruning dalvik file: " + file.getAbsolutePath()); 1751 file.delete(); 1752 } else { 1753 File[] subDirList = file.listFiles(); 1754 if (subDirList != null) { 1755 for (File subDirFile : subDirList) { 1756 final String fn = subDirFile.getName(); 1757 if (fn.startsWith("data@app@") || fn.startsWith("data@app-private@")) { 1758 Slog.i(TAG, "Pruning dalvik file: " + fn); 1759 subDirFile.delete(); 1760 } 1761 } 1762 } 1763 } 1764 } 1765 } 1766 } 1767 1768 @Override 1769 public boolean isFirstBoot() { 1770 return !mRestoredSettings || mPackageUsage.isFirstBoot(); 1771 } 1772 1773 @Override 1774 public boolean isOnlyCoreApps() { 1775 return mOnlyCore; 1776 } 1777 1778 private String getRequiredVerifierLPr() { 1779 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1780 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1781 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1782 1783 String requiredVerifier = null; 1784 1785 final int N = receivers.size(); 1786 for (int i = 0; i < N; i++) { 1787 final ResolveInfo info = receivers.get(i); 1788 1789 if (info.activityInfo == null) { 1790 continue; 1791 } 1792 1793 final String packageName = info.activityInfo.packageName; 1794 1795 final PackageSetting ps = mSettings.mPackages.get(packageName); 1796 if (ps == null) { 1797 continue; 1798 } 1799 1800 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1801 if (!gp.grantedPermissions 1802 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1803 continue; 1804 } 1805 1806 if (requiredVerifier != null) { 1807 throw new RuntimeException("There can be only one required verifier"); 1808 } 1809 1810 requiredVerifier = packageName; 1811 } 1812 1813 return requiredVerifier; 1814 } 1815 1816 @Override 1817 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1818 throws RemoteException { 1819 try { 1820 return super.onTransact(code, data, reply, flags); 1821 } catch (RuntimeException e) { 1822 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1823 Slog.wtf(TAG, "Package Manager Crash", e); 1824 } 1825 throw e; 1826 } 1827 } 1828 1829 void cleanupInstallFailedPackage(PackageSetting ps) { 1830 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1831 removeDataDirsLI(ps.name); 1832 if (ps.codePath != null) { 1833 if (!ps.codePath.delete()) { 1834 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1835 } 1836 } 1837 if (ps.resourcePath != null) { 1838 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1839 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1840 } 1841 } 1842 mSettings.removePackageLPw(ps.name); 1843 } 1844 1845 void readPermissions(File libraryDir, boolean onlyFeatures) { 1846 // Read permissions from .../etc/permission directory. 1847 if (!libraryDir.exists() || !libraryDir.isDirectory()) { 1848 Slog.w(TAG, "No directory " + libraryDir + ", skipping"); 1849 return; 1850 } 1851 if (!libraryDir.canRead()) { 1852 Slog.w(TAG, "Directory " + libraryDir + " cannot be read"); 1853 return; 1854 } 1855 1856 // Iterate over the files in the directory and scan .xml files 1857 for (File f : libraryDir.listFiles()) { 1858 // We'll read platform.xml last 1859 if (f.getPath().endsWith("etc/permissions/platform.xml")) { 1860 continue; 1861 } 1862 1863 if (!f.getPath().endsWith(".xml")) { 1864 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring"); 1865 continue; 1866 } 1867 if (!f.canRead()) { 1868 Slog.w(TAG, "Permissions library file " + f + " cannot be read"); 1869 continue; 1870 } 1871 1872 readPermissionsFromXml(f, onlyFeatures); 1873 } 1874 1875 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence 1876 final File permFile = new File(Environment.getRootDirectory(), 1877 "etc/permissions/platform.xml"); 1878 readPermissionsFromXml(permFile, onlyFeatures); 1879 } 1880 1881 private void readPermissionsFromXml(File permFile, boolean onlyFeatures) { 1882 FileReader permReader = null; 1883 try { 1884 permReader = new FileReader(permFile); 1885 } catch (FileNotFoundException e) { 1886 Slog.w(TAG, "Couldn't find or open permissions file " + permFile); 1887 return; 1888 } 1889 1890 try { 1891 XmlPullParser parser = Xml.newPullParser(); 1892 parser.setInput(permReader); 1893 1894 XmlUtils.beginDocument(parser, "permissions"); 1895 1896 while (true) { 1897 XmlUtils.nextElement(parser); 1898 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) { 1899 break; 1900 } 1901 1902 String name = parser.getName(); 1903 if ("group".equals(name) && !onlyFeatures) { 1904 String gidStr = parser.getAttributeValue(null, "gid"); 1905 if (gidStr != null) { 1906 int gid = Process.getGidForName(gidStr); 1907 mGlobalGids = appendInt(mGlobalGids, gid); 1908 } else { 1909 Slog.w(TAG, "<group> without gid at " 1910 + parser.getPositionDescription()); 1911 } 1912 1913 XmlUtils.skipCurrentTag(parser); 1914 continue; 1915 } else if ("permission".equals(name) && !onlyFeatures) { 1916 String perm = parser.getAttributeValue(null, "name"); 1917 if (perm == null) { 1918 Slog.w(TAG, "<permission> without name at " 1919 + parser.getPositionDescription()); 1920 XmlUtils.skipCurrentTag(parser); 1921 continue; 1922 } 1923 perm = perm.intern(); 1924 readPermission(parser, perm); 1925 1926 } else if ("assign-permission".equals(name) && !onlyFeatures) { 1927 String perm = parser.getAttributeValue(null, "name"); 1928 if (perm == null) { 1929 Slog.w(TAG, "<assign-permission> without name at " 1930 + parser.getPositionDescription()); 1931 XmlUtils.skipCurrentTag(parser); 1932 continue; 1933 } 1934 String uidStr = parser.getAttributeValue(null, "uid"); 1935 if (uidStr == null) { 1936 Slog.w(TAG, "<assign-permission> without uid at " 1937 + parser.getPositionDescription()); 1938 XmlUtils.skipCurrentTag(parser); 1939 continue; 1940 } 1941 int uid = Process.getUidForName(uidStr); 1942 if (uid < 0) { 1943 Slog.w(TAG, "<assign-permission> with unknown uid \"" 1944 + uidStr + "\" at " 1945 + parser.getPositionDescription()); 1946 XmlUtils.skipCurrentTag(parser); 1947 continue; 1948 } 1949 perm = perm.intern(); 1950 HashSet<String> perms = mSystemPermissions.get(uid); 1951 if (perms == null) { 1952 perms = new HashSet<String>(); 1953 mSystemPermissions.put(uid, perms); 1954 } 1955 perms.add(perm); 1956 XmlUtils.skipCurrentTag(parser); 1957 1958 } else if ("library".equals(name) && !onlyFeatures) { 1959 String lname = parser.getAttributeValue(null, "name"); 1960 String lfile = parser.getAttributeValue(null, "file"); 1961 if (lname == null) { 1962 Slog.w(TAG, "<library> without name at " 1963 + parser.getPositionDescription()); 1964 } else if (lfile == null) { 1965 Slog.w(TAG, "<library> without file at " 1966 + parser.getPositionDescription()); 1967 } else { 1968 //Log.i(TAG, "Got library " + lname + " in " + lfile); 1969 mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null)); 1970 } 1971 XmlUtils.skipCurrentTag(parser); 1972 continue; 1973 1974 } else if ("feature".equals(name)) { 1975 String fname = parser.getAttributeValue(null, "name"); 1976 if (fname == null) { 1977 Slog.w(TAG, "<feature> without name at " 1978 + parser.getPositionDescription()); 1979 } else { 1980 //Log.i(TAG, "Got feature " + fname); 1981 FeatureInfo fi = new FeatureInfo(); 1982 fi.name = fname; 1983 mAvailableFeatures.put(fname, fi); 1984 } 1985 XmlUtils.skipCurrentTag(parser); 1986 continue; 1987 1988 } else { 1989 XmlUtils.skipCurrentTag(parser); 1990 continue; 1991 } 1992 1993 } 1994 permReader.close(); 1995 } catch (XmlPullParserException e) { 1996 Slog.w(TAG, "Got execption parsing permissions.", e); 1997 } catch (IOException e) { 1998 Slog.w(TAG, "Got execption parsing permissions.", e); 1999 } 2000 } 2001 2002 void readPermission(XmlPullParser parser, String name) 2003 throws IOException, XmlPullParserException { 2004 2005 name = name.intern(); 2006 2007 BasePermission bp = mSettings.mPermissions.get(name); 2008 if (bp == null) { 2009 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN); 2010 mSettings.mPermissions.put(name, bp); 2011 } 2012 int outerDepth = parser.getDepth(); 2013 int type; 2014 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 2015 && (type != XmlPullParser.END_TAG 2016 || parser.getDepth() > outerDepth)) { 2017 if (type == XmlPullParser.END_TAG 2018 || type == XmlPullParser.TEXT) { 2019 continue; 2020 } 2021 2022 String tagName = parser.getName(); 2023 if ("group".equals(tagName)) { 2024 String gidStr = parser.getAttributeValue(null, "gid"); 2025 if (gidStr != null) { 2026 int gid = Process.getGidForName(gidStr); 2027 bp.gids = appendInt(bp.gids, gid); 2028 } else { 2029 Slog.w(TAG, "<group> without gid at " 2030 + parser.getPositionDescription()); 2031 } 2032 } 2033 XmlUtils.skipCurrentTag(parser); 2034 } 2035 } 2036 2037 static int[] appendInts(int[] cur, int[] add) { 2038 if (add == null) return cur; 2039 if (cur == null) return add; 2040 final int N = add.length; 2041 for (int i=0; i<N; i++) { 2042 cur = appendInt(cur, add[i]); 2043 } 2044 return cur; 2045 } 2046 2047 static int[] removeInts(int[] cur, int[] rem) { 2048 if (rem == null) return cur; 2049 if (cur == null) return cur; 2050 final int N = rem.length; 2051 for (int i=0; i<N; i++) { 2052 cur = removeInt(cur, rem[i]); 2053 } 2054 return cur; 2055 } 2056 2057 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2058 if (!sUserManager.exists(userId)) return null; 2059 final PackageSetting ps = (PackageSetting) p.mExtras; 2060 if (ps == null) { 2061 return null; 2062 } 2063 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 2064 final PackageUserState state = ps.readUserState(userId); 2065 return PackageParser.generatePackageInfo(p, gp.gids, flags, 2066 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 2067 state, userId); 2068 } 2069 2070 @Override 2071 public boolean isPackageAvailable(String packageName, int userId) { 2072 if (!sUserManager.exists(userId)) return false; 2073 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 2074 synchronized (mPackages) { 2075 PackageParser.Package p = mPackages.get(packageName); 2076 if (p != null) { 2077 final PackageSetting ps = (PackageSetting) p.mExtras; 2078 if (ps != null) { 2079 final PackageUserState state = ps.readUserState(userId); 2080 if (state != null) { 2081 return PackageParser.isAvailable(state); 2082 } 2083 } 2084 } 2085 } 2086 return false; 2087 } 2088 2089 @Override 2090 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2091 if (!sUserManager.exists(userId)) return null; 2092 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 2093 // reader 2094 synchronized (mPackages) { 2095 PackageParser.Package p = mPackages.get(packageName); 2096 if (DEBUG_PACKAGE_INFO) 2097 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2098 if (p != null) { 2099 return generatePackageInfo(p, flags, userId); 2100 } 2101 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2102 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2103 } 2104 } 2105 return null; 2106 } 2107 2108 @Override 2109 public String[] currentToCanonicalPackageNames(String[] names) { 2110 String[] out = new String[names.length]; 2111 // reader 2112 synchronized (mPackages) { 2113 for (int i=names.length-1; i>=0; i--) { 2114 PackageSetting ps = mSettings.mPackages.get(names[i]); 2115 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2116 } 2117 } 2118 return out; 2119 } 2120 2121 @Override 2122 public String[] canonicalToCurrentPackageNames(String[] names) { 2123 String[] out = new String[names.length]; 2124 // reader 2125 synchronized (mPackages) { 2126 for (int i=names.length-1; i>=0; i--) { 2127 String cur = mSettings.mRenamedPackages.get(names[i]); 2128 out[i] = cur != null ? cur : names[i]; 2129 } 2130 } 2131 return out; 2132 } 2133 2134 @Override 2135 public int getPackageUid(String packageName, int userId) { 2136 if (!sUserManager.exists(userId)) return -1; 2137 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 2138 // reader 2139 synchronized (mPackages) { 2140 PackageParser.Package p = mPackages.get(packageName); 2141 if(p != null) { 2142 return UserHandle.getUid(userId, p.applicationInfo.uid); 2143 } 2144 PackageSetting ps = mSettings.mPackages.get(packageName); 2145 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2146 return -1; 2147 } 2148 p = ps.pkg; 2149 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2150 } 2151 } 2152 2153 @Override 2154 public int[] getPackageGids(String packageName) { 2155 // reader 2156 synchronized (mPackages) { 2157 PackageParser.Package p = mPackages.get(packageName); 2158 if (DEBUG_PACKAGE_INFO) 2159 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2160 if (p != null) { 2161 final PackageSetting ps = (PackageSetting)p.mExtras; 2162 return ps.getGids(); 2163 } 2164 } 2165 // stupid thing to indicate an error. 2166 return new int[0]; 2167 } 2168 2169 static final PermissionInfo generatePermissionInfo( 2170 BasePermission bp, int flags) { 2171 if (bp.perm != null) { 2172 return PackageParser.generatePermissionInfo(bp.perm, flags); 2173 } 2174 PermissionInfo pi = new PermissionInfo(); 2175 pi.name = bp.name; 2176 pi.packageName = bp.sourcePackage; 2177 pi.nonLocalizedLabel = bp.name; 2178 pi.protectionLevel = bp.protectionLevel; 2179 return pi; 2180 } 2181 2182 @Override 2183 public PermissionInfo getPermissionInfo(String name, int flags) { 2184 // reader 2185 synchronized (mPackages) { 2186 final BasePermission p = mSettings.mPermissions.get(name); 2187 if (p != null) { 2188 return generatePermissionInfo(p, flags); 2189 } 2190 return null; 2191 } 2192 } 2193 2194 @Override 2195 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2196 // reader 2197 synchronized (mPackages) { 2198 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2199 for (BasePermission p : mSettings.mPermissions.values()) { 2200 if (group == null) { 2201 if (p.perm == null || p.perm.info.group == null) { 2202 out.add(generatePermissionInfo(p, flags)); 2203 } 2204 } else { 2205 if (p.perm != null && group.equals(p.perm.info.group)) { 2206 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2207 } 2208 } 2209 } 2210 2211 if (out.size() > 0) { 2212 return out; 2213 } 2214 return mPermissionGroups.containsKey(group) ? out : null; 2215 } 2216 } 2217 2218 @Override 2219 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2220 // reader 2221 synchronized (mPackages) { 2222 return PackageParser.generatePermissionGroupInfo( 2223 mPermissionGroups.get(name), flags); 2224 } 2225 } 2226 2227 @Override 2228 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2229 // reader 2230 synchronized (mPackages) { 2231 final int N = mPermissionGroups.size(); 2232 ArrayList<PermissionGroupInfo> out 2233 = new ArrayList<PermissionGroupInfo>(N); 2234 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2235 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2236 } 2237 return out; 2238 } 2239 } 2240 2241 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2242 int userId) { 2243 if (!sUserManager.exists(userId)) return null; 2244 PackageSetting ps = mSettings.mPackages.get(packageName); 2245 if (ps != null) { 2246 if (ps.pkg == null) { 2247 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2248 flags, userId); 2249 if (pInfo != null) { 2250 return pInfo.applicationInfo; 2251 } 2252 return null; 2253 } 2254 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2255 ps.readUserState(userId), userId); 2256 } 2257 return null; 2258 } 2259 2260 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2261 int userId) { 2262 if (!sUserManager.exists(userId)) return null; 2263 PackageSetting ps = mSettings.mPackages.get(packageName); 2264 if (ps != null) { 2265 PackageParser.Package pkg = ps.pkg; 2266 if (pkg == null) { 2267 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2268 return null; 2269 } 2270 // TODO: teach about reading split name 2271 pkg = new PackageParser.Package(packageName, null); 2272 pkg.applicationInfo.packageName = packageName; 2273 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2274 pkg.applicationInfo.publicSourceDir = ps.resourcePathString; 2275 pkg.applicationInfo.sourceDir = ps.codePathString; 2276 pkg.applicationInfo.dataDir = 2277 getDataPathForPackage(packageName, 0).getPath(); 2278 pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString; 2279 pkg.applicationInfo.cpuAbi = ps.cpuAbiString; 2280 } 2281 return generatePackageInfo(pkg, flags, userId); 2282 } 2283 return null; 2284 } 2285 2286 @Override 2287 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2288 if (!sUserManager.exists(userId)) return null; 2289 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2290 // writer 2291 synchronized (mPackages) { 2292 PackageParser.Package p = mPackages.get(packageName); 2293 if (DEBUG_PACKAGE_INFO) Log.v( 2294 TAG, "getApplicationInfo " + packageName 2295 + ": " + p); 2296 if (p != null) { 2297 PackageSetting ps = mSettings.mPackages.get(packageName); 2298 if (ps == null) return null; 2299 // Note: isEnabledLP() does not apply here - always return info 2300 return PackageParser.generateApplicationInfo( 2301 p, flags, ps.readUserState(userId), userId); 2302 } 2303 if ("android".equals(packageName)||"system".equals(packageName)) { 2304 return mAndroidApplication; 2305 } 2306 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2307 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2308 } 2309 } 2310 return null; 2311 } 2312 2313 2314 @Override 2315 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2316 mContext.enforceCallingOrSelfPermission( 2317 android.Manifest.permission.CLEAR_APP_CACHE, null); 2318 // Queue up an async operation since clearing cache may take a little while. 2319 mHandler.post(new Runnable() { 2320 public void run() { 2321 mHandler.removeCallbacks(this); 2322 int retCode = -1; 2323 synchronized (mInstallLock) { 2324 retCode = mInstaller.freeCache(freeStorageSize); 2325 if (retCode < 0) { 2326 Slog.w(TAG, "Couldn't clear application caches"); 2327 } 2328 } 2329 if (observer != null) { 2330 try { 2331 observer.onRemoveCompleted(null, (retCode >= 0)); 2332 } catch (RemoteException e) { 2333 Slog.w(TAG, "RemoveException when invoking call back"); 2334 } 2335 } 2336 } 2337 }); 2338 } 2339 2340 @Override 2341 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2342 mContext.enforceCallingOrSelfPermission( 2343 android.Manifest.permission.CLEAR_APP_CACHE, null); 2344 // Queue up an async operation since clearing cache may take a little while. 2345 mHandler.post(new Runnable() { 2346 public void run() { 2347 mHandler.removeCallbacks(this); 2348 int retCode = -1; 2349 synchronized (mInstallLock) { 2350 retCode = mInstaller.freeCache(freeStorageSize); 2351 if (retCode < 0) { 2352 Slog.w(TAG, "Couldn't clear application caches"); 2353 } 2354 } 2355 if(pi != null) { 2356 try { 2357 // Callback via pending intent 2358 int code = (retCode >= 0) ? 1 : 0; 2359 pi.sendIntent(null, code, null, 2360 null, null); 2361 } catch (SendIntentException e1) { 2362 Slog.i(TAG, "Failed to send pending intent"); 2363 } 2364 } 2365 } 2366 }); 2367 } 2368 2369 void freeStorage(long freeStorageSize) throws IOException { 2370 synchronized (mInstallLock) { 2371 if (mInstaller.freeCache(freeStorageSize) < 0) { 2372 throw new IOException("Failed to free enough space"); 2373 } 2374 } 2375 } 2376 2377 @Override 2378 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2379 if (!sUserManager.exists(userId)) return null; 2380 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2381 synchronized (mPackages) { 2382 PackageParser.Activity a = mActivities.mActivities.get(component); 2383 2384 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2385 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2386 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2387 if (ps == null) return null; 2388 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2389 userId); 2390 } 2391 if (mResolveComponentName.equals(component)) { 2392 return mResolveActivity; 2393 } 2394 } 2395 return null; 2396 } 2397 2398 @Override 2399 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2400 String resolvedType) { 2401 synchronized (mPackages) { 2402 PackageParser.Activity a = mActivities.mActivities.get(component); 2403 if (a == null) { 2404 return false; 2405 } 2406 for (int i=0; i<a.intents.size(); i++) { 2407 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2408 intent.getData(), intent.getCategories(), TAG) >= 0) { 2409 return true; 2410 } 2411 } 2412 return false; 2413 } 2414 } 2415 2416 @Override 2417 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2418 if (!sUserManager.exists(userId)) return null; 2419 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2420 synchronized (mPackages) { 2421 PackageParser.Activity a = mReceivers.mActivities.get(component); 2422 if (DEBUG_PACKAGE_INFO) Log.v( 2423 TAG, "getReceiverInfo " + component + ": " + a); 2424 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2425 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2426 if (ps == null) return null; 2427 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2428 userId); 2429 } 2430 } 2431 return null; 2432 } 2433 2434 @Override 2435 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2436 if (!sUserManager.exists(userId)) return null; 2437 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2438 synchronized (mPackages) { 2439 PackageParser.Service s = mServices.mServices.get(component); 2440 if (DEBUG_PACKAGE_INFO) Log.v( 2441 TAG, "getServiceInfo " + component + ": " + s); 2442 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2443 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2444 if (ps == null) return null; 2445 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2446 userId); 2447 } 2448 } 2449 return null; 2450 } 2451 2452 @Override 2453 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2454 if (!sUserManager.exists(userId)) return null; 2455 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2456 synchronized (mPackages) { 2457 PackageParser.Provider p = mProviders.mProviders.get(component); 2458 if (DEBUG_PACKAGE_INFO) Log.v( 2459 TAG, "getProviderInfo " + component + ": " + p); 2460 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2461 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2462 if (ps == null) return null; 2463 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2464 userId); 2465 } 2466 } 2467 return null; 2468 } 2469 2470 @Override 2471 public String[] getSystemSharedLibraryNames() { 2472 Set<String> libSet; 2473 synchronized (mPackages) { 2474 libSet = mSharedLibraries.keySet(); 2475 int size = libSet.size(); 2476 if (size > 0) { 2477 String[] libs = new String[size]; 2478 libSet.toArray(libs); 2479 return libs; 2480 } 2481 } 2482 return null; 2483 } 2484 2485 @Override 2486 public FeatureInfo[] getSystemAvailableFeatures() { 2487 Collection<FeatureInfo> featSet; 2488 synchronized (mPackages) { 2489 featSet = mAvailableFeatures.values(); 2490 int size = featSet.size(); 2491 if (size > 0) { 2492 FeatureInfo[] features = new FeatureInfo[size+1]; 2493 featSet.toArray(features); 2494 FeatureInfo fi = new FeatureInfo(); 2495 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2496 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2497 features[size] = fi; 2498 return features; 2499 } 2500 } 2501 return null; 2502 } 2503 2504 @Override 2505 public boolean hasSystemFeature(String name) { 2506 synchronized (mPackages) { 2507 return mAvailableFeatures.containsKey(name); 2508 } 2509 } 2510 2511 private void checkValidCaller(int uid, int userId) { 2512 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2513 return; 2514 2515 throw new SecurityException("Caller uid=" + uid 2516 + " is not privileged to communicate with user=" + userId); 2517 } 2518 2519 @Override 2520 public int checkPermission(String permName, String pkgName) { 2521 synchronized (mPackages) { 2522 PackageParser.Package p = mPackages.get(pkgName); 2523 if (p != null && p.mExtras != null) { 2524 PackageSetting ps = (PackageSetting)p.mExtras; 2525 if (ps.sharedUser != null) { 2526 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2527 return PackageManager.PERMISSION_GRANTED; 2528 } 2529 } else if (ps.grantedPermissions.contains(permName)) { 2530 return PackageManager.PERMISSION_GRANTED; 2531 } 2532 } 2533 } 2534 return PackageManager.PERMISSION_DENIED; 2535 } 2536 2537 @Override 2538 public int checkUidPermission(String permName, int uid) { 2539 synchronized (mPackages) { 2540 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2541 if (obj != null) { 2542 GrantedPermissions gp = (GrantedPermissions)obj; 2543 if (gp.grantedPermissions.contains(permName)) { 2544 return PackageManager.PERMISSION_GRANTED; 2545 } 2546 } else { 2547 HashSet<String> perms = mSystemPermissions.get(uid); 2548 if (perms != null && perms.contains(permName)) { 2549 return PackageManager.PERMISSION_GRANTED; 2550 } 2551 } 2552 } 2553 return PackageManager.PERMISSION_DENIED; 2554 } 2555 2556 /** 2557 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2558 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2559 * @param message the message to log on security exception 2560 */ 2561 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2562 String message) { 2563 if (userId < 0) { 2564 throw new IllegalArgumentException("Invalid userId " + userId); 2565 } 2566 if (userId == UserHandle.getUserId(callingUid)) return; 2567 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2568 if (requireFullPermission) { 2569 mContext.enforceCallingOrSelfPermission( 2570 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2571 } else { 2572 try { 2573 mContext.enforceCallingOrSelfPermission( 2574 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2575 } catch (SecurityException se) { 2576 mContext.enforceCallingOrSelfPermission( 2577 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2578 } 2579 } 2580 } 2581 } 2582 2583 private BasePermission findPermissionTreeLP(String permName) { 2584 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2585 if (permName.startsWith(bp.name) && 2586 permName.length() > bp.name.length() && 2587 permName.charAt(bp.name.length()) == '.') { 2588 return bp; 2589 } 2590 } 2591 return null; 2592 } 2593 2594 private BasePermission checkPermissionTreeLP(String permName) { 2595 if (permName != null) { 2596 BasePermission bp = findPermissionTreeLP(permName); 2597 if (bp != null) { 2598 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2599 return bp; 2600 } 2601 throw new SecurityException("Calling uid " 2602 + Binder.getCallingUid() 2603 + " is not allowed to add to permission tree " 2604 + bp.name + " owned by uid " + bp.uid); 2605 } 2606 } 2607 throw new SecurityException("No permission tree found for " + permName); 2608 } 2609 2610 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2611 if (s1 == null) { 2612 return s2 == null; 2613 } 2614 if (s2 == null) { 2615 return false; 2616 } 2617 if (s1.getClass() != s2.getClass()) { 2618 return false; 2619 } 2620 return s1.equals(s2); 2621 } 2622 2623 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2624 if (pi1.icon != pi2.icon) return false; 2625 if (pi1.logo != pi2.logo) return false; 2626 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2627 if (!compareStrings(pi1.name, pi2.name)) return false; 2628 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2629 // We'll take care of setting this one. 2630 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2631 // These are not currently stored in settings. 2632 //if (!compareStrings(pi1.group, pi2.group)) return false; 2633 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2634 //if (pi1.labelRes != pi2.labelRes) return false; 2635 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2636 return true; 2637 } 2638 2639 int permissionInfoFootprint(PermissionInfo info) { 2640 int size = info.name.length(); 2641 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2642 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2643 return size; 2644 } 2645 2646 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2647 int size = 0; 2648 for (BasePermission perm : mSettings.mPermissions.values()) { 2649 if (perm.uid == tree.uid) { 2650 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2651 } 2652 } 2653 return size; 2654 } 2655 2656 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2657 // We calculate the max size of permissions defined by this uid and throw 2658 // if that plus the size of 'info' would exceed our stated maximum. 2659 if (tree.uid != Process.SYSTEM_UID) { 2660 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2661 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2662 throw new SecurityException("Permission tree size cap exceeded"); 2663 } 2664 } 2665 } 2666 2667 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2668 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2669 throw new SecurityException("Label must be specified in permission"); 2670 } 2671 BasePermission tree = checkPermissionTreeLP(info.name); 2672 BasePermission bp = mSettings.mPermissions.get(info.name); 2673 boolean added = bp == null; 2674 boolean changed = true; 2675 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2676 if (added) { 2677 enforcePermissionCapLocked(info, tree); 2678 bp = new BasePermission(info.name, tree.sourcePackage, 2679 BasePermission.TYPE_DYNAMIC); 2680 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2681 throw new SecurityException( 2682 "Not allowed to modify non-dynamic permission " 2683 + info.name); 2684 } else { 2685 if (bp.protectionLevel == fixedLevel 2686 && bp.perm.owner.equals(tree.perm.owner) 2687 && bp.uid == tree.uid 2688 && comparePermissionInfos(bp.perm.info, info)) { 2689 changed = false; 2690 } 2691 } 2692 bp.protectionLevel = fixedLevel; 2693 info = new PermissionInfo(info); 2694 info.protectionLevel = fixedLevel; 2695 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2696 bp.perm.info.packageName = tree.perm.info.packageName; 2697 bp.uid = tree.uid; 2698 if (added) { 2699 mSettings.mPermissions.put(info.name, bp); 2700 } 2701 if (changed) { 2702 if (!async) { 2703 mSettings.writeLPr(); 2704 } else { 2705 scheduleWriteSettingsLocked(); 2706 } 2707 } 2708 return added; 2709 } 2710 2711 @Override 2712 public boolean addPermission(PermissionInfo info) { 2713 synchronized (mPackages) { 2714 return addPermissionLocked(info, false); 2715 } 2716 } 2717 2718 @Override 2719 public boolean addPermissionAsync(PermissionInfo info) { 2720 synchronized (mPackages) { 2721 return addPermissionLocked(info, true); 2722 } 2723 } 2724 2725 @Override 2726 public void removePermission(String name) { 2727 synchronized (mPackages) { 2728 checkPermissionTreeLP(name); 2729 BasePermission bp = mSettings.mPermissions.get(name); 2730 if (bp != null) { 2731 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2732 throw new SecurityException( 2733 "Not allowed to modify non-dynamic permission " 2734 + name); 2735 } 2736 mSettings.mPermissions.remove(name); 2737 mSettings.writeLPr(); 2738 } 2739 } 2740 } 2741 2742 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2743 int index = pkg.requestedPermissions.indexOf(bp.name); 2744 if (index == -1) { 2745 throw new SecurityException("Package " + pkg.packageName 2746 + " has not requested permission " + bp.name); 2747 } 2748 boolean isNormal = 2749 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2750 == PermissionInfo.PROTECTION_NORMAL); 2751 boolean isDangerous = 2752 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2753 == PermissionInfo.PROTECTION_DANGEROUS); 2754 boolean isDevelopment = 2755 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2756 2757 if (!isNormal && !isDangerous && !isDevelopment) { 2758 throw new SecurityException("Permission " + bp.name 2759 + " is not a changeable permission type"); 2760 } 2761 2762 if (isNormal || isDangerous) { 2763 if (pkg.requestedPermissionsRequired.get(index)) { 2764 throw new SecurityException("Can't change " + bp.name 2765 + ". It is required by the application"); 2766 } 2767 } 2768 } 2769 2770 @Override 2771 public void grantPermission(String packageName, String permissionName) { 2772 mContext.enforceCallingOrSelfPermission( 2773 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2774 synchronized (mPackages) { 2775 final PackageParser.Package pkg = mPackages.get(packageName); 2776 if (pkg == null) { 2777 throw new IllegalArgumentException("Unknown package: " + packageName); 2778 } 2779 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2780 if (bp == null) { 2781 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2782 } 2783 2784 checkGrantRevokePermissions(pkg, bp); 2785 2786 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2787 if (ps == null) { 2788 return; 2789 } 2790 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2791 if (gp.grantedPermissions.add(permissionName)) { 2792 if (ps.haveGids) { 2793 gp.gids = appendInts(gp.gids, bp.gids); 2794 } 2795 mSettings.writeLPr(); 2796 } 2797 } 2798 } 2799 2800 @Override 2801 public void revokePermission(String packageName, String permissionName) { 2802 int changedAppId = -1; 2803 2804 synchronized (mPackages) { 2805 final PackageParser.Package pkg = mPackages.get(packageName); 2806 if (pkg == null) { 2807 throw new IllegalArgumentException("Unknown package: " + packageName); 2808 } 2809 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2810 mContext.enforceCallingOrSelfPermission( 2811 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2812 } 2813 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2814 if (bp == null) { 2815 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2816 } 2817 2818 checkGrantRevokePermissions(pkg, bp); 2819 2820 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2821 if (ps == null) { 2822 return; 2823 } 2824 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2825 if (gp.grantedPermissions.remove(permissionName)) { 2826 gp.grantedPermissions.remove(permissionName); 2827 if (ps.haveGids) { 2828 gp.gids = removeInts(gp.gids, bp.gids); 2829 } 2830 mSettings.writeLPr(); 2831 changedAppId = ps.appId; 2832 } 2833 } 2834 2835 if (changedAppId >= 0) { 2836 // We changed the perm on someone, kill its processes. 2837 IActivityManager am = ActivityManagerNative.getDefault(); 2838 if (am != null) { 2839 final int callingUserId = UserHandle.getCallingUserId(); 2840 final long ident = Binder.clearCallingIdentity(); 2841 try { 2842 //XXX we should only revoke for the calling user's app permissions, 2843 // but for now we impact all users. 2844 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2845 // "revoke " + permissionName); 2846 int[] users = sUserManager.getUserIds(); 2847 for (int user : users) { 2848 am.killUid(UserHandle.getUid(user, changedAppId), 2849 "revoke " + permissionName); 2850 } 2851 } catch (RemoteException e) { 2852 } finally { 2853 Binder.restoreCallingIdentity(ident); 2854 } 2855 } 2856 } 2857 } 2858 2859 @Override 2860 public boolean isProtectedBroadcast(String actionName) { 2861 synchronized (mPackages) { 2862 return mProtectedBroadcasts.contains(actionName); 2863 } 2864 } 2865 2866 @Override 2867 public int checkSignatures(String pkg1, String pkg2) { 2868 synchronized (mPackages) { 2869 final PackageParser.Package p1 = mPackages.get(pkg1); 2870 final PackageParser.Package p2 = mPackages.get(pkg2); 2871 if (p1 == null || p1.mExtras == null 2872 || p2 == null || p2.mExtras == null) { 2873 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2874 } 2875 return compareSignatures(p1.mSignatures, p2.mSignatures); 2876 } 2877 } 2878 2879 @Override 2880 public int checkUidSignatures(int uid1, int uid2) { 2881 // Map to base uids. 2882 uid1 = UserHandle.getAppId(uid1); 2883 uid2 = UserHandle.getAppId(uid2); 2884 // reader 2885 synchronized (mPackages) { 2886 Signature[] s1; 2887 Signature[] s2; 2888 Object obj = mSettings.getUserIdLPr(uid1); 2889 if (obj != null) { 2890 if (obj instanceof SharedUserSetting) { 2891 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2892 } else if (obj instanceof PackageSetting) { 2893 s1 = ((PackageSetting)obj).signatures.mSignatures; 2894 } else { 2895 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2896 } 2897 } else { 2898 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2899 } 2900 obj = mSettings.getUserIdLPr(uid2); 2901 if (obj != null) { 2902 if (obj instanceof SharedUserSetting) { 2903 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2904 } else if (obj instanceof PackageSetting) { 2905 s2 = ((PackageSetting)obj).signatures.mSignatures; 2906 } else { 2907 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2908 } 2909 } else { 2910 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2911 } 2912 return compareSignatures(s1, s2); 2913 } 2914 } 2915 2916 /** 2917 * Compares two sets of signatures. Returns: 2918 * <br /> 2919 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2920 * <br /> 2921 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2922 * <br /> 2923 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2924 * <br /> 2925 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2926 * <br /> 2927 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2928 */ 2929 static int compareSignatures(Signature[] s1, Signature[] s2) { 2930 if (s1 == null) { 2931 return s2 == null 2932 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2933 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2934 } 2935 2936 if (s2 == null) { 2937 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2938 } 2939 2940 if (s1.length != s2.length) { 2941 return PackageManager.SIGNATURE_NO_MATCH; 2942 } 2943 2944 // Since both signature sets are of size 1, we can compare without HashSets. 2945 if (s1.length == 1) { 2946 return s1[0].equals(s2[0]) ? 2947 PackageManager.SIGNATURE_MATCH : 2948 PackageManager.SIGNATURE_NO_MATCH; 2949 } 2950 2951 HashSet<Signature> set1 = new HashSet<Signature>(); 2952 for (Signature sig : s1) { 2953 set1.add(sig); 2954 } 2955 HashSet<Signature> set2 = new HashSet<Signature>(); 2956 for (Signature sig : s2) { 2957 set2.add(sig); 2958 } 2959 // Make sure s2 contains all signatures in s1. 2960 if (set1.equals(set2)) { 2961 return PackageManager.SIGNATURE_MATCH; 2962 } 2963 return PackageManager.SIGNATURE_NO_MATCH; 2964 } 2965 2966 /** 2967 * If the database version for this type of package (internal storage or 2968 * external storage) is less than the version where package signatures 2969 * were updated, return true. 2970 */ 2971 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2972 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2973 DatabaseVersion.SIGNATURE_END_ENTITY)) 2974 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2975 DatabaseVersion.SIGNATURE_END_ENTITY)); 2976 } 2977 2978 /** 2979 * Used for backward compatibility to make sure any packages with 2980 * certificate chains get upgraded to the new style. {@code existingSigs} 2981 * will be in the old format (since they were stored on disk from before the 2982 * system upgrade) and {@code scannedSigs} will be in the newer format. 2983 */ 2984 private int compareSignaturesCompat(PackageSignatures existingSigs, 2985 PackageParser.Package scannedPkg) { 2986 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2987 return PackageManager.SIGNATURE_NO_MATCH; 2988 } 2989 2990 HashSet<Signature> existingSet = new HashSet<Signature>(); 2991 for (Signature sig : existingSigs.mSignatures) { 2992 existingSet.add(sig); 2993 } 2994 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2995 for (Signature sig : scannedPkg.mSignatures) { 2996 try { 2997 Signature[] chainSignatures = sig.getChainSignatures(); 2998 for (Signature chainSig : chainSignatures) { 2999 scannedCompatSet.add(chainSig); 3000 } 3001 } catch (CertificateEncodingException e) { 3002 scannedCompatSet.add(sig); 3003 } 3004 } 3005 /* 3006 * Make sure the expanded scanned set contains all signatures in the 3007 * existing one. 3008 */ 3009 if (scannedCompatSet.equals(existingSet)) { 3010 // Migrate the old signatures to the new scheme. 3011 existingSigs.assignSignatures(scannedPkg.mSignatures); 3012 // The new KeySets will be re-added later in the scanning process. 3013 mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName); 3014 return PackageManager.SIGNATURE_MATCH; 3015 } 3016 return PackageManager.SIGNATURE_NO_MATCH; 3017 } 3018 3019 @Override 3020 public String[] getPackagesForUid(int uid) { 3021 uid = UserHandle.getAppId(uid); 3022 // reader 3023 synchronized (mPackages) { 3024 Object obj = mSettings.getUserIdLPr(uid); 3025 if (obj instanceof SharedUserSetting) { 3026 final SharedUserSetting sus = (SharedUserSetting) obj; 3027 final int N = sus.packages.size(); 3028 final String[] res = new String[N]; 3029 final Iterator<PackageSetting> it = sus.packages.iterator(); 3030 int i = 0; 3031 while (it.hasNext()) { 3032 res[i++] = it.next().name; 3033 } 3034 return res; 3035 } else if (obj instanceof PackageSetting) { 3036 final PackageSetting ps = (PackageSetting) obj; 3037 return new String[] { ps.name }; 3038 } 3039 } 3040 return null; 3041 } 3042 3043 @Override 3044 public String getNameForUid(int uid) { 3045 // reader 3046 synchronized (mPackages) { 3047 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3048 if (obj instanceof SharedUserSetting) { 3049 final SharedUserSetting sus = (SharedUserSetting) obj; 3050 return sus.name + ":" + sus.userId; 3051 } else if (obj instanceof PackageSetting) { 3052 final PackageSetting ps = (PackageSetting) obj; 3053 return ps.name; 3054 } 3055 } 3056 return null; 3057 } 3058 3059 @Override 3060 public int getUidForSharedUser(String sharedUserName) { 3061 if(sharedUserName == null) { 3062 return -1; 3063 } 3064 // reader 3065 synchronized (mPackages) { 3066 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 3067 if (suid == null) { 3068 return -1; 3069 } 3070 return suid.userId; 3071 } 3072 } 3073 3074 @Override 3075 public int getFlagsForUid(int uid) { 3076 synchronized (mPackages) { 3077 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3078 if (obj instanceof SharedUserSetting) { 3079 final SharedUserSetting sus = (SharedUserSetting) obj; 3080 return sus.pkgFlags; 3081 } else if (obj instanceof PackageSetting) { 3082 final PackageSetting ps = (PackageSetting) obj; 3083 return ps.pkgFlags; 3084 } 3085 } 3086 return 0; 3087 } 3088 3089 @Override 3090 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3091 int flags, int userId) { 3092 if (!sUserManager.exists(userId)) return null; 3093 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 3094 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3095 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3096 } 3097 3098 @Override 3099 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3100 IntentFilter filter, int match, ComponentName activity) { 3101 final int userId = UserHandle.getCallingUserId(); 3102 if (DEBUG_PREFERRED) { 3103 Log.v(TAG, "setLastChosenActivity intent=" + intent 3104 + " resolvedType=" + resolvedType 3105 + " flags=" + flags 3106 + " filter=" + filter 3107 + " match=" + match 3108 + " activity=" + activity); 3109 filter.dump(new PrintStreamPrinter(System.out), " "); 3110 } 3111 intent.setComponent(null); 3112 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3113 // Find any earlier preferred or last chosen entries and nuke them 3114 findPreferredActivity(intent, resolvedType, 3115 flags, query, 0, false, true, false, userId); 3116 // Add the new activity as the last chosen for this filter 3117 addPreferredActivityInternal(filter, match, null, activity, false, userId); 3118 } 3119 3120 @Override 3121 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3122 final int userId = UserHandle.getCallingUserId(); 3123 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3124 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3125 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3126 false, false, false, userId); 3127 } 3128 3129 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3130 int flags, List<ResolveInfo> query, int userId) { 3131 if (query != null) { 3132 final int N = query.size(); 3133 if (N == 1) { 3134 return query.get(0); 3135 } else if (N > 1) { 3136 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3137 // If there is more than one activity with the same priority, 3138 // then let the user decide between them. 3139 ResolveInfo r0 = query.get(0); 3140 ResolveInfo r1 = query.get(1); 3141 if (DEBUG_INTENT_MATCHING || debug) { 3142 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3143 + r1.activityInfo.name + "=" + r1.priority); 3144 } 3145 // If the first activity has a higher priority, or a different 3146 // default, then it is always desireable to pick it. 3147 if (r0.priority != r1.priority 3148 || r0.preferredOrder != r1.preferredOrder 3149 || r0.isDefault != r1.isDefault) { 3150 return query.get(0); 3151 } 3152 // If we have saved a preference for a preferred activity for 3153 // this Intent, use that. 3154 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3155 flags, query, r0.priority, true, false, debug, userId); 3156 if (ri != null) { 3157 return ri; 3158 } 3159 if (userId != 0) { 3160 ri = new ResolveInfo(mResolveInfo); 3161 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3162 ri.activityInfo.applicationInfo = new ApplicationInfo( 3163 ri.activityInfo.applicationInfo); 3164 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3165 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3166 return ri; 3167 } 3168 return mResolveInfo; 3169 } 3170 } 3171 return null; 3172 } 3173 3174 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3175 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3176 final int N = query.size(); 3177 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3178 .get(userId); 3179 // Get the list of persistent preferred activities that handle the intent 3180 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3181 List<PersistentPreferredActivity> pprefs = ppir != null 3182 ? ppir.queryIntent(intent, resolvedType, 3183 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3184 : null; 3185 if (pprefs != null && pprefs.size() > 0) { 3186 final int M = pprefs.size(); 3187 for (int i=0; i<M; i++) { 3188 final PersistentPreferredActivity ppa = pprefs.get(i); 3189 if (DEBUG_PREFERRED || debug) { 3190 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3191 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3192 + "\n component=" + ppa.mComponent); 3193 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3194 } 3195 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3196 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3197 if (DEBUG_PREFERRED || debug) { 3198 Slog.v(TAG, "Found persistent preferred activity:"); 3199 if (ai != null) { 3200 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3201 } else { 3202 Slog.v(TAG, " null"); 3203 } 3204 } 3205 if (ai == null) { 3206 // This previously registered persistent preferred activity 3207 // component is no longer known. Ignore it and do NOT remove it. 3208 continue; 3209 } 3210 for (int j=0; j<N; j++) { 3211 final ResolveInfo ri = query.get(j); 3212 if (!ri.activityInfo.applicationInfo.packageName 3213 .equals(ai.applicationInfo.packageName)) { 3214 continue; 3215 } 3216 if (!ri.activityInfo.name.equals(ai.name)) { 3217 continue; 3218 } 3219 // Found a persistent preference that can handle the intent. 3220 if (DEBUG_PREFERRED || debug) { 3221 Slog.v(TAG, "Returning persistent preferred activity: " + 3222 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3223 } 3224 return ri; 3225 } 3226 } 3227 } 3228 return null; 3229 } 3230 3231 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3232 List<ResolveInfo> query, int priority, boolean always, 3233 boolean removeMatches, boolean debug, int userId) { 3234 if (!sUserManager.exists(userId)) return null; 3235 // writer 3236 synchronized (mPackages) { 3237 if (intent.getSelector() != null) { 3238 intent = intent.getSelector(); 3239 } 3240 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3241 3242 // Try to find a matching persistent preferred activity. 3243 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3244 debug, userId); 3245 3246 // If a persistent preferred activity matched, use it. 3247 if (pri != null) { 3248 return pri; 3249 } 3250 3251 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3252 // Get the list of preferred activities that handle the intent 3253 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3254 List<PreferredActivity> prefs = pir != null 3255 ? pir.queryIntent(intent, resolvedType, 3256 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3257 : null; 3258 if (prefs != null && prefs.size() > 0) { 3259 // First figure out how good the original match set is. 3260 // We will only allow preferred activities that came 3261 // from the same match quality. 3262 int match = 0; 3263 3264 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3265 3266 final int N = query.size(); 3267 for (int j=0; j<N; j++) { 3268 final ResolveInfo ri = query.get(j); 3269 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3270 + ": 0x" + Integer.toHexString(match)); 3271 if (ri.match > match) { 3272 match = ri.match; 3273 } 3274 } 3275 3276 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3277 + Integer.toHexString(match)); 3278 3279 match &= IntentFilter.MATCH_CATEGORY_MASK; 3280 final int M = prefs.size(); 3281 for (int i=0; i<M; i++) { 3282 final PreferredActivity pa = prefs.get(i); 3283 if (DEBUG_PREFERRED || debug) { 3284 Slog.v(TAG, "Checking PreferredActivity ds=" 3285 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3286 + "\n component=" + pa.mPref.mComponent); 3287 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3288 } 3289 if (pa.mPref.mMatch != match) { 3290 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3291 + Integer.toHexString(pa.mPref.mMatch)); 3292 continue; 3293 } 3294 // If it's not an "always" type preferred activity and that's what we're 3295 // looking for, skip it. 3296 if (always && !pa.mPref.mAlways) { 3297 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3298 continue; 3299 } 3300 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3301 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3302 if (DEBUG_PREFERRED || debug) { 3303 Slog.v(TAG, "Found preferred activity:"); 3304 if (ai != null) { 3305 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3306 } else { 3307 Slog.v(TAG, " null"); 3308 } 3309 } 3310 if (ai == null) { 3311 // This previously registered preferred activity 3312 // component is no longer known. Most likely an update 3313 // to the app was installed and in the new version this 3314 // component no longer exists. Clean it up by removing 3315 // it from the preferred activities list, and skip it. 3316 Slog.w(TAG, "Removing dangling preferred activity: " 3317 + pa.mPref.mComponent); 3318 pir.removeFilter(pa); 3319 continue; 3320 } 3321 for (int j=0; j<N; j++) { 3322 final ResolveInfo ri = query.get(j); 3323 if (!ri.activityInfo.applicationInfo.packageName 3324 .equals(ai.applicationInfo.packageName)) { 3325 continue; 3326 } 3327 if (!ri.activityInfo.name.equals(ai.name)) { 3328 continue; 3329 } 3330 3331 if (removeMatches) { 3332 pir.removeFilter(pa); 3333 if (DEBUG_PREFERRED) { 3334 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3335 } 3336 break; 3337 } 3338 3339 // Okay we found a previously set preferred or last chosen app. 3340 // If the result set is different from when this 3341 // was created, we need to clear it and re-ask the 3342 // user their preference, if we're looking for an "always" type entry. 3343 if (always && !pa.mPref.sameSet(query, priority)) { 3344 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3345 + intent + " type " + resolvedType); 3346 if (DEBUG_PREFERRED) { 3347 Slog.v(TAG, "Removing preferred activity since set changed " 3348 + pa.mPref.mComponent); 3349 } 3350 pir.removeFilter(pa); 3351 // Re-add the filter as a "last chosen" entry (!always) 3352 PreferredActivity lastChosen = new PreferredActivity( 3353 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3354 pir.addFilter(lastChosen); 3355 mSettings.writePackageRestrictionsLPr(userId); 3356 return null; 3357 } 3358 3359 // Yay! Either the set matched or we're looking for the last chosen 3360 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3361 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3362 mSettings.writePackageRestrictionsLPr(userId); 3363 return ri; 3364 } 3365 } 3366 } 3367 mSettings.writePackageRestrictionsLPr(userId); 3368 } 3369 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3370 return null; 3371 } 3372 3373 /* 3374 * Returns if intent can be forwarded from the userId from to dest 3375 */ 3376 @Override 3377 public boolean canForwardTo(Intent intent, String resolvedType, int userIdFrom, int userIdDest) { 3378 mContext.enforceCallingOrSelfPermission( 3379 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3380 List<ForwardingIntentFilter> matches = 3381 getMatchingForwardingIntentFilters(intent, resolvedType, userIdFrom); 3382 if (matches != null) { 3383 int size = matches.size(); 3384 for (int i = 0; i < size; i++) { 3385 if (matches.get(i).getUserIdDest() == userIdDest) return true; 3386 } 3387 } 3388 return false; 3389 } 3390 3391 private List<ForwardingIntentFilter> getMatchingForwardingIntentFilters(Intent intent, 3392 String resolvedType, int userId) { 3393 ForwardingIntentResolver fir = mSettings.mForwardingIntentResolvers.get(userId); 3394 if (fir != null) { 3395 return fir.queryIntent(intent, resolvedType, false, userId); 3396 } 3397 return null; 3398 } 3399 3400 @Override 3401 public List<ResolveInfo> queryIntentActivities(Intent intent, 3402 String resolvedType, int flags, int userId) { 3403 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3404 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3405 ComponentName comp = intent.getComponent(); 3406 if (comp == null) { 3407 if (intent.getSelector() != null) { 3408 intent = intent.getSelector(); 3409 comp = intent.getComponent(); 3410 } 3411 } 3412 3413 if (comp != null) { 3414 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3415 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3416 if (ai != null) { 3417 final ResolveInfo ri = new ResolveInfo(); 3418 ri.activityInfo = ai; 3419 list.add(ri); 3420 } 3421 return list; 3422 } 3423 3424 // reader 3425 synchronized (mPackages) { 3426 final String pkgName = intent.getPackage(); 3427 if (pkgName == null) { 3428 List<ResolveInfo> result = 3429 mActivities.queryIntent(intent, resolvedType, flags, userId); 3430 // Checking if we can forward the intent to another user 3431 List<ForwardingIntentFilter> fifs = 3432 getMatchingForwardingIntentFilters(intent, resolvedType, userId); 3433 if (fifs != null) { 3434 ForwardingIntentFilter forwardingIntentFilterWithResult = null; 3435 HashSet<Integer> alreadyTriedUserIds = new HashSet<Integer>(); 3436 for (ForwardingIntentFilter fif : fifs) { 3437 int userIdDest = fif.getUserIdDest(); 3438 // Two {@link ForwardingIntentFilter}s can have the same userIdDest and 3439 // match the same an intent. For performance reasons, it is better not to 3440 // run queryIntent twice for the same userId 3441 if (!alreadyTriedUserIds.contains(userIdDest)) { 3442 List<ResolveInfo> resultUser = mActivities.queryIntent(intent, 3443 resolvedType, flags, userIdDest); 3444 if (resultUser != null) { 3445 forwardingIntentFilterWithResult = fif; 3446 // As soon as there is a match in another user, we add the 3447 // intentForwarderActivity to the list of ResolveInfo. 3448 break; 3449 } 3450 alreadyTriedUserIds.add(userIdDest); 3451 } 3452 } 3453 if (forwardingIntentFilterWithResult != null) { 3454 ResolveInfo forwardingResolveInfo = createForwardingResolveInfo( 3455 forwardingIntentFilterWithResult, userId); 3456 result.add(forwardingResolveInfo); 3457 } 3458 } 3459 return result; 3460 } 3461 final PackageParser.Package pkg = mPackages.get(pkgName); 3462 if (pkg != null) { 3463 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3464 pkg.activities, userId); 3465 } 3466 return new ArrayList<ResolveInfo>(); 3467 } 3468 } 3469 3470 private ResolveInfo createForwardingResolveInfo(ForwardingIntentFilter fif, int userIdFrom) { 3471 String className; 3472 int userIdDest = fif.getUserIdDest(); 3473 if (userIdDest == UserHandle.USER_OWNER) { 3474 className = FORWARD_INTENT_TO_USER_OWNER; 3475 } else { 3476 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3477 } 3478 ComponentName forwardingActivityComponentName = new ComponentName( 3479 mAndroidApplication.packageName, className); 3480 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3481 userIdFrom); 3482 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3483 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3484 forwardingResolveInfo.priority = 0; 3485 forwardingResolveInfo.preferredOrder = 0; 3486 forwardingResolveInfo.match = 0; 3487 forwardingResolveInfo.isDefault = true; 3488 forwardingResolveInfo.filter = fif; 3489 return forwardingResolveInfo; 3490 } 3491 3492 @Override 3493 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3494 Intent[] specifics, String[] specificTypes, Intent intent, 3495 String resolvedType, int flags, int userId) { 3496 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3497 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3498 "query intent activity options"); 3499 final String resultsAction = intent.getAction(); 3500 3501 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3502 | PackageManager.GET_RESOLVED_FILTER, userId); 3503 3504 if (DEBUG_INTENT_MATCHING) { 3505 Log.v(TAG, "Query " + intent + ": " + results); 3506 } 3507 3508 int specificsPos = 0; 3509 int N; 3510 3511 // todo: note that the algorithm used here is O(N^2). This 3512 // isn't a problem in our current environment, but if we start running 3513 // into situations where we have more than 5 or 10 matches then this 3514 // should probably be changed to something smarter... 3515 3516 // First we go through and resolve each of the specific items 3517 // that were supplied, taking care of removing any corresponding 3518 // duplicate items in the generic resolve list. 3519 if (specifics != null) { 3520 for (int i=0; i<specifics.length; i++) { 3521 final Intent sintent = specifics[i]; 3522 if (sintent == null) { 3523 continue; 3524 } 3525 3526 if (DEBUG_INTENT_MATCHING) { 3527 Log.v(TAG, "Specific #" + i + ": " + sintent); 3528 } 3529 3530 String action = sintent.getAction(); 3531 if (resultsAction != null && resultsAction.equals(action)) { 3532 // If this action was explicitly requested, then don't 3533 // remove things that have it. 3534 action = null; 3535 } 3536 3537 ResolveInfo ri = null; 3538 ActivityInfo ai = null; 3539 3540 ComponentName comp = sintent.getComponent(); 3541 if (comp == null) { 3542 ri = resolveIntent( 3543 sintent, 3544 specificTypes != null ? specificTypes[i] : null, 3545 flags, userId); 3546 if (ri == null) { 3547 continue; 3548 } 3549 if (ri == mResolveInfo) { 3550 // ACK! Must do something better with this. 3551 } 3552 ai = ri.activityInfo; 3553 comp = new ComponentName(ai.applicationInfo.packageName, 3554 ai.name); 3555 } else { 3556 ai = getActivityInfo(comp, flags, userId); 3557 if (ai == null) { 3558 continue; 3559 } 3560 } 3561 3562 // Look for any generic query activities that are duplicates 3563 // of this specific one, and remove them from the results. 3564 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3565 N = results.size(); 3566 int j; 3567 for (j=specificsPos; j<N; j++) { 3568 ResolveInfo sri = results.get(j); 3569 if ((sri.activityInfo.name.equals(comp.getClassName()) 3570 && sri.activityInfo.applicationInfo.packageName.equals( 3571 comp.getPackageName())) 3572 || (action != null && sri.filter.matchAction(action))) { 3573 results.remove(j); 3574 if (DEBUG_INTENT_MATCHING) Log.v( 3575 TAG, "Removing duplicate item from " + j 3576 + " due to specific " + specificsPos); 3577 if (ri == null) { 3578 ri = sri; 3579 } 3580 j--; 3581 N--; 3582 } 3583 } 3584 3585 // Add this specific item to its proper place. 3586 if (ri == null) { 3587 ri = new ResolveInfo(); 3588 ri.activityInfo = ai; 3589 } 3590 results.add(specificsPos, ri); 3591 ri.specificIndex = i; 3592 specificsPos++; 3593 } 3594 } 3595 3596 // Now we go through the remaining generic results and remove any 3597 // duplicate actions that are found here. 3598 N = results.size(); 3599 for (int i=specificsPos; i<N-1; i++) { 3600 final ResolveInfo rii = results.get(i); 3601 if (rii.filter == null) { 3602 continue; 3603 } 3604 3605 // Iterate over all of the actions of this result's intent 3606 // filter... typically this should be just one. 3607 final Iterator<String> it = rii.filter.actionsIterator(); 3608 if (it == null) { 3609 continue; 3610 } 3611 while (it.hasNext()) { 3612 final String action = it.next(); 3613 if (resultsAction != null && resultsAction.equals(action)) { 3614 // If this action was explicitly requested, then don't 3615 // remove things that have it. 3616 continue; 3617 } 3618 for (int j=i+1; j<N; j++) { 3619 final ResolveInfo rij = results.get(j); 3620 if (rij.filter != null && rij.filter.hasAction(action)) { 3621 results.remove(j); 3622 if (DEBUG_INTENT_MATCHING) Log.v( 3623 TAG, "Removing duplicate item from " + j 3624 + " due to action " + action + " at " + i); 3625 j--; 3626 N--; 3627 } 3628 } 3629 } 3630 3631 // If the caller didn't request filter information, drop it now 3632 // so we don't have to marshall/unmarshall it. 3633 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3634 rii.filter = null; 3635 } 3636 } 3637 3638 // Filter out the caller activity if so requested. 3639 if (caller != null) { 3640 N = results.size(); 3641 for (int i=0; i<N; i++) { 3642 ActivityInfo ainfo = results.get(i).activityInfo; 3643 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3644 && caller.getClassName().equals(ainfo.name)) { 3645 results.remove(i); 3646 break; 3647 } 3648 } 3649 } 3650 3651 // If the caller didn't request filter information, 3652 // drop them now so we don't have to 3653 // marshall/unmarshall it. 3654 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3655 N = results.size(); 3656 for (int i=0; i<N; i++) { 3657 results.get(i).filter = null; 3658 } 3659 } 3660 3661 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3662 return results; 3663 } 3664 3665 @Override 3666 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3667 int userId) { 3668 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3669 ComponentName comp = intent.getComponent(); 3670 if (comp == null) { 3671 if (intent.getSelector() != null) { 3672 intent = intent.getSelector(); 3673 comp = intent.getComponent(); 3674 } 3675 } 3676 if (comp != null) { 3677 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3678 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3679 if (ai != null) { 3680 ResolveInfo ri = new ResolveInfo(); 3681 ri.activityInfo = ai; 3682 list.add(ri); 3683 } 3684 return list; 3685 } 3686 3687 // reader 3688 synchronized (mPackages) { 3689 String pkgName = intent.getPackage(); 3690 if (pkgName == null) { 3691 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3692 } 3693 final PackageParser.Package pkg = mPackages.get(pkgName); 3694 if (pkg != null) { 3695 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3696 userId); 3697 } 3698 return null; 3699 } 3700 } 3701 3702 @Override 3703 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3704 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3705 if (!sUserManager.exists(userId)) return null; 3706 if (query != null) { 3707 if (query.size() >= 1) { 3708 // If there is more than one service with the same priority, 3709 // just arbitrarily pick the first one. 3710 return query.get(0); 3711 } 3712 } 3713 return null; 3714 } 3715 3716 @Override 3717 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3718 int userId) { 3719 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3720 ComponentName comp = intent.getComponent(); 3721 if (comp == null) { 3722 if (intent.getSelector() != null) { 3723 intent = intent.getSelector(); 3724 comp = intent.getComponent(); 3725 } 3726 } 3727 if (comp != null) { 3728 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3729 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3730 if (si != null) { 3731 final ResolveInfo ri = new ResolveInfo(); 3732 ri.serviceInfo = si; 3733 list.add(ri); 3734 } 3735 return list; 3736 } 3737 3738 // reader 3739 synchronized (mPackages) { 3740 String pkgName = intent.getPackage(); 3741 if (pkgName == null) { 3742 return mServices.queryIntent(intent, resolvedType, flags, userId); 3743 } 3744 final PackageParser.Package pkg = mPackages.get(pkgName); 3745 if (pkg != null) { 3746 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3747 userId); 3748 } 3749 return null; 3750 } 3751 } 3752 3753 @Override 3754 public List<ResolveInfo> queryIntentContentProviders( 3755 Intent intent, String resolvedType, int flags, int userId) { 3756 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3757 ComponentName comp = intent.getComponent(); 3758 if (comp == null) { 3759 if (intent.getSelector() != null) { 3760 intent = intent.getSelector(); 3761 comp = intent.getComponent(); 3762 } 3763 } 3764 if (comp != null) { 3765 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3766 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3767 if (pi != null) { 3768 final ResolveInfo ri = new ResolveInfo(); 3769 ri.providerInfo = pi; 3770 list.add(ri); 3771 } 3772 return list; 3773 } 3774 3775 // reader 3776 synchronized (mPackages) { 3777 String pkgName = intent.getPackage(); 3778 if (pkgName == null) { 3779 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3780 } 3781 final PackageParser.Package pkg = mPackages.get(pkgName); 3782 if (pkg != null) { 3783 return mProviders.queryIntentForPackage( 3784 intent, resolvedType, flags, pkg.providers, userId); 3785 } 3786 return null; 3787 } 3788 } 3789 3790 @Override 3791 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3792 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3793 3794 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3795 3796 // writer 3797 synchronized (mPackages) { 3798 ArrayList<PackageInfo> list; 3799 if (listUninstalled) { 3800 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3801 for (PackageSetting ps : mSettings.mPackages.values()) { 3802 PackageInfo pi; 3803 if (ps.pkg != null) { 3804 pi = generatePackageInfo(ps.pkg, flags, userId); 3805 } else { 3806 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3807 } 3808 if (pi != null) { 3809 list.add(pi); 3810 } 3811 } 3812 } else { 3813 list = new ArrayList<PackageInfo>(mPackages.size()); 3814 for (PackageParser.Package p : mPackages.values()) { 3815 PackageInfo pi = generatePackageInfo(p, flags, userId); 3816 if (pi != null) { 3817 list.add(pi); 3818 } 3819 } 3820 } 3821 3822 return new ParceledListSlice<PackageInfo>(list); 3823 } 3824 } 3825 3826 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3827 String[] permissions, boolean[] tmp, int flags, int userId) { 3828 int numMatch = 0; 3829 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3830 for (int i=0; i<permissions.length; i++) { 3831 if (gp.grantedPermissions.contains(permissions[i])) { 3832 tmp[i] = true; 3833 numMatch++; 3834 } else { 3835 tmp[i] = false; 3836 } 3837 } 3838 if (numMatch == 0) { 3839 return; 3840 } 3841 PackageInfo pi; 3842 if (ps.pkg != null) { 3843 pi = generatePackageInfo(ps.pkg, flags, userId); 3844 } else { 3845 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3846 } 3847 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3848 if (numMatch == permissions.length) { 3849 pi.requestedPermissions = permissions; 3850 } else { 3851 pi.requestedPermissions = new String[numMatch]; 3852 numMatch = 0; 3853 for (int i=0; i<permissions.length; i++) { 3854 if (tmp[i]) { 3855 pi.requestedPermissions[numMatch] = permissions[i]; 3856 numMatch++; 3857 } 3858 } 3859 } 3860 } 3861 list.add(pi); 3862 } 3863 3864 @Override 3865 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3866 String[] permissions, int flags, int userId) { 3867 if (!sUserManager.exists(userId)) return null; 3868 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3869 3870 // writer 3871 synchronized (mPackages) { 3872 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3873 boolean[] tmpBools = new boolean[permissions.length]; 3874 if (listUninstalled) { 3875 for (PackageSetting ps : mSettings.mPackages.values()) { 3876 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3877 } 3878 } else { 3879 for (PackageParser.Package pkg : mPackages.values()) { 3880 PackageSetting ps = (PackageSetting)pkg.mExtras; 3881 if (ps != null) { 3882 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3883 userId); 3884 } 3885 } 3886 } 3887 3888 return new ParceledListSlice<PackageInfo>(list); 3889 } 3890 } 3891 3892 @Override 3893 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3894 if (!sUserManager.exists(userId)) return null; 3895 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3896 3897 // writer 3898 synchronized (mPackages) { 3899 ArrayList<ApplicationInfo> list; 3900 if (listUninstalled) { 3901 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3902 for (PackageSetting ps : mSettings.mPackages.values()) { 3903 ApplicationInfo ai; 3904 if (ps.pkg != null) { 3905 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3906 ps.readUserState(userId), userId); 3907 } else { 3908 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3909 } 3910 if (ai != null) { 3911 list.add(ai); 3912 } 3913 } 3914 } else { 3915 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3916 for (PackageParser.Package p : mPackages.values()) { 3917 if (p.mExtras != null) { 3918 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3919 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3920 if (ai != null) { 3921 list.add(ai); 3922 } 3923 } 3924 } 3925 } 3926 3927 return new ParceledListSlice<ApplicationInfo>(list); 3928 } 3929 } 3930 3931 public List<ApplicationInfo> getPersistentApplications(int flags) { 3932 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3933 3934 // reader 3935 synchronized (mPackages) { 3936 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3937 final int userId = UserHandle.getCallingUserId(); 3938 while (i.hasNext()) { 3939 final PackageParser.Package p = i.next(); 3940 if (p.applicationInfo != null 3941 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3942 && (!mSafeMode || isSystemApp(p))) { 3943 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3944 if (ps != null) { 3945 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3946 ps.readUserState(userId), userId); 3947 if (ai != null) { 3948 finalList.add(ai); 3949 } 3950 } 3951 } 3952 } 3953 } 3954 3955 return finalList; 3956 } 3957 3958 @Override 3959 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3960 if (!sUserManager.exists(userId)) return null; 3961 // reader 3962 synchronized (mPackages) { 3963 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3964 PackageSetting ps = provider != null 3965 ? mSettings.mPackages.get(provider.owner.packageName) 3966 : null; 3967 return ps != null 3968 && mSettings.isEnabledLPr(provider.info, flags, userId) 3969 && (!mSafeMode || (provider.info.applicationInfo.flags 3970 &ApplicationInfo.FLAG_SYSTEM) != 0) 3971 ? PackageParser.generateProviderInfo(provider, flags, 3972 ps.readUserState(userId), userId) 3973 : null; 3974 } 3975 } 3976 3977 /** 3978 * @deprecated 3979 */ 3980 @Deprecated 3981 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3982 // reader 3983 synchronized (mPackages) { 3984 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3985 .entrySet().iterator(); 3986 final int userId = UserHandle.getCallingUserId(); 3987 while (i.hasNext()) { 3988 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3989 PackageParser.Provider p = entry.getValue(); 3990 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3991 3992 if (ps != null && p.syncable 3993 && (!mSafeMode || (p.info.applicationInfo.flags 3994 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3995 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3996 ps.readUserState(userId), userId); 3997 if (info != null) { 3998 outNames.add(entry.getKey()); 3999 outInfo.add(info); 4000 } 4001 } 4002 } 4003 } 4004 } 4005 4006 @Override 4007 public List<ProviderInfo> queryContentProviders(String processName, 4008 int uid, int flags) { 4009 ArrayList<ProviderInfo> finalList = null; 4010 // reader 4011 synchronized (mPackages) { 4012 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4013 final int userId = processName != null ? 4014 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4015 while (i.hasNext()) { 4016 final PackageParser.Provider p = i.next(); 4017 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4018 if (ps != null && p.info.authority != null 4019 && (processName == null 4020 || (p.info.processName.equals(processName) 4021 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4022 && mSettings.isEnabledLPr(p.info, flags, userId) 4023 && (!mSafeMode 4024 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4025 if (finalList == null) { 4026 finalList = new ArrayList<ProviderInfo>(3); 4027 } 4028 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4029 ps.readUserState(userId), userId); 4030 if (info != null) { 4031 finalList.add(info); 4032 } 4033 } 4034 } 4035 } 4036 4037 if (finalList != null) { 4038 Collections.sort(finalList, mProviderInitOrderSorter); 4039 } 4040 4041 return finalList; 4042 } 4043 4044 @Override 4045 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4046 int flags) { 4047 // reader 4048 synchronized (mPackages) { 4049 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4050 return PackageParser.generateInstrumentationInfo(i, flags); 4051 } 4052 } 4053 4054 @Override 4055 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4056 int flags) { 4057 ArrayList<InstrumentationInfo> finalList = 4058 new ArrayList<InstrumentationInfo>(); 4059 4060 // reader 4061 synchronized (mPackages) { 4062 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4063 while (i.hasNext()) { 4064 final PackageParser.Instrumentation p = i.next(); 4065 if (targetPackage == null 4066 || targetPackage.equals(p.info.targetPackage)) { 4067 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4068 flags); 4069 if (ii != null) { 4070 finalList.add(ii); 4071 } 4072 } 4073 } 4074 } 4075 4076 return finalList; 4077 } 4078 4079 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4080 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4081 if (overlays == null) { 4082 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4083 return; 4084 } 4085 for (PackageParser.Package opkg : overlays.values()) { 4086 // Not much to do if idmap fails: we already logged the error 4087 // and we certainly don't want to abort installation of pkg simply 4088 // because an overlay didn't fit properly. For these reasons, 4089 // ignore the return value of createIdmapForPackagePairLI. 4090 createIdmapForPackagePairLI(pkg, opkg); 4091 } 4092 } 4093 4094 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4095 PackageParser.Package opkg) { 4096 if (!opkg.mTrustedOverlay) { 4097 Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " + 4098 opkg.mScanPath + ": overlay not trusted"); 4099 return false; 4100 } 4101 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4102 if (overlaySet == null) { 4103 Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " + 4104 opkg.mScanPath + " but target package has no known overlays"); 4105 return false; 4106 } 4107 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4108 if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) { 4109 Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath); 4110 return false; 4111 } 4112 PackageParser.Package[] overlayArray = 4113 overlaySet.values().toArray(new PackageParser.Package[0]); 4114 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4115 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4116 return p1.mOverlayPriority - p2.mOverlayPriority; 4117 } 4118 }; 4119 Arrays.sort(overlayArray, cmp); 4120 4121 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4122 int i = 0; 4123 for (PackageParser.Package p : overlayArray) { 4124 pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir; 4125 } 4126 return true; 4127 } 4128 4129 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4130 String[] files = dir.list(); 4131 if (files == null) { 4132 Log.d(TAG, "No files in app dir " + dir); 4133 return; 4134 } 4135 4136 if (DEBUG_PACKAGE_SCANNING) { 4137 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4138 + " flags=0x" + Integer.toHexString(flags)); 4139 } 4140 4141 int i; 4142 for (i=0; i<files.length; i++) { 4143 File file = new File(dir, files[i]); 4144 if (!isPackageFilename(files[i])) { 4145 // Ignore entries which are not apk's 4146 continue; 4147 } 4148 PackageParser.Package pkg = scanPackageLI(file, 4149 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null); 4150 // Don't mess around with apps in system partition. 4151 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4152 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 4153 // Delete the apk 4154 Slog.w(TAG, "Cleaning up failed install of " + file); 4155 file.delete(); 4156 } 4157 } 4158 } 4159 4160 private static File getSettingsProblemFile() { 4161 File dataDir = Environment.getDataDirectory(); 4162 File systemDir = new File(dataDir, "system"); 4163 File fname = new File(systemDir, "uiderrors.txt"); 4164 return fname; 4165 } 4166 4167 static void reportSettingsProblem(int priority, String msg) { 4168 try { 4169 File fname = getSettingsProblemFile(); 4170 FileOutputStream out = new FileOutputStream(fname, true); 4171 PrintWriter pw = new FastPrintWriter(out); 4172 SimpleDateFormat formatter = new SimpleDateFormat(); 4173 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4174 pw.println(dateString + ": " + msg); 4175 pw.close(); 4176 FileUtils.setPermissions( 4177 fname.toString(), 4178 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4179 -1, -1); 4180 } catch (java.io.IOException e) { 4181 } 4182 Slog.println(priority, TAG, msg); 4183 } 4184 4185 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 4186 PackageParser.Package pkg, File srcFile, int parseFlags) { 4187 if (ps != null 4188 && ps.codePath.equals(srcFile) 4189 && ps.timeStamp == srcFile.lastModified() 4190 && !isCompatSignatureUpdateNeeded(pkg)) { 4191 if (ps.signatures.mSignatures != null 4192 && ps.signatures.mSignatures.length != 0) { 4193 // Optimization: reuse the existing cached certificates 4194 // if the package appears to be unchanged. 4195 pkg.mSignatures = ps.signatures.mSignatures; 4196 return true; 4197 } 4198 4199 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 4200 } else { 4201 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4202 } 4203 4204 if (!pp.collectCertificates(pkg, parseFlags)) { 4205 mLastScanError = pp.getParseError(); 4206 return false; 4207 } 4208 return true; 4209 } 4210 4211 /* 4212 * Scan a package and return the newly parsed package. 4213 * Returns null in case of errors and the error code is stored in mLastScanError 4214 */ 4215 private PackageParser.Package scanPackageLI(File scanFile, 4216 int parseFlags, int scanMode, long currentTime, UserHandle user) { 4217 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 4218 String scanPath = scanFile.getPath(); 4219 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath); 4220 parseFlags |= mDefParseFlags; 4221 PackageParser pp = new PackageParser(scanPath); 4222 pp.setSeparateProcesses(mSeparateProcesses); 4223 pp.setOnlyCoreApps(mOnlyCore); 4224 final PackageParser.Package pkg = pp.parsePackage(scanFile, 4225 scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0); 4226 4227 if (pkg == null) { 4228 mLastScanError = pp.getParseError(); 4229 return null; 4230 } 4231 4232 PackageSetting ps = null; 4233 PackageSetting updatedPkg; 4234 // reader 4235 synchronized (mPackages) { 4236 // Look to see if we already know about this package. 4237 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4238 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4239 // This package has been renamed to its original name. Let's 4240 // use that. 4241 ps = mSettings.peekPackageLPr(oldName); 4242 } 4243 // If there was no original package, see one for the real package name. 4244 if (ps == null) { 4245 ps = mSettings.peekPackageLPr(pkg.packageName); 4246 } 4247 // Check to see if this package could be hiding/updating a system 4248 // package. Must look for it either under the original or real 4249 // package name depending on our state. 4250 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4251 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4252 } 4253 boolean updatedPkgBetter = false; 4254 // First check if this is a system package that may involve an update 4255 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4256 if (ps != null && !ps.codePath.equals(scanFile)) { 4257 // The path has changed from what was last scanned... check the 4258 // version of the new path against what we have stored to determine 4259 // what to do. 4260 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4261 if (pkg.mVersionCode < ps.versionCode) { 4262 // The system package has been updated and the code path does not match 4263 // Ignore entry. Skip it. 4264 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4265 + " ignored: updated version " + ps.versionCode 4266 + " better than this " + pkg.mVersionCode); 4267 if (!updatedPkg.codePath.equals(scanFile)) { 4268 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4269 + ps.name + " changing from " + updatedPkg.codePathString 4270 + " to " + scanFile); 4271 updatedPkg.codePath = scanFile; 4272 updatedPkg.codePathString = scanFile.toString(); 4273 // This is the point at which we know that the system-disk APK 4274 // for this package has moved during a reboot (e.g. due to an OTA), 4275 // so we need to reevaluate it for privilege policy. 4276 if (locationIsPrivileged(scanFile)) { 4277 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4278 } 4279 } 4280 updatedPkg.pkg = pkg; 4281 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4282 return null; 4283 } else { 4284 // The current app on the system partion is better than 4285 // what we have updated to on the data partition; switch 4286 // back to the system partition version. 4287 // At this point, its safely assumed that package installation for 4288 // apps in system partition will go through. If not there won't be a working 4289 // version of the app 4290 // writer 4291 synchronized (mPackages) { 4292 // Just remove the loaded entries from package lists. 4293 mPackages.remove(ps.name); 4294 } 4295 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4296 + "reverting from " + ps.codePathString 4297 + ": new version " + pkg.mVersionCode 4298 + " better than installed " + ps.versionCode); 4299 4300 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4301 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4302 getAppInstructionSetFromSettings(ps)); 4303 synchronized (mInstallLock) { 4304 args.cleanUpResourcesLI(); 4305 } 4306 synchronized (mPackages) { 4307 mSettings.enableSystemPackageLPw(ps.name); 4308 } 4309 updatedPkgBetter = true; 4310 } 4311 } 4312 } 4313 4314 if (updatedPkg != null) { 4315 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4316 // initially 4317 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4318 4319 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4320 // flag set initially 4321 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4322 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4323 } 4324 } 4325 // Verify certificates against what was last scanned 4326 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 4327 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 4328 return null; 4329 } 4330 4331 /* 4332 * A new system app appeared, but we already had a non-system one of the 4333 * same name installed earlier. 4334 */ 4335 boolean shouldHideSystemApp = false; 4336 if (updatedPkg == null && ps != null 4337 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4338 /* 4339 * Check to make sure the signatures match first. If they don't, 4340 * wipe the installed application and its data. 4341 */ 4342 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4343 != PackageManager.SIGNATURE_MATCH) { 4344 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4345 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4346 ps = null; 4347 } else { 4348 /* 4349 * If the newly-added system app is an older version than the 4350 * already installed version, hide it. It will be scanned later 4351 * and re-added like an update. 4352 */ 4353 if (pkg.mVersionCode < ps.versionCode) { 4354 shouldHideSystemApp = true; 4355 } else { 4356 /* 4357 * The newly found system app is a newer version that the 4358 * one previously installed. Simply remove the 4359 * already-installed application and replace it with our own 4360 * while keeping the application data. 4361 */ 4362 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4363 + ps.codePathString + ": new version " + pkg.mVersionCode 4364 + " better than installed " + ps.versionCode); 4365 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4366 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4367 getAppInstructionSetFromSettings(ps)); 4368 synchronized (mInstallLock) { 4369 args.cleanUpResourcesLI(); 4370 } 4371 } 4372 } 4373 } 4374 4375 // The apk is forward locked (not public) if its code and resources 4376 // are kept in different files. (except for app in either system or 4377 // vendor path). 4378 // TODO grab this value from PackageSettings 4379 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4380 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4381 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4382 } 4383 } 4384 4385 String codePath = null; 4386 String resPath = null; 4387 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4388 if (ps != null && ps.resourcePathString != null) { 4389 resPath = ps.resourcePathString; 4390 } else { 4391 // Should not happen at all. Just log an error. 4392 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4393 } 4394 } else { 4395 resPath = pkg.mScanPath; 4396 } 4397 4398 codePath = pkg.mScanPath; 4399 // Set application objects path explicitly. 4400 setApplicationInfoPaths(pkg, codePath, resPath); 4401 // Note that we invoke the following method only if we are about to unpack an application 4402 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4403 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4404 4405 /* 4406 * If the system app should be overridden by a previously installed 4407 * data, hide the system app now and let the /data/app scan pick it up 4408 * again. 4409 */ 4410 if (shouldHideSystemApp) { 4411 synchronized (mPackages) { 4412 /* 4413 * We have to grant systems permissions before we hide, because 4414 * grantPermissions will assume the package update is trying to 4415 * expand its permissions. 4416 */ 4417 grantPermissionsLPw(pkg, true); 4418 mSettings.disableSystemPackageLPw(pkg.packageName); 4419 } 4420 } 4421 4422 return scannedPkg; 4423 } 4424 4425 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath, 4426 String destResPath) { 4427 pkg.mPath = pkg.mScanPath = destCodePath; 4428 pkg.applicationInfo.sourceDir = destCodePath; 4429 pkg.applicationInfo.publicSourceDir = destResPath; 4430 } 4431 4432 private static String fixProcessName(String defProcessName, 4433 String processName, int uid) { 4434 if (processName == null) { 4435 return defProcessName; 4436 } 4437 return processName; 4438 } 4439 4440 private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) { 4441 if (pkgSetting.signatures.mSignatures != null) { 4442 // Already existing package. Make sure signatures match 4443 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4444 == PackageManager.SIGNATURE_MATCH; 4445 if (!match) { 4446 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4447 == PackageManager.SIGNATURE_MATCH; 4448 } 4449 if (!match) { 4450 Slog.e(TAG, "Package " + pkg.packageName 4451 + " signatures do not match the previously installed version; ignoring!"); 4452 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4453 return false; 4454 } 4455 } 4456 // Check for shared user signatures 4457 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4458 // Already existing package. Make sure signatures match 4459 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4460 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4461 if (!match) { 4462 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4463 == PackageManager.SIGNATURE_MATCH; 4464 } 4465 if (!match) { 4466 Slog.e(TAG, "Package " + pkg.packageName 4467 + " has no signatures that match those in shared user " 4468 + pkgSetting.sharedUser.name + "; ignoring!"); 4469 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4470 return false; 4471 } 4472 } 4473 return true; 4474 } 4475 4476 /** 4477 * Enforces that only the system UID or root's UID can call a method exposed 4478 * via Binder. 4479 * 4480 * @param message used as message if SecurityException is thrown 4481 * @throws SecurityException if the caller is not system or root 4482 */ 4483 private static final void enforceSystemOrRoot(String message) { 4484 final int uid = Binder.getCallingUid(); 4485 if (uid != Process.SYSTEM_UID && uid != 0) { 4486 throw new SecurityException(message); 4487 } 4488 } 4489 4490 @Override 4491 public void performBootDexOpt() { 4492 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4493 4494 final HashSet<PackageParser.Package> pkgs; 4495 synchronized (mPackages) { 4496 pkgs = mDeferredDexOpt; 4497 mDeferredDexOpt = null; 4498 } 4499 4500 if (pkgs != null) { 4501 // Filter out packages that aren't recently used. 4502 // 4503 // The exception is first boot of a non-eng device, which 4504 // should do a full dexopt. 4505 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4506 if (eng || !isFirstBoot()) { 4507 // TODO: add a property to control this? 4508 long dexOptLRUThresholdInMinutes; 4509 if (eng) { 4510 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4511 } else { 4512 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4513 } 4514 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4515 4516 int total = pkgs.size(); 4517 int skipped = 0; 4518 long now = System.currentTimeMillis(); 4519 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4520 PackageParser.Package pkg = i.next(); 4521 long then = pkg.mLastPackageUsageTimeInMills; 4522 if (then + dexOptLRUThresholdInMills < now) { 4523 if (DEBUG_DEXOPT) { 4524 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4525 ((then == 0) ? "never" : new Date(then))); 4526 } 4527 i.remove(); 4528 skipped++; 4529 } 4530 } 4531 if (DEBUG_DEXOPT) { 4532 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4533 } 4534 } 4535 4536 int i = 0; 4537 for (PackageParser.Package pkg : pkgs) { 4538 i++; 4539 if (DEBUG_DEXOPT) { 4540 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4541 + ": " + pkg.packageName); 4542 } 4543 if (!isFirstBoot()) { 4544 try { 4545 ActivityManagerNative.getDefault().showBootMessage( 4546 mContext.getResources().getString( 4547 R.string.android_upgrading_apk, 4548 i, pkgs.size()), true); 4549 } catch (RemoteException e) { 4550 } 4551 } 4552 PackageParser.Package p = pkg; 4553 synchronized (mInstallLock) { 4554 if (p.mDexOptNeeded) { 4555 performDexOptLI(p, false /* force dex */, false /* defer */, 4556 true /* include dependencies */); 4557 } 4558 } 4559 } 4560 } 4561 } 4562 4563 @Override 4564 public boolean performDexOpt(String packageName) { 4565 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4566 return performDexOpt(packageName, true); 4567 } 4568 4569 public boolean performDexOpt(String packageName, boolean updateUsage) { 4570 4571 PackageParser.Package p; 4572 synchronized (mPackages) { 4573 p = mPackages.get(packageName); 4574 if (p == null) { 4575 return false; 4576 } 4577 if (updateUsage) { 4578 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4579 } 4580 mPackageUsage.write(false); 4581 if (!p.mDexOptNeeded) { 4582 return false; 4583 } 4584 } 4585 4586 synchronized (mInstallLock) { 4587 return performDexOptLI(p, false /* force dex */, false /* defer */, 4588 true /* include dependencies */) == DEX_OPT_PERFORMED; 4589 } 4590 } 4591 4592 public HashSet<String> getPackagesThatNeedDexOpt() { 4593 HashSet<String> pkgs = null; 4594 synchronized (mPackages) { 4595 for (PackageParser.Package p : mPackages.values()) { 4596 if (DEBUG_DEXOPT) { 4597 Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded); 4598 } 4599 if (!p.mDexOptNeeded) { 4600 continue; 4601 } 4602 if (pkgs == null) { 4603 pkgs = new HashSet<String>(); 4604 } 4605 pkgs.add(p.packageName); 4606 } 4607 } 4608 return pkgs; 4609 } 4610 4611 public void shutdown() { 4612 mPackageUsage.write(true); 4613 } 4614 4615 private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, 4616 boolean forceDex, boolean defer, HashSet<String> done) { 4617 for (int i=0; i<libs.size(); i++) { 4618 PackageParser.Package libPkg; 4619 String libName; 4620 synchronized (mPackages) { 4621 libName = libs.get(i); 4622 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4623 if (lib != null && lib.apk != null) { 4624 libPkg = mPackages.get(lib.apk); 4625 } else { 4626 libPkg = null; 4627 } 4628 } 4629 if (libPkg != null && !done.contains(libName)) { 4630 performDexOptLI(libPkg, instructionSet, forceDex, defer, done); 4631 } 4632 } 4633 } 4634 4635 static final int DEX_OPT_SKIPPED = 0; 4636 static final int DEX_OPT_PERFORMED = 1; 4637 static final int DEX_OPT_DEFERRED = 2; 4638 static final int DEX_OPT_FAILED = -1; 4639 4640 private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride, 4641 boolean forceDex, boolean defer, HashSet<String> done) { 4642 final String instructionSet = instructionSetOverride != null ? 4643 instructionSetOverride : getAppInstructionSet(pkg.applicationInfo); 4644 4645 if (done != null) { 4646 done.add(pkg.packageName); 4647 if (pkg.usesLibraries != null) { 4648 performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done); 4649 } 4650 if (pkg.usesOptionalLibraries != null) { 4651 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done); 4652 } 4653 } 4654 4655 boolean performed = false; 4656 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 4657 String path = pkg.mScanPath; 4658 try { 4659 boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path, 4660 pkg.packageName, 4661 instructionSet, 4662 defer); 4663 // There are three basic cases here: 4664 // 1.) we need to dexopt, either because we are forced or it is needed 4665 // 2.) we are defering a needed dexopt 4666 // 3.) we are skipping an unneeded dexopt 4667 if (forceDex || (!defer && isDexOptNeededInternal)) { 4668 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName); 4669 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4670 int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4671 pkg.packageName, instructionSet); 4672 // Note that we ran dexopt, since rerunning will 4673 // probably just result in an error again. 4674 pkg.mDexOptNeeded = false; 4675 if (ret < 0) { 4676 return DEX_OPT_FAILED; 4677 } 4678 return DEX_OPT_PERFORMED; 4679 } 4680 if (defer && isDexOptNeededInternal) { 4681 if (mDeferredDexOpt == null) { 4682 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4683 } 4684 mDeferredDexOpt.add(pkg); 4685 return DEX_OPT_DEFERRED; 4686 } 4687 pkg.mDexOptNeeded = false; 4688 return DEX_OPT_SKIPPED; 4689 } catch (FileNotFoundException e) { 4690 Slog.w(TAG, "Apk not found for dexopt: " + path); 4691 return DEX_OPT_FAILED; 4692 } catch (IOException e) { 4693 Slog.w(TAG, "IOException reading apk: " + path, e); 4694 return DEX_OPT_FAILED; 4695 } catch (StaleDexCacheError e) { 4696 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4697 return DEX_OPT_FAILED; 4698 } catch (Exception e) { 4699 Slog.w(TAG, "Exception when doing dexopt : ", e); 4700 return DEX_OPT_FAILED; 4701 } 4702 } 4703 return DEX_OPT_SKIPPED; 4704 } 4705 4706 private String getAppInstructionSet(ApplicationInfo info) { 4707 String instructionSet = getPreferredInstructionSet(); 4708 4709 if (info.cpuAbi != null) { 4710 instructionSet = VMRuntime.getInstructionSet(info.cpuAbi); 4711 } 4712 4713 return instructionSet; 4714 } 4715 4716 private String getAppInstructionSetFromSettings(PackageSetting ps) { 4717 String instructionSet = getPreferredInstructionSet(); 4718 4719 if (ps.cpuAbiString != null) { 4720 instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 4721 } 4722 4723 return instructionSet; 4724 } 4725 4726 private static String getPreferredInstructionSet() { 4727 if (sPreferredInstructionSet == null) { 4728 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4729 } 4730 4731 return sPreferredInstructionSet; 4732 } 4733 4734 private static List<String> getAllInstructionSets() { 4735 final String[] allAbis = Build.SUPPORTED_ABIS; 4736 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4737 4738 for (String abi : allAbis) { 4739 final String instructionSet = VMRuntime.getInstructionSet(abi); 4740 if (!allInstructionSets.contains(instructionSet)) { 4741 allInstructionSets.add(instructionSet); 4742 } 4743 } 4744 4745 return allInstructionSets; 4746 } 4747 4748 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4749 boolean inclDependencies) { 4750 HashSet<String> done; 4751 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4752 done = new HashSet<String>(); 4753 done.add(pkg.packageName); 4754 } else { 4755 done = null; 4756 } 4757 return performDexOptLI(pkg, null /* instruction set override */, forceDex, defer, done); 4758 } 4759 4760 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4761 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4762 Slog.w(TAG, "Unable to update from " + oldPkg.name 4763 + " to " + newPkg.packageName 4764 + ": old package not in system partition"); 4765 return false; 4766 } else if (mPackages.get(oldPkg.name) != null) { 4767 Slog.w(TAG, "Unable to update from " + oldPkg.name 4768 + " to " + newPkg.packageName 4769 + ": old package still exists"); 4770 return false; 4771 } 4772 return true; 4773 } 4774 4775 File getDataPathForUser(int userId) { 4776 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4777 } 4778 4779 private File getDataPathForPackage(String packageName, int userId) { 4780 /* 4781 * Until we fully support multiple users, return the directory we 4782 * previously would have. The PackageManagerTests will need to be 4783 * revised when this is changed back.. 4784 */ 4785 if (userId == 0) { 4786 return new File(mAppDataDir, packageName); 4787 } else { 4788 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4789 + File.separator + packageName); 4790 } 4791 } 4792 4793 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4794 int[] users = sUserManager.getUserIds(); 4795 int res = mInstaller.install(packageName, uid, uid, seinfo); 4796 if (res < 0) { 4797 return res; 4798 } 4799 for (int user : users) { 4800 if (user != 0) { 4801 res = mInstaller.createUserData(packageName, 4802 UserHandle.getUid(user, uid), user, seinfo); 4803 if (res < 0) { 4804 return res; 4805 } 4806 } 4807 } 4808 return res; 4809 } 4810 4811 private int removeDataDirsLI(String packageName) { 4812 int[] users = sUserManager.getUserIds(); 4813 int res = 0; 4814 for (int user : users) { 4815 int resInner = mInstaller.remove(packageName, user); 4816 if (resInner < 0) { 4817 res = resInner; 4818 } 4819 } 4820 4821 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4822 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4823 if (!nativeLibraryFile.delete()) { 4824 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4825 } 4826 4827 return res; 4828 } 4829 4830 private int addSharedLibraryLPw(final SharedLibraryEntry file, int num, 4831 PackageParser.Package changingLib) { 4832 if (file.path != null) { 4833 mTmpSharedLibraries[num] = file.path; 4834 return num+1; 4835 } 4836 PackageParser.Package p = mPackages.get(file.apk); 4837 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4838 // If we are doing this while in the middle of updating a library apk, 4839 // then we need to make sure to use that new apk for determining the 4840 // dependencies here. (We haven't yet finished committing the new apk 4841 // to the package manager state.) 4842 if (p == null || p.packageName.equals(changingLib.packageName)) { 4843 p = changingLib; 4844 } 4845 } 4846 if (p != null) { 4847 String path = p.mPath; 4848 for (int i=0; i<num; i++) { 4849 if (mTmpSharedLibraries[i].equals(path)) { 4850 return num; 4851 } 4852 } 4853 mTmpSharedLibraries[num] = p.mPath; 4854 return num+1; 4855 } 4856 return num; 4857 } 4858 4859 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4860 PackageParser.Package changingLib) { 4861 // We might be upgrading from a version of the platform that did not 4862 // provide per-package native library directories for system apps. 4863 // Fix that up here. 4864 if (isSystemApp(pkg)) { 4865 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4866 setInternalAppNativeLibraryPath(pkg, ps); 4867 } 4868 4869 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4870 if (mTmpSharedLibraries == null || 4871 mTmpSharedLibraries.length < mSharedLibraries.size()) { 4872 mTmpSharedLibraries = new String[mSharedLibraries.size()]; 4873 } 4874 int num = 0; 4875 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4876 for (int i=0; i<N; i++) { 4877 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4878 if (file == null) { 4879 Slog.e(TAG, "Package " + pkg.packageName 4880 + " requires unavailable shared library " 4881 + pkg.usesLibraries.get(i) + "; failing!"); 4882 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4883 return false; 4884 } 4885 num = addSharedLibraryLPw(file, num, changingLib); 4886 } 4887 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4888 for (int i=0; i<N; i++) { 4889 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4890 if (file == null) { 4891 Slog.w(TAG, "Package " + pkg.packageName 4892 + " desires unavailable shared library " 4893 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4894 } else { 4895 num = addSharedLibraryLPw(file, num, changingLib); 4896 } 4897 } 4898 if (num > 0) { 4899 pkg.usesLibraryFiles = new String[num]; 4900 System.arraycopy(mTmpSharedLibraries, 0, 4901 pkg.usesLibraryFiles, 0, num); 4902 } else { 4903 pkg.usesLibraryFiles = null; 4904 } 4905 } 4906 return true; 4907 } 4908 4909 private static boolean hasString(List<String> list, List<String> which) { 4910 if (list == null) { 4911 return false; 4912 } 4913 for (int i=list.size()-1; i>=0; i--) { 4914 for (int j=which.size()-1; j>=0; j--) { 4915 if (which.get(j).equals(list.get(i))) { 4916 return true; 4917 } 4918 } 4919 } 4920 return false; 4921 } 4922 4923 private void updateAllSharedLibrariesLPw() { 4924 for (PackageParser.Package pkg : mPackages.values()) { 4925 updateSharedLibrariesLPw(pkg, null); 4926 } 4927 } 4928 4929 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4930 PackageParser.Package changingPkg) { 4931 ArrayList<PackageParser.Package> res = null; 4932 for (PackageParser.Package pkg : mPackages.values()) { 4933 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4934 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4935 if (res == null) { 4936 res = new ArrayList<PackageParser.Package>(); 4937 } 4938 res.add(pkg); 4939 updateSharedLibrariesLPw(pkg, changingPkg); 4940 } 4941 } 4942 return res; 4943 } 4944 4945 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4946 int parseFlags, int scanMode, long currentTime, UserHandle user) { 4947 File scanFile = new File(pkg.mScanPath); 4948 if (scanFile == null || pkg.applicationInfo.sourceDir == null || 4949 pkg.applicationInfo.publicSourceDir == null) { 4950 // Bail out. The resource and code paths haven't been set. 4951 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4952 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4953 return null; 4954 } 4955 4956 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4957 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4958 } 4959 4960 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4961 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4962 } 4963 4964 if (mCustomResolverComponentName != null && 4965 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4966 setUpCustomResolverActivity(pkg); 4967 } 4968 4969 if (pkg.packageName.equals("android")) { 4970 synchronized (mPackages) { 4971 if (mAndroidApplication != null) { 4972 Slog.w(TAG, "*************************************************"); 4973 Slog.w(TAG, "Core android package being redefined. Skipping."); 4974 Slog.w(TAG, " file=" + scanFile); 4975 Slog.w(TAG, "*************************************************"); 4976 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4977 return null; 4978 } 4979 4980 // Set up information for our fall-back user intent resolution activity. 4981 mPlatformPackage = pkg; 4982 pkg.mVersionCode = mSdkVersion; 4983 mAndroidApplication = pkg.applicationInfo; 4984 4985 if (!mResolverReplaced) { 4986 mResolveActivity.applicationInfo = mAndroidApplication; 4987 mResolveActivity.name = ResolverActivity.class.getName(); 4988 mResolveActivity.packageName = mAndroidApplication.packageName; 4989 mResolveActivity.processName = "system:ui"; 4990 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4991 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4992 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 4993 mResolveActivity.exported = true; 4994 mResolveActivity.enabled = true; 4995 mResolveInfo.activityInfo = mResolveActivity; 4996 mResolveInfo.priority = 0; 4997 mResolveInfo.preferredOrder = 0; 4998 mResolveInfo.match = 0; 4999 mResolveComponentName = new ComponentName( 5000 mAndroidApplication.packageName, mResolveActivity.name); 5001 } 5002 } 5003 } 5004 5005 if (DEBUG_PACKAGE_SCANNING) { 5006 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5007 Log.d(TAG, "Scanning package " + pkg.packageName); 5008 } 5009 5010 if (mPackages.containsKey(pkg.packageName) 5011 || mSharedLibraries.containsKey(pkg.packageName)) { 5012 Slog.w(TAG, "Application package " + pkg.packageName 5013 + " already installed. Skipping duplicate."); 5014 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 5015 return null; 5016 } 5017 5018 // Initialize package source and resource directories 5019 File destCodeFile = new File(pkg.applicationInfo.sourceDir); 5020 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir); 5021 5022 SharedUserSetting suid = null; 5023 PackageSetting pkgSetting = null; 5024 5025 if (!isSystemApp(pkg)) { 5026 // Only system apps can use these features. 5027 pkg.mOriginalPackages = null; 5028 pkg.mRealPackage = null; 5029 pkg.mAdoptPermissions = null; 5030 } 5031 5032 // writer 5033 synchronized (mPackages) { 5034 if (pkg.mSharedUserId != null) { 5035 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5036 if (suid == null) { 5037 Slog.w(TAG, "Creating application package " + pkg.packageName 5038 + " for shared user failed"); 5039 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5040 return null; 5041 } 5042 if (DEBUG_PACKAGE_SCANNING) { 5043 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5044 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5045 + "): packages=" + suid.packages); 5046 } 5047 } 5048 5049 // Check if we are renaming from an original package name. 5050 PackageSetting origPackage = null; 5051 String realName = null; 5052 if (pkg.mOriginalPackages != null) { 5053 // This package may need to be renamed to a previously 5054 // installed name. Let's check on that... 5055 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5056 if (pkg.mOriginalPackages.contains(renamed)) { 5057 // This package had originally been installed as the 5058 // original name, and we have already taken care of 5059 // transitioning to the new one. Just update the new 5060 // one to continue using the old name. 5061 realName = pkg.mRealPackage; 5062 if (!pkg.packageName.equals(renamed)) { 5063 // Callers into this function may have already taken 5064 // care of renaming the package; only do it here if 5065 // it is not already done. 5066 pkg.setPackageName(renamed); 5067 } 5068 5069 } else { 5070 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5071 if ((origPackage = mSettings.peekPackageLPr( 5072 pkg.mOriginalPackages.get(i))) != null) { 5073 // We do have the package already installed under its 5074 // original name... should we use it? 5075 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5076 // New package is not compatible with original. 5077 origPackage = null; 5078 continue; 5079 } else if (origPackage.sharedUser != null) { 5080 // Make sure uid is compatible between packages. 5081 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5082 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5083 + " to " + pkg.packageName + ": old uid " 5084 + origPackage.sharedUser.name 5085 + " differs from " + pkg.mSharedUserId); 5086 origPackage = null; 5087 continue; 5088 } 5089 } else { 5090 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5091 + pkg.packageName + " to old name " + origPackage.name); 5092 } 5093 break; 5094 } 5095 } 5096 } 5097 } 5098 5099 if (mTransferedPackages.contains(pkg.packageName)) { 5100 Slog.w(TAG, "Package " + pkg.packageName 5101 + " was transferred to another, but its .apk remains"); 5102 } 5103 5104 // Just create the setting, don't add it yet. For already existing packages 5105 // the PkgSetting exists already and doesn't have to be created. 5106 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5107 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 5108 pkg.applicationInfo.cpuAbi, 5109 pkg.applicationInfo.flags, user, false); 5110 if (pkgSetting == null) { 5111 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 5112 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5113 return null; 5114 } 5115 5116 if (pkgSetting.origPackage != null) { 5117 // If we are first transitioning from an original package, 5118 // fix up the new package's name now. We need to do this after 5119 // looking up the package under its new name, so getPackageLP 5120 // can take care of fiddling things correctly. 5121 pkg.setPackageName(origPackage.name); 5122 5123 // File a report about this. 5124 String msg = "New package " + pkgSetting.realName 5125 + " renamed to replace old package " + pkgSetting.name; 5126 reportSettingsProblem(Log.WARN, msg); 5127 5128 // Make a note of it. 5129 mTransferedPackages.add(origPackage.name); 5130 5131 // No longer need to retain this. 5132 pkgSetting.origPackage = null; 5133 } 5134 5135 if (realName != null) { 5136 // Make a note of it. 5137 mTransferedPackages.add(pkg.packageName); 5138 } 5139 5140 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5141 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5142 } 5143 5144 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5145 // Check all shared libraries and map to their actual file path. 5146 // We only do this here for apps not on a system dir, because those 5147 // are the only ones that can fail an install due to this. We 5148 // will take care of the system apps by updating all of their 5149 // library paths after the scan is done. 5150 if (!updateSharedLibrariesLPw(pkg, null)) { 5151 return null; 5152 } 5153 } 5154 5155 if (mFoundPolicyFile) { 5156 SELinuxMMAC.assignSeinfoValue(pkg); 5157 } 5158 5159 pkg.applicationInfo.uid = pkgSetting.appId; 5160 pkg.mExtras = pkgSetting; 5161 5162 if (!verifySignaturesLP(pkgSetting, pkg)) { 5163 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5164 return null; 5165 } 5166 // The signature has changed, but this package is in the system 5167 // image... let's recover! 5168 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5169 // However... if this package is part of a shared user, but it 5170 // doesn't match the signature of the shared user, let's fail. 5171 // What this means is that you can't change the signatures 5172 // associated with an overall shared user, which doesn't seem all 5173 // that unreasonable. 5174 if (pkgSetting.sharedUser != null) { 5175 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5176 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5177 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 5178 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 5179 return null; 5180 } 5181 } 5182 // File a report about this. 5183 String msg = "System package " + pkg.packageName 5184 + " signature changed; retaining data."; 5185 reportSettingsProblem(Log.WARN, msg); 5186 } 5187 5188 // Verify that this new package doesn't have any content providers 5189 // that conflict with existing packages. Only do this if the 5190 // package isn't already installed, since we don't want to break 5191 // things that are installed. 5192 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5193 final int N = pkg.providers.size(); 5194 int i; 5195 for (i=0; i<N; i++) { 5196 PackageParser.Provider p = pkg.providers.get(i); 5197 if (p.info.authority != null) { 5198 String names[] = p.info.authority.split(";"); 5199 for (int j = 0; j < names.length; j++) { 5200 if (mProvidersByAuthority.containsKey(names[j])) { 5201 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5202 Slog.w(TAG, "Can't install because provider name " + names[j] + 5203 " (in package " + pkg.applicationInfo.packageName + 5204 ") is already used by " 5205 + ((other != null && other.getComponentName() != null) 5206 ? other.getComponentName().getPackageName() : "?")); 5207 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 5208 return null; 5209 } 5210 } 5211 } 5212 } 5213 } 5214 5215 if (pkg.mAdoptPermissions != null) { 5216 // This package wants to adopt ownership of permissions from 5217 // another package. 5218 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5219 final String origName = pkg.mAdoptPermissions.get(i); 5220 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5221 if (orig != null) { 5222 if (verifyPackageUpdateLPr(orig, pkg)) { 5223 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5224 + pkg.packageName); 5225 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5226 } 5227 } 5228 } 5229 } 5230 } 5231 5232 final String pkgName = pkg.packageName; 5233 5234 final long scanFileTime = scanFile.lastModified(); 5235 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5236 pkg.applicationInfo.processName = fixProcessName( 5237 pkg.applicationInfo.packageName, 5238 pkg.applicationInfo.processName, 5239 pkg.applicationInfo.uid); 5240 5241 File dataPath; 5242 if (mPlatformPackage == pkg) { 5243 // The system package is special. 5244 dataPath = new File (Environment.getDataDirectory(), "system"); 5245 pkg.applicationInfo.dataDir = dataPath.getPath(); 5246 } else { 5247 // This is a normal package, need to make its data directory. 5248 dataPath = getDataPathForPackage(pkg.packageName, 0); 5249 5250 boolean uidError = false; 5251 5252 if (dataPath.exists()) { 5253 int currentUid = 0; 5254 try { 5255 StructStat stat = Os.stat(dataPath.getPath()); 5256 currentUid = stat.st_uid; 5257 } catch (ErrnoException e) { 5258 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5259 } 5260 5261 // If we have mismatched owners for the data path, we have a problem. 5262 if (currentUid != pkg.applicationInfo.uid) { 5263 boolean recovered = false; 5264 if (currentUid == 0) { 5265 // The directory somehow became owned by root. Wow. 5266 // This is probably because the system was stopped while 5267 // installd was in the middle of messing with its libs 5268 // directory. Ask installd to fix that. 5269 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5270 pkg.applicationInfo.uid); 5271 if (ret >= 0) { 5272 recovered = true; 5273 String msg = "Package " + pkg.packageName 5274 + " unexpectedly changed to uid 0; recovered to " + 5275 + pkg.applicationInfo.uid; 5276 reportSettingsProblem(Log.WARN, msg); 5277 } 5278 } 5279 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5280 || (scanMode&SCAN_BOOTING) != 0)) { 5281 // If this is a system app, we can at least delete its 5282 // current data so the application will still work. 5283 int ret = removeDataDirsLI(pkgName); 5284 if (ret >= 0) { 5285 // TODO: Kill the processes first 5286 // Old data gone! 5287 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5288 ? "System package " : "Third party package "; 5289 String msg = prefix + pkg.packageName 5290 + " has changed from uid: " 5291 + currentUid + " to " 5292 + pkg.applicationInfo.uid + "; old data erased"; 5293 reportSettingsProblem(Log.WARN, msg); 5294 recovered = true; 5295 5296 // And now re-install the app. 5297 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5298 pkg.applicationInfo.seinfo); 5299 if (ret == -1) { 5300 // Ack should not happen! 5301 msg = prefix + pkg.packageName 5302 + " could not have data directory re-created after delete."; 5303 reportSettingsProblem(Log.WARN, msg); 5304 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5305 return null; 5306 } 5307 } 5308 if (!recovered) { 5309 mHasSystemUidErrors = true; 5310 } 5311 } else if (!recovered) { 5312 // If we allow this install to proceed, we will be broken. 5313 // Abort, abort! 5314 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 5315 return null; 5316 } 5317 if (!recovered) { 5318 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5319 + pkg.applicationInfo.uid + "/fs_" 5320 + currentUid; 5321 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5322 String msg = "Package " + pkg.packageName 5323 + " has mismatched uid: " 5324 + currentUid + " on disk, " 5325 + pkg.applicationInfo.uid + " in settings"; 5326 // writer 5327 synchronized (mPackages) { 5328 mSettings.mReadMessages.append(msg); 5329 mSettings.mReadMessages.append('\n'); 5330 uidError = true; 5331 if (!pkgSetting.uidError) { 5332 reportSettingsProblem(Log.ERROR, msg); 5333 } 5334 } 5335 } 5336 } 5337 pkg.applicationInfo.dataDir = dataPath.getPath(); 5338 if (mShouldRestoreconData) { 5339 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5340 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5341 pkg.applicationInfo.uid); 5342 } 5343 } else { 5344 if (DEBUG_PACKAGE_SCANNING) { 5345 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5346 Log.v(TAG, "Want this data dir: " + dataPath); 5347 } 5348 //invoke installer to do the actual installation 5349 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5350 pkg.applicationInfo.seinfo); 5351 if (ret < 0) { 5352 // Error from installer 5353 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5354 return null; 5355 } 5356 5357 if (dataPath.exists()) { 5358 pkg.applicationInfo.dataDir = dataPath.getPath(); 5359 } else { 5360 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5361 pkg.applicationInfo.dataDir = null; 5362 } 5363 } 5364 5365 /* 5366 * Set the data dir to the default "/data/data/<package name>/lib" 5367 * if we got here without anyone telling us different (e.g., apps 5368 * stored on SD card have their native libraries stored in the ASEC 5369 * container with the APK). 5370 * 5371 * This happens during an upgrade from a package settings file that 5372 * doesn't have a native library path attribute at all. 5373 */ 5374 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 5375 if (pkgSetting.nativeLibraryPathString == null) { 5376 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5377 } else { 5378 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 5379 } 5380 } 5381 pkgSetting.uidError = uidError; 5382 } 5383 5384 String path = scanFile.getPath(); 5385 /* Note: We don't want to unpack the native binaries for 5386 * system applications, unless they have been updated 5387 * (the binaries are already under /system/lib). 5388 * Also, don't unpack libs for apps on the external card 5389 * since they should have their libraries in the ASEC 5390 * container already. 5391 * 5392 * In other words, we're going to unpack the binaries 5393 * only for non-system apps and system app upgrades. 5394 */ 5395 if (pkg.applicationInfo.nativeLibraryDir != null) { 5396 try { 5397 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5398 final String dataPathString = dataPath.getCanonicalPath(); 5399 5400 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5401 /* 5402 * Upgrading from a previous version of the OS sometimes 5403 * leaves native libraries in the /data/data/<app>/lib 5404 * directory for system apps even when they shouldn't be. 5405 * Recent changes in the JNI library search path 5406 * necessitates we remove those to match previous behavior. 5407 */ 5408 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 5409 Log.i(TAG, "removed obsolete native libraries for system package " 5410 + path); 5411 } 5412 5413 setInternalAppAbi(pkg, pkgSetting); 5414 } else { 5415 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 5416 /* 5417 * Update native library dir if it starts with 5418 * /data/data 5419 */ 5420 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 5421 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5422 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5423 } 5424 5425 try { 5426 int copyRet = copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir); 5427 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5428 Slog.e(TAG, "Unable to copy native libraries"); 5429 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5430 return null; 5431 } 5432 5433 // We've successfully copied native libraries across, so we make a 5434 // note of what ABI we're using 5435 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5436 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_ABIS[copyRet]; 5437 } else { 5438 pkg.applicationInfo.cpuAbi = null; 5439 } 5440 } catch (IOException e) { 5441 Slog.e(TAG, "Unable to copy native libraries", e); 5442 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5443 return null; 5444 } 5445 } else { 5446 // We don't have to copy the shared libraries if we're in the ASEC container 5447 // but we still need to scan the file to figure out what ABI the app needs. 5448 // 5449 // TODO: This duplicates work done in the default container service. It's possible 5450 // to clean this up but we'll need to change the interface between this service 5451 // and IMediaContainerService (but doing so will spread this logic out, rather 5452 // than centralizing it). 5453 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile); 5454 final int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS); 5455 if (abi >= 0) { 5456 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_ABIS[abi]; 5457 } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) { 5458 // Note that (non upgraded) system apps will not have any native 5459 // libraries bundled in their APK, but we're guaranteed not to be 5460 // such an app at this point. 5461 pkg.applicationInfo.cpuAbi = null; 5462 } else { 5463 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5464 return null; 5465 } 5466 handle.close(); 5467 } 5468 5469 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5470 final int[] userIds = sUserManager.getUserIds(); 5471 synchronized (mInstallLock) { 5472 for (int userId : userIds) { 5473 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 5474 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 5475 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5476 + ")"); 5477 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5478 return null; 5479 } 5480 } 5481 } 5482 } 5483 } catch (IOException ioe) { 5484 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5485 } 5486 } 5487 pkg.mScanPath = path; 5488 5489 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5490 // We don't do this here during boot because we can do it all 5491 // at once after scanning all existing packages. 5492 // 5493 // We also do this *before* we perform dexopt on this package, so that 5494 // we can avoid redundant dexopts, and also to make sure we've got the 5495 // code and package path correct. 5496 if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5497 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) { 5498 mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE; 5499 return null; 5500 } 5501 } 5502 5503 if ((scanMode&SCAN_NO_DEX) == 0) { 5504 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5505 == DEX_OPT_FAILED) { 5506 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5507 removeDataDirsLI(pkg.packageName); 5508 } 5509 5510 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5511 return null; 5512 } 5513 } 5514 5515 if (mFactoryTest && pkg.requestedPermissions.contains( 5516 android.Manifest.permission.FACTORY_TEST)) { 5517 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5518 } 5519 5520 ArrayList<PackageParser.Package> clientLibPkgs = null; 5521 5522 // writer 5523 synchronized (mPackages) { 5524 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5525 // Only system apps can add new shared libraries. 5526 if (pkg.libraryNames != null) { 5527 for (int i=0; i<pkg.libraryNames.size(); i++) { 5528 String name = pkg.libraryNames.get(i); 5529 boolean allowed = false; 5530 if (isUpdatedSystemApp(pkg)) { 5531 // New library entries can only be added through the 5532 // system image. This is important to get rid of a lot 5533 // of nasty edge cases: for example if we allowed a non- 5534 // system update of the app to add a library, then uninstalling 5535 // the update would make the library go away, and assumptions 5536 // we made such as through app install filtering would now 5537 // have allowed apps on the device which aren't compatible 5538 // with it. Better to just have the restriction here, be 5539 // conservative, and create many fewer cases that can negatively 5540 // impact the user experience. 5541 final PackageSetting sysPs = mSettings 5542 .getDisabledSystemPkgLPr(pkg.packageName); 5543 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5544 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5545 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5546 allowed = true; 5547 allowed = true; 5548 break; 5549 } 5550 } 5551 } 5552 } else { 5553 allowed = true; 5554 } 5555 if (allowed) { 5556 if (!mSharedLibraries.containsKey(name)) { 5557 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5558 } else if (!name.equals(pkg.packageName)) { 5559 Slog.w(TAG, "Package " + pkg.packageName + " library " 5560 + name + " already exists; skipping"); 5561 } 5562 } else { 5563 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5564 + name + " that is not declared on system image; skipping"); 5565 } 5566 } 5567 if ((scanMode&SCAN_BOOTING) == 0) { 5568 // If we are not booting, we need to update any applications 5569 // that are clients of our shared library. If we are booting, 5570 // this will all be done once the scan is complete. 5571 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5572 } 5573 } 5574 } 5575 } 5576 5577 // We also need to dexopt any apps that are dependent on this library. Note that 5578 // if these fail, we should abort the install since installing the library will 5579 // result in some apps being broken. 5580 if (clientLibPkgs != null) { 5581 if ((scanMode&SCAN_NO_DEX) == 0) { 5582 for (int i=0; i<clientLibPkgs.size(); i++) { 5583 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5584 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5585 == DEX_OPT_FAILED) { 5586 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5587 removeDataDirsLI(pkg.packageName); 5588 } 5589 5590 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5591 return null; 5592 } 5593 } 5594 } 5595 } 5596 5597 // Request the ActivityManager to kill the process(only for existing packages) 5598 // so that we do not end up in a confused state while the user is still using the older 5599 // version of the application while the new one gets installed. 5600 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5601 // If the package lives in an asec, tell everyone that the container is going 5602 // away so they can clean up any references to its resources (which would prevent 5603 // vold from being able to unmount the asec) 5604 if (isForwardLocked(pkg) || isExternal(pkg)) { 5605 if (DEBUG_INSTALL) { 5606 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5607 } 5608 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5609 final ArrayList<String> pkgList = new ArrayList<String>(1); 5610 pkgList.add(pkg.applicationInfo.packageName); 5611 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5612 } 5613 5614 // Post the request that it be killed now that the going-away broadcast is en route 5615 killApplication(pkg.applicationInfo.packageName, 5616 pkg.applicationInfo.uid, "update pkg"); 5617 } 5618 5619 // Also need to kill any apps that are dependent on the library. 5620 if (clientLibPkgs != null) { 5621 for (int i=0; i<clientLibPkgs.size(); i++) { 5622 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5623 killApplication(clientPkg.applicationInfo.packageName, 5624 clientPkg.applicationInfo.uid, "update lib"); 5625 } 5626 } 5627 5628 // writer 5629 synchronized (mPackages) { 5630 // We don't expect installation to fail beyond this point, 5631 if ((scanMode&SCAN_MONITOR) != 0) { 5632 mAppDirs.put(pkg.mPath, pkg); 5633 } 5634 // Add the new setting to mSettings 5635 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5636 // Add the new setting to mPackages 5637 mPackages.put(pkg.applicationInfo.packageName, pkg); 5638 // Make sure we don't accidentally delete its data. 5639 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5640 while (iter.hasNext()) { 5641 PackageCleanItem item = iter.next(); 5642 if (pkgName.equals(item.packageName)) { 5643 iter.remove(); 5644 } 5645 } 5646 5647 // Take care of first install / last update times. 5648 if (currentTime != 0) { 5649 if (pkgSetting.firstInstallTime == 0) { 5650 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5651 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5652 pkgSetting.lastUpdateTime = currentTime; 5653 } 5654 } else if (pkgSetting.firstInstallTime == 0) { 5655 // We need *something*. Take time time stamp of the file. 5656 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5657 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5658 if (scanFileTime != pkgSetting.timeStamp) { 5659 // A package on the system image has changed; consider this 5660 // to be an update. 5661 pkgSetting.lastUpdateTime = scanFileTime; 5662 } 5663 } 5664 5665 // Add the package's KeySets to the global KeySetManager 5666 KeySetManager ksm = mSettings.mKeySetManager; 5667 try { 5668 ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5669 if (pkg.mKeySetMapping != null) { 5670 for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) { 5671 if (entry.getValue() != null) { 5672 ksm.addDefinedKeySetToPackage(pkg.packageName, 5673 entry.getValue(), entry.getKey()); 5674 } 5675 } 5676 } 5677 } catch (NullPointerException e) { 5678 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5679 } catch (IllegalArgumentException e) { 5680 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5681 } 5682 5683 int N = pkg.providers.size(); 5684 StringBuilder r = null; 5685 int i; 5686 for (i=0; i<N; i++) { 5687 PackageParser.Provider p = pkg.providers.get(i); 5688 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5689 p.info.processName, pkg.applicationInfo.uid); 5690 mProviders.addProvider(p); 5691 p.syncable = p.info.isSyncable; 5692 if (p.info.authority != null) { 5693 String names[] = p.info.authority.split(";"); 5694 p.info.authority = null; 5695 for (int j = 0; j < names.length; j++) { 5696 if (j == 1 && p.syncable) { 5697 // We only want the first authority for a provider to possibly be 5698 // syncable, so if we already added this provider using a different 5699 // authority clear the syncable flag. We copy the provider before 5700 // changing it because the mProviders object contains a reference 5701 // to a provider that we don't want to change. 5702 // Only do this for the second authority since the resulting provider 5703 // object can be the same for all future authorities for this provider. 5704 p = new PackageParser.Provider(p); 5705 p.syncable = false; 5706 } 5707 if (!mProvidersByAuthority.containsKey(names[j])) { 5708 mProvidersByAuthority.put(names[j], p); 5709 if (p.info.authority == null) { 5710 p.info.authority = names[j]; 5711 } else { 5712 p.info.authority = p.info.authority + ";" + names[j]; 5713 } 5714 if (DEBUG_PACKAGE_SCANNING) { 5715 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5716 Log.d(TAG, "Registered content provider: " + names[j] 5717 + ", className = " + p.info.name + ", isSyncable = " 5718 + p.info.isSyncable); 5719 } 5720 } else { 5721 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5722 Slog.w(TAG, "Skipping provider name " + names[j] + 5723 " (in package " + pkg.applicationInfo.packageName + 5724 "): name already used by " 5725 + ((other != null && other.getComponentName() != null) 5726 ? other.getComponentName().getPackageName() : "?")); 5727 } 5728 } 5729 } 5730 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5731 if (r == null) { 5732 r = new StringBuilder(256); 5733 } else { 5734 r.append(' '); 5735 } 5736 r.append(p.info.name); 5737 } 5738 } 5739 if (r != null) { 5740 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5741 } 5742 5743 N = pkg.services.size(); 5744 r = null; 5745 for (i=0; i<N; i++) { 5746 PackageParser.Service s = pkg.services.get(i); 5747 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5748 s.info.processName, pkg.applicationInfo.uid); 5749 mServices.addService(s); 5750 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5751 if (r == null) { 5752 r = new StringBuilder(256); 5753 } else { 5754 r.append(' '); 5755 } 5756 r.append(s.info.name); 5757 } 5758 } 5759 if (r != null) { 5760 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5761 } 5762 5763 N = pkg.receivers.size(); 5764 r = null; 5765 for (i=0; i<N; i++) { 5766 PackageParser.Activity a = pkg.receivers.get(i); 5767 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5768 a.info.processName, pkg.applicationInfo.uid); 5769 mReceivers.addActivity(a, "receiver"); 5770 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5771 if (r == null) { 5772 r = new StringBuilder(256); 5773 } else { 5774 r.append(' '); 5775 } 5776 r.append(a.info.name); 5777 } 5778 } 5779 if (r != null) { 5780 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5781 } 5782 5783 N = pkg.activities.size(); 5784 r = null; 5785 for (i=0; i<N; i++) { 5786 PackageParser.Activity a = pkg.activities.get(i); 5787 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5788 a.info.processName, pkg.applicationInfo.uid); 5789 mActivities.addActivity(a, "activity"); 5790 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5791 if (r == null) { 5792 r = new StringBuilder(256); 5793 } else { 5794 r.append(' '); 5795 } 5796 r.append(a.info.name); 5797 } 5798 } 5799 if (r != null) { 5800 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5801 } 5802 5803 N = pkg.permissionGroups.size(); 5804 r = null; 5805 for (i=0; i<N; i++) { 5806 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5807 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5808 if (cur == null) { 5809 mPermissionGroups.put(pg.info.name, pg); 5810 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5811 if (r == null) { 5812 r = new StringBuilder(256); 5813 } else { 5814 r.append(' '); 5815 } 5816 r.append(pg.info.name); 5817 } 5818 } else { 5819 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5820 + pg.info.packageName + " ignored: original from " 5821 + cur.info.packageName); 5822 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5823 if (r == null) { 5824 r = new StringBuilder(256); 5825 } else { 5826 r.append(' '); 5827 } 5828 r.append("DUP:"); 5829 r.append(pg.info.name); 5830 } 5831 } 5832 } 5833 if (r != null) { 5834 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5835 } 5836 5837 N = pkg.permissions.size(); 5838 r = null; 5839 for (i=0; i<N; i++) { 5840 PackageParser.Permission p = pkg.permissions.get(i); 5841 HashMap<String, BasePermission> permissionMap = 5842 p.tree ? mSettings.mPermissionTrees 5843 : mSettings.mPermissions; 5844 p.group = mPermissionGroups.get(p.info.group); 5845 if (p.info.group == null || p.group != null) { 5846 BasePermission bp = permissionMap.get(p.info.name); 5847 if (bp == null) { 5848 bp = new BasePermission(p.info.name, p.info.packageName, 5849 BasePermission.TYPE_NORMAL); 5850 permissionMap.put(p.info.name, bp); 5851 } 5852 if (bp.perm == null) { 5853 if (bp.sourcePackage != null 5854 && !bp.sourcePackage.equals(p.info.packageName)) { 5855 // If this is a permission that was formerly defined by a non-system 5856 // app, but is now defined by a system app (following an upgrade), 5857 // discard the previous declaration and consider the system's to be 5858 // canonical. 5859 if (isSystemApp(p.owner)) { 5860 String msg = "New decl " + p.owner + " of permission " 5861 + p.info.name + " is system"; 5862 reportSettingsProblem(Log.WARN, msg); 5863 bp.sourcePackage = null; 5864 } 5865 } 5866 if (bp.sourcePackage == null 5867 || bp.sourcePackage.equals(p.info.packageName)) { 5868 BasePermission tree = findPermissionTreeLP(p.info.name); 5869 if (tree == null 5870 || tree.sourcePackage.equals(p.info.packageName)) { 5871 bp.packageSetting = pkgSetting; 5872 bp.perm = p; 5873 bp.uid = pkg.applicationInfo.uid; 5874 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5875 if (r == null) { 5876 r = new StringBuilder(256); 5877 } else { 5878 r.append(' '); 5879 } 5880 r.append(p.info.name); 5881 } 5882 } else { 5883 Slog.w(TAG, "Permission " + p.info.name + " from package " 5884 + p.info.packageName + " ignored: base tree " 5885 + tree.name + " is from package " 5886 + tree.sourcePackage); 5887 } 5888 } else { 5889 Slog.w(TAG, "Permission " + p.info.name + " from package " 5890 + p.info.packageName + " ignored: original from " 5891 + bp.sourcePackage); 5892 } 5893 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5894 if (r == null) { 5895 r = new StringBuilder(256); 5896 } else { 5897 r.append(' '); 5898 } 5899 r.append("DUP:"); 5900 r.append(p.info.name); 5901 } 5902 if (bp.perm == p) { 5903 bp.protectionLevel = p.info.protectionLevel; 5904 } 5905 } else { 5906 Slog.w(TAG, "Permission " + p.info.name + " from package " 5907 + p.info.packageName + " ignored: no group " 5908 + p.group); 5909 } 5910 } 5911 if (r != null) { 5912 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5913 } 5914 5915 N = pkg.instrumentation.size(); 5916 r = null; 5917 for (i=0; i<N; i++) { 5918 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5919 a.info.packageName = pkg.applicationInfo.packageName; 5920 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5921 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5922 a.info.dataDir = pkg.applicationInfo.dataDir; 5923 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5924 mInstrumentation.put(a.getComponentName(), a); 5925 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5926 if (r == null) { 5927 r = new StringBuilder(256); 5928 } else { 5929 r.append(' '); 5930 } 5931 r.append(a.info.name); 5932 } 5933 } 5934 if (r != null) { 5935 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5936 } 5937 5938 if (pkg.protectedBroadcasts != null) { 5939 N = pkg.protectedBroadcasts.size(); 5940 for (i=0; i<N; i++) { 5941 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5942 } 5943 } 5944 5945 pkgSetting.setTimeStamp(scanFileTime); 5946 5947 // Create idmap files for pairs of (packages, overlay packages). 5948 // Note: "android", ie framework-res.apk, is handled by native layers. 5949 if (pkg.mOverlayTarget != null) { 5950 // This is an overlay package. 5951 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 5952 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 5953 mOverlays.put(pkg.mOverlayTarget, 5954 new HashMap<String, PackageParser.Package>()); 5955 } 5956 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 5957 map.put(pkg.packageName, pkg); 5958 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 5959 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 5960 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5961 return null; 5962 } 5963 } 5964 } else if (mOverlays.containsKey(pkg.packageName) && 5965 !pkg.packageName.equals("android")) { 5966 // This is a regular package, with one or more known overlay packages. 5967 createIdmapsForPackageLI(pkg); 5968 } 5969 } 5970 5971 return pkg; 5972 } 5973 5974 /** 5975 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 5976 * i.e, so that all packages can be run inside a single process if required. 5977 * 5978 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 5979 * this function will either try and make the ABI for all packages in {@code packagesForUser} 5980 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 5981 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 5982 * updating a package that belongs to a shared user. 5983 */ 5984 private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 5985 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 5986 String requiredInstructionSet = null; 5987 if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) { 5988 requiredInstructionSet = VMRuntime.getInstructionSet( 5989 scannedPackage.applicationInfo.cpuAbi); 5990 } 5991 5992 PackageSetting requirer = null; 5993 for (PackageSetting ps : packagesForUser) { 5994 // If packagesForUser contains scannedPackage, we skip it. This will happen 5995 // when scannedPackage is an update of an existing package. Without this check, 5996 // we will never be able to change the ABI of any package belonging to a shared 5997 // user, even if it's compatible with other packages. 5998 if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) { 5999 if (ps.cpuAbiString == null) { 6000 continue; 6001 } 6002 6003 final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 6004 if (requiredInstructionSet != null) { 6005 if (!instructionSet.equals(requiredInstructionSet)) { 6006 // We have a mismatch between instruction sets (say arm vs arm64). 6007 // bail out. 6008 String errorMessage = "Instruction set mismatch, " 6009 + ((requirer == null) ? "[caller]" : requirer) 6010 + " requires " + requiredInstructionSet + " whereas " + ps 6011 + " requires " + instructionSet; 6012 Slog.e(TAG, errorMessage); 6013 6014 reportSettingsProblem(Log.WARN, errorMessage); 6015 // Give up, don't bother making any other changes to the package settings. 6016 return false; 6017 } 6018 } else { 6019 requiredInstructionSet = instructionSet; 6020 requirer = ps; 6021 } 6022 } 6023 } 6024 6025 if (requiredInstructionSet != null) { 6026 String adjustedAbi; 6027 if (requirer != null) { 6028 // requirer != null implies that either scannedPackage was null or that scannedPackage 6029 // did not require an ABI, in which case we have to adjust scannedPackage to match 6030 // the ABI of the set (which is the same as requirer's ABI) 6031 adjustedAbi = requirer.cpuAbiString; 6032 if (scannedPackage != null) { 6033 scannedPackage.applicationInfo.cpuAbi = adjustedAbi; 6034 } 6035 } else { 6036 // requirer == null implies that we're updating all ABIs in the set to 6037 // match scannedPackage. 6038 adjustedAbi = scannedPackage.applicationInfo.cpuAbi; 6039 } 6040 6041 for (PackageSetting ps : packagesForUser) { 6042 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6043 if (ps.cpuAbiString != null) { 6044 continue; 6045 } 6046 6047 ps.cpuAbiString = adjustedAbi; 6048 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6049 ps.pkg.applicationInfo.cpuAbi = adjustedAbi; 6050 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6051 6052 if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) { 6053 ps.cpuAbiString = null; 6054 ps.pkg.applicationInfo.cpuAbi = null; 6055 return false; 6056 } else { 6057 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6058 } 6059 } 6060 } 6061 } 6062 } 6063 6064 return true; 6065 } 6066 6067 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6068 synchronized (mPackages) { 6069 mResolverReplaced = true; 6070 // Set up information for custom user intent resolution activity. 6071 mResolveActivity.applicationInfo = pkg.applicationInfo; 6072 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6073 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6074 mResolveActivity.processName = null; 6075 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6076 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6077 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6078 mResolveActivity.theme = 0; 6079 mResolveActivity.exported = true; 6080 mResolveActivity.enabled = true; 6081 mResolveInfo.activityInfo = mResolveActivity; 6082 mResolveInfo.priority = 0; 6083 mResolveInfo.preferredOrder = 0; 6084 mResolveInfo.match = 0; 6085 mResolveComponentName = mCustomResolverComponentName; 6086 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6087 mResolveComponentName); 6088 } 6089 } 6090 6091 private String calculateApkRoot(final String codePathString) { 6092 final File codePath = new File(codePathString); 6093 final File codeRoot; 6094 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6095 codeRoot = Environment.getRootDirectory(); 6096 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6097 codeRoot = Environment.getOemDirectory(); 6098 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6099 codeRoot = Environment.getVendorDirectory(); 6100 } else { 6101 // Unrecognized code path; take its top real segment as the apk root: 6102 // e.g. /something/app/blah.apk => /something 6103 try { 6104 File f = codePath.getCanonicalFile(); 6105 File parent = f.getParentFile(); // non-null because codePath is a file 6106 File tmp; 6107 while ((tmp = parent.getParentFile()) != null) { 6108 f = parent; 6109 parent = tmp; 6110 } 6111 codeRoot = f; 6112 Slog.w(TAG, "Unrecognized code path " 6113 + codePath + " - using " + codeRoot); 6114 } catch (IOException e) { 6115 // Can't canonicalize the lib path -- shenanigans? 6116 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6117 return Environment.getRootDirectory().getPath(); 6118 } 6119 } 6120 return codeRoot.getPath(); 6121 } 6122 6123 // This is the initial scan-time determination of how to handle a given 6124 // package for purposes of native library location. 6125 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 6126 PackageSetting pkgSetting) { 6127 // "bundled" here means system-installed with no overriding update 6128 final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg); 6129 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 6130 final File libDir; 6131 if (bundledApk) { 6132 // If "/system/lib64/apkname" exists, assume that is the per-package 6133 // native library directory to use; otherwise use "/system/lib/apkname". 6134 String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6135 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 6136 File packLib64 = new File(lib64, apkName); 6137 libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 6138 } else { 6139 libDir = mAppLibInstallDir; 6140 } 6141 final String nativeLibraryPath = (new File(libDir, apkName)).getPath(); 6142 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 6143 // pkgSetting might be null during rescan following uninstall of updates 6144 // to a bundled app, so accommodate that possibility. The settings in 6145 // that case will be established later from the parsed package. 6146 if (pkgSetting != null) { 6147 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 6148 } 6149 } 6150 6151 // Deduces the required ABI of an upgraded system app. 6152 private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) { 6153 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6154 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 6155 6156 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 6157 // or similar. 6158 final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath()); 6159 final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath()); 6160 6161 // Assume that the bundled native libraries always correspond to the 6162 // most preferred 32 or 64 bit ABI. 6163 if (lib64.exists()) { 6164 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6165 pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0]; 6166 } else if (lib.exists()) { 6167 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6168 pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0]; 6169 } else { 6170 // This is the case where the app has no native code. 6171 pkg.applicationInfo.cpuAbi = null; 6172 pkgSetting.cpuAbiString = null; 6173 } 6174 } 6175 6176 private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir) 6177 throws IOException { 6178 if (!nativeLibraryDir.isDirectory()) { 6179 nativeLibraryDir.delete(); 6180 6181 if (!nativeLibraryDir.mkdir()) { 6182 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 6183 } 6184 6185 try { 6186 Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6187 } catch (ErrnoException e) { 6188 throw new IOException("Cannot chmod native library directory " 6189 + nativeLibraryDir.getPath(), e); 6190 } 6191 } else if (!SELinux.restorecon(nativeLibraryDir)) { 6192 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 6193 } 6194 6195 /* 6196 * If this is an internal application or our nativeLibraryPath points to 6197 * the app-lib directory, unpack the libraries if necessary. 6198 */ 6199 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile); 6200 try { 6201 int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS); 6202 if (abi >= 0) { 6203 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 6204 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 6205 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6206 return copyRet; 6207 } 6208 } 6209 6210 return abi; 6211 } finally { 6212 handle.close(); 6213 } 6214 } 6215 6216 private void killApplication(String pkgName, int appId, String reason) { 6217 // Request the ActivityManager to kill the process(only for existing packages) 6218 // so that we do not end up in a confused state while the user is still using the older 6219 // version of the application while the new one gets installed. 6220 IActivityManager am = ActivityManagerNative.getDefault(); 6221 if (am != null) { 6222 try { 6223 am.killApplicationWithAppId(pkgName, appId, reason); 6224 } catch (RemoteException e) { 6225 } 6226 } 6227 } 6228 6229 void removePackageLI(PackageSetting ps, boolean chatty) { 6230 if (DEBUG_INSTALL) { 6231 if (chatty) 6232 Log.d(TAG, "Removing package " + ps.name); 6233 } 6234 6235 // writer 6236 synchronized (mPackages) { 6237 mPackages.remove(ps.name); 6238 if (ps.codePathString != null) { 6239 mAppDirs.remove(ps.codePathString); 6240 } 6241 6242 final PackageParser.Package pkg = ps.pkg; 6243 if (pkg != null) { 6244 cleanPackageDataStructuresLILPw(pkg, chatty); 6245 } 6246 } 6247 } 6248 6249 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6250 if (DEBUG_INSTALL) { 6251 if (chatty) 6252 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6253 } 6254 6255 // writer 6256 synchronized (mPackages) { 6257 mPackages.remove(pkg.applicationInfo.packageName); 6258 if (pkg.mPath != null) { 6259 mAppDirs.remove(pkg.mPath); 6260 } 6261 cleanPackageDataStructuresLILPw(pkg, chatty); 6262 } 6263 } 6264 6265 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6266 int N = pkg.providers.size(); 6267 StringBuilder r = null; 6268 int i; 6269 for (i=0; i<N; i++) { 6270 PackageParser.Provider p = pkg.providers.get(i); 6271 mProviders.removeProvider(p); 6272 if (p.info.authority == null) { 6273 6274 /* There was another ContentProvider with this authority when 6275 * this app was installed so this authority is null, 6276 * Ignore it as we don't have to unregister the provider. 6277 */ 6278 continue; 6279 } 6280 String names[] = p.info.authority.split(";"); 6281 for (int j = 0; j < names.length; j++) { 6282 if (mProvidersByAuthority.get(names[j]) == p) { 6283 mProvidersByAuthority.remove(names[j]); 6284 if (DEBUG_REMOVE) { 6285 if (chatty) 6286 Log.d(TAG, "Unregistered content provider: " + names[j] 6287 + ", className = " + p.info.name + ", isSyncable = " 6288 + p.info.isSyncable); 6289 } 6290 } 6291 } 6292 if (DEBUG_REMOVE && chatty) { 6293 if (r == null) { 6294 r = new StringBuilder(256); 6295 } else { 6296 r.append(' '); 6297 } 6298 r.append(p.info.name); 6299 } 6300 } 6301 if (r != null) { 6302 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6303 } 6304 6305 N = pkg.services.size(); 6306 r = null; 6307 for (i=0; i<N; i++) { 6308 PackageParser.Service s = pkg.services.get(i); 6309 mServices.removeService(s); 6310 if (chatty) { 6311 if (r == null) { 6312 r = new StringBuilder(256); 6313 } else { 6314 r.append(' '); 6315 } 6316 r.append(s.info.name); 6317 } 6318 } 6319 if (r != null) { 6320 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6321 } 6322 6323 N = pkg.receivers.size(); 6324 r = null; 6325 for (i=0; i<N; i++) { 6326 PackageParser.Activity a = pkg.receivers.get(i); 6327 mReceivers.removeActivity(a, "receiver"); 6328 if (DEBUG_REMOVE && chatty) { 6329 if (r == null) { 6330 r = new StringBuilder(256); 6331 } else { 6332 r.append(' '); 6333 } 6334 r.append(a.info.name); 6335 } 6336 } 6337 if (r != null) { 6338 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6339 } 6340 6341 N = pkg.activities.size(); 6342 r = null; 6343 for (i=0; i<N; i++) { 6344 PackageParser.Activity a = pkg.activities.get(i); 6345 mActivities.removeActivity(a, "activity"); 6346 if (DEBUG_REMOVE && chatty) { 6347 if (r == null) { 6348 r = new StringBuilder(256); 6349 } else { 6350 r.append(' '); 6351 } 6352 r.append(a.info.name); 6353 } 6354 } 6355 if (r != null) { 6356 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6357 } 6358 6359 N = pkg.permissions.size(); 6360 r = null; 6361 for (i=0; i<N; i++) { 6362 PackageParser.Permission p = pkg.permissions.get(i); 6363 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6364 if (bp == null) { 6365 bp = mSettings.mPermissionTrees.get(p.info.name); 6366 } 6367 if (bp != null && bp.perm == p) { 6368 bp.perm = null; 6369 if (DEBUG_REMOVE && chatty) { 6370 if (r == null) { 6371 r = new StringBuilder(256); 6372 } else { 6373 r.append(' '); 6374 } 6375 r.append(p.info.name); 6376 } 6377 } 6378 } 6379 if (r != null) { 6380 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6381 } 6382 6383 N = pkg.instrumentation.size(); 6384 r = null; 6385 for (i=0; i<N; i++) { 6386 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6387 mInstrumentation.remove(a.getComponentName()); 6388 if (DEBUG_REMOVE && chatty) { 6389 if (r == null) { 6390 r = new StringBuilder(256); 6391 } else { 6392 r.append(' '); 6393 } 6394 r.append(a.info.name); 6395 } 6396 } 6397 if (r != null) { 6398 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6399 } 6400 6401 r = null; 6402 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6403 // Only system apps can hold shared libraries. 6404 if (pkg.libraryNames != null) { 6405 for (i=0; i<pkg.libraryNames.size(); i++) { 6406 String name = pkg.libraryNames.get(i); 6407 SharedLibraryEntry cur = mSharedLibraries.get(name); 6408 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6409 mSharedLibraries.remove(name); 6410 if (DEBUG_REMOVE && chatty) { 6411 if (r == null) { 6412 r = new StringBuilder(256); 6413 } else { 6414 r.append(' '); 6415 } 6416 r.append(name); 6417 } 6418 } 6419 } 6420 } 6421 } 6422 if (r != null) { 6423 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6424 } 6425 } 6426 6427 private static final boolean isPackageFilename(String name) { 6428 return name != null && name.endsWith(".apk"); 6429 } 6430 6431 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6432 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6433 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6434 return true; 6435 } 6436 } 6437 return false; 6438 } 6439 6440 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6441 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6442 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6443 6444 private void updatePermissionsLPw(String changingPkg, 6445 PackageParser.Package pkgInfo, int flags) { 6446 // Make sure there are no dangling permission trees. 6447 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6448 while (it.hasNext()) { 6449 final BasePermission bp = it.next(); 6450 if (bp.packageSetting == null) { 6451 // We may not yet have parsed the package, so just see if 6452 // we still know about its settings. 6453 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6454 } 6455 if (bp.packageSetting == null) { 6456 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6457 + " from package " + bp.sourcePackage); 6458 it.remove(); 6459 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6460 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6461 Slog.i(TAG, "Removing old permission tree: " + bp.name 6462 + " from package " + bp.sourcePackage); 6463 flags |= UPDATE_PERMISSIONS_ALL; 6464 it.remove(); 6465 } 6466 } 6467 } 6468 6469 // Make sure all dynamic permissions have been assigned to a package, 6470 // and make sure there are no dangling permissions. 6471 it = mSettings.mPermissions.values().iterator(); 6472 while (it.hasNext()) { 6473 final BasePermission bp = it.next(); 6474 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6475 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6476 + bp.name + " pkg=" + bp.sourcePackage 6477 + " info=" + bp.pendingInfo); 6478 if (bp.packageSetting == null && bp.pendingInfo != null) { 6479 final BasePermission tree = findPermissionTreeLP(bp.name); 6480 if (tree != null && tree.perm != null) { 6481 bp.packageSetting = tree.packageSetting; 6482 bp.perm = new PackageParser.Permission(tree.perm.owner, 6483 new PermissionInfo(bp.pendingInfo)); 6484 bp.perm.info.packageName = tree.perm.info.packageName; 6485 bp.perm.info.name = bp.name; 6486 bp.uid = tree.uid; 6487 } 6488 } 6489 } 6490 if (bp.packageSetting == null) { 6491 // We may not yet have parsed the package, so just see if 6492 // we still know about its settings. 6493 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6494 } 6495 if (bp.packageSetting == null) { 6496 Slog.w(TAG, "Removing dangling permission: " + bp.name 6497 + " from package " + bp.sourcePackage); 6498 it.remove(); 6499 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6500 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6501 Slog.i(TAG, "Removing old permission: " + bp.name 6502 + " from package " + bp.sourcePackage); 6503 flags |= UPDATE_PERMISSIONS_ALL; 6504 it.remove(); 6505 } 6506 } 6507 } 6508 6509 // Now update the permissions for all packages, in particular 6510 // replace the granted permissions of the system packages. 6511 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6512 for (PackageParser.Package pkg : mPackages.values()) { 6513 if (pkg != pkgInfo) { 6514 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6515 } 6516 } 6517 } 6518 6519 if (pkgInfo != null) { 6520 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6521 } 6522 } 6523 6524 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6525 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6526 if (ps == null) { 6527 return; 6528 } 6529 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6530 HashSet<String> origPermissions = gp.grantedPermissions; 6531 boolean changedPermission = false; 6532 6533 if (replace) { 6534 ps.permissionsFixed = false; 6535 if (gp == ps) { 6536 origPermissions = new HashSet<String>(gp.grantedPermissions); 6537 gp.grantedPermissions.clear(); 6538 gp.gids = mGlobalGids; 6539 } 6540 } 6541 6542 if (gp.gids == null) { 6543 gp.gids = mGlobalGids; 6544 } 6545 6546 final int N = pkg.requestedPermissions.size(); 6547 for (int i=0; i<N; i++) { 6548 final String name = pkg.requestedPermissions.get(i); 6549 final boolean required = pkg.requestedPermissionsRequired.get(i); 6550 final BasePermission bp = mSettings.mPermissions.get(name); 6551 if (DEBUG_INSTALL) { 6552 if (gp != ps) { 6553 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6554 } 6555 } 6556 6557 if (bp == null || bp.packageSetting == null) { 6558 Slog.w(TAG, "Unknown permission " + name 6559 + " in package " + pkg.packageName); 6560 continue; 6561 } 6562 6563 final String perm = bp.name; 6564 boolean allowed; 6565 boolean allowedSig = false; 6566 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6567 if (level == PermissionInfo.PROTECTION_NORMAL 6568 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6569 // We grant a normal or dangerous permission if any of the following 6570 // are true: 6571 // 1) The permission is required 6572 // 2) The permission is optional, but was granted in the past 6573 // 3) The permission is optional, but was requested by an 6574 // app in /system (not /data) 6575 // 6576 // Otherwise, reject the permission. 6577 allowed = (required || origPermissions.contains(perm) 6578 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6579 } else if (bp.packageSetting == null) { 6580 // This permission is invalid; skip it. 6581 allowed = false; 6582 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6583 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6584 if (allowed) { 6585 allowedSig = true; 6586 } 6587 } else { 6588 allowed = false; 6589 } 6590 if (DEBUG_INSTALL) { 6591 if (gp != ps) { 6592 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6593 } 6594 } 6595 if (allowed) { 6596 if (!isSystemApp(ps) && ps.permissionsFixed) { 6597 // If this is an existing, non-system package, then 6598 // we can't add any new permissions to it. 6599 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6600 // Except... if this is a permission that was added 6601 // to the platform (note: need to only do this when 6602 // updating the platform). 6603 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6604 } 6605 } 6606 if (allowed) { 6607 if (!gp.grantedPermissions.contains(perm)) { 6608 changedPermission = true; 6609 gp.grantedPermissions.add(perm); 6610 gp.gids = appendInts(gp.gids, bp.gids); 6611 } else if (!ps.haveGids) { 6612 gp.gids = appendInts(gp.gids, bp.gids); 6613 } 6614 } else { 6615 Slog.w(TAG, "Not granting permission " + perm 6616 + " to package " + pkg.packageName 6617 + " because it was previously installed without"); 6618 } 6619 } else { 6620 if (gp.grantedPermissions.remove(perm)) { 6621 changedPermission = true; 6622 gp.gids = removeInts(gp.gids, bp.gids); 6623 Slog.i(TAG, "Un-granting permission " + perm 6624 + " from package " + pkg.packageName 6625 + " (protectionLevel=" + bp.protectionLevel 6626 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6627 + ")"); 6628 } else { 6629 Slog.w(TAG, "Not granting permission " + perm 6630 + " to package " + pkg.packageName 6631 + " (protectionLevel=" + bp.protectionLevel 6632 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6633 + ")"); 6634 } 6635 } 6636 } 6637 6638 if ((changedPermission || replace) && !ps.permissionsFixed && 6639 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6640 // This is the first that we have heard about this package, so the 6641 // permissions we have now selected are fixed until explicitly 6642 // changed. 6643 ps.permissionsFixed = true; 6644 } 6645 ps.haveGids = true; 6646 } 6647 6648 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6649 boolean allowed = false; 6650 final int NP = PackageParser.NEW_PERMISSIONS.length; 6651 for (int ip=0; ip<NP; ip++) { 6652 final PackageParser.NewPermissionInfo npi 6653 = PackageParser.NEW_PERMISSIONS[ip]; 6654 if (npi.name.equals(perm) 6655 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6656 allowed = true; 6657 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6658 + pkg.packageName); 6659 break; 6660 } 6661 } 6662 return allowed; 6663 } 6664 6665 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6666 BasePermission bp, HashSet<String> origPermissions) { 6667 boolean allowed; 6668 allowed = (compareSignatures( 6669 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6670 == PackageManager.SIGNATURE_MATCH) 6671 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6672 == PackageManager.SIGNATURE_MATCH); 6673 if (!allowed && (bp.protectionLevel 6674 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6675 if (isSystemApp(pkg)) { 6676 // For updated system applications, a system permission 6677 // is granted only if it had been defined by the original application. 6678 if (isUpdatedSystemApp(pkg)) { 6679 final PackageSetting sysPs = mSettings 6680 .getDisabledSystemPkgLPr(pkg.packageName); 6681 final GrantedPermissions origGp = sysPs.sharedUser != null 6682 ? sysPs.sharedUser : sysPs; 6683 6684 if (origGp.grantedPermissions.contains(perm)) { 6685 // If the original was granted this permission, we take 6686 // that grant decision as read and propagate it to the 6687 // update. 6688 allowed = true; 6689 } else { 6690 // The system apk may have been updated with an older 6691 // version of the one on the data partition, but which 6692 // granted a new system permission that it didn't have 6693 // before. In this case we do want to allow the app to 6694 // now get the new permission if the ancestral apk is 6695 // privileged to get it. 6696 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6697 for (int j=0; 6698 j<sysPs.pkg.requestedPermissions.size(); j++) { 6699 if (perm.equals( 6700 sysPs.pkg.requestedPermissions.get(j))) { 6701 allowed = true; 6702 break; 6703 } 6704 } 6705 } 6706 } 6707 } else { 6708 allowed = isPrivilegedApp(pkg); 6709 } 6710 } 6711 } 6712 if (!allowed && (bp.protectionLevel 6713 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6714 // For development permissions, a development permission 6715 // is granted only if it was already granted. 6716 allowed = origPermissions.contains(perm); 6717 } 6718 return allowed; 6719 } 6720 6721 final class ActivityIntentResolver 6722 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6723 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6724 boolean defaultOnly, int userId) { 6725 if (!sUserManager.exists(userId)) return null; 6726 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6727 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6728 } 6729 6730 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6731 int userId) { 6732 if (!sUserManager.exists(userId)) return null; 6733 mFlags = flags; 6734 return super.queryIntent(intent, resolvedType, 6735 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6736 } 6737 6738 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6739 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6740 if (!sUserManager.exists(userId)) return null; 6741 if (packageActivities == null) { 6742 return null; 6743 } 6744 mFlags = flags; 6745 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6746 final int N = packageActivities.size(); 6747 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6748 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6749 6750 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6751 for (int i = 0; i < N; ++i) { 6752 intentFilters = packageActivities.get(i).intents; 6753 if (intentFilters != null && intentFilters.size() > 0) { 6754 PackageParser.ActivityIntentInfo[] array = 6755 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6756 intentFilters.toArray(array); 6757 listCut.add(array); 6758 } 6759 } 6760 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6761 } 6762 6763 public final void addActivity(PackageParser.Activity a, String type) { 6764 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6765 mActivities.put(a.getComponentName(), a); 6766 if (DEBUG_SHOW_INFO) 6767 Log.v( 6768 TAG, " " + type + " " + 6769 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6770 if (DEBUG_SHOW_INFO) 6771 Log.v(TAG, " Class=" + a.info.name); 6772 final int NI = a.intents.size(); 6773 for (int j=0; j<NI; j++) { 6774 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6775 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6776 intent.setPriority(0); 6777 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6778 + a.className + " with priority > 0, forcing to 0"); 6779 } 6780 if (DEBUG_SHOW_INFO) { 6781 Log.v(TAG, " IntentFilter:"); 6782 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6783 } 6784 if (!intent.debugCheck()) { 6785 Log.w(TAG, "==> For Activity " + a.info.name); 6786 } 6787 addFilter(intent); 6788 } 6789 } 6790 6791 public final void removeActivity(PackageParser.Activity a, String type) { 6792 mActivities.remove(a.getComponentName()); 6793 if (DEBUG_SHOW_INFO) { 6794 Log.v(TAG, " " + type + " " 6795 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6796 : a.info.name) + ":"); 6797 Log.v(TAG, " Class=" + a.info.name); 6798 } 6799 final int NI = a.intents.size(); 6800 for (int j=0; j<NI; j++) { 6801 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6802 if (DEBUG_SHOW_INFO) { 6803 Log.v(TAG, " IntentFilter:"); 6804 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6805 } 6806 removeFilter(intent); 6807 } 6808 } 6809 6810 @Override 6811 protected boolean allowFilterResult( 6812 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6813 ActivityInfo filterAi = filter.activity.info; 6814 for (int i=dest.size()-1; i>=0; i--) { 6815 ActivityInfo destAi = dest.get(i).activityInfo; 6816 if (destAi.name == filterAi.name 6817 && destAi.packageName == filterAi.packageName) { 6818 return false; 6819 } 6820 } 6821 return true; 6822 } 6823 6824 @Override 6825 protected ActivityIntentInfo[] newArray(int size) { 6826 return new ActivityIntentInfo[size]; 6827 } 6828 6829 @Override 6830 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6831 if (!sUserManager.exists(userId)) return true; 6832 PackageParser.Package p = filter.activity.owner; 6833 if (p != null) { 6834 PackageSetting ps = (PackageSetting)p.mExtras; 6835 if (ps != null) { 6836 // System apps are never considered stopped for purposes of 6837 // filtering, because there may be no way for the user to 6838 // actually re-launch them. 6839 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6840 && ps.getStopped(userId); 6841 } 6842 } 6843 return false; 6844 } 6845 6846 @Override 6847 protected boolean isPackageForFilter(String packageName, 6848 PackageParser.ActivityIntentInfo info) { 6849 return packageName.equals(info.activity.owner.packageName); 6850 } 6851 6852 @Override 6853 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6854 int match, int userId) { 6855 if (!sUserManager.exists(userId)) return null; 6856 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6857 return null; 6858 } 6859 final PackageParser.Activity activity = info.activity; 6860 if (mSafeMode && (activity.info.applicationInfo.flags 6861 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6862 return null; 6863 } 6864 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6865 if (ps == null) { 6866 return null; 6867 } 6868 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6869 ps.readUserState(userId), userId); 6870 if (ai == null) { 6871 return null; 6872 } 6873 final ResolveInfo res = new ResolveInfo(); 6874 res.activityInfo = ai; 6875 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6876 res.filter = info; 6877 } 6878 res.priority = info.getPriority(); 6879 res.preferredOrder = activity.owner.mPreferredOrder; 6880 //System.out.println("Result: " + res.activityInfo.className + 6881 // " = " + res.priority); 6882 res.match = match; 6883 res.isDefault = info.hasDefault; 6884 res.labelRes = info.labelRes; 6885 res.nonLocalizedLabel = info.nonLocalizedLabel; 6886 res.icon = info.icon; 6887 res.system = isSystemApp(res.activityInfo.applicationInfo); 6888 return res; 6889 } 6890 6891 @Override 6892 protected void sortResults(List<ResolveInfo> results) { 6893 Collections.sort(results, mResolvePrioritySorter); 6894 } 6895 6896 @Override 6897 protected void dumpFilter(PrintWriter out, String prefix, 6898 PackageParser.ActivityIntentInfo filter) { 6899 out.print(prefix); out.print( 6900 Integer.toHexString(System.identityHashCode(filter.activity))); 6901 out.print(' '); 6902 filter.activity.printComponentShortName(out); 6903 out.print(" filter "); 6904 out.println(Integer.toHexString(System.identityHashCode(filter))); 6905 } 6906 6907// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6908// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6909// final List<ResolveInfo> retList = Lists.newArrayList(); 6910// while (i.hasNext()) { 6911// final ResolveInfo resolveInfo = i.next(); 6912// if (isEnabledLP(resolveInfo.activityInfo)) { 6913// retList.add(resolveInfo); 6914// } 6915// } 6916// return retList; 6917// } 6918 6919 // Keys are String (activity class name), values are Activity. 6920 private final HashMap<ComponentName, PackageParser.Activity> mActivities 6921 = new HashMap<ComponentName, PackageParser.Activity>(); 6922 private int mFlags; 6923 } 6924 6925 private final class ServiceIntentResolver 6926 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 6927 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6928 boolean defaultOnly, int userId) { 6929 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6930 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6931 } 6932 6933 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6934 int userId) { 6935 if (!sUserManager.exists(userId)) return null; 6936 mFlags = flags; 6937 return super.queryIntent(intent, resolvedType, 6938 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6939 } 6940 6941 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6942 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 6943 if (!sUserManager.exists(userId)) return null; 6944 if (packageServices == null) { 6945 return null; 6946 } 6947 mFlags = flags; 6948 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6949 final int N = packageServices.size(); 6950 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 6951 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 6952 6953 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 6954 for (int i = 0; i < N; ++i) { 6955 intentFilters = packageServices.get(i).intents; 6956 if (intentFilters != null && intentFilters.size() > 0) { 6957 PackageParser.ServiceIntentInfo[] array = 6958 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 6959 intentFilters.toArray(array); 6960 listCut.add(array); 6961 } 6962 } 6963 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6964 } 6965 6966 public final void addService(PackageParser.Service s) { 6967 mServices.put(s.getComponentName(), s); 6968 if (DEBUG_SHOW_INFO) { 6969 Log.v(TAG, " " 6970 + (s.info.nonLocalizedLabel != null 6971 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6972 Log.v(TAG, " Class=" + s.info.name); 6973 } 6974 final int NI = s.intents.size(); 6975 int j; 6976 for (j=0; j<NI; j++) { 6977 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6978 if (DEBUG_SHOW_INFO) { 6979 Log.v(TAG, " IntentFilter:"); 6980 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6981 } 6982 if (!intent.debugCheck()) { 6983 Log.w(TAG, "==> For Service " + s.info.name); 6984 } 6985 addFilter(intent); 6986 } 6987 } 6988 6989 public final void removeService(PackageParser.Service s) { 6990 mServices.remove(s.getComponentName()); 6991 if (DEBUG_SHOW_INFO) { 6992 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 6993 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6994 Log.v(TAG, " Class=" + s.info.name); 6995 } 6996 final int NI = s.intents.size(); 6997 int j; 6998 for (j=0; j<NI; j++) { 6999 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7000 if (DEBUG_SHOW_INFO) { 7001 Log.v(TAG, " IntentFilter:"); 7002 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7003 } 7004 removeFilter(intent); 7005 } 7006 } 7007 7008 @Override 7009 protected boolean allowFilterResult( 7010 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7011 ServiceInfo filterSi = filter.service.info; 7012 for (int i=dest.size()-1; i>=0; i--) { 7013 ServiceInfo destAi = dest.get(i).serviceInfo; 7014 if (destAi.name == filterSi.name 7015 && destAi.packageName == filterSi.packageName) { 7016 return false; 7017 } 7018 } 7019 return true; 7020 } 7021 7022 @Override 7023 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7024 return new PackageParser.ServiceIntentInfo[size]; 7025 } 7026 7027 @Override 7028 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7029 if (!sUserManager.exists(userId)) return true; 7030 PackageParser.Package p = filter.service.owner; 7031 if (p != null) { 7032 PackageSetting ps = (PackageSetting)p.mExtras; 7033 if (ps != null) { 7034 // System apps are never considered stopped for purposes of 7035 // filtering, because there may be no way for the user to 7036 // actually re-launch them. 7037 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7038 && ps.getStopped(userId); 7039 } 7040 } 7041 return false; 7042 } 7043 7044 @Override 7045 protected boolean isPackageForFilter(String packageName, 7046 PackageParser.ServiceIntentInfo info) { 7047 return packageName.equals(info.service.owner.packageName); 7048 } 7049 7050 @Override 7051 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7052 int match, int userId) { 7053 if (!sUserManager.exists(userId)) return null; 7054 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7055 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7056 return null; 7057 } 7058 final PackageParser.Service service = info.service; 7059 if (mSafeMode && (service.info.applicationInfo.flags 7060 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7061 return null; 7062 } 7063 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7064 if (ps == null) { 7065 return null; 7066 } 7067 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7068 ps.readUserState(userId), userId); 7069 if (si == null) { 7070 return null; 7071 } 7072 final ResolveInfo res = new ResolveInfo(); 7073 res.serviceInfo = si; 7074 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7075 res.filter = filter; 7076 } 7077 res.priority = info.getPriority(); 7078 res.preferredOrder = service.owner.mPreferredOrder; 7079 //System.out.println("Result: " + res.activityInfo.className + 7080 // " = " + res.priority); 7081 res.match = match; 7082 res.isDefault = info.hasDefault; 7083 res.labelRes = info.labelRes; 7084 res.nonLocalizedLabel = info.nonLocalizedLabel; 7085 res.icon = info.icon; 7086 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7087 return res; 7088 } 7089 7090 @Override 7091 protected void sortResults(List<ResolveInfo> results) { 7092 Collections.sort(results, mResolvePrioritySorter); 7093 } 7094 7095 @Override 7096 protected void dumpFilter(PrintWriter out, String prefix, 7097 PackageParser.ServiceIntentInfo filter) { 7098 out.print(prefix); out.print( 7099 Integer.toHexString(System.identityHashCode(filter.service))); 7100 out.print(' '); 7101 filter.service.printComponentShortName(out); 7102 out.print(" filter "); 7103 out.println(Integer.toHexString(System.identityHashCode(filter))); 7104 } 7105 7106// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7107// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7108// final List<ResolveInfo> retList = Lists.newArrayList(); 7109// while (i.hasNext()) { 7110// final ResolveInfo resolveInfo = (ResolveInfo) i; 7111// if (isEnabledLP(resolveInfo.serviceInfo)) { 7112// retList.add(resolveInfo); 7113// } 7114// } 7115// return retList; 7116// } 7117 7118 // Keys are String (activity class name), values are Activity. 7119 private final HashMap<ComponentName, PackageParser.Service> mServices 7120 = new HashMap<ComponentName, PackageParser.Service>(); 7121 private int mFlags; 7122 }; 7123 7124 private final class ProviderIntentResolver 7125 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7126 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7127 boolean defaultOnly, int userId) { 7128 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7129 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7130 } 7131 7132 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7133 int userId) { 7134 if (!sUserManager.exists(userId)) 7135 return null; 7136 mFlags = flags; 7137 return super.queryIntent(intent, resolvedType, 7138 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7139 } 7140 7141 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7142 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7143 if (!sUserManager.exists(userId)) 7144 return null; 7145 if (packageProviders == null) { 7146 return null; 7147 } 7148 mFlags = flags; 7149 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7150 final int N = packageProviders.size(); 7151 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7152 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7153 7154 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7155 for (int i = 0; i < N; ++i) { 7156 intentFilters = packageProviders.get(i).intents; 7157 if (intentFilters != null && intentFilters.size() > 0) { 7158 PackageParser.ProviderIntentInfo[] array = 7159 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7160 intentFilters.toArray(array); 7161 listCut.add(array); 7162 } 7163 } 7164 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7165 } 7166 7167 public final void addProvider(PackageParser.Provider p) { 7168 if (mProviders.containsKey(p.getComponentName())) { 7169 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7170 return; 7171 } 7172 7173 mProviders.put(p.getComponentName(), p); 7174 if (DEBUG_SHOW_INFO) { 7175 Log.v(TAG, " " 7176 + (p.info.nonLocalizedLabel != null 7177 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7178 Log.v(TAG, " Class=" + p.info.name); 7179 } 7180 final int NI = p.intents.size(); 7181 int j; 7182 for (j = 0; j < NI; j++) { 7183 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7184 if (DEBUG_SHOW_INFO) { 7185 Log.v(TAG, " IntentFilter:"); 7186 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7187 } 7188 if (!intent.debugCheck()) { 7189 Log.w(TAG, "==> For Provider " + p.info.name); 7190 } 7191 addFilter(intent); 7192 } 7193 } 7194 7195 public final void removeProvider(PackageParser.Provider p) { 7196 mProviders.remove(p.getComponentName()); 7197 if (DEBUG_SHOW_INFO) { 7198 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7199 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7200 Log.v(TAG, " Class=" + p.info.name); 7201 } 7202 final int NI = p.intents.size(); 7203 int j; 7204 for (j = 0; j < NI; j++) { 7205 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7206 if (DEBUG_SHOW_INFO) { 7207 Log.v(TAG, " IntentFilter:"); 7208 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7209 } 7210 removeFilter(intent); 7211 } 7212 } 7213 7214 @Override 7215 protected boolean allowFilterResult( 7216 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7217 ProviderInfo filterPi = filter.provider.info; 7218 for (int i = dest.size() - 1; i >= 0; i--) { 7219 ProviderInfo destPi = dest.get(i).providerInfo; 7220 if (destPi.name == filterPi.name 7221 && destPi.packageName == filterPi.packageName) { 7222 return false; 7223 } 7224 } 7225 return true; 7226 } 7227 7228 @Override 7229 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7230 return new PackageParser.ProviderIntentInfo[size]; 7231 } 7232 7233 @Override 7234 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7235 if (!sUserManager.exists(userId)) 7236 return true; 7237 PackageParser.Package p = filter.provider.owner; 7238 if (p != null) { 7239 PackageSetting ps = (PackageSetting) p.mExtras; 7240 if (ps != null) { 7241 // System apps are never considered stopped for purposes of 7242 // filtering, because there may be no way for the user to 7243 // actually re-launch them. 7244 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7245 && ps.getStopped(userId); 7246 } 7247 } 7248 return false; 7249 } 7250 7251 @Override 7252 protected boolean isPackageForFilter(String packageName, 7253 PackageParser.ProviderIntentInfo info) { 7254 return packageName.equals(info.provider.owner.packageName); 7255 } 7256 7257 @Override 7258 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7259 int match, int userId) { 7260 if (!sUserManager.exists(userId)) 7261 return null; 7262 final PackageParser.ProviderIntentInfo info = filter; 7263 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7264 return null; 7265 } 7266 final PackageParser.Provider provider = info.provider; 7267 if (mSafeMode && (provider.info.applicationInfo.flags 7268 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7269 return null; 7270 } 7271 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7272 if (ps == null) { 7273 return null; 7274 } 7275 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7276 ps.readUserState(userId), userId); 7277 if (pi == null) { 7278 return null; 7279 } 7280 final ResolveInfo res = new ResolveInfo(); 7281 res.providerInfo = pi; 7282 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7283 res.filter = filter; 7284 } 7285 res.priority = info.getPriority(); 7286 res.preferredOrder = provider.owner.mPreferredOrder; 7287 res.match = match; 7288 res.isDefault = info.hasDefault; 7289 res.labelRes = info.labelRes; 7290 res.nonLocalizedLabel = info.nonLocalizedLabel; 7291 res.icon = info.icon; 7292 res.system = isSystemApp(res.providerInfo.applicationInfo); 7293 return res; 7294 } 7295 7296 @Override 7297 protected void sortResults(List<ResolveInfo> results) { 7298 Collections.sort(results, mResolvePrioritySorter); 7299 } 7300 7301 @Override 7302 protected void dumpFilter(PrintWriter out, String prefix, 7303 PackageParser.ProviderIntentInfo filter) { 7304 out.print(prefix); 7305 out.print( 7306 Integer.toHexString(System.identityHashCode(filter.provider))); 7307 out.print(' '); 7308 filter.provider.printComponentShortName(out); 7309 out.print(" filter "); 7310 out.println(Integer.toHexString(System.identityHashCode(filter))); 7311 } 7312 7313 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7314 = new HashMap<ComponentName, PackageParser.Provider>(); 7315 private int mFlags; 7316 }; 7317 7318 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7319 new Comparator<ResolveInfo>() { 7320 public int compare(ResolveInfo r1, ResolveInfo r2) { 7321 int v1 = r1.priority; 7322 int v2 = r2.priority; 7323 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7324 if (v1 != v2) { 7325 return (v1 > v2) ? -1 : 1; 7326 } 7327 v1 = r1.preferredOrder; 7328 v2 = r2.preferredOrder; 7329 if (v1 != v2) { 7330 return (v1 > v2) ? -1 : 1; 7331 } 7332 if (r1.isDefault != r2.isDefault) { 7333 return r1.isDefault ? -1 : 1; 7334 } 7335 v1 = r1.match; 7336 v2 = r2.match; 7337 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7338 if (v1 != v2) { 7339 return (v1 > v2) ? -1 : 1; 7340 } 7341 if (r1.system != r2.system) { 7342 return r1.system ? -1 : 1; 7343 } 7344 return 0; 7345 } 7346 }; 7347 7348 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7349 new Comparator<ProviderInfo>() { 7350 public int compare(ProviderInfo p1, ProviderInfo p2) { 7351 final int v1 = p1.initOrder; 7352 final int v2 = p2.initOrder; 7353 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7354 } 7355 }; 7356 7357 static final void sendPackageBroadcast(String action, String pkg, 7358 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7359 int[] userIds) { 7360 IActivityManager am = ActivityManagerNative.getDefault(); 7361 if (am != null) { 7362 try { 7363 if (userIds == null) { 7364 userIds = am.getRunningUserIds(); 7365 } 7366 for (int id : userIds) { 7367 final Intent intent = new Intent(action, 7368 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7369 if (extras != null) { 7370 intent.putExtras(extras); 7371 } 7372 if (targetPkg != null) { 7373 intent.setPackage(targetPkg); 7374 } 7375 // Modify the UID when posting to other users 7376 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7377 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7378 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7379 intent.putExtra(Intent.EXTRA_UID, uid); 7380 } 7381 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7382 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7383 if (DEBUG_BROADCASTS) { 7384 RuntimeException here = new RuntimeException("here"); 7385 here.fillInStackTrace(); 7386 Slog.d(TAG, "Sending to user " + id + ": " 7387 + intent.toShortString(false, true, false, false) 7388 + " " + intent.getExtras(), here); 7389 } 7390 am.broadcastIntent(null, intent, null, finishedReceiver, 7391 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7392 finishedReceiver != null, false, id); 7393 } 7394 } catch (RemoteException ex) { 7395 } 7396 } 7397 } 7398 7399 /** 7400 * Check if the external storage media is available. This is true if there 7401 * is a mounted external storage medium or if the external storage is 7402 * emulated. 7403 */ 7404 private boolean isExternalMediaAvailable() { 7405 return mMediaMounted || Environment.isExternalStorageEmulated(); 7406 } 7407 7408 @Override 7409 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7410 // writer 7411 synchronized (mPackages) { 7412 if (!isExternalMediaAvailable()) { 7413 // If the external storage is no longer mounted at this point, 7414 // the caller may not have been able to delete all of this 7415 // packages files and can not delete any more. Bail. 7416 return null; 7417 } 7418 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7419 if (lastPackage != null) { 7420 pkgs.remove(lastPackage); 7421 } 7422 if (pkgs.size() > 0) { 7423 return pkgs.get(0); 7424 } 7425 } 7426 return null; 7427 } 7428 7429 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7430 if (false) { 7431 RuntimeException here = new RuntimeException("here"); 7432 here.fillInStackTrace(); 7433 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7434 + " andCode=" + andCode, here); 7435 } 7436 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7437 userId, andCode ? 1 : 0, packageName)); 7438 } 7439 7440 void startCleaningPackages() { 7441 // reader 7442 synchronized (mPackages) { 7443 if (!isExternalMediaAvailable()) { 7444 return; 7445 } 7446 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7447 return; 7448 } 7449 } 7450 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7451 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7452 IActivityManager am = ActivityManagerNative.getDefault(); 7453 if (am != null) { 7454 try { 7455 am.startService(null, intent, null, UserHandle.USER_OWNER); 7456 } catch (RemoteException e) { 7457 } 7458 } 7459 } 7460 7461 private final class AppDirObserver extends FileObserver { 7462 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7463 super(path, mask); 7464 mRootDir = path; 7465 mIsRom = isrom; 7466 mIsPrivileged = isPrivileged; 7467 } 7468 7469 public void onEvent(int event, String path) { 7470 String removedPackage = null; 7471 int removedAppId = -1; 7472 int[] removedUsers = null; 7473 String addedPackage = null; 7474 int addedAppId = -1; 7475 int[] addedUsers = null; 7476 7477 // TODO post a message to the handler to obtain serial ordering 7478 synchronized (mInstallLock) { 7479 String fullPathStr = null; 7480 File fullPath = null; 7481 if (path != null) { 7482 fullPath = new File(mRootDir, path); 7483 fullPathStr = fullPath.getPath(); 7484 } 7485 7486 if (DEBUG_APP_DIR_OBSERVER) 7487 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7488 7489 if (!isPackageFilename(path)) { 7490 if (DEBUG_APP_DIR_OBSERVER) 7491 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7492 return; 7493 } 7494 7495 // Ignore packages that are being installed or 7496 // have just been installed. 7497 if (ignoreCodePath(fullPathStr)) { 7498 return; 7499 } 7500 PackageParser.Package p = null; 7501 PackageSetting ps = null; 7502 // reader 7503 synchronized (mPackages) { 7504 p = mAppDirs.get(fullPathStr); 7505 if (p != null) { 7506 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7507 if (ps != null) { 7508 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7509 } else { 7510 removedUsers = sUserManager.getUserIds(); 7511 } 7512 } 7513 addedUsers = sUserManager.getUserIds(); 7514 } 7515 if ((event&REMOVE_EVENTS) != 0) { 7516 if (ps != null) { 7517 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7518 removePackageLI(ps, true); 7519 removedPackage = ps.name; 7520 removedAppId = ps.appId; 7521 } 7522 } 7523 7524 if ((event&ADD_EVENTS) != 0) { 7525 if (p == null) { 7526 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7527 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7528 if (mIsRom) { 7529 flags |= PackageParser.PARSE_IS_SYSTEM 7530 | PackageParser.PARSE_IS_SYSTEM_DIR; 7531 if (mIsPrivileged) { 7532 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7533 } 7534 } 7535 p = scanPackageLI(fullPath, flags, 7536 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7537 System.currentTimeMillis(), UserHandle.ALL); 7538 if (p != null) { 7539 /* 7540 * TODO this seems dangerous as the package may have 7541 * changed since we last acquired the mPackages 7542 * lock. 7543 */ 7544 // writer 7545 synchronized (mPackages) { 7546 updatePermissionsLPw(p.packageName, p, 7547 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7548 } 7549 addedPackage = p.applicationInfo.packageName; 7550 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7551 } 7552 } 7553 } 7554 7555 // reader 7556 synchronized (mPackages) { 7557 mSettings.writeLPr(); 7558 } 7559 } 7560 7561 if (removedPackage != null) { 7562 Bundle extras = new Bundle(1); 7563 extras.putInt(Intent.EXTRA_UID, removedAppId); 7564 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7565 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7566 extras, null, null, removedUsers); 7567 } 7568 if (addedPackage != null) { 7569 Bundle extras = new Bundle(1); 7570 extras.putInt(Intent.EXTRA_UID, addedAppId); 7571 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7572 extras, null, null, addedUsers); 7573 } 7574 } 7575 7576 private final String mRootDir; 7577 private final boolean mIsRom; 7578 private final boolean mIsPrivileged; 7579 } 7580 7581 /* 7582 * The old-style observer methods all just trampoline to the newer signature with 7583 * expanded install observer API. The older API continues to work but does not 7584 * supply the additional details of the Observer2 API. 7585 */ 7586 7587 /* Called when a downloaded package installation has been confirmed by the user */ 7588 public void installPackage( 7589 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 7590 installPackageEtc(packageURI, observer, null, flags, null); 7591 } 7592 7593 /* Called when a downloaded package installation has been confirmed by the user */ 7594 @Override 7595 public void installPackage( 7596 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 7597 final String installerPackageName) { 7598 installPackageWithVerificationEtc(packageURI, observer, null, flags, 7599 installerPackageName, null, null, null); 7600 } 7601 7602 @Override 7603 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 7604 int flags, String installerPackageName, Uri verificationURI, 7605 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7606 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7607 VerificationParams.NO_UID, manifestDigest); 7608 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7609 installerPackageName, verificationParams, encryptionParams); 7610 } 7611 7612 @Override 7613 public void installPackageWithVerificationAndEncryption(Uri packageURI, 7614 IPackageInstallObserver observer, int flags, String installerPackageName, 7615 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7616 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7617 installerPackageName, verificationParams, encryptionParams); 7618 } 7619 7620 /* 7621 * And here are the "live" versions that take both observer arguments 7622 */ 7623 public void installPackageEtc( 7624 final Uri packageURI, final IPackageInstallObserver observer, 7625 IPackageInstallObserver2 observer2, final int flags) { 7626 installPackageEtc(packageURI, observer, observer2, flags, null); 7627 } 7628 7629 public void installPackageEtc( 7630 final Uri packageURI, final IPackageInstallObserver observer, 7631 final IPackageInstallObserver2 observer2, final int flags, 7632 final String installerPackageName) { 7633 installPackageWithVerificationEtc(packageURI, observer, observer2, flags, 7634 installerPackageName, null, null, null); 7635 } 7636 7637 @Override 7638 public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer, 7639 IPackageInstallObserver2 observer2, 7640 int flags, String installerPackageName, Uri verificationURI, 7641 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7642 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7643 VerificationParams.NO_UID, manifestDigest); 7644 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags, 7645 installerPackageName, verificationParams, encryptionParams); 7646 } 7647 7648 /* 7649 * All of the installPackage...*() methods redirect to this one for the master implementation 7650 */ 7651 public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI, 7652 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7653 int flags, String installerPackageName, 7654 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7655 if (observer == null && observer2 == null) { 7656 throw new IllegalArgumentException("No install observer supplied"); 7657 } 7658 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7659 null); 7660 7661 final int uid = Binder.getCallingUid(); 7662 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7663 try { 7664 if (observer != null) { 7665 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7666 } 7667 if (observer2 != null) { 7668 observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7669 } 7670 } catch (RemoteException re) { 7671 } 7672 return; 7673 } 7674 7675 UserHandle user; 7676 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7677 user = UserHandle.ALL; 7678 } else { 7679 user = new UserHandle(UserHandle.getUserId(uid)); 7680 } 7681 7682 final int filteredFlags; 7683 7684 if (uid == Process.SHELL_UID || uid == 0) { 7685 if (DEBUG_INSTALL) { 7686 Slog.v(TAG, "Install from ADB"); 7687 } 7688 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7689 } else { 7690 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7691 } 7692 7693 verificationParams.setInstallerUid(uid); 7694 7695 final Message msg = mHandler.obtainMessage(INIT_COPY); 7696 msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags, 7697 installerPackageName, verificationParams, encryptionParams, user); 7698 mHandler.sendMessage(msg); 7699 } 7700 7701 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7702 Bundle extras = new Bundle(1); 7703 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7704 7705 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7706 packageName, extras, null, null, new int[] {userId}); 7707 try { 7708 IActivityManager am = ActivityManagerNative.getDefault(); 7709 final boolean isSystem = 7710 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7711 if (isSystem && am.isUserRunning(userId, false)) { 7712 // The just-installed/enabled app is bundled on the system, so presumed 7713 // to be able to run automatically without needing an explicit launch. 7714 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7715 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7716 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7717 .setPackage(packageName); 7718 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7719 android.app.AppOpsManager.OP_NONE, false, false, userId); 7720 } 7721 } catch (RemoteException e) { 7722 // shouldn't happen 7723 Slog.w(TAG, "Unable to bootstrap installed package", e); 7724 } 7725 } 7726 7727 @Override 7728 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7729 int userId) { 7730 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7731 PackageSetting pkgSetting; 7732 final int uid = Binder.getCallingUid(); 7733 if (UserHandle.getUserId(uid) != userId) { 7734 mContext.enforceCallingOrSelfPermission( 7735 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7736 "setApplicationBlockedSetting for user " + userId); 7737 } 7738 7739 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7740 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7741 return false; 7742 } 7743 7744 long callingId = Binder.clearCallingIdentity(); 7745 try { 7746 boolean sendAdded = false; 7747 boolean sendRemoved = false; 7748 // writer 7749 synchronized (mPackages) { 7750 pkgSetting = mSettings.mPackages.get(packageName); 7751 if (pkgSetting == null) { 7752 return false; 7753 } 7754 if (pkgSetting.getBlocked(userId) != blocked) { 7755 pkgSetting.setBlocked(blocked, userId); 7756 mSettings.writePackageRestrictionsLPr(userId); 7757 if (blocked) { 7758 sendRemoved = true; 7759 } else { 7760 sendAdded = true; 7761 } 7762 } 7763 } 7764 if (sendAdded) { 7765 sendPackageAddedForUser(packageName, pkgSetting, userId); 7766 return true; 7767 } 7768 if (sendRemoved) { 7769 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7770 "blocking pkg"); 7771 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7772 } 7773 } finally { 7774 Binder.restoreCallingIdentity(callingId); 7775 } 7776 return false; 7777 } 7778 7779 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7780 int userId) { 7781 final PackageRemovedInfo info = new PackageRemovedInfo(); 7782 info.removedPackage = packageName; 7783 info.removedUsers = new int[] {userId}; 7784 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7785 info.sendBroadcast(false, false, false); 7786 } 7787 7788 /** 7789 * Returns true if application is not found or there was an error. Otherwise it returns 7790 * the blocked state of the package for the given user. 7791 */ 7792 @Override 7793 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7794 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7795 PackageSetting pkgSetting; 7796 final int uid = Binder.getCallingUid(); 7797 if (UserHandle.getUserId(uid) != userId) { 7798 mContext.enforceCallingPermission( 7799 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7800 "getApplicationBlocked for user " + userId); 7801 } 7802 long callingId = Binder.clearCallingIdentity(); 7803 try { 7804 // writer 7805 synchronized (mPackages) { 7806 pkgSetting = mSettings.mPackages.get(packageName); 7807 if (pkgSetting == null) { 7808 return true; 7809 } 7810 return pkgSetting.getBlocked(userId); 7811 } 7812 } finally { 7813 Binder.restoreCallingIdentity(callingId); 7814 } 7815 } 7816 7817 void installStage(String basePackageName, File stageDir, IPackageInstallObserver2 observer, 7818 int flags) { 7819 // TODO: install stage! 7820 try { 7821 observer.packageInstalled(basePackageName, null, 7822 PackageManager.INSTALL_FAILED_INTERNAL_ERROR); 7823 } catch (RemoteException ignored) { 7824 } 7825 } 7826 7827 /** 7828 * @hide 7829 */ 7830 @Override 7831 public int installExistingPackageAsUser(String packageName, int userId) { 7832 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7833 null); 7834 PackageSetting pkgSetting; 7835 final int uid = Binder.getCallingUid(); 7836 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7837 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7838 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7839 } 7840 7841 long callingId = Binder.clearCallingIdentity(); 7842 try { 7843 boolean sendAdded = false; 7844 Bundle extras = new Bundle(1); 7845 7846 // writer 7847 synchronized (mPackages) { 7848 pkgSetting = mSettings.mPackages.get(packageName); 7849 if (pkgSetting == null) { 7850 return PackageManager.INSTALL_FAILED_INVALID_URI; 7851 } 7852 if (!pkgSetting.getInstalled(userId)) { 7853 pkgSetting.setInstalled(true, userId); 7854 pkgSetting.setBlocked(false, userId); 7855 mSettings.writePackageRestrictionsLPr(userId); 7856 sendAdded = true; 7857 } 7858 } 7859 7860 if (sendAdded) { 7861 sendPackageAddedForUser(packageName, pkgSetting, userId); 7862 } 7863 } finally { 7864 Binder.restoreCallingIdentity(callingId); 7865 } 7866 7867 return PackageManager.INSTALL_SUCCEEDED; 7868 } 7869 7870 boolean isUserRestricted(int userId, String restrictionKey) { 7871 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7872 if (restrictions.getBoolean(restrictionKey, false)) { 7873 Log.w(TAG, "User is restricted: " + restrictionKey); 7874 return true; 7875 } 7876 return false; 7877 } 7878 7879 @Override 7880 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7881 mContext.enforceCallingOrSelfPermission( 7882 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7883 "Only package verification agents can verify applications"); 7884 7885 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7886 final PackageVerificationResponse response = new PackageVerificationResponse( 7887 verificationCode, Binder.getCallingUid()); 7888 msg.arg1 = id; 7889 msg.obj = response; 7890 mHandler.sendMessage(msg); 7891 } 7892 7893 @Override 7894 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7895 long millisecondsToDelay) { 7896 mContext.enforceCallingOrSelfPermission( 7897 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7898 "Only package verification agents can extend verification timeouts"); 7899 7900 final PackageVerificationState state = mPendingVerification.get(id); 7901 final PackageVerificationResponse response = new PackageVerificationResponse( 7902 verificationCodeAtTimeout, Binder.getCallingUid()); 7903 7904 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7905 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7906 } 7907 if (millisecondsToDelay < 0) { 7908 millisecondsToDelay = 0; 7909 } 7910 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7911 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7912 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7913 } 7914 7915 if ((state != null) && !state.timeoutExtended()) { 7916 state.extendTimeout(); 7917 7918 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7919 msg.arg1 = id; 7920 msg.obj = response; 7921 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7922 } 7923 } 7924 7925 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7926 int verificationCode, UserHandle user) { 7927 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7928 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7929 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7930 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7931 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7932 7933 mContext.sendBroadcastAsUser(intent, user, 7934 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7935 } 7936 7937 private ComponentName matchComponentForVerifier(String packageName, 7938 List<ResolveInfo> receivers) { 7939 ActivityInfo targetReceiver = null; 7940 7941 final int NR = receivers.size(); 7942 for (int i = 0; i < NR; i++) { 7943 final ResolveInfo info = receivers.get(i); 7944 if (info.activityInfo == null) { 7945 continue; 7946 } 7947 7948 if (packageName.equals(info.activityInfo.packageName)) { 7949 targetReceiver = info.activityInfo; 7950 break; 7951 } 7952 } 7953 7954 if (targetReceiver == null) { 7955 return null; 7956 } 7957 7958 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 7959 } 7960 7961 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 7962 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 7963 if (pkgInfo.verifiers.length == 0) { 7964 return null; 7965 } 7966 7967 final int N = pkgInfo.verifiers.length; 7968 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 7969 for (int i = 0; i < N; i++) { 7970 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 7971 7972 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 7973 receivers); 7974 if (comp == null) { 7975 continue; 7976 } 7977 7978 final int verifierUid = getUidForVerifier(verifierInfo); 7979 if (verifierUid == -1) { 7980 continue; 7981 } 7982 7983 if (DEBUG_VERIFY) { 7984 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 7985 + " with the correct signature"); 7986 } 7987 sufficientVerifiers.add(comp); 7988 verificationState.addSufficientVerifier(verifierUid); 7989 } 7990 7991 return sufficientVerifiers; 7992 } 7993 7994 private int getUidForVerifier(VerifierInfo verifierInfo) { 7995 synchronized (mPackages) { 7996 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 7997 if (pkg == null) { 7998 return -1; 7999 } else if (pkg.mSignatures.length != 1) { 8000 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8001 + " has more than one signature; ignoring"); 8002 return -1; 8003 } 8004 8005 /* 8006 * If the public key of the package's signature does not match 8007 * our expected public key, then this is a different package and 8008 * we should skip. 8009 */ 8010 8011 final byte[] expectedPublicKey; 8012 try { 8013 final Signature verifierSig = pkg.mSignatures[0]; 8014 final PublicKey publicKey = verifierSig.getPublicKey(); 8015 expectedPublicKey = publicKey.getEncoded(); 8016 } catch (CertificateException e) { 8017 return -1; 8018 } 8019 8020 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8021 8022 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8023 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8024 + " does not have the expected public key; ignoring"); 8025 return -1; 8026 } 8027 8028 return pkg.applicationInfo.uid; 8029 } 8030 } 8031 8032 @Override 8033 public void finishPackageInstall(int token) { 8034 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8035 8036 if (DEBUG_INSTALL) { 8037 Slog.v(TAG, "BM finishing package install for " + token); 8038 } 8039 8040 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8041 mHandler.sendMessage(msg); 8042 } 8043 8044 /** 8045 * Get the verification agent timeout. 8046 * 8047 * @return verification timeout in milliseconds 8048 */ 8049 private long getVerificationTimeout() { 8050 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8051 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8052 DEFAULT_VERIFICATION_TIMEOUT); 8053 } 8054 8055 /** 8056 * Get the default verification agent response code. 8057 * 8058 * @return default verification response code 8059 */ 8060 private int getDefaultVerificationResponse() { 8061 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8062 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8063 DEFAULT_VERIFICATION_RESPONSE); 8064 } 8065 8066 /** 8067 * Check whether or not package verification has been enabled. 8068 * 8069 * @return true if verification should be performed 8070 */ 8071 private boolean isVerificationEnabled(int flags) { 8072 if (!DEFAULT_VERIFY_ENABLE) { 8073 return false; 8074 } 8075 8076 // Check if installing from ADB 8077 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8078 // Do not run verification in a test harness environment 8079 if (ActivityManager.isRunningInTestHarness()) { 8080 return false; 8081 } 8082 // Check if the developer does not want package verification for ADB installs 8083 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8084 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8085 return false; 8086 } 8087 } 8088 8089 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8090 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8091 } 8092 8093 /** 8094 * Get the "allow unknown sources" setting. 8095 * 8096 * @return the current "allow unknown sources" setting 8097 */ 8098 private int getUnknownSourcesSettings() { 8099 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8100 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8101 -1); 8102 } 8103 8104 @Override 8105 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8106 final int uid = Binder.getCallingUid(); 8107 // writer 8108 synchronized (mPackages) { 8109 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8110 if (targetPackageSetting == null) { 8111 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8112 } 8113 8114 PackageSetting installerPackageSetting; 8115 if (installerPackageName != null) { 8116 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8117 if (installerPackageSetting == null) { 8118 throw new IllegalArgumentException("Unknown installer package: " 8119 + installerPackageName); 8120 } 8121 } else { 8122 installerPackageSetting = null; 8123 } 8124 8125 Signature[] callerSignature; 8126 Object obj = mSettings.getUserIdLPr(uid); 8127 if (obj != null) { 8128 if (obj instanceof SharedUserSetting) { 8129 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8130 } else if (obj instanceof PackageSetting) { 8131 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8132 } else { 8133 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8134 } 8135 } else { 8136 throw new SecurityException("Unknown calling uid " + uid); 8137 } 8138 8139 // Verify: can't set installerPackageName to a package that is 8140 // not signed with the same cert as the caller. 8141 if (installerPackageSetting != null) { 8142 if (compareSignatures(callerSignature, 8143 installerPackageSetting.signatures.mSignatures) 8144 != PackageManager.SIGNATURE_MATCH) { 8145 throw new SecurityException( 8146 "Caller does not have same cert as new installer package " 8147 + installerPackageName); 8148 } 8149 } 8150 8151 // Verify: if target already has an installer package, it must 8152 // be signed with the same cert as the caller. 8153 if (targetPackageSetting.installerPackageName != null) { 8154 PackageSetting setting = mSettings.mPackages.get( 8155 targetPackageSetting.installerPackageName); 8156 // If the currently set package isn't valid, then it's always 8157 // okay to change it. 8158 if (setting != null) { 8159 if (compareSignatures(callerSignature, 8160 setting.signatures.mSignatures) 8161 != PackageManager.SIGNATURE_MATCH) { 8162 throw new SecurityException( 8163 "Caller does not have same cert as old installer package " 8164 + targetPackageSetting.installerPackageName); 8165 } 8166 } 8167 } 8168 8169 // Okay! 8170 targetPackageSetting.installerPackageName = installerPackageName; 8171 scheduleWriteSettingsLocked(); 8172 } 8173 } 8174 8175 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8176 // Queue up an async operation since the package installation may take a little while. 8177 mHandler.post(new Runnable() { 8178 public void run() { 8179 mHandler.removeCallbacks(this); 8180 // Result object to be returned 8181 PackageInstalledInfo res = new PackageInstalledInfo(); 8182 res.returnCode = currentStatus; 8183 res.uid = -1; 8184 res.pkg = null; 8185 res.removedInfo = new PackageRemovedInfo(); 8186 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8187 args.doPreInstall(res.returnCode); 8188 synchronized (mInstallLock) { 8189 installPackageLI(args, true, res); 8190 } 8191 args.doPostInstall(res.returnCode, res.uid); 8192 } 8193 8194 // A restore should be performed at this point if (a) the install 8195 // succeeded, (b) the operation is not an update, and (c) the new 8196 // package has a backupAgent defined. 8197 final boolean update = res.removedInfo.removedPackage != null; 8198 boolean doRestore = (!update 8199 && res.pkg != null 8200 && res.pkg.applicationInfo.backupAgentName != null); 8201 8202 // Set up the post-install work request bookkeeping. This will be used 8203 // and cleaned up by the post-install event handling regardless of whether 8204 // there's a restore pass performed. Token values are >= 1. 8205 int token; 8206 if (mNextInstallToken < 0) mNextInstallToken = 1; 8207 token = mNextInstallToken++; 8208 8209 PostInstallData data = new PostInstallData(args, res); 8210 mRunningInstalls.put(token, data); 8211 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8212 8213 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8214 // Pass responsibility to the Backup Manager. It will perform a 8215 // restore if appropriate, then pass responsibility back to the 8216 // Package Manager to run the post-install observer callbacks 8217 // and broadcasts. 8218 IBackupManager bm = IBackupManager.Stub.asInterface( 8219 ServiceManager.getService(Context.BACKUP_SERVICE)); 8220 if (bm != null) { 8221 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8222 + " to BM for possible restore"); 8223 try { 8224 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8225 } catch (RemoteException e) { 8226 // can't happen; the backup manager is local 8227 } catch (Exception e) { 8228 Slog.e(TAG, "Exception trying to enqueue restore", e); 8229 doRestore = false; 8230 } 8231 } else { 8232 Slog.e(TAG, "Backup Manager not found!"); 8233 doRestore = false; 8234 } 8235 } 8236 8237 if (!doRestore) { 8238 // No restore possible, or the Backup Manager was mysteriously not 8239 // available -- just fire the post-install work request directly. 8240 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8241 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8242 mHandler.sendMessage(msg); 8243 } 8244 } 8245 }); 8246 } 8247 8248 private abstract class HandlerParams { 8249 private static final int MAX_RETRIES = 4; 8250 8251 /** 8252 * Number of times startCopy() has been attempted and had a non-fatal 8253 * error. 8254 */ 8255 private int mRetries = 0; 8256 8257 /** User handle for the user requesting the information or installation. */ 8258 private final UserHandle mUser; 8259 8260 HandlerParams(UserHandle user) { 8261 mUser = user; 8262 } 8263 8264 UserHandle getUser() { 8265 return mUser; 8266 } 8267 8268 final boolean startCopy() { 8269 boolean res; 8270 try { 8271 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8272 8273 if (++mRetries > MAX_RETRIES) { 8274 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8275 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8276 handleServiceError(); 8277 return false; 8278 } else { 8279 handleStartCopy(); 8280 res = true; 8281 } 8282 } catch (RemoteException e) { 8283 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8284 mHandler.sendEmptyMessage(MCS_RECONNECT); 8285 res = false; 8286 } 8287 handleReturnCode(); 8288 return res; 8289 } 8290 8291 final void serviceError() { 8292 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8293 handleServiceError(); 8294 handleReturnCode(); 8295 } 8296 8297 abstract void handleStartCopy() throws RemoteException; 8298 abstract void handleServiceError(); 8299 abstract void handleReturnCode(); 8300 } 8301 8302 class MeasureParams extends HandlerParams { 8303 private final PackageStats mStats; 8304 private boolean mSuccess; 8305 8306 private final IPackageStatsObserver mObserver; 8307 8308 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8309 super(new UserHandle(stats.userHandle)); 8310 mObserver = observer; 8311 mStats = stats; 8312 } 8313 8314 @Override 8315 public String toString() { 8316 return "MeasureParams{" 8317 + Integer.toHexString(System.identityHashCode(this)) 8318 + " " + mStats.packageName + "}"; 8319 } 8320 8321 @Override 8322 void handleStartCopy() throws RemoteException { 8323 synchronized (mInstallLock) { 8324 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8325 } 8326 8327 if (mSuccess) { 8328 final boolean mounted; 8329 if (Environment.isExternalStorageEmulated()) { 8330 mounted = true; 8331 } else { 8332 final String status = Environment.getExternalStorageState(); 8333 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8334 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8335 } 8336 8337 if (mounted) { 8338 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8339 8340 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8341 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8342 8343 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8344 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8345 8346 // Always subtract cache size, since it's a subdirectory 8347 mStats.externalDataSize -= mStats.externalCacheSize; 8348 8349 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8350 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8351 8352 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8353 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8354 } 8355 } 8356 } 8357 8358 @Override 8359 void handleReturnCode() { 8360 if (mObserver != null) { 8361 try { 8362 mObserver.onGetStatsCompleted(mStats, mSuccess); 8363 } catch (RemoteException e) { 8364 Slog.i(TAG, "Observer no longer exists."); 8365 } 8366 } 8367 } 8368 8369 @Override 8370 void handleServiceError() { 8371 Slog.e(TAG, "Could not measure application " + mStats.packageName 8372 + " external storage"); 8373 } 8374 } 8375 8376 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8377 throws RemoteException { 8378 long result = 0; 8379 for (File path : paths) { 8380 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8381 } 8382 return result; 8383 } 8384 8385 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8386 for (File path : paths) { 8387 try { 8388 mcs.clearDirectory(path.getAbsolutePath()); 8389 } catch (RemoteException e) { 8390 } 8391 } 8392 } 8393 8394 class InstallParams extends HandlerParams { 8395 final IPackageInstallObserver observer; 8396 final IPackageInstallObserver2 observer2; 8397 int flags; 8398 8399 private final Uri mPackageURI; 8400 final String installerPackageName; 8401 final VerificationParams verificationParams; 8402 private InstallArgs mArgs; 8403 private int mRet; 8404 private File mTempPackage; 8405 final ContainerEncryptionParams encryptionParams; 8406 8407 InstallParams(Uri packageURI, 8408 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 8409 int flags, String installerPackageName, VerificationParams verificationParams, 8410 ContainerEncryptionParams encryptionParams, UserHandle user) { 8411 super(user); 8412 this.mPackageURI = packageURI; 8413 this.flags = flags; 8414 this.observer = observer; 8415 this.observer2 = observer2; 8416 this.installerPackageName = installerPackageName; 8417 this.verificationParams = verificationParams; 8418 this.encryptionParams = encryptionParams; 8419 } 8420 8421 @Override 8422 public String toString() { 8423 return "InstallParams{" 8424 + Integer.toHexString(System.identityHashCode(this)) 8425 + " " + mPackageURI + "}"; 8426 } 8427 8428 public ManifestDigest getManifestDigest() { 8429 if (verificationParams == null) { 8430 return null; 8431 } 8432 return verificationParams.getManifestDigest(); 8433 } 8434 8435 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8436 String packageName = pkgLite.packageName; 8437 int installLocation = pkgLite.installLocation; 8438 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8439 // reader 8440 synchronized (mPackages) { 8441 PackageParser.Package pkg = mPackages.get(packageName); 8442 if (pkg != null) { 8443 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8444 // Check for downgrading. 8445 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8446 if (pkgLite.versionCode < pkg.mVersionCode) { 8447 Slog.w(TAG, "Can't install update of " + packageName 8448 + " update version " + pkgLite.versionCode 8449 + " is older than installed version " 8450 + pkg.mVersionCode); 8451 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8452 } 8453 } 8454 // Check for updated system application. 8455 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8456 if (onSd) { 8457 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8458 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8459 } 8460 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8461 } else { 8462 if (onSd) { 8463 // Install flag overrides everything. 8464 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8465 } 8466 // If current upgrade specifies particular preference 8467 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8468 // Application explicitly specified internal. 8469 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8470 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8471 // App explictly prefers external. Let policy decide 8472 } else { 8473 // Prefer previous location 8474 if (isExternal(pkg)) { 8475 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8476 } 8477 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8478 } 8479 } 8480 } else { 8481 // Invalid install. Return error code 8482 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8483 } 8484 } 8485 } 8486 // All the special cases have been taken care of. 8487 // Return result based on recommended install location. 8488 if (onSd) { 8489 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8490 } 8491 return pkgLite.recommendedInstallLocation; 8492 } 8493 8494 private long getMemoryLowThreshold() { 8495 final DeviceStorageMonitorInternal 8496 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8497 if (dsm == null) { 8498 return 0L; 8499 } 8500 return dsm.getMemoryLowThreshold(); 8501 } 8502 8503 /* 8504 * Invoke remote method to get package information and install 8505 * location values. Override install location based on default 8506 * policy if needed and then create install arguments based 8507 * on the install location. 8508 */ 8509 public void handleStartCopy() throws RemoteException { 8510 int ret = PackageManager.INSTALL_SUCCEEDED; 8511 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8512 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8513 PackageInfoLite pkgLite = null; 8514 8515 if (onInt && onSd) { 8516 // Check if both bits are set. 8517 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8518 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8519 } else { 8520 final long lowThreshold = getMemoryLowThreshold(); 8521 if (lowThreshold == 0L) { 8522 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8523 } 8524 8525 try { 8526 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI, 8527 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8528 8529 final File packageFile; 8530 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) { 8531 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir); 8532 if (mTempPackage != null) { 8533 ParcelFileDescriptor out; 8534 try { 8535 out = ParcelFileDescriptor.open(mTempPackage, 8536 ParcelFileDescriptor.MODE_READ_WRITE); 8537 } catch (FileNotFoundException e) { 8538 out = null; 8539 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI); 8540 } 8541 8542 // Make a temporary file for decryption. 8543 ret = mContainerService 8544 .copyResource(mPackageURI, encryptionParams, out); 8545 IoUtils.closeQuietly(out); 8546 8547 packageFile = mTempPackage; 8548 8549 FileUtils.setPermissions(packageFile.getAbsolutePath(), 8550 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP 8551 | FileUtils.S_IROTH, 8552 -1, -1); 8553 } else { 8554 packageFile = null; 8555 } 8556 } else { 8557 packageFile = new File(mPackageURI.getPath()); 8558 } 8559 8560 if (packageFile != null) { 8561 // Remote call to find out default install location 8562 final String packageFilePath = packageFile.getAbsolutePath(); 8563 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags, 8564 lowThreshold); 8565 8566 /* 8567 * If we have too little free space, try to free cache 8568 * before giving up. 8569 */ 8570 if (pkgLite.recommendedInstallLocation 8571 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8572 final long size = mContainerService.calculateInstalledSize( 8573 packageFilePath, isForwardLocked()); 8574 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8575 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, 8576 flags, lowThreshold); 8577 } 8578 /* 8579 * The cache free must have deleted the file we 8580 * downloaded to install. 8581 * 8582 * TODO: fix the "freeCache" call to not delete 8583 * the file we care about. 8584 */ 8585 if (pkgLite.recommendedInstallLocation 8586 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8587 pkgLite.recommendedInstallLocation 8588 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8589 } 8590 } 8591 } 8592 } finally { 8593 mContext.revokeUriPermission(mPackageURI, 8594 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8595 } 8596 } 8597 8598 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8599 int loc = pkgLite.recommendedInstallLocation; 8600 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8601 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8602 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8603 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8604 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8605 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8606 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8607 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8608 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8609 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8610 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8611 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8612 } else { 8613 // Override with defaults if needed. 8614 loc = installLocationPolicy(pkgLite, flags); 8615 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8616 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8617 } else if (!onSd && !onInt) { 8618 // Override install location with flags 8619 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8620 // Set the flag to install on external media. 8621 flags |= PackageManager.INSTALL_EXTERNAL; 8622 flags &= ~PackageManager.INSTALL_INTERNAL; 8623 } else { 8624 // Make sure the flag for installing on external 8625 // media is unset 8626 flags |= PackageManager.INSTALL_INTERNAL; 8627 flags &= ~PackageManager.INSTALL_EXTERNAL; 8628 } 8629 } 8630 } 8631 } 8632 8633 final InstallArgs args = createInstallArgs(this); 8634 mArgs = args; 8635 8636 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8637 /* 8638 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8639 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8640 */ 8641 int userIdentifier = getUser().getIdentifier(); 8642 if (userIdentifier == UserHandle.USER_ALL 8643 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8644 userIdentifier = UserHandle.USER_OWNER; 8645 } 8646 8647 /* 8648 * Determine if we have any installed package verifiers. If we 8649 * do, then we'll defer to them to verify the packages. 8650 */ 8651 final int requiredUid = mRequiredVerifierPackage == null ? -1 8652 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8653 if (requiredUid != -1 && isVerificationEnabled(flags)) { 8654 final Intent verification = new Intent( 8655 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8656 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE); 8657 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8658 8659 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8660 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8661 0 /* TODO: Which userId? */); 8662 8663 if (DEBUG_VERIFY) { 8664 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8665 + verification.toString() + " with " + pkgLite.verifiers.length 8666 + " optional verifiers"); 8667 } 8668 8669 final int verificationId = mPendingVerificationToken++; 8670 8671 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8672 8673 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8674 installerPackageName); 8675 8676 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8677 8678 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8679 pkgLite.packageName); 8680 8681 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8682 pkgLite.versionCode); 8683 8684 if (verificationParams != null) { 8685 if (verificationParams.getVerificationURI() != null) { 8686 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8687 verificationParams.getVerificationURI()); 8688 } 8689 if (verificationParams.getOriginatingURI() != null) { 8690 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8691 verificationParams.getOriginatingURI()); 8692 } 8693 if (verificationParams.getReferrer() != null) { 8694 verification.putExtra(Intent.EXTRA_REFERRER, 8695 verificationParams.getReferrer()); 8696 } 8697 if (verificationParams.getOriginatingUid() >= 0) { 8698 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8699 verificationParams.getOriginatingUid()); 8700 } 8701 if (verificationParams.getInstallerUid() >= 0) { 8702 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8703 verificationParams.getInstallerUid()); 8704 } 8705 } 8706 8707 final PackageVerificationState verificationState = new PackageVerificationState( 8708 requiredUid, args); 8709 8710 mPendingVerification.append(verificationId, verificationState); 8711 8712 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8713 receivers, verificationState); 8714 8715 /* 8716 * If any sufficient verifiers were listed in the package 8717 * manifest, attempt to ask them. 8718 */ 8719 if (sufficientVerifiers != null) { 8720 final int N = sufficientVerifiers.size(); 8721 if (N == 0) { 8722 Slog.i(TAG, "Additional verifiers required, but none installed."); 8723 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8724 } else { 8725 for (int i = 0; i < N; i++) { 8726 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8727 8728 final Intent sufficientIntent = new Intent(verification); 8729 sufficientIntent.setComponent(verifierComponent); 8730 8731 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8732 } 8733 } 8734 } 8735 8736 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8737 mRequiredVerifierPackage, receivers); 8738 if (ret == PackageManager.INSTALL_SUCCEEDED 8739 && mRequiredVerifierPackage != null) { 8740 /* 8741 * Send the intent to the required verification agent, 8742 * but only start the verification timeout after the 8743 * target BroadcastReceivers have run. 8744 */ 8745 verification.setComponent(requiredVerifierComponent); 8746 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8747 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8748 new BroadcastReceiver() { 8749 @Override 8750 public void onReceive(Context context, Intent intent) { 8751 final Message msg = mHandler 8752 .obtainMessage(CHECK_PENDING_VERIFICATION); 8753 msg.arg1 = verificationId; 8754 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8755 } 8756 }, null, 0, null, null); 8757 8758 /* 8759 * We don't want the copy to proceed until verification 8760 * succeeds, so null out this field. 8761 */ 8762 mArgs = null; 8763 } 8764 } else { 8765 /* 8766 * No package verification is enabled, so immediately start 8767 * the remote call to initiate copy using temporary file. 8768 */ 8769 ret = args.copyApk(mContainerService, true); 8770 } 8771 } 8772 8773 mRet = ret; 8774 } 8775 8776 @Override 8777 void handleReturnCode() { 8778 // If mArgs is null, then MCS couldn't be reached. When it 8779 // reconnects, it will try again to install. At that point, this 8780 // will succeed. 8781 if (mArgs != null) { 8782 processPendingInstall(mArgs, mRet); 8783 8784 if (mTempPackage != null) { 8785 if (!mTempPackage.delete()) { 8786 Slog.w(TAG, "Couldn't delete temporary file: " + 8787 mTempPackage.getAbsolutePath()); 8788 } 8789 } 8790 } 8791 } 8792 8793 @Override 8794 void handleServiceError() { 8795 mArgs = createInstallArgs(this); 8796 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8797 } 8798 8799 public boolean isForwardLocked() { 8800 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8801 } 8802 8803 public Uri getPackageUri() { 8804 if (mTempPackage != null) { 8805 return Uri.fromFile(mTempPackage); 8806 } else { 8807 return mPackageURI; 8808 } 8809 } 8810 } 8811 8812 /* 8813 * Utility class used in movePackage api. 8814 * srcArgs and targetArgs are not set for invalid flags and make 8815 * sure to do null checks when invoking methods on them. 8816 * We probably want to return ErrorPrams for both failed installs 8817 * and moves. 8818 */ 8819 class MoveParams extends HandlerParams { 8820 final IPackageMoveObserver observer; 8821 final int flags; 8822 final String packageName; 8823 final InstallArgs srcArgs; 8824 final InstallArgs targetArgs; 8825 int uid; 8826 int mRet; 8827 8828 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8829 String packageName, String dataDir, String instructionSet, 8830 int uid, UserHandle user) { 8831 super(user); 8832 this.srcArgs = srcArgs; 8833 this.observer = observer; 8834 this.flags = flags; 8835 this.packageName = packageName; 8836 this.uid = uid; 8837 if (srcArgs != null) { 8838 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath())); 8839 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet); 8840 } else { 8841 targetArgs = null; 8842 } 8843 } 8844 8845 @Override 8846 public String toString() { 8847 return "MoveParams{" 8848 + Integer.toHexString(System.identityHashCode(this)) 8849 + " " + packageName + "}"; 8850 } 8851 8852 public void handleStartCopy() throws RemoteException { 8853 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8854 // Check for storage space on target medium 8855 if (!targetArgs.checkFreeStorage(mContainerService)) { 8856 Log.w(TAG, "Insufficient storage to install"); 8857 return; 8858 } 8859 8860 mRet = srcArgs.doPreCopy(); 8861 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8862 return; 8863 } 8864 8865 mRet = targetArgs.copyApk(mContainerService, false); 8866 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8867 srcArgs.doPostCopy(uid); 8868 return; 8869 } 8870 8871 mRet = srcArgs.doPostCopy(uid); 8872 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8873 return; 8874 } 8875 8876 mRet = targetArgs.doPreInstall(mRet); 8877 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8878 return; 8879 } 8880 8881 if (DEBUG_SD_INSTALL) { 8882 StringBuilder builder = new StringBuilder(); 8883 if (srcArgs != null) { 8884 builder.append("src: "); 8885 builder.append(srcArgs.getCodePath()); 8886 } 8887 if (targetArgs != null) { 8888 builder.append(" target : "); 8889 builder.append(targetArgs.getCodePath()); 8890 } 8891 Log.i(TAG, builder.toString()); 8892 } 8893 } 8894 8895 @Override 8896 void handleReturnCode() { 8897 targetArgs.doPostInstall(mRet, uid); 8898 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8899 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8900 currentStatus = PackageManager.MOVE_SUCCEEDED; 8901 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8902 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8903 } 8904 processPendingMove(this, currentStatus); 8905 } 8906 8907 @Override 8908 void handleServiceError() { 8909 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8910 } 8911 } 8912 8913 /** 8914 * Used during creation of InstallArgs 8915 * 8916 * @param flags package installation flags 8917 * @return true if should be installed on external storage 8918 */ 8919 private static boolean installOnSd(int flags) { 8920 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8921 return false; 8922 } 8923 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8924 return true; 8925 } 8926 return false; 8927 } 8928 8929 /** 8930 * Used during creation of InstallArgs 8931 * 8932 * @param flags package installation flags 8933 * @return true if should be installed as forward locked 8934 */ 8935 private static boolean installForwardLocked(int flags) { 8936 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8937 } 8938 8939 private InstallArgs createInstallArgs(InstallParams params) { 8940 if (installOnSd(params.flags) || params.isForwardLocked()) { 8941 return new AsecInstallArgs(params); 8942 } else { 8943 return new FileInstallArgs(params); 8944 } 8945 } 8946 8947 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath, 8948 String nativeLibraryPath, String instructionSet) { 8949 final boolean isInAsec; 8950 if (installOnSd(flags)) { 8951 /* Apps on SD card are always in ASEC containers. */ 8952 isInAsec = true; 8953 } else if (installForwardLocked(flags) 8954 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8955 /* 8956 * Forward-locked apps are only in ASEC containers if they're the 8957 * new style 8958 */ 8959 isInAsec = true; 8960 } else { 8961 isInAsec = false; 8962 } 8963 8964 if (isInAsec) { 8965 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8966 instructionSet, installOnSd(flags), installForwardLocked(flags)); 8967 } else { 8968 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8969 instructionSet); 8970 } 8971 } 8972 8973 // Used by package mover 8974 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir, 8975 String instructionSet) { 8976 if (installOnSd(flags) || installForwardLocked(flags)) { 8977 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/" 8978 + AsecInstallArgs.RES_FILE_NAME); 8979 return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags), 8980 installForwardLocked(flags)); 8981 } else { 8982 return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet); 8983 } 8984 } 8985 8986 static abstract class InstallArgs { 8987 final IPackageInstallObserver observer; 8988 final IPackageInstallObserver2 observer2; 8989 // Always refers to PackageManager flags only 8990 final int flags; 8991 final Uri packageURI; 8992 final String installerPackageName; 8993 final ManifestDigest manifestDigest; 8994 final UserHandle user; 8995 final String instructionSet; 8996 8997 InstallArgs(Uri packageURI, 8998 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 8999 int flags, String installerPackageName, ManifestDigest manifestDigest, 9000 UserHandle user, String instructionSet) { 9001 this.packageURI = packageURI; 9002 this.flags = flags; 9003 this.observer = observer; 9004 this.observer2 = observer2; 9005 this.installerPackageName = installerPackageName; 9006 this.manifestDigest = manifestDigest; 9007 this.user = user; 9008 this.instructionSet = instructionSet; 9009 } 9010 9011 abstract void createCopyFile(); 9012 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9013 abstract int doPreInstall(int status); 9014 abstract boolean doRename(int status, String pkgName, String oldCodePath); 9015 9016 abstract int doPostInstall(int status, int uid); 9017 abstract String getCodePath(); 9018 abstract String getResourcePath(); 9019 abstract String getNativeLibraryPath(); 9020 // Need installer lock especially for dex file removal. 9021 abstract void cleanUpResourcesLI(); 9022 abstract boolean doPostDeleteLI(boolean delete); 9023 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9024 9025 /** 9026 * Called before the source arguments are copied. This is used mostly 9027 * for MoveParams when it needs to read the source file to put it in the 9028 * destination. 9029 */ 9030 int doPreCopy() { 9031 return PackageManager.INSTALL_SUCCEEDED; 9032 } 9033 9034 /** 9035 * Called after the source arguments are copied. This is used mostly for 9036 * MoveParams when it needs to read the source file to put it in the 9037 * destination. 9038 * 9039 * @return 9040 */ 9041 int doPostCopy(int uid) { 9042 return PackageManager.INSTALL_SUCCEEDED; 9043 } 9044 9045 protected boolean isFwdLocked() { 9046 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9047 } 9048 9049 UserHandle getUser() { 9050 return user; 9051 } 9052 } 9053 9054 class FileInstallArgs extends InstallArgs { 9055 File installDir; 9056 String codeFileName; 9057 String resourceFileName; 9058 String libraryPath; 9059 boolean created = false; 9060 9061 FileInstallArgs(InstallParams params) { 9062 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 9063 params.installerPackageName, params.getManifestDigest(), 9064 params.getUser(), null /* instruction set */); 9065 } 9066 9067 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9068 String instructionSet) { 9069 super(null, null, null, 0, null, null, null, instructionSet); 9070 File codeFile = new File(fullCodePath); 9071 installDir = codeFile.getParentFile(); 9072 codeFileName = fullCodePath; 9073 resourceFileName = fullResourcePath; 9074 libraryPath = nativeLibraryPath; 9075 } 9076 9077 FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) { 9078 super(packageURI, null, null, 0, null, null, null, instructionSet); 9079 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 9080 String apkName = getNextCodePath(null, pkgName, ".apk"); 9081 codeFileName = new File(installDir, apkName + ".apk").getPath(); 9082 resourceFileName = getResourcePathFromCodePath(); 9083 libraryPath = new File(mAppLibInstallDir, pkgName).getPath(); 9084 } 9085 9086 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9087 final long lowThreshold; 9088 9089 final DeviceStorageMonitorInternal 9090 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9091 if (dsm == null) { 9092 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9093 lowThreshold = 0L; 9094 } else { 9095 if (dsm.isMemoryLow()) { 9096 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9097 return false; 9098 } 9099 9100 lowThreshold = dsm.getMemoryLowThreshold(); 9101 } 9102 9103 try { 9104 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9105 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9106 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold); 9107 } finally { 9108 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9109 } 9110 } 9111 9112 String getCodePath() { 9113 return codeFileName; 9114 } 9115 9116 void createCopyFile() { 9117 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 9118 codeFileName = createTempPackageFile(installDir).getPath(); 9119 resourceFileName = getResourcePathFromCodePath(); 9120 libraryPath = getLibraryPathFromCodePath(); 9121 created = true; 9122 } 9123 9124 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9125 if (temp) { 9126 // Generate temp file name 9127 createCopyFile(); 9128 } 9129 // Get a ParcelFileDescriptor to write to the output file 9130 File codeFile = new File(codeFileName); 9131 if (!created) { 9132 try { 9133 codeFile.createNewFile(); 9134 // Set permissions 9135 if (!setPermissions()) { 9136 // Failed setting permissions. 9137 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9138 } 9139 } catch (IOException e) { 9140 Slog.w(TAG, "Failed to create file " + codeFile); 9141 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9142 } 9143 } 9144 ParcelFileDescriptor out = null; 9145 try { 9146 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 9147 } catch (FileNotFoundException e) { 9148 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 9149 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9150 } 9151 // Copy the resource now 9152 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9153 try { 9154 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9155 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9156 ret = imcs.copyResource(packageURI, null, out); 9157 } finally { 9158 IoUtils.closeQuietly(out); 9159 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9160 } 9161 9162 if (isFwdLocked()) { 9163 final File destResourceFile = new File(getResourcePath()); 9164 9165 // Copy the public files 9166 try { 9167 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 9168 } catch (IOException e) { 9169 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 9170 + " forward-locked app."); 9171 destResourceFile.delete(); 9172 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9173 } 9174 } 9175 9176 final File nativeLibraryFile = new File(getNativeLibraryPath()); 9177 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath()); 9178 if (nativeLibraryFile.exists()) { 9179 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 9180 nativeLibraryFile.delete(); 9181 } 9182 try { 9183 int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile); 9184 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9185 return copyRet; 9186 } 9187 } catch (IOException e) { 9188 Slog.e(TAG, "Copying native libraries failed", e); 9189 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9190 } 9191 9192 return ret; 9193 } 9194 9195 int doPreInstall(int status) { 9196 if (status != PackageManager.INSTALL_SUCCEEDED) { 9197 cleanUp(); 9198 } 9199 return status; 9200 } 9201 9202 boolean doRename(int status, final String pkgName, String oldCodePath) { 9203 if (status != PackageManager.INSTALL_SUCCEEDED) { 9204 cleanUp(); 9205 return false; 9206 } else { 9207 final File oldCodeFile = new File(getCodePath()); 9208 final File oldResourceFile = new File(getResourcePath()); 9209 final File oldLibraryFile = new File(getNativeLibraryPath()); 9210 9211 // Rename APK file based on packageName 9212 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 9213 final File newCodeFile = new File(installDir, apkName + ".apk"); 9214 if (!oldCodeFile.renameTo(newCodeFile)) { 9215 return false; 9216 } 9217 codeFileName = newCodeFile.getPath(); 9218 9219 // Rename public resource file if it's forward-locked. 9220 final File newResFile = new File(getResourcePathFromCodePath()); 9221 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 9222 return false; 9223 } 9224 resourceFileName = newResFile.getPath(); 9225 9226 // Rename library path 9227 final File newLibraryFile = new File(getLibraryPathFromCodePath()); 9228 if (newLibraryFile.exists()) { 9229 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile); 9230 newLibraryFile.delete(); 9231 } 9232 if (!oldLibraryFile.renameTo(newLibraryFile)) { 9233 Slog.e(TAG, "Cannot rename native library directory " 9234 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath()); 9235 return false; 9236 } 9237 libraryPath = newLibraryFile.getPath(); 9238 9239 // Attempt to set permissions 9240 if (!setPermissions()) { 9241 return false; 9242 } 9243 9244 if (!SELinux.restorecon(newCodeFile)) { 9245 return false; 9246 } 9247 9248 return true; 9249 } 9250 } 9251 9252 int doPostInstall(int status, int uid) { 9253 if (status != PackageManager.INSTALL_SUCCEEDED) { 9254 cleanUp(); 9255 } 9256 return status; 9257 } 9258 9259 String getResourcePath() { 9260 return resourceFileName; 9261 } 9262 9263 private String getResourcePathFromCodePath() { 9264 final String codePath = getCodePath(); 9265 if (isFwdLocked()) { 9266 final StringBuilder sb = new StringBuilder(); 9267 9268 sb.append(mAppInstallDir.getPath()); 9269 sb.append('/'); 9270 sb.append(getApkName(codePath)); 9271 sb.append(".zip"); 9272 9273 /* 9274 * If our APK is a temporary file, mark the resource as a 9275 * temporary file as well so it can be cleaned up after 9276 * catastrophic failure. 9277 */ 9278 if (codePath.endsWith(".tmp")) { 9279 sb.append(".tmp"); 9280 } 9281 9282 return sb.toString(); 9283 } else { 9284 return codePath; 9285 } 9286 } 9287 9288 private String getLibraryPathFromCodePath() { 9289 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath(); 9290 } 9291 9292 @Override 9293 String getNativeLibraryPath() { 9294 if (libraryPath == null) { 9295 libraryPath = getLibraryPathFromCodePath(); 9296 } 9297 return libraryPath; 9298 } 9299 9300 private boolean cleanUp() { 9301 boolean ret = true; 9302 String sourceDir = getCodePath(); 9303 String publicSourceDir = getResourcePath(); 9304 if (sourceDir != null) { 9305 File sourceFile = new File(sourceDir); 9306 if (!sourceFile.exists()) { 9307 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 9308 ret = false; 9309 } 9310 // Delete application's code and resources 9311 sourceFile.delete(); 9312 } 9313 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 9314 final File publicSourceFile = new File(publicSourceDir); 9315 if (!publicSourceFile.exists()) { 9316 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 9317 } 9318 if (publicSourceFile.exists()) { 9319 publicSourceFile.delete(); 9320 } 9321 } 9322 9323 if (libraryPath != null) { 9324 File nativeLibraryFile = new File(libraryPath); 9325 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 9326 if (!nativeLibraryFile.delete()) { 9327 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath); 9328 } 9329 } 9330 9331 return ret; 9332 } 9333 9334 void cleanUpResourcesLI() { 9335 String sourceDir = getCodePath(); 9336 if (cleanUp()) { 9337 if (instructionSet == null) { 9338 throw new IllegalStateException("instructionSet == null"); 9339 } 9340 int retCode = mInstaller.rmdex(sourceDir, instructionSet); 9341 if (retCode < 0) { 9342 Slog.w(TAG, "Couldn't remove dex file for package: " 9343 + " at location " 9344 + sourceDir + ", retcode=" + retCode); 9345 // we don't consider this to be a failure of the core package deletion 9346 } 9347 } 9348 } 9349 9350 private boolean setPermissions() { 9351 // TODO Do this in a more elegant way later on. for now just a hack 9352 if (!isFwdLocked()) { 9353 final int filePermissions = 9354 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 9355 |FileUtils.S_IROTH; 9356 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 9357 if (retCode != 0) { 9358 Slog.e(TAG, "Couldn't set new package file permissions for " + 9359 getCodePath() 9360 + ". The return code was: " + retCode); 9361 // TODO Define new internal error 9362 return false; 9363 } 9364 return true; 9365 } 9366 return true; 9367 } 9368 9369 boolean doPostDeleteLI(boolean delete) { 9370 // XXX err, shouldn't we respect the delete flag? 9371 cleanUpResourcesLI(); 9372 return true; 9373 } 9374 } 9375 9376 private boolean isAsecExternal(String cid) { 9377 final String asecPath = PackageHelper.getSdFilesystem(cid); 9378 return !asecPath.startsWith(mAsecInternalPath); 9379 } 9380 9381 /** 9382 * Extract the MountService "container ID" from the full code path of an 9383 * .apk. 9384 */ 9385 static String cidFromCodePath(String fullCodePath) { 9386 int eidx = fullCodePath.lastIndexOf("/"); 9387 String subStr1 = fullCodePath.substring(0, eidx); 9388 int sidx = subStr1.lastIndexOf("/"); 9389 return subStr1.substring(sidx+1, eidx); 9390 } 9391 9392 class AsecInstallArgs extends InstallArgs { 9393 static final String RES_FILE_NAME = "pkg.apk"; 9394 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9395 9396 String cid; 9397 String packagePath; 9398 String resourcePath; 9399 String libraryPath; 9400 9401 AsecInstallArgs(InstallParams params) { 9402 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 9403 params.installerPackageName, params.getManifestDigest(), 9404 params.getUser(), null /* instruction set */); 9405 } 9406 9407 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9408 String instructionSet, boolean isExternal, boolean isForwardLocked) { 9409 super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9410 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9411 null, null, null, instructionSet); 9412 // Extract cid from fullCodePath 9413 int eidx = fullCodePath.lastIndexOf("/"); 9414 String subStr1 = fullCodePath.substring(0, eidx); 9415 int sidx = subStr1.lastIndexOf("/"); 9416 cid = subStr1.substring(sidx+1, eidx); 9417 setCachePath(subStr1); 9418 } 9419 9420 AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) { 9421 super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 9422 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9423 null, null, null, instructionSet); 9424 this.cid = cid; 9425 setCachePath(PackageHelper.getSdDir(cid)); 9426 } 9427 9428 AsecInstallArgs(Uri packageURI, String cid, String instructionSet, 9429 boolean isExternal, boolean isForwardLocked) { 9430 super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9431 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9432 null, null, null, instructionSet); 9433 this.cid = cid; 9434 } 9435 9436 void createCopyFile() { 9437 cid = getTempContainerId(); 9438 } 9439 9440 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9441 try { 9442 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9443 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9444 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked()); 9445 } finally { 9446 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9447 } 9448 } 9449 9450 private final boolean isExternal() { 9451 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9452 } 9453 9454 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9455 if (temp) { 9456 createCopyFile(); 9457 } else { 9458 /* 9459 * Pre-emptively destroy the container since it's destroyed if 9460 * copying fails due to it existing anyway. 9461 */ 9462 PackageHelper.destroySdDir(cid); 9463 } 9464 9465 final String newCachePath; 9466 try { 9467 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9468 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9469 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(), 9470 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked()); 9471 } finally { 9472 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9473 } 9474 9475 if (newCachePath != null) { 9476 setCachePath(newCachePath); 9477 return PackageManager.INSTALL_SUCCEEDED; 9478 } else { 9479 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9480 } 9481 } 9482 9483 @Override 9484 String getCodePath() { 9485 return packagePath; 9486 } 9487 9488 @Override 9489 String getResourcePath() { 9490 return resourcePath; 9491 } 9492 9493 @Override 9494 String getNativeLibraryPath() { 9495 return libraryPath; 9496 } 9497 9498 int doPreInstall(int status) { 9499 if (status != PackageManager.INSTALL_SUCCEEDED) { 9500 // Destroy container 9501 PackageHelper.destroySdDir(cid); 9502 } else { 9503 boolean mounted = PackageHelper.isContainerMounted(cid); 9504 if (!mounted) { 9505 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9506 Process.SYSTEM_UID); 9507 if (newCachePath != null) { 9508 setCachePath(newCachePath); 9509 } else { 9510 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9511 } 9512 } 9513 } 9514 return status; 9515 } 9516 9517 boolean doRename(int status, final String pkgName, 9518 String oldCodePath) { 9519 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 9520 String newCachePath = null; 9521 if (PackageHelper.isContainerMounted(cid)) { 9522 // Unmount the container 9523 if (!PackageHelper.unMountSdDir(cid)) { 9524 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9525 return false; 9526 } 9527 } 9528 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9529 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9530 " which might be stale. Will try to clean up."); 9531 // Clean up the stale container and proceed to recreate. 9532 if (!PackageHelper.destroySdDir(newCacheId)) { 9533 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9534 return false; 9535 } 9536 // Successfully cleaned up stale container. Try to rename again. 9537 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9538 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9539 + " inspite of cleaning it up."); 9540 return false; 9541 } 9542 } 9543 if (!PackageHelper.isContainerMounted(newCacheId)) { 9544 Slog.w(TAG, "Mounting container " + newCacheId); 9545 newCachePath = PackageHelper.mountSdDir(newCacheId, 9546 getEncryptKey(), Process.SYSTEM_UID); 9547 } else { 9548 newCachePath = PackageHelper.getSdDir(newCacheId); 9549 } 9550 if (newCachePath == null) { 9551 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9552 return false; 9553 } 9554 Log.i(TAG, "Succesfully renamed " + cid + 9555 " to " + newCacheId + 9556 " at new path: " + newCachePath); 9557 cid = newCacheId; 9558 setCachePath(newCachePath); 9559 return true; 9560 } 9561 9562 private void setCachePath(String newCachePath) { 9563 File cachePath = new File(newCachePath); 9564 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 9565 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9566 9567 if (isFwdLocked()) { 9568 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9569 } else { 9570 resourcePath = packagePath; 9571 } 9572 } 9573 9574 int doPostInstall(int status, int uid) { 9575 if (status != PackageManager.INSTALL_SUCCEEDED) { 9576 cleanUp(); 9577 } else { 9578 final int groupOwner; 9579 final String protectedFile; 9580 if (isFwdLocked()) { 9581 groupOwner = UserHandle.getSharedAppGid(uid); 9582 protectedFile = RES_FILE_NAME; 9583 } else { 9584 groupOwner = -1; 9585 protectedFile = null; 9586 } 9587 9588 if (uid < Process.FIRST_APPLICATION_UID 9589 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9590 Slog.e(TAG, "Failed to finalize " + cid); 9591 PackageHelper.destroySdDir(cid); 9592 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9593 } 9594 9595 boolean mounted = PackageHelper.isContainerMounted(cid); 9596 if (!mounted) { 9597 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9598 } 9599 } 9600 return status; 9601 } 9602 9603 private void cleanUp() { 9604 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9605 9606 // Destroy secure container 9607 PackageHelper.destroySdDir(cid); 9608 } 9609 9610 void cleanUpResourcesLI() { 9611 String sourceFile = getCodePath(); 9612 // Remove dex file 9613 if (instructionSet == null) { 9614 throw new IllegalStateException("instructionSet == null"); 9615 } 9616 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9617 if (retCode < 0) { 9618 Slog.w(TAG, "Couldn't remove dex file for package: " 9619 + " at location " 9620 + sourceFile.toString() + ", retcode=" + retCode); 9621 // we don't consider this to be a failure of the core package deletion 9622 } 9623 cleanUp(); 9624 } 9625 9626 boolean matchContainer(String app) { 9627 if (cid.startsWith(app)) { 9628 return true; 9629 } 9630 return false; 9631 } 9632 9633 String getPackageName() { 9634 return getAsecPackageName(cid); 9635 } 9636 9637 boolean doPostDeleteLI(boolean delete) { 9638 boolean ret = false; 9639 boolean mounted = PackageHelper.isContainerMounted(cid); 9640 if (mounted) { 9641 // Unmount first 9642 ret = PackageHelper.unMountSdDir(cid); 9643 } 9644 if (ret && delete) { 9645 cleanUpResourcesLI(); 9646 } 9647 return ret; 9648 } 9649 9650 @Override 9651 int doPreCopy() { 9652 if (isFwdLocked()) { 9653 if (!PackageHelper.fixSdPermissions(cid, 9654 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9655 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9656 } 9657 } 9658 9659 return PackageManager.INSTALL_SUCCEEDED; 9660 } 9661 9662 @Override 9663 int doPostCopy(int uid) { 9664 if (isFwdLocked()) { 9665 if (uid < Process.FIRST_APPLICATION_UID 9666 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9667 RES_FILE_NAME)) { 9668 Slog.e(TAG, "Failed to finalize " + cid); 9669 PackageHelper.destroySdDir(cid); 9670 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9671 } 9672 } 9673 9674 return PackageManager.INSTALL_SUCCEEDED; 9675 } 9676 }; 9677 9678 static String getAsecPackageName(String packageCid) { 9679 int idx = packageCid.lastIndexOf("-"); 9680 if (idx == -1) { 9681 return packageCid; 9682 } 9683 return packageCid.substring(0, idx); 9684 } 9685 9686 // Utility method used to create code paths based on package name and available index. 9687 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9688 String idxStr = ""; 9689 int idx = 1; 9690 // Fall back to default value of idx=1 if prefix is not 9691 // part of oldCodePath 9692 if (oldCodePath != null) { 9693 String subStr = oldCodePath; 9694 // Drop the suffix right away 9695 if (subStr.endsWith(suffix)) { 9696 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9697 } 9698 // If oldCodePath already contains prefix find out the 9699 // ending index to either increment or decrement. 9700 int sidx = subStr.lastIndexOf(prefix); 9701 if (sidx != -1) { 9702 subStr = subStr.substring(sidx + prefix.length()); 9703 if (subStr != null) { 9704 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9705 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9706 } 9707 try { 9708 idx = Integer.parseInt(subStr); 9709 if (idx <= 1) { 9710 idx++; 9711 } else { 9712 idx--; 9713 } 9714 } catch(NumberFormatException e) { 9715 } 9716 } 9717 } 9718 } 9719 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9720 return prefix + idxStr; 9721 } 9722 9723 // Utility method used to ignore ADD/REMOVE events 9724 // by directory observer. 9725 private static boolean ignoreCodePath(String fullPathStr) { 9726 String apkName = getApkName(fullPathStr); 9727 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9728 if (idx != -1 && ((idx+1) < apkName.length())) { 9729 // Make sure the package ends with a numeral 9730 String version = apkName.substring(idx+1); 9731 try { 9732 Integer.parseInt(version); 9733 return true; 9734 } catch (NumberFormatException e) {} 9735 } 9736 return false; 9737 } 9738 9739 // Utility method that returns the relative package path with respect 9740 // to the installation directory. Like say for /data/data/com.test-1.apk 9741 // string com.test-1 is returned. 9742 static String getApkName(String codePath) { 9743 if (codePath == null) { 9744 return null; 9745 } 9746 int sidx = codePath.lastIndexOf("/"); 9747 int eidx = codePath.lastIndexOf("."); 9748 if (eidx == -1) { 9749 eidx = codePath.length(); 9750 } else if (eidx == 0) { 9751 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 9752 return null; 9753 } 9754 return codePath.substring(sidx+1, eidx); 9755 } 9756 9757 class PackageInstalledInfo { 9758 String name; 9759 int uid; 9760 // The set of users that originally had this package installed. 9761 int[] origUsers; 9762 // The set of users that now have this package installed. 9763 int[] newUsers; 9764 PackageParser.Package pkg; 9765 int returnCode; 9766 PackageRemovedInfo removedInfo; 9767 9768 // In some error cases we want to convey more info back to the observer 9769 String origPackage; 9770 String origPermission; 9771 } 9772 9773 /* 9774 * Install a non-existing package. 9775 */ 9776 private void installNewPackageLI(PackageParser.Package pkg, 9777 int parseFlags, int scanMode, UserHandle user, 9778 String installerPackageName, PackageInstalledInfo res) { 9779 // Remember this for later, in case we need to rollback this install 9780 String pkgName = pkg.packageName; 9781 9782 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9783 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9784 synchronized(mPackages) { 9785 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9786 // A package with the same name is already installed, though 9787 // it has been renamed to an older name. The package we 9788 // are trying to install should be installed as an update to 9789 // the existing one, but that has not been requested, so bail. 9790 Slog.w(TAG, "Attempt to re-install " + pkgName 9791 + " without first uninstalling package running as " 9792 + mSettings.mRenamedPackages.get(pkgName)); 9793 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9794 return; 9795 } 9796 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) { 9797 // Don't allow installation over an existing package with the same name. 9798 Slog.w(TAG, "Attempt to re-install " + pkgName 9799 + " without first uninstalling."); 9800 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9801 return; 9802 } 9803 } 9804 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9805 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9806 System.currentTimeMillis(), user); 9807 if (newPackage == null) { 9808 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9809 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9810 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9811 } 9812 } else { 9813 updateSettingsLI(newPackage, 9814 installerPackageName, 9815 null, null, 9816 res); 9817 // delete the partially installed application. the data directory will have to be 9818 // restored if it was already existing 9819 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9820 // remove package from internal structures. Note that we want deletePackageX to 9821 // delete the package data and cache directories that it created in 9822 // scanPackageLocked, unless those directories existed before we even tried to 9823 // install. 9824 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9825 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9826 res.removedInfo, true); 9827 } 9828 } 9829 } 9830 9831 private void replacePackageLI(PackageParser.Package pkg, 9832 int parseFlags, int scanMode, UserHandle user, 9833 String installerPackageName, PackageInstalledInfo res) { 9834 9835 PackageParser.Package oldPackage; 9836 String pkgName = pkg.packageName; 9837 int[] allUsers; 9838 boolean[] perUserInstalled; 9839 9840 // First find the old package info and check signatures 9841 synchronized(mPackages) { 9842 oldPackage = mPackages.get(pkgName); 9843 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9844 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9845 != PackageManager.SIGNATURE_MATCH) { 9846 Slog.w(TAG, "New package has a different signature: " + pkgName); 9847 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9848 return; 9849 } 9850 9851 // In case of rollback, remember per-user/profile install state 9852 PackageSetting ps = mSettings.mPackages.get(pkgName); 9853 allUsers = sUserManager.getUserIds(); 9854 perUserInstalled = new boolean[allUsers.length]; 9855 for (int i = 0; i < allUsers.length; i++) { 9856 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9857 } 9858 } 9859 boolean sysPkg = (isSystemApp(oldPackage)); 9860 if (sysPkg) { 9861 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9862 user, allUsers, perUserInstalled, installerPackageName, res); 9863 } else { 9864 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9865 user, allUsers, perUserInstalled, installerPackageName, res); 9866 } 9867 } 9868 9869 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9870 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9871 int[] allUsers, boolean[] perUserInstalled, 9872 String installerPackageName, PackageInstalledInfo res) { 9873 PackageParser.Package newPackage = null; 9874 String pkgName = deletedPackage.packageName; 9875 boolean deletedPkg = true; 9876 boolean updatedSettings = false; 9877 9878 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9879 + deletedPackage); 9880 long origUpdateTime; 9881 if (pkg.mExtras != null) { 9882 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9883 } else { 9884 origUpdateTime = 0; 9885 } 9886 9887 // First delete the existing package while retaining the data directory 9888 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9889 res.removedInfo, true)) { 9890 // If the existing package wasn't successfully deleted 9891 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9892 deletedPkg = false; 9893 } else { 9894 // Successfully deleted the old package. Now proceed with re-installation 9895 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9896 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9897 System.currentTimeMillis(), user); 9898 if (newPackage == null) { 9899 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9900 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9901 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9902 } 9903 } else { 9904 updateSettingsLI(newPackage, 9905 installerPackageName, 9906 allUsers, perUserInstalled, 9907 res); 9908 updatedSettings = true; 9909 } 9910 } 9911 9912 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9913 // remove package from internal structures. Note that we want deletePackageX to 9914 // delete the package data and cache directories that it created in 9915 // scanPackageLocked, unless those directories existed before we even tried to 9916 // install. 9917 if(updatedSettings) { 9918 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9919 deletePackageLI( 9920 pkgName, null, true, allUsers, perUserInstalled, 9921 PackageManager.DELETE_KEEP_DATA, 9922 res.removedInfo, true); 9923 } 9924 // Since we failed to install the new package we need to restore the old 9925 // package that we deleted. 9926 if(deletedPkg) { 9927 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9928 File restoreFile = new File(deletedPackage.mPath); 9929 // Parse old package 9930 boolean oldOnSd = isExternal(deletedPackage); 9931 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9932 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9933 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9934 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 9935 | SCAN_UPDATE_TIME; 9936 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 9937 origUpdateTime, null) == null) { 9938 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 9939 return; 9940 } 9941 // Restore of old package succeeded. Update permissions. 9942 // writer 9943 synchronized (mPackages) { 9944 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9945 UPDATE_PERMISSIONS_ALL); 9946 // can downgrade to reader 9947 mSettings.writeLPr(); 9948 } 9949 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9950 } 9951 } 9952 } 9953 9954 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9955 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9956 int[] allUsers, boolean[] perUserInstalled, 9957 String installerPackageName, PackageInstalledInfo res) { 9958 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9959 + ", old=" + deletedPackage); 9960 PackageParser.Package newPackage = null; 9961 boolean updatedSettings = false; 9962 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 9963 PackageParser.PARSE_IS_SYSTEM; 9964 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9965 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9966 } 9967 String packageName = deletedPackage.packageName; 9968 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9969 if (packageName == null) { 9970 Slog.w(TAG, "Attempt to delete null packageName."); 9971 return; 9972 } 9973 PackageParser.Package oldPkg; 9974 PackageSetting oldPkgSetting; 9975 // reader 9976 synchronized (mPackages) { 9977 oldPkg = mPackages.get(packageName); 9978 oldPkgSetting = mSettings.mPackages.get(packageName); 9979 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 9980 (oldPkgSetting == null)) { 9981 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 9982 return; 9983 } 9984 } 9985 9986 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 9987 9988 res.removedInfo.uid = oldPkg.applicationInfo.uid; 9989 res.removedInfo.removedPackage = packageName; 9990 // Remove existing system package 9991 removePackageLI(oldPkgSetting, true); 9992 // writer 9993 synchronized (mPackages) { 9994 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 9995 // We didn't need to disable the .apk as a current system package, 9996 // which means we are replacing another update that is already 9997 // installed. We need to make sure to delete the older one's .apk. 9998 res.removedInfo.args = createInstallArgs(0, 9999 deletedPackage.applicationInfo.sourceDir, 10000 deletedPackage.applicationInfo.publicSourceDir, 10001 deletedPackage.applicationInfo.nativeLibraryDir, 10002 getAppInstructionSet(deletedPackage.applicationInfo)); 10003 } else { 10004 res.removedInfo.args = null; 10005 } 10006 } 10007 10008 // Successfully disabled the old package. Now proceed with re-installation 10009 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 10010 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10011 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user); 10012 if (newPackage == null) { 10013 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 10014 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 10015 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 10016 } 10017 } else { 10018 if (newPackage.mExtras != null) { 10019 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 10020 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10021 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10022 10023 // is the update attempting to change shared user? that isn't going to work... 10024 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10025 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 10026 + " to " + newPkgSetting.sharedUser); 10027 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 10028 updatedSettings = true; 10029 } 10030 } 10031 10032 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10033 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10034 updatedSettings = true; 10035 } 10036 } 10037 10038 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10039 // Re installation failed. Restore old information 10040 // Remove new pkg information 10041 if (newPackage != null) { 10042 removeInstalledPackageLI(newPackage, true); 10043 } 10044 // Add back the old system package 10045 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user); 10046 // Restore the old system information in Settings 10047 synchronized(mPackages) { 10048 if (updatedSettings) { 10049 mSettings.enableSystemPackageLPw(packageName); 10050 mSettings.setInstallerPackageName(packageName, 10051 oldPkgSetting.installerPackageName); 10052 } 10053 mSettings.writeLPr(); 10054 } 10055 } 10056 } 10057 10058 // Utility method used to move dex files during install. 10059 private int moveDexFilesLI(PackageParser.Package newPackage) { 10060 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10061 final String instructionSet = getAppInstructionSet(newPackage.applicationInfo); 10062 int retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath, 10063 instructionSet); 10064 if (retCode != 0) { 10065 /* 10066 * Programs may be lazily run through dexopt, so the 10067 * source may not exist. However, something seems to 10068 * have gone wrong, so note that dexopt needs to be 10069 * run again and remove the source file. In addition, 10070 * remove the target to make sure there isn't a stale 10071 * file from a previous version of the package. 10072 */ 10073 newPackage.mDexOptNeeded = true; 10074 mInstaller.rmdex(newPackage.mScanPath, instructionSet); 10075 mInstaller.rmdex(newPackage.mPath, instructionSet); 10076 } 10077 } 10078 return PackageManager.INSTALL_SUCCEEDED; 10079 } 10080 10081 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10082 int[] allUsers, boolean[] perUserInstalled, 10083 PackageInstalledInfo res) { 10084 String pkgName = newPackage.packageName; 10085 synchronized (mPackages) { 10086 //write settings. the installStatus will be incomplete at this stage. 10087 //note that the new package setting would have already been 10088 //added to mPackages. It hasn't been persisted yet. 10089 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10090 mSettings.writeLPr(); 10091 } 10092 10093 if ((res.returnCode = moveDexFilesLI(newPackage)) 10094 != PackageManager.INSTALL_SUCCEEDED) { 10095 // Discontinue if moving dex files failed. 10096 return; 10097 } 10098 10099 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath); 10100 10101 synchronized (mPackages) { 10102 updatePermissionsLPw(newPackage.packageName, newPackage, 10103 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10104 ? UPDATE_PERMISSIONS_ALL : 0)); 10105 // For system-bundled packages, we assume that installing an upgraded version 10106 // of the package implies that the user actually wants to run that new code, 10107 // so we enable the package. 10108 if (isSystemApp(newPackage)) { 10109 // NB: implicit assumption that system package upgrades apply to all users 10110 if (DEBUG_INSTALL) { 10111 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10112 } 10113 PackageSetting ps = mSettings.mPackages.get(pkgName); 10114 if (ps != null) { 10115 if (res.origUsers != null) { 10116 for (int userHandle : res.origUsers) { 10117 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10118 userHandle, installerPackageName); 10119 } 10120 } 10121 // Also convey the prior install/uninstall state 10122 if (allUsers != null && perUserInstalled != null) { 10123 for (int i = 0; i < allUsers.length; i++) { 10124 if (DEBUG_INSTALL) { 10125 Slog.d(TAG, " user " + allUsers[i] 10126 + " => " + perUserInstalled[i]); 10127 } 10128 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10129 } 10130 // these install state changes will be persisted in the 10131 // upcoming call to mSettings.writeLPr(). 10132 } 10133 } 10134 } 10135 res.name = pkgName; 10136 res.uid = newPackage.applicationInfo.uid; 10137 res.pkg = newPackage; 10138 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10139 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10140 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10141 //to update install status 10142 mSettings.writeLPr(); 10143 } 10144 } 10145 10146 private void installPackageLI(InstallArgs args, 10147 boolean newInstall, PackageInstalledInfo res) { 10148 int pFlags = args.flags; 10149 String installerPackageName = args.installerPackageName; 10150 File tmpPackageFile = new File(args.getCodePath()); 10151 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10152 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10153 boolean replace = false; 10154 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10155 | (newInstall ? SCAN_NEW_INSTALL : 0); 10156 // Result object to be returned 10157 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10158 10159 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10160 // Retrieve PackageSettings and parse package 10161 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10162 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10163 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10164 PackageParser pp = new PackageParser(tmpPackageFile.getPath()); 10165 pp.setSeparateProcesses(mSeparateProcesses); 10166 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile, 10167 null, mMetrics, parseFlags); 10168 if (pkg == null) { 10169 res.returnCode = pp.getParseError(); 10170 return; 10171 } 10172 String pkgName = res.name = pkg.packageName; 10173 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10174 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10175 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 10176 return; 10177 } 10178 } 10179 if (!pp.collectCertificates(pkg, parseFlags)) { 10180 res.returnCode = pp.getParseError(); 10181 return; 10182 } 10183 10184 /* If the installer passed in a manifest digest, compare it now. */ 10185 if (args.manifestDigest != null) { 10186 if (DEBUG_INSTALL) { 10187 final String parsedManifest = pkg.manifestDigest == null ? "null" 10188 : pkg.manifestDigest.toString(); 10189 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10190 + parsedManifest); 10191 } 10192 10193 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10194 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 10195 return; 10196 } 10197 } else if (DEBUG_INSTALL) { 10198 final String parsedManifest = pkg.manifestDigest == null 10199 ? "null" : pkg.manifestDigest.toString(); 10200 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10201 } 10202 10203 // Get rid of all references to package scan path via parser. 10204 pp = null; 10205 String oldCodePath = null; 10206 boolean systemApp = false; 10207 synchronized (mPackages) { 10208 // Check whether the newly-scanned package wants to define an already-defined perm 10209 int N = pkg.permissions.size(); 10210 for (int i = 0; i < N; i++) { 10211 PackageParser.Permission perm = pkg.permissions.get(i); 10212 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10213 if (bp != null) { 10214 // If the defining package is signed with our cert, it's okay. This 10215 // also includes the "updating the same package" case, of course. 10216 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10217 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10218 Slog.w(TAG, "Package " + pkg.packageName 10219 + " attempting to redeclare permission " + perm.info.name 10220 + " already owned by " + bp.sourcePackage); 10221 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 10222 res.origPermission = perm.info.name; 10223 res.origPackage = bp.sourcePackage; 10224 return; 10225 } 10226 } 10227 } 10228 10229 // Check if installing already existing package 10230 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10231 String oldName = mSettings.mRenamedPackages.get(pkgName); 10232 if (pkg.mOriginalPackages != null 10233 && pkg.mOriginalPackages.contains(oldName) 10234 && mPackages.containsKey(oldName)) { 10235 // This package is derived from an original package, 10236 // and this device has been updating from that original 10237 // name. We must continue using the original name, so 10238 // rename the new package here. 10239 pkg.setPackageName(oldName); 10240 pkgName = pkg.packageName; 10241 replace = true; 10242 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10243 + oldName + " pkgName=" + pkgName); 10244 } else if (mPackages.containsKey(pkgName)) { 10245 // This package, under its official name, already exists 10246 // on the device; we should replace it. 10247 replace = true; 10248 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10249 } 10250 } 10251 PackageSetting ps = mSettings.mPackages.get(pkgName); 10252 if (ps != null) { 10253 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10254 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10255 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10256 systemApp = (ps.pkg.applicationInfo.flags & 10257 ApplicationInfo.FLAG_SYSTEM) != 0; 10258 } 10259 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10260 } 10261 } 10262 10263 if (systemApp && onSd) { 10264 // Disable updates to system apps on sdcard 10265 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 10266 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10267 return; 10268 } 10269 10270 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 10271 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10272 return; 10273 } 10274 // Set application objects path explicitly after the rename 10275 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath()); 10276 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 10277 if (replace) { 10278 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10279 installerPackageName, res); 10280 } else { 10281 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10282 installerPackageName, res); 10283 } 10284 synchronized (mPackages) { 10285 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10286 if (ps != null) { 10287 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10288 } 10289 } 10290 } 10291 10292 private static boolean isForwardLocked(PackageParser.Package pkg) { 10293 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10294 } 10295 10296 10297 private boolean isForwardLocked(PackageSetting ps) { 10298 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10299 } 10300 10301 private static boolean isExternal(PackageParser.Package pkg) { 10302 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10303 } 10304 10305 private static boolean isExternal(PackageSetting ps) { 10306 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10307 } 10308 10309 private static boolean isSystemApp(PackageParser.Package pkg) { 10310 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10311 } 10312 10313 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10314 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10315 } 10316 10317 private static boolean isSystemApp(ApplicationInfo info) { 10318 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10319 } 10320 10321 private static boolean isSystemApp(PackageSetting ps) { 10322 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10323 } 10324 10325 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10326 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10327 } 10328 10329 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10330 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10331 } 10332 10333 private int packageFlagsToInstallFlags(PackageSetting ps) { 10334 int installFlags = 0; 10335 if (isExternal(ps)) { 10336 installFlags |= PackageManager.INSTALL_EXTERNAL; 10337 } 10338 if (isForwardLocked(ps)) { 10339 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10340 } 10341 return installFlags; 10342 } 10343 10344 private void deleteTempPackageFiles() { 10345 final FilenameFilter filter = new FilenameFilter() { 10346 public boolean accept(File dir, String name) { 10347 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10348 } 10349 }; 10350 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 10351 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 10352 } 10353 10354 private static final void deleteTempPackageFilesInDirectory(File directory, 10355 FilenameFilter filter) { 10356 final String[] tmpFilesList = directory.list(filter); 10357 if (tmpFilesList == null) { 10358 return; 10359 } 10360 for (int i = 0; i < tmpFilesList.length; i++) { 10361 final File tmpFile = new File(directory, tmpFilesList[i]); 10362 tmpFile.delete(); 10363 } 10364 } 10365 10366 private File createTempPackageFile(File installDir) { 10367 File tmpPackageFile; 10368 try { 10369 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 10370 } catch (IOException e) { 10371 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 10372 return null; 10373 } 10374 try { 10375 FileUtils.setPermissions( 10376 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 10377 -1, -1); 10378 if (!SELinux.restorecon(tmpPackageFile)) { 10379 return null; 10380 } 10381 } catch (IOException e) { 10382 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 10383 return null; 10384 } 10385 return tmpPackageFile; 10386 } 10387 10388 @Override 10389 public void deletePackageAsUser(final String packageName, 10390 final IPackageDeleteObserver observer, 10391 final int userId, final int flags) { 10392 mContext.enforceCallingOrSelfPermission( 10393 android.Manifest.permission.DELETE_PACKAGES, null); 10394 final int uid = Binder.getCallingUid(); 10395 if (UserHandle.getUserId(uid) != userId) { 10396 mContext.enforceCallingPermission( 10397 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10398 "deletePackage for user " + userId); 10399 } 10400 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10401 try { 10402 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10403 } catch (RemoteException re) { 10404 } 10405 return; 10406 } 10407 10408 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10409 // Queue up an async operation since the package deletion may take a little while. 10410 mHandler.post(new Runnable() { 10411 public void run() { 10412 mHandler.removeCallbacks(this); 10413 final int returnCode = deletePackageX(packageName, userId, flags); 10414 if (observer != null) { 10415 try { 10416 observer.packageDeleted(packageName, returnCode); 10417 } catch (RemoteException e) { 10418 Log.i(TAG, "Observer no longer exists."); 10419 } //end catch 10420 } //end if 10421 } //end run 10422 }); 10423 } 10424 10425 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10426 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10427 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10428 try { 10429 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10430 || dpm.isDeviceOwner(packageName))) { 10431 return true; 10432 } 10433 } catch (RemoteException e) { 10434 } 10435 return false; 10436 } 10437 10438 /** 10439 * This method is an internal method that could be get invoked either 10440 * to delete an installed package or to clean up a failed installation. 10441 * After deleting an installed package, a broadcast is sent to notify any 10442 * listeners that the package has been installed. For cleaning up a failed 10443 * installation, the broadcast is not necessary since the package's 10444 * installation wouldn't have sent the initial broadcast either 10445 * The key steps in deleting a package are 10446 * deleting the package information in internal structures like mPackages, 10447 * deleting the packages base directories through installd 10448 * updating mSettings to reflect current status 10449 * persisting settings for later use 10450 * sending a broadcast if necessary 10451 */ 10452 private int deletePackageX(String packageName, int userId, int flags) { 10453 final PackageRemovedInfo info = new PackageRemovedInfo(); 10454 final boolean res; 10455 10456 if (isPackageDeviceAdmin(packageName, userId)) { 10457 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10458 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10459 } 10460 10461 boolean removedForAllUsers = false; 10462 boolean systemUpdate = false; 10463 10464 // for the uninstall-updates case and restricted profiles, remember the per- 10465 // userhandle installed state 10466 int[] allUsers; 10467 boolean[] perUserInstalled; 10468 synchronized (mPackages) { 10469 PackageSetting ps = mSettings.mPackages.get(packageName); 10470 allUsers = sUserManager.getUserIds(); 10471 perUserInstalled = new boolean[allUsers.length]; 10472 for (int i = 0; i < allUsers.length; i++) { 10473 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10474 } 10475 } 10476 10477 synchronized (mInstallLock) { 10478 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10479 res = deletePackageLI(packageName, 10480 (flags & PackageManager.DELETE_ALL_USERS) != 0 10481 ? UserHandle.ALL : new UserHandle(userId), 10482 true, allUsers, perUserInstalled, 10483 flags | REMOVE_CHATTY, info, true); 10484 systemUpdate = info.isRemovedPackageSystemUpdate; 10485 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10486 removedForAllUsers = true; 10487 } 10488 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10489 + " removedForAllUsers=" + removedForAllUsers); 10490 } 10491 10492 if (res) { 10493 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10494 10495 // If the removed package was a system update, the old system package 10496 // was re-enabled; we need to broadcast this information 10497 if (systemUpdate) { 10498 Bundle extras = new Bundle(1); 10499 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10500 ? info.removedAppId : info.uid); 10501 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10502 10503 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10504 extras, null, null, null); 10505 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10506 extras, null, null, null); 10507 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10508 null, packageName, null, null); 10509 } 10510 } 10511 // Force a gc here. 10512 Runtime.getRuntime().gc(); 10513 // Delete the resources here after sending the broadcast to let 10514 // other processes clean up before deleting resources. 10515 if (info.args != null) { 10516 synchronized (mInstallLock) { 10517 info.args.doPostDeleteLI(true); 10518 } 10519 } 10520 10521 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10522 } 10523 10524 static class PackageRemovedInfo { 10525 String removedPackage; 10526 int uid = -1; 10527 int removedAppId = -1; 10528 int[] removedUsers = null; 10529 boolean isRemovedPackageSystemUpdate = false; 10530 // Clean up resources deleted packages. 10531 InstallArgs args = null; 10532 10533 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10534 Bundle extras = new Bundle(1); 10535 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10536 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10537 if (replacing) { 10538 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10539 } 10540 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10541 if (removedPackage != null) { 10542 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10543 extras, null, null, removedUsers); 10544 if (fullRemove && !replacing) { 10545 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10546 extras, null, null, removedUsers); 10547 } 10548 } 10549 if (removedAppId >= 0) { 10550 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10551 removedUsers); 10552 } 10553 } 10554 } 10555 10556 /* 10557 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10558 * flag is not set, the data directory is removed as well. 10559 * make sure this flag is set for partially installed apps. If not its meaningless to 10560 * delete a partially installed application. 10561 */ 10562 private void removePackageDataLI(PackageSetting ps, 10563 int[] allUserHandles, boolean[] perUserInstalled, 10564 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10565 String packageName = ps.name; 10566 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10567 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10568 // Retrieve object to delete permissions for shared user later on 10569 final PackageSetting deletedPs; 10570 // reader 10571 synchronized (mPackages) { 10572 deletedPs = mSettings.mPackages.get(packageName); 10573 if (outInfo != null) { 10574 outInfo.removedPackage = packageName; 10575 outInfo.removedUsers = deletedPs != null 10576 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10577 : null; 10578 } 10579 } 10580 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10581 removeDataDirsLI(packageName); 10582 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10583 } 10584 // writer 10585 synchronized (mPackages) { 10586 if (deletedPs != null) { 10587 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10588 if (outInfo != null) { 10589 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10590 } 10591 if (deletedPs != null) { 10592 updatePermissionsLPw(deletedPs.name, null, 0); 10593 if (deletedPs.sharedUser != null) { 10594 // remove permissions associated with package 10595 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10596 } 10597 } 10598 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10599 } 10600 // make sure to preserve per-user disabled state if this removal was just 10601 // a downgrade of a system app to the factory package 10602 if (allUserHandles != null && perUserInstalled != null) { 10603 if (DEBUG_REMOVE) { 10604 Slog.d(TAG, "Propagating install state across downgrade"); 10605 } 10606 for (int i = 0; i < allUserHandles.length; i++) { 10607 if (DEBUG_REMOVE) { 10608 Slog.d(TAG, " user " + allUserHandles[i] 10609 + " => " + perUserInstalled[i]); 10610 } 10611 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10612 } 10613 } 10614 } 10615 // can downgrade to reader 10616 if (writeSettings) { 10617 // Save settings now 10618 mSettings.writeLPr(); 10619 } 10620 } 10621 if (outInfo != null) { 10622 // A user ID was deleted here. Go through all users and remove it 10623 // from KeyStore. 10624 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10625 } 10626 } 10627 10628 static boolean locationIsPrivileged(File path) { 10629 try { 10630 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10631 .getCanonicalPath(); 10632 return path.getCanonicalPath().startsWith(privilegedAppDir); 10633 } catch (IOException e) { 10634 Slog.e(TAG, "Unable to access code path " + path); 10635 } 10636 return false; 10637 } 10638 10639 /* 10640 * Tries to delete system package. 10641 */ 10642 private boolean deleteSystemPackageLI(PackageSetting newPs, 10643 int[] allUserHandles, boolean[] perUserInstalled, 10644 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10645 final boolean applyUserRestrictions 10646 = (allUserHandles != null) && (perUserInstalled != null); 10647 PackageSetting disabledPs = null; 10648 // Confirm if the system package has been updated 10649 // An updated system app can be deleted. This will also have to restore 10650 // the system pkg from system partition 10651 // reader 10652 synchronized (mPackages) { 10653 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10654 } 10655 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10656 + " disabledPs=" + disabledPs); 10657 if (disabledPs == null) { 10658 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10659 return false; 10660 } else if (DEBUG_REMOVE) { 10661 Slog.d(TAG, "Deleting system pkg from data partition"); 10662 } 10663 if (DEBUG_REMOVE) { 10664 if (applyUserRestrictions) { 10665 Slog.d(TAG, "Remembering install states:"); 10666 for (int i = 0; i < allUserHandles.length; i++) { 10667 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10668 } 10669 } 10670 } 10671 // Delete the updated package 10672 outInfo.isRemovedPackageSystemUpdate = true; 10673 if (disabledPs.versionCode < newPs.versionCode) { 10674 // Delete data for downgrades 10675 flags &= ~PackageManager.DELETE_KEEP_DATA; 10676 } else { 10677 // Preserve data by setting flag 10678 flags |= PackageManager.DELETE_KEEP_DATA; 10679 } 10680 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10681 allUserHandles, perUserInstalled, outInfo, writeSettings); 10682 if (!ret) { 10683 return false; 10684 } 10685 // writer 10686 synchronized (mPackages) { 10687 // Reinstate the old system package 10688 mSettings.enableSystemPackageLPw(newPs.name); 10689 // Remove any native libraries from the upgraded package. 10690 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 10691 } 10692 // Install the system package 10693 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10694 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10695 if (locationIsPrivileged(disabledPs.codePath)) { 10696 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10697 } 10698 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10699 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null); 10700 10701 if (newPkg == null) { 10702 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10703 + " with error:" + mLastScanError); 10704 return false; 10705 } 10706 // writer 10707 synchronized (mPackages) { 10708 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10709 setInternalAppNativeLibraryPath(newPkg, ps); 10710 updatePermissionsLPw(newPkg.packageName, newPkg, 10711 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10712 if (applyUserRestrictions) { 10713 if (DEBUG_REMOVE) { 10714 Slog.d(TAG, "Propagating install state across reinstall"); 10715 } 10716 for (int i = 0; i < allUserHandles.length; i++) { 10717 if (DEBUG_REMOVE) { 10718 Slog.d(TAG, " user " + allUserHandles[i] 10719 + " => " + perUserInstalled[i]); 10720 } 10721 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10722 } 10723 // Regardless of writeSettings we need to ensure that this restriction 10724 // state propagation is persisted 10725 mSettings.writeAllUsersPackageRestrictionsLPr(); 10726 } 10727 // can downgrade to reader here 10728 if (writeSettings) { 10729 mSettings.writeLPr(); 10730 } 10731 } 10732 return true; 10733 } 10734 10735 private boolean deleteInstalledPackageLI(PackageSetting ps, 10736 boolean deleteCodeAndResources, int flags, 10737 int[] allUserHandles, boolean[] perUserInstalled, 10738 PackageRemovedInfo outInfo, boolean writeSettings) { 10739 if (outInfo != null) { 10740 outInfo.uid = ps.appId; 10741 } 10742 10743 // Delete package data from internal structures and also remove data if flag is set 10744 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10745 10746 // Delete application code and resources 10747 if (deleteCodeAndResources && (outInfo != null)) { 10748 outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString, 10749 ps.resourcePathString, ps.nativeLibraryPathString, 10750 getAppInstructionSetFromSettings(ps)); 10751 } 10752 return true; 10753 } 10754 10755 /* 10756 * This method handles package deletion in general 10757 */ 10758 private boolean deletePackageLI(String packageName, UserHandle user, 10759 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10760 int flags, PackageRemovedInfo outInfo, 10761 boolean writeSettings) { 10762 if (packageName == null) { 10763 Slog.w(TAG, "Attempt to delete null packageName."); 10764 return false; 10765 } 10766 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10767 PackageSetting ps; 10768 boolean dataOnly = false; 10769 int removeUser = -1; 10770 int appId = -1; 10771 synchronized (mPackages) { 10772 ps = mSettings.mPackages.get(packageName); 10773 if (ps == null) { 10774 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10775 return false; 10776 } 10777 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10778 && user.getIdentifier() != UserHandle.USER_ALL) { 10779 // The caller is asking that the package only be deleted for a single 10780 // user. To do this, we just mark its uninstalled state and delete 10781 // its data. If this is a system app, we only allow this to happen if 10782 // they have set the special DELETE_SYSTEM_APP which requests different 10783 // semantics than normal for uninstalling system apps. 10784 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10785 ps.setUserState(user.getIdentifier(), 10786 COMPONENT_ENABLED_STATE_DEFAULT, 10787 false, //installed 10788 true, //stopped 10789 true, //notLaunched 10790 false, //blocked 10791 null, null, null); 10792 if (!isSystemApp(ps)) { 10793 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10794 // Other user still have this package installed, so all 10795 // we need to do is clear this user's data and save that 10796 // it is uninstalled. 10797 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10798 removeUser = user.getIdentifier(); 10799 appId = ps.appId; 10800 mSettings.writePackageRestrictionsLPr(removeUser); 10801 } else { 10802 // We need to set it back to 'installed' so the uninstall 10803 // broadcasts will be sent correctly. 10804 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10805 ps.setInstalled(true, user.getIdentifier()); 10806 } 10807 } else { 10808 // This is a system app, so we assume that the 10809 // other users still have this package installed, so all 10810 // we need to do is clear this user's data and save that 10811 // it is uninstalled. 10812 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10813 removeUser = user.getIdentifier(); 10814 appId = ps.appId; 10815 mSettings.writePackageRestrictionsLPr(removeUser); 10816 } 10817 } 10818 } 10819 10820 if (removeUser >= 0) { 10821 // From above, we determined that we are deleting this only 10822 // for a single user. Continue the work here. 10823 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10824 if (outInfo != null) { 10825 outInfo.removedPackage = packageName; 10826 outInfo.removedAppId = appId; 10827 outInfo.removedUsers = new int[] {removeUser}; 10828 } 10829 mInstaller.clearUserData(packageName, removeUser); 10830 removeKeystoreDataIfNeeded(removeUser, appId); 10831 schedulePackageCleaning(packageName, removeUser, false); 10832 return true; 10833 } 10834 10835 if (dataOnly) { 10836 // Delete application data first 10837 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10838 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10839 return true; 10840 } 10841 10842 boolean ret = false; 10843 mSettings.mKeySetManager.removeAppKeySetData(packageName); 10844 if (isSystemApp(ps)) { 10845 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10846 // When an updated system application is deleted we delete the existing resources as well and 10847 // fall back to existing code in system partition 10848 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10849 flags, outInfo, writeSettings); 10850 } else { 10851 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10852 // Kill application pre-emptively especially for apps on sd. 10853 killApplication(packageName, ps.appId, "uninstall pkg"); 10854 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10855 allUserHandles, perUserInstalled, 10856 outInfo, writeSettings); 10857 } 10858 10859 return ret; 10860 } 10861 10862 private final class ClearStorageConnection implements ServiceConnection { 10863 IMediaContainerService mContainerService; 10864 10865 @Override 10866 public void onServiceConnected(ComponentName name, IBinder service) { 10867 synchronized (this) { 10868 mContainerService = IMediaContainerService.Stub.asInterface(service); 10869 notifyAll(); 10870 } 10871 } 10872 10873 @Override 10874 public void onServiceDisconnected(ComponentName name) { 10875 } 10876 } 10877 10878 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10879 final boolean mounted; 10880 if (Environment.isExternalStorageEmulated()) { 10881 mounted = true; 10882 } else { 10883 final String status = Environment.getExternalStorageState(); 10884 10885 mounted = status.equals(Environment.MEDIA_MOUNTED) 10886 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10887 } 10888 10889 if (!mounted) { 10890 return; 10891 } 10892 10893 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10894 int[] users; 10895 if (userId == UserHandle.USER_ALL) { 10896 users = sUserManager.getUserIds(); 10897 } else { 10898 users = new int[] { userId }; 10899 } 10900 final ClearStorageConnection conn = new ClearStorageConnection(); 10901 if (mContext.bindServiceAsUser( 10902 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10903 try { 10904 for (int curUser : users) { 10905 long timeout = SystemClock.uptimeMillis() + 5000; 10906 synchronized (conn) { 10907 long now = SystemClock.uptimeMillis(); 10908 while (conn.mContainerService == null && now < timeout) { 10909 try { 10910 conn.wait(timeout - now); 10911 } catch (InterruptedException e) { 10912 } 10913 } 10914 } 10915 if (conn.mContainerService == null) { 10916 return; 10917 } 10918 10919 final UserEnvironment userEnv = new UserEnvironment(curUser); 10920 clearDirectory(conn.mContainerService, 10921 userEnv.buildExternalStorageAppCacheDirs(packageName)); 10922 if (allData) { 10923 clearDirectory(conn.mContainerService, 10924 userEnv.buildExternalStorageAppDataDirs(packageName)); 10925 clearDirectory(conn.mContainerService, 10926 userEnv.buildExternalStorageAppMediaDirs(packageName)); 10927 } 10928 } 10929 } finally { 10930 mContext.unbindService(conn); 10931 } 10932 } 10933 } 10934 10935 @Override 10936 public void clearApplicationUserData(final String packageName, 10937 final IPackageDataObserver observer, final int userId) { 10938 mContext.enforceCallingOrSelfPermission( 10939 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 10940 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 10941 // Queue up an async operation since the package deletion may take a little while. 10942 mHandler.post(new Runnable() { 10943 public void run() { 10944 mHandler.removeCallbacks(this); 10945 final boolean succeeded; 10946 synchronized (mInstallLock) { 10947 succeeded = clearApplicationUserDataLI(packageName, userId); 10948 } 10949 clearExternalStorageDataSync(packageName, userId, true); 10950 if (succeeded) { 10951 // invoke DeviceStorageMonitor's update method to clear any notifications 10952 DeviceStorageMonitorInternal 10953 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 10954 if (dsm != null) { 10955 dsm.checkMemory(); 10956 } 10957 } 10958 if(observer != null) { 10959 try { 10960 observer.onRemoveCompleted(packageName, succeeded); 10961 } catch (RemoteException e) { 10962 Log.i(TAG, "Observer no longer exists."); 10963 } 10964 } //end if observer 10965 } //end run 10966 }); 10967 } 10968 10969 private boolean clearApplicationUserDataLI(String packageName, int userId) { 10970 if (packageName == null) { 10971 Slog.w(TAG, "Attempt to delete null packageName."); 10972 return false; 10973 } 10974 PackageParser.Package p; 10975 boolean dataOnly = false; 10976 final int appId; 10977 synchronized (mPackages) { 10978 p = mPackages.get(packageName); 10979 if (p == null) { 10980 dataOnly = true; 10981 PackageSetting ps = mSettings.mPackages.get(packageName); 10982 if ((ps == null) || (ps.pkg == null)) { 10983 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10984 return false; 10985 } 10986 p = ps.pkg; 10987 } 10988 if (!dataOnly) { 10989 // need to check this only for fully installed applications 10990 if (p == null) { 10991 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10992 return false; 10993 } 10994 final ApplicationInfo applicationInfo = p.applicationInfo; 10995 if (applicationInfo == null) { 10996 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10997 return false; 10998 } 10999 } 11000 if (p != null && p.applicationInfo != null) { 11001 appId = p.applicationInfo.uid; 11002 } else { 11003 appId = -1; 11004 } 11005 } 11006 int retCode = mInstaller.clearUserData(packageName, userId); 11007 if (retCode < 0) { 11008 Slog.w(TAG, "Couldn't remove cache files for package: " 11009 + packageName); 11010 return false; 11011 } 11012 removeKeystoreDataIfNeeded(userId, appId); 11013 return true; 11014 } 11015 11016 /** 11017 * Remove entries from the keystore daemon. Will only remove it if the 11018 * {@code appId} is valid. 11019 */ 11020 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11021 if (appId < 0) { 11022 return; 11023 } 11024 11025 final KeyStore keyStore = KeyStore.getInstance(); 11026 if (keyStore != null) { 11027 if (userId == UserHandle.USER_ALL) { 11028 for (final int individual : sUserManager.getUserIds()) { 11029 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11030 } 11031 } else { 11032 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11033 } 11034 } else { 11035 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11036 } 11037 } 11038 11039 @Override 11040 public void deleteApplicationCacheFiles(final String packageName, 11041 final IPackageDataObserver observer) { 11042 mContext.enforceCallingOrSelfPermission( 11043 android.Manifest.permission.DELETE_CACHE_FILES, null); 11044 // Queue up an async operation since the package deletion may take a little while. 11045 final int userId = UserHandle.getCallingUserId(); 11046 mHandler.post(new Runnable() { 11047 public void run() { 11048 mHandler.removeCallbacks(this); 11049 final boolean succeded; 11050 synchronized (mInstallLock) { 11051 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11052 } 11053 clearExternalStorageDataSync(packageName, userId, false); 11054 if(observer != null) { 11055 try { 11056 observer.onRemoveCompleted(packageName, succeded); 11057 } catch (RemoteException e) { 11058 Log.i(TAG, "Observer no longer exists."); 11059 } 11060 } //end if observer 11061 } //end run 11062 }); 11063 } 11064 11065 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11066 if (packageName == null) { 11067 Slog.w(TAG, "Attempt to delete null packageName."); 11068 return false; 11069 } 11070 PackageParser.Package p; 11071 synchronized (mPackages) { 11072 p = mPackages.get(packageName); 11073 } 11074 if (p == null) { 11075 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11076 return false; 11077 } 11078 final ApplicationInfo applicationInfo = p.applicationInfo; 11079 if (applicationInfo == null) { 11080 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11081 return false; 11082 } 11083 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11084 if (retCode < 0) { 11085 Slog.w(TAG, "Couldn't remove cache files for package: " 11086 + packageName + " u" + userId); 11087 return false; 11088 } 11089 return true; 11090 } 11091 11092 @Override 11093 public void getPackageSizeInfo(final String packageName, int userHandle, 11094 final IPackageStatsObserver observer) { 11095 mContext.enforceCallingOrSelfPermission( 11096 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11097 if (packageName == null) { 11098 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11099 } 11100 11101 PackageStats stats = new PackageStats(packageName, userHandle); 11102 11103 /* 11104 * Queue up an async operation since the package measurement may take a 11105 * little while. 11106 */ 11107 Message msg = mHandler.obtainMessage(INIT_COPY); 11108 msg.obj = new MeasureParams(stats, observer); 11109 mHandler.sendMessage(msg); 11110 } 11111 11112 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11113 PackageStats pStats) { 11114 if (packageName == null) { 11115 Slog.w(TAG, "Attempt to get size of null packageName."); 11116 return false; 11117 } 11118 PackageParser.Package p; 11119 boolean dataOnly = false; 11120 String libDirPath = null; 11121 String asecPath = null; 11122 PackageSetting ps = null; 11123 synchronized (mPackages) { 11124 p = mPackages.get(packageName); 11125 ps = mSettings.mPackages.get(packageName); 11126 if(p == null) { 11127 dataOnly = true; 11128 if((ps == null) || (ps.pkg == null)) { 11129 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11130 return false; 11131 } 11132 p = ps.pkg; 11133 } 11134 if (ps != null) { 11135 libDirPath = ps.nativeLibraryPathString; 11136 } 11137 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11138 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 11139 if (secureContainerId != null) { 11140 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11141 } 11142 } 11143 } 11144 String publicSrcDir = null; 11145 if(!dataOnly) { 11146 final ApplicationInfo applicationInfo = p.applicationInfo; 11147 if (applicationInfo == null) { 11148 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11149 return false; 11150 } 11151 if (isForwardLocked(p)) { 11152 publicSrcDir = applicationInfo.publicSourceDir; 11153 } 11154 } 11155 int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath, 11156 publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps), 11157 pStats); 11158 if (res < 0) { 11159 return false; 11160 } 11161 11162 // Fix-up for forward-locked applications in ASEC containers. 11163 if (!isExternal(p)) { 11164 pStats.codeSize += pStats.externalCodeSize; 11165 pStats.externalCodeSize = 0L; 11166 } 11167 11168 return true; 11169 } 11170 11171 11172 @Override 11173 public void addPackageToPreferred(String packageName) { 11174 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11175 } 11176 11177 @Override 11178 public void removePackageFromPreferred(String packageName) { 11179 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11180 } 11181 11182 @Override 11183 public List<PackageInfo> getPreferredPackages(int flags) { 11184 return new ArrayList<PackageInfo>(); 11185 } 11186 11187 private int getUidTargetSdkVersionLockedLPr(int uid) { 11188 Object obj = mSettings.getUserIdLPr(uid); 11189 if (obj instanceof SharedUserSetting) { 11190 final SharedUserSetting sus = (SharedUserSetting) obj; 11191 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11192 final Iterator<PackageSetting> it = sus.packages.iterator(); 11193 while (it.hasNext()) { 11194 final PackageSetting ps = it.next(); 11195 if (ps.pkg != null) { 11196 int v = ps.pkg.applicationInfo.targetSdkVersion; 11197 if (v < vers) vers = v; 11198 } 11199 } 11200 return vers; 11201 } else if (obj instanceof PackageSetting) { 11202 final PackageSetting ps = (PackageSetting) obj; 11203 if (ps.pkg != null) { 11204 return ps.pkg.applicationInfo.targetSdkVersion; 11205 } 11206 } 11207 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11208 } 11209 11210 @Override 11211 public void addPreferredActivity(IntentFilter filter, int match, 11212 ComponentName[] set, ComponentName activity, int userId) { 11213 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11214 } 11215 11216 private void addPreferredActivityInternal(IntentFilter filter, int match, 11217 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11218 // writer 11219 int callingUid = Binder.getCallingUid(); 11220 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11221 if (filter.countActions() == 0) { 11222 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11223 return; 11224 } 11225 synchronized (mPackages) { 11226 if (mContext.checkCallingOrSelfPermission( 11227 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11228 != PackageManager.PERMISSION_GRANTED) { 11229 if (getUidTargetSdkVersionLockedLPr(callingUid) 11230 < Build.VERSION_CODES.FROYO) { 11231 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11232 + callingUid); 11233 return; 11234 } 11235 mContext.enforceCallingOrSelfPermission( 11236 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11237 } 11238 11239 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11240 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11241 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11242 new PreferredActivity(filter, match, set, activity, always)); 11243 mSettings.writePackageRestrictionsLPr(userId); 11244 } 11245 } 11246 11247 @Override 11248 public void replacePreferredActivity(IntentFilter filter, int match, 11249 ComponentName[] set, ComponentName activity) { 11250 if (filter.countActions() != 1) { 11251 throw new IllegalArgumentException( 11252 "replacePreferredActivity expects filter to have only 1 action."); 11253 } 11254 if (filter.countDataAuthorities() != 0 11255 || filter.countDataPaths() != 0 11256 || filter.countDataSchemes() > 1 11257 || filter.countDataTypes() != 0) { 11258 throw new IllegalArgumentException( 11259 "replacePreferredActivity expects filter to have no data authorities, " + 11260 "paths, or types; and at most one scheme."); 11261 } 11262 synchronized (mPackages) { 11263 if (mContext.checkCallingOrSelfPermission( 11264 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11265 != PackageManager.PERMISSION_GRANTED) { 11266 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11267 < Build.VERSION_CODES.FROYO) { 11268 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11269 + Binder.getCallingUid()); 11270 return; 11271 } 11272 mContext.enforceCallingOrSelfPermission( 11273 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11274 } 11275 11276 final int callingUserId = UserHandle.getCallingUserId(); 11277 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11278 if (pir != null) { 11279 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11280 if (filter.countDataSchemes() == 1) { 11281 Uri.Builder builder = new Uri.Builder(); 11282 builder.scheme(filter.getDataScheme(0)); 11283 intent.setData(builder.build()); 11284 } 11285 List<PreferredActivity> matches = pir.queryIntent( 11286 intent, null, true, callingUserId); 11287 if (DEBUG_PREFERRED) { 11288 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11289 } 11290 for (int i = 0; i < matches.size(); i++) { 11291 PreferredActivity pa = matches.get(i); 11292 if (DEBUG_PREFERRED) { 11293 Slog.i(TAG, "Removing preferred activity " 11294 + pa.mPref.mComponent + ":"); 11295 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11296 } 11297 pir.removeFilter(pa); 11298 } 11299 } 11300 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11301 } 11302 } 11303 11304 @Override 11305 public void clearPackagePreferredActivities(String packageName) { 11306 final int uid = Binder.getCallingUid(); 11307 // writer 11308 synchronized (mPackages) { 11309 PackageParser.Package pkg = mPackages.get(packageName); 11310 if (pkg == null || pkg.applicationInfo.uid != uid) { 11311 if (mContext.checkCallingOrSelfPermission( 11312 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11313 != PackageManager.PERMISSION_GRANTED) { 11314 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11315 < Build.VERSION_CODES.FROYO) { 11316 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11317 + Binder.getCallingUid()); 11318 return; 11319 } 11320 mContext.enforceCallingOrSelfPermission( 11321 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11322 } 11323 } 11324 11325 int user = UserHandle.getCallingUserId(); 11326 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11327 mSettings.writePackageRestrictionsLPr(user); 11328 scheduleWriteSettingsLocked(); 11329 } 11330 } 11331 } 11332 11333 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11334 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11335 ArrayList<PreferredActivity> removed = null; 11336 boolean changed = false; 11337 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11338 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11339 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11340 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11341 continue; 11342 } 11343 Iterator<PreferredActivity> it = pir.filterIterator(); 11344 while (it.hasNext()) { 11345 PreferredActivity pa = it.next(); 11346 // Mark entry for removal only if it matches the package name 11347 // and the entry is of type "always". 11348 if (packageName == null || 11349 (pa.mPref.mComponent.getPackageName().equals(packageName) 11350 && pa.mPref.mAlways)) { 11351 if (removed == null) { 11352 removed = new ArrayList<PreferredActivity>(); 11353 } 11354 removed.add(pa); 11355 } 11356 } 11357 if (removed != null) { 11358 for (int j=0; j<removed.size(); j++) { 11359 PreferredActivity pa = removed.get(j); 11360 pir.removeFilter(pa); 11361 } 11362 changed = true; 11363 } 11364 } 11365 return changed; 11366 } 11367 11368 @Override 11369 public void resetPreferredActivities(int userId) { 11370 mContext.enforceCallingOrSelfPermission( 11371 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11372 // writer 11373 synchronized (mPackages) { 11374 int user = UserHandle.getCallingUserId(); 11375 clearPackagePreferredActivitiesLPw(null, user); 11376 mSettings.readDefaultPreferredAppsLPw(this, user); 11377 mSettings.writePackageRestrictionsLPr(user); 11378 scheduleWriteSettingsLocked(); 11379 } 11380 } 11381 11382 @Override 11383 public int getPreferredActivities(List<IntentFilter> outFilters, 11384 List<ComponentName> outActivities, String packageName) { 11385 11386 int num = 0; 11387 final int userId = UserHandle.getCallingUserId(); 11388 // reader 11389 synchronized (mPackages) { 11390 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11391 if (pir != null) { 11392 final Iterator<PreferredActivity> it = pir.filterIterator(); 11393 while (it.hasNext()) { 11394 final PreferredActivity pa = it.next(); 11395 if (packageName == null 11396 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11397 && pa.mPref.mAlways)) { 11398 if (outFilters != null) { 11399 outFilters.add(new IntentFilter(pa)); 11400 } 11401 if (outActivities != null) { 11402 outActivities.add(pa.mPref.mComponent); 11403 } 11404 } 11405 } 11406 } 11407 } 11408 11409 return num; 11410 } 11411 11412 @Override 11413 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11414 int userId) { 11415 int callingUid = Binder.getCallingUid(); 11416 if (callingUid != Process.SYSTEM_UID) { 11417 throw new SecurityException( 11418 "addPersistentPreferredActivity can only be run by the system"); 11419 } 11420 if (filter.countActions() == 0) { 11421 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11422 return; 11423 } 11424 synchronized (mPackages) { 11425 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11426 " :"); 11427 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11428 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11429 new PersistentPreferredActivity(filter, activity)); 11430 mSettings.writePackageRestrictionsLPr(userId); 11431 } 11432 } 11433 11434 @Override 11435 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11436 int callingUid = Binder.getCallingUid(); 11437 if (callingUid != Process.SYSTEM_UID) { 11438 throw new SecurityException( 11439 "clearPackagePersistentPreferredActivities can only be run by the system"); 11440 } 11441 ArrayList<PersistentPreferredActivity> removed = null; 11442 boolean changed = false; 11443 synchronized (mPackages) { 11444 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11445 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11446 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11447 .valueAt(i); 11448 if (userId != thisUserId) { 11449 continue; 11450 } 11451 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11452 while (it.hasNext()) { 11453 PersistentPreferredActivity ppa = it.next(); 11454 // Mark entry for removal only if it matches the package name. 11455 if (ppa.mComponent.getPackageName().equals(packageName)) { 11456 if (removed == null) { 11457 removed = new ArrayList<PersistentPreferredActivity>(); 11458 } 11459 removed.add(ppa); 11460 } 11461 } 11462 if (removed != null) { 11463 for (int j=0; j<removed.size(); j++) { 11464 PersistentPreferredActivity ppa = removed.get(j); 11465 ppir.removeFilter(ppa); 11466 } 11467 changed = true; 11468 } 11469 } 11470 11471 if (changed) { 11472 mSettings.writePackageRestrictionsLPr(userId); 11473 } 11474 } 11475 } 11476 11477 @Override 11478 public void addForwardingIntentFilter(IntentFilter filter, boolean removable, int userIdOrig, 11479 int userIdDest) { 11480 mContext.enforceCallingOrSelfPermission( 11481 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11482 if (filter.countActions() == 0) { 11483 Slog.w(TAG, "Cannot set a forwarding intent filter with no filter actions"); 11484 return; 11485 } 11486 synchronized (mPackages) { 11487 mSettings.editForwardingIntentResolverLPw(userIdOrig).addFilter( 11488 new ForwardingIntentFilter(filter, removable, userIdDest)); 11489 mSettings.writePackageRestrictionsLPr(userIdOrig); 11490 } 11491 } 11492 11493 @Override 11494 public void clearForwardingIntentFilters(int userIdOrig) { 11495 mContext.enforceCallingOrSelfPermission( 11496 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11497 synchronized (mPackages) { 11498 ForwardingIntentResolver fir = mSettings.editForwardingIntentResolverLPw(userIdOrig); 11499 HashSet<ForwardingIntentFilter> set = 11500 new HashSet<ForwardingIntentFilter>(fir.filterSet()); 11501 for (ForwardingIntentFilter fif : set) { 11502 if (fif.isRemovable()) fir.removeFilter(fif); 11503 } 11504 mSettings.writePackageRestrictionsLPr(userIdOrig); 11505 } 11506 } 11507 11508 @Override 11509 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11510 Intent intent = new Intent(Intent.ACTION_MAIN); 11511 intent.addCategory(Intent.CATEGORY_HOME); 11512 11513 final int callingUserId = UserHandle.getCallingUserId(); 11514 List<ResolveInfo> list = queryIntentActivities(intent, null, 11515 PackageManager.GET_META_DATA, callingUserId); 11516 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11517 true, false, false, callingUserId); 11518 11519 allHomeCandidates.clear(); 11520 if (list != null) { 11521 for (ResolveInfo ri : list) { 11522 allHomeCandidates.add(ri); 11523 } 11524 } 11525 return (preferred == null || preferred.activityInfo == null) 11526 ? null 11527 : new ComponentName(preferred.activityInfo.packageName, 11528 preferred.activityInfo.name); 11529 } 11530 11531 @Override 11532 public void setApplicationEnabledSetting(String appPackageName, 11533 int newState, int flags, int userId, String callingPackage) { 11534 if (!sUserManager.exists(userId)) return; 11535 if (callingPackage == null) { 11536 callingPackage = Integer.toString(Binder.getCallingUid()); 11537 } 11538 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11539 } 11540 11541 @Override 11542 public void setComponentEnabledSetting(ComponentName componentName, 11543 int newState, int flags, int userId) { 11544 if (!sUserManager.exists(userId)) return; 11545 setEnabledSetting(componentName.getPackageName(), 11546 componentName.getClassName(), newState, flags, userId, null); 11547 } 11548 11549 private void setEnabledSetting(final String packageName, String className, int newState, 11550 final int flags, int userId, String callingPackage) { 11551 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11552 || newState == COMPONENT_ENABLED_STATE_ENABLED 11553 || newState == COMPONENT_ENABLED_STATE_DISABLED 11554 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11555 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11556 throw new IllegalArgumentException("Invalid new component state: " 11557 + newState); 11558 } 11559 PackageSetting pkgSetting; 11560 final int uid = Binder.getCallingUid(); 11561 final int permission = mContext.checkCallingOrSelfPermission( 11562 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11563 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11564 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11565 boolean sendNow = false; 11566 boolean isApp = (className == null); 11567 String componentName = isApp ? packageName : className; 11568 int packageUid = -1; 11569 ArrayList<String> components; 11570 11571 // writer 11572 synchronized (mPackages) { 11573 pkgSetting = mSettings.mPackages.get(packageName); 11574 if (pkgSetting == null) { 11575 if (className == null) { 11576 throw new IllegalArgumentException( 11577 "Unknown package: " + packageName); 11578 } 11579 throw new IllegalArgumentException( 11580 "Unknown component: " + packageName 11581 + "/" + className); 11582 } 11583 // Allow root and verify that userId is not being specified by a different user 11584 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11585 throw new SecurityException( 11586 "Permission Denial: attempt to change component state from pid=" 11587 + Binder.getCallingPid() 11588 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11589 } 11590 if (className == null) { 11591 // We're dealing with an application/package level state change 11592 if (pkgSetting.getEnabled(userId) == newState) { 11593 // Nothing to do 11594 return; 11595 } 11596 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11597 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11598 // Don't care about who enables an app. 11599 callingPackage = null; 11600 } 11601 pkgSetting.setEnabled(newState, userId, callingPackage); 11602 // pkgSetting.pkg.mSetEnabled = newState; 11603 } else { 11604 // We're dealing with a component level state change 11605 // First, verify that this is a valid class name. 11606 PackageParser.Package pkg = pkgSetting.pkg; 11607 if (pkg == null || !pkg.hasComponentClassName(className)) { 11608 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11609 throw new IllegalArgumentException("Component class " + className 11610 + " does not exist in " + packageName); 11611 } else { 11612 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11613 + className + " does not exist in " + packageName); 11614 } 11615 } 11616 switch (newState) { 11617 case COMPONENT_ENABLED_STATE_ENABLED: 11618 if (!pkgSetting.enableComponentLPw(className, userId)) { 11619 return; 11620 } 11621 break; 11622 case COMPONENT_ENABLED_STATE_DISABLED: 11623 if (!pkgSetting.disableComponentLPw(className, userId)) { 11624 return; 11625 } 11626 break; 11627 case COMPONENT_ENABLED_STATE_DEFAULT: 11628 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11629 return; 11630 } 11631 break; 11632 default: 11633 Slog.e(TAG, "Invalid new component state: " + newState); 11634 return; 11635 } 11636 } 11637 mSettings.writePackageRestrictionsLPr(userId); 11638 components = mPendingBroadcasts.get(userId, packageName); 11639 final boolean newPackage = components == null; 11640 if (newPackage) { 11641 components = new ArrayList<String>(); 11642 } 11643 if (!components.contains(componentName)) { 11644 components.add(componentName); 11645 } 11646 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11647 sendNow = true; 11648 // Purge entry from pending broadcast list if another one exists already 11649 // since we are sending one right away. 11650 mPendingBroadcasts.remove(userId, packageName); 11651 } else { 11652 if (newPackage) { 11653 mPendingBroadcasts.put(userId, packageName, components); 11654 } 11655 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11656 // Schedule a message 11657 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11658 } 11659 } 11660 } 11661 11662 long callingId = Binder.clearCallingIdentity(); 11663 try { 11664 if (sendNow) { 11665 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11666 sendPackageChangedBroadcast(packageName, 11667 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11668 } 11669 } finally { 11670 Binder.restoreCallingIdentity(callingId); 11671 } 11672 } 11673 11674 private void sendPackageChangedBroadcast(String packageName, 11675 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11676 if (DEBUG_INSTALL) 11677 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11678 + componentNames); 11679 Bundle extras = new Bundle(4); 11680 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11681 String nameList[] = new String[componentNames.size()]; 11682 componentNames.toArray(nameList); 11683 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11684 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11685 extras.putInt(Intent.EXTRA_UID, packageUid); 11686 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11687 new int[] {UserHandle.getUserId(packageUid)}); 11688 } 11689 11690 @Override 11691 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11692 if (!sUserManager.exists(userId)) return; 11693 final int uid = Binder.getCallingUid(); 11694 final int permission = mContext.checkCallingOrSelfPermission( 11695 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11696 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11697 enforceCrossUserPermission(uid, userId, true, "stop package"); 11698 // writer 11699 synchronized (mPackages) { 11700 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11701 uid, userId)) { 11702 scheduleWritePackageRestrictionsLocked(userId); 11703 } 11704 } 11705 } 11706 11707 @Override 11708 public String getInstallerPackageName(String packageName) { 11709 // reader 11710 synchronized (mPackages) { 11711 return mSettings.getInstallerPackageNameLPr(packageName); 11712 } 11713 } 11714 11715 @Override 11716 public int getApplicationEnabledSetting(String packageName, int userId) { 11717 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11718 int uid = Binder.getCallingUid(); 11719 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11720 // reader 11721 synchronized (mPackages) { 11722 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11723 } 11724 } 11725 11726 @Override 11727 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11728 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11729 int uid = Binder.getCallingUid(); 11730 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11731 // reader 11732 synchronized (mPackages) { 11733 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11734 } 11735 } 11736 11737 @Override 11738 public void enterSafeMode() { 11739 enforceSystemOrRoot("Only the system can request entering safe mode"); 11740 11741 if (!mSystemReady) { 11742 mSafeMode = true; 11743 } 11744 } 11745 11746 @Override 11747 public void systemReady() { 11748 mSystemReady = true; 11749 11750 // Read the compatibilty setting when the system is ready. 11751 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11752 mContext.getContentResolver(), 11753 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11754 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11755 if (DEBUG_SETTINGS) { 11756 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11757 } 11758 11759 synchronized (mPackages) { 11760 // Verify that all of the preferred activity components actually 11761 // exist. It is possible for applications to be updated and at 11762 // that point remove a previously declared activity component that 11763 // had been set as a preferred activity. We try to clean this up 11764 // the next time we encounter that preferred activity, but it is 11765 // possible for the user flow to never be able to return to that 11766 // situation so here we do a sanity check to make sure we haven't 11767 // left any junk around. 11768 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11769 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11770 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11771 removed.clear(); 11772 for (PreferredActivity pa : pir.filterSet()) { 11773 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11774 removed.add(pa); 11775 } 11776 } 11777 if (removed.size() > 0) { 11778 for (int j=0; j<removed.size(); j++) { 11779 PreferredActivity pa = removed.get(i); 11780 Slog.w(TAG, "Removing dangling preferred activity: " 11781 + pa.mPref.mComponent); 11782 pir.removeFilter(pa); 11783 } 11784 mSettings.writePackageRestrictionsLPr( 11785 mSettings.mPreferredActivities.keyAt(i)); 11786 } 11787 } 11788 } 11789 sUserManager.systemReady(); 11790 } 11791 11792 @Override 11793 public boolean isSafeMode() { 11794 return mSafeMode; 11795 } 11796 11797 @Override 11798 public boolean hasSystemUidErrors() { 11799 return mHasSystemUidErrors; 11800 } 11801 11802 static String arrayToString(int[] array) { 11803 StringBuffer buf = new StringBuffer(128); 11804 buf.append('['); 11805 if (array != null) { 11806 for (int i=0; i<array.length; i++) { 11807 if (i > 0) buf.append(", "); 11808 buf.append(array[i]); 11809 } 11810 } 11811 buf.append(']'); 11812 return buf.toString(); 11813 } 11814 11815 static class DumpState { 11816 public static final int DUMP_LIBS = 1 << 0; 11817 11818 public static final int DUMP_FEATURES = 1 << 1; 11819 11820 public static final int DUMP_RESOLVERS = 1 << 2; 11821 11822 public static final int DUMP_PERMISSIONS = 1 << 3; 11823 11824 public static final int DUMP_PACKAGES = 1 << 4; 11825 11826 public static final int DUMP_SHARED_USERS = 1 << 5; 11827 11828 public static final int DUMP_MESSAGES = 1 << 6; 11829 11830 public static final int DUMP_PROVIDERS = 1 << 7; 11831 11832 public static final int DUMP_VERIFIERS = 1 << 8; 11833 11834 public static final int DUMP_PREFERRED = 1 << 9; 11835 11836 public static final int DUMP_PREFERRED_XML = 1 << 10; 11837 11838 public static final int DUMP_KEYSETS = 1 << 11; 11839 11840 public static final int DUMP_VERSION = 1 << 12; 11841 11842 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11843 11844 private int mTypes; 11845 11846 private int mOptions; 11847 11848 private boolean mTitlePrinted; 11849 11850 private SharedUserSetting mSharedUser; 11851 11852 public boolean isDumping(int type) { 11853 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11854 return true; 11855 } 11856 11857 return (mTypes & type) != 0; 11858 } 11859 11860 public void setDump(int type) { 11861 mTypes |= type; 11862 } 11863 11864 public boolean isOptionEnabled(int option) { 11865 return (mOptions & option) != 0; 11866 } 11867 11868 public void setOptionEnabled(int option) { 11869 mOptions |= option; 11870 } 11871 11872 public boolean onTitlePrinted() { 11873 final boolean printed = mTitlePrinted; 11874 mTitlePrinted = true; 11875 return printed; 11876 } 11877 11878 public boolean getTitlePrinted() { 11879 return mTitlePrinted; 11880 } 11881 11882 public void setTitlePrinted(boolean enabled) { 11883 mTitlePrinted = enabled; 11884 } 11885 11886 public SharedUserSetting getSharedUser() { 11887 return mSharedUser; 11888 } 11889 11890 public void setSharedUser(SharedUserSetting user) { 11891 mSharedUser = user; 11892 } 11893 } 11894 11895 @Override 11896 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 11897 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 11898 != PackageManager.PERMISSION_GRANTED) { 11899 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 11900 + Binder.getCallingPid() 11901 + ", uid=" + Binder.getCallingUid() 11902 + " without permission " 11903 + android.Manifest.permission.DUMP); 11904 return; 11905 } 11906 11907 DumpState dumpState = new DumpState(); 11908 boolean fullPreferred = false; 11909 boolean checkin = false; 11910 11911 String packageName = null; 11912 11913 int opti = 0; 11914 while (opti < args.length) { 11915 String opt = args[opti]; 11916 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 11917 break; 11918 } 11919 opti++; 11920 if ("-a".equals(opt)) { 11921 // Right now we only know how to print all. 11922 } else if ("-h".equals(opt)) { 11923 pw.println("Package manager dump options:"); 11924 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 11925 pw.println(" --checkin: dump for a checkin"); 11926 pw.println(" -f: print details of intent filters"); 11927 pw.println(" -h: print this help"); 11928 pw.println(" cmd may be one of:"); 11929 pw.println(" l[ibraries]: list known shared libraries"); 11930 pw.println(" f[ibraries]: list device features"); 11931 pw.println(" k[eysets]: print known keysets"); 11932 pw.println(" r[esolvers]: dump intent resolvers"); 11933 pw.println(" perm[issions]: dump permissions"); 11934 pw.println(" pref[erred]: print preferred package settings"); 11935 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 11936 pw.println(" prov[iders]: dump content providers"); 11937 pw.println(" p[ackages]: dump installed packages"); 11938 pw.println(" s[hared-users]: dump shared user IDs"); 11939 pw.println(" m[essages]: print collected runtime messages"); 11940 pw.println(" v[erifiers]: print package verifier info"); 11941 pw.println(" version: print database version info"); 11942 pw.println(" write: write current settings now"); 11943 pw.println(" <package.name>: info about given package"); 11944 return; 11945 } else if ("--checkin".equals(opt)) { 11946 checkin = true; 11947 } else if ("-f".equals(opt)) { 11948 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11949 } else { 11950 pw.println("Unknown argument: " + opt + "; use -h for help"); 11951 } 11952 } 11953 11954 // Is the caller requesting to dump a particular piece of data? 11955 if (opti < args.length) { 11956 String cmd = args[opti]; 11957 opti++; 11958 // Is this a package name? 11959 if ("android".equals(cmd) || cmd.contains(".")) { 11960 packageName = cmd; 11961 // When dumping a single package, we always dump all of its 11962 // filter information since the amount of data will be reasonable. 11963 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11964 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 11965 dumpState.setDump(DumpState.DUMP_LIBS); 11966 } else if ("f".equals(cmd) || "features".equals(cmd)) { 11967 dumpState.setDump(DumpState.DUMP_FEATURES); 11968 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 11969 dumpState.setDump(DumpState.DUMP_RESOLVERS); 11970 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 11971 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 11972 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 11973 dumpState.setDump(DumpState.DUMP_PREFERRED); 11974 } else if ("preferred-xml".equals(cmd)) { 11975 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 11976 if (opti < args.length && "--full".equals(args[opti])) { 11977 fullPreferred = true; 11978 opti++; 11979 } 11980 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 11981 dumpState.setDump(DumpState.DUMP_PACKAGES); 11982 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 11983 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 11984 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 11985 dumpState.setDump(DumpState.DUMP_PROVIDERS); 11986 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 11987 dumpState.setDump(DumpState.DUMP_MESSAGES); 11988 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 11989 dumpState.setDump(DumpState.DUMP_VERIFIERS); 11990 } else if ("version".equals(cmd)) { 11991 dumpState.setDump(DumpState.DUMP_VERSION); 11992 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 11993 dumpState.setDump(DumpState.DUMP_KEYSETS); 11994 } else if ("write".equals(cmd)) { 11995 synchronized (mPackages) { 11996 mSettings.writeLPr(); 11997 pw.println("Settings written."); 11998 return; 11999 } 12000 } 12001 } 12002 12003 if (checkin) { 12004 pw.println("vers,1"); 12005 } 12006 12007 // reader 12008 synchronized (mPackages) { 12009 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12010 if (!checkin) { 12011 if (dumpState.onTitlePrinted()) 12012 pw.println(); 12013 pw.println("Database versions:"); 12014 pw.print(" SDK Version:"); 12015 pw.print(" internal="); 12016 pw.print(mSettings.mInternalSdkPlatform); 12017 pw.print(" external="); 12018 pw.println(mSettings.mExternalSdkPlatform); 12019 pw.print(" DB Version:"); 12020 pw.print(" internal="); 12021 pw.print(mSettings.mInternalDatabaseVersion); 12022 pw.print(" external="); 12023 pw.println(mSettings.mExternalDatabaseVersion); 12024 } 12025 } 12026 12027 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12028 if (!checkin) { 12029 if (dumpState.onTitlePrinted()) 12030 pw.println(); 12031 pw.println("Verifiers:"); 12032 pw.print(" Required: "); 12033 pw.print(mRequiredVerifierPackage); 12034 pw.print(" (uid="); 12035 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12036 pw.println(")"); 12037 } else if (mRequiredVerifierPackage != null) { 12038 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12039 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12040 } 12041 } 12042 12043 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12044 boolean printedHeader = false; 12045 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12046 while (it.hasNext()) { 12047 String name = it.next(); 12048 SharedLibraryEntry ent = mSharedLibraries.get(name); 12049 if (!checkin) { 12050 if (!printedHeader) { 12051 if (dumpState.onTitlePrinted()) 12052 pw.println(); 12053 pw.println("Libraries:"); 12054 printedHeader = true; 12055 } 12056 pw.print(" "); 12057 } else { 12058 pw.print("lib,"); 12059 } 12060 pw.print(name); 12061 if (!checkin) { 12062 pw.print(" -> "); 12063 } 12064 if (ent.path != null) { 12065 if (!checkin) { 12066 pw.print("(jar) "); 12067 pw.print(ent.path); 12068 } else { 12069 pw.print(",jar,"); 12070 pw.print(ent.path); 12071 } 12072 } else { 12073 if (!checkin) { 12074 pw.print("(apk) "); 12075 pw.print(ent.apk); 12076 } else { 12077 pw.print(",apk,"); 12078 pw.print(ent.apk); 12079 } 12080 } 12081 pw.println(); 12082 } 12083 } 12084 12085 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12086 if (dumpState.onTitlePrinted()) 12087 pw.println(); 12088 if (!checkin) { 12089 pw.println("Features:"); 12090 } 12091 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12092 while (it.hasNext()) { 12093 String name = it.next(); 12094 if (!checkin) { 12095 pw.print(" "); 12096 } else { 12097 pw.print("feat,"); 12098 } 12099 pw.println(name); 12100 } 12101 } 12102 12103 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12104 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12105 : "Activity Resolver Table:", " ", packageName, 12106 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12107 dumpState.setTitlePrinted(true); 12108 } 12109 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12110 : "Receiver Resolver Table:", " ", packageName, 12111 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12112 dumpState.setTitlePrinted(true); 12113 } 12114 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12115 : "Service Resolver Table:", " ", packageName, 12116 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12117 dumpState.setTitlePrinted(true); 12118 } 12119 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12120 : "Provider Resolver Table:", " ", packageName, 12121 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12122 dumpState.setTitlePrinted(true); 12123 } 12124 } 12125 12126 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12127 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12128 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12129 int user = mSettings.mPreferredActivities.keyAt(i); 12130 if (pir.dump(pw, 12131 dumpState.getTitlePrinted() 12132 ? "\nPreferred Activities User " + user + ":" 12133 : "Preferred Activities User " + user + ":", " ", 12134 packageName, true)) { 12135 dumpState.setTitlePrinted(true); 12136 } 12137 } 12138 } 12139 12140 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12141 pw.flush(); 12142 FileOutputStream fout = new FileOutputStream(fd); 12143 BufferedOutputStream str = new BufferedOutputStream(fout); 12144 XmlSerializer serializer = new FastXmlSerializer(); 12145 try { 12146 serializer.setOutput(str, "utf-8"); 12147 serializer.startDocument(null, true); 12148 serializer.setFeature( 12149 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12150 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12151 serializer.endDocument(); 12152 serializer.flush(); 12153 } catch (IllegalArgumentException e) { 12154 pw.println("Failed writing: " + e); 12155 } catch (IllegalStateException e) { 12156 pw.println("Failed writing: " + e); 12157 } catch (IOException e) { 12158 pw.println("Failed writing: " + e); 12159 } 12160 } 12161 12162 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12163 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12164 } 12165 12166 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12167 boolean printedSomething = false; 12168 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12169 if (packageName != null && !packageName.equals(p.info.packageName)) { 12170 continue; 12171 } 12172 if (!printedSomething) { 12173 if (dumpState.onTitlePrinted()) 12174 pw.println(); 12175 pw.println("Registered ContentProviders:"); 12176 printedSomething = true; 12177 } 12178 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12179 pw.print(" "); pw.println(p.toString()); 12180 } 12181 printedSomething = false; 12182 for (Map.Entry<String, PackageParser.Provider> entry : 12183 mProvidersByAuthority.entrySet()) { 12184 PackageParser.Provider p = entry.getValue(); 12185 if (packageName != null && !packageName.equals(p.info.packageName)) { 12186 continue; 12187 } 12188 if (!printedSomething) { 12189 if (dumpState.onTitlePrinted()) 12190 pw.println(); 12191 pw.println("ContentProvider Authorities:"); 12192 printedSomething = true; 12193 } 12194 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12195 pw.print(" "); pw.println(p.toString()); 12196 if (p.info != null && p.info.applicationInfo != null) { 12197 final String appInfo = p.info.applicationInfo.toString(); 12198 pw.print(" applicationInfo="); pw.println(appInfo); 12199 } 12200 } 12201 } 12202 12203 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12204 mSettings.mKeySetManager.dump(pw, packageName, dumpState); 12205 } 12206 12207 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12208 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12209 } 12210 12211 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12212 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12213 } 12214 12215 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12216 if (dumpState.onTitlePrinted()) 12217 pw.println(); 12218 mSettings.dumpReadMessagesLPr(pw, dumpState); 12219 12220 pw.println(); 12221 pw.println("Package warning messages:"); 12222 final File fname = getSettingsProblemFile(); 12223 FileInputStream in = null; 12224 try { 12225 in = new FileInputStream(fname); 12226 final int avail = in.available(); 12227 final byte[] data = new byte[avail]; 12228 in.read(data); 12229 pw.print(new String(data)); 12230 } catch (FileNotFoundException e) { 12231 } catch (IOException e) { 12232 } finally { 12233 if (in != null) { 12234 try { 12235 in.close(); 12236 } catch (IOException e) { 12237 } 12238 } 12239 } 12240 } 12241 } 12242 } 12243 12244 // ------- apps on sdcard specific code ------- 12245 static final boolean DEBUG_SD_INSTALL = false; 12246 12247 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12248 12249 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12250 12251 private boolean mMediaMounted = false; 12252 12253 private String getEncryptKey() { 12254 try { 12255 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12256 SD_ENCRYPTION_KEYSTORE_NAME); 12257 if (sdEncKey == null) { 12258 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12259 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12260 if (sdEncKey == null) { 12261 Slog.e(TAG, "Failed to create encryption keys"); 12262 return null; 12263 } 12264 } 12265 return sdEncKey; 12266 } catch (NoSuchAlgorithmException nsae) { 12267 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12268 return null; 12269 } catch (IOException ioe) { 12270 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12271 return null; 12272 } 12273 12274 } 12275 12276 /* package */static String getTempContainerId() { 12277 int tmpIdx = 1; 12278 String list[] = PackageHelper.getSecureContainerList(); 12279 if (list != null) { 12280 for (final String name : list) { 12281 // Ignore null and non-temporary container entries 12282 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12283 continue; 12284 } 12285 12286 String subStr = name.substring(mTempContainerPrefix.length()); 12287 try { 12288 int cid = Integer.parseInt(subStr); 12289 if (cid >= tmpIdx) { 12290 tmpIdx = cid + 1; 12291 } 12292 } catch (NumberFormatException e) { 12293 } 12294 } 12295 } 12296 return mTempContainerPrefix + tmpIdx; 12297 } 12298 12299 /* 12300 * Update media status on PackageManager. 12301 */ 12302 @Override 12303 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12304 int callingUid = Binder.getCallingUid(); 12305 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12306 throw new SecurityException("Media status can only be updated by the system"); 12307 } 12308 // reader; this apparently protects mMediaMounted, but should probably 12309 // be a different lock in that case. 12310 synchronized (mPackages) { 12311 Log.i(TAG, "Updating external media status from " 12312 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12313 + (mediaStatus ? "mounted" : "unmounted")); 12314 if (DEBUG_SD_INSTALL) 12315 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12316 + ", mMediaMounted=" + mMediaMounted); 12317 if (mediaStatus == mMediaMounted) { 12318 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12319 : 0, -1); 12320 mHandler.sendMessage(msg); 12321 return; 12322 } 12323 mMediaMounted = mediaStatus; 12324 } 12325 // Queue up an async operation since the package installation may take a 12326 // little while. 12327 mHandler.post(new Runnable() { 12328 public void run() { 12329 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12330 } 12331 }); 12332 } 12333 12334 /** 12335 * Called by MountService when the initial ASECs to scan are available. 12336 * Should block until all the ASEC containers are finished being scanned. 12337 */ 12338 public void scanAvailableAsecs() { 12339 updateExternalMediaStatusInner(true, false, false); 12340 if (mShouldRestoreconData) { 12341 SELinuxMMAC.setRestoreconDone(); 12342 mShouldRestoreconData = false; 12343 } 12344 } 12345 12346 /* 12347 * Collect information of applications on external media, map them against 12348 * existing containers and update information based on current mount status. 12349 * Please note that we always have to report status if reportStatus has been 12350 * set to true especially when unloading packages. 12351 */ 12352 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12353 boolean externalStorage) { 12354 // Collection of uids 12355 int uidArr[] = null; 12356 // Collection of stale containers 12357 HashSet<String> removeCids = new HashSet<String>(); 12358 // Collection of packages on external media with valid containers. 12359 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12360 // Get list of secure containers. 12361 final String list[] = PackageHelper.getSecureContainerList(); 12362 if (list == null || list.length == 0) { 12363 Log.i(TAG, "No secure containers on sdcard"); 12364 } else { 12365 // Process list of secure containers and categorize them 12366 // as active or stale based on their package internal state. 12367 int uidList[] = new int[list.length]; 12368 int num = 0; 12369 // reader 12370 synchronized (mPackages) { 12371 for (String cid : list) { 12372 if (DEBUG_SD_INSTALL) 12373 Log.i(TAG, "Processing container " + cid); 12374 String pkgName = getAsecPackageName(cid); 12375 if (pkgName == null) { 12376 if (DEBUG_SD_INSTALL) 12377 Log.i(TAG, "Container : " + cid + " stale"); 12378 removeCids.add(cid); 12379 continue; 12380 } 12381 if (DEBUG_SD_INSTALL) 12382 Log.i(TAG, "Looking for pkg : " + pkgName); 12383 12384 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12385 if (ps == null) { 12386 Log.i(TAG, "Deleting container with no matching settings " + cid); 12387 removeCids.add(cid); 12388 continue; 12389 } 12390 12391 /* 12392 * Skip packages that are not external if we're unmounting 12393 * external storage. 12394 */ 12395 if (externalStorage && !isMounted && !isExternal(ps)) { 12396 continue; 12397 } 12398 12399 final AsecInstallArgs args = new AsecInstallArgs(cid, 12400 getAppInstructionSetFromSettings(ps), 12401 isForwardLocked(ps)); 12402 // The package status is changed only if the code path 12403 // matches between settings and the container id. 12404 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12405 if (DEBUG_SD_INSTALL) { 12406 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12407 + " at code path: " + ps.codePathString); 12408 } 12409 12410 // We do have a valid package installed on sdcard 12411 processCids.put(args, ps.codePathString); 12412 final int uid = ps.appId; 12413 if (uid != -1) { 12414 uidList[num++] = uid; 12415 } 12416 } else { 12417 Log.i(TAG, "Deleting stale container for " + cid); 12418 removeCids.add(cid); 12419 } 12420 } 12421 } 12422 12423 if (num > 0) { 12424 // Sort uid list 12425 Arrays.sort(uidList, 0, num); 12426 // Throw away duplicates 12427 uidArr = new int[num]; 12428 uidArr[0] = uidList[0]; 12429 int di = 0; 12430 for (int i = 1; i < num; i++) { 12431 if (uidList[i - 1] != uidList[i]) { 12432 uidArr[di++] = uidList[i]; 12433 } 12434 } 12435 } 12436 } 12437 // Process packages with valid entries. 12438 if (isMounted) { 12439 if (DEBUG_SD_INSTALL) 12440 Log.i(TAG, "Loading packages"); 12441 loadMediaPackages(processCids, uidArr, removeCids); 12442 startCleaningPackages(); 12443 } else { 12444 if (DEBUG_SD_INSTALL) 12445 Log.i(TAG, "Unloading packages"); 12446 unloadMediaPackages(processCids, uidArr, reportStatus); 12447 } 12448 } 12449 12450 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12451 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12452 int size = pkgList.size(); 12453 if (size > 0) { 12454 // Send broadcasts here 12455 Bundle extras = new Bundle(); 12456 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12457 .toArray(new String[size])); 12458 if (uidArr != null) { 12459 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12460 } 12461 if (replacing) { 12462 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12463 } 12464 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12465 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12466 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12467 } 12468 } 12469 12470 /* 12471 * Look at potentially valid container ids from processCids If package 12472 * information doesn't match the one on record or package scanning fails, 12473 * the cid is added to list of removeCids. We currently don't delete stale 12474 * containers. 12475 */ 12476 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12477 HashSet<String> removeCids) { 12478 ArrayList<String> pkgList = new ArrayList<String>(); 12479 Set<AsecInstallArgs> keys = processCids.keySet(); 12480 boolean doGc = false; 12481 for (AsecInstallArgs args : keys) { 12482 String codePath = processCids.get(args); 12483 if (DEBUG_SD_INSTALL) 12484 Log.i(TAG, "Loading container : " + args.cid); 12485 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12486 try { 12487 // Make sure there are no container errors first. 12488 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12489 Slog.e(TAG, "Failed to mount cid : " + args.cid 12490 + " when installing from sdcard"); 12491 continue; 12492 } 12493 // Check code path here. 12494 if (codePath == null || !codePath.equals(args.getCodePath())) { 12495 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12496 + " does not match one in settings " + codePath); 12497 continue; 12498 } 12499 // Parse package 12500 int parseFlags = mDefParseFlags; 12501 if (args.isExternal()) { 12502 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12503 } 12504 if (args.isFwdLocked()) { 12505 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12506 } 12507 12508 doGc = true; 12509 synchronized (mInstallLock) { 12510 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 12511 0, 0, null); 12512 // Scan the package 12513 if (pkg != null) { 12514 /* 12515 * TODO why is the lock being held? doPostInstall is 12516 * called in other places without the lock. This needs 12517 * to be straightened out. 12518 */ 12519 // writer 12520 synchronized (mPackages) { 12521 retCode = PackageManager.INSTALL_SUCCEEDED; 12522 pkgList.add(pkg.packageName); 12523 // Post process args 12524 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12525 pkg.applicationInfo.uid); 12526 } 12527 } else { 12528 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12529 } 12530 } 12531 12532 } finally { 12533 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12534 // Don't destroy container here. Wait till gc clears things 12535 // up. 12536 removeCids.add(args.cid); 12537 } 12538 } 12539 } 12540 // writer 12541 synchronized (mPackages) { 12542 // If the platform SDK has changed since the last time we booted, 12543 // we need to re-grant app permission to catch any new ones that 12544 // appear. This is really a hack, and means that apps can in some 12545 // cases get permissions that the user didn't initially explicitly 12546 // allow... it would be nice to have some better way to handle 12547 // this situation. 12548 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12549 if (regrantPermissions) 12550 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12551 + mSdkVersion + "; regranting permissions for external storage"); 12552 mSettings.mExternalSdkPlatform = mSdkVersion; 12553 12554 // Make sure group IDs have been assigned, and any permission 12555 // changes in other apps are accounted for 12556 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12557 | (regrantPermissions 12558 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12559 : 0)); 12560 12561 mSettings.updateExternalDatabaseVersion(); 12562 12563 // can downgrade to reader 12564 // Persist settings 12565 mSettings.writeLPr(); 12566 } 12567 // Send a broadcast to let everyone know we are done processing 12568 if (pkgList.size() > 0) { 12569 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12570 } 12571 // Force gc to avoid any stale parser references that we might have. 12572 if (doGc) { 12573 Runtime.getRuntime().gc(); 12574 } 12575 // List stale containers and destroy stale temporary containers. 12576 if (removeCids != null) { 12577 for (String cid : removeCids) { 12578 if (cid.startsWith(mTempContainerPrefix)) { 12579 Log.i(TAG, "Destroying stale temporary container " + cid); 12580 PackageHelper.destroySdDir(cid); 12581 } else { 12582 Log.w(TAG, "Container " + cid + " is stale"); 12583 } 12584 } 12585 } 12586 } 12587 12588 /* 12589 * Utility method to unload a list of specified containers 12590 */ 12591 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12592 // Just unmount all valid containers. 12593 for (AsecInstallArgs arg : cidArgs) { 12594 synchronized (mInstallLock) { 12595 arg.doPostDeleteLI(false); 12596 } 12597 } 12598 } 12599 12600 /* 12601 * Unload packages mounted on external media. This involves deleting package 12602 * data from internal structures, sending broadcasts about diabled packages, 12603 * gc'ing to free up references, unmounting all secure containers 12604 * corresponding to packages on external media, and posting a 12605 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12606 * that we always have to post this message if status has been requested no 12607 * matter what. 12608 */ 12609 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12610 final boolean reportStatus) { 12611 if (DEBUG_SD_INSTALL) 12612 Log.i(TAG, "unloading media packages"); 12613 ArrayList<String> pkgList = new ArrayList<String>(); 12614 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12615 final Set<AsecInstallArgs> keys = processCids.keySet(); 12616 for (AsecInstallArgs args : keys) { 12617 String pkgName = args.getPackageName(); 12618 if (DEBUG_SD_INSTALL) 12619 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12620 // Delete package internally 12621 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12622 synchronized (mInstallLock) { 12623 boolean res = deletePackageLI(pkgName, null, false, null, null, 12624 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12625 if (res) { 12626 pkgList.add(pkgName); 12627 } else { 12628 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12629 failedList.add(args); 12630 } 12631 } 12632 } 12633 12634 // reader 12635 synchronized (mPackages) { 12636 // We didn't update the settings after removing each package; 12637 // write them now for all packages. 12638 mSettings.writeLPr(); 12639 } 12640 12641 // We have to absolutely send UPDATED_MEDIA_STATUS only 12642 // after confirming that all the receivers processed the ordered 12643 // broadcast when packages get disabled, force a gc to clean things up. 12644 // and unload all the containers. 12645 if (pkgList.size() > 0) { 12646 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12647 new IIntentReceiver.Stub() { 12648 public void performReceive(Intent intent, int resultCode, String data, 12649 Bundle extras, boolean ordered, boolean sticky, 12650 int sendingUser) throws RemoteException { 12651 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12652 reportStatus ? 1 : 0, 1, keys); 12653 mHandler.sendMessage(msg); 12654 } 12655 }); 12656 } else { 12657 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12658 keys); 12659 mHandler.sendMessage(msg); 12660 } 12661 } 12662 12663 /** Binder call */ 12664 @Override 12665 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12666 final int flags) { 12667 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12668 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12669 int returnCode = PackageManager.MOVE_SUCCEEDED; 12670 int currFlags = 0; 12671 int newFlags = 0; 12672 // reader 12673 synchronized (mPackages) { 12674 PackageParser.Package pkg = mPackages.get(packageName); 12675 if (pkg == null) { 12676 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12677 } else { 12678 // Disable moving fwd locked apps and system packages 12679 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12680 Slog.w(TAG, "Cannot move system application"); 12681 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12682 } else if (pkg.mOperationPending) { 12683 Slog.w(TAG, "Attempt to move package which has pending operations"); 12684 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12685 } else { 12686 // Find install location first 12687 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12688 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12689 Slog.w(TAG, "Ambigous flags specified for move location."); 12690 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12691 } else { 12692 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12693 : PackageManager.INSTALL_INTERNAL; 12694 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12695 : PackageManager.INSTALL_INTERNAL; 12696 12697 if (newFlags == currFlags) { 12698 Slog.w(TAG, "No move required. Trying to move to same location"); 12699 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12700 } else { 12701 if (isForwardLocked(pkg)) { 12702 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12703 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12704 } 12705 } 12706 } 12707 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12708 pkg.mOperationPending = true; 12709 } 12710 } 12711 } 12712 12713 /* 12714 * TODO this next block probably shouldn't be inside the lock. We 12715 * can't guarantee these won't change after this is fired off 12716 * anyway. 12717 */ 12718 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12719 processPendingMove(new MoveParams(null, observer, 0, packageName, null, 12720 null, -1, user), 12721 returnCode); 12722 } else { 12723 Message msg = mHandler.obtainMessage(INIT_COPY); 12724 final String instructionSet = getAppInstructionSet(pkg.applicationInfo); 12725 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir, 12726 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir, 12727 instructionSet); 12728 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12729 pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user); 12730 msg.obj = mp; 12731 mHandler.sendMessage(msg); 12732 } 12733 } 12734 } 12735 12736 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12737 // Queue up an async operation since the package deletion may take a 12738 // little while. 12739 mHandler.post(new Runnable() { 12740 public void run() { 12741 // TODO fix this; this does nothing. 12742 mHandler.removeCallbacks(this); 12743 int returnCode = currentStatus; 12744 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12745 int uidArr[] = null; 12746 ArrayList<String> pkgList = null; 12747 synchronized (mPackages) { 12748 PackageParser.Package pkg = mPackages.get(mp.packageName); 12749 if (pkg == null) { 12750 Slog.w(TAG, " Package " + mp.packageName 12751 + " doesn't exist. Aborting move"); 12752 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12753 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 12754 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12755 + mp.srcArgs.getCodePath() + " to " 12756 + pkg.applicationInfo.sourceDir 12757 + " Aborting move and returning error"); 12758 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12759 } else { 12760 uidArr = new int[] { 12761 pkg.applicationInfo.uid 12762 }; 12763 pkgList = new ArrayList<String>(); 12764 pkgList.add(mp.packageName); 12765 } 12766 } 12767 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12768 // Send resources unavailable broadcast 12769 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12770 // Update package code and resource paths 12771 synchronized (mInstallLock) { 12772 synchronized (mPackages) { 12773 PackageParser.Package pkg = mPackages.get(mp.packageName); 12774 // Recheck for package again. 12775 if (pkg == null) { 12776 Slog.w(TAG, " Package " + mp.packageName 12777 + " doesn't exist. Aborting move"); 12778 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12779 } else if (!mp.srcArgs.getCodePath().equals( 12780 pkg.applicationInfo.sourceDir)) { 12781 Slog.w(TAG, "Package " + mp.packageName 12782 + " code path changed from " + mp.srcArgs.getCodePath() 12783 + " to " + pkg.applicationInfo.sourceDir 12784 + " Aborting move and returning error"); 12785 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12786 } else { 12787 final String oldCodePath = pkg.mPath; 12788 final String newCodePath = mp.targetArgs.getCodePath(); 12789 final String newResPath = mp.targetArgs.getResourcePath(); 12790 final String newNativePath = mp.targetArgs 12791 .getNativeLibraryPath(); 12792 12793 final File newNativeDir = new File(newNativePath); 12794 12795 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12796 // NOTE: We do not report any errors from the APK scan and library 12797 // copy at this point. 12798 NativeLibraryHelper.ApkHandle handle = 12799 new NativeLibraryHelper.ApkHandle(newCodePath); 12800 final int abi = NativeLibraryHelper.findSupportedAbi( 12801 handle, Build.SUPPORTED_ABIS); 12802 if (abi >= 0) { 12803 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12804 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12805 } 12806 handle.close(); 12807 } 12808 final int[] users = sUserManager.getUserIds(); 12809 for (int user : users) { 12810 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 12811 newNativePath, user) < 0) { 12812 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12813 } 12814 } 12815 12816 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12817 pkg.mPath = newCodePath; 12818 // Move dex files around 12819 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) { 12820 // Moving of dex files failed. Set 12821 // error code and abort move. 12822 pkg.mPath = pkg.mScanPath; 12823 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12824 } 12825 } 12826 12827 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12828 pkg.mScanPath = newCodePath; 12829 pkg.applicationInfo.sourceDir = newCodePath; 12830 pkg.applicationInfo.publicSourceDir = newResPath; 12831 pkg.applicationInfo.nativeLibraryDir = newNativePath; 12832 PackageSetting ps = (PackageSetting) pkg.mExtras; 12833 ps.codePath = new File(pkg.applicationInfo.sourceDir); 12834 ps.codePathString = ps.codePath.getPath(); 12835 ps.resourcePath = new File( 12836 pkg.applicationInfo.publicSourceDir); 12837 ps.resourcePathString = ps.resourcePath.getPath(); 12838 ps.nativeLibraryPathString = newNativePath; 12839 // Set the application info flag 12840 // correctly. 12841 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 12842 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12843 } else { 12844 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12845 } 12846 ps.setFlags(pkg.applicationInfo.flags); 12847 mAppDirs.remove(oldCodePath); 12848 mAppDirs.put(newCodePath, pkg); 12849 // Persist settings 12850 mSettings.writeLPr(); 12851 } 12852 } 12853 } 12854 } 12855 // Send resources available broadcast 12856 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12857 } 12858 } 12859 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12860 // Clean up failed installation 12861 if (mp.targetArgs != null) { 12862 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 12863 -1); 12864 } 12865 } else { 12866 // Force a gc to clear things up. 12867 Runtime.getRuntime().gc(); 12868 // Delete older code 12869 synchronized (mInstallLock) { 12870 mp.srcArgs.doPostDeleteLI(true); 12871 } 12872 } 12873 12874 // Allow more operations on this file if we didn't fail because 12875 // an operation was already pending for this package. 12876 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 12877 synchronized (mPackages) { 12878 PackageParser.Package pkg = mPackages.get(mp.packageName); 12879 if (pkg != null) { 12880 pkg.mOperationPending = false; 12881 } 12882 } 12883 } 12884 12885 IPackageMoveObserver observer = mp.observer; 12886 if (observer != null) { 12887 try { 12888 observer.packageMoved(mp.packageName, returnCode); 12889 } catch (RemoteException e) { 12890 Log.i(TAG, "Observer no longer exists."); 12891 } 12892 } 12893 } 12894 }); 12895 } 12896 12897 @Override 12898 public boolean setInstallLocation(int loc) { 12899 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12900 null); 12901 if (getInstallLocation() == loc) { 12902 return true; 12903 } 12904 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12905 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12906 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12907 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12908 return true; 12909 } 12910 return false; 12911 } 12912 12913 @Override 12914 public int getInstallLocation() { 12915 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12916 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12917 PackageHelper.APP_INSTALL_AUTO); 12918 } 12919 12920 /** Called by UserManagerService */ 12921 void cleanUpUserLILPw(int userHandle) { 12922 mDirtyUsers.remove(userHandle); 12923 mSettings.removeUserLPr(userHandle); 12924 mPendingBroadcasts.remove(userHandle); 12925 if (mInstaller != null) { 12926 // Technically, we shouldn't be doing this with the package lock 12927 // held. However, this is very rare, and there is already so much 12928 // other disk I/O going on, that we'll let it slide for now. 12929 mInstaller.removeUserDataDirs(userHandle); 12930 } 12931 } 12932 12933 /** Called by UserManagerService */ 12934 void createNewUserLILPw(int userHandle, File path) { 12935 if (mInstaller != null) { 12936 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 12937 } 12938 } 12939 12940 @Override 12941 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 12942 mContext.enforceCallingOrSelfPermission( 12943 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12944 "Only package verification agents can read the verifier device identity"); 12945 12946 synchronized (mPackages) { 12947 return mSettings.getVerifierDeviceIdentityLPw(); 12948 } 12949 } 12950 12951 @Override 12952 public void setPermissionEnforced(String permission, boolean enforced) { 12953 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 12954 if (READ_EXTERNAL_STORAGE.equals(permission)) { 12955 synchronized (mPackages) { 12956 if (mSettings.mReadExternalStorageEnforced == null 12957 || mSettings.mReadExternalStorageEnforced != enforced) { 12958 mSettings.mReadExternalStorageEnforced = enforced; 12959 mSettings.writeLPr(); 12960 } 12961 } 12962 // kill any non-foreground processes so we restart them and 12963 // grant/revoke the GID. 12964 final IActivityManager am = ActivityManagerNative.getDefault(); 12965 if (am != null) { 12966 final long token = Binder.clearCallingIdentity(); 12967 try { 12968 am.killProcessesBelowForeground("setPermissionEnforcement"); 12969 } catch (RemoteException e) { 12970 } finally { 12971 Binder.restoreCallingIdentity(token); 12972 } 12973 } 12974 } else { 12975 throw new IllegalArgumentException("No selective enforcement for " + permission); 12976 } 12977 } 12978 12979 @Override 12980 @Deprecated 12981 public boolean isPermissionEnforced(String permission) { 12982 return true; 12983 } 12984 12985 @Override 12986 public boolean isStorageLow() { 12987 final long token = Binder.clearCallingIdentity(); 12988 try { 12989 final DeviceStorageMonitorInternal 12990 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12991 if (dsm != null) { 12992 return dsm.isMemoryLow(); 12993 } else { 12994 return false; 12995 } 12996 } finally { 12997 Binder.restoreCallingIdentity(token); 12998 } 12999 } 13000 13001 @Override 13002 public IPackageInstaller getPackageInstaller() { 13003 return mInstallerService; 13004 } 13005} 13006