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