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