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