PackageManagerService.java revision 6e2ae2590ded39f04f76d5ddca0f06fe01586e26
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 mIsFirstBoot = false; 625 626 boolean isFirstBoot() { 627 return mIsFirstBoot; 628 } 629 630 void write(boolean force) { 631 if (force) { 632 writeInternal(); 633 return; 634 } 635 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 636 && !DEBUG_DEXOPT) { 637 return; 638 } 639 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 640 new Thread("PackageUsage_DiskWriter") { 641 @Override 642 public void run() { 643 try { 644 writeInternal(); 645 } finally { 646 mBackgroundWriteRunning.set(false); 647 } 648 } 649 }.start(); 650 } 651 } 652 653 private void writeInternal() { 654 synchronized (mPackages) { 655 synchronized (mFileLock) { 656 AtomicFile file = getFile(); 657 FileOutputStream f = null; 658 try { 659 f = file.startWrite(); 660 BufferedOutputStream out = new BufferedOutputStream(f); 661 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 662 StringBuilder sb = new StringBuilder(); 663 for (PackageParser.Package pkg : mPackages.values()) { 664 if (pkg.mLastPackageUsageTimeInMills == 0) { 665 continue; 666 } 667 sb.setLength(0); 668 sb.append(pkg.packageName); 669 sb.append(' '); 670 sb.append((long)pkg.mLastPackageUsageTimeInMills); 671 sb.append('\n'); 672 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 673 } 674 out.flush(); 675 file.finishWrite(f); 676 } catch (IOException e) { 677 if (f != null) { 678 file.failWrite(f); 679 } 680 Log.e(TAG, "Failed to write package usage times", e); 681 } 682 } 683 } 684 mLastWritten.set(SystemClock.elapsedRealtime()); 685 } 686 687 void readLP() { 688 synchronized (mFileLock) { 689 AtomicFile file = getFile(); 690 BufferedInputStream in = null; 691 try { 692 in = new BufferedInputStream(file.openRead()); 693 StringBuffer sb = new StringBuffer(); 694 while (true) { 695 String packageName = readToken(in, sb, ' '); 696 if (packageName == null) { 697 break; 698 } 699 String timeInMillisString = readToken(in, sb, '\n'); 700 if (timeInMillisString == null) { 701 throw new IOException("Failed to find last usage time for package " 702 + packageName); 703 } 704 PackageParser.Package pkg = mPackages.get(packageName); 705 if (pkg == null) { 706 continue; 707 } 708 long timeInMillis; 709 try { 710 timeInMillis = Long.parseLong(timeInMillisString.toString()); 711 } catch (NumberFormatException e) { 712 throw new IOException("Failed to parse " + timeInMillisString 713 + " as a long.", e); 714 } 715 pkg.mLastPackageUsageTimeInMills = timeInMillis; 716 } 717 } catch (FileNotFoundException expected) { 718 mIsFirstBoot = true; 719 } catch (IOException e) { 720 Log.w(TAG, "Failed to read package usage times", e); 721 } finally { 722 IoUtils.closeQuietly(in); 723 } 724 } 725 mLastWritten.set(SystemClock.elapsedRealtime()); 726 } 727 728 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 729 throws IOException { 730 sb.setLength(0); 731 while (true) { 732 int ch = in.read(); 733 if (ch == -1) { 734 if (sb.length() == 0) { 735 return null; 736 } 737 throw new IOException("Unexpected EOF"); 738 } 739 if (ch == endOfToken) { 740 return sb.toString(); 741 } 742 sb.append((char)ch); 743 } 744 } 745 746 private AtomicFile getFile() { 747 File dataDir = Environment.getDataDirectory(); 748 File systemDir = new File(dataDir, "system"); 749 File fname = new File(systemDir, "package-usage.list"); 750 return new AtomicFile(fname); 751 } 752 } 753 754 class PackageHandler extends Handler { 755 private boolean mBound = false; 756 final ArrayList<HandlerParams> mPendingInstalls = 757 new ArrayList<HandlerParams>(); 758 759 private boolean connectToService() { 760 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 761 " DefaultContainerService"); 762 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 763 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 764 if (mContext.bindServiceAsUser(service, mDefContainerConn, 765 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 766 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 767 mBound = true; 768 return true; 769 } 770 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 771 return false; 772 } 773 774 private void disconnectService() { 775 mContainerService = null; 776 mBound = false; 777 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 778 mContext.unbindService(mDefContainerConn); 779 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 780 } 781 782 PackageHandler(Looper looper) { 783 super(looper); 784 } 785 786 public void handleMessage(Message msg) { 787 try { 788 doHandleMessage(msg); 789 } finally { 790 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 791 } 792 } 793 794 void doHandleMessage(Message msg) { 795 switch (msg.what) { 796 case INIT_COPY: { 797 HandlerParams params = (HandlerParams) msg.obj; 798 int idx = mPendingInstalls.size(); 799 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 800 // If a bind was already initiated we dont really 801 // need to do anything. The pending install 802 // will be processed later on. 803 if (!mBound) { 804 // If this is the only one pending we might 805 // have to bind to the service again. 806 if (!connectToService()) { 807 Slog.e(TAG, "Failed to bind to media container service"); 808 params.serviceError(); 809 return; 810 } else { 811 // Once we bind to the service, the first 812 // pending request will be processed. 813 mPendingInstalls.add(idx, params); 814 } 815 } else { 816 mPendingInstalls.add(idx, params); 817 // Already bound to the service. Just make 818 // sure we trigger off processing the first request. 819 if (idx == 0) { 820 mHandler.sendEmptyMessage(MCS_BOUND); 821 } 822 } 823 break; 824 } 825 case MCS_BOUND: { 826 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 827 if (msg.obj != null) { 828 mContainerService = (IMediaContainerService) msg.obj; 829 } 830 if (mContainerService == null) { 831 // Something seriously wrong. Bail out 832 Slog.e(TAG, "Cannot bind to media container service"); 833 for (HandlerParams params : mPendingInstalls) { 834 // Indicate service bind error 835 params.serviceError(); 836 } 837 mPendingInstalls.clear(); 838 } else if (mPendingInstalls.size() > 0) { 839 HandlerParams params = mPendingInstalls.get(0); 840 if (params != null) { 841 if (params.startCopy()) { 842 // We are done... look for more work or to 843 // go idle. 844 if (DEBUG_SD_INSTALL) Log.i(TAG, 845 "Checking for more work or unbind..."); 846 // Delete pending install 847 if (mPendingInstalls.size() > 0) { 848 mPendingInstalls.remove(0); 849 } 850 if (mPendingInstalls.size() == 0) { 851 if (mBound) { 852 if (DEBUG_SD_INSTALL) Log.i(TAG, 853 "Posting delayed MCS_UNBIND"); 854 removeMessages(MCS_UNBIND); 855 Message ubmsg = obtainMessage(MCS_UNBIND); 856 // Unbind after a little delay, to avoid 857 // continual thrashing. 858 sendMessageDelayed(ubmsg, 10000); 859 } 860 } else { 861 // There are more pending requests in queue. 862 // Just post MCS_BOUND message to trigger processing 863 // of next pending install. 864 if (DEBUG_SD_INSTALL) Log.i(TAG, 865 "Posting MCS_BOUND for next work"); 866 mHandler.sendEmptyMessage(MCS_BOUND); 867 } 868 } 869 } 870 } else { 871 // Should never happen ideally. 872 Slog.w(TAG, "Empty queue"); 873 } 874 break; 875 } 876 case MCS_RECONNECT: { 877 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 878 if (mPendingInstalls.size() > 0) { 879 if (mBound) { 880 disconnectService(); 881 } 882 if (!connectToService()) { 883 Slog.e(TAG, "Failed to bind to media container service"); 884 for (HandlerParams params : mPendingInstalls) { 885 // Indicate service bind error 886 params.serviceError(); 887 } 888 mPendingInstalls.clear(); 889 } 890 } 891 break; 892 } 893 case MCS_UNBIND: { 894 // If there is no actual work left, then time to unbind. 895 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 896 897 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 898 if (mBound) { 899 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 900 901 disconnectService(); 902 } 903 } else if (mPendingInstalls.size() > 0) { 904 // There are more pending requests in queue. 905 // Just post MCS_BOUND message to trigger processing 906 // of next pending install. 907 mHandler.sendEmptyMessage(MCS_BOUND); 908 } 909 910 break; 911 } 912 case MCS_GIVE_UP: { 913 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 914 mPendingInstalls.remove(0); 915 break; 916 } 917 case SEND_PENDING_BROADCAST: { 918 String packages[]; 919 ArrayList<String> components[]; 920 int size = 0; 921 int uids[]; 922 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 923 synchronized (mPackages) { 924 if (mPendingBroadcasts == null) { 925 return; 926 } 927 size = mPendingBroadcasts.size(); 928 if (size <= 0) { 929 // Nothing to be done. Just return 930 return; 931 } 932 packages = new String[size]; 933 components = new ArrayList[size]; 934 uids = new int[size]; 935 int i = 0; // filling out the above arrays 936 937 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 938 int packageUserId = mPendingBroadcasts.userIdAt(n); 939 Iterator<Map.Entry<String, ArrayList<String>>> it 940 = mPendingBroadcasts.packagesForUserId(packageUserId) 941 .entrySet().iterator(); 942 while (it.hasNext() && i < size) { 943 Map.Entry<String, ArrayList<String>> ent = it.next(); 944 packages[i] = ent.getKey(); 945 components[i] = ent.getValue(); 946 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 947 uids[i] = (ps != null) 948 ? UserHandle.getUid(packageUserId, ps.appId) 949 : -1; 950 i++; 951 } 952 } 953 size = i; 954 mPendingBroadcasts.clear(); 955 } 956 // Send broadcasts 957 for (int i = 0; i < size; i++) { 958 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 959 } 960 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 961 break; 962 } 963 case START_CLEANING_PACKAGE: { 964 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 965 final String packageName = (String)msg.obj; 966 final int userId = msg.arg1; 967 final boolean andCode = msg.arg2 != 0; 968 synchronized (mPackages) { 969 if (userId == UserHandle.USER_ALL) { 970 int[] users = sUserManager.getUserIds(); 971 for (int user : users) { 972 mSettings.addPackageToCleanLPw( 973 new PackageCleanItem(user, packageName, andCode)); 974 } 975 } else { 976 mSettings.addPackageToCleanLPw( 977 new PackageCleanItem(userId, packageName, andCode)); 978 } 979 } 980 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 981 startCleaningPackages(); 982 } break; 983 case POST_INSTALL: { 984 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 985 PostInstallData data = mRunningInstalls.get(msg.arg1); 986 mRunningInstalls.delete(msg.arg1); 987 boolean deleteOld = false; 988 989 if (data != null) { 990 InstallArgs args = data.args; 991 PackageInstalledInfo res = data.res; 992 993 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 994 res.removedInfo.sendBroadcast(false, true, false); 995 Bundle extras = new Bundle(1); 996 extras.putInt(Intent.EXTRA_UID, res.uid); 997 // Determine the set of users who are adding this 998 // package for the first time vs. those who are seeing 999 // an update. 1000 int[] firstUsers; 1001 int[] updateUsers = new int[0]; 1002 if (res.origUsers == null || res.origUsers.length == 0) { 1003 firstUsers = res.newUsers; 1004 } else { 1005 firstUsers = new int[0]; 1006 for (int i=0; i<res.newUsers.length; i++) { 1007 int user = res.newUsers[i]; 1008 boolean isNew = true; 1009 for (int j=0; j<res.origUsers.length; j++) { 1010 if (res.origUsers[j] == user) { 1011 isNew = false; 1012 break; 1013 } 1014 } 1015 if (isNew) { 1016 int[] newFirst = new int[firstUsers.length+1]; 1017 System.arraycopy(firstUsers, 0, newFirst, 0, 1018 firstUsers.length); 1019 newFirst[firstUsers.length] = user; 1020 firstUsers = newFirst; 1021 } else { 1022 int[] newUpdate = new int[updateUsers.length+1]; 1023 System.arraycopy(updateUsers, 0, newUpdate, 0, 1024 updateUsers.length); 1025 newUpdate[updateUsers.length] = user; 1026 updateUsers = newUpdate; 1027 } 1028 } 1029 } 1030 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1031 res.pkg.applicationInfo.packageName, 1032 extras, null, null, firstUsers); 1033 final boolean update = res.removedInfo.removedPackage != null; 1034 if (update) { 1035 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1036 } 1037 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1038 res.pkg.applicationInfo.packageName, 1039 extras, null, null, updateUsers); 1040 if (update) { 1041 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1042 res.pkg.applicationInfo.packageName, 1043 extras, null, null, updateUsers); 1044 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1045 null, null, 1046 res.pkg.applicationInfo.packageName, null, updateUsers); 1047 1048 // treat asec-hosted packages like removable media on upgrade 1049 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1050 if (DEBUG_INSTALL) { 1051 Slog.i(TAG, "upgrading pkg " + res.pkg 1052 + " is ASEC-hosted -> AVAILABLE"); 1053 } 1054 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1055 ArrayList<String> pkgList = new ArrayList<String>(1); 1056 pkgList.add(res.pkg.applicationInfo.packageName); 1057 sendResourcesChangedBroadcast(true, true, 1058 pkgList,uidArray, null); 1059 } 1060 } 1061 if (res.removedInfo.args != null) { 1062 // Remove the replaced package's older resources safely now 1063 deleteOld = true; 1064 } 1065 1066 // Log current value of "unknown sources" setting 1067 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1068 getUnknownSourcesSettings()); 1069 } 1070 // Force a gc to clear up things 1071 Runtime.getRuntime().gc(); 1072 // We delete after a gc for applications on sdcard. 1073 if (deleteOld) { 1074 synchronized (mInstallLock) { 1075 res.removedInfo.args.doPostDeleteLI(true); 1076 } 1077 } 1078 if (args.observer != null) { 1079 try { 1080 args.observer.packageInstalled(res.name, res.returnCode); 1081 } catch (RemoteException e) { 1082 Slog.i(TAG, "Observer no longer exists."); 1083 } 1084 } 1085 if (args.observer2 != null) { 1086 try { 1087 Bundle extras = extrasForInstallResult(res); 1088 args.observer2.packageInstalled(res.name, extras, res.returnCode); 1089 } catch (RemoteException e) { 1090 Slog.i(TAG, "Observer no longer exists."); 1091 } 1092 } 1093 } else { 1094 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1095 } 1096 } break; 1097 case UPDATED_MEDIA_STATUS: { 1098 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1099 boolean reportStatus = msg.arg1 == 1; 1100 boolean doGc = msg.arg2 == 1; 1101 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1102 if (doGc) { 1103 // Force a gc to clear up stale containers. 1104 Runtime.getRuntime().gc(); 1105 } 1106 if (msg.obj != null) { 1107 @SuppressWarnings("unchecked") 1108 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1109 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1110 // Unload containers 1111 unloadAllContainers(args); 1112 } 1113 if (reportStatus) { 1114 try { 1115 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1116 PackageHelper.getMountService().finishMediaUpdate(); 1117 } catch (RemoteException e) { 1118 Log.e(TAG, "MountService not running?"); 1119 } 1120 } 1121 } break; 1122 case WRITE_SETTINGS: { 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1124 synchronized (mPackages) { 1125 removeMessages(WRITE_SETTINGS); 1126 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1127 mSettings.writeLPr(); 1128 mDirtyUsers.clear(); 1129 } 1130 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1131 } break; 1132 case WRITE_PACKAGE_RESTRICTIONS: { 1133 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1134 synchronized (mPackages) { 1135 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1136 for (int userId : mDirtyUsers) { 1137 mSettings.writePackageRestrictionsLPr(userId); 1138 } 1139 mDirtyUsers.clear(); 1140 } 1141 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1142 } break; 1143 case CHECK_PENDING_VERIFICATION: { 1144 final int verificationId = msg.arg1; 1145 final PackageVerificationState state = mPendingVerification.get(verificationId); 1146 1147 if ((state != null) && !state.timeoutExtended()) { 1148 final InstallArgs args = state.getInstallArgs(); 1149 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString()); 1150 mPendingVerification.remove(verificationId); 1151 1152 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1153 1154 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1155 Slog.i(TAG, "Continuing with installation of " 1156 + args.packageURI.toString()); 1157 state.setVerifierResponse(Binder.getCallingUid(), 1158 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1159 broadcastPackageVerified(verificationId, args.packageURI, 1160 PackageManager.VERIFICATION_ALLOW, 1161 state.getInstallArgs().getUser()); 1162 try { 1163 ret = args.copyApk(mContainerService, true); 1164 } catch (RemoteException e) { 1165 Slog.e(TAG, "Could not contact the ContainerService"); 1166 } 1167 } else { 1168 broadcastPackageVerified(verificationId, args.packageURI, 1169 PackageManager.VERIFICATION_REJECT, 1170 state.getInstallArgs().getUser()); 1171 } 1172 1173 processPendingInstall(args, ret); 1174 mHandler.sendEmptyMessage(MCS_UNBIND); 1175 } 1176 break; 1177 } 1178 case PACKAGE_VERIFIED: { 1179 final int verificationId = msg.arg1; 1180 1181 final PackageVerificationState state = mPendingVerification.get(verificationId); 1182 if (state == null) { 1183 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1184 break; 1185 } 1186 1187 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1188 1189 state.setVerifierResponse(response.callerUid, response.code); 1190 1191 if (state.isVerificationComplete()) { 1192 mPendingVerification.remove(verificationId); 1193 1194 final InstallArgs args = state.getInstallArgs(); 1195 1196 int ret; 1197 if (state.isInstallAllowed()) { 1198 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1199 broadcastPackageVerified(verificationId, args.packageURI, 1200 response.code, state.getInstallArgs().getUser()); 1201 try { 1202 ret = args.copyApk(mContainerService, true); 1203 } catch (RemoteException e) { 1204 Slog.e(TAG, "Could not contact the ContainerService"); 1205 } 1206 } else { 1207 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1208 } 1209 1210 processPendingInstall(args, ret); 1211 1212 mHandler.sendEmptyMessage(MCS_UNBIND); 1213 } 1214 1215 break; 1216 } 1217 } 1218 } 1219 } 1220 1221 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1222 Bundle extras = null; 1223 switch (res.returnCode) { 1224 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1225 extras = new Bundle(); 1226 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1227 res.origPermission); 1228 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1229 res.origPackage); 1230 break; 1231 } 1232 } 1233 return extras; 1234 } 1235 1236 void scheduleWriteSettingsLocked() { 1237 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1238 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1239 } 1240 } 1241 1242 void scheduleWritePackageRestrictionsLocked(int userId) { 1243 if (!sUserManager.exists(userId)) return; 1244 mDirtyUsers.add(userId); 1245 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1246 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1247 } 1248 } 1249 1250 public static final 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 // Additionally, delete all dex files from the root directory 1492 // since there shouldn't be any there anyway. 1493 // 1494 // TODO: This should be revisited because it isn't as good an indicator 1495 // as it used to be. It used to include the boot classpath but at some point 1496 // DexFile.isDexOptNeeded started returning false for the boot 1497 // class path files in all cases. It is very possible in a 1498 // small maintenance release update that the library and tool 1499 // jars may be unchanged but APK could be removed resulting in 1500 // unused dalvik-cache files. 1501 mInstaller.pruneDexCache(); 1502 } 1503 1504 // Collect vendor overlay packages. 1505 // (Do this before scanning any apps.) 1506 // For security and version matching reason, only consider 1507 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1508 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1509 mVendorOverlayInstallObserver = new AppDirObserver( 1510 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1511 mVendorOverlayInstallObserver.startWatching(); 1512 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1513 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1514 1515 // Find base frameworks (resource packages without code). 1516 mFrameworkInstallObserver = new AppDirObserver( 1517 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1518 mFrameworkInstallObserver.startWatching(); 1519 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1520 | PackageParser.PARSE_IS_SYSTEM_DIR 1521 | PackageParser.PARSE_IS_PRIVILEGED, 1522 scanMode | SCAN_NO_DEX, 0); 1523 1524 // Collected privileged system packages. 1525 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1526 mPrivilegedInstallObserver = new AppDirObserver( 1527 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1528 mPrivilegedInstallObserver.startWatching(); 1529 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1530 | PackageParser.PARSE_IS_SYSTEM_DIR 1531 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1532 1533 // Collect ordinary system packages. 1534 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1535 mSystemInstallObserver = new AppDirObserver( 1536 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1537 mSystemInstallObserver.startWatching(); 1538 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1539 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1540 1541 // Collect all vendor packages. 1542 File vendorAppDir = new File("/vendor/app"); 1543 try { 1544 vendorAppDir = vendorAppDir.getCanonicalFile(); 1545 } catch (IOException e) { 1546 // failed to look up canonical path, continue with original one 1547 } 1548 mVendorInstallObserver = new AppDirObserver( 1549 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1550 mVendorInstallObserver.startWatching(); 1551 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1552 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1553 1554 // Collect all OEM packages. 1555 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1556 mOemInstallObserver = new AppDirObserver( 1557 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1558 mOemInstallObserver.startWatching(); 1559 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1560 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1561 1562 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1563 mInstaller.moveFiles(); 1564 1565 // Prune any system packages that no longer exist. 1566 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1567 if (!mOnlyCore) { 1568 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1569 while (psit.hasNext()) { 1570 PackageSetting ps = psit.next(); 1571 1572 /* 1573 * If this is not a system app, it can't be a 1574 * disable system app. 1575 */ 1576 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1577 continue; 1578 } 1579 1580 /* 1581 * If the package is scanned, it's not erased. 1582 */ 1583 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1584 if (scannedPkg != null) { 1585 /* 1586 * If the system app is both scanned and in the 1587 * disabled packages list, then it must have been 1588 * added via OTA. Remove it from the currently 1589 * scanned package so the previously user-installed 1590 * application can be scanned. 1591 */ 1592 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1593 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1594 + "; removing system app"); 1595 removePackageLI(ps, true); 1596 } 1597 1598 continue; 1599 } 1600 1601 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1602 psit.remove(); 1603 String msg = "System package " + ps.name 1604 + " no longer exists; wiping its data"; 1605 reportSettingsProblem(Log.WARN, msg); 1606 removeDataDirsLI(ps.name); 1607 } else { 1608 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1609 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1610 possiblyDeletedUpdatedSystemApps.add(ps.name); 1611 } 1612 } 1613 } 1614 } 1615 1616 //look for any incomplete package installations 1617 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1618 //clean up list 1619 for(int i = 0; i < deletePkgsList.size(); i++) { 1620 //clean up here 1621 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1622 } 1623 //delete tmp files 1624 deleteTempPackageFiles(); 1625 1626 // Remove any shared userIDs that have no associated packages 1627 mSettings.pruneSharedUsersLPw(); 1628 1629 if (!mOnlyCore) { 1630 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1631 SystemClock.uptimeMillis()); 1632 mAppInstallObserver = new AppDirObserver( 1633 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1634 mAppInstallObserver.startWatching(); 1635 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1636 1637 mDrmAppInstallObserver = new AppDirObserver( 1638 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1639 mDrmAppInstallObserver.startWatching(); 1640 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1641 scanMode, 0); 1642 1643 /** 1644 * Remove disable package settings for any updated system 1645 * apps that were removed via an OTA. If they're not a 1646 * previously-updated app, remove them completely. 1647 * Otherwise, just revoke their system-level permissions. 1648 */ 1649 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1650 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1651 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1652 1653 String msg; 1654 if (deletedPkg == null) { 1655 msg = "Updated system package " + deletedAppName 1656 + " no longer exists; wiping its data"; 1657 removeDataDirsLI(deletedAppName); 1658 } else { 1659 msg = "Updated system app + " + deletedAppName 1660 + " no longer present; removing system privileges for " 1661 + deletedAppName; 1662 1663 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1664 1665 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1666 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1667 } 1668 reportSettingsProblem(Log.WARN, msg); 1669 } 1670 } else { 1671 mAppInstallObserver = null; 1672 mDrmAppInstallObserver = null; 1673 } 1674 1675 // Now that we know all of the shared libraries, update all clients to have 1676 // the correct library paths. 1677 updateAllSharedLibrariesLPw(); 1678 1679 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1680 // NOTE: We ignore potential failures here during a system scan (like 1681 // the rest of the commands above) because there's precious little we 1682 // can do about it. A settings error is reported, though. 1683 adjustCpuAbisForSharedUserLPw(setting.packages, null, 1684 false /* force dexopt */, false /* defer dexopt */); 1685 } 1686 1687 // Now that we know all the packages we are keeping, 1688 // read and update their last usage times. 1689 mPackageUsage.readLP(); 1690 1691 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1692 SystemClock.uptimeMillis()); 1693 Slog.i(TAG, "Time to scan packages: " 1694 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1695 + " seconds"); 1696 1697 // If the platform SDK has changed since the last time we booted, 1698 // we need to re-grant app permission to catch any new ones that 1699 // appear. This is really a hack, and means that apps can in some 1700 // cases get permissions that the user didn't initially explicitly 1701 // allow... it would be nice to have some better way to handle 1702 // this situation. 1703 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1704 != mSdkVersion; 1705 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1706 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1707 + "; regranting permissions for internal storage"); 1708 mSettings.mInternalSdkPlatform = mSdkVersion; 1709 1710 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1711 | (regrantPermissions 1712 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1713 : 0)); 1714 1715 // If this is the first boot, and it is a normal boot, then 1716 // we need to initialize the default preferred apps. 1717 if (!mRestoredSettings && !onlyCore) { 1718 mSettings.readDefaultPreferredAppsLPw(this, 0); 1719 } 1720 1721 // All the changes are done during package scanning. 1722 mSettings.updateInternalDatabaseVersion(); 1723 1724 // can downgrade to reader 1725 mSettings.writeLPr(); 1726 1727 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1728 SystemClock.uptimeMillis()); 1729 1730 1731 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1732 } // synchronized (mPackages) 1733 } // synchronized (mInstallLock) 1734 1735 mInstallerService = new PackageInstallerService(context, this, mAppStagingDir); 1736 1737 // Now after opening every single application zip, make sure they 1738 // are all flushed. Not really needed, but keeps things nice and 1739 // tidy. 1740 Runtime.getRuntime().gc(); 1741 } 1742 1743 @Override 1744 public boolean isFirstBoot() { 1745 return !mRestoredSettings || mPackageUsage.isFirstBoot(); 1746 } 1747 1748 @Override 1749 public boolean isOnlyCoreApps() { 1750 return mOnlyCore; 1751 } 1752 1753 private String getRequiredVerifierLPr() { 1754 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1755 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1756 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1757 1758 String requiredVerifier = null; 1759 1760 final int N = receivers.size(); 1761 for (int i = 0; i < N; i++) { 1762 final ResolveInfo info = receivers.get(i); 1763 1764 if (info.activityInfo == null) { 1765 continue; 1766 } 1767 1768 final String packageName = info.activityInfo.packageName; 1769 1770 final PackageSetting ps = mSettings.mPackages.get(packageName); 1771 if (ps == null) { 1772 continue; 1773 } 1774 1775 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1776 if (!gp.grantedPermissions 1777 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1778 continue; 1779 } 1780 1781 if (requiredVerifier != null) { 1782 throw new RuntimeException("There can be only one required verifier"); 1783 } 1784 1785 requiredVerifier = packageName; 1786 } 1787 1788 return requiredVerifier; 1789 } 1790 1791 @Override 1792 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1793 throws RemoteException { 1794 try { 1795 return super.onTransact(code, data, reply, flags); 1796 } catch (RuntimeException e) { 1797 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1798 Slog.wtf(TAG, "Package Manager Crash", e); 1799 } 1800 throw e; 1801 } 1802 } 1803 1804 void cleanupInstallFailedPackage(PackageSetting ps) { 1805 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1806 removeDataDirsLI(ps.name); 1807 if (ps.codePath != null) { 1808 if (!ps.codePath.delete()) { 1809 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1810 } 1811 } 1812 if (ps.resourcePath != null) { 1813 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1814 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1815 } 1816 } 1817 mSettings.removePackageLPw(ps.name); 1818 } 1819 1820 void readPermissions(File libraryDir, boolean onlyFeatures) { 1821 // Read permissions from .../etc/permission directory. 1822 if (!libraryDir.exists() || !libraryDir.isDirectory()) { 1823 Slog.w(TAG, "No directory " + libraryDir + ", skipping"); 1824 return; 1825 } 1826 if (!libraryDir.canRead()) { 1827 Slog.w(TAG, "Directory " + libraryDir + " cannot be read"); 1828 return; 1829 } 1830 1831 // Iterate over the files in the directory and scan .xml files 1832 for (File f : libraryDir.listFiles()) { 1833 // We'll read platform.xml last 1834 if (f.getPath().endsWith("etc/permissions/platform.xml")) { 1835 continue; 1836 } 1837 1838 if (!f.getPath().endsWith(".xml")) { 1839 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring"); 1840 continue; 1841 } 1842 if (!f.canRead()) { 1843 Slog.w(TAG, "Permissions library file " + f + " cannot be read"); 1844 continue; 1845 } 1846 1847 readPermissionsFromXml(f, onlyFeatures); 1848 } 1849 1850 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence 1851 final File permFile = new File(Environment.getRootDirectory(), 1852 "etc/permissions/platform.xml"); 1853 readPermissionsFromXml(permFile, onlyFeatures); 1854 } 1855 1856 private void readPermissionsFromXml(File permFile, boolean onlyFeatures) { 1857 FileReader permReader = null; 1858 try { 1859 permReader = new FileReader(permFile); 1860 } catch (FileNotFoundException e) { 1861 Slog.w(TAG, "Couldn't find or open permissions file " + permFile); 1862 return; 1863 } 1864 1865 try { 1866 XmlPullParser parser = Xml.newPullParser(); 1867 parser.setInput(permReader); 1868 1869 XmlUtils.beginDocument(parser, "permissions"); 1870 1871 while (true) { 1872 XmlUtils.nextElement(parser); 1873 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) { 1874 break; 1875 } 1876 1877 String name = parser.getName(); 1878 if ("group".equals(name) && !onlyFeatures) { 1879 String gidStr = parser.getAttributeValue(null, "gid"); 1880 if (gidStr != null) { 1881 int gid = Process.getGidForName(gidStr); 1882 mGlobalGids = appendInt(mGlobalGids, gid); 1883 } else { 1884 Slog.w(TAG, "<group> without gid at " 1885 + parser.getPositionDescription()); 1886 } 1887 1888 XmlUtils.skipCurrentTag(parser); 1889 continue; 1890 } else if ("permission".equals(name) && !onlyFeatures) { 1891 String perm = parser.getAttributeValue(null, "name"); 1892 if (perm == null) { 1893 Slog.w(TAG, "<permission> without name at " 1894 + parser.getPositionDescription()); 1895 XmlUtils.skipCurrentTag(parser); 1896 continue; 1897 } 1898 perm = perm.intern(); 1899 readPermission(parser, perm); 1900 1901 } else if ("assign-permission".equals(name) && !onlyFeatures) { 1902 String perm = parser.getAttributeValue(null, "name"); 1903 if (perm == null) { 1904 Slog.w(TAG, "<assign-permission> without name at " 1905 + parser.getPositionDescription()); 1906 XmlUtils.skipCurrentTag(parser); 1907 continue; 1908 } 1909 String uidStr = parser.getAttributeValue(null, "uid"); 1910 if (uidStr == null) { 1911 Slog.w(TAG, "<assign-permission> without uid at " 1912 + parser.getPositionDescription()); 1913 XmlUtils.skipCurrentTag(parser); 1914 continue; 1915 } 1916 int uid = Process.getUidForName(uidStr); 1917 if (uid < 0) { 1918 Slog.w(TAG, "<assign-permission> with unknown uid \"" 1919 + uidStr + "\" at " 1920 + parser.getPositionDescription()); 1921 XmlUtils.skipCurrentTag(parser); 1922 continue; 1923 } 1924 perm = perm.intern(); 1925 HashSet<String> perms = mSystemPermissions.get(uid); 1926 if (perms == null) { 1927 perms = new HashSet<String>(); 1928 mSystemPermissions.put(uid, perms); 1929 } 1930 perms.add(perm); 1931 XmlUtils.skipCurrentTag(parser); 1932 1933 } else if ("library".equals(name) && !onlyFeatures) { 1934 String lname = parser.getAttributeValue(null, "name"); 1935 String lfile = parser.getAttributeValue(null, "file"); 1936 if (lname == null) { 1937 Slog.w(TAG, "<library> without name at " 1938 + parser.getPositionDescription()); 1939 } else if (lfile == null) { 1940 Slog.w(TAG, "<library> without file at " 1941 + parser.getPositionDescription()); 1942 } else { 1943 //Log.i(TAG, "Got library " + lname + " in " + lfile); 1944 mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null)); 1945 } 1946 XmlUtils.skipCurrentTag(parser); 1947 continue; 1948 1949 } else if ("feature".equals(name)) { 1950 String fname = parser.getAttributeValue(null, "name"); 1951 if (fname == null) { 1952 Slog.w(TAG, "<feature> without name at " 1953 + parser.getPositionDescription()); 1954 } else { 1955 //Log.i(TAG, "Got feature " + fname); 1956 FeatureInfo fi = new FeatureInfo(); 1957 fi.name = fname; 1958 mAvailableFeatures.put(fname, fi); 1959 } 1960 XmlUtils.skipCurrentTag(parser); 1961 continue; 1962 1963 } else { 1964 XmlUtils.skipCurrentTag(parser); 1965 continue; 1966 } 1967 1968 } 1969 permReader.close(); 1970 } catch (XmlPullParserException e) { 1971 Slog.w(TAG, "Got execption parsing permissions.", e); 1972 } catch (IOException e) { 1973 Slog.w(TAG, "Got execption parsing permissions.", e); 1974 } 1975 } 1976 1977 void readPermission(XmlPullParser parser, String name) 1978 throws IOException, XmlPullParserException { 1979 1980 name = name.intern(); 1981 1982 BasePermission bp = mSettings.mPermissions.get(name); 1983 if (bp == null) { 1984 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN); 1985 mSettings.mPermissions.put(name, bp); 1986 } 1987 int outerDepth = parser.getDepth(); 1988 int type; 1989 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 1990 && (type != XmlPullParser.END_TAG 1991 || parser.getDepth() > outerDepth)) { 1992 if (type == XmlPullParser.END_TAG 1993 || type == XmlPullParser.TEXT) { 1994 continue; 1995 } 1996 1997 String tagName = parser.getName(); 1998 if ("group".equals(tagName)) { 1999 String gidStr = parser.getAttributeValue(null, "gid"); 2000 if (gidStr != null) { 2001 int gid = Process.getGidForName(gidStr); 2002 bp.gids = appendInt(bp.gids, gid); 2003 } else { 2004 Slog.w(TAG, "<group> without gid at " 2005 + parser.getPositionDescription()); 2006 } 2007 } 2008 XmlUtils.skipCurrentTag(parser); 2009 } 2010 } 2011 2012 static int[] appendInts(int[] cur, int[] add) { 2013 if (add == null) return cur; 2014 if (cur == null) return add; 2015 final int N = add.length; 2016 for (int i=0; i<N; i++) { 2017 cur = appendInt(cur, add[i]); 2018 } 2019 return cur; 2020 } 2021 2022 static int[] removeInts(int[] cur, int[] rem) { 2023 if (rem == null) return cur; 2024 if (cur == null) return cur; 2025 final int N = rem.length; 2026 for (int i=0; i<N; i++) { 2027 cur = removeInt(cur, rem[i]); 2028 } 2029 return cur; 2030 } 2031 2032 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2033 if (!sUserManager.exists(userId)) return null; 2034 final PackageSetting ps = (PackageSetting) p.mExtras; 2035 if (ps == null) { 2036 return null; 2037 } 2038 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 2039 final PackageUserState state = ps.readUserState(userId); 2040 return PackageParser.generatePackageInfo(p, gp.gids, flags, 2041 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 2042 state, userId); 2043 } 2044 2045 @Override 2046 public boolean isPackageAvailable(String packageName, int userId) { 2047 if (!sUserManager.exists(userId)) return false; 2048 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 2049 synchronized (mPackages) { 2050 PackageParser.Package p = mPackages.get(packageName); 2051 if (p != null) { 2052 final PackageSetting ps = (PackageSetting) p.mExtras; 2053 if (ps != null) { 2054 final PackageUserState state = ps.readUserState(userId); 2055 if (state != null) { 2056 return PackageParser.isAvailable(state); 2057 } 2058 } 2059 } 2060 } 2061 return false; 2062 } 2063 2064 @Override 2065 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2066 if (!sUserManager.exists(userId)) return null; 2067 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 2068 // reader 2069 synchronized (mPackages) { 2070 PackageParser.Package p = mPackages.get(packageName); 2071 if (DEBUG_PACKAGE_INFO) 2072 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2073 if (p != null) { 2074 return generatePackageInfo(p, flags, userId); 2075 } 2076 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2077 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2078 } 2079 } 2080 return null; 2081 } 2082 2083 @Override 2084 public String[] currentToCanonicalPackageNames(String[] names) { 2085 String[] out = new String[names.length]; 2086 // reader 2087 synchronized (mPackages) { 2088 for (int i=names.length-1; i>=0; i--) { 2089 PackageSetting ps = mSettings.mPackages.get(names[i]); 2090 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2091 } 2092 } 2093 return out; 2094 } 2095 2096 @Override 2097 public String[] canonicalToCurrentPackageNames(String[] names) { 2098 String[] out = new String[names.length]; 2099 // reader 2100 synchronized (mPackages) { 2101 for (int i=names.length-1; i>=0; i--) { 2102 String cur = mSettings.mRenamedPackages.get(names[i]); 2103 out[i] = cur != null ? cur : names[i]; 2104 } 2105 } 2106 return out; 2107 } 2108 2109 @Override 2110 public int getPackageUid(String packageName, int userId) { 2111 if (!sUserManager.exists(userId)) return -1; 2112 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 2113 // reader 2114 synchronized (mPackages) { 2115 PackageParser.Package p = mPackages.get(packageName); 2116 if(p != null) { 2117 return UserHandle.getUid(userId, p.applicationInfo.uid); 2118 } 2119 PackageSetting ps = mSettings.mPackages.get(packageName); 2120 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2121 return -1; 2122 } 2123 p = ps.pkg; 2124 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2125 } 2126 } 2127 2128 @Override 2129 public int[] getPackageGids(String packageName) { 2130 // reader 2131 synchronized (mPackages) { 2132 PackageParser.Package p = mPackages.get(packageName); 2133 if (DEBUG_PACKAGE_INFO) 2134 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2135 if (p != null) { 2136 final PackageSetting ps = (PackageSetting)p.mExtras; 2137 return ps.getGids(); 2138 } 2139 } 2140 // stupid thing to indicate an error. 2141 return new int[0]; 2142 } 2143 2144 static final PermissionInfo generatePermissionInfo( 2145 BasePermission bp, int flags) { 2146 if (bp.perm != null) { 2147 return PackageParser.generatePermissionInfo(bp.perm, flags); 2148 } 2149 PermissionInfo pi = new PermissionInfo(); 2150 pi.name = bp.name; 2151 pi.packageName = bp.sourcePackage; 2152 pi.nonLocalizedLabel = bp.name; 2153 pi.protectionLevel = bp.protectionLevel; 2154 return pi; 2155 } 2156 2157 @Override 2158 public PermissionInfo getPermissionInfo(String name, int flags) { 2159 // reader 2160 synchronized (mPackages) { 2161 final BasePermission p = mSettings.mPermissions.get(name); 2162 if (p != null) { 2163 return generatePermissionInfo(p, flags); 2164 } 2165 return null; 2166 } 2167 } 2168 2169 @Override 2170 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2171 // reader 2172 synchronized (mPackages) { 2173 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2174 for (BasePermission p : mSettings.mPermissions.values()) { 2175 if (group == null) { 2176 if (p.perm == null || p.perm.info.group == null) { 2177 out.add(generatePermissionInfo(p, flags)); 2178 } 2179 } else { 2180 if (p.perm != null && group.equals(p.perm.info.group)) { 2181 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2182 } 2183 } 2184 } 2185 2186 if (out.size() > 0) { 2187 return out; 2188 } 2189 return mPermissionGroups.containsKey(group) ? out : null; 2190 } 2191 } 2192 2193 @Override 2194 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2195 // reader 2196 synchronized (mPackages) { 2197 return PackageParser.generatePermissionGroupInfo( 2198 mPermissionGroups.get(name), flags); 2199 } 2200 } 2201 2202 @Override 2203 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2204 // reader 2205 synchronized (mPackages) { 2206 final int N = mPermissionGroups.size(); 2207 ArrayList<PermissionGroupInfo> out 2208 = new ArrayList<PermissionGroupInfo>(N); 2209 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2210 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2211 } 2212 return out; 2213 } 2214 } 2215 2216 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2217 int userId) { 2218 if (!sUserManager.exists(userId)) return null; 2219 PackageSetting ps = mSettings.mPackages.get(packageName); 2220 if (ps != null) { 2221 if (ps.pkg == null) { 2222 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2223 flags, userId); 2224 if (pInfo != null) { 2225 return pInfo.applicationInfo; 2226 } 2227 return null; 2228 } 2229 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2230 ps.readUserState(userId), userId); 2231 } 2232 return null; 2233 } 2234 2235 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2236 int userId) { 2237 if (!sUserManager.exists(userId)) return null; 2238 PackageSetting ps = mSettings.mPackages.get(packageName); 2239 if (ps != null) { 2240 PackageParser.Package pkg = ps.pkg; 2241 if (pkg == null) { 2242 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2243 return null; 2244 } 2245 // App code is gone, so we aren't worried about split paths 2246 pkg = new PackageParser.Package(packageName); 2247 pkg.applicationInfo.packageName = packageName; 2248 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2249 pkg.applicationInfo.sourceDir = ps.codePathString; 2250 pkg.applicationInfo.publicSourceDir = ps.resourcePathString; 2251 pkg.applicationInfo.dataDir = 2252 getDataPathForPackage(packageName, 0).getPath(); 2253 pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString; 2254 pkg.applicationInfo.cpuAbi = ps.cpuAbiString; 2255 } 2256 return generatePackageInfo(pkg, flags, userId); 2257 } 2258 return null; 2259 } 2260 2261 @Override 2262 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2263 if (!sUserManager.exists(userId)) return null; 2264 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2265 // writer 2266 synchronized (mPackages) { 2267 PackageParser.Package p = mPackages.get(packageName); 2268 if (DEBUG_PACKAGE_INFO) Log.v( 2269 TAG, "getApplicationInfo " + packageName 2270 + ": " + p); 2271 if (p != null) { 2272 PackageSetting ps = mSettings.mPackages.get(packageName); 2273 if (ps == null) return null; 2274 // Note: isEnabledLP() does not apply here - always return info 2275 return PackageParser.generateApplicationInfo( 2276 p, flags, ps.readUserState(userId), userId); 2277 } 2278 if ("android".equals(packageName)||"system".equals(packageName)) { 2279 return mAndroidApplication; 2280 } 2281 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2282 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2283 } 2284 } 2285 return null; 2286 } 2287 2288 2289 @Override 2290 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2291 mContext.enforceCallingOrSelfPermission( 2292 android.Manifest.permission.CLEAR_APP_CACHE, null); 2293 // Queue up an async operation since clearing cache may take a little while. 2294 mHandler.post(new Runnable() { 2295 public void run() { 2296 mHandler.removeCallbacks(this); 2297 int retCode = -1; 2298 synchronized (mInstallLock) { 2299 retCode = mInstaller.freeCache(freeStorageSize); 2300 if (retCode < 0) { 2301 Slog.w(TAG, "Couldn't clear application caches"); 2302 } 2303 } 2304 if (observer != null) { 2305 try { 2306 observer.onRemoveCompleted(null, (retCode >= 0)); 2307 } catch (RemoteException e) { 2308 Slog.w(TAG, "RemoveException when invoking call back"); 2309 } 2310 } 2311 } 2312 }); 2313 } 2314 2315 @Override 2316 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2317 mContext.enforceCallingOrSelfPermission( 2318 android.Manifest.permission.CLEAR_APP_CACHE, null); 2319 // Queue up an async operation since clearing cache may take a little while. 2320 mHandler.post(new Runnable() { 2321 public void run() { 2322 mHandler.removeCallbacks(this); 2323 int retCode = -1; 2324 synchronized (mInstallLock) { 2325 retCode = mInstaller.freeCache(freeStorageSize); 2326 if (retCode < 0) { 2327 Slog.w(TAG, "Couldn't clear application caches"); 2328 } 2329 } 2330 if(pi != null) { 2331 try { 2332 // Callback via pending intent 2333 int code = (retCode >= 0) ? 1 : 0; 2334 pi.sendIntent(null, code, null, 2335 null, null); 2336 } catch (SendIntentException e1) { 2337 Slog.i(TAG, "Failed to send pending intent"); 2338 } 2339 } 2340 } 2341 }); 2342 } 2343 2344 void freeStorage(long freeStorageSize) throws IOException { 2345 synchronized (mInstallLock) { 2346 if (mInstaller.freeCache(freeStorageSize) < 0) { 2347 throw new IOException("Failed to free enough space"); 2348 } 2349 } 2350 } 2351 2352 @Override 2353 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2354 if (!sUserManager.exists(userId)) return null; 2355 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2356 synchronized (mPackages) { 2357 PackageParser.Activity a = mActivities.mActivities.get(component); 2358 2359 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2360 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2361 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2362 if (ps == null) return null; 2363 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2364 userId); 2365 } 2366 if (mResolveComponentName.equals(component)) { 2367 return mResolveActivity; 2368 } 2369 } 2370 return null; 2371 } 2372 2373 @Override 2374 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2375 String resolvedType) { 2376 synchronized (mPackages) { 2377 PackageParser.Activity a = mActivities.mActivities.get(component); 2378 if (a == null) { 2379 return false; 2380 } 2381 for (int i=0; i<a.intents.size(); i++) { 2382 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2383 intent.getData(), intent.getCategories(), TAG) >= 0) { 2384 return true; 2385 } 2386 } 2387 return false; 2388 } 2389 } 2390 2391 @Override 2392 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2393 if (!sUserManager.exists(userId)) return null; 2394 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2395 synchronized (mPackages) { 2396 PackageParser.Activity a = mReceivers.mActivities.get(component); 2397 if (DEBUG_PACKAGE_INFO) Log.v( 2398 TAG, "getReceiverInfo " + component + ": " + a); 2399 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2400 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2401 if (ps == null) return null; 2402 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2403 userId); 2404 } 2405 } 2406 return null; 2407 } 2408 2409 @Override 2410 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2411 if (!sUserManager.exists(userId)) return null; 2412 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2413 synchronized (mPackages) { 2414 PackageParser.Service s = mServices.mServices.get(component); 2415 if (DEBUG_PACKAGE_INFO) Log.v( 2416 TAG, "getServiceInfo " + component + ": " + s); 2417 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2418 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2419 if (ps == null) return null; 2420 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2421 userId); 2422 } 2423 } 2424 return null; 2425 } 2426 2427 @Override 2428 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2429 if (!sUserManager.exists(userId)) return null; 2430 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2431 synchronized (mPackages) { 2432 PackageParser.Provider p = mProviders.mProviders.get(component); 2433 if (DEBUG_PACKAGE_INFO) Log.v( 2434 TAG, "getProviderInfo " + component + ": " + p); 2435 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2436 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2437 if (ps == null) return null; 2438 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2439 userId); 2440 } 2441 } 2442 return null; 2443 } 2444 2445 @Override 2446 public String[] getSystemSharedLibraryNames() { 2447 Set<String> libSet; 2448 synchronized (mPackages) { 2449 libSet = mSharedLibraries.keySet(); 2450 int size = libSet.size(); 2451 if (size > 0) { 2452 String[] libs = new String[size]; 2453 libSet.toArray(libs); 2454 return libs; 2455 } 2456 } 2457 return null; 2458 } 2459 2460 @Override 2461 public FeatureInfo[] getSystemAvailableFeatures() { 2462 Collection<FeatureInfo> featSet; 2463 synchronized (mPackages) { 2464 featSet = mAvailableFeatures.values(); 2465 int size = featSet.size(); 2466 if (size > 0) { 2467 FeatureInfo[] features = new FeatureInfo[size+1]; 2468 featSet.toArray(features); 2469 FeatureInfo fi = new FeatureInfo(); 2470 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2471 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2472 features[size] = fi; 2473 return features; 2474 } 2475 } 2476 return null; 2477 } 2478 2479 @Override 2480 public boolean hasSystemFeature(String name) { 2481 synchronized (mPackages) { 2482 return mAvailableFeatures.containsKey(name); 2483 } 2484 } 2485 2486 private void checkValidCaller(int uid, int userId) { 2487 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2488 return; 2489 2490 throw new SecurityException("Caller uid=" + uid 2491 + " is not privileged to communicate with user=" + userId); 2492 } 2493 2494 @Override 2495 public int checkPermission(String permName, String pkgName) { 2496 synchronized (mPackages) { 2497 PackageParser.Package p = mPackages.get(pkgName); 2498 if (p != null && p.mExtras != null) { 2499 PackageSetting ps = (PackageSetting)p.mExtras; 2500 if (ps.sharedUser != null) { 2501 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2502 return PackageManager.PERMISSION_GRANTED; 2503 } 2504 } else if (ps.grantedPermissions.contains(permName)) { 2505 return PackageManager.PERMISSION_GRANTED; 2506 } 2507 } 2508 } 2509 return PackageManager.PERMISSION_DENIED; 2510 } 2511 2512 @Override 2513 public int checkUidPermission(String permName, int uid) { 2514 synchronized (mPackages) { 2515 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2516 if (obj != null) { 2517 GrantedPermissions gp = (GrantedPermissions)obj; 2518 if (gp.grantedPermissions.contains(permName)) { 2519 return PackageManager.PERMISSION_GRANTED; 2520 } 2521 } else { 2522 HashSet<String> perms = mSystemPermissions.get(uid); 2523 if (perms != null && perms.contains(permName)) { 2524 return PackageManager.PERMISSION_GRANTED; 2525 } 2526 } 2527 } 2528 return PackageManager.PERMISSION_DENIED; 2529 } 2530 2531 /** 2532 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2533 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2534 * @param message the message to log on security exception 2535 */ 2536 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2537 String message) { 2538 if (userId < 0) { 2539 throw new IllegalArgumentException("Invalid userId " + userId); 2540 } 2541 if (userId == UserHandle.getUserId(callingUid)) return; 2542 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2543 if (requireFullPermission) { 2544 mContext.enforceCallingOrSelfPermission( 2545 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2546 } else { 2547 try { 2548 mContext.enforceCallingOrSelfPermission( 2549 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2550 } catch (SecurityException se) { 2551 mContext.enforceCallingOrSelfPermission( 2552 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2553 } 2554 } 2555 } 2556 } 2557 2558 private BasePermission findPermissionTreeLP(String permName) { 2559 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2560 if (permName.startsWith(bp.name) && 2561 permName.length() > bp.name.length() && 2562 permName.charAt(bp.name.length()) == '.') { 2563 return bp; 2564 } 2565 } 2566 return null; 2567 } 2568 2569 private BasePermission checkPermissionTreeLP(String permName) { 2570 if (permName != null) { 2571 BasePermission bp = findPermissionTreeLP(permName); 2572 if (bp != null) { 2573 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2574 return bp; 2575 } 2576 throw new SecurityException("Calling uid " 2577 + Binder.getCallingUid() 2578 + " is not allowed to add to permission tree " 2579 + bp.name + " owned by uid " + bp.uid); 2580 } 2581 } 2582 throw new SecurityException("No permission tree found for " + permName); 2583 } 2584 2585 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2586 if (s1 == null) { 2587 return s2 == null; 2588 } 2589 if (s2 == null) { 2590 return false; 2591 } 2592 if (s1.getClass() != s2.getClass()) { 2593 return false; 2594 } 2595 return s1.equals(s2); 2596 } 2597 2598 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2599 if (pi1.icon != pi2.icon) return false; 2600 if (pi1.logo != pi2.logo) return false; 2601 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2602 if (!compareStrings(pi1.name, pi2.name)) return false; 2603 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2604 // We'll take care of setting this one. 2605 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2606 // These are not currently stored in settings. 2607 //if (!compareStrings(pi1.group, pi2.group)) return false; 2608 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2609 //if (pi1.labelRes != pi2.labelRes) return false; 2610 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2611 return true; 2612 } 2613 2614 int permissionInfoFootprint(PermissionInfo info) { 2615 int size = info.name.length(); 2616 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2617 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2618 return size; 2619 } 2620 2621 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2622 int size = 0; 2623 for (BasePermission perm : mSettings.mPermissions.values()) { 2624 if (perm.uid == tree.uid) { 2625 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2626 } 2627 } 2628 return size; 2629 } 2630 2631 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2632 // We calculate the max size of permissions defined by this uid and throw 2633 // if that plus the size of 'info' would exceed our stated maximum. 2634 if (tree.uid != Process.SYSTEM_UID) { 2635 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2636 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2637 throw new SecurityException("Permission tree size cap exceeded"); 2638 } 2639 } 2640 } 2641 2642 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2643 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2644 throw new SecurityException("Label must be specified in permission"); 2645 } 2646 BasePermission tree = checkPermissionTreeLP(info.name); 2647 BasePermission bp = mSettings.mPermissions.get(info.name); 2648 boolean added = bp == null; 2649 boolean changed = true; 2650 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2651 if (added) { 2652 enforcePermissionCapLocked(info, tree); 2653 bp = new BasePermission(info.name, tree.sourcePackage, 2654 BasePermission.TYPE_DYNAMIC); 2655 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2656 throw new SecurityException( 2657 "Not allowed to modify non-dynamic permission " 2658 + info.name); 2659 } else { 2660 if (bp.protectionLevel == fixedLevel 2661 && bp.perm.owner.equals(tree.perm.owner) 2662 && bp.uid == tree.uid 2663 && comparePermissionInfos(bp.perm.info, info)) { 2664 changed = false; 2665 } 2666 } 2667 bp.protectionLevel = fixedLevel; 2668 info = new PermissionInfo(info); 2669 info.protectionLevel = fixedLevel; 2670 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2671 bp.perm.info.packageName = tree.perm.info.packageName; 2672 bp.uid = tree.uid; 2673 if (added) { 2674 mSettings.mPermissions.put(info.name, bp); 2675 } 2676 if (changed) { 2677 if (!async) { 2678 mSettings.writeLPr(); 2679 } else { 2680 scheduleWriteSettingsLocked(); 2681 } 2682 } 2683 return added; 2684 } 2685 2686 @Override 2687 public boolean addPermission(PermissionInfo info) { 2688 synchronized (mPackages) { 2689 return addPermissionLocked(info, false); 2690 } 2691 } 2692 2693 @Override 2694 public boolean addPermissionAsync(PermissionInfo info) { 2695 synchronized (mPackages) { 2696 return addPermissionLocked(info, true); 2697 } 2698 } 2699 2700 @Override 2701 public void removePermission(String name) { 2702 synchronized (mPackages) { 2703 checkPermissionTreeLP(name); 2704 BasePermission bp = mSettings.mPermissions.get(name); 2705 if (bp != null) { 2706 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2707 throw new SecurityException( 2708 "Not allowed to modify non-dynamic permission " 2709 + name); 2710 } 2711 mSettings.mPermissions.remove(name); 2712 mSettings.writeLPr(); 2713 } 2714 } 2715 } 2716 2717 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2718 int index = pkg.requestedPermissions.indexOf(bp.name); 2719 if (index == -1) { 2720 throw new SecurityException("Package " + pkg.packageName 2721 + " has not requested permission " + bp.name); 2722 } 2723 boolean isNormal = 2724 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2725 == PermissionInfo.PROTECTION_NORMAL); 2726 boolean isDangerous = 2727 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2728 == PermissionInfo.PROTECTION_DANGEROUS); 2729 boolean isDevelopment = 2730 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2731 2732 if (!isNormal && !isDangerous && !isDevelopment) { 2733 throw new SecurityException("Permission " + bp.name 2734 + " is not a changeable permission type"); 2735 } 2736 2737 if (isNormal || isDangerous) { 2738 if (pkg.requestedPermissionsRequired.get(index)) { 2739 throw new SecurityException("Can't change " + bp.name 2740 + ". It is required by the application"); 2741 } 2742 } 2743 } 2744 2745 @Override 2746 public void grantPermission(String packageName, String permissionName) { 2747 mContext.enforceCallingOrSelfPermission( 2748 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2749 synchronized (mPackages) { 2750 final PackageParser.Package pkg = mPackages.get(packageName); 2751 if (pkg == null) { 2752 throw new IllegalArgumentException("Unknown package: " + packageName); 2753 } 2754 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2755 if (bp == null) { 2756 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2757 } 2758 2759 checkGrantRevokePermissions(pkg, bp); 2760 2761 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2762 if (ps == null) { 2763 return; 2764 } 2765 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2766 if (gp.grantedPermissions.add(permissionName)) { 2767 if (ps.haveGids) { 2768 gp.gids = appendInts(gp.gids, bp.gids); 2769 } 2770 mSettings.writeLPr(); 2771 } 2772 } 2773 } 2774 2775 @Override 2776 public void revokePermission(String packageName, String permissionName) { 2777 int changedAppId = -1; 2778 2779 synchronized (mPackages) { 2780 final PackageParser.Package pkg = mPackages.get(packageName); 2781 if (pkg == null) { 2782 throw new IllegalArgumentException("Unknown package: " + packageName); 2783 } 2784 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2785 mContext.enforceCallingOrSelfPermission( 2786 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2787 } 2788 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2789 if (bp == null) { 2790 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2791 } 2792 2793 checkGrantRevokePermissions(pkg, bp); 2794 2795 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2796 if (ps == null) { 2797 return; 2798 } 2799 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2800 if (gp.grantedPermissions.remove(permissionName)) { 2801 gp.grantedPermissions.remove(permissionName); 2802 if (ps.haveGids) { 2803 gp.gids = removeInts(gp.gids, bp.gids); 2804 } 2805 mSettings.writeLPr(); 2806 changedAppId = ps.appId; 2807 } 2808 } 2809 2810 if (changedAppId >= 0) { 2811 // We changed the perm on someone, kill its processes. 2812 IActivityManager am = ActivityManagerNative.getDefault(); 2813 if (am != null) { 2814 final int callingUserId = UserHandle.getCallingUserId(); 2815 final long ident = Binder.clearCallingIdentity(); 2816 try { 2817 //XXX we should only revoke for the calling user's app permissions, 2818 // but for now we impact all users. 2819 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2820 // "revoke " + permissionName); 2821 int[] users = sUserManager.getUserIds(); 2822 for (int user : users) { 2823 am.killUid(UserHandle.getUid(user, changedAppId), 2824 "revoke " + permissionName); 2825 } 2826 } catch (RemoteException e) { 2827 } finally { 2828 Binder.restoreCallingIdentity(ident); 2829 } 2830 } 2831 } 2832 } 2833 2834 @Override 2835 public boolean isProtectedBroadcast(String actionName) { 2836 synchronized (mPackages) { 2837 return mProtectedBroadcasts.contains(actionName); 2838 } 2839 } 2840 2841 @Override 2842 public int checkSignatures(String pkg1, String pkg2) { 2843 synchronized (mPackages) { 2844 final PackageParser.Package p1 = mPackages.get(pkg1); 2845 final PackageParser.Package p2 = mPackages.get(pkg2); 2846 if (p1 == null || p1.mExtras == null 2847 || p2 == null || p2.mExtras == null) { 2848 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2849 } 2850 return compareSignatures(p1.mSignatures, p2.mSignatures); 2851 } 2852 } 2853 2854 @Override 2855 public int checkUidSignatures(int uid1, int uid2) { 2856 // Map to base uids. 2857 uid1 = UserHandle.getAppId(uid1); 2858 uid2 = UserHandle.getAppId(uid2); 2859 // reader 2860 synchronized (mPackages) { 2861 Signature[] s1; 2862 Signature[] s2; 2863 Object obj = mSettings.getUserIdLPr(uid1); 2864 if (obj != null) { 2865 if (obj instanceof SharedUserSetting) { 2866 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2867 } else if (obj instanceof PackageSetting) { 2868 s1 = ((PackageSetting)obj).signatures.mSignatures; 2869 } else { 2870 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2871 } 2872 } else { 2873 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2874 } 2875 obj = mSettings.getUserIdLPr(uid2); 2876 if (obj != null) { 2877 if (obj instanceof SharedUserSetting) { 2878 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2879 } else if (obj instanceof PackageSetting) { 2880 s2 = ((PackageSetting)obj).signatures.mSignatures; 2881 } else { 2882 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2883 } 2884 } else { 2885 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2886 } 2887 return compareSignatures(s1, s2); 2888 } 2889 } 2890 2891 /** 2892 * Compares two sets of signatures. Returns: 2893 * <br /> 2894 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2895 * <br /> 2896 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2897 * <br /> 2898 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2899 * <br /> 2900 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2901 * <br /> 2902 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2903 */ 2904 static int compareSignatures(Signature[] s1, Signature[] s2) { 2905 if (s1 == null) { 2906 return s2 == null 2907 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2908 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2909 } 2910 2911 if (s2 == null) { 2912 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2913 } 2914 2915 if (s1.length != s2.length) { 2916 return PackageManager.SIGNATURE_NO_MATCH; 2917 } 2918 2919 // Since both signature sets are of size 1, we can compare without HashSets. 2920 if (s1.length == 1) { 2921 return s1[0].equals(s2[0]) ? 2922 PackageManager.SIGNATURE_MATCH : 2923 PackageManager.SIGNATURE_NO_MATCH; 2924 } 2925 2926 HashSet<Signature> set1 = new HashSet<Signature>(); 2927 for (Signature sig : s1) { 2928 set1.add(sig); 2929 } 2930 HashSet<Signature> set2 = new HashSet<Signature>(); 2931 for (Signature sig : s2) { 2932 set2.add(sig); 2933 } 2934 // Make sure s2 contains all signatures in s1. 2935 if (set1.equals(set2)) { 2936 return PackageManager.SIGNATURE_MATCH; 2937 } 2938 return PackageManager.SIGNATURE_NO_MATCH; 2939 } 2940 2941 /** 2942 * If the database version for this type of package (internal storage or 2943 * external storage) is less than the version where package signatures 2944 * were updated, return true. 2945 */ 2946 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2947 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2948 DatabaseVersion.SIGNATURE_END_ENTITY)) 2949 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2950 DatabaseVersion.SIGNATURE_END_ENTITY)); 2951 } 2952 2953 /** 2954 * Used for backward compatibility to make sure any packages with 2955 * certificate chains get upgraded to the new style. {@code existingSigs} 2956 * will be in the old format (since they were stored on disk from before the 2957 * system upgrade) and {@code scannedSigs} will be in the newer format. 2958 */ 2959 private int compareSignaturesCompat(PackageSignatures existingSigs, 2960 PackageParser.Package scannedPkg) { 2961 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2962 return PackageManager.SIGNATURE_NO_MATCH; 2963 } 2964 2965 HashSet<Signature> existingSet = new HashSet<Signature>(); 2966 for (Signature sig : existingSigs.mSignatures) { 2967 existingSet.add(sig); 2968 } 2969 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2970 for (Signature sig : scannedPkg.mSignatures) { 2971 try { 2972 Signature[] chainSignatures = sig.getChainSignatures(); 2973 for (Signature chainSig : chainSignatures) { 2974 scannedCompatSet.add(chainSig); 2975 } 2976 } catch (CertificateEncodingException e) { 2977 scannedCompatSet.add(sig); 2978 } 2979 } 2980 /* 2981 * Make sure the expanded scanned set contains all signatures in the 2982 * existing one. 2983 */ 2984 if (scannedCompatSet.equals(existingSet)) { 2985 // Migrate the old signatures to the new scheme. 2986 existingSigs.assignSignatures(scannedPkg.mSignatures); 2987 // The new KeySets will be re-added later in the scanning process. 2988 mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName); 2989 return PackageManager.SIGNATURE_MATCH; 2990 } 2991 return PackageManager.SIGNATURE_NO_MATCH; 2992 } 2993 2994 @Override 2995 public String[] getPackagesForUid(int uid) { 2996 uid = UserHandle.getAppId(uid); 2997 // reader 2998 synchronized (mPackages) { 2999 Object obj = mSettings.getUserIdLPr(uid); 3000 if (obj instanceof SharedUserSetting) { 3001 final SharedUserSetting sus = (SharedUserSetting) obj; 3002 final int N = sus.packages.size(); 3003 final String[] res = new String[N]; 3004 final Iterator<PackageSetting> it = sus.packages.iterator(); 3005 int i = 0; 3006 while (it.hasNext()) { 3007 res[i++] = it.next().name; 3008 } 3009 return res; 3010 } else if (obj instanceof PackageSetting) { 3011 final PackageSetting ps = (PackageSetting) obj; 3012 return new String[] { ps.name }; 3013 } 3014 } 3015 return null; 3016 } 3017 3018 @Override 3019 public String getNameForUid(int uid) { 3020 // reader 3021 synchronized (mPackages) { 3022 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3023 if (obj instanceof SharedUserSetting) { 3024 final SharedUserSetting sus = (SharedUserSetting) obj; 3025 return sus.name + ":" + sus.userId; 3026 } else if (obj instanceof PackageSetting) { 3027 final PackageSetting ps = (PackageSetting) obj; 3028 return ps.name; 3029 } 3030 } 3031 return null; 3032 } 3033 3034 @Override 3035 public int getUidForSharedUser(String sharedUserName) { 3036 if(sharedUserName == null) { 3037 return -1; 3038 } 3039 // reader 3040 synchronized (mPackages) { 3041 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 3042 if (suid == null) { 3043 return -1; 3044 } 3045 return suid.userId; 3046 } 3047 } 3048 3049 @Override 3050 public int getFlagsForUid(int uid) { 3051 synchronized (mPackages) { 3052 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3053 if (obj instanceof SharedUserSetting) { 3054 final SharedUserSetting sus = (SharedUserSetting) obj; 3055 return sus.pkgFlags; 3056 } else if (obj instanceof PackageSetting) { 3057 final PackageSetting ps = (PackageSetting) obj; 3058 return ps.pkgFlags; 3059 } 3060 } 3061 return 0; 3062 } 3063 3064 @Override 3065 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3066 int flags, int userId) { 3067 if (!sUserManager.exists(userId)) return null; 3068 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 3069 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3070 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3071 } 3072 3073 @Override 3074 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3075 IntentFilter filter, int match, ComponentName activity) { 3076 final int userId = UserHandle.getCallingUserId(); 3077 if (DEBUG_PREFERRED) { 3078 Log.v(TAG, "setLastChosenActivity intent=" + intent 3079 + " resolvedType=" + resolvedType 3080 + " flags=" + flags 3081 + " filter=" + filter 3082 + " match=" + match 3083 + " activity=" + activity); 3084 filter.dump(new PrintStreamPrinter(System.out), " "); 3085 } 3086 intent.setComponent(null); 3087 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3088 // Find any earlier preferred or last chosen entries and nuke them 3089 findPreferredActivity(intent, resolvedType, 3090 flags, query, 0, false, true, false, userId); 3091 // Add the new activity as the last chosen for this filter 3092 addPreferredActivityInternal(filter, match, null, activity, false, userId); 3093 } 3094 3095 @Override 3096 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3097 final int userId = UserHandle.getCallingUserId(); 3098 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3099 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3100 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3101 false, false, false, userId); 3102 } 3103 3104 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3105 int flags, List<ResolveInfo> query, int userId) { 3106 if (query != null) { 3107 final int N = query.size(); 3108 if (N == 1) { 3109 return query.get(0); 3110 } else if (N > 1) { 3111 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3112 // If there is more than one activity with the same priority, 3113 // then let the user decide between them. 3114 ResolveInfo r0 = query.get(0); 3115 ResolveInfo r1 = query.get(1); 3116 if (DEBUG_INTENT_MATCHING || debug) { 3117 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3118 + r1.activityInfo.name + "=" + r1.priority); 3119 } 3120 // If the first activity has a higher priority, or a different 3121 // default, then it is always desireable to pick it. 3122 if (r0.priority != r1.priority 3123 || r0.preferredOrder != r1.preferredOrder 3124 || r0.isDefault != r1.isDefault) { 3125 return query.get(0); 3126 } 3127 // If we have saved a preference for a preferred activity for 3128 // this Intent, use that. 3129 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3130 flags, query, r0.priority, true, false, debug, userId); 3131 if (ri != null) { 3132 return ri; 3133 } 3134 if (userId != 0) { 3135 ri = new ResolveInfo(mResolveInfo); 3136 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3137 ri.activityInfo.applicationInfo = new ApplicationInfo( 3138 ri.activityInfo.applicationInfo); 3139 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3140 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3141 return ri; 3142 } 3143 return mResolveInfo; 3144 } 3145 } 3146 return null; 3147 } 3148 3149 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3150 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3151 final int N = query.size(); 3152 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3153 .get(userId); 3154 // Get the list of persistent preferred activities that handle the intent 3155 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3156 List<PersistentPreferredActivity> pprefs = ppir != null 3157 ? ppir.queryIntent(intent, resolvedType, 3158 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3159 : null; 3160 if (pprefs != null && pprefs.size() > 0) { 3161 final int M = pprefs.size(); 3162 for (int i=0; i<M; i++) { 3163 final PersistentPreferredActivity ppa = pprefs.get(i); 3164 if (DEBUG_PREFERRED || debug) { 3165 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3166 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3167 + "\n component=" + ppa.mComponent); 3168 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3169 } 3170 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3171 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3172 if (DEBUG_PREFERRED || debug) { 3173 Slog.v(TAG, "Found persistent preferred activity:"); 3174 if (ai != null) { 3175 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3176 } else { 3177 Slog.v(TAG, " null"); 3178 } 3179 } 3180 if (ai == null) { 3181 // This previously registered persistent preferred activity 3182 // component is no longer known. Ignore it and do NOT remove it. 3183 continue; 3184 } 3185 for (int j=0; j<N; j++) { 3186 final ResolveInfo ri = query.get(j); 3187 if (!ri.activityInfo.applicationInfo.packageName 3188 .equals(ai.applicationInfo.packageName)) { 3189 continue; 3190 } 3191 if (!ri.activityInfo.name.equals(ai.name)) { 3192 continue; 3193 } 3194 // Found a persistent preference that can handle the intent. 3195 if (DEBUG_PREFERRED || debug) { 3196 Slog.v(TAG, "Returning persistent preferred activity: " + 3197 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3198 } 3199 return ri; 3200 } 3201 } 3202 } 3203 return null; 3204 } 3205 3206 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3207 List<ResolveInfo> query, int priority, boolean always, 3208 boolean removeMatches, boolean debug, int userId) { 3209 if (!sUserManager.exists(userId)) return null; 3210 // writer 3211 synchronized (mPackages) { 3212 if (intent.getSelector() != null) { 3213 intent = intent.getSelector(); 3214 } 3215 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3216 3217 // Try to find a matching persistent preferred activity. 3218 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3219 debug, userId); 3220 3221 // If a persistent preferred activity matched, use it. 3222 if (pri != null) { 3223 return pri; 3224 } 3225 3226 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3227 // Get the list of preferred activities that handle the intent 3228 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3229 List<PreferredActivity> prefs = pir != null 3230 ? pir.queryIntent(intent, resolvedType, 3231 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3232 : null; 3233 if (prefs != null && prefs.size() > 0) { 3234 // First figure out how good the original match set is. 3235 // We will only allow preferred activities that came 3236 // from the same match quality. 3237 int match = 0; 3238 3239 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3240 3241 final int N = query.size(); 3242 for (int j=0; j<N; j++) { 3243 final ResolveInfo ri = query.get(j); 3244 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3245 + ": 0x" + Integer.toHexString(match)); 3246 if (ri.match > match) { 3247 match = ri.match; 3248 } 3249 } 3250 3251 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3252 + Integer.toHexString(match)); 3253 3254 match &= IntentFilter.MATCH_CATEGORY_MASK; 3255 final int M = prefs.size(); 3256 for (int i=0; i<M; i++) { 3257 final PreferredActivity pa = prefs.get(i); 3258 if (DEBUG_PREFERRED || debug) { 3259 Slog.v(TAG, "Checking PreferredActivity ds=" 3260 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3261 + "\n component=" + pa.mPref.mComponent); 3262 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3263 } 3264 if (pa.mPref.mMatch != match) { 3265 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3266 + Integer.toHexString(pa.mPref.mMatch)); 3267 continue; 3268 } 3269 // If it's not an "always" type preferred activity and that's what we're 3270 // looking for, skip it. 3271 if (always && !pa.mPref.mAlways) { 3272 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3273 continue; 3274 } 3275 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3276 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3277 if (DEBUG_PREFERRED || debug) { 3278 Slog.v(TAG, "Found preferred activity:"); 3279 if (ai != null) { 3280 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3281 } else { 3282 Slog.v(TAG, " null"); 3283 } 3284 } 3285 if (ai == null) { 3286 // This previously registered preferred activity 3287 // component is no longer known. Most likely an update 3288 // to the app was installed and in the new version this 3289 // component no longer exists. Clean it up by removing 3290 // it from the preferred activities list, and skip it. 3291 Slog.w(TAG, "Removing dangling preferred activity: " 3292 + pa.mPref.mComponent); 3293 pir.removeFilter(pa); 3294 continue; 3295 } 3296 for (int j=0; j<N; j++) { 3297 final ResolveInfo ri = query.get(j); 3298 if (!ri.activityInfo.applicationInfo.packageName 3299 .equals(ai.applicationInfo.packageName)) { 3300 continue; 3301 } 3302 if (!ri.activityInfo.name.equals(ai.name)) { 3303 continue; 3304 } 3305 3306 if (removeMatches) { 3307 pir.removeFilter(pa); 3308 if (DEBUG_PREFERRED) { 3309 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3310 } 3311 break; 3312 } 3313 3314 // Okay we found a previously set preferred or last chosen app. 3315 // If the result set is different from when this 3316 // was created, we need to clear it and re-ask the 3317 // user their preference, if we're looking for an "always" type entry. 3318 if (always && !pa.mPref.sameSet(query, priority)) { 3319 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3320 + intent + " type " + resolvedType); 3321 if (DEBUG_PREFERRED) { 3322 Slog.v(TAG, "Removing preferred activity since set changed " 3323 + pa.mPref.mComponent); 3324 } 3325 pir.removeFilter(pa); 3326 // Re-add the filter as a "last chosen" entry (!always) 3327 PreferredActivity lastChosen = new PreferredActivity( 3328 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3329 pir.addFilter(lastChosen); 3330 mSettings.writePackageRestrictionsLPr(userId); 3331 return null; 3332 } 3333 3334 // Yay! Either the set matched or we're looking for the last chosen 3335 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3336 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3337 mSettings.writePackageRestrictionsLPr(userId); 3338 return ri; 3339 } 3340 } 3341 } 3342 mSettings.writePackageRestrictionsLPr(userId); 3343 } 3344 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3345 return null; 3346 } 3347 3348 /* 3349 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3350 */ 3351 @Override 3352 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3353 int targetUserId) { 3354 mContext.enforceCallingOrSelfPermission( 3355 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3356 List<CrossProfileIntentFilter> matches = 3357 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3358 if (matches != null) { 3359 int size = matches.size(); 3360 for (int i = 0; i < size; i++) { 3361 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3362 } 3363 } 3364 3365 ArrayList<String> packageNames = null; 3366 SparseArray<ArrayList<String>> fromSource = 3367 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3368 if (fromSource != null) { 3369 packageNames = fromSource.get(targetUserId); 3370 } 3371 if (packageNames.contains(intent.getPackage())) { 3372 return true; 3373 } 3374 // We need the package name, so we try to resolve with the loosest flags possible 3375 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3376 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3377 int count = resolveInfos.size(); 3378 for (int i = 0; i < count; i++) { 3379 ResolveInfo resolveInfo = resolveInfos.get(i); 3380 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3381 return true; 3382 } 3383 } 3384 return false; 3385 } 3386 3387 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3388 String resolvedType, int userId) { 3389 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3390 if (resolver != null) { 3391 return resolver.queryIntent(intent, resolvedType, false, userId); 3392 } 3393 return null; 3394 } 3395 3396 @Override 3397 public List<ResolveInfo> queryIntentActivities(Intent intent, 3398 String resolvedType, int flags, int userId) { 3399 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3400 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3401 ComponentName comp = intent.getComponent(); 3402 if (comp == null) { 3403 if (intent.getSelector() != null) { 3404 intent = intent.getSelector(); 3405 comp = intent.getComponent(); 3406 } 3407 } 3408 3409 if (comp != null) { 3410 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3411 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3412 if (ai != null) { 3413 final ResolveInfo ri = new ResolveInfo(); 3414 ri.activityInfo = ai; 3415 list.add(ri); 3416 } 3417 return list; 3418 } 3419 3420 // reader 3421 synchronized (mPackages) { 3422 final String pkgName = intent.getPackage(); 3423 if (pkgName == null) { 3424 //Check if the intent needs to be forwarded to another user for this package 3425 ArrayList<ResolveInfo> crossProfileResult = 3426 queryIntentActivitiesCrossProfilePackage( 3427 intent, resolvedType, flags, userId); 3428 if (!crossProfileResult.isEmpty()) { 3429 // Skip the current profile 3430 return crossProfileResult; 3431 } 3432 List<ResolveInfo> result; 3433 List<CrossProfileIntentFilter> matchingFilters = 3434 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3435 // Check for results that need to skip the current profile. 3436 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3437 resolvedType, flags, userId); 3438 if (resolveInfo != null) { 3439 result = new ArrayList<ResolveInfo>(1); 3440 result.add(resolveInfo); 3441 return result; 3442 } 3443 // Check for results in the current profile. 3444 result = mActivities.queryIntent(intent, resolvedType, flags, userId); 3445 // Check for cross profile results. 3446 resolveInfo = queryCrossProfileIntents( 3447 matchingFilters, intent, resolvedType, flags, userId); 3448 if (resolveInfo != null) { 3449 result.add(resolveInfo); 3450 } 3451 return result; 3452 } 3453 final PackageParser.Package pkg = mPackages.get(pkgName); 3454 if (pkg != null) { 3455 ArrayList<ResolveInfo> crossProfileResult = 3456 queryIntentActivitiesCrossProfilePackage( 3457 intent, resolvedType, flags, userId, pkg, pkgName); 3458 if (!crossProfileResult.isEmpty()) { 3459 // Skip the current profile 3460 return crossProfileResult; 3461 } 3462 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3463 pkg.activities, userId); 3464 } 3465 return new ArrayList<ResolveInfo>(); 3466 } 3467 } 3468 3469 private ResolveInfo querySkipCurrentProfileIntents( 3470 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3471 int flags, int sourceUserId) { 3472 if (matchingFilters != null) { 3473 int size = matchingFilters.size(); 3474 for (int i = 0; i < size; i ++) { 3475 CrossProfileIntentFilter filter = matchingFilters.get(i); 3476 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3477 // Checking if there are activities in the target user that can handle the 3478 // intent. 3479 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3480 flags, sourceUserId); 3481 if (resolveInfo != null) { 3482 return createForwardingResolveInfo( 3483 filter, sourceUserId, filter.getTargetUserId()); 3484 } 3485 } 3486 } 3487 } 3488 return null; 3489 } 3490 3491 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3492 Intent intent, String resolvedType, int flags, int userId) { 3493 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3494 SparseArray<ArrayList<String>> sourceForwardingInfo = 3495 mSettings.mCrossProfilePackageInfo.get(userId); 3496 if (sourceForwardingInfo != null) { 3497 int NI = sourceForwardingInfo.size(); 3498 for (int i = 0; i < NI; i++) { 3499 int targetUserId = sourceForwardingInfo.keyAt(i); 3500 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3501 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3502 intent, resolvedType, flags, targetUserId); 3503 int NJ = resolveInfos.size(); 3504 for (int j = 0; j < NJ; j++) { 3505 ResolveInfo resolveInfo = resolveInfos.get(j); 3506 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3507 matchingResolveInfos.add(createForwardingResolveInfo( 3508 resolveInfo.filter, userId, targetUserId)); 3509 } 3510 } 3511 } 3512 } 3513 return matchingResolveInfos; 3514 } 3515 3516 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3517 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3518 String packageName) { 3519 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3520 SparseArray<ArrayList<String>> sourceForwardingInfo = 3521 mSettings.mCrossProfilePackageInfo.get(userId); 3522 if (sourceForwardingInfo != null) { 3523 int NI = sourceForwardingInfo.size(); 3524 for (int i = 0; i < NI; i++) { 3525 int targetUserId = sourceForwardingInfo.keyAt(i); 3526 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3527 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3528 intent, resolvedType, flags, pkg.activities, targetUserId); 3529 int NJ = resolveInfos.size(); 3530 for (int j = 0; j < NJ; j++) { 3531 ResolveInfo resolveInfo = resolveInfos.get(j); 3532 matchingResolveInfos.add(createForwardingResolveInfo( 3533 resolveInfo.filter, userId, targetUserId)); 3534 } 3535 } 3536 } 3537 } 3538 return matchingResolveInfos; 3539 } 3540 3541 // Return matching ResolveInfo if any for skip current profile intent filters. 3542 private ResolveInfo queryCrossProfileIntents( 3543 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3544 int flags, int sourceUserId) { 3545 if (matchingFilters != null) { 3546 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3547 // match the same intent. For performance reasons, it is better not to 3548 // run queryIntent twice for the same userId 3549 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3550 int size = matchingFilters.size(); 3551 for (int i = 0; i < size; i++) { 3552 CrossProfileIntentFilter filter = matchingFilters.get(i); 3553 int targetUserId = filter.getTargetUserId(); 3554 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3555 && !alreadyTriedUserIds.get(targetUserId)) { 3556 // Checking if there are activities in the target user that can handle the 3557 // intent. 3558 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3559 flags, sourceUserId); 3560 if (resolveInfo != null) return resolveInfo; 3561 alreadyTriedUserIds.put(targetUserId, true); 3562 } 3563 } 3564 } 3565 return null; 3566 } 3567 3568 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3569 String resolvedType, int flags, int sourceUserId) { 3570 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3571 resolvedType, flags, filter.getTargetUserId()); 3572 if (resultTargetUser != null) { 3573 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3574 } 3575 return null; 3576 } 3577 3578 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3579 int sourceUserId, int targetUserId) { 3580 String className; 3581 if (targetUserId == UserHandle.USER_OWNER) { 3582 className = FORWARD_INTENT_TO_USER_OWNER; 3583 } else { 3584 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3585 } 3586 ComponentName forwardingActivityComponentName = new ComponentName( 3587 mAndroidApplication.packageName, className); 3588 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3589 sourceUserId); 3590 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3591 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3592 forwardingResolveInfo.priority = 0; 3593 forwardingResolveInfo.preferredOrder = 0; 3594 forwardingResolveInfo.match = 0; 3595 forwardingResolveInfo.isDefault = true; 3596 forwardingResolveInfo.filter = filter; 3597 return forwardingResolveInfo; 3598 } 3599 3600 @Override 3601 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3602 Intent[] specifics, String[] specificTypes, Intent intent, 3603 String resolvedType, int flags, int userId) { 3604 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3605 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3606 "query intent activity options"); 3607 final String resultsAction = intent.getAction(); 3608 3609 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3610 | PackageManager.GET_RESOLVED_FILTER, userId); 3611 3612 if (DEBUG_INTENT_MATCHING) { 3613 Log.v(TAG, "Query " + intent + ": " + results); 3614 } 3615 3616 int specificsPos = 0; 3617 int N; 3618 3619 // todo: note that the algorithm used here is O(N^2). This 3620 // isn't a problem in our current environment, but if we start running 3621 // into situations where we have more than 5 or 10 matches then this 3622 // should probably be changed to something smarter... 3623 3624 // First we go through and resolve each of the specific items 3625 // that were supplied, taking care of removing any corresponding 3626 // duplicate items in the generic resolve list. 3627 if (specifics != null) { 3628 for (int i=0; i<specifics.length; i++) { 3629 final Intent sintent = specifics[i]; 3630 if (sintent == null) { 3631 continue; 3632 } 3633 3634 if (DEBUG_INTENT_MATCHING) { 3635 Log.v(TAG, "Specific #" + i + ": " + sintent); 3636 } 3637 3638 String action = sintent.getAction(); 3639 if (resultsAction != null && resultsAction.equals(action)) { 3640 // If this action was explicitly requested, then don't 3641 // remove things that have it. 3642 action = null; 3643 } 3644 3645 ResolveInfo ri = null; 3646 ActivityInfo ai = null; 3647 3648 ComponentName comp = sintent.getComponent(); 3649 if (comp == null) { 3650 ri = resolveIntent( 3651 sintent, 3652 specificTypes != null ? specificTypes[i] : null, 3653 flags, userId); 3654 if (ri == null) { 3655 continue; 3656 } 3657 if (ri == mResolveInfo) { 3658 // ACK! Must do something better with this. 3659 } 3660 ai = ri.activityInfo; 3661 comp = new ComponentName(ai.applicationInfo.packageName, 3662 ai.name); 3663 } else { 3664 ai = getActivityInfo(comp, flags, userId); 3665 if (ai == null) { 3666 continue; 3667 } 3668 } 3669 3670 // Look for any generic query activities that are duplicates 3671 // of this specific one, and remove them from the results. 3672 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3673 N = results.size(); 3674 int j; 3675 for (j=specificsPos; j<N; j++) { 3676 ResolveInfo sri = results.get(j); 3677 if ((sri.activityInfo.name.equals(comp.getClassName()) 3678 && sri.activityInfo.applicationInfo.packageName.equals( 3679 comp.getPackageName())) 3680 || (action != null && sri.filter.matchAction(action))) { 3681 results.remove(j); 3682 if (DEBUG_INTENT_MATCHING) Log.v( 3683 TAG, "Removing duplicate item from " + j 3684 + " due to specific " + specificsPos); 3685 if (ri == null) { 3686 ri = sri; 3687 } 3688 j--; 3689 N--; 3690 } 3691 } 3692 3693 // Add this specific item to its proper place. 3694 if (ri == null) { 3695 ri = new ResolveInfo(); 3696 ri.activityInfo = ai; 3697 } 3698 results.add(specificsPos, ri); 3699 ri.specificIndex = i; 3700 specificsPos++; 3701 } 3702 } 3703 3704 // Now we go through the remaining generic results and remove any 3705 // duplicate actions that are found here. 3706 N = results.size(); 3707 for (int i=specificsPos; i<N-1; i++) { 3708 final ResolveInfo rii = results.get(i); 3709 if (rii.filter == null) { 3710 continue; 3711 } 3712 3713 // Iterate over all of the actions of this result's intent 3714 // filter... typically this should be just one. 3715 final Iterator<String> it = rii.filter.actionsIterator(); 3716 if (it == null) { 3717 continue; 3718 } 3719 while (it.hasNext()) { 3720 final String action = it.next(); 3721 if (resultsAction != null && resultsAction.equals(action)) { 3722 // If this action was explicitly requested, then don't 3723 // remove things that have it. 3724 continue; 3725 } 3726 for (int j=i+1; j<N; j++) { 3727 final ResolveInfo rij = results.get(j); 3728 if (rij.filter != null && rij.filter.hasAction(action)) { 3729 results.remove(j); 3730 if (DEBUG_INTENT_MATCHING) Log.v( 3731 TAG, "Removing duplicate item from " + j 3732 + " due to action " + action + " at " + i); 3733 j--; 3734 N--; 3735 } 3736 } 3737 } 3738 3739 // If the caller didn't request filter information, drop it now 3740 // so we don't have to marshall/unmarshall it. 3741 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3742 rii.filter = null; 3743 } 3744 } 3745 3746 // Filter out the caller activity if so requested. 3747 if (caller != null) { 3748 N = results.size(); 3749 for (int i=0; i<N; i++) { 3750 ActivityInfo ainfo = results.get(i).activityInfo; 3751 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3752 && caller.getClassName().equals(ainfo.name)) { 3753 results.remove(i); 3754 break; 3755 } 3756 } 3757 } 3758 3759 // If the caller didn't request filter information, 3760 // drop them now so we don't have to 3761 // marshall/unmarshall it. 3762 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3763 N = results.size(); 3764 for (int i=0; i<N; i++) { 3765 results.get(i).filter = null; 3766 } 3767 } 3768 3769 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3770 return results; 3771 } 3772 3773 @Override 3774 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3775 int userId) { 3776 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3777 ComponentName comp = intent.getComponent(); 3778 if (comp == null) { 3779 if (intent.getSelector() != null) { 3780 intent = intent.getSelector(); 3781 comp = intent.getComponent(); 3782 } 3783 } 3784 if (comp != null) { 3785 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3786 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3787 if (ai != null) { 3788 ResolveInfo ri = new ResolveInfo(); 3789 ri.activityInfo = ai; 3790 list.add(ri); 3791 } 3792 return list; 3793 } 3794 3795 // reader 3796 synchronized (mPackages) { 3797 String pkgName = intent.getPackage(); 3798 if (pkgName == null) { 3799 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3800 } 3801 final PackageParser.Package pkg = mPackages.get(pkgName); 3802 if (pkg != null) { 3803 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3804 userId); 3805 } 3806 return null; 3807 } 3808 } 3809 3810 @Override 3811 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3812 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3813 if (!sUserManager.exists(userId)) return null; 3814 if (query != null) { 3815 if (query.size() >= 1) { 3816 // If there is more than one service with the same priority, 3817 // just arbitrarily pick the first one. 3818 return query.get(0); 3819 } 3820 } 3821 return null; 3822 } 3823 3824 @Override 3825 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3826 int userId) { 3827 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3828 ComponentName comp = intent.getComponent(); 3829 if (comp == null) { 3830 if (intent.getSelector() != null) { 3831 intent = intent.getSelector(); 3832 comp = intent.getComponent(); 3833 } 3834 } 3835 if (comp != null) { 3836 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3837 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3838 if (si != null) { 3839 final ResolveInfo ri = new ResolveInfo(); 3840 ri.serviceInfo = si; 3841 list.add(ri); 3842 } 3843 return list; 3844 } 3845 3846 // reader 3847 synchronized (mPackages) { 3848 String pkgName = intent.getPackage(); 3849 if (pkgName == null) { 3850 return mServices.queryIntent(intent, resolvedType, flags, userId); 3851 } 3852 final PackageParser.Package pkg = mPackages.get(pkgName); 3853 if (pkg != null) { 3854 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3855 userId); 3856 } 3857 return null; 3858 } 3859 } 3860 3861 @Override 3862 public List<ResolveInfo> queryIntentContentProviders( 3863 Intent intent, String resolvedType, int flags, int userId) { 3864 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3865 ComponentName comp = intent.getComponent(); 3866 if (comp == null) { 3867 if (intent.getSelector() != null) { 3868 intent = intent.getSelector(); 3869 comp = intent.getComponent(); 3870 } 3871 } 3872 if (comp != null) { 3873 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3874 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3875 if (pi != null) { 3876 final ResolveInfo ri = new ResolveInfo(); 3877 ri.providerInfo = pi; 3878 list.add(ri); 3879 } 3880 return list; 3881 } 3882 3883 // reader 3884 synchronized (mPackages) { 3885 String pkgName = intent.getPackage(); 3886 if (pkgName == null) { 3887 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3888 } 3889 final PackageParser.Package pkg = mPackages.get(pkgName); 3890 if (pkg != null) { 3891 return mProviders.queryIntentForPackage( 3892 intent, resolvedType, flags, pkg.providers, userId); 3893 } 3894 return null; 3895 } 3896 } 3897 3898 @Override 3899 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3900 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3901 3902 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3903 3904 // writer 3905 synchronized (mPackages) { 3906 ArrayList<PackageInfo> list; 3907 if (listUninstalled) { 3908 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3909 for (PackageSetting ps : mSettings.mPackages.values()) { 3910 PackageInfo pi; 3911 if (ps.pkg != null) { 3912 pi = generatePackageInfo(ps.pkg, flags, userId); 3913 } else { 3914 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3915 } 3916 if (pi != null) { 3917 list.add(pi); 3918 } 3919 } 3920 } else { 3921 list = new ArrayList<PackageInfo>(mPackages.size()); 3922 for (PackageParser.Package p : mPackages.values()) { 3923 PackageInfo pi = generatePackageInfo(p, flags, userId); 3924 if (pi != null) { 3925 list.add(pi); 3926 } 3927 } 3928 } 3929 3930 return new ParceledListSlice<PackageInfo>(list); 3931 } 3932 } 3933 3934 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3935 String[] permissions, boolean[] tmp, int flags, int userId) { 3936 int numMatch = 0; 3937 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3938 for (int i=0; i<permissions.length; i++) { 3939 if (gp.grantedPermissions.contains(permissions[i])) { 3940 tmp[i] = true; 3941 numMatch++; 3942 } else { 3943 tmp[i] = false; 3944 } 3945 } 3946 if (numMatch == 0) { 3947 return; 3948 } 3949 PackageInfo pi; 3950 if (ps.pkg != null) { 3951 pi = generatePackageInfo(ps.pkg, flags, userId); 3952 } else { 3953 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3954 } 3955 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3956 if (numMatch == permissions.length) { 3957 pi.requestedPermissions = permissions; 3958 } else { 3959 pi.requestedPermissions = new String[numMatch]; 3960 numMatch = 0; 3961 for (int i=0; i<permissions.length; i++) { 3962 if (tmp[i]) { 3963 pi.requestedPermissions[numMatch] = permissions[i]; 3964 numMatch++; 3965 } 3966 } 3967 } 3968 } 3969 list.add(pi); 3970 } 3971 3972 @Override 3973 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3974 String[] permissions, int flags, int userId) { 3975 if (!sUserManager.exists(userId)) return null; 3976 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3977 3978 // writer 3979 synchronized (mPackages) { 3980 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3981 boolean[] tmpBools = new boolean[permissions.length]; 3982 if (listUninstalled) { 3983 for (PackageSetting ps : mSettings.mPackages.values()) { 3984 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3985 } 3986 } else { 3987 for (PackageParser.Package pkg : mPackages.values()) { 3988 PackageSetting ps = (PackageSetting)pkg.mExtras; 3989 if (ps != null) { 3990 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3991 userId); 3992 } 3993 } 3994 } 3995 3996 return new ParceledListSlice<PackageInfo>(list); 3997 } 3998 } 3999 4000 @Override 4001 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4002 if (!sUserManager.exists(userId)) return null; 4003 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4004 4005 // writer 4006 synchronized (mPackages) { 4007 ArrayList<ApplicationInfo> list; 4008 if (listUninstalled) { 4009 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4010 for (PackageSetting ps : mSettings.mPackages.values()) { 4011 ApplicationInfo ai; 4012 if (ps.pkg != null) { 4013 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4014 ps.readUserState(userId), userId); 4015 } else { 4016 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4017 } 4018 if (ai != null) { 4019 list.add(ai); 4020 } 4021 } 4022 } else { 4023 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4024 for (PackageParser.Package p : mPackages.values()) { 4025 if (p.mExtras != null) { 4026 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4027 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4028 if (ai != null) { 4029 list.add(ai); 4030 } 4031 } 4032 } 4033 } 4034 4035 return new ParceledListSlice<ApplicationInfo>(list); 4036 } 4037 } 4038 4039 public List<ApplicationInfo> getPersistentApplications(int flags) { 4040 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4041 4042 // reader 4043 synchronized (mPackages) { 4044 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4045 final int userId = UserHandle.getCallingUserId(); 4046 while (i.hasNext()) { 4047 final PackageParser.Package p = i.next(); 4048 if (p.applicationInfo != null 4049 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4050 && (!mSafeMode || isSystemApp(p))) { 4051 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4052 if (ps != null) { 4053 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4054 ps.readUserState(userId), userId); 4055 if (ai != null) { 4056 finalList.add(ai); 4057 } 4058 } 4059 } 4060 } 4061 } 4062 4063 return finalList; 4064 } 4065 4066 @Override 4067 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4068 if (!sUserManager.exists(userId)) return null; 4069 // reader 4070 synchronized (mPackages) { 4071 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4072 PackageSetting ps = provider != null 4073 ? mSettings.mPackages.get(provider.owner.packageName) 4074 : null; 4075 return ps != null 4076 && mSettings.isEnabledLPr(provider.info, flags, userId) 4077 && (!mSafeMode || (provider.info.applicationInfo.flags 4078 &ApplicationInfo.FLAG_SYSTEM) != 0) 4079 ? PackageParser.generateProviderInfo(provider, flags, 4080 ps.readUserState(userId), userId) 4081 : null; 4082 } 4083 } 4084 4085 /** 4086 * @deprecated 4087 */ 4088 @Deprecated 4089 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4090 // reader 4091 synchronized (mPackages) { 4092 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4093 .entrySet().iterator(); 4094 final int userId = UserHandle.getCallingUserId(); 4095 while (i.hasNext()) { 4096 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4097 PackageParser.Provider p = entry.getValue(); 4098 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4099 4100 if (ps != null && p.syncable 4101 && (!mSafeMode || (p.info.applicationInfo.flags 4102 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4103 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4104 ps.readUserState(userId), userId); 4105 if (info != null) { 4106 outNames.add(entry.getKey()); 4107 outInfo.add(info); 4108 } 4109 } 4110 } 4111 } 4112 } 4113 4114 @Override 4115 public List<ProviderInfo> queryContentProviders(String processName, 4116 int uid, int flags) { 4117 ArrayList<ProviderInfo> finalList = null; 4118 // reader 4119 synchronized (mPackages) { 4120 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4121 final int userId = processName != null ? 4122 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4123 while (i.hasNext()) { 4124 final PackageParser.Provider p = i.next(); 4125 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4126 if (ps != null && p.info.authority != null 4127 && (processName == null 4128 || (p.info.processName.equals(processName) 4129 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4130 && mSettings.isEnabledLPr(p.info, flags, userId) 4131 && (!mSafeMode 4132 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4133 if (finalList == null) { 4134 finalList = new ArrayList<ProviderInfo>(3); 4135 } 4136 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4137 ps.readUserState(userId), userId); 4138 if (info != null) { 4139 finalList.add(info); 4140 } 4141 } 4142 } 4143 } 4144 4145 if (finalList != null) { 4146 Collections.sort(finalList, mProviderInitOrderSorter); 4147 } 4148 4149 return finalList; 4150 } 4151 4152 @Override 4153 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4154 int flags) { 4155 // reader 4156 synchronized (mPackages) { 4157 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4158 return PackageParser.generateInstrumentationInfo(i, flags); 4159 } 4160 } 4161 4162 @Override 4163 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4164 int flags) { 4165 ArrayList<InstrumentationInfo> finalList = 4166 new ArrayList<InstrumentationInfo>(); 4167 4168 // reader 4169 synchronized (mPackages) { 4170 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4171 while (i.hasNext()) { 4172 final PackageParser.Instrumentation p = i.next(); 4173 if (targetPackage == null 4174 || targetPackage.equals(p.info.targetPackage)) { 4175 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4176 flags); 4177 if (ii != null) { 4178 finalList.add(ii); 4179 } 4180 } 4181 } 4182 } 4183 4184 return finalList; 4185 } 4186 4187 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4188 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4189 if (overlays == null) { 4190 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4191 return; 4192 } 4193 for (PackageParser.Package opkg : overlays.values()) { 4194 // Not much to do if idmap fails: we already logged the error 4195 // and we certainly don't want to abort installation of pkg simply 4196 // because an overlay didn't fit properly. For these reasons, 4197 // ignore the return value of createIdmapForPackagePairLI. 4198 createIdmapForPackagePairLI(pkg, opkg); 4199 } 4200 } 4201 4202 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4203 PackageParser.Package opkg) { 4204 if (!opkg.mTrustedOverlay) { 4205 Slog.w(TAG, "Skipping target and overlay pair " + pkg.codePath + " and " + 4206 opkg.codePath + ": overlay not trusted"); 4207 return false; 4208 } 4209 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4210 if (overlaySet == null) { 4211 Slog.e(TAG, "was about to create idmap for " + pkg.codePath + " and " + 4212 opkg.codePath + " but target package has no known overlays"); 4213 return false; 4214 } 4215 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4216 // TODO: generate idmap for split APKs 4217 if (mInstaller.idmap(pkg.codePath, opkg.codePath, sharedGid) != 0) { 4218 Slog.e(TAG, "Failed to generate idmap for " + pkg.codePath + " and " + opkg.codePath); 4219 return false; 4220 } 4221 PackageParser.Package[] overlayArray = 4222 overlaySet.values().toArray(new PackageParser.Package[0]); 4223 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4224 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4225 return p1.mOverlayPriority - p2.mOverlayPriority; 4226 } 4227 }; 4228 Arrays.sort(overlayArray, cmp); 4229 4230 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4231 int i = 0; 4232 for (PackageParser.Package p : overlayArray) { 4233 pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir; 4234 } 4235 return true; 4236 } 4237 4238 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4239 String[] files = dir.list(); 4240 if (files == null) { 4241 Log.d(TAG, "No files in app dir " + dir); 4242 return; 4243 } 4244 4245 if (DEBUG_PACKAGE_SCANNING) { 4246 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4247 + " flags=0x" + Integer.toHexString(flags)); 4248 } 4249 4250 int i; 4251 for (i=0; i<files.length; i++) { 4252 File file = new File(dir, files[i]); 4253 if (!isPackageFilename(files[i])) { 4254 // Ignore entries which are not apk's 4255 continue; 4256 } 4257 PackageParser.Package pkg = scanPackageLI(file, 4258 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null); 4259 // Don't mess around with apps in system partition. 4260 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4261 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 4262 // Delete the apk 4263 Slog.w(TAG, "Cleaning up failed install of " + file); 4264 file.delete(); 4265 } 4266 } 4267 } 4268 4269 private static File getSettingsProblemFile() { 4270 File dataDir = Environment.getDataDirectory(); 4271 File systemDir = new File(dataDir, "system"); 4272 File fname = new File(systemDir, "uiderrors.txt"); 4273 return fname; 4274 } 4275 4276 static void reportSettingsProblem(int priority, String msg) { 4277 try { 4278 File fname = getSettingsProblemFile(); 4279 FileOutputStream out = new FileOutputStream(fname, true); 4280 PrintWriter pw = new FastPrintWriter(out); 4281 SimpleDateFormat formatter = new SimpleDateFormat(); 4282 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4283 pw.println(dateString + ": " + msg); 4284 pw.close(); 4285 FileUtils.setPermissions( 4286 fname.toString(), 4287 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4288 -1, -1); 4289 } catch (java.io.IOException e) { 4290 } 4291 Slog.println(priority, TAG, msg); 4292 } 4293 4294 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 4295 PackageParser.Package pkg, File srcFile, int parseFlags) { 4296 if (ps != null 4297 && ps.codePath.equals(srcFile) 4298 && ps.timeStamp == srcFile.lastModified() 4299 && !isCompatSignatureUpdateNeeded(pkg)) { 4300 if (ps.signatures.mSignatures != null 4301 && ps.signatures.mSignatures.length != 0) { 4302 // Optimization: reuse the existing cached certificates 4303 // if the package appears to be unchanged. 4304 pkg.mSignatures = ps.signatures.mSignatures; 4305 return true; 4306 } 4307 4308 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 4309 } else { 4310 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4311 } 4312 4313 try { 4314 pp.collectCertificates(pkg, parseFlags); 4315 } catch (PackageParserException e) { 4316 mLastScanError = e.error; 4317 return false; 4318 } 4319 return true; 4320 } 4321 4322 /* 4323 * Scan a package and return the newly parsed package. 4324 * Returns null in case of errors and the error code is stored in mLastScanError 4325 */ 4326 private PackageParser.Package scanPackageLI(File scanFile, 4327 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4328 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 4329 String scanPath = scanFile.getPath(); 4330 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath); 4331 parseFlags |= mDefParseFlags; 4332 PackageParser pp = new PackageParser(); 4333 pp.setSeparateProcesses(mSeparateProcesses); 4334 pp.setOnlyCoreApps(mOnlyCore); 4335 pp.setDisplayMetrics(mMetrics); 4336 4337 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4338 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4339 } 4340 4341 final PackageParser.Package pkg; 4342 try { 4343 pkg = pp.parseMonolithicPackage(scanFile, parseFlags); 4344 } catch (PackageParserException e) { 4345 mLastScanError = e.error; 4346 return null; 4347 } 4348 4349 PackageSetting ps = null; 4350 PackageSetting updatedPkg; 4351 // reader 4352 synchronized (mPackages) { 4353 // Look to see if we already know about this package. 4354 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4355 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4356 // This package has been renamed to its original name. Let's 4357 // use that. 4358 ps = mSettings.peekPackageLPr(oldName); 4359 } 4360 // If there was no original package, see one for the real package name. 4361 if (ps == null) { 4362 ps = mSettings.peekPackageLPr(pkg.packageName); 4363 } 4364 // Check to see if this package could be hiding/updating a system 4365 // package. Must look for it either under the original or real 4366 // package name depending on our state. 4367 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4368 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4369 } 4370 boolean updatedPkgBetter = false; 4371 // First check if this is a system package that may involve an update 4372 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4373 if (ps != null && !ps.codePath.equals(scanFile)) { 4374 // The path has changed from what was last scanned... check the 4375 // version of the new path against what we have stored to determine 4376 // what to do. 4377 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4378 if (pkg.mVersionCode < ps.versionCode) { 4379 // The system package has been updated and the code path does not match 4380 // Ignore entry. Skip it. 4381 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4382 + " ignored: updated version " + ps.versionCode 4383 + " better than this " + pkg.mVersionCode); 4384 if (!updatedPkg.codePath.equals(scanFile)) { 4385 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4386 + ps.name + " changing from " + updatedPkg.codePathString 4387 + " to " + scanFile); 4388 updatedPkg.codePath = scanFile; 4389 updatedPkg.codePathString = scanFile.toString(); 4390 // This is the point at which we know that the system-disk APK 4391 // for this package has moved during a reboot (e.g. due to an OTA), 4392 // so we need to reevaluate it for privilege policy. 4393 if (locationIsPrivileged(scanFile)) { 4394 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4395 } 4396 } 4397 updatedPkg.pkg = pkg; 4398 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4399 return null; 4400 } else { 4401 // The current app on the system partition is better than 4402 // what we have updated to on the data partition; switch 4403 // back to the system partition version. 4404 // At this point, its safely assumed that package installation for 4405 // apps in system partition will go through. If not there won't be a working 4406 // version of the app 4407 // writer 4408 synchronized (mPackages) { 4409 // Just remove the loaded entries from package lists. 4410 mPackages.remove(ps.name); 4411 } 4412 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4413 + "reverting from " + ps.codePathString 4414 + ": new version " + pkg.mVersionCode 4415 + " better than installed " + ps.versionCode); 4416 4417 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4418 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4419 getAppInstructionSetFromSettings(ps)); 4420 synchronized (mInstallLock) { 4421 args.cleanUpResourcesLI(); 4422 } 4423 synchronized (mPackages) { 4424 mSettings.enableSystemPackageLPw(ps.name); 4425 } 4426 updatedPkgBetter = true; 4427 } 4428 } 4429 } 4430 4431 if (updatedPkg != null) { 4432 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4433 // initially 4434 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4435 4436 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4437 // flag set initially 4438 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4439 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4440 } 4441 } 4442 // Verify certificates against what was last scanned 4443 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 4444 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 4445 return null; 4446 } 4447 4448 /* 4449 * A new system app appeared, but we already had a non-system one of the 4450 * same name installed earlier. 4451 */ 4452 boolean shouldHideSystemApp = false; 4453 if (updatedPkg == null && ps != null 4454 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4455 /* 4456 * Check to make sure the signatures match first. If they don't, 4457 * wipe the installed application and its data. 4458 */ 4459 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4460 != PackageManager.SIGNATURE_MATCH) { 4461 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4462 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4463 ps = null; 4464 } else { 4465 /* 4466 * If the newly-added system app is an older version than the 4467 * already installed version, hide it. It will be scanned later 4468 * and re-added like an update. 4469 */ 4470 if (pkg.mVersionCode < ps.versionCode) { 4471 shouldHideSystemApp = true; 4472 } else { 4473 /* 4474 * The newly found system app is a newer version that the 4475 * one previously installed. Simply remove the 4476 * already-installed application and replace it with our own 4477 * while keeping the application data. 4478 */ 4479 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4480 + ps.codePathString + ": new version " + pkg.mVersionCode 4481 + " better than installed " + ps.versionCode); 4482 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4483 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4484 getAppInstructionSetFromSettings(ps)); 4485 synchronized (mInstallLock) { 4486 args.cleanUpResourcesLI(); 4487 } 4488 } 4489 } 4490 } 4491 4492 // The apk is forward locked (not public) if its code and resources 4493 // are kept in different files. (except for app in either system or 4494 // vendor path). 4495 // TODO grab this value from PackageSettings 4496 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4497 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4498 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4499 } 4500 } 4501 4502 final String codePath = pkg.codePath; 4503 final String[] splitCodePaths = pkg.splitCodePaths; 4504 4505 String resPath = null; 4506 String[] splitResPaths = null; 4507 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4508 if (ps != null && ps.resourcePathString != null) { 4509 resPath = ps.resourcePathString; 4510 splitResPaths = deriveSplitResPaths(pkg.splitCodePaths); 4511 } else { 4512 // Should not happen at all. Just log an error. 4513 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4514 } 4515 } else { 4516 resPath = pkg.codePath; 4517 splitResPaths = pkg.splitCodePaths; 4518 } 4519 4520 // Set application objects path explicitly. 4521 pkg.applicationInfo.sourceDir = codePath; 4522 pkg.applicationInfo.publicSourceDir = resPath; 4523 pkg.applicationInfo.splitSourceDirs = splitCodePaths; 4524 pkg.applicationInfo.splitPublicSourceDirs = splitResPaths; 4525 4526 // Note that we invoke the following method only if we are about to unpack an application 4527 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4528 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4529 4530 /* 4531 * If the system app should be overridden by a previously installed 4532 * data, hide the system app now and let the /data/app scan pick it up 4533 * again. 4534 */ 4535 if (shouldHideSystemApp) { 4536 synchronized (mPackages) { 4537 /* 4538 * We have to grant systems permissions before we hide, because 4539 * grantPermissions will assume the package update is trying to 4540 * expand its permissions. 4541 */ 4542 grantPermissionsLPw(pkg, true); 4543 mSettings.disableSystemPackageLPw(pkg.packageName); 4544 } 4545 } 4546 4547 return scannedPkg; 4548 } 4549 4550 private static String fixProcessName(String defProcessName, 4551 String processName, int uid) { 4552 if (processName == null) { 4553 return defProcessName; 4554 } 4555 return processName; 4556 } 4557 4558 private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) { 4559 if (pkgSetting.signatures.mSignatures != null) { 4560 // Already existing package. Make sure signatures match 4561 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4562 == PackageManager.SIGNATURE_MATCH; 4563 if (!match) { 4564 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4565 == PackageManager.SIGNATURE_MATCH; 4566 } 4567 if (!match) { 4568 Slog.e(TAG, "Package " + pkg.packageName 4569 + " signatures do not match the previously installed version; ignoring!"); 4570 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4571 return false; 4572 } 4573 } 4574 // Check for shared user signatures 4575 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4576 // Already existing package. Make sure signatures match 4577 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4578 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4579 if (!match) { 4580 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4581 == PackageManager.SIGNATURE_MATCH; 4582 } 4583 if (!match) { 4584 Slog.e(TAG, "Package " + pkg.packageName 4585 + " has no signatures that match those in shared user " 4586 + pkgSetting.sharedUser.name + "; ignoring!"); 4587 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4588 return false; 4589 } 4590 } 4591 return true; 4592 } 4593 4594 /** 4595 * Enforces that only the system UID or root's UID can call a method exposed 4596 * via Binder. 4597 * 4598 * @param message used as message if SecurityException is thrown 4599 * @throws SecurityException if the caller is not system or root 4600 */ 4601 private static final void enforceSystemOrRoot(String message) { 4602 final int uid = Binder.getCallingUid(); 4603 if (uid != Process.SYSTEM_UID && uid != 0) { 4604 throw new SecurityException(message); 4605 } 4606 } 4607 4608 @Override 4609 public void performBootDexOpt() { 4610 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4611 4612 final HashSet<PackageParser.Package> pkgs; 4613 synchronized (mPackages) { 4614 pkgs = mDeferredDexOpt; 4615 mDeferredDexOpt = null; 4616 } 4617 4618 if (pkgs != null) { 4619 // Filter out packages that aren't recently used. 4620 // 4621 // The exception is first boot of a non-eng device, which 4622 // should do a full dexopt. 4623 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4624 if (eng || !isFirstBoot()) { 4625 // TODO: add a property to control this? 4626 long dexOptLRUThresholdInMinutes; 4627 if (eng) { 4628 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4629 } else { 4630 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4631 } 4632 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4633 4634 int total = pkgs.size(); 4635 int skipped = 0; 4636 long now = System.currentTimeMillis(); 4637 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4638 PackageParser.Package pkg = i.next(); 4639 long then = pkg.mLastPackageUsageTimeInMills; 4640 if (then + dexOptLRUThresholdInMills < now) { 4641 if (DEBUG_DEXOPT) { 4642 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4643 ((then == 0) ? "never" : new Date(then))); 4644 } 4645 i.remove(); 4646 skipped++; 4647 } 4648 } 4649 if (DEBUG_DEXOPT) { 4650 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4651 } 4652 } 4653 4654 int i = 0; 4655 for (PackageParser.Package pkg : pkgs) { 4656 i++; 4657 if (DEBUG_DEXOPT) { 4658 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4659 + ": " + pkg.packageName); 4660 } 4661 if (!isFirstBoot()) { 4662 try { 4663 ActivityManagerNative.getDefault().showBootMessage( 4664 mContext.getResources().getString( 4665 R.string.android_upgrading_apk, 4666 i, pkgs.size()), true); 4667 } catch (RemoteException e) { 4668 } 4669 } 4670 PackageParser.Package p = pkg; 4671 synchronized (mInstallLock) { 4672 if (p.mDexOptNeeded) { 4673 performDexOptLI(p, false /* force dex */, false /* defer */, 4674 true /* include dependencies */); 4675 } 4676 } 4677 } 4678 } 4679 } 4680 4681 @Override 4682 public boolean performDexOpt(String packageName) { 4683 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4684 return performDexOpt(packageName, true); 4685 } 4686 4687 public boolean performDexOpt(String packageName, boolean updateUsage) { 4688 4689 PackageParser.Package p; 4690 synchronized (mPackages) { 4691 p = mPackages.get(packageName); 4692 if (p == null) { 4693 return false; 4694 } 4695 if (updateUsage) { 4696 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4697 } 4698 mPackageUsage.write(false); 4699 if (!p.mDexOptNeeded) { 4700 return false; 4701 } 4702 } 4703 4704 synchronized (mInstallLock) { 4705 return performDexOptLI(p, false /* force dex */, false /* defer */, 4706 true /* include dependencies */) == DEX_OPT_PERFORMED; 4707 } 4708 } 4709 4710 public HashSet<String> getPackagesThatNeedDexOpt() { 4711 HashSet<String> pkgs = null; 4712 synchronized (mPackages) { 4713 for (PackageParser.Package p : mPackages.values()) { 4714 if (DEBUG_DEXOPT) { 4715 Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded); 4716 } 4717 if (!p.mDexOptNeeded) { 4718 continue; 4719 } 4720 if (pkgs == null) { 4721 pkgs = new HashSet<String>(); 4722 } 4723 pkgs.add(p.packageName); 4724 } 4725 } 4726 return pkgs; 4727 } 4728 4729 public void shutdown() { 4730 mPackageUsage.write(true); 4731 } 4732 4733 private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, 4734 boolean forceDex, boolean defer, HashSet<String> done) { 4735 for (int i=0; i<libs.size(); i++) { 4736 PackageParser.Package libPkg; 4737 String libName; 4738 synchronized (mPackages) { 4739 libName = libs.get(i); 4740 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4741 if (lib != null && lib.apk != null) { 4742 libPkg = mPackages.get(lib.apk); 4743 } else { 4744 libPkg = null; 4745 } 4746 } 4747 if (libPkg != null && !done.contains(libName)) { 4748 performDexOptLI(libPkg, instructionSet, forceDex, defer, done); 4749 } 4750 } 4751 } 4752 4753 static final int DEX_OPT_SKIPPED = 0; 4754 static final int DEX_OPT_PERFORMED = 1; 4755 static final int DEX_OPT_DEFERRED = 2; 4756 static final int DEX_OPT_FAILED = -1; 4757 4758 private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride, 4759 boolean forceDex, boolean defer, HashSet<String> done) { 4760 final String instructionSet = instructionSetOverride != null ? 4761 instructionSetOverride : getAppInstructionSet(pkg.applicationInfo); 4762 4763 if (done != null) { 4764 done.add(pkg.packageName); 4765 if (pkg.usesLibraries != null) { 4766 performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done); 4767 } 4768 if (pkg.usesOptionalLibraries != null) { 4769 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done); 4770 } 4771 } 4772 4773 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) { 4774 final Collection<String> paths = pkg.getAllCodePaths(); 4775 for (String path : paths) { 4776 try { 4777 boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path, 4778 pkg.packageName, instructionSet, defer); 4779 // There are three basic cases here: 4780 // 1.) we need to dexopt, either because we are forced or it is needed 4781 // 2.) we are defering a needed dexopt 4782 // 3.) we are skipping an unneeded dexopt 4783 if (forceDex || (!defer && isDexOptNeededInternal)) { 4784 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName); 4785 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4786 int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4787 pkg.packageName, instructionSet); 4788 // Note that we ran dexopt, since rerunning will 4789 // probably just result in an error again. 4790 pkg.mDexOptNeeded = false; 4791 if (ret < 0) { 4792 return DEX_OPT_FAILED; 4793 } 4794 return DEX_OPT_PERFORMED; 4795 } 4796 if (defer && isDexOptNeededInternal) { 4797 if (mDeferredDexOpt == null) { 4798 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4799 } 4800 mDeferredDexOpt.add(pkg); 4801 return DEX_OPT_DEFERRED; 4802 } 4803 pkg.mDexOptNeeded = false; 4804 return DEX_OPT_SKIPPED; 4805 } catch (FileNotFoundException e) { 4806 Slog.w(TAG, "Apk not found for dexopt: " + path); 4807 return DEX_OPT_FAILED; 4808 } catch (IOException e) { 4809 Slog.w(TAG, "IOException reading apk: " + path, e); 4810 return DEX_OPT_FAILED; 4811 } catch (StaleDexCacheError e) { 4812 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4813 return DEX_OPT_FAILED; 4814 } catch (Exception e) { 4815 Slog.w(TAG, "Exception when doing dexopt : ", e); 4816 return DEX_OPT_FAILED; 4817 } 4818 } 4819 } 4820 return DEX_OPT_SKIPPED; 4821 } 4822 4823 private String getAppInstructionSet(ApplicationInfo info) { 4824 String instructionSet = getPreferredInstructionSet(); 4825 4826 if (info.cpuAbi != null) { 4827 instructionSet = VMRuntime.getInstructionSet(info.cpuAbi); 4828 } 4829 4830 return instructionSet; 4831 } 4832 4833 private String getAppInstructionSetFromSettings(PackageSetting ps) { 4834 String instructionSet = getPreferredInstructionSet(); 4835 4836 if (ps.cpuAbiString != null) { 4837 instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 4838 } 4839 4840 return instructionSet; 4841 } 4842 4843 private static String getPreferredInstructionSet() { 4844 if (sPreferredInstructionSet == null) { 4845 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4846 } 4847 4848 return sPreferredInstructionSet; 4849 } 4850 4851 private static List<String> getAllInstructionSets() { 4852 final String[] allAbis = Build.SUPPORTED_ABIS; 4853 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4854 4855 for (String abi : allAbis) { 4856 final String instructionSet = VMRuntime.getInstructionSet(abi); 4857 if (!allInstructionSets.contains(instructionSet)) { 4858 allInstructionSets.add(instructionSet); 4859 } 4860 } 4861 4862 return allInstructionSets; 4863 } 4864 4865 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4866 boolean inclDependencies) { 4867 HashSet<String> done; 4868 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4869 done = new HashSet<String>(); 4870 done.add(pkg.packageName); 4871 } else { 4872 done = null; 4873 } 4874 return performDexOptLI(pkg, null /* instruction set override */, forceDex, defer, done); 4875 } 4876 4877 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4878 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4879 Slog.w(TAG, "Unable to update from " + oldPkg.name 4880 + " to " + newPkg.packageName 4881 + ": old package not in system partition"); 4882 return false; 4883 } else if (mPackages.get(oldPkg.name) != null) { 4884 Slog.w(TAG, "Unable to update from " + oldPkg.name 4885 + " to " + newPkg.packageName 4886 + ": old package still exists"); 4887 return false; 4888 } 4889 return true; 4890 } 4891 4892 File getDataPathForUser(int userId) { 4893 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4894 } 4895 4896 private File getDataPathForPackage(String packageName, int userId) { 4897 /* 4898 * Until we fully support multiple users, return the directory we 4899 * previously would have. The PackageManagerTests will need to be 4900 * revised when this is changed back.. 4901 */ 4902 if (userId == 0) { 4903 return new File(mAppDataDir, packageName); 4904 } else { 4905 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4906 + File.separator + packageName); 4907 } 4908 } 4909 4910 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4911 int[] users = sUserManager.getUserIds(); 4912 int res = mInstaller.install(packageName, uid, uid, seinfo); 4913 if (res < 0) { 4914 return res; 4915 } 4916 for (int user : users) { 4917 if (user != 0) { 4918 res = mInstaller.createUserData(packageName, 4919 UserHandle.getUid(user, uid), user, seinfo); 4920 if (res < 0) { 4921 return res; 4922 } 4923 } 4924 } 4925 return res; 4926 } 4927 4928 private int removeDataDirsLI(String packageName) { 4929 int[] users = sUserManager.getUserIds(); 4930 int res = 0; 4931 for (int user : users) { 4932 int resInner = mInstaller.remove(packageName, user); 4933 if (resInner < 0) { 4934 res = resInner; 4935 } 4936 } 4937 4938 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4939 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4940 if (!nativeLibraryFile.delete()) { 4941 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4942 } 4943 4944 return res; 4945 } 4946 4947 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4948 PackageParser.Package changingLib) { 4949 if (file.path != null) { 4950 usesLibraryFiles.add(file.path); 4951 return; 4952 } 4953 PackageParser.Package p = mPackages.get(file.apk); 4954 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4955 // If we are doing this while in the middle of updating a library apk, 4956 // then we need to make sure to use that new apk for determining the 4957 // dependencies here. (We haven't yet finished committing the new apk 4958 // to the package manager state.) 4959 if (p == null || p.packageName.equals(changingLib.packageName)) { 4960 p = changingLib; 4961 } 4962 } 4963 if (p != null) { 4964 usesLibraryFiles.addAll(p.getAllCodePaths()); 4965 } 4966 } 4967 4968 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4969 PackageParser.Package changingLib) { 4970 // We might be upgrading from a version of the platform that did not 4971 // provide per-package native library directories for system apps. 4972 // Fix that up here. 4973 if (isSystemApp(pkg)) { 4974 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4975 setInternalAppNativeLibraryPath(pkg, ps); 4976 } 4977 4978 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4979 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4980 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4981 for (int i=0; i<N; i++) { 4982 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4983 if (file == null) { 4984 Slog.e(TAG, "Package " + pkg.packageName 4985 + " requires unavailable shared library " 4986 + pkg.usesLibraries.get(i) + "; failing!"); 4987 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4988 return false; 4989 } 4990 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4991 } 4992 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4993 for (int i=0; i<N; i++) { 4994 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4995 if (file == null) { 4996 Slog.w(TAG, "Package " + pkg.packageName 4997 + " desires unavailable shared library " 4998 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4999 } else { 5000 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5001 } 5002 } 5003 N = usesLibraryFiles.size(); 5004 if (N > 0) { 5005 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5006 } else { 5007 pkg.usesLibraryFiles = null; 5008 } 5009 } 5010 return true; 5011 } 5012 5013 private static boolean hasString(List<String> list, List<String> which) { 5014 if (list == null) { 5015 return false; 5016 } 5017 for (int i=list.size()-1; i>=0; i--) { 5018 for (int j=which.size()-1; j>=0; j--) { 5019 if (which.get(j).equals(list.get(i))) { 5020 return true; 5021 } 5022 } 5023 } 5024 return false; 5025 } 5026 5027 private void updateAllSharedLibrariesLPw() { 5028 for (PackageParser.Package pkg : mPackages.values()) { 5029 updateSharedLibrariesLPw(pkg, null); 5030 } 5031 } 5032 5033 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5034 PackageParser.Package changingPkg) { 5035 ArrayList<PackageParser.Package> res = null; 5036 for (PackageParser.Package pkg : mPackages.values()) { 5037 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5038 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5039 if (res == null) { 5040 res = new ArrayList<PackageParser.Package>(); 5041 } 5042 res.add(pkg); 5043 updateSharedLibrariesLPw(pkg, changingPkg); 5044 } 5045 } 5046 return res; 5047 } 5048 5049 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 5050 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 5051 final File scanFile = new File(pkg.codePath); 5052 if (pkg.applicationInfo.sourceDir == null || 5053 pkg.applicationInfo.publicSourceDir == null) { 5054 // Bail out. The resource and code paths haven't been set. 5055 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 5056 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 5057 return null; 5058 } 5059 5060 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5061 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5062 } 5063 5064 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5065 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5066 } 5067 5068 if (mCustomResolverComponentName != null && 5069 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5070 setUpCustomResolverActivity(pkg); 5071 } 5072 5073 if (pkg.packageName.equals("android")) { 5074 synchronized (mPackages) { 5075 if (mAndroidApplication != null) { 5076 Slog.w(TAG, "*************************************************"); 5077 Slog.w(TAG, "Core android package being redefined. Skipping."); 5078 Slog.w(TAG, " file=" + scanFile); 5079 Slog.w(TAG, "*************************************************"); 5080 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 5081 return null; 5082 } 5083 5084 // Set up information for our fall-back user intent resolution activity. 5085 mPlatformPackage = pkg; 5086 pkg.mVersionCode = mSdkVersion; 5087 mAndroidApplication = pkg.applicationInfo; 5088 5089 if (!mResolverReplaced) { 5090 mResolveActivity.applicationInfo = mAndroidApplication; 5091 mResolveActivity.name = ResolverActivity.class.getName(); 5092 mResolveActivity.packageName = mAndroidApplication.packageName; 5093 mResolveActivity.processName = "system:ui"; 5094 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5095 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5096 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5097 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5098 mResolveActivity.exported = true; 5099 mResolveActivity.enabled = true; 5100 mResolveInfo.activityInfo = mResolveActivity; 5101 mResolveInfo.priority = 0; 5102 mResolveInfo.preferredOrder = 0; 5103 mResolveInfo.match = 0; 5104 mResolveComponentName = new ComponentName( 5105 mAndroidApplication.packageName, mResolveActivity.name); 5106 } 5107 } 5108 } 5109 5110 if (DEBUG_PACKAGE_SCANNING) { 5111 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5112 Log.d(TAG, "Scanning package " + pkg.packageName); 5113 } 5114 5115 if (mPackages.containsKey(pkg.packageName) 5116 || mSharedLibraries.containsKey(pkg.packageName)) { 5117 Slog.w(TAG, "Application package " + pkg.packageName 5118 + " already installed. Skipping duplicate."); 5119 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 5120 return null; 5121 } 5122 5123 // Initialize package source and resource directories 5124 File destCodeFile = new File(pkg.applicationInfo.sourceDir); 5125 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir); 5126 5127 SharedUserSetting suid = null; 5128 PackageSetting pkgSetting = null; 5129 5130 if (!isSystemApp(pkg)) { 5131 // Only system apps can use these features. 5132 pkg.mOriginalPackages = null; 5133 pkg.mRealPackage = null; 5134 pkg.mAdoptPermissions = null; 5135 } 5136 5137 // writer 5138 synchronized (mPackages) { 5139 if (pkg.mSharedUserId != null) { 5140 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5141 if (suid == null) { 5142 Slog.w(TAG, "Creating application package " + pkg.packageName 5143 + " for shared user failed"); 5144 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5145 return null; 5146 } 5147 if (DEBUG_PACKAGE_SCANNING) { 5148 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5149 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5150 + "): packages=" + suid.packages); 5151 } 5152 } 5153 5154 // Check if we are renaming from an original package name. 5155 PackageSetting origPackage = null; 5156 String realName = null; 5157 if (pkg.mOriginalPackages != null) { 5158 // This package may need to be renamed to a previously 5159 // installed name. Let's check on that... 5160 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5161 if (pkg.mOriginalPackages.contains(renamed)) { 5162 // This package had originally been installed as the 5163 // original name, and we have already taken care of 5164 // transitioning to the new one. Just update the new 5165 // one to continue using the old name. 5166 realName = pkg.mRealPackage; 5167 if (!pkg.packageName.equals(renamed)) { 5168 // Callers into this function may have already taken 5169 // care of renaming the package; only do it here if 5170 // it is not already done. 5171 pkg.setPackageName(renamed); 5172 } 5173 5174 } else { 5175 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5176 if ((origPackage = mSettings.peekPackageLPr( 5177 pkg.mOriginalPackages.get(i))) != null) { 5178 // We do have the package already installed under its 5179 // original name... should we use it? 5180 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5181 // New package is not compatible with original. 5182 origPackage = null; 5183 continue; 5184 } else if (origPackage.sharedUser != null) { 5185 // Make sure uid is compatible between packages. 5186 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5187 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5188 + " to " + pkg.packageName + ": old uid " 5189 + origPackage.sharedUser.name 5190 + " differs from " + pkg.mSharedUserId); 5191 origPackage = null; 5192 continue; 5193 } 5194 } else { 5195 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5196 + pkg.packageName + " to old name " + origPackage.name); 5197 } 5198 break; 5199 } 5200 } 5201 } 5202 } 5203 5204 if (mTransferedPackages.contains(pkg.packageName)) { 5205 Slog.w(TAG, "Package " + pkg.packageName 5206 + " was transferred to another, but its .apk remains"); 5207 } 5208 5209 // Just create the setting, don't add it yet. For already existing packages 5210 // the PkgSetting exists already and doesn't have to be created. 5211 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5212 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 5213 pkg.applicationInfo.cpuAbi, 5214 pkg.applicationInfo.flags, user, false); 5215 if (pkgSetting == null) { 5216 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 5217 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5218 return null; 5219 } 5220 5221 if (pkgSetting.origPackage != null) { 5222 // If we are first transitioning from an original package, 5223 // fix up the new package's name now. We need to do this after 5224 // looking up the package under its new name, so getPackageLP 5225 // can take care of fiddling things correctly. 5226 pkg.setPackageName(origPackage.name); 5227 5228 // File a report about this. 5229 String msg = "New package " + pkgSetting.realName 5230 + " renamed to replace old package " + pkgSetting.name; 5231 reportSettingsProblem(Log.WARN, msg); 5232 5233 // Make a note of it. 5234 mTransferedPackages.add(origPackage.name); 5235 5236 // No longer need to retain this. 5237 pkgSetting.origPackage = null; 5238 } 5239 5240 if (realName != null) { 5241 // Make a note of it. 5242 mTransferedPackages.add(pkg.packageName); 5243 } 5244 5245 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5246 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5247 } 5248 5249 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5250 // Check all shared libraries and map to their actual file path. 5251 // We only do this here for apps not on a system dir, because those 5252 // are the only ones that can fail an install due to this. We 5253 // will take care of the system apps by updating all of their 5254 // library paths after the scan is done. 5255 if (!updateSharedLibrariesLPw(pkg, null)) { 5256 return null; 5257 } 5258 } 5259 5260 if (mFoundPolicyFile) { 5261 SELinuxMMAC.assignSeinfoValue(pkg); 5262 } 5263 5264 pkg.applicationInfo.uid = pkgSetting.appId; 5265 pkg.mExtras = pkgSetting; 5266 5267 if (!verifySignaturesLP(pkgSetting, pkg)) { 5268 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5269 return null; 5270 } 5271 // The signature has changed, but this package is in the system 5272 // image... let's recover! 5273 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5274 // However... if this package is part of a shared user, but it 5275 // doesn't match the signature of the shared user, let's fail. 5276 // What this means is that you can't change the signatures 5277 // associated with an overall shared user, which doesn't seem all 5278 // that unreasonable. 5279 if (pkgSetting.sharedUser != null) { 5280 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5281 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5282 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 5283 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 5284 return null; 5285 } 5286 } 5287 // File a report about this. 5288 String msg = "System package " + pkg.packageName 5289 + " signature changed; retaining data."; 5290 reportSettingsProblem(Log.WARN, msg); 5291 } 5292 5293 // Verify that this new package doesn't have any content providers 5294 // that conflict with existing packages. Only do this if the 5295 // package isn't already installed, since we don't want to break 5296 // things that are installed. 5297 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5298 final int N = pkg.providers.size(); 5299 int i; 5300 for (i=0; i<N; i++) { 5301 PackageParser.Provider p = pkg.providers.get(i); 5302 if (p.info.authority != null) { 5303 String names[] = p.info.authority.split(";"); 5304 for (int j = 0; j < names.length; j++) { 5305 if (mProvidersByAuthority.containsKey(names[j])) { 5306 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5307 Slog.w(TAG, "Can't install because provider name " + names[j] + 5308 " (in package " + pkg.applicationInfo.packageName + 5309 ") is already used by " 5310 + ((other != null && other.getComponentName() != null) 5311 ? other.getComponentName().getPackageName() : "?")); 5312 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 5313 return null; 5314 } 5315 } 5316 } 5317 } 5318 } 5319 5320 if (pkg.mAdoptPermissions != null) { 5321 // This package wants to adopt ownership of permissions from 5322 // another package. 5323 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5324 final String origName = pkg.mAdoptPermissions.get(i); 5325 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5326 if (orig != null) { 5327 if (verifyPackageUpdateLPr(orig, pkg)) { 5328 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5329 + pkg.packageName); 5330 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5331 } 5332 } 5333 } 5334 } 5335 } 5336 5337 final String pkgName = pkg.packageName; 5338 5339 final long scanFileTime = scanFile.lastModified(); 5340 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5341 pkg.applicationInfo.processName = fixProcessName( 5342 pkg.applicationInfo.packageName, 5343 pkg.applicationInfo.processName, 5344 pkg.applicationInfo.uid); 5345 5346 File dataPath; 5347 if (mPlatformPackage == pkg) { 5348 // The system package is special. 5349 dataPath = new File (Environment.getDataDirectory(), "system"); 5350 pkg.applicationInfo.dataDir = dataPath.getPath(); 5351 } else { 5352 // This is a normal package, need to make its data directory. 5353 dataPath = getDataPathForPackage(pkg.packageName, 0); 5354 5355 boolean uidError = false; 5356 5357 if (dataPath.exists()) { 5358 int currentUid = 0; 5359 try { 5360 StructStat stat = Os.stat(dataPath.getPath()); 5361 currentUid = stat.st_uid; 5362 } catch (ErrnoException e) { 5363 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5364 } 5365 5366 // If we have mismatched owners for the data path, we have a problem. 5367 if (currentUid != pkg.applicationInfo.uid) { 5368 boolean recovered = false; 5369 if (currentUid == 0) { 5370 // The directory somehow became owned by root. Wow. 5371 // This is probably because the system was stopped while 5372 // installd was in the middle of messing with its libs 5373 // directory. Ask installd to fix that. 5374 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5375 pkg.applicationInfo.uid); 5376 if (ret >= 0) { 5377 recovered = true; 5378 String msg = "Package " + pkg.packageName 5379 + " unexpectedly changed to uid 0; recovered to " + 5380 + pkg.applicationInfo.uid; 5381 reportSettingsProblem(Log.WARN, msg); 5382 } 5383 } 5384 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5385 || (scanMode&SCAN_BOOTING) != 0)) { 5386 // If this is a system app, we can at least delete its 5387 // current data so the application will still work. 5388 int ret = removeDataDirsLI(pkgName); 5389 if (ret >= 0) { 5390 // TODO: Kill the processes first 5391 // Old data gone! 5392 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5393 ? "System package " : "Third party package "; 5394 String msg = prefix + pkg.packageName 5395 + " has changed from uid: " 5396 + currentUid + " to " 5397 + pkg.applicationInfo.uid + "; old data erased"; 5398 reportSettingsProblem(Log.WARN, msg); 5399 recovered = true; 5400 5401 // And now re-install the app. 5402 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5403 pkg.applicationInfo.seinfo); 5404 if (ret == -1) { 5405 // Ack should not happen! 5406 msg = prefix + pkg.packageName 5407 + " could not have data directory re-created after delete."; 5408 reportSettingsProblem(Log.WARN, msg); 5409 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5410 return null; 5411 } 5412 } 5413 if (!recovered) { 5414 mHasSystemUidErrors = true; 5415 } 5416 } else if (!recovered) { 5417 // If we allow this install to proceed, we will be broken. 5418 // Abort, abort! 5419 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 5420 return null; 5421 } 5422 if (!recovered) { 5423 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5424 + pkg.applicationInfo.uid + "/fs_" 5425 + currentUid; 5426 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5427 String msg = "Package " + pkg.packageName 5428 + " has mismatched uid: " 5429 + currentUid + " on disk, " 5430 + pkg.applicationInfo.uid + " in settings"; 5431 // writer 5432 synchronized (mPackages) { 5433 mSettings.mReadMessages.append(msg); 5434 mSettings.mReadMessages.append('\n'); 5435 uidError = true; 5436 if (!pkgSetting.uidError) { 5437 reportSettingsProblem(Log.ERROR, msg); 5438 } 5439 } 5440 } 5441 } 5442 pkg.applicationInfo.dataDir = dataPath.getPath(); 5443 if (mShouldRestoreconData) { 5444 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5445 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5446 pkg.applicationInfo.uid); 5447 } 5448 } else { 5449 if (DEBUG_PACKAGE_SCANNING) { 5450 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5451 Log.v(TAG, "Want this data dir: " + dataPath); 5452 } 5453 //invoke installer to do the actual installation 5454 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5455 pkg.applicationInfo.seinfo); 5456 if (ret < 0) { 5457 // Error from installer 5458 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5459 return null; 5460 } 5461 5462 if (dataPath.exists()) { 5463 pkg.applicationInfo.dataDir = dataPath.getPath(); 5464 } else { 5465 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5466 pkg.applicationInfo.dataDir = null; 5467 } 5468 } 5469 5470 /* 5471 * Set the data dir to the default "/data/data/<package name>/lib" 5472 * if we got here without anyone telling us different (e.g., apps 5473 * stored on SD card have their native libraries stored in the ASEC 5474 * container with the APK). 5475 * 5476 * This happens during an upgrade from a package settings file that 5477 * doesn't have a native library path attribute at all. 5478 */ 5479 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 5480 if (pkgSetting.nativeLibraryPathString == null) { 5481 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5482 } else { 5483 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 5484 } 5485 } 5486 pkgSetting.uidError = uidError; 5487 } 5488 5489 final String path = scanFile.getPath(); 5490 /* Note: We don't want to unpack the native binaries for 5491 * system applications, unless they have been updated 5492 * (the binaries are already under /system/lib). 5493 * Also, don't unpack libs for apps on the external card 5494 * since they should have their libraries in the ASEC 5495 * container already. 5496 * 5497 * In other words, we're going to unpack the binaries 5498 * only for non-system apps and system app upgrades. 5499 */ 5500 if (pkg.applicationInfo.nativeLibraryDir != null) { 5501 // TODO: extend to extract native code from split APKs 5502 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile); 5503 try { 5504 // Enable gross and lame hacks for apps that are built with old 5505 // SDK tools. We must scan their APKs for renderscript bitcode and 5506 // not launch them if it's present. Don't bother checking on devices 5507 // that don't have 64 bit support. 5508 String[] abiList = Build.SUPPORTED_ABIS; 5509 boolean hasLegacyRenderscriptBitcode = false; 5510 if (abiOverride != null) { 5511 abiList = new String[] { abiOverride }; 5512 } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 5513 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5514 abiList = Build.SUPPORTED_32_BIT_ABIS; 5515 hasLegacyRenderscriptBitcode = true; 5516 } 5517 5518 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5519 final String dataPathString = dataPath.getCanonicalPath(); 5520 5521 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5522 /* 5523 * Upgrading from a previous version of the OS sometimes 5524 * leaves native libraries in the /data/data/<app>/lib 5525 * directory for system apps even when they shouldn't be. 5526 * Recent changes in the JNI library search path 5527 * necessitates we remove those to match previous behavior. 5528 */ 5529 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 5530 Log.i(TAG, "removed obsolete native libraries for system package " 5531 + path); 5532 } 5533 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5534 pkg.applicationInfo.cpuAbi = abiList[0]; 5535 pkgSetting.cpuAbiString = abiList[0]; 5536 } else { 5537 setInternalAppAbi(pkg, pkgSetting); 5538 } 5539 } else { 5540 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 5541 /* 5542 * Update native library dir if it starts with 5543 * /data/data 5544 */ 5545 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 5546 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5547 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5548 } 5549 5550 try { 5551 int copyRet = copyNativeLibrariesForInternalApp(handle, 5552 nativeLibraryDir, abiList); 5553 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5554 Slog.e(TAG, "Unable to copy native libraries"); 5555 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5556 return null; 5557 } 5558 5559 // We've successfully copied native libraries across, so we make a 5560 // note of what ABI we're using 5561 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5562 pkg.applicationInfo.cpuAbi = abiList[copyRet]; 5563 } else if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5564 pkg.applicationInfo.cpuAbi = abiList[0]; 5565 } else { 5566 pkg.applicationInfo.cpuAbi = null; 5567 } 5568 } catch (IOException e) { 5569 Slog.e(TAG, "Unable to copy native libraries", e); 5570 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5571 return null; 5572 } 5573 } else { 5574 // We don't have to copy the shared libraries if we're in the ASEC container 5575 // but we still need to scan the file to figure out what ABI the app needs. 5576 // 5577 // TODO: This duplicates work done in the default container service. It's possible 5578 // to clean this up but we'll need to change the interface between this service 5579 // and IMediaContainerService (but doing so will spread this logic out, rather 5580 // than centralizing it). 5581 final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5582 if (abi >= 0) { 5583 pkg.applicationInfo.cpuAbi = abiList[abi]; 5584 } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) { 5585 // Note that (non upgraded) system apps will not have any native 5586 // libraries bundled in their APK, but we're guaranteed not to be 5587 // such an app at this point. 5588 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5589 pkg.applicationInfo.cpuAbi = abiList[0]; 5590 } else { 5591 pkg.applicationInfo.cpuAbi = null; 5592 } 5593 } else { 5594 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5595 return null; 5596 } 5597 } 5598 5599 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5600 final int[] userIds = sUserManager.getUserIds(); 5601 synchronized (mInstallLock) { 5602 for (int userId : userIds) { 5603 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 5604 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 5605 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5606 + ")"); 5607 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5608 return null; 5609 } 5610 } 5611 } 5612 } 5613 5614 pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi; 5615 } catch (IOException ioe) { 5616 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5617 } finally { 5618 handle.close(); 5619 } 5620 } 5621 5622 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5623 // We don't do this here during boot because we can do it all 5624 // at once after scanning all existing packages. 5625 // 5626 // We also do this *before* we perform dexopt on this package, so that 5627 // we can avoid redundant dexopts, and also to make sure we've got the 5628 // code and package path correct. 5629 if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5630 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) { 5631 mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE; 5632 return null; 5633 } 5634 } 5635 5636 if ((scanMode&SCAN_NO_DEX) == 0) { 5637 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5638 == DEX_OPT_FAILED) { 5639 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5640 removeDataDirsLI(pkg.packageName); 5641 } 5642 5643 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5644 return null; 5645 } 5646 } 5647 5648 if (mFactoryTest && pkg.requestedPermissions.contains( 5649 android.Manifest.permission.FACTORY_TEST)) { 5650 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5651 } 5652 5653 ArrayList<PackageParser.Package> clientLibPkgs = null; 5654 5655 // writer 5656 synchronized (mPackages) { 5657 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5658 // Only system apps can add new shared libraries. 5659 if (pkg.libraryNames != null) { 5660 for (int i=0; i<pkg.libraryNames.size(); i++) { 5661 String name = pkg.libraryNames.get(i); 5662 boolean allowed = false; 5663 if (isUpdatedSystemApp(pkg)) { 5664 // New library entries can only be added through the 5665 // system image. This is important to get rid of a lot 5666 // of nasty edge cases: for example if we allowed a non- 5667 // system update of the app to add a library, then uninstalling 5668 // the update would make the library go away, and assumptions 5669 // we made such as through app install filtering would now 5670 // have allowed apps on the device which aren't compatible 5671 // with it. Better to just have the restriction here, be 5672 // conservative, and create many fewer cases that can negatively 5673 // impact the user experience. 5674 final PackageSetting sysPs = mSettings 5675 .getDisabledSystemPkgLPr(pkg.packageName); 5676 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5677 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5678 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5679 allowed = true; 5680 allowed = true; 5681 break; 5682 } 5683 } 5684 } 5685 } else { 5686 allowed = true; 5687 } 5688 if (allowed) { 5689 if (!mSharedLibraries.containsKey(name)) { 5690 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5691 } else if (!name.equals(pkg.packageName)) { 5692 Slog.w(TAG, "Package " + pkg.packageName + " library " 5693 + name + " already exists; skipping"); 5694 } 5695 } else { 5696 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5697 + name + " that is not declared on system image; skipping"); 5698 } 5699 } 5700 if ((scanMode&SCAN_BOOTING) == 0) { 5701 // If we are not booting, we need to update any applications 5702 // that are clients of our shared library. If we are booting, 5703 // this will all be done once the scan is complete. 5704 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5705 } 5706 } 5707 } 5708 } 5709 5710 // We also need to dexopt any apps that are dependent on this library. Note that 5711 // if these fail, we should abort the install since installing the library will 5712 // result in some apps being broken. 5713 if (clientLibPkgs != null) { 5714 if ((scanMode&SCAN_NO_DEX) == 0) { 5715 for (int i=0; i<clientLibPkgs.size(); i++) { 5716 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5717 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5718 == DEX_OPT_FAILED) { 5719 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5720 removeDataDirsLI(pkg.packageName); 5721 } 5722 5723 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5724 return null; 5725 } 5726 } 5727 } 5728 } 5729 5730 // Request the ActivityManager to kill the process(only for existing packages) 5731 // so that we do not end up in a confused state while the user is still using the older 5732 // version of the application while the new one gets installed. 5733 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5734 // If the package lives in an asec, tell everyone that the container is going 5735 // away so they can clean up any references to its resources (which would prevent 5736 // vold from being able to unmount the asec) 5737 if (isForwardLocked(pkg) || isExternal(pkg)) { 5738 if (DEBUG_INSTALL) { 5739 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5740 } 5741 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5742 final ArrayList<String> pkgList = new ArrayList<String>(1); 5743 pkgList.add(pkg.applicationInfo.packageName); 5744 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5745 } 5746 5747 // Post the request that it be killed now that the going-away broadcast is en route 5748 killApplication(pkg.applicationInfo.packageName, 5749 pkg.applicationInfo.uid, "update pkg"); 5750 } 5751 5752 // Also need to kill any apps that are dependent on the library. 5753 if (clientLibPkgs != null) { 5754 for (int i=0; i<clientLibPkgs.size(); i++) { 5755 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5756 killApplication(clientPkg.applicationInfo.packageName, 5757 clientPkg.applicationInfo.uid, "update lib"); 5758 } 5759 } 5760 5761 // writer 5762 synchronized (mPackages) { 5763 // We don't expect installation to fail beyond this point, 5764 if ((scanMode&SCAN_MONITOR) != 0) { 5765 mAppDirs.put(pkg.codePath, pkg); 5766 } 5767 // Add the new setting to mSettings 5768 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5769 // Add the new setting to mPackages 5770 mPackages.put(pkg.applicationInfo.packageName, pkg); 5771 // Make sure we don't accidentally delete its data. 5772 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5773 while (iter.hasNext()) { 5774 PackageCleanItem item = iter.next(); 5775 if (pkgName.equals(item.packageName)) { 5776 iter.remove(); 5777 } 5778 } 5779 5780 // Take care of first install / last update times. 5781 if (currentTime != 0) { 5782 if (pkgSetting.firstInstallTime == 0) { 5783 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5784 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5785 pkgSetting.lastUpdateTime = currentTime; 5786 } 5787 } else if (pkgSetting.firstInstallTime == 0) { 5788 // We need *something*. Take time time stamp of the file. 5789 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5790 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5791 if (scanFileTime != pkgSetting.timeStamp) { 5792 // A package on the system image has changed; consider this 5793 // to be an update. 5794 pkgSetting.lastUpdateTime = scanFileTime; 5795 } 5796 } 5797 5798 // Add the package's KeySets to the global KeySetManager 5799 KeySetManager ksm = mSettings.mKeySetManager; 5800 try { 5801 ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5802 if (pkg.mKeySetMapping != null) { 5803 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5804 pkg.mKeySetMapping.entrySet()) { 5805 if (entry.getValue() != null) { 5806 ksm.addDefinedKeySetToPackage(pkg.packageName, 5807 entry.getValue(), entry.getKey()); 5808 } 5809 } 5810 } 5811 } catch (NullPointerException e) { 5812 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5813 } catch (IllegalArgumentException e) { 5814 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5815 } 5816 5817 int N = pkg.providers.size(); 5818 StringBuilder r = null; 5819 int i; 5820 for (i=0; i<N; i++) { 5821 PackageParser.Provider p = pkg.providers.get(i); 5822 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5823 p.info.processName, pkg.applicationInfo.uid); 5824 mProviders.addProvider(p); 5825 p.syncable = p.info.isSyncable; 5826 if (p.info.authority != null) { 5827 String names[] = p.info.authority.split(";"); 5828 p.info.authority = null; 5829 for (int j = 0; j < names.length; j++) { 5830 if (j == 1 && p.syncable) { 5831 // We only want the first authority for a provider to possibly be 5832 // syncable, so if we already added this provider using a different 5833 // authority clear the syncable flag. We copy the provider before 5834 // changing it because the mProviders object contains a reference 5835 // to a provider that we don't want to change. 5836 // Only do this for the second authority since the resulting provider 5837 // object can be the same for all future authorities for this provider. 5838 p = new PackageParser.Provider(p); 5839 p.syncable = false; 5840 } 5841 if (!mProvidersByAuthority.containsKey(names[j])) { 5842 mProvidersByAuthority.put(names[j], p); 5843 if (p.info.authority == null) { 5844 p.info.authority = names[j]; 5845 } else { 5846 p.info.authority = p.info.authority + ";" + names[j]; 5847 } 5848 if (DEBUG_PACKAGE_SCANNING) { 5849 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5850 Log.d(TAG, "Registered content provider: " + names[j] 5851 + ", className = " + p.info.name + ", isSyncable = " 5852 + p.info.isSyncable); 5853 } 5854 } else { 5855 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5856 Slog.w(TAG, "Skipping provider name " + names[j] + 5857 " (in package " + pkg.applicationInfo.packageName + 5858 "): name already used by " 5859 + ((other != null && other.getComponentName() != null) 5860 ? other.getComponentName().getPackageName() : "?")); 5861 } 5862 } 5863 } 5864 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5865 if (r == null) { 5866 r = new StringBuilder(256); 5867 } else { 5868 r.append(' '); 5869 } 5870 r.append(p.info.name); 5871 } 5872 } 5873 if (r != null) { 5874 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5875 } 5876 5877 N = pkg.services.size(); 5878 r = null; 5879 for (i=0; i<N; i++) { 5880 PackageParser.Service s = pkg.services.get(i); 5881 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5882 s.info.processName, pkg.applicationInfo.uid); 5883 mServices.addService(s); 5884 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5885 if (r == null) { 5886 r = new StringBuilder(256); 5887 } else { 5888 r.append(' '); 5889 } 5890 r.append(s.info.name); 5891 } 5892 } 5893 if (r != null) { 5894 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5895 } 5896 5897 N = pkg.receivers.size(); 5898 r = null; 5899 for (i=0; i<N; i++) { 5900 PackageParser.Activity a = pkg.receivers.get(i); 5901 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5902 a.info.processName, pkg.applicationInfo.uid); 5903 mReceivers.addActivity(a, "receiver"); 5904 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5905 if (r == null) { 5906 r = new StringBuilder(256); 5907 } else { 5908 r.append(' '); 5909 } 5910 r.append(a.info.name); 5911 } 5912 } 5913 if (r != null) { 5914 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5915 } 5916 5917 N = pkg.activities.size(); 5918 r = null; 5919 for (i=0; i<N; i++) { 5920 PackageParser.Activity a = pkg.activities.get(i); 5921 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5922 a.info.processName, pkg.applicationInfo.uid); 5923 mActivities.addActivity(a, "activity"); 5924 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5925 if (r == null) { 5926 r = new StringBuilder(256); 5927 } else { 5928 r.append(' '); 5929 } 5930 r.append(a.info.name); 5931 } 5932 } 5933 if (r != null) { 5934 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5935 } 5936 5937 N = pkg.permissionGroups.size(); 5938 r = null; 5939 for (i=0; i<N; i++) { 5940 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5941 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5942 if (cur == null) { 5943 mPermissionGroups.put(pg.info.name, pg); 5944 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5945 if (r == null) { 5946 r = new StringBuilder(256); 5947 } else { 5948 r.append(' '); 5949 } 5950 r.append(pg.info.name); 5951 } 5952 } else { 5953 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5954 + pg.info.packageName + " ignored: original from " 5955 + cur.info.packageName); 5956 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5957 if (r == null) { 5958 r = new StringBuilder(256); 5959 } else { 5960 r.append(' '); 5961 } 5962 r.append("DUP:"); 5963 r.append(pg.info.name); 5964 } 5965 } 5966 } 5967 if (r != null) { 5968 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5969 } 5970 5971 N = pkg.permissions.size(); 5972 r = null; 5973 for (i=0; i<N; i++) { 5974 PackageParser.Permission p = pkg.permissions.get(i); 5975 HashMap<String, BasePermission> permissionMap = 5976 p.tree ? mSettings.mPermissionTrees 5977 : mSettings.mPermissions; 5978 p.group = mPermissionGroups.get(p.info.group); 5979 if (p.info.group == null || p.group != null) { 5980 BasePermission bp = permissionMap.get(p.info.name); 5981 if (bp == null) { 5982 bp = new BasePermission(p.info.name, p.info.packageName, 5983 BasePermission.TYPE_NORMAL); 5984 permissionMap.put(p.info.name, bp); 5985 } 5986 if (bp.perm == null) { 5987 if (bp.sourcePackage != null 5988 && !bp.sourcePackage.equals(p.info.packageName)) { 5989 // If this is a permission that was formerly defined by a non-system 5990 // app, but is now defined by a system app (following an upgrade), 5991 // discard the previous declaration and consider the system's to be 5992 // canonical. 5993 if (isSystemApp(p.owner)) { 5994 String msg = "New decl " + p.owner + " of permission " 5995 + p.info.name + " is system"; 5996 reportSettingsProblem(Log.WARN, msg); 5997 bp.sourcePackage = null; 5998 } 5999 } 6000 if (bp.sourcePackage == null 6001 || bp.sourcePackage.equals(p.info.packageName)) { 6002 BasePermission tree = findPermissionTreeLP(p.info.name); 6003 if (tree == null 6004 || tree.sourcePackage.equals(p.info.packageName)) { 6005 bp.packageSetting = pkgSetting; 6006 bp.perm = p; 6007 bp.uid = pkg.applicationInfo.uid; 6008 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6009 if (r == null) { 6010 r = new StringBuilder(256); 6011 } else { 6012 r.append(' '); 6013 } 6014 r.append(p.info.name); 6015 } 6016 } else { 6017 Slog.w(TAG, "Permission " + p.info.name + " from package " 6018 + p.info.packageName + " ignored: base tree " 6019 + tree.name + " is from package " 6020 + tree.sourcePackage); 6021 } 6022 } else { 6023 Slog.w(TAG, "Permission " + p.info.name + " from package " 6024 + p.info.packageName + " ignored: original from " 6025 + bp.sourcePackage); 6026 } 6027 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6028 if (r == null) { 6029 r = new StringBuilder(256); 6030 } else { 6031 r.append(' '); 6032 } 6033 r.append("DUP:"); 6034 r.append(p.info.name); 6035 } 6036 if (bp.perm == p) { 6037 bp.protectionLevel = p.info.protectionLevel; 6038 } 6039 } else { 6040 Slog.w(TAG, "Permission " + p.info.name + " from package " 6041 + p.info.packageName + " ignored: no group " 6042 + p.group); 6043 } 6044 } 6045 if (r != null) { 6046 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6047 } 6048 6049 N = pkg.instrumentation.size(); 6050 r = null; 6051 for (i=0; i<N; i++) { 6052 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6053 a.info.packageName = pkg.applicationInfo.packageName; 6054 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6055 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6056 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6057 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6058 a.info.dataDir = pkg.applicationInfo.dataDir; 6059 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6060 mInstrumentation.put(a.getComponentName(), a); 6061 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6062 if (r == null) { 6063 r = new StringBuilder(256); 6064 } else { 6065 r.append(' '); 6066 } 6067 r.append(a.info.name); 6068 } 6069 } 6070 if (r != null) { 6071 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6072 } 6073 6074 if (pkg.protectedBroadcasts != null) { 6075 N = pkg.protectedBroadcasts.size(); 6076 for (i=0; i<N; i++) { 6077 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6078 } 6079 } 6080 6081 pkgSetting.setTimeStamp(scanFileTime); 6082 6083 // Create idmap files for pairs of (packages, overlay packages). 6084 // Note: "android", ie framework-res.apk, is handled by native layers. 6085 if (pkg.mOverlayTarget != null) { 6086 // This is an overlay package. 6087 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6088 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6089 mOverlays.put(pkg.mOverlayTarget, 6090 new HashMap<String, PackageParser.Package>()); 6091 } 6092 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6093 map.put(pkg.packageName, pkg); 6094 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6095 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6096 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 6097 return null; 6098 } 6099 } 6100 } else if (mOverlays.containsKey(pkg.packageName) && 6101 !pkg.packageName.equals("android")) { 6102 // This is a regular package, with one or more known overlay packages. 6103 createIdmapsForPackageLI(pkg); 6104 } 6105 } 6106 6107 return pkg; 6108 } 6109 6110 /** 6111 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6112 * i.e, so that all packages can be run inside a single process if required. 6113 * 6114 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6115 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6116 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6117 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6118 * updating a package that belongs to a shared user. 6119 */ 6120 private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6121 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6122 String requiredInstructionSet = null; 6123 if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) { 6124 requiredInstructionSet = VMRuntime.getInstructionSet( 6125 scannedPackage.applicationInfo.cpuAbi); 6126 } 6127 6128 PackageSetting requirer = null; 6129 for (PackageSetting ps : packagesForUser) { 6130 // If packagesForUser contains scannedPackage, we skip it. This will happen 6131 // when scannedPackage is an update of an existing package. Without this check, 6132 // we will never be able to change the ABI of any package belonging to a shared 6133 // user, even if it's compatible with other packages. 6134 if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) { 6135 if (ps.cpuAbiString == null) { 6136 continue; 6137 } 6138 6139 final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 6140 if (requiredInstructionSet != null) { 6141 if (!instructionSet.equals(requiredInstructionSet)) { 6142 // We have a mismatch between instruction sets (say arm vs arm64). 6143 // bail out. 6144 String errorMessage = "Instruction set mismatch, " 6145 + ((requirer == null) ? "[caller]" : requirer) 6146 + " requires " + requiredInstructionSet + " whereas " + ps 6147 + " requires " + instructionSet; 6148 Slog.e(TAG, errorMessage); 6149 6150 reportSettingsProblem(Log.WARN, errorMessage); 6151 // Give up, don't bother making any other changes to the package settings. 6152 return false; 6153 } 6154 } else { 6155 requiredInstructionSet = instructionSet; 6156 requirer = ps; 6157 } 6158 } 6159 } 6160 6161 if (requiredInstructionSet != null) { 6162 String adjustedAbi; 6163 if (requirer != null) { 6164 // requirer != null implies that either scannedPackage was null or that scannedPackage 6165 // did not require an ABI, in which case we have to adjust scannedPackage to match 6166 // the ABI of the set (which is the same as requirer's ABI) 6167 adjustedAbi = requirer.cpuAbiString; 6168 if (scannedPackage != null) { 6169 scannedPackage.applicationInfo.cpuAbi = adjustedAbi; 6170 } 6171 } else { 6172 // requirer == null implies that we're updating all ABIs in the set to 6173 // match scannedPackage. 6174 adjustedAbi = scannedPackage.applicationInfo.cpuAbi; 6175 } 6176 6177 for (PackageSetting ps : packagesForUser) { 6178 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6179 if (ps.cpuAbiString != null) { 6180 continue; 6181 } 6182 6183 ps.cpuAbiString = adjustedAbi; 6184 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6185 ps.pkg.applicationInfo.cpuAbi = adjustedAbi; 6186 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6187 6188 if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) { 6189 ps.cpuAbiString = null; 6190 ps.pkg.applicationInfo.cpuAbi = null; 6191 return false; 6192 } else { 6193 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6194 } 6195 } 6196 } 6197 } 6198 } 6199 6200 return true; 6201 } 6202 6203 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6204 synchronized (mPackages) { 6205 mResolverReplaced = true; 6206 // Set up information for custom user intent resolution activity. 6207 mResolveActivity.applicationInfo = pkg.applicationInfo; 6208 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6209 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6210 mResolveActivity.processName = null; 6211 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6212 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6213 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6214 mResolveActivity.theme = 0; 6215 mResolveActivity.exported = true; 6216 mResolveActivity.enabled = true; 6217 mResolveInfo.activityInfo = mResolveActivity; 6218 mResolveInfo.priority = 0; 6219 mResolveInfo.preferredOrder = 0; 6220 mResolveInfo.match = 0; 6221 mResolveComponentName = mCustomResolverComponentName; 6222 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6223 mResolveComponentName); 6224 } 6225 } 6226 6227 private String calculateApkRoot(final String codePathString) { 6228 final File codePath = new File(codePathString); 6229 final File codeRoot; 6230 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6231 codeRoot = Environment.getRootDirectory(); 6232 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6233 codeRoot = Environment.getOemDirectory(); 6234 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6235 codeRoot = Environment.getVendorDirectory(); 6236 } else { 6237 // Unrecognized code path; take its top real segment as the apk root: 6238 // e.g. /something/app/blah.apk => /something 6239 try { 6240 File f = codePath.getCanonicalFile(); 6241 File parent = f.getParentFile(); // non-null because codePath is a file 6242 File tmp; 6243 while ((tmp = parent.getParentFile()) != null) { 6244 f = parent; 6245 parent = tmp; 6246 } 6247 codeRoot = f; 6248 Slog.w(TAG, "Unrecognized code path " 6249 + codePath + " - using " + codeRoot); 6250 } catch (IOException e) { 6251 // Can't canonicalize the lib path -- shenanigans? 6252 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6253 return Environment.getRootDirectory().getPath(); 6254 } 6255 } 6256 return codeRoot.getPath(); 6257 } 6258 6259 // This is the initial scan-time determination of how to handle a given 6260 // package for purposes of native library location. 6261 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 6262 PackageSetting pkgSetting) { 6263 // "bundled" here means system-installed with no overriding update 6264 final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg); 6265 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 6266 final File libDir; 6267 if (bundledApk) { 6268 // If "/system/lib64/apkname" exists, assume that is the per-package 6269 // native library directory to use; otherwise use "/system/lib/apkname". 6270 String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6271 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 6272 File packLib64 = new File(lib64, apkName); 6273 libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 6274 } else { 6275 libDir = mAppLibInstallDir; 6276 } 6277 final String nativeLibraryPath = (new File(libDir, apkName)).getPath(); 6278 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 6279 // pkgSetting might be null during rescan following uninstall of updates 6280 // to a bundled app, so accommodate that possibility. The settings in 6281 // that case will be established later from the parsed package. 6282 if (pkgSetting != null) { 6283 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 6284 } 6285 } 6286 6287 // Deduces the required ABI of an upgraded system app. 6288 private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) { 6289 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6290 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 6291 6292 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 6293 // or similar. 6294 final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath()); 6295 final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath()); 6296 6297 // Assume that the bundled native libraries always correspond to the 6298 // most preferred 32 or 64 bit ABI. 6299 if (lib64.exists()) { 6300 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6301 pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0]; 6302 } else if (lib.exists()) { 6303 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6304 pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0]; 6305 } else { 6306 // This is the case where the app has no native code. 6307 pkg.applicationInfo.cpuAbi = null; 6308 pkgSetting.cpuAbiString = null; 6309 } 6310 } 6311 6312 private static int copyNativeLibrariesForInternalApp(ApkHandle handle, 6313 final File nativeLibraryDir, String[] abiList) throws IOException { 6314 if (!nativeLibraryDir.isDirectory()) { 6315 nativeLibraryDir.delete(); 6316 6317 if (!nativeLibraryDir.mkdir()) { 6318 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 6319 } 6320 6321 try { 6322 Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6323 } catch (ErrnoException e) { 6324 throw new IOException("Cannot chmod native library directory " 6325 + nativeLibraryDir.getPath(), e); 6326 } 6327 } else if (!SELinux.restorecon(nativeLibraryDir)) { 6328 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 6329 } 6330 6331 /* 6332 * If this is an internal application or our nativeLibraryPath points to 6333 * the app-lib directory, unpack the libraries if necessary. 6334 */ 6335 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6336 if (abi >= 0) { 6337 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 6338 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 6339 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6340 return copyRet; 6341 } 6342 } 6343 6344 return abi; 6345 } 6346 6347 private void killApplication(String pkgName, int appId, String reason) { 6348 // Request the ActivityManager to kill the process(only for existing packages) 6349 // so that we do not end up in a confused state while the user is still using the older 6350 // version of the application while the new one gets installed. 6351 IActivityManager am = ActivityManagerNative.getDefault(); 6352 if (am != null) { 6353 try { 6354 am.killApplicationWithAppId(pkgName, appId, reason); 6355 } catch (RemoteException e) { 6356 } 6357 } 6358 } 6359 6360 void removePackageLI(PackageSetting ps, boolean chatty) { 6361 if (DEBUG_INSTALL) { 6362 if (chatty) 6363 Log.d(TAG, "Removing package " + ps.name); 6364 } 6365 6366 // writer 6367 synchronized (mPackages) { 6368 mPackages.remove(ps.name); 6369 if (ps.codePathString != null) { 6370 mAppDirs.remove(ps.codePathString); 6371 } 6372 6373 final PackageParser.Package pkg = ps.pkg; 6374 if (pkg != null) { 6375 cleanPackageDataStructuresLILPw(pkg, chatty); 6376 } 6377 } 6378 } 6379 6380 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6381 if (DEBUG_INSTALL) { 6382 if (chatty) 6383 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6384 } 6385 6386 // writer 6387 synchronized (mPackages) { 6388 mPackages.remove(pkg.applicationInfo.packageName); 6389 if (pkg.codePath != null) { 6390 mAppDirs.remove(pkg.codePath); 6391 } 6392 cleanPackageDataStructuresLILPw(pkg, chatty); 6393 } 6394 } 6395 6396 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6397 int N = pkg.providers.size(); 6398 StringBuilder r = null; 6399 int i; 6400 for (i=0; i<N; i++) { 6401 PackageParser.Provider p = pkg.providers.get(i); 6402 mProviders.removeProvider(p); 6403 if (p.info.authority == null) { 6404 6405 /* There was another ContentProvider with this authority when 6406 * this app was installed so this authority is null, 6407 * Ignore it as we don't have to unregister the provider. 6408 */ 6409 continue; 6410 } 6411 String names[] = p.info.authority.split(";"); 6412 for (int j = 0; j < names.length; j++) { 6413 if (mProvidersByAuthority.get(names[j]) == p) { 6414 mProvidersByAuthority.remove(names[j]); 6415 if (DEBUG_REMOVE) { 6416 if (chatty) 6417 Log.d(TAG, "Unregistered content provider: " + names[j] 6418 + ", className = " + p.info.name + ", isSyncable = " 6419 + p.info.isSyncable); 6420 } 6421 } 6422 } 6423 if (DEBUG_REMOVE && chatty) { 6424 if (r == null) { 6425 r = new StringBuilder(256); 6426 } else { 6427 r.append(' '); 6428 } 6429 r.append(p.info.name); 6430 } 6431 } 6432 if (r != null) { 6433 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6434 } 6435 6436 N = pkg.services.size(); 6437 r = null; 6438 for (i=0; i<N; i++) { 6439 PackageParser.Service s = pkg.services.get(i); 6440 mServices.removeService(s); 6441 if (chatty) { 6442 if (r == null) { 6443 r = new StringBuilder(256); 6444 } else { 6445 r.append(' '); 6446 } 6447 r.append(s.info.name); 6448 } 6449 } 6450 if (r != null) { 6451 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6452 } 6453 6454 N = pkg.receivers.size(); 6455 r = null; 6456 for (i=0; i<N; i++) { 6457 PackageParser.Activity a = pkg.receivers.get(i); 6458 mReceivers.removeActivity(a, "receiver"); 6459 if (DEBUG_REMOVE && chatty) { 6460 if (r == null) { 6461 r = new StringBuilder(256); 6462 } else { 6463 r.append(' '); 6464 } 6465 r.append(a.info.name); 6466 } 6467 } 6468 if (r != null) { 6469 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6470 } 6471 6472 N = pkg.activities.size(); 6473 r = null; 6474 for (i=0; i<N; i++) { 6475 PackageParser.Activity a = pkg.activities.get(i); 6476 mActivities.removeActivity(a, "activity"); 6477 if (DEBUG_REMOVE && chatty) { 6478 if (r == null) { 6479 r = new StringBuilder(256); 6480 } else { 6481 r.append(' '); 6482 } 6483 r.append(a.info.name); 6484 } 6485 } 6486 if (r != null) { 6487 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6488 } 6489 6490 N = pkg.permissions.size(); 6491 r = null; 6492 for (i=0; i<N; i++) { 6493 PackageParser.Permission p = pkg.permissions.get(i); 6494 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6495 if (bp == null) { 6496 bp = mSettings.mPermissionTrees.get(p.info.name); 6497 } 6498 if (bp != null && bp.perm == p) { 6499 bp.perm = null; 6500 if (DEBUG_REMOVE && chatty) { 6501 if (r == null) { 6502 r = new StringBuilder(256); 6503 } else { 6504 r.append(' '); 6505 } 6506 r.append(p.info.name); 6507 } 6508 } 6509 } 6510 if (r != null) { 6511 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6512 } 6513 6514 N = pkg.instrumentation.size(); 6515 r = null; 6516 for (i=0; i<N; i++) { 6517 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6518 mInstrumentation.remove(a.getComponentName()); 6519 if (DEBUG_REMOVE && chatty) { 6520 if (r == null) { 6521 r = new StringBuilder(256); 6522 } else { 6523 r.append(' '); 6524 } 6525 r.append(a.info.name); 6526 } 6527 } 6528 if (r != null) { 6529 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6530 } 6531 6532 r = null; 6533 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6534 // Only system apps can hold shared libraries. 6535 if (pkg.libraryNames != null) { 6536 for (i=0; i<pkg.libraryNames.size(); i++) { 6537 String name = pkg.libraryNames.get(i); 6538 SharedLibraryEntry cur = mSharedLibraries.get(name); 6539 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6540 mSharedLibraries.remove(name); 6541 if (DEBUG_REMOVE && chatty) { 6542 if (r == null) { 6543 r = new StringBuilder(256); 6544 } else { 6545 r.append(' '); 6546 } 6547 r.append(name); 6548 } 6549 } 6550 } 6551 } 6552 } 6553 if (r != null) { 6554 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6555 } 6556 } 6557 6558 private static final boolean isPackageFilename(String name) { 6559 return name != null && name.endsWith(".apk"); 6560 } 6561 6562 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6563 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6564 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6565 return true; 6566 } 6567 } 6568 return false; 6569 } 6570 6571 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6572 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6573 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6574 6575 private void updatePermissionsLPw(String changingPkg, 6576 PackageParser.Package pkgInfo, int flags) { 6577 // Make sure there are no dangling permission trees. 6578 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6579 while (it.hasNext()) { 6580 final BasePermission bp = it.next(); 6581 if (bp.packageSetting == null) { 6582 // We may not yet have parsed the package, so just see if 6583 // we still know about its settings. 6584 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6585 } 6586 if (bp.packageSetting == null) { 6587 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6588 + " from package " + bp.sourcePackage); 6589 it.remove(); 6590 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6591 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6592 Slog.i(TAG, "Removing old permission tree: " + bp.name 6593 + " from package " + bp.sourcePackage); 6594 flags |= UPDATE_PERMISSIONS_ALL; 6595 it.remove(); 6596 } 6597 } 6598 } 6599 6600 // Make sure all dynamic permissions have been assigned to a package, 6601 // and make sure there are no dangling permissions. 6602 it = mSettings.mPermissions.values().iterator(); 6603 while (it.hasNext()) { 6604 final BasePermission bp = it.next(); 6605 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6606 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6607 + bp.name + " pkg=" + bp.sourcePackage 6608 + " info=" + bp.pendingInfo); 6609 if (bp.packageSetting == null && bp.pendingInfo != null) { 6610 final BasePermission tree = findPermissionTreeLP(bp.name); 6611 if (tree != null && tree.perm != null) { 6612 bp.packageSetting = tree.packageSetting; 6613 bp.perm = new PackageParser.Permission(tree.perm.owner, 6614 new PermissionInfo(bp.pendingInfo)); 6615 bp.perm.info.packageName = tree.perm.info.packageName; 6616 bp.perm.info.name = bp.name; 6617 bp.uid = tree.uid; 6618 } 6619 } 6620 } 6621 if (bp.packageSetting == null) { 6622 // We may not yet have parsed the package, so just see if 6623 // we still know about its settings. 6624 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6625 } 6626 if (bp.packageSetting == null) { 6627 Slog.w(TAG, "Removing dangling permission: " + bp.name 6628 + " from package " + bp.sourcePackage); 6629 it.remove(); 6630 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6631 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6632 Slog.i(TAG, "Removing old permission: " + bp.name 6633 + " from package " + bp.sourcePackage); 6634 flags |= UPDATE_PERMISSIONS_ALL; 6635 it.remove(); 6636 } 6637 } 6638 } 6639 6640 // Now update the permissions for all packages, in particular 6641 // replace the granted permissions of the system packages. 6642 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6643 for (PackageParser.Package pkg : mPackages.values()) { 6644 if (pkg != pkgInfo) { 6645 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6646 } 6647 } 6648 } 6649 6650 if (pkgInfo != null) { 6651 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6652 } 6653 } 6654 6655 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6656 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6657 if (ps == null) { 6658 return; 6659 } 6660 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6661 HashSet<String> origPermissions = gp.grantedPermissions; 6662 boolean changedPermission = false; 6663 6664 if (replace) { 6665 ps.permissionsFixed = false; 6666 if (gp == ps) { 6667 origPermissions = new HashSet<String>(gp.grantedPermissions); 6668 gp.grantedPermissions.clear(); 6669 gp.gids = mGlobalGids; 6670 } 6671 } 6672 6673 if (gp.gids == null) { 6674 gp.gids = mGlobalGids; 6675 } 6676 6677 final int N = pkg.requestedPermissions.size(); 6678 for (int i=0; i<N; i++) { 6679 final String name = pkg.requestedPermissions.get(i); 6680 final boolean required = pkg.requestedPermissionsRequired.get(i); 6681 final BasePermission bp = mSettings.mPermissions.get(name); 6682 if (DEBUG_INSTALL) { 6683 if (gp != ps) { 6684 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6685 } 6686 } 6687 6688 if (bp == null || bp.packageSetting == null) { 6689 Slog.w(TAG, "Unknown permission " + name 6690 + " in package " + pkg.packageName); 6691 continue; 6692 } 6693 6694 final String perm = bp.name; 6695 boolean allowed; 6696 boolean allowedSig = false; 6697 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6698 if (level == PermissionInfo.PROTECTION_NORMAL 6699 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6700 // We grant a normal or dangerous permission if any of the following 6701 // are true: 6702 // 1) The permission is required 6703 // 2) The permission is optional, but was granted in the past 6704 // 3) The permission is optional, but was requested by an 6705 // app in /system (not /data) 6706 // 6707 // Otherwise, reject the permission. 6708 allowed = (required || origPermissions.contains(perm) 6709 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6710 } else if (bp.packageSetting == null) { 6711 // This permission is invalid; skip it. 6712 allowed = false; 6713 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6714 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6715 if (allowed) { 6716 allowedSig = true; 6717 } 6718 } else { 6719 allowed = false; 6720 } 6721 if (DEBUG_INSTALL) { 6722 if (gp != ps) { 6723 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6724 } 6725 } 6726 if (allowed) { 6727 if (!isSystemApp(ps) && ps.permissionsFixed) { 6728 // If this is an existing, non-system package, then 6729 // we can't add any new permissions to it. 6730 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6731 // Except... if this is a permission that was added 6732 // to the platform (note: need to only do this when 6733 // updating the platform). 6734 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6735 } 6736 } 6737 if (allowed) { 6738 if (!gp.grantedPermissions.contains(perm)) { 6739 changedPermission = true; 6740 gp.grantedPermissions.add(perm); 6741 gp.gids = appendInts(gp.gids, bp.gids); 6742 } else if (!ps.haveGids) { 6743 gp.gids = appendInts(gp.gids, bp.gids); 6744 } 6745 } else { 6746 Slog.w(TAG, "Not granting permission " + perm 6747 + " to package " + pkg.packageName 6748 + " because it was previously installed without"); 6749 } 6750 } else { 6751 if (gp.grantedPermissions.remove(perm)) { 6752 changedPermission = true; 6753 gp.gids = removeInts(gp.gids, bp.gids); 6754 Slog.i(TAG, "Un-granting permission " + perm 6755 + " from package " + pkg.packageName 6756 + " (protectionLevel=" + bp.protectionLevel 6757 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6758 + ")"); 6759 } else { 6760 Slog.w(TAG, "Not granting permission " + perm 6761 + " to package " + pkg.packageName 6762 + " (protectionLevel=" + bp.protectionLevel 6763 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6764 + ")"); 6765 } 6766 } 6767 } 6768 6769 if ((changedPermission || replace) && !ps.permissionsFixed && 6770 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6771 // This is the first that we have heard about this package, so the 6772 // permissions we have now selected are fixed until explicitly 6773 // changed. 6774 ps.permissionsFixed = true; 6775 } 6776 ps.haveGids = true; 6777 } 6778 6779 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6780 boolean allowed = false; 6781 final int NP = PackageParser.NEW_PERMISSIONS.length; 6782 for (int ip=0; ip<NP; ip++) { 6783 final PackageParser.NewPermissionInfo npi 6784 = PackageParser.NEW_PERMISSIONS[ip]; 6785 if (npi.name.equals(perm) 6786 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6787 allowed = true; 6788 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6789 + pkg.packageName); 6790 break; 6791 } 6792 } 6793 return allowed; 6794 } 6795 6796 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6797 BasePermission bp, HashSet<String> origPermissions) { 6798 boolean allowed; 6799 allowed = (compareSignatures( 6800 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6801 == PackageManager.SIGNATURE_MATCH) 6802 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6803 == PackageManager.SIGNATURE_MATCH); 6804 if (!allowed && (bp.protectionLevel 6805 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6806 if (isSystemApp(pkg)) { 6807 // For updated system applications, a system permission 6808 // is granted only if it had been defined by the original application. 6809 if (isUpdatedSystemApp(pkg)) { 6810 final PackageSetting sysPs = mSettings 6811 .getDisabledSystemPkgLPr(pkg.packageName); 6812 final GrantedPermissions origGp = sysPs.sharedUser != null 6813 ? sysPs.sharedUser : sysPs; 6814 6815 if (origGp.grantedPermissions.contains(perm)) { 6816 // If the original was granted this permission, we take 6817 // that grant decision as read and propagate it to the 6818 // update. 6819 allowed = true; 6820 } else { 6821 // The system apk may have been updated with an older 6822 // version of the one on the data partition, but which 6823 // granted a new system permission that it didn't have 6824 // before. In this case we do want to allow the app to 6825 // now get the new permission if the ancestral apk is 6826 // privileged to get it. 6827 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6828 for (int j=0; 6829 j<sysPs.pkg.requestedPermissions.size(); j++) { 6830 if (perm.equals( 6831 sysPs.pkg.requestedPermissions.get(j))) { 6832 allowed = true; 6833 break; 6834 } 6835 } 6836 } 6837 } 6838 } else { 6839 allowed = isPrivilegedApp(pkg); 6840 } 6841 } 6842 } 6843 if (!allowed && (bp.protectionLevel 6844 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6845 // For development permissions, a development permission 6846 // is granted only if it was already granted. 6847 allowed = origPermissions.contains(perm); 6848 } 6849 return allowed; 6850 } 6851 6852 final class ActivityIntentResolver 6853 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6854 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6855 boolean defaultOnly, int userId) { 6856 if (!sUserManager.exists(userId)) return null; 6857 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6858 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6859 } 6860 6861 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6862 int userId) { 6863 if (!sUserManager.exists(userId)) return null; 6864 mFlags = flags; 6865 return super.queryIntent(intent, resolvedType, 6866 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6867 } 6868 6869 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6870 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6871 if (!sUserManager.exists(userId)) return null; 6872 if (packageActivities == null) { 6873 return null; 6874 } 6875 mFlags = flags; 6876 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6877 final int N = packageActivities.size(); 6878 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6879 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6880 6881 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6882 for (int i = 0; i < N; ++i) { 6883 intentFilters = packageActivities.get(i).intents; 6884 if (intentFilters != null && intentFilters.size() > 0) { 6885 PackageParser.ActivityIntentInfo[] array = 6886 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6887 intentFilters.toArray(array); 6888 listCut.add(array); 6889 } 6890 } 6891 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6892 } 6893 6894 public final void addActivity(PackageParser.Activity a, String type) { 6895 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6896 mActivities.put(a.getComponentName(), a); 6897 if (DEBUG_SHOW_INFO) 6898 Log.v( 6899 TAG, " " + type + " " + 6900 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6901 if (DEBUG_SHOW_INFO) 6902 Log.v(TAG, " Class=" + a.info.name); 6903 final int NI = a.intents.size(); 6904 for (int j=0; j<NI; j++) { 6905 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6906 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6907 intent.setPriority(0); 6908 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6909 + a.className + " with priority > 0, forcing to 0"); 6910 } 6911 if (DEBUG_SHOW_INFO) { 6912 Log.v(TAG, " IntentFilter:"); 6913 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6914 } 6915 if (!intent.debugCheck()) { 6916 Log.w(TAG, "==> For Activity " + a.info.name); 6917 } 6918 addFilter(intent); 6919 } 6920 } 6921 6922 public final void removeActivity(PackageParser.Activity a, String type) { 6923 mActivities.remove(a.getComponentName()); 6924 if (DEBUG_SHOW_INFO) { 6925 Log.v(TAG, " " + type + " " 6926 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6927 : a.info.name) + ":"); 6928 Log.v(TAG, " Class=" + a.info.name); 6929 } 6930 final int NI = a.intents.size(); 6931 for (int j=0; j<NI; j++) { 6932 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6933 if (DEBUG_SHOW_INFO) { 6934 Log.v(TAG, " IntentFilter:"); 6935 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6936 } 6937 removeFilter(intent); 6938 } 6939 } 6940 6941 @Override 6942 protected boolean allowFilterResult( 6943 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6944 ActivityInfo filterAi = filter.activity.info; 6945 for (int i=dest.size()-1; i>=0; i--) { 6946 ActivityInfo destAi = dest.get(i).activityInfo; 6947 if (destAi.name == filterAi.name 6948 && destAi.packageName == filterAi.packageName) { 6949 return false; 6950 } 6951 } 6952 return true; 6953 } 6954 6955 @Override 6956 protected ActivityIntentInfo[] newArray(int size) { 6957 return new ActivityIntentInfo[size]; 6958 } 6959 6960 @Override 6961 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6962 if (!sUserManager.exists(userId)) return true; 6963 PackageParser.Package p = filter.activity.owner; 6964 if (p != null) { 6965 PackageSetting ps = (PackageSetting)p.mExtras; 6966 if (ps != null) { 6967 // System apps are never considered stopped for purposes of 6968 // filtering, because there may be no way for the user to 6969 // actually re-launch them. 6970 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6971 && ps.getStopped(userId); 6972 } 6973 } 6974 return false; 6975 } 6976 6977 @Override 6978 protected boolean isPackageForFilter(String packageName, 6979 PackageParser.ActivityIntentInfo info) { 6980 return packageName.equals(info.activity.owner.packageName); 6981 } 6982 6983 @Override 6984 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6985 int match, int userId) { 6986 if (!sUserManager.exists(userId)) return null; 6987 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6988 return null; 6989 } 6990 final PackageParser.Activity activity = info.activity; 6991 if (mSafeMode && (activity.info.applicationInfo.flags 6992 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6993 return null; 6994 } 6995 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6996 if (ps == null) { 6997 return null; 6998 } 6999 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7000 ps.readUserState(userId), userId); 7001 if (ai == null) { 7002 return null; 7003 } 7004 final ResolveInfo res = new ResolveInfo(); 7005 res.activityInfo = ai; 7006 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7007 res.filter = info; 7008 } 7009 res.priority = info.getPriority(); 7010 res.preferredOrder = activity.owner.mPreferredOrder; 7011 //System.out.println("Result: " + res.activityInfo.className + 7012 // " = " + res.priority); 7013 res.match = match; 7014 res.isDefault = info.hasDefault; 7015 res.labelRes = info.labelRes; 7016 res.nonLocalizedLabel = info.nonLocalizedLabel; 7017 res.icon = info.icon; 7018 res.system = isSystemApp(res.activityInfo.applicationInfo); 7019 return res; 7020 } 7021 7022 @Override 7023 protected void sortResults(List<ResolveInfo> results) { 7024 Collections.sort(results, mResolvePrioritySorter); 7025 } 7026 7027 @Override 7028 protected void dumpFilter(PrintWriter out, String prefix, 7029 PackageParser.ActivityIntentInfo filter) { 7030 out.print(prefix); out.print( 7031 Integer.toHexString(System.identityHashCode(filter.activity))); 7032 out.print(' '); 7033 filter.activity.printComponentShortName(out); 7034 out.print(" filter "); 7035 out.println(Integer.toHexString(System.identityHashCode(filter))); 7036 } 7037 7038// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7039// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7040// final List<ResolveInfo> retList = Lists.newArrayList(); 7041// while (i.hasNext()) { 7042// final ResolveInfo resolveInfo = i.next(); 7043// if (isEnabledLP(resolveInfo.activityInfo)) { 7044// retList.add(resolveInfo); 7045// } 7046// } 7047// return retList; 7048// } 7049 7050 // Keys are String (activity class name), values are Activity. 7051 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7052 = new HashMap<ComponentName, PackageParser.Activity>(); 7053 private int mFlags; 7054 } 7055 7056 private final class ServiceIntentResolver 7057 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7058 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7059 boolean defaultOnly, int userId) { 7060 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7061 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7062 } 7063 7064 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7065 int userId) { 7066 if (!sUserManager.exists(userId)) return null; 7067 mFlags = flags; 7068 return super.queryIntent(intent, resolvedType, 7069 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7070 } 7071 7072 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7073 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7074 if (!sUserManager.exists(userId)) return null; 7075 if (packageServices == null) { 7076 return null; 7077 } 7078 mFlags = flags; 7079 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7080 final int N = packageServices.size(); 7081 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7082 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7083 7084 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7085 for (int i = 0; i < N; ++i) { 7086 intentFilters = packageServices.get(i).intents; 7087 if (intentFilters != null && intentFilters.size() > 0) { 7088 PackageParser.ServiceIntentInfo[] array = 7089 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7090 intentFilters.toArray(array); 7091 listCut.add(array); 7092 } 7093 } 7094 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7095 } 7096 7097 public final void addService(PackageParser.Service s) { 7098 mServices.put(s.getComponentName(), s); 7099 if (DEBUG_SHOW_INFO) { 7100 Log.v(TAG, " " 7101 + (s.info.nonLocalizedLabel != null 7102 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7103 Log.v(TAG, " Class=" + s.info.name); 7104 } 7105 final int NI = s.intents.size(); 7106 int j; 7107 for (j=0; j<NI; j++) { 7108 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7109 if (DEBUG_SHOW_INFO) { 7110 Log.v(TAG, " IntentFilter:"); 7111 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7112 } 7113 if (!intent.debugCheck()) { 7114 Log.w(TAG, "==> For Service " + s.info.name); 7115 } 7116 addFilter(intent); 7117 } 7118 } 7119 7120 public final void removeService(PackageParser.Service s) { 7121 mServices.remove(s.getComponentName()); 7122 if (DEBUG_SHOW_INFO) { 7123 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7124 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7125 Log.v(TAG, " Class=" + s.info.name); 7126 } 7127 final int NI = s.intents.size(); 7128 int j; 7129 for (j=0; j<NI; j++) { 7130 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7131 if (DEBUG_SHOW_INFO) { 7132 Log.v(TAG, " IntentFilter:"); 7133 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7134 } 7135 removeFilter(intent); 7136 } 7137 } 7138 7139 @Override 7140 protected boolean allowFilterResult( 7141 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7142 ServiceInfo filterSi = filter.service.info; 7143 for (int i=dest.size()-1; i>=0; i--) { 7144 ServiceInfo destAi = dest.get(i).serviceInfo; 7145 if (destAi.name == filterSi.name 7146 && destAi.packageName == filterSi.packageName) { 7147 return false; 7148 } 7149 } 7150 return true; 7151 } 7152 7153 @Override 7154 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7155 return new PackageParser.ServiceIntentInfo[size]; 7156 } 7157 7158 @Override 7159 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7160 if (!sUserManager.exists(userId)) return true; 7161 PackageParser.Package p = filter.service.owner; 7162 if (p != null) { 7163 PackageSetting ps = (PackageSetting)p.mExtras; 7164 if (ps != null) { 7165 // System apps are never considered stopped for purposes of 7166 // filtering, because there may be no way for the user to 7167 // actually re-launch them. 7168 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7169 && ps.getStopped(userId); 7170 } 7171 } 7172 return false; 7173 } 7174 7175 @Override 7176 protected boolean isPackageForFilter(String packageName, 7177 PackageParser.ServiceIntentInfo info) { 7178 return packageName.equals(info.service.owner.packageName); 7179 } 7180 7181 @Override 7182 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7183 int match, int userId) { 7184 if (!sUserManager.exists(userId)) return null; 7185 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7186 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7187 return null; 7188 } 7189 final PackageParser.Service service = info.service; 7190 if (mSafeMode && (service.info.applicationInfo.flags 7191 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7192 return null; 7193 } 7194 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7195 if (ps == null) { 7196 return null; 7197 } 7198 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7199 ps.readUserState(userId), userId); 7200 if (si == null) { 7201 return null; 7202 } 7203 final ResolveInfo res = new ResolveInfo(); 7204 res.serviceInfo = si; 7205 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7206 res.filter = filter; 7207 } 7208 res.priority = info.getPriority(); 7209 res.preferredOrder = service.owner.mPreferredOrder; 7210 //System.out.println("Result: " + res.activityInfo.className + 7211 // " = " + res.priority); 7212 res.match = match; 7213 res.isDefault = info.hasDefault; 7214 res.labelRes = info.labelRes; 7215 res.nonLocalizedLabel = info.nonLocalizedLabel; 7216 res.icon = info.icon; 7217 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7218 return res; 7219 } 7220 7221 @Override 7222 protected void sortResults(List<ResolveInfo> results) { 7223 Collections.sort(results, mResolvePrioritySorter); 7224 } 7225 7226 @Override 7227 protected void dumpFilter(PrintWriter out, String prefix, 7228 PackageParser.ServiceIntentInfo filter) { 7229 out.print(prefix); out.print( 7230 Integer.toHexString(System.identityHashCode(filter.service))); 7231 out.print(' '); 7232 filter.service.printComponentShortName(out); 7233 out.print(" filter "); 7234 out.println(Integer.toHexString(System.identityHashCode(filter))); 7235 } 7236 7237// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7238// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7239// final List<ResolveInfo> retList = Lists.newArrayList(); 7240// while (i.hasNext()) { 7241// final ResolveInfo resolveInfo = (ResolveInfo) i; 7242// if (isEnabledLP(resolveInfo.serviceInfo)) { 7243// retList.add(resolveInfo); 7244// } 7245// } 7246// return retList; 7247// } 7248 7249 // Keys are String (activity class name), values are Activity. 7250 private final HashMap<ComponentName, PackageParser.Service> mServices 7251 = new HashMap<ComponentName, PackageParser.Service>(); 7252 private int mFlags; 7253 }; 7254 7255 private final class ProviderIntentResolver 7256 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7257 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7258 boolean defaultOnly, int userId) { 7259 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7260 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7261 } 7262 7263 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7264 int userId) { 7265 if (!sUserManager.exists(userId)) 7266 return null; 7267 mFlags = flags; 7268 return super.queryIntent(intent, resolvedType, 7269 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7270 } 7271 7272 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7273 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7274 if (!sUserManager.exists(userId)) 7275 return null; 7276 if (packageProviders == null) { 7277 return null; 7278 } 7279 mFlags = flags; 7280 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7281 final int N = packageProviders.size(); 7282 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7283 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7284 7285 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7286 for (int i = 0; i < N; ++i) { 7287 intentFilters = packageProviders.get(i).intents; 7288 if (intentFilters != null && intentFilters.size() > 0) { 7289 PackageParser.ProviderIntentInfo[] array = 7290 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7291 intentFilters.toArray(array); 7292 listCut.add(array); 7293 } 7294 } 7295 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7296 } 7297 7298 public final void addProvider(PackageParser.Provider p) { 7299 if (mProviders.containsKey(p.getComponentName())) { 7300 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7301 return; 7302 } 7303 7304 mProviders.put(p.getComponentName(), p); 7305 if (DEBUG_SHOW_INFO) { 7306 Log.v(TAG, " " 7307 + (p.info.nonLocalizedLabel != null 7308 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7309 Log.v(TAG, " Class=" + p.info.name); 7310 } 7311 final int NI = p.intents.size(); 7312 int j; 7313 for (j = 0; j < NI; j++) { 7314 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7315 if (DEBUG_SHOW_INFO) { 7316 Log.v(TAG, " IntentFilter:"); 7317 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7318 } 7319 if (!intent.debugCheck()) { 7320 Log.w(TAG, "==> For Provider " + p.info.name); 7321 } 7322 addFilter(intent); 7323 } 7324 } 7325 7326 public final void removeProvider(PackageParser.Provider p) { 7327 mProviders.remove(p.getComponentName()); 7328 if (DEBUG_SHOW_INFO) { 7329 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7330 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7331 Log.v(TAG, " Class=" + p.info.name); 7332 } 7333 final int NI = p.intents.size(); 7334 int j; 7335 for (j = 0; j < NI; j++) { 7336 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7337 if (DEBUG_SHOW_INFO) { 7338 Log.v(TAG, " IntentFilter:"); 7339 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7340 } 7341 removeFilter(intent); 7342 } 7343 } 7344 7345 @Override 7346 protected boolean allowFilterResult( 7347 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7348 ProviderInfo filterPi = filter.provider.info; 7349 for (int i = dest.size() - 1; i >= 0; i--) { 7350 ProviderInfo destPi = dest.get(i).providerInfo; 7351 if (destPi.name == filterPi.name 7352 && destPi.packageName == filterPi.packageName) { 7353 return false; 7354 } 7355 } 7356 return true; 7357 } 7358 7359 @Override 7360 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7361 return new PackageParser.ProviderIntentInfo[size]; 7362 } 7363 7364 @Override 7365 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7366 if (!sUserManager.exists(userId)) 7367 return true; 7368 PackageParser.Package p = filter.provider.owner; 7369 if (p != null) { 7370 PackageSetting ps = (PackageSetting) p.mExtras; 7371 if (ps != null) { 7372 // System apps are never considered stopped for purposes of 7373 // filtering, because there may be no way for the user to 7374 // actually re-launch them. 7375 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7376 && ps.getStopped(userId); 7377 } 7378 } 7379 return false; 7380 } 7381 7382 @Override 7383 protected boolean isPackageForFilter(String packageName, 7384 PackageParser.ProviderIntentInfo info) { 7385 return packageName.equals(info.provider.owner.packageName); 7386 } 7387 7388 @Override 7389 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7390 int match, int userId) { 7391 if (!sUserManager.exists(userId)) 7392 return null; 7393 final PackageParser.ProviderIntentInfo info = filter; 7394 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7395 return null; 7396 } 7397 final PackageParser.Provider provider = info.provider; 7398 if (mSafeMode && (provider.info.applicationInfo.flags 7399 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7400 return null; 7401 } 7402 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7403 if (ps == null) { 7404 return null; 7405 } 7406 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7407 ps.readUserState(userId), userId); 7408 if (pi == null) { 7409 return null; 7410 } 7411 final ResolveInfo res = new ResolveInfo(); 7412 res.providerInfo = pi; 7413 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7414 res.filter = filter; 7415 } 7416 res.priority = info.getPriority(); 7417 res.preferredOrder = provider.owner.mPreferredOrder; 7418 res.match = match; 7419 res.isDefault = info.hasDefault; 7420 res.labelRes = info.labelRes; 7421 res.nonLocalizedLabel = info.nonLocalizedLabel; 7422 res.icon = info.icon; 7423 res.system = isSystemApp(res.providerInfo.applicationInfo); 7424 return res; 7425 } 7426 7427 @Override 7428 protected void sortResults(List<ResolveInfo> results) { 7429 Collections.sort(results, mResolvePrioritySorter); 7430 } 7431 7432 @Override 7433 protected void dumpFilter(PrintWriter out, String prefix, 7434 PackageParser.ProviderIntentInfo filter) { 7435 out.print(prefix); 7436 out.print( 7437 Integer.toHexString(System.identityHashCode(filter.provider))); 7438 out.print(' '); 7439 filter.provider.printComponentShortName(out); 7440 out.print(" filter "); 7441 out.println(Integer.toHexString(System.identityHashCode(filter))); 7442 } 7443 7444 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7445 = new HashMap<ComponentName, PackageParser.Provider>(); 7446 private int mFlags; 7447 }; 7448 7449 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7450 new Comparator<ResolveInfo>() { 7451 public int compare(ResolveInfo r1, ResolveInfo r2) { 7452 int v1 = r1.priority; 7453 int v2 = r2.priority; 7454 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7455 if (v1 != v2) { 7456 return (v1 > v2) ? -1 : 1; 7457 } 7458 v1 = r1.preferredOrder; 7459 v2 = r2.preferredOrder; 7460 if (v1 != v2) { 7461 return (v1 > v2) ? -1 : 1; 7462 } 7463 if (r1.isDefault != r2.isDefault) { 7464 return r1.isDefault ? -1 : 1; 7465 } 7466 v1 = r1.match; 7467 v2 = r2.match; 7468 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7469 if (v1 != v2) { 7470 return (v1 > v2) ? -1 : 1; 7471 } 7472 if (r1.system != r2.system) { 7473 return r1.system ? -1 : 1; 7474 } 7475 return 0; 7476 } 7477 }; 7478 7479 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7480 new Comparator<ProviderInfo>() { 7481 public int compare(ProviderInfo p1, ProviderInfo p2) { 7482 final int v1 = p1.initOrder; 7483 final int v2 = p2.initOrder; 7484 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7485 } 7486 }; 7487 7488 static final void sendPackageBroadcast(String action, String pkg, 7489 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7490 int[] userIds) { 7491 IActivityManager am = ActivityManagerNative.getDefault(); 7492 if (am != null) { 7493 try { 7494 if (userIds == null) { 7495 userIds = am.getRunningUserIds(); 7496 } 7497 for (int id : userIds) { 7498 final Intent intent = new Intent(action, 7499 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7500 if (extras != null) { 7501 intent.putExtras(extras); 7502 } 7503 if (targetPkg != null) { 7504 intent.setPackage(targetPkg); 7505 } 7506 // Modify the UID when posting to other users 7507 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7508 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7509 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7510 intent.putExtra(Intent.EXTRA_UID, uid); 7511 } 7512 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7513 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7514 if (DEBUG_BROADCASTS) { 7515 RuntimeException here = new RuntimeException("here"); 7516 here.fillInStackTrace(); 7517 Slog.d(TAG, "Sending to user " + id + ": " 7518 + intent.toShortString(false, true, false, false) 7519 + " " + intent.getExtras(), here); 7520 } 7521 am.broadcastIntent(null, intent, null, finishedReceiver, 7522 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7523 finishedReceiver != null, false, id); 7524 } 7525 } catch (RemoteException ex) { 7526 } 7527 } 7528 } 7529 7530 /** 7531 * Check if the external storage media is available. This is true if there 7532 * is a mounted external storage medium or if the external storage is 7533 * emulated. 7534 */ 7535 private boolean isExternalMediaAvailable() { 7536 return mMediaMounted || Environment.isExternalStorageEmulated(); 7537 } 7538 7539 @Override 7540 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7541 // writer 7542 synchronized (mPackages) { 7543 if (!isExternalMediaAvailable()) { 7544 // If the external storage is no longer mounted at this point, 7545 // the caller may not have been able to delete all of this 7546 // packages files and can not delete any more. Bail. 7547 return null; 7548 } 7549 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7550 if (lastPackage != null) { 7551 pkgs.remove(lastPackage); 7552 } 7553 if (pkgs.size() > 0) { 7554 return pkgs.get(0); 7555 } 7556 } 7557 return null; 7558 } 7559 7560 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7561 if (false) { 7562 RuntimeException here = new RuntimeException("here"); 7563 here.fillInStackTrace(); 7564 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7565 + " andCode=" + andCode, here); 7566 } 7567 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7568 userId, andCode ? 1 : 0, packageName)); 7569 } 7570 7571 void startCleaningPackages() { 7572 // reader 7573 synchronized (mPackages) { 7574 if (!isExternalMediaAvailable()) { 7575 return; 7576 } 7577 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7578 return; 7579 } 7580 } 7581 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7582 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7583 IActivityManager am = ActivityManagerNative.getDefault(); 7584 if (am != null) { 7585 try { 7586 am.startService(null, intent, null, UserHandle.USER_OWNER); 7587 } catch (RemoteException e) { 7588 } 7589 } 7590 } 7591 7592 private final class AppDirObserver extends FileObserver { 7593 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7594 super(path, mask); 7595 mRootDir = path; 7596 mIsRom = isrom; 7597 mIsPrivileged = isPrivileged; 7598 } 7599 7600 public void onEvent(int event, String path) { 7601 String removedPackage = null; 7602 int removedAppId = -1; 7603 int[] removedUsers = null; 7604 String addedPackage = null; 7605 int addedAppId = -1; 7606 int[] addedUsers = null; 7607 7608 // TODO post a message to the handler to obtain serial ordering 7609 synchronized (mInstallLock) { 7610 String fullPathStr = null; 7611 File fullPath = null; 7612 if (path != null) { 7613 fullPath = new File(mRootDir, path); 7614 fullPathStr = fullPath.getPath(); 7615 } 7616 7617 if (DEBUG_APP_DIR_OBSERVER) 7618 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7619 7620 if (!isPackageFilename(path)) { 7621 if (DEBUG_APP_DIR_OBSERVER) 7622 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7623 return; 7624 } 7625 7626 // Ignore packages that are being installed or 7627 // have just been installed. 7628 if (ignoreCodePath(fullPathStr)) { 7629 return; 7630 } 7631 PackageParser.Package p = null; 7632 PackageSetting ps = null; 7633 // reader 7634 synchronized (mPackages) { 7635 p = mAppDirs.get(fullPathStr); 7636 if (p != null) { 7637 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7638 if (ps != null) { 7639 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7640 } else { 7641 removedUsers = sUserManager.getUserIds(); 7642 } 7643 } 7644 addedUsers = sUserManager.getUserIds(); 7645 } 7646 if ((event&REMOVE_EVENTS) != 0) { 7647 if (ps != null) { 7648 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7649 removePackageLI(ps, true); 7650 removedPackage = ps.name; 7651 removedAppId = ps.appId; 7652 } 7653 } 7654 7655 if ((event&ADD_EVENTS) != 0) { 7656 if (p == null) { 7657 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7658 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7659 if (mIsRom) { 7660 flags |= PackageParser.PARSE_IS_SYSTEM 7661 | PackageParser.PARSE_IS_SYSTEM_DIR; 7662 if (mIsPrivileged) { 7663 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7664 } 7665 } 7666 p = scanPackageLI(fullPath, flags, 7667 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7668 System.currentTimeMillis(), UserHandle.ALL, null); 7669 if (p != null) { 7670 /* 7671 * TODO this seems dangerous as the package may have 7672 * changed since we last acquired the mPackages 7673 * lock. 7674 */ 7675 // writer 7676 synchronized (mPackages) { 7677 updatePermissionsLPw(p.packageName, p, 7678 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7679 } 7680 addedPackage = p.applicationInfo.packageName; 7681 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7682 } 7683 } 7684 } 7685 7686 // reader 7687 synchronized (mPackages) { 7688 mSettings.writeLPr(); 7689 } 7690 } 7691 7692 if (removedPackage != null) { 7693 Bundle extras = new Bundle(1); 7694 extras.putInt(Intent.EXTRA_UID, removedAppId); 7695 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7696 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7697 extras, null, null, removedUsers); 7698 } 7699 if (addedPackage != null) { 7700 Bundle extras = new Bundle(1); 7701 extras.putInt(Intent.EXTRA_UID, addedAppId); 7702 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7703 extras, null, null, addedUsers); 7704 } 7705 } 7706 7707 private final String mRootDir; 7708 private final boolean mIsRom; 7709 private final boolean mIsPrivileged; 7710 } 7711 7712 /* 7713 * The old-style observer methods all just trampoline to the newer signature with 7714 * expanded install observer API. The older API continues to work but does not 7715 * supply the additional details of the Observer2 API. 7716 */ 7717 7718 /* Called when a downloaded package installation has been confirmed by the user */ 7719 public void installPackage( 7720 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 7721 installPackageEtc(packageURI, observer, null, flags, null); 7722 } 7723 7724 /* Called when a downloaded package installation has been confirmed by the user */ 7725 @Override 7726 public void installPackage( 7727 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 7728 final String installerPackageName) { 7729 installPackageWithVerificationEtc(packageURI, observer, null, flags, 7730 installerPackageName, null, null, null); 7731 } 7732 7733 @Override 7734 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 7735 int flags, String installerPackageName, Uri verificationURI, 7736 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7737 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7738 VerificationParams.NO_UID, manifestDigest); 7739 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7740 installerPackageName, verificationParams, encryptionParams); 7741 } 7742 7743 @Override 7744 public void installPackageWithVerificationAndEncryption(Uri packageURI, 7745 IPackageInstallObserver observer, int flags, String installerPackageName, 7746 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7747 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7748 installerPackageName, verificationParams, encryptionParams); 7749 } 7750 7751 /* 7752 * And here are the "live" versions that take both observer arguments 7753 */ 7754 public void installPackageEtc( 7755 final Uri packageURI, final IPackageInstallObserver observer, 7756 IPackageInstallObserver2 observer2, final int flags) { 7757 installPackageEtc(packageURI, observer, observer2, flags, null); 7758 } 7759 7760 public void installPackageEtc( 7761 final Uri packageURI, final IPackageInstallObserver observer, 7762 final IPackageInstallObserver2 observer2, final int flags, 7763 final String installerPackageName) { 7764 installPackageWithVerificationEtc(packageURI, observer, observer2, flags, 7765 installerPackageName, null, null, null); 7766 } 7767 7768 @Override 7769 public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer, 7770 IPackageInstallObserver2 observer2, 7771 int flags, String installerPackageName, Uri verificationURI, 7772 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7773 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7774 VerificationParams.NO_UID, manifestDigest); 7775 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags, 7776 installerPackageName, verificationParams, encryptionParams); 7777 } 7778 7779 /* 7780 * All of the installPackage...*() methods redirect to this one for the master implementation 7781 */ 7782 public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI, 7783 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7784 int flags, String installerPackageName, 7785 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7786 if (observer == null && observer2 == null) { 7787 throw new IllegalArgumentException("No install observer supplied"); 7788 } 7789 installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2, 7790 flags, installerPackageName, verificationParams, encryptionParams, null); 7791 } 7792 7793 @Override 7794 public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI, 7795 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7796 int flags, String installerPackageName, 7797 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams, 7798 String packageAbiOverride) { 7799 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7800 null); 7801 7802 final int uid = Binder.getCallingUid(); 7803 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7804 try { 7805 if (observer != null) { 7806 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7807 } 7808 if (observer2 != null) { 7809 observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7810 } 7811 } catch (RemoteException re) { 7812 } 7813 return; 7814 } 7815 7816 UserHandle user; 7817 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7818 user = UserHandle.ALL; 7819 } else { 7820 user = new UserHandle(UserHandle.getUserId(uid)); 7821 } 7822 7823 final int filteredFlags; 7824 7825 if (uid == Process.SHELL_UID || uid == 0) { 7826 if (DEBUG_INSTALL) { 7827 Slog.v(TAG, "Install from ADB"); 7828 } 7829 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7830 } else { 7831 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7832 } 7833 7834 verificationParams.setInstallerUid(uid); 7835 7836 final Message msg = mHandler.obtainMessage(INIT_COPY); 7837 msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags, 7838 installerPackageName, verificationParams, encryptionParams, user, 7839 packageAbiOverride); 7840 mHandler.sendMessage(msg); 7841 } 7842 7843 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7844 Bundle extras = new Bundle(1); 7845 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7846 7847 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7848 packageName, extras, null, null, new int[] {userId}); 7849 try { 7850 IActivityManager am = ActivityManagerNative.getDefault(); 7851 final boolean isSystem = 7852 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7853 if (isSystem && am.isUserRunning(userId, false)) { 7854 // The just-installed/enabled app is bundled on the system, so presumed 7855 // to be able to run automatically without needing an explicit launch. 7856 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7857 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7858 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7859 .setPackage(packageName); 7860 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7861 android.app.AppOpsManager.OP_NONE, false, false, userId); 7862 } 7863 } catch (RemoteException e) { 7864 // shouldn't happen 7865 Slog.w(TAG, "Unable to bootstrap installed package", e); 7866 } 7867 } 7868 7869 @Override 7870 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7871 int userId) { 7872 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7873 PackageSetting pkgSetting; 7874 final int uid = Binder.getCallingUid(); 7875 if (UserHandle.getUserId(uid) != userId) { 7876 mContext.enforceCallingOrSelfPermission( 7877 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7878 "setApplicationBlockedSetting for user " + userId); 7879 } 7880 7881 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7882 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7883 return false; 7884 } 7885 7886 long callingId = Binder.clearCallingIdentity(); 7887 try { 7888 boolean sendAdded = false; 7889 boolean sendRemoved = false; 7890 // writer 7891 synchronized (mPackages) { 7892 pkgSetting = mSettings.mPackages.get(packageName); 7893 if (pkgSetting == null) { 7894 return false; 7895 } 7896 if (pkgSetting.getBlocked(userId) != blocked) { 7897 pkgSetting.setBlocked(blocked, userId); 7898 mSettings.writePackageRestrictionsLPr(userId); 7899 if (blocked) { 7900 sendRemoved = true; 7901 } else { 7902 sendAdded = true; 7903 } 7904 } 7905 } 7906 if (sendAdded) { 7907 sendPackageAddedForUser(packageName, pkgSetting, userId); 7908 return true; 7909 } 7910 if (sendRemoved) { 7911 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7912 "blocking pkg"); 7913 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7914 } 7915 } finally { 7916 Binder.restoreCallingIdentity(callingId); 7917 } 7918 return false; 7919 } 7920 7921 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7922 int userId) { 7923 final PackageRemovedInfo info = new PackageRemovedInfo(); 7924 info.removedPackage = packageName; 7925 info.removedUsers = new int[] {userId}; 7926 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7927 info.sendBroadcast(false, false, false); 7928 } 7929 7930 /** 7931 * Returns true if application is not found or there was an error. Otherwise it returns 7932 * the blocked state of the package for the given user. 7933 */ 7934 @Override 7935 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7936 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7937 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7938 "getApplicationBlocked for user " + userId); 7939 PackageSetting pkgSetting; 7940 long callingId = Binder.clearCallingIdentity(); 7941 try { 7942 // writer 7943 synchronized (mPackages) { 7944 pkgSetting = mSettings.mPackages.get(packageName); 7945 if (pkgSetting == null) { 7946 return true; 7947 } 7948 return pkgSetting.getBlocked(userId); 7949 } 7950 } finally { 7951 Binder.restoreCallingIdentity(callingId); 7952 } 7953 } 7954 7955 void installStage(String basePackageName, File stageDir, IPackageInstallObserver2 observer, 7956 int flags) { 7957 // TODO: install stage! 7958 try { 7959 observer.packageInstalled(basePackageName, null, 7960 PackageManager.INSTALL_FAILED_INTERNAL_ERROR); 7961 } catch (RemoteException ignored) { 7962 } 7963 } 7964 7965 /** 7966 * @hide 7967 */ 7968 @Override 7969 public int installExistingPackageAsUser(String packageName, int userId) { 7970 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7971 null); 7972 PackageSetting pkgSetting; 7973 final int uid = Binder.getCallingUid(); 7974 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7975 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7976 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7977 } 7978 7979 long callingId = Binder.clearCallingIdentity(); 7980 try { 7981 boolean sendAdded = false; 7982 Bundle extras = new Bundle(1); 7983 7984 // writer 7985 synchronized (mPackages) { 7986 pkgSetting = mSettings.mPackages.get(packageName); 7987 if (pkgSetting == null) { 7988 return PackageManager.INSTALL_FAILED_INVALID_URI; 7989 } 7990 if (!pkgSetting.getInstalled(userId)) { 7991 pkgSetting.setInstalled(true, userId); 7992 pkgSetting.setBlocked(false, userId); 7993 mSettings.writePackageRestrictionsLPr(userId); 7994 sendAdded = true; 7995 } 7996 } 7997 7998 if (sendAdded) { 7999 sendPackageAddedForUser(packageName, pkgSetting, userId); 8000 } 8001 } finally { 8002 Binder.restoreCallingIdentity(callingId); 8003 } 8004 8005 return PackageManager.INSTALL_SUCCEEDED; 8006 } 8007 8008 boolean isUserRestricted(int userId, String restrictionKey) { 8009 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8010 if (restrictions.getBoolean(restrictionKey, false)) { 8011 Log.w(TAG, "User is restricted: " + restrictionKey); 8012 return true; 8013 } 8014 return false; 8015 } 8016 8017 @Override 8018 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8019 mContext.enforceCallingOrSelfPermission( 8020 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8021 "Only package verification agents can verify applications"); 8022 8023 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8024 final PackageVerificationResponse response = new PackageVerificationResponse( 8025 verificationCode, Binder.getCallingUid()); 8026 msg.arg1 = id; 8027 msg.obj = response; 8028 mHandler.sendMessage(msg); 8029 } 8030 8031 @Override 8032 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8033 long millisecondsToDelay) { 8034 mContext.enforceCallingOrSelfPermission( 8035 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8036 "Only package verification agents can extend verification timeouts"); 8037 8038 final PackageVerificationState state = mPendingVerification.get(id); 8039 final PackageVerificationResponse response = new PackageVerificationResponse( 8040 verificationCodeAtTimeout, Binder.getCallingUid()); 8041 8042 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8043 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8044 } 8045 if (millisecondsToDelay < 0) { 8046 millisecondsToDelay = 0; 8047 } 8048 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8049 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8050 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8051 } 8052 8053 if ((state != null) && !state.timeoutExtended()) { 8054 state.extendTimeout(); 8055 8056 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8057 msg.arg1 = id; 8058 msg.obj = response; 8059 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8060 } 8061 } 8062 8063 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8064 int verificationCode, UserHandle user) { 8065 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8066 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8067 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8068 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8069 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8070 8071 mContext.sendBroadcastAsUser(intent, user, 8072 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8073 } 8074 8075 private ComponentName matchComponentForVerifier(String packageName, 8076 List<ResolveInfo> receivers) { 8077 ActivityInfo targetReceiver = null; 8078 8079 final int NR = receivers.size(); 8080 for (int i = 0; i < NR; i++) { 8081 final ResolveInfo info = receivers.get(i); 8082 if (info.activityInfo == null) { 8083 continue; 8084 } 8085 8086 if (packageName.equals(info.activityInfo.packageName)) { 8087 targetReceiver = info.activityInfo; 8088 break; 8089 } 8090 } 8091 8092 if (targetReceiver == null) { 8093 return null; 8094 } 8095 8096 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8097 } 8098 8099 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8100 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8101 if (pkgInfo.verifiers.length == 0) { 8102 return null; 8103 } 8104 8105 final int N = pkgInfo.verifiers.length; 8106 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8107 for (int i = 0; i < N; i++) { 8108 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8109 8110 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8111 receivers); 8112 if (comp == null) { 8113 continue; 8114 } 8115 8116 final int verifierUid = getUidForVerifier(verifierInfo); 8117 if (verifierUid == -1) { 8118 continue; 8119 } 8120 8121 if (DEBUG_VERIFY) { 8122 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8123 + " with the correct signature"); 8124 } 8125 sufficientVerifiers.add(comp); 8126 verificationState.addSufficientVerifier(verifierUid); 8127 } 8128 8129 return sufficientVerifiers; 8130 } 8131 8132 private int getUidForVerifier(VerifierInfo verifierInfo) { 8133 synchronized (mPackages) { 8134 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8135 if (pkg == null) { 8136 return -1; 8137 } else if (pkg.mSignatures.length != 1) { 8138 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8139 + " has more than one signature; ignoring"); 8140 return -1; 8141 } 8142 8143 /* 8144 * If the public key of the package's signature does not match 8145 * our expected public key, then this is a different package and 8146 * we should skip. 8147 */ 8148 8149 final byte[] expectedPublicKey; 8150 try { 8151 final Signature verifierSig = pkg.mSignatures[0]; 8152 final PublicKey publicKey = verifierSig.getPublicKey(); 8153 expectedPublicKey = publicKey.getEncoded(); 8154 } catch (CertificateException e) { 8155 return -1; 8156 } 8157 8158 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8159 8160 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8161 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8162 + " does not have the expected public key; ignoring"); 8163 return -1; 8164 } 8165 8166 return pkg.applicationInfo.uid; 8167 } 8168 } 8169 8170 @Override 8171 public void finishPackageInstall(int token) { 8172 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8173 8174 if (DEBUG_INSTALL) { 8175 Slog.v(TAG, "BM finishing package install for " + token); 8176 } 8177 8178 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8179 mHandler.sendMessage(msg); 8180 } 8181 8182 /** 8183 * Get the verification agent timeout. 8184 * 8185 * @return verification timeout in milliseconds 8186 */ 8187 private long getVerificationTimeout() { 8188 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8189 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8190 DEFAULT_VERIFICATION_TIMEOUT); 8191 } 8192 8193 /** 8194 * Get the default verification agent response code. 8195 * 8196 * @return default verification response code 8197 */ 8198 private int getDefaultVerificationResponse() { 8199 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8200 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8201 DEFAULT_VERIFICATION_RESPONSE); 8202 } 8203 8204 /** 8205 * Check whether or not package verification has been enabled. 8206 * 8207 * @return true if verification should be performed 8208 */ 8209 private boolean isVerificationEnabled(int flags) { 8210 if (!DEFAULT_VERIFY_ENABLE) { 8211 return false; 8212 } 8213 8214 // Check if installing from ADB 8215 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8216 // Do not run verification in a test harness environment 8217 if (ActivityManager.isRunningInTestHarness()) { 8218 return false; 8219 } 8220 // Check if the developer does not want package verification for ADB installs 8221 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8222 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8223 return false; 8224 } 8225 } 8226 8227 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8228 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8229 } 8230 8231 /** 8232 * Get the "allow unknown sources" setting. 8233 * 8234 * @return the current "allow unknown sources" setting 8235 */ 8236 private int getUnknownSourcesSettings() { 8237 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8238 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8239 -1); 8240 } 8241 8242 @Override 8243 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8244 final int uid = Binder.getCallingUid(); 8245 // writer 8246 synchronized (mPackages) { 8247 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8248 if (targetPackageSetting == null) { 8249 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8250 } 8251 8252 PackageSetting installerPackageSetting; 8253 if (installerPackageName != null) { 8254 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8255 if (installerPackageSetting == null) { 8256 throw new IllegalArgumentException("Unknown installer package: " 8257 + installerPackageName); 8258 } 8259 } else { 8260 installerPackageSetting = null; 8261 } 8262 8263 Signature[] callerSignature; 8264 Object obj = mSettings.getUserIdLPr(uid); 8265 if (obj != null) { 8266 if (obj instanceof SharedUserSetting) { 8267 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8268 } else if (obj instanceof PackageSetting) { 8269 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8270 } else { 8271 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8272 } 8273 } else { 8274 throw new SecurityException("Unknown calling uid " + uid); 8275 } 8276 8277 // Verify: can't set installerPackageName to a package that is 8278 // not signed with the same cert as the caller. 8279 if (installerPackageSetting != null) { 8280 if (compareSignatures(callerSignature, 8281 installerPackageSetting.signatures.mSignatures) 8282 != PackageManager.SIGNATURE_MATCH) { 8283 throw new SecurityException( 8284 "Caller does not have same cert as new installer package " 8285 + installerPackageName); 8286 } 8287 } 8288 8289 // Verify: if target already has an installer package, it must 8290 // be signed with the same cert as the caller. 8291 if (targetPackageSetting.installerPackageName != null) { 8292 PackageSetting setting = mSettings.mPackages.get( 8293 targetPackageSetting.installerPackageName); 8294 // If the currently set package isn't valid, then it's always 8295 // okay to change it. 8296 if (setting != null) { 8297 if (compareSignatures(callerSignature, 8298 setting.signatures.mSignatures) 8299 != PackageManager.SIGNATURE_MATCH) { 8300 throw new SecurityException( 8301 "Caller does not have same cert as old installer package " 8302 + targetPackageSetting.installerPackageName); 8303 } 8304 } 8305 } 8306 8307 // Okay! 8308 targetPackageSetting.installerPackageName = installerPackageName; 8309 scheduleWriteSettingsLocked(); 8310 } 8311 } 8312 8313 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8314 // Queue up an async operation since the package installation may take a little while. 8315 mHandler.post(new Runnable() { 8316 public void run() { 8317 mHandler.removeCallbacks(this); 8318 // Result object to be returned 8319 PackageInstalledInfo res = new PackageInstalledInfo(); 8320 res.returnCode = currentStatus; 8321 res.uid = -1; 8322 res.pkg = null; 8323 res.removedInfo = new PackageRemovedInfo(); 8324 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8325 args.doPreInstall(res.returnCode); 8326 synchronized (mInstallLock) { 8327 installPackageLI(args, true, res); 8328 } 8329 args.doPostInstall(res.returnCode, res.uid); 8330 } 8331 8332 // A restore should be performed at this point if (a) the install 8333 // succeeded, (b) the operation is not an update, and (c) the new 8334 // package has a backupAgent defined. 8335 final boolean update = res.removedInfo.removedPackage != null; 8336 boolean doRestore = (!update 8337 && res.pkg != null 8338 && res.pkg.applicationInfo.backupAgentName != null); 8339 8340 // Set up the post-install work request bookkeeping. This will be used 8341 // and cleaned up by the post-install event handling regardless of whether 8342 // there's a restore pass performed. Token values are >= 1. 8343 int token; 8344 if (mNextInstallToken < 0) mNextInstallToken = 1; 8345 token = mNextInstallToken++; 8346 8347 PostInstallData data = new PostInstallData(args, res); 8348 mRunningInstalls.put(token, data); 8349 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8350 8351 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8352 // Pass responsibility to the Backup Manager. It will perform a 8353 // restore if appropriate, then pass responsibility back to the 8354 // Package Manager to run the post-install observer callbacks 8355 // and broadcasts. 8356 IBackupManager bm = IBackupManager.Stub.asInterface( 8357 ServiceManager.getService(Context.BACKUP_SERVICE)); 8358 if (bm != null) { 8359 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8360 + " to BM for possible restore"); 8361 try { 8362 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8363 } catch (RemoteException e) { 8364 // can't happen; the backup manager is local 8365 } catch (Exception e) { 8366 Slog.e(TAG, "Exception trying to enqueue restore", e); 8367 doRestore = false; 8368 } 8369 } else { 8370 Slog.e(TAG, "Backup Manager not found!"); 8371 doRestore = false; 8372 } 8373 } 8374 8375 if (!doRestore) { 8376 // No restore possible, or the Backup Manager was mysteriously not 8377 // available -- just fire the post-install work request directly. 8378 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8379 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8380 mHandler.sendMessage(msg); 8381 } 8382 } 8383 }); 8384 } 8385 8386 private abstract class HandlerParams { 8387 private static final int MAX_RETRIES = 4; 8388 8389 /** 8390 * Number of times startCopy() has been attempted and had a non-fatal 8391 * error. 8392 */ 8393 private int mRetries = 0; 8394 8395 /** User handle for the user requesting the information or installation. */ 8396 private final UserHandle mUser; 8397 8398 HandlerParams(UserHandle user) { 8399 mUser = user; 8400 } 8401 8402 UserHandle getUser() { 8403 return mUser; 8404 } 8405 8406 final boolean startCopy() { 8407 boolean res; 8408 try { 8409 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8410 8411 if (++mRetries > MAX_RETRIES) { 8412 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8413 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8414 handleServiceError(); 8415 return false; 8416 } else { 8417 handleStartCopy(); 8418 res = true; 8419 } 8420 } catch (RemoteException e) { 8421 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8422 mHandler.sendEmptyMessage(MCS_RECONNECT); 8423 res = false; 8424 } 8425 handleReturnCode(); 8426 return res; 8427 } 8428 8429 final void serviceError() { 8430 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8431 handleServiceError(); 8432 handleReturnCode(); 8433 } 8434 8435 abstract void handleStartCopy() throws RemoteException; 8436 abstract void handleServiceError(); 8437 abstract void handleReturnCode(); 8438 } 8439 8440 class MeasureParams extends HandlerParams { 8441 private final PackageStats mStats; 8442 private boolean mSuccess; 8443 8444 private final IPackageStatsObserver mObserver; 8445 8446 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8447 super(new UserHandle(stats.userHandle)); 8448 mObserver = observer; 8449 mStats = stats; 8450 } 8451 8452 @Override 8453 public String toString() { 8454 return "MeasureParams{" 8455 + Integer.toHexString(System.identityHashCode(this)) 8456 + " " + mStats.packageName + "}"; 8457 } 8458 8459 @Override 8460 void handleStartCopy() throws RemoteException { 8461 synchronized (mInstallLock) { 8462 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8463 } 8464 8465 if (mSuccess) { 8466 final boolean mounted; 8467 if (Environment.isExternalStorageEmulated()) { 8468 mounted = true; 8469 } else { 8470 final String status = Environment.getExternalStorageState(); 8471 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8472 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8473 } 8474 8475 if (mounted) { 8476 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8477 8478 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8479 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8480 8481 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8482 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8483 8484 // Always subtract cache size, since it's a subdirectory 8485 mStats.externalDataSize -= mStats.externalCacheSize; 8486 8487 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8488 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8489 8490 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8491 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8492 } 8493 } 8494 } 8495 8496 @Override 8497 void handleReturnCode() { 8498 if (mObserver != null) { 8499 try { 8500 mObserver.onGetStatsCompleted(mStats, mSuccess); 8501 } catch (RemoteException e) { 8502 Slog.i(TAG, "Observer no longer exists."); 8503 } 8504 } 8505 } 8506 8507 @Override 8508 void handleServiceError() { 8509 Slog.e(TAG, "Could not measure application " + mStats.packageName 8510 + " external storage"); 8511 } 8512 } 8513 8514 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8515 throws RemoteException { 8516 long result = 0; 8517 for (File path : paths) { 8518 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8519 } 8520 return result; 8521 } 8522 8523 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8524 for (File path : paths) { 8525 try { 8526 mcs.clearDirectory(path.getAbsolutePath()); 8527 } catch (RemoteException e) { 8528 } 8529 } 8530 } 8531 8532 class InstallParams extends HandlerParams { 8533 final IPackageInstallObserver observer; 8534 final IPackageInstallObserver2 observer2; 8535 int flags; 8536 8537 private final Uri mPackageURI; 8538 final String installerPackageName; 8539 final VerificationParams verificationParams; 8540 private InstallArgs mArgs; 8541 private int mRet; 8542 private File mTempPackage; 8543 final ContainerEncryptionParams encryptionParams; 8544 final String packageAbiOverride; 8545 final String packageInstructionSetOverride; 8546 8547 InstallParams(Uri packageURI, 8548 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 8549 int flags, String installerPackageName, VerificationParams verificationParams, 8550 ContainerEncryptionParams encryptionParams, UserHandle user, 8551 String packageAbiOverride) { 8552 super(user); 8553 this.mPackageURI = packageURI; 8554 this.flags = flags; 8555 this.observer = observer; 8556 this.observer2 = observer2; 8557 this.installerPackageName = installerPackageName; 8558 this.verificationParams = verificationParams; 8559 this.encryptionParams = encryptionParams; 8560 this.packageAbiOverride = packageAbiOverride; 8561 this.packageInstructionSetOverride = (packageAbiOverride == null) ? 8562 packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride); 8563 } 8564 8565 @Override 8566 public String toString() { 8567 return "InstallParams{" 8568 + Integer.toHexString(System.identityHashCode(this)) 8569 + " " + mPackageURI + "}"; 8570 } 8571 8572 public ManifestDigest getManifestDigest() { 8573 if (verificationParams == null) { 8574 return null; 8575 } 8576 return verificationParams.getManifestDigest(); 8577 } 8578 8579 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8580 String packageName = pkgLite.packageName; 8581 int installLocation = pkgLite.installLocation; 8582 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8583 // reader 8584 synchronized (mPackages) { 8585 PackageParser.Package pkg = mPackages.get(packageName); 8586 if (pkg != null) { 8587 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8588 // Check for downgrading. 8589 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8590 if (pkgLite.versionCode < pkg.mVersionCode) { 8591 Slog.w(TAG, "Can't install update of " + packageName 8592 + " update version " + pkgLite.versionCode 8593 + " is older than installed version " 8594 + pkg.mVersionCode); 8595 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8596 } 8597 } 8598 // Check for updated system application. 8599 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8600 if (onSd) { 8601 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8602 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8603 } 8604 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8605 } else { 8606 if (onSd) { 8607 // Install flag overrides everything. 8608 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8609 } 8610 // If current upgrade specifies particular preference 8611 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8612 // Application explicitly specified internal. 8613 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8614 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8615 // App explictly prefers external. Let policy decide 8616 } else { 8617 // Prefer previous location 8618 if (isExternal(pkg)) { 8619 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8620 } 8621 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8622 } 8623 } 8624 } else { 8625 // Invalid install. Return error code 8626 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8627 } 8628 } 8629 } 8630 // All the special cases have been taken care of. 8631 // Return result based on recommended install location. 8632 if (onSd) { 8633 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8634 } 8635 return pkgLite.recommendedInstallLocation; 8636 } 8637 8638 private long getMemoryLowThreshold() { 8639 final DeviceStorageMonitorInternal 8640 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8641 if (dsm == null) { 8642 return 0L; 8643 } 8644 return dsm.getMemoryLowThreshold(); 8645 } 8646 8647 /* 8648 * Invoke remote method to get package information and install 8649 * location values. Override install location based on default 8650 * policy if needed and then create install arguments based 8651 * on the install location. 8652 */ 8653 public void handleStartCopy() throws RemoteException { 8654 int ret = PackageManager.INSTALL_SUCCEEDED; 8655 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8656 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8657 PackageInfoLite pkgLite = null; 8658 8659 if (onInt && onSd) { 8660 // Check if both bits are set. 8661 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8662 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8663 } else { 8664 final long lowThreshold = getMemoryLowThreshold(); 8665 if (lowThreshold == 0L) { 8666 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8667 } 8668 8669 try { 8670 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI, 8671 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8672 8673 final File packageFile; 8674 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) { 8675 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir); 8676 if (mTempPackage != null) { 8677 ParcelFileDescriptor out; 8678 try { 8679 out = ParcelFileDescriptor.open(mTempPackage, 8680 ParcelFileDescriptor.MODE_READ_WRITE); 8681 } catch (FileNotFoundException e) { 8682 out = null; 8683 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI); 8684 } 8685 8686 // Make a temporary file for decryption. 8687 ret = mContainerService 8688 .copyResource(mPackageURI, encryptionParams, out); 8689 IoUtils.closeQuietly(out); 8690 8691 packageFile = mTempPackage; 8692 8693 FileUtils.setPermissions(packageFile.getAbsolutePath(), 8694 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP 8695 | FileUtils.S_IROTH, 8696 -1, -1); 8697 } else { 8698 packageFile = null; 8699 } 8700 } else { 8701 packageFile = new File(mPackageURI.getPath()); 8702 } 8703 8704 if (packageFile != null) { 8705 // Remote call to find out default install location 8706 final String packageFilePath = packageFile.getAbsolutePath(); 8707 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags, 8708 lowThreshold, packageAbiOverride); 8709 8710 /* 8711 * If we have too little free space, try to free cache 8712 * before giving up. 8713 */ 8714 if (pkgLite.recommendedInstallLocation 8715 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8716 final long size = mContainerService.calculateInstalledSize( 8717 packageFilePath, isForwardLocked(), packageAbiOverride); 8718 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8719 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, 8720 flags, lowThreshold, packageAbiOverride); 8721 } 8722 /* 8723 * The cache free must have deleted the file we 8724 * downloaded to install. 8725 * 8726 * TODO: fix the "freeCache" call to not delete 8727 * the file we care about. 8728 */ 8729 if (pkgLite.recommendedInstallLocation 8730 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8731 pkgLite.recommendedInstallLocation 8732 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8733 } 8734 } 8735 } 8736 } finally { 8737 mContext.revokeUriPermission(mPackageURI, 8738 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8739 } 8740 } 8741 8742 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8743 int loc = pkgLite.recommendedInstallLocation; 8744 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8745 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8746 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8747 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8748 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8749 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8750 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8751 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8752 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8753 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8754 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8755 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8756 } else { 8757 // Override with defaults if needed. 8758 loc = installLocationPolicy(pkgLite, flags); 8759 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8760 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8761 } else if (!onSd && !onInt) { 8762 // Override install location with flags 8763 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8764 // Set the flag to install on external media. 8765 flags |= PackageManager.INSTALL_EXTERNAL; 8766 flags &= ~PackageManager.INSTALL_INTERNAL; 8767 } else { 8768 // Make sure the flag for installing on external 8769 // media is unset 8770 flags |= PackageManager.INSTALL_INTERNAL; 8771 flags &= ~PackageManager.INSTALL_EXTERNAL; 8772 } 8773 } 8774 } 8775 } 8776 8777 final InstallArgs args = createInstallArgs(this); 8778 mArgs = args; 8779 8780 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8781 /* 8782 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8783 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8784 */ 8785 int userIdentifier = getUser().getIdentifier(); 8786 if (userIdentifier == UserHandle.USER_ALL 8787 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8788 userIdentifier = UserHandle.USER_OWNER; 8789 } 8790 8791 /* 8792 * Determine if we have any installed package verifiers. If we 8793 * do, then we'll defer to them to verify the packages. 8794 */ 8795 final int requiredUid = mRequiredVerifierPackage == null ? -1 8796 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8797 if (requiredUid != -1 && isVerificationEnabled(flags)) { 8798 final Intent verification = new Intent( 8799 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8800 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE); 8801 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8802 8803 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8804 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8805 0 /* TODO: Which userId? */); 8806 8807 if (DEBUG_VERIFY) { 8808 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8809 + verification.toString() + " with " + pkgLite.verifiers.length 8810 + " optional verifiers"); 8811 } 8812 8813 final int verificationId = mPendingVerificationToken++; 8814 8815 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8816 8817 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8818 installerPackageName); 8819 8820 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8821 8822 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8823 pkgLite.packageName); 8824 8825 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8826 pkgLite.versionCode); 8827 8828 if (verificationParams != null) { 8829 if (verificationParams.getVerificationURI() != null) { 8830 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8831 verificationParams.getVerificationURI()); 8832 } 8833 if (verificationParams.getOriginatingURI() != null) { 8834 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8835 verificationParams.getOriginatingURI()); 8836 } 8837 if (verificationParams.getReferrer() != null) { 8838 verification.putExtra(Intent.EXTRA_REFERRER, 8839 verificationParams.getReferrer()); 8840 } 8841 if (verificationParams.getOriginatingUid() >= 0) { 8842 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8843 verificationParams.getOriginatingUid()); 8844 } 8845 if (verificationParams.getInstallerUid() >= 0) { 8846 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8847 verificationParams.getInstallerUid()); 8848 } 8849 } 8850 8851 final PackageVerificationState verificationState = new PackageVerificationState( 8852 requiredUid, args); 8853 8854 mPendingVerification.append(verificationId, verificationState); 8855 8856 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8857 receivers, verificationState); 8858 8859 /* 8860 * If any sufficient verifiers were listed in the package 8861 * manifest, attempt to ask them. 8862 */ 8863 if (sufficientVerifiers != null) { 8864 final int N = sufficientVerifiers.size(); 8865 if (N == 0) { 8866 Slog.i(TAG, "Additional verifiers required, but none installed."); 8867 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8868 } else { 8869 for (int i = 0; i < N; i++) { 8870 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8871 8872 final Intent sufficientIntent = new Intent(verification); 8873 sufficientIntent.setComponent(verifierComponent); 8874 8875 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8876 } 8877 } 8878 } 8879 8880 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8881 mRequiredVerifierPackage, receivers); 8882 if (ret == PackageManager.INSTALL_SUCCEEDED 8883 && mRequiredVerifierPackage != null) { 8884 /* 8885 * Send the intent to the required verification agent, 8886 * but only start the verification timeout after the 8887 * target BroadcastReceivers have run. 8888 */ 8889 verification.setComponent(requiredVerifierComponent); 8890 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8891 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8892 new BroadcastReceiver() { 8893 @Override 8894 public void onReceive(Context context, Intent intent) { 8895 final Message msg = mHandler 8896 .obtainMessage(CHECK_PENDING_VERIFICATION); 8897 msg.arg1 = verificationId; 8898 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8899 } 8900 }, null, 0, null, null); 8901 8902 /* 8903 * We don't want the copy to proceed until verification 8904 * succeeds, so null out this field. 8905 */ 8906 mArgs = null; 8907 } 8908 } else { 8909 /* 8910 * No package verification is enabled, so immediately start 8911 * the remote call to initiate copy using temporary file. 8912 */ 8913 ret = args.copyApk(mContainerService, true); 8914 } 8915 } 8916 8917 mRet = ret; 8918 } 8919 8920 @Override 8921 void handleReturnCode() { 8922 // If mArgs is null, then MCS couldn't be reached. When it 8923 // reconnects, it will try again to install. At that point, this 8924 // will succeed. 8925 if (mArgs != null) { 8926 processPendingInstall(mArgs, mRet); 8927 8928 if (mTempPackage != null) { 8929 if (!mTempPackage.delete()) { 8930 Slog.w(TAG, "Couldn't delete temporary file: " + 8931 mTempPackage.getAbsolutePath()); 8932 } 8933 } 8934 } 8935 } 8936 8937 @Override 8938 void handleServiceError() { 8939 mArgs = createInstallArgs(this); 8940 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8941 } 8942 8943 public boolean isForwardLocked() { 8944 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8945 } 8946 8947 public Uri getPackageUri() { 8948 if (mTempPackage != null) { 8949 return Uri.fromFile(mTempPackage); 8950 } else { 8951 return mPackageURI; 8952 } 8953 } 8954 } 8955 8956 /* 8957 * Utility class used in movePackage api. 8958 * srcArgs and targetArgs are not set for invalid flags and make 8959 * sure to do null checks when invoking methods on them. 8960 * We probably want to return ErrorPrams for both failed installs 8961 * and moves. 8962 */ 8963 class MoveParams extends HandlerParams { 8964 final IPackageMoveObserver observer; 8965 final int flags; 8966 final String packageName; 8967 final InstallArgs srcArgs; 8968 final InstallArgs targetArgs; 8969 int uid; 8970 int mRet; 8971 8972 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8973 String packageName, String dataDir, String instructionSet, 8974 int uid, UserHandle user) { 8975 super(user); 8976 this.srcArgs = srcArgs; 8977 this.observer = observer; 8978 this.flags = flags; 8979 this.packageName = packageName; 8980 this.uid = uid; 8981 if (srcArgs != null) { 8982 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath())); 8983 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet); 8984 } else { 8985 targetArgs = null; 8986 } 8987 } 8988 8989 @Override 8990 public String toString() { 8991 return "MoveParams{" 8992 + Integer.toHexString(System.identityHashCode(this)) 8993 + " " + packageName + "}"; 8994 } 8995 8996 public void handleStartCopy() throws RemoteException { 8997 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8998 // Check for storage space on target medium 8999 if (!targetArgs.checkFreeStorage(mContainerService)) { 9000 Log.w(TAG, "Insufficient storage to install"); 9001 return; 9002 } 9003 9004 mRet = srcArgs.doPreCopy(); 9005 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 9006 return; 9007 } 9008 9009 mRet = targetArgs.copyApk(mContainerService, false); 9010 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 9011 srcArgs.doPostCopy(uid); 9012 return; 9013 } 9014 9015 mRet = srcArgs.doPostCopy(uid); 9016 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 9017 return; 9018 } 9019 9020 mRet = targetArgs.doPreInstall(mRet); 9021 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 9022 return; 9023 } 9024 9025 if (DEBUG_SD_INSTALL) { 9026 StringBuilder builder = new StringBuilder(); 9027 if (srcArgs != null) { 9028 builder.append("src: "); 9029 builder.append(srcArgs.getCodePath()); 9030 } 9031 if (targetArgs != null) { 9032 builder.append(" target : "); 9033 builder.append(targetArgs.getCodePath()); 9034 } 9035 Log.i(TAG, builder.toString()); 9036 } 9037 } 9038 9039 @Override 9040 void handleReturnCode() { 9041 targetArgs.doPostInstall(mRet, uid); 9042 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 9043 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 9044 currentStatus = PackageManager.MOVE_SUCCEEDED; 9045 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 9046 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 9047 } 9048 processPendingMove(this, currentStatus); 9049 } 9050 9051 @Override 9052 void handleServiceError() { 9053 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9054 } 9055 } 9056 9057 /** 9058 * Used during creation of InstallArgs 9059 * 9060 * @param flags package installation flags 9061 * @return true if should be installed on external storage 9062 */ 9063 private static boolean installOnSd(int flags) { 9064 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 9065 return false; 9066 } 9067 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 9068 return true; 9069 } 9070 return false; 9071 } 9072 9073 /** 9074 * Used during creation of InstallArgs 9075 * 9076 * @param flags package installation flags 9077 * @return true if should be installed as forward locked 9078 */ 9079 private static boolean installForwardLocked(int flags) { 9080 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9081 } 9082 9083 private InstallArgs createInstallArgs(InstallParams params) { 9084 if (installOnSd(params.flags) || params.isForwardLocked()) { 9085 return new AsecInstallArgs(params); 9086 } else { 9087 return new FileInstallArgs(params); 9088 } 9089 } 9090 9091 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath, 9092 String nativeLibraryPath, String instructionSet) { 9093 final boolean isInAsec; 9094 if (installOnSd(flags)) { 9095 /* Apps on SD card are always in ASEC containers. */ 9096 isInAsec = true; 9097 } else if (installForwardLocked(flags) 9098 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9099 /* 9100 * Forward-locked apps are only in ASEC containers if they're the 9101 * new style 9102 */ 9103 isInAsec = true; 9104 } else { 9105 isInAsec = false; 9106 } 9107 9108 if (isInAsec) { 9109 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 9110 instructionSet, installOnSd(flags), installForwardLocked(flags)); 9111 } else { 9112 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 9113 instructionSet); 9114 } 9115 } 9116 9117 // Used by package mover 9118 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir, 9119 String instructionSet) { 9120 if (installOnSd(flags) || installForwardLocked(flags)) { 9121 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/" 9122 + AsecInstallArgs.RES_FILE_NAME); 9123 return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags), 9124 installForwardLocked(flags)); 9125 } else { 9126 return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet); 9127 } 9128 } 9129 9130 static abstract class InstallArgs { 9131 final IPackageInstallObserver observer; 9132 final IPackageInstallObserver2 observer2; 9133 // Always refers to PackageManager flags only 9134 final int flags; 9135 final Uri packageURI; 9136 final String installerPackageName; 9137 final ManifestDigest manifestDigest; 9138 final UserHandle user; 9139 final String instructionSet; 9140 final String abiOverride; 9141 9142 InstallArgs(Uri packageURI, 9143 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 9144 int flags, String installerPackageName, ManifestDigest manifestDigest, 9145 UserHandle user, String instructionSet, String abiOverride) { 9146 this.packageURI = packageURI; 9147 this.flags = flags; 9148 this.observer = observer; 9149 this.observer2 = observer2; 9150 this.installerPackageName = installerPackageName; 9151 this.manifestDigest = manifestDigest; 9152 this.user = user; 9153 this.instructionSet = instructionSet; 9154 this.abiOverride = abiOverride; 9155 } 9156 9157 abstract void createCopyFile(); 9158 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9159 abstract int doPreInstall(int status); 9160 abstract boolean doRename(int status, String pkgName, String oldCodePath); 9161 9162 abstract int doPostInstall(int status, int uid); 9163 abstract String getCodePath(); 9164 abstract String getResourcePath(); 9165 abstract String getNativeLibraryPath(); 9166 // Need installer lock especially for dex file removal. 9167 abstract void cleanUpResourcesLI(); 9168 abstract boolean doPostDeleteLI(boolean delete); 9169 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9170 9171 String[] getSplitCodePaths() { 9172 return null; 9173 } 9174 9175 /** 9176 * Called before the source arguments are copied. This is used mostly 9177 * for MoveParams when it needs to read the source file to put it in the 9178 * destination. 9179 */ 9180 int doPreCopy() { 9181 return PackageManager.INSTALL_SUCCEEDED; 9182 } 9183 9184 /** 9185 * Called after the source arguments are copied. This is used mostly for 9186 * MoveParams when it needs to read the source file to put it in the 9187 * destination. 9188 * 9189 * @return 9190 */ 9191 int doPostCopy(int uid) { 9192 return PackageManager.INSTALL_SUCCEEDED; 9193 } 9194 9195 protected boolean isFwdLocked() { 9196 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9197 } 9198 9199 UserHandle getUser() { 9200 return user; 9201 } 9202 } 9203 9204 class FileInstallArgs extends InstallArgs { 9205 File installDir; 9206 String codeFileName; 9207 String resourceFileName; 9208 String libraryPath; 9209 boolean created = false; 9210 9211 FileInstallArgs(InstallParams params) { 9212 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 9213 params.installerPackageName, params.getManifestDigest(), 9214 params.getUser(), params.packageInstructionSetOverride, 9215 params.packageAbiOverride); 9216 } 9217 9218 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9219 String instructionSet) { 9220 super(null, null, null, 0, null, null, null, instructionSet, null); 9221 File codeFile = new File(fullCodePath); 9222 installDir = codeFile.getParentFile(); 9223 codeFileName = fullCodePath; 9224 resourceFileName = fullResourcePath; 9225 libraryPath = nativeLibraryPath; 9226 } 9227 9228 FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) { 9229 super(packageURI, null, null, 0, null, null, null, instructionSet, null); 9230 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 9231 String apkName = getNextCodePath(null, pkgName, ".apk"); 9232 codeFileName = new File(installDir, apkName + ".apk").getPath(); 9233 resourceFileName = getResourcePathFromCodePath(); 9234 libraryPath = new File(mAppLibInstallDir, pkgName).getPath(); 9235 } 9236 9237 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9238 final long lowThreshold; 9239 9240 final DeviceStorageMonitorInternal 9241 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9242 if (dsm == null) { 9243 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9244 lowThreshold = 0L; 9245 } else { 9246 if (dsm.isMemoryLow()) { 9247 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9248 return false; 9249 } 9250 9251 lowThreshold = dsm.getMemoryLowThreshold(); 9252 } 9253 9254 try { 9255 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9256 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9257 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold); 9258 } finally { 9259 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9260 } 9261 } 9262 9263 void createCopyFile() { 9264 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 9265 codeFileName = createTempPackageFile(installDir).getPath(); 9266 resourceFileName = getResourcePathFromCodePath(); 9267 libraryPath = getLibraryPathFromCodePath(); 9268 created = true; 9269 } 9270 9271 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9272 if (temp) { 9273 // Generate temp file name 9274 createCopyFile(); 9275 } 9276 // Get a ParcelFileDescriptor to write to the output file 9277 File codeFile = new File(codeFileName); 9278 if (!created) { 9279 try { 9280 codeFile.createNewFile(); 9281 // Set permissions 9282 if (!setPermissions()) { 9283 // Failed setting permissions. 9284 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9285 } 9286 } catch (IOException e) { 9287 Slog.w(TAG, "Failed to create file " + codeFile); 9288 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9289 } 9290 } 9291 ParcelFileDescriptor out = null; 9292 try { 9293 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 9294 } catch (FileNotFoundException e) { 9295 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 9296 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9297 } 9298 // Copy the resource now 9299 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9300 try { 9301 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9302 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9303 ret = imcs.copyResource(packageURI, null, out); 9304 } finally { 9305 IoUtils.closeQuietly(out); 9306 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9307 } 9308 9309 if (isFwdLocked()) { 9310 final File destResourceFile = new File(getResourcePath()); 9311 9312 // Copy the public files 9313 try { 9314 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 9315 } catch (IOException e) { 9316 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 9317 + " forward-locked app."); 9318 destResourceFile.delete(); 9319 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9320 } 9321 } 9322 9323 final File nativeLibraryFile = new File(getNativeLibraryPath()); 9324 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath()); 9325 if (nativeLibraryFile.exists()) { 9326 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 9327 nativeLibraryFile.delete(); 9328 } 9329 9330 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(codeFile); 9331 String[] abiList = (abiOverride != null) ? 9332 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9333 try { 9334 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 9335 abiOverride == null && 9336 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9337 abiList = Build.SUPPORTED_32_BIT_ABIS; 9338 } 9339 9340 int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList); 9341 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9342 return copyRet; 9343 } 9344 } catch (IOException e) { 9345 Slog.e(TAG, "Copying native libraries failed", e); 9346 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9347 } finally { 9348 handle.close(); 9349 } 9350 9351 return ret; 9352 } 9353 9354 int doPreInstall(int status) { 9355 if (status != PackageManager.INSTALL_SUCCEEDED) { 9356 cleanUp(); 9357 } 9358 return status; 9359 } 9360 9361 boolean doRename(int status, final String pkgName, String oldCodePath) { 9362 if (status != PackageManager.INSTALL_SUCCEEDED) { 9363 cleanUp(); 9364 return false; 9365 } else { 9366 final File oldCodeFile = new File(getCodePath()); 9367 final File oldResourceFile = new File(getResourcePath()); 9368 final File oldLibraryFile = new File(getNativeLibraryPath()); 9369 9370 // Rename APK file based on packageName 9371 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 9372 final File newCodeFile = new File(installDir, apkName + ".apk"); 9373 if (!oldCodeFile.renameTo(newCodeFile)) { 9374 return false; 9375 } 9376 codeFileName = newCodeFile.getPath(); 9377 9378 // Rename public resource file if it's forward-locked. 9379 final File newResFile = new File(getResourcePathFromCodePath()); 9380 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 9381 return false; 9382 } 9383 resourceFileName = newResFile.getPath(); 9384 9385 // Rename library path 9386 final File newLibraryFile = new File(getLibraryPathFromCodePath()); 9387 if (newLibraryFile.exists()) { 9388 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile); 9389 newLibraryFile.delete(); 9390 } 9391 if (!oldLibraryFile.renameTo(newLibraryFile)) { 9392 Slog.e(TAG, "Cannot rename native library directory " 9393 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath()); 9394 return false; 9395 } 9396 libraryPath = newLibraryFile.getPath(); 9397 9398 // Attempt to set permissions 9399 if (!setPermissions()) { 9400 return false; 9401 } 9402 9403 if (!SELinux.restorecon(newCodeFile)) { 9404 return false; 9405 } 9406 9407 return true; 9408 } 9409 } 9410 9411 int doPostInstall(int status, int uid) { 9412 if (status != PackageManager.INSTALL_SUCCEEDED) { 9413 cleanUp(); 9414 } 9415 return status; 9416 } 9417 9418 private String getResourcePathFromCodePath() { 9419 final String codePath = getCodePath(); 9420 if (isFwdLocked()) { 9421 final StringBuilder sb = new StringBuilder(); 9422 9423 sb.append(mAppInstallDir.getPath()); 9424 sb.append('/'); 9425 sb.append(getApkName(codePath)); 9426 sb.append(".zip"); 9427 9428 /* 9429 * If our APK is a temporary file, mark the resource as a 9430 * temporary file as well so it can be cleaned up after 9431 * catastrophic failure. 9432 */ 9433 if (codePath.endsWith(".tmp")) { 9434 sb.append(".tmp"); 9435 } 9436 9437 return sb.toString(); 9438 } else { 9439 return codePath; 9440 } 9441 } 9442 9443 private String getLibraryPathFromCodePath() { 9444 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath(); 9445 } 9446 9447 @Override 9448 String getCodePath() { 9449 return codeFileName; 9450 } 9451 9452 @Override 9453 String getResourcePath() { 9454 return resourceFileName; 9455 } 9456 9457 @Override 9458 String getNativeLibraryPath() { 9459 if (libraryPath == null) { 9460 libraryPath = getLibraryPathFromCodePath(); 9461 } 9462 return libraryPath; 9463 } 9464 9465 private boolean cleanUp() { 9466 boolean ret = true; 9467 String sourceDir = getCodePath(); 9468 String publicSourceDir = getResourcePath(); 9469 if (sourceDir != null) { 9470 File sourceFile = new File(sourceDir); 9471 if (!sourceFile.exists()) { 9472 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 9473 ret = false; 9474 } 9475 // Delete application's code and resources 9476 sourceFile.delete(); 9477 } 9478 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 9479 final File publicSourceFile = new File(publicSourceDir); 9480 if (!publicSourceFile.exists()) { 9481 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 9482 } 9483 if (publicSourceFile.exists()) { 9484 publicSourceFile.delete(); 9485 } 9486 } 9487 9488 if (libraryPath != null) { 9489 File nativeLibraryFile = new File(libraryPath); 9490 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 9491 if (!nativeLibraryFile.delete()) { 9492 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath); 9493 } 9494 } 9495 9496 return ret; 9497 } 9498 9499 void cleanUpResourcesLI() { 9500 String sourceDir = getCodePath(); 9501 if (cleanUp()) { 9502 if (instructionSet == null) { 9503 throw new IllegalStateException("instructionSet == null"); 9504 } 9505 int retCode = mInstaller.rmdex(sourceDir, instructionSet); 9506 if (retCode < 0) { 9507 Slog.w(TAG, "Couldn't remove dex file for package: " 9508 + " at location " 9509 + sourceDir + ", retcode=" + retCode); 9510 // we don't consider this to be a failure of the core package deletion 9511 } 9512 } 9513 } 9514 9515 private boolean setPermissions() { 9516 // TODO Do this in a more elegant way later on. for now just a hack 9517 if (!isFwdLocked()) { 9518 final int filePermissions = 9519 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 9520 |FileUtils.S_IROTH; 9521 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 9522 if (retCode != 0) { 9523 Slog.e(TAG, "Couldn't set new package file permissions for " + 9524 getCodePath() 9525 + ". The return code was: " + retCode); 9526 // TODO Define new internal error 9527 return false; 9528 } 9529 return true; 9530 } 9531 return true; 9532 } 9533 9534 boolean doPostDeleteLI(boolean delete) { 9535 // XXX err, shouldn't we respect the delete flag? 9536 cleanUpResourcesLI(); 9537 return true; 9538 } 9539 } 9540 9541 private boolean isAsecExternal(String cid) { 9542 final String asecPath = PackageHelper.getSdFilesystem(cid); 9543 return !asecPath.startsWith(mAsecInternalPath); 9544 } 9545 9546 /** 9547 * Extract the MountService "container ID" from the full code path of an 9548 * .apk. 9549 */ 9550 static String cidFromCodePath(String fullCodePath) { 9551 int eidx = fullCodePath.lastIndexOf("/"); 9552 String subStr1 = fullCodePath.substring(0, eidx); 9553 int sidx = subStr1.lastIndexOf("/"); 9554 return subStr1.substring(sidx+1, eidx); 9555 } 9556 9557 class AsecInstallArgs extends InstallArgs { 9558 static final String RES_FILE_NAME = "pkg.apk"; 9559 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9560 9561 String cid; 9562 String packagePath; 9563 String resourcePath; 9564 String libraryPath; 9565 9566 AsecInstallArgs(InstallParams params) { 9567 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 9568 params.installerPackageName, params.getManifestDigest(), 9569 params.getUser(), params.packageInstructionSetOverride, 9570 params.packageAbiOverride); 9571 } 9572 9573 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9574 String instructionSet, boolean isExternal, boolean isForwardLocked) { 9575 super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9576 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9577 null, null, null, instructionSet, null); 9578 // Extract cid from fullCodePath 9579 int eidx = fullCodePath.lastIndexOf("/"); 9580 String subStr1 = fullCodePath.substring(0, eidx); 9581 int sidx = subStr1.lastIndexOf("/"); 9582 cid = subStr1.substring(sidx+1, eidx); 9583 setCachePath(subStr1); 9584 } 9585 9586 AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) { 9587 super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 9588 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9589 null, null, null, instructionSet, null); 9590 this.cid = cid; 9591 setCachePath(PackageHelper.getSdDir(cid)); 9592 } 9593 9594 AsecInstallArgs(Uri packageURI, String cid, String instructionSet, 9595 boolean isExternal, boolean isForwardLocked) { 9596 super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9597 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9598 null, null, null, instructionSet, null); 9599 this.cid = cid; 9600 } 9601 9602 void createCopyFile() { 9603 cid = getTempContainerId(); 9604 } 9605 9606 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9607 try { 9608 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9609 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9610 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked(), abiOverride); 9611 } finally { 9612 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9613 } 9614 } 9615 9616 private final boolean isExternal() { 9617 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9618 } 9619 9620 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9621 if (temp) { 9622 createCopyFile(); 9623 } else { 9624 /* 9625 * Pre-emptively destroy the container since it's destroyed if 9626 * copying fails due to it existing anyway. 9627 */ 9628 PackageHelper.destroySdDir(cid); 9629 } 9630 9631 final String newCachePath; 9632 try { 9633 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9634 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9635 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(), 9636 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked(), 9637 abiOverride); 9638 } finally { 9639 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9640 } 9641 9642 if (newCachePath != null) { 9643 setCachePath(newCachePath); 9644 return PackageManager.INSTALL_SUCCEEDED; 9645 } else { 9646 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9647 } 9648 } 9649 9650 @Override 9651 String getCodePath() { 9652 return packagePath; 9653 } 9654 9655 @Override 9656 String getResourcePath() { 9657 return resourcePath; 9658 } 9659 9660 @Override 9661 String getNativeLibraryPath() { 9662 return libraryPath; 9663 } 9664 9665 int doPreInstall(int status) { 9666 if (status != PackageManager.INSTALL_SUCCEEDED) { 9667 // Destroy container 9668 PackageHelper.destroySdDir(cid); 9669 } else { 9670 boolean mounted = PackageHelper.isContainerMounted(cid); 9671 if (!mounted) { 9672 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9673 Process.SYSTEM_UID); 9674 if (newCachePath != null) { 9675 setCachePath(newCachePath); 9676 } else { 9677 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9678 } 9679 } 9680 } 9681 return status; 9682 } 9683 9684 boolean doRename(int status, final String pkgName, 9685 String oldCodePath) { 9686 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 9687 String newCachePath = null; 9688 if (PackageHelper.isContainerMounted(cid)) { 9689 // Unmount the container 9690 if (!PackageHelper.unMountSdDir(cid)) { 9691 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9692 return false; 9693 } 9694 } 9695 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9696 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9697 " which might be stale. Will try to clean up."); 9698 // Clean up the stale container and proceed to recreate. 9699 if (!PackageHelper.destroySdDir(newCacheId)) { 9700 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9701 return false; 9702 } 9703 // Successfully cleaned up stale container. Try to rename again. 9704 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9705 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9706 + " inspite of cleaning it up."); 9707 return false; 9708 } 9709 } 9710 if (!PackageHelper.isContainerMounted(newCacheId)) { 9711 Slog.w(TAG, "Mounting container " + newCacheId); 9712 newCachePath = PackageHelper.mountSdDir(newCacheId, 9713 getEncryptKey(), Process.SYSTEM_UID); 9714 } else { 9715 newCachePath = PackageHelper.getSdDir(newCacheId); 9716 } 9717 if (newCachePath == null) { 9718 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9719 return false; 9720 } 9721 Log.i(TAG, "Succesfully renamed " + cid + 9722 " to " + newCacheId + 9723 " at new path: " + newCachePath); 9724 cid = newCacheId; 9725 setCachePath(newCachePath); 9726 return true; 9727 } 9728 9729 private void setCachePath(String newCachePath) { 9730 File cachePath = new File(newCachePath); 9731 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 9732 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9733 9734 if (isFwdLocked()) { 9735 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9736 } else { 9737 resourcePath = packagePath; 9738 } 9739 } 9740 9741 int doPostInstall(int status, int uid) { 9742 if (status != PackageManager.INSTALL_SUCCEEDED) { 9743 cleanUp(); 9744 } else { 9745 final int groupOwner; 9746 final String protectedFile; 9747 if (isFwdLocked()) { 9748 groupOwner = UserHandle.getSharedAppGid(uid); 9749 protectedFile = RES_FILE_NAME; 9750 } else { 9751 groupOwner = -1; 9752 protectedFile = null; 9753 } 9754 9755 if (uid < Process.FIRST_APPLICATION_UID 9756 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9757 Slog.e(TAG, "Failed to finalize " + cid); 9758 PackageHelper.destroySdDir(cid); 9759 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9760 } 9761 9762 boolean mounted = PackageHelper.isContainerMounted(cid); 9763 if (!mounted) { 9764 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9765 } 9766 } 9767 return status; 9768 } 9769 9770 private void cleanUp() { 9771 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9772 9773 // Destroy secure container 9774 PackageHelper.destroySdDir(cid); 9775 } 9776 9777 void cleanUpResourcesLI() { 9778 String sourceFile = getCodePath(); 9779 // Remove dex file 9780 if (instructionSet == null) { 9781 throw new IllegalStateException("instructionSet == null"); 9782 } 9783 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9784 if (retCode < 0) { 9785 Slog.w(TAG, "Couldn't remove dex file for package: " 9786 + " at location " 9787 + sourceFile.toString() + ", retcode=" + retCode); 9788 // we don't consider this to be a failure of the core package deletion 9789 } 9790 cleanUp(); 9791 } 9792 9793 boolean matchContainer(String app) { 9794 if (cid.startsWith(app)) { 9795 return true; 9796 } 9797 return false; 9798 } 9799 9800 String getPackageName() { 9801 return getAsecPackageName(cid); 9802 } 9803 9804 boolean doPostDeleteLI(boolean delete) { 9805 boolean ret = false; 9806 boolean mounted = PackageHelper.isContainerMounted(cid); 9807 if (mounted) { 9808 // Unmount first 9809 ret = PackageHelper.unMountSdDir(cid); 9810 } 9811 if (ret && delete) { 9812 cleanUpResourcesLI(); 9813 } 9814 return ret; 9815 } 9816 9817 @Override 9818 int doPreCopy() { 9819 if (isFwdLocked()) { 9820 if (!PackageHelper.fixSdPermissions(cid, 9821 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9822 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9823 } 9824 } 9825 9826 return PackageManager.INSTALL_SUCCEEDED; 9827 } 9828 9829 @Override 9830 int doPostCopy(int uid) { 9831 if (isFwdLocked()) { 9832 if (uid < Process.FIRST_APPLICATION_UID 9833 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9834 RES_FILE_NAME)) { 9835 Slog.e(TAG, "Failed to finalize " + cid); 9836 PackageHelper.destroySdDir(cid); 9837 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9838 } 9839 } 9840 9841 return PackageManager.INSTALL_SUCCEEDED; 9842 } 9843 } 9844 9845 static String getAsecPackageName(String packageCid) { 9846 int idx = packageCid.lastIndexOf("-"); 9847 if (idx == -1) { 9848 return packageCid; 9849 } 9850 return packageCid.substring(0, idx); 9851 } 9852 9853 // Utility method used to create code paths based on package name and available index. 9854 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9855 String idxStr = ""; 9856 int idx = 1; 9857 // Fall back to default value of idx=1 if prefix is not 9858 // part of oldCodePath 9859 if (oldCodePath != null) { 9860 String subStr = oldCodePath; 9861 // Drop the suffix right away 9862 if (subStr.endsWith(suffix)) { 9863 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9864 } 9865 // If oldCodePath already contains prefix find out the 9866 // ending index to either increment or decrement. 9867 int sidx = subStr.lastIndexOf(prefix); 9868 if (sidx != -1) { 9869 subStr = subStr.substring(sidx + prefix.length()); 9870 if (subStr != null) { 9871 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9872 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9873 } 9874 try { 9875 idx = Integer.parseInt(subStr); 9876 if (idx <= 1) { 9877 idx++; 9878 } else { 9879 idx--; 9880 } 9881 } catch(NumberFormatException e) { 9882 } 9883 } 9884 } 9885 } 9886 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9887 return prefix + idxStr; 9888 } 9889 9890 // Utility method used to ignore ADD/REMOVE events 9891 // by directory observer. 9892 private static boolean ignoreCodePath(String fullPathStr) { 9893 String apkName = getApkName(fullPathStr); 9894 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9895 if (idx != -1 && ((idx+1) < apkName.length())) { 9896 // Make sure the package ends with a numeral 9897 String version = apkName.substring(idx+1); 9898 try { 9899 Integer.parseInt(version); 9900 return true; 9901 } catch (NumberFormatException e) {} 9902 } 9903 return false; 9904 } 9905 9906 // Utility method that returns the relative package path with respect 9907 // to the installation directory. Like say for /data/data/com.test-1.apk 9908 // string com.test-1 is returned. 9909 static String getApkName(String codePath) { 9910 if (codePath == null) { 9911 return null; 9912 } 9913 int sidx = codePath.lastIndexOf("/"); 9914 int eidx = codePath.lastIndexOf("."); 9915 if (eidx == -1) { 9916 eidx = codePath.length(); 9917 } else if (eidx == 0) { 9918 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 9919 return null; 9920 } 9921 return codePath.substring(sidx+1, eidx); 9922 } 9923 9924 private static String[] deriveSplitResPaths(String[] splitCodePaths) { 9925 String[] splitResPaths = null; 9926 if (!ArrayUtils.isEmpty(splitCodePaths)) { 9927 splitResPaths = new String[splitCodePaths.length]; 9928 for (int i = 0; i < splitCodePaths.length; i++) { 9929 final String splitCodePath = splitCodePaths[i]; 9930 final String resName = getApkName(splitCodePath) + ".zip"; 9931 splitResPaths[i] = new File(new File(splitCodePath).getParentFile(), 9932 resName).getAbsolutePath(); 9933 } 9934 } 9935 return splitResPaths; 9936 } 9937 9938 class PackageInstalledInfo { 9939 String name; 9940 int uid; 9941 // The set of users that originally had this package installed. 9942 int[] origUsers; 9943 // The set of users that now have this package installed. 9944 int[] newUsers; 9945 PackageParser.Package pkg; 9946 int returnCode; 9947 PackageRemovedInfo removedInfo; 9948 9949 // In some error cases we want to convey more info back to the observer 9950 String origPackage; 9951 String origPermission; 9952 } 9953 9954 /* 9955 * Install a non-existing package. 9956 */ 9957 private void installNewPackageLI(PackageParser.Package pkg, 9958 int parseFlags, int scanMode, UserHandle user, 9959 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9960 // Remember this for later, in case we need to rollback this install 9961 String pkgName = pkg.packageName; 9962 9963 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9964 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9965 synchronized(mPackages) { 9966 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9967 // A package with the same name is already installed, though 9968 // it has been renamed to an older name. The package we 9969 // are trying to install should be installed as an update to 9970 // the existing one, but that has not been requested, so bail. 9971 Slog.w(TAG, "Attempt to re-install " + pkgName 9972 + " without first uninstalling package running as " 9973 + mSettings.mRenamedPackages.get(pkgName)); 9974 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9975 return; 9976 } 9977 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9978 // Don't allow installation over an existing package with the same name. 9979 Slog.w(TAG, "Attempt to re-install " + pkgName 9980 + " without first uninstalling."); 9981 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9982 return; 9983 } 9984 } 9985 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9986 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9987 System.currentTimeMillis(), user, abiOverride); 9988 if (newPackage == null) { 9989 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9990 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9991 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9992 } 9993 } else { 9994 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9995 // delete the partially installed application. the data directory will have to be 9996 // restored if it was already existing 9997 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9998 // remove package from internal structures. Note that we want deletePackageX to 9999 // delete the package data and cache directories that it created in 10000 // scanPackageLocked, unless those directories existed before we even tried to 10001 // install. 10002 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10003 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10004 res.removedInfo, true); 10005 } 10006 } 10007 } 10008 10009 private void replacePackageLI(PackageParser.Package pkg, 10010 int parseFlags, int scanMode, UserHandle user, 10011 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10012 10013 PackageParser.Package oldPackage; 10014 String pkgName = pkg.packageName; 10015 int[] allUsers; 10016 boolean[] perUserInstalled; 10017 10018 // First find the old package info and check signatures 10019 synchronized(mPackages) { 10020 oldPackage = mPackages.get(pkgName); 10021 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10022 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10023 != PackageManager.SIGNATURE_MATCH) { 10024 Slog.w(TAG, "New package has a different signature: " + pkgName); 10025 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 10026 return; 10027 } 10028 10029 // In case of rollback, remember per-user/profile install state 10030 PackageSetting ps = mSettings.mPackages.get(pkgName); 10031 allUsers = sUserManager.getUserIds(); 10032 perUserInstalled = new boolean[allUsers.length]; 10033 for (int i = 0; i < allUsers.length; i++) { 10034 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10035 } 10036 } 10037 boolean sysPkg = (isSystemApp(oldPackage)); 10038 if (sysPkg) { 10039 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10040 user, allUsers, perUserInstalled, installerPackageName, res, 10041 abiOverride); 10042 } else { 10043 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10044 user, allUsers, perUserInstalled, installerPackageName, res, 10045 abiOverride); 10046 } 10047 } 10048 10049 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10050 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10051 int[] allUsers, boolean[] perUserInstalled, 10052 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10053 PackageParser.Package newPackage = null; 10054 String pkgName = deletedPackage.packageName; 10055 boolean deletedPkg = true; 10056 boolean updatedSettings = false; 10057 10058 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10059 + deletedPackage); 10060 long origUpdateTime; 10061 if (pkg.mExtras != null) { 10062 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10063 } else { 10064 origUpdateTime = 0; 10065 } 10066 10067 // First delete the existing package while retaining the data directory 10068 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10069 res.removedInfo, true)) { 10070 // If the existing package wasn't successfully deleted 10071 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 10072 deletedPkg = false; 10073 } else { 10074 // Successfully deleted the old package. Now proceed with re-installation 10075 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 10076 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 10077 System.currentTimeMillis(), user, abiOverride); 10078 if (newPackage == null) { 10079 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 10080 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 10081 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 10082 } 10083 } else { 10084 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10085 updatedSettings = true; 10086 } 10087 } 10088 10089 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10090 // remove package from internal structures. Note that we want deletePackageX to 10091 // delete the package data and cache directories that it created in 10092 // scanPackageLocked, unless those directories existed before we even tried to 10093 // install. 10094 if(updatedSettings) { 10095 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10096 deletePackageLI( 10097 pkgName, null, true, allUsers, perUserInstalled, 10098 PackageManager.DELETE_KEEP_DATA, 10099 res.removedInfo, true); 10100 } 10101 // Since we failed to install the new package we need to restore the old 10102 // package that we deleted. 10103 if (deletedPkg) { 10104 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10105 File restoreFile = new File(deletedPackage.codePath); 10106 // Parse old package 10107 boolean oldOnSd = isExternal(deletedPackage); 10108 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10109 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10110 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10111 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10112 | SCAN_UPDATE_TIME; 10113 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 10114 origUpdateTime, null, null) == null) { 10115 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 10116 return; 10117 } 10118 // Restore of old package succeeded. Update permissions. 10119 // writer 10120 synchronized (mPackages) { 10121 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10122 UPDATE_PERMISSIONS_ALL); 10123 // can downgrade to reader 10124 mSettings.writeLPr(); 10125 } 10126 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10127 } 10128 } 10129 } 10130 10131 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10132 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10133 int[] allUsers, boolean[] perUserInstalled, 10134 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10135 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10136 + ", old=" + deletedPackage); 10137 PackageParser.Package newPackage = null; 10138 boolean updatedSettings = false; 10139 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10140 PackageParser.PARSE_IS_SYSTEM; 10141 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10142 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10143 } 10144 String packageName = deletedPackage.packageName; 10145 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 10146 if (packageName == null) { 10147 Slog.w(TAG, "Attempt to delete null packageName."); 10148 return; 10149 } 10150 PackageParser.Package oldPkg; 10151 PackageSetting oldPkgSetting; 10152 // reader 10153 synchronized (mPackages) { 10154 oldPkg = mPackages.get(packageName); 10155 oldPkgSetting = mSettings.mPackages.get(packageName); 10156 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10157 (oldPkgSetting == null)) { 10158 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 10159 return; 10160 } 10161 } 10162 10163 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10164 10165 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10166 res.removedInfo.removedPackage = packageName; 10167 // Remove existing system package 10168 removePackageLI(oldPkgSetting, true); 10169 // writer 10170 synchronized (mPackages) { 10171 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10172 // We didn't need to disable the .apk as a current system package, 10173 // which means we are replacing another update that is already 10174 // installed. We need to make sure to delete the older one's .apk. 10175 res.removedInfo.args = createInstallArgs(0, 10176 deletedPackage.applicationInfo.sourceDir, 10177 deletedPackage.applicationInfo.publicSourceDir, 10178 deletedPackage.applicationInfo.nativeLibraryDir, 10179 getAppInstructionSet(deletedPackage.applicationInfo)); 10180 } else { 10181 res.removedInfo.args = null; 10182 } 10183 } 10184 10185 // Successfully disabled the old package. Now proceed with re-installation 10186 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 10187 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10188 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10189 if (newPackage == null) { 10190 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 10191 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 10192 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 10193 } 10194 } else { 10195 if (newPackage.mExtras != null) { 10196 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 10197 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10198 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10199 10200 // is the update attempting to change shared user? that isn't going to work... 10201 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10202 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 10203 + " to " + newPkgSetting.sharedUser); 10204 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 10205 updatedSettings = true; 10206 } 10207 } 10208 10209 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10210 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10211 updatedSettings = true; 10212 } 10213 } 10214 10215 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10216 // Re installation failed. Restore old information 10217 // Remove new pkg information 10218 if (newPackage != null) { 10219 removeInstalledPackageLI(newPackage, true); 10220 } 10221 // Add back the old system package 10222 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null); 10223 // Restore the old system information in Settings 10224 synchronized(mPackages) { 10225 if (updatedSettings) { 10226 mSettings.enableSystemPackageLPw(packageName); 10227 mSettings.setInstallerPackageName(packageName, 10228 oldPkgSetting.installerPackageName); 10229 } 10230 mSettings.writeLPr(); 10231 } 10232 } 10233 } 10234 10235 // Utility method used to move dex files during install. 10236 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10237 // TODO: extend to move split APK dex files 10238 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10239 final String instructionSet = getAppInstructionSet(newPackage.applicationInfo); 10240 int retCode = mInstaller.movedex(oldCodePath, newPackage.codePath, 10241 instructionSet); 10242 if (retCode != 0) { 10243 /* 10244 * Programs may be lazily run through dexopt, so the 10245 * source may not exist. However, something seems to 10246 * have gone wrong, so note that dexopt needs to be 10247 * run again and remove the source file. In addition, 10248 * remove the target to make sure there isn't a stale 10249 * file from a previous version of the package. 10250 */ 10251 newPackage.mDexOptNeeded = true; 10252 mInstaller.rmdex(oldCodePath, instructionSet); 10253 mInstaller.rmdex(newPackage.codePath, instructionSet); 10254 } 10255 } 10256 return PackageManager.INSTALL_SUCCEEDED; 10257 } 10258 10259 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10260 int[] allUsers, boolean[] perUserInstalled, 10261 PackageInstalledInfo res) { 10262 String pkgName = newPackage.packageName; 10263 synchronized (mPackages) { 10264 //write settings. the installStatus will be incomplete at this stage. 10265 //note that the new package setting would have already been 10266 //added to mPackages. It hasn't been persisted yet. 10267 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10268 mSettings.writeLPr(); 10269 } 10270 10271 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10272 10273 synchronized (mPackages) { 10274 updatePermissionsLPw(newPackage.packageName, newPackage, 10275 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10276 ? UPDATE_PERMISSIONS_ALL : 0)); 10277 // For system-bundled packages, we assume that installing an upgraded version 10278 // of the package implies that the user actually wants to run that new code, 10279 // so we enable the package. 10280 if (isSystemApp(newPackage)) { 10281 // NB: implicit assumption that system package upgrades apply to all users 10282 if (DEBUG_INSTALL) { 10283 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10284 } 10285 PackageSetting ps = mSettings.mPackages.get(pkgName); 10286 if (ps != null) { 10287 if (res.origUsers != null) { 10288 for (int userHandle : res.origUsers) { 10289 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10290 userHandle, installerPackageName); 10291 } 10292 } 10293 // Also convey the prior install/uninstall state 10294 if (allUsers != null && perUserInstalled != null) { 10295 for (int i = 0; i < allUsers.length; i++) { 10296 if (DEBUG_INSTALL) { 10297 Slog.d(TAG, " user " + allUsers[i] 10298 + " => " + perUserInstalled[i]); 10299 } 10300 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10301 } 10302 // these install state changes will be persisted in the 10303 // upcoming call to mSettings.writeLPr(). 10304 } 10305 } 10306 } 10307 res.name = pkgName; 10308 res.uid = newPackage.applicationInfo.uid; 10309 res.pkg = newPackage; 10310 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10311 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10312 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10313 //to update install status 10314 mSettings.writeLPr(); 10315 } 10316 } 10317 10318 private void installPackageLI(InstallArgs args, 10319 boolean newInstall, PackageInstalledInfo res) { 10320 int pFlags = args.flags; 10321 String installerPackageName = args.installerPackageName; 10322 File tmpPackageFile = new File(args.getCodePath()); 10323 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10324 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10325 boolean replace = false; 10326 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10327 | (newInstall ? SCAN_NEW_INSTALL : 0); 10328 // Result object to be returned 10329 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10330 10331 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10332 // Retrieve PackageSettings and parse package 10333 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10334 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10335 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10336 PackageParser pp = new PackageParser(); 10337 pp.setSeparateProcesses(mSeparateProcesses); 10338 pp.setDisplayMetrics(mMetrics); 10339 10340 final PackageParser.Package pkg; 10341 try { 10342 pkg = pp.parseMonolithicPackage(tmpPackageFile, parseFlags); 10343 } catch (PackageParserException e) { 10344 res.returnCode = e.error; 10345 return; 10346 } 10347 10348 String pkgName = res.name = pkg.packageName; 10349 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10350 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10351 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 10352 return; 10353 } 10354 } 10355 10356 try { 10357 pp.collectCertificates(pkg, parseFlags); 10358 } catch (PackageParserException e) { 10359 res.returnCode = e.error; 10360 return; 10361 } 10362 10363 /* If the installer passed in a manifest digest, compare it now. */ 10364 if (args.manifestDigest != null) { 10365 if (DEBUG_INSTALL) { 10366 final String parsedManifest = pkg.manifestDigest == null ? "null" 10367 : pkg.manifestDigest.toString(); 10368 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10369 + parsedManifest); 10370 } 10371 10372 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10373 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 10374 return; 10375 } 10376 } else if (DEBUG_INSTALL) { 10377 final String parsedManifest = pkg.manifestDigest == null 10378 ? "null" : pkg.manifestDigest.toString(); 10379 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10380 } 10381 10382 // Get rid of all references to package scan path via parser. 10383 pp = null; 10384 String oldCodePath = null; 10385 boolean systemApp = false; 10386 synchronized (mPackages) { 10387 // Check whether the newly-scanned package wants to define an already-defined perm 10388 int N = pkg.permissions.size(); 10389 for (int i = N-1; i >= 0; i--) { 10390 PackageParser.Permission perm = pkg.permissions.get(i); 10391 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10392 if (bp != null) { 10393 // If the defining package is signed with our cert, it's okay. This 10394 // also includes the "updating the same package" case, of course. 10395 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10396 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10397 // If the owning package is the system itself, we log but allow 10398 // install to proceed; we fail the install on all other permission 10399 // redefinitions. 10400 if (!bp.sourcePackage.equals("android")) { 10401 Slog.w(TAG, "Package " + pkg.packageName 10402 + " attempting to redeclare permission " + perm.info.name 10403 + " already owned by " + bp.sourcePackage); 10404 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 10405 res.origPermission = perm.info.name; 10406 res.origPackage = bp.sourcePackage; 10407 return; 10408 } else { 10409 Slog.w(TAG, "Package " + pkg.packageName 10410 + " attempting to redeclare system permission " 10411 + perm.info.name + "; ignoring new declaration"); 10412 pkg.permissions.remove(i); 10413 } 10414 } 10415 } 10416 } 10417 10418 // Check if installing already existing package 10419 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10420 String oldName = mSettings.mRenamedPackages.get(pkgName); 10421 if (pkg.mOriginalPackages != null 10422 && pkg.mOriginalPackages.contains(oldName) 10423 && mPackages.containsKey(oldName)) { 10424 // This package is derived from an original package, 10425 // and this device has been updating from that original 10426 // name. We must continue using the original name, so 10427 // rename the new package here. 10428 pkg.setPackageName(oldName); 10429 pkgName = pkg.packageName; 10430 replace = true; 10431 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10432 + oldName + " pkgName=" + pkgName); 10433 } else if (mPackages.containsKey(pkgName)) { 10434 // This package, under its official name, already exists 10435 // on the device; we should replace it. 10436 replace = true; 10437 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10438 } 10439 } 10440 PackageSetting ps = mSettings.mPackages.get(pkgName); 10441 if (ps != null) { 10442 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10443 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10444 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10445 systemApp = (ps.pkg.applicationInfo.flags & 10446 ApplicationInfo.FLAG_SYSTEM) != 0; 10447 } 10448 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10449 } 10450 } 10451 10452 if (systemApp && onSd) { 10453 // Disable updates to system apps on sdcard 10454 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 10455 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10456 return; 10457 } 10458 10459 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 10460 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10461 return; 10462 } 10463 // Set application objects path explicitly after the rename 10464 pkg.codePath = args.getCodePath(); 10465 pkg.applicationInfo.sourceDir = args.getCodePath(); 10466 pkg.applicationInfo.publicSourceDir = args.getResourcePath(); 10467 pkg.applicationInfo.splitSourceDirs = args.getSplitCodePaths(); 10468 pkg.applicationInfo.splitPublicSourceDirs = deriveSplitResPaths( 10469 pkg.applicationInfo.splitSourceDirs); 10470 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 10471 if (replace) { 10472 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10473 installerPackageName, res, args.abiOverride); 10474 } else { 10475 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10476 installerPackageName, res, args.abiOverride); 10477 } 10478 synchronized (mPackages) { 10479 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10480 if (ps != null) { 10481 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10482 } 10483 } 10484 } 10485 10486 private static boolean isForwardLocked(PackageParser.Package pkg) { 10487 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10488 } 10489 10490 10491 private boolean isForwardLocked(PackageSetting ps) { 10492 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10493 } 10494 10495 private static boolean isExternal(PackageParser.Package pkg) { 10496 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10497 } 10498 10499 private static boolean isExternal(PackageSetting ps) { 10500 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10501 } 10502 10503 private static boolean isSystemApp(PackageParser.Package pkg) { 10504 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10505 } 10506 10507 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10508 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10509 } 10510 10511 private static boolean isSystemApp(ApplicationInfo info) { 10512 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10513 } 10514 10515 private static boolean isSystemApp(PackageSetting ps) { 10516 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10517 } 10518 10519 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10520 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10521 } 10522 10523 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10524 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10525 } 10526 10527 private int packageFlagsToInstallFlags(PackageSetting ps) { 10528 int installFlags = 0; 10529 if (isExternal(ps)) { 10530 installFlags |= PackageManager.INSTALL_EXTERNAL; 10531 } 10532 if (isForwardLocked(ps)) { 10533 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10534 } 10535 return installFlags; 10536 } 10537 10538 private void deleteTempPackageFiles() { 10539 final FilenameFilter filter = new FilenameFilter() { 10540 public boolean accept(File dir, String name) { 10541 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10542 } 10543 }; 10544 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 10545 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 10546 } 10547 10548 private static final void deleteTempPackageFilesInDirectory(File directory, 10549 FilenameFilter filter) { 10550 final String[] tmpFilesList = directory.list(filter); 10551 if (tmpFilesList == null) { 10552 return; 10553 } 10554 for (int i = 0; i < tmpFilesList.length; i++) { 10555 final File tmpFile = new File(directory, tmpFilesList[i]); 10556 tmpFile.delete(); 10557 } 10558 } 10559 10560 private File createTempPackageFile(File installDir) { 10561 File tmpPackageFile; 10562 try { 10563 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 10564 } catch (IOException e) { 10565 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 10566 return null; 10567 } 10568 try { 10569 FileUtils.setPermissions( 10570 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 10571 -1, -1); 10572 if (!SELinux.restorecon(tmpPackageFile)) { 10573 return null; 10574 } 10575 } catch (IOException e) { 10576 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 10577 return null; 10578 } 10579 return tmpPackageFile; 10580 } 10581 10582 @Override 10583 public void deletePackageAsUser(final String packageName, 10584 final IPackageDeleteObserver observer, 10585 final int userId, final int flags) { 10586 mContext.enforceCallingOrSelfPermission( 10587 android.Manifest.permission.DELETE_PACKAGES, null); 10588 final int uid = Binder.getCallingUid(); 10589 if (UserHandle.getUserId(uid) != userId) { 10590 mContext.enforceCallingPermission( 10591 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10592 "deletePackage for user " + userId); 10593 } 10594 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10595 try { 10596 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10597 } catch (RemoteException re) { 10598 } 10599 return; 10600 } 10601 10602 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10603 // Queue up an async operation since the package deletion may take a little while. 10604 mHandler.post(new Runnable() { 10605 public void run() { 10606 mHandler.removeCallbacks(this); 10607 final int returnCode = deletePackageX(packageName, userId, flags); 10608 if (observer != null) { 10609 try { 10610 observer.packageDeleted(packageName, returnCode); 10611 } catch (RemoteException e) { 10612 Log.i(TAG, "Observer no longer exists."); 10613 } //end catch 10614 } //end if 10615 } //end run 10616 }); 10617 } 10618 10619 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10620 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10621 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10622 try { 10623 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10624 || dpm.isDeviceOwner(packageName))) { 10625 return true; 10626 } 10627 } catch (RemoteException e) { 10628 } 10629 return false; 10630 } 10631 10632 /** 10633 * This method is an internal method that could be get invoked either 10634 * to delete an installed package or to clean up a failed installation. 10635 * After deleting an installed package, a broadcast is sent to notify any 10636 * listeners that the package has been installed. For cleaning up a failed 10637 * installation, the broadcast is not necessary since the package's 10638 * installation wouldn't have sent the initial broadcast either 10639 * The key steps in deleting a package are 10640 * deleting the package information in internal structures like mPackages, 10641 * deleting the packages base directories through installd 10642 * updating mSettings to reflect current status 10643 * persisting settings for later use 10644 * sending a broadcast if necessary 10645 */ 10646 private int deletePackageX(String packageName, int userId, int flags) { 10647 final PackageRemovedInfo info = new PackageRemovedInfo(); 10648 final boolean res; 10649 10650 if (isPackageDeviceAdmin(packageName, userId)) { 10651 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10652 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10653 } 10654 10655 boolean removedForAllUsers = false; 10656 boolean systemUpdate = false; 10657 10658 // for the uninstall-updates case and restricted profiles, remember the per- 10659 // userhandle installed state 10660 int[] allUsers; 10661 boolean[] perUserInstalled; 10662 synchronized (mPackages) { 10663 PackageSetting ps = mSettings.mPackages.get(packageName); 10664 allUsers = sUserManager.getUserIds(); 10665 perUserInstalled = new boolean[allUsers.length]; 10666 for (int i = 0; i < allUsers.length; i++) { 10667 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10668 } 10669 } 10670 10671 synchronized (mInstallLock) { 10672 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10673 res = deletePackageLI(packageName, 10674 (flags & PackageManager.DELETE_ALL_USERS) != 0 10675 ? UserHandle.ALL : new UserHandle(userId), 10676 true, allUsers, perUserInstalled, 10677 flags | REMOVE_CHATTY, info, true); 10678 systemUpdate = info.isRemovedPackageSystemUpdate; 10679 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10680 removedForAllUsers = true; 10681 } 10682 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10683 + " removedForAllUsers=" + removedForAllUsers); 10684 } 10685 10686 if (res) { 10687 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10688 10689 // If the removed package was a system update, the old system package 10690 // was re-enabled; we need to broadcast this information 10691 if (systemUpdate) { 10692 Bundle extras = new Bundle(1); 10693 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10694 ? info.removedAppId : info.uid); 10695 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10696 10697 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10698 extras, null, null, null); 10699 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10700 extras, null, null, null); 10701 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10702 null, packageName, null, null); 10703 } 10704 } 10705 // Force a gc here. 10706 Runtime.getRuntime().gc(); 10707 // Delete the resources here after sending the broadcast to let 10708 // other processes clean up before deleting resources. 10709 if (info.args != null) { 10710 synchronized (mInstallLock) { 10711 info.args.doPostDeleteLI(true); 10712 } 10713 } 10714 10715 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10716 } 10717 10718 static class PackageRemovedInfo { 10719 String removedPackage; 10720 int uid = -1; 10721 int removedAppId = -1; 10722 int[] removedUsers = null; 10723 boolean isRemovedPackageSystemUpdate = false; 10724 // Clean up resources deleted packages. 10725 InstallArgs args = null; 10726 10727 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10728 Bundle extras = new Bundle(1); 10729 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10730 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10731 if (replacing) { 10732 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10733 } 10734 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10735 if (removedPackage != null) { 10736 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10737 extras, null, null, removedUsers); 10738 if (fullRemove && !replacing) { 10739 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10740 extras, null, null, removedUsers); 10741 } 10742 } 10743 if (removedAppId >= 0) { 10744 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10745 removedUsers); 10746 } 10747 } 10748 } 10749 10750 /* 10751 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10752 * flag is not set, the data directory is removed as well. 10753 * make sure this flag is set for partially installed apps. If not its meaningless to 10754 * delete a partially installed application. 10755 */ 10756 private void removePackageDataLI(PackageSetting ps, 10757 int[] allUserHandles, boolean[] perUserInstalled, 10758 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10759 String packageName = ps.name; 10760 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10761 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10762 // Retrieve object to delete permissions for shared user later on 10763 final PackageSetting deletedPs; 10764 // reader 10765 synchronized (mPackages) { 10766 deletedPs = mSettings.mPackages.get(packageName); 10767 if (outInfo != null) { 10768 outInfo.removedPackage = packageName; 10769 outInfo.removedUsers = deletedPs != null 10770 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10771 : null; 10772 } 10773 } 10774 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10775 removeDataDirsLI(packageName); 10776 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10777 } 10778 // writer 10779 synchronized (mPackages) { 10780 if (deletedPs != null) { 10781 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10782 if (outInfo != null) { 10783 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10784 } 10785 if (deletedPs != null) { 10786 updatePermissionsLPw(deletedPs.name, null, 0); 10787 if (deletedPs.sharedUser != null) { 10788 // remove permissions associated with package 10789 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10790 } 10791 } 10792 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10793 } 10794 // make sure to preserve per-user disabled state if this removal was just 10795 // a downgrade of a system app to the factory package 10796 if (allUserHandles != null && perUserInstalled != null) { 10797 if (DEBUG_REMOVE) { 10798 Slog.d(TAG, "Propagating install state across downgrade"); 10799 } 10800 for (int i = 0; i < allUserHandles.length; i++) { 10801 if (DEBUG_REMOVE) { 10802 Slog.d(TAG, " user " + allUserHandles[i] 10803 + " => " + perUserInstalled[i]); 10804 } 10805 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10806 } 10807 } 10808 } 10809 // can downgrade to reader 10810 if (writeSettings) { 10811 // Save settings now 10812 mSettings.writeLPr(); 10813 } 10814 } 10815 if (outInfo != null) { 10816 // A user ID was deleted here. Go through all users and remove it 10817 // from KeyStore. 10818 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10819 } 10820 } 10821 10822 static boolean locationIsPrivileged(File path) { 10823 try { 10824 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10825 .getCanonicalPath(); 10826 return path.getCanonicalPath().startsWith(privilegedAppDir); 10827 } catch (IOException e) { 10828 Slog.e(TAG, "Unable to access code path " + path); 10829 } 10830 return false; 10831 } 10832 10833 /* 10834 * Tries to delete system package. 10835 */ 10836 private boolean deleteSystemPackageLI(PackageSetting newPs, 10837 int[] allUserHandles, boolean[] perUserInstalled, 10838 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10839 final boolean applyUserRestrictions 10840 = (allUserHandles != null) && (perUserInstalled != null); 10841 PackageSetting disabledPs = null; 10842 // Confirm if the system package has been updated 10843 // An updated system app can be deleted. This will also have to restore 10844 // the system pkg from system partition 10845 // reader 10846 synchronized (mPackages) { 10847 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10848 } 10849 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10850 + " disabledPs=" + disabledPs); 10851 if (disabledPs == null) { 10852 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10853 return false; 10854 } else if (DEBUG_REMOVE) { 10855 Slog.d(TAG, "Deleting system pkg from data partition"); 10856 } 10857 if (DEBUG_REMOVE) { 10858 if (applyUserRestrictions) { 10859 Slog.d(TAG, "Remembering install states:"); 10860 for (int i = 0; i < allUserHandles.length; i++) { 10861 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10862 } 10863 } 10864 } 10865 // Delete the updated package 10866 outInfo.isRemovedPackageSystemUpdate = true; 10867 if (disabledPs.versionCode < newPs.versionCode) { 10868 // Delete data for downgrades 10869 flags &= ~PackageManager.DELETE_KEEP_DATA; 10870 } else { 10871 // Preserve data by setting flag 10872 flags |= PackageManager.DELETE_KEEP_DATA; 10873 } 10874 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10875 allUserHandles, perUserInstalled, outInfo, writeSettings); 10876 if (!ret) { 10877 return false; 10878 } 10879 // writer 10880 synchronized (mPackages) { 10881 // Reinstate the old system package 10882 mSettings.enableSystemPackageLPw(newPs.name); 10883 // Remove any native libraries from the upgraded package. 10884 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 10885 } 10886 // Install the system package 10887 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10888 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10889 if (locationIsPrivileged(disabledPs.codePath)) { 10890 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10891 } 10892 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10893 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null); 10894 10895 if (newPkg == null) { 10896 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10897 + " with error:" + mLastScanError); 10898 return false; 10899 } 10900 // writer 10901 synchronized (mPackages) { 10902 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10903 setInternalAppNativeLibraryPath(newPkg, ps); 10904 updatePermissionsLPw(newPkg.packageName, newPkg, 10905 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10906 if (applyUserRestrictions) { 10907 if (DEBUG_REMOVE) { 10908 Slog.d(TAG, "Propagating install state across reinstall"); 10909 } 10910 for (int i = 0; i < allUserHandles.length; i++) { 10911 if (DEBUG_REMOVE) { 10912 Slog.d(TAG, " user " + allUserHandles[i] 10913 + " => " + perUserInstalled[i]); 10914 } 10915 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10916 } 10917 // Regardless of writeSettings we need to ensure that this restriction 10918 // state propagation is persisted 10919 mSettings.writeAllUsersPackageRestrictionsLPr(); 10920 } 10921 // can downgrade to reader here 10922 if (writeSettings) { 10923 mSettings.writeLPr(); 10924 } 10925 } 10926 return true; 10927 } 10928 10929 private boolean deleteInstalledPackageLI(PackageSetting ps, 10930 boolean deleteCodeAndResources, int flags, 10931 int[] allUserHandles, boolean[] perUserInstalled, 10932 PackageRemovedInfo outInfo, boolean writeSettings) { 10933 if (outInfo != null) { 10934 outInfo.uid = ps.appId; 10935 } 10936 10937 // Delete package data from internal structures and also remove data if flag is set 10938 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10939 10940 // Delete application code and resources 10941 if (deleteCodeAndResources && (outInfo != null)) { 10942 outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString, 10943 ps.resourcePathString, ps.nativeLibraryPathString, 10944 getAppInstructionSetFromSettings(ps)); 10945 } 10946 return true; 10947 } 10948 10949 /* 10950 * This method handles package deletion in general 10951 */ 10952 private boolean deletePackageLI(String packageName, UserHandle user, 10953 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10954 int flags, PackageRemovedInfo outInfo, 10955 boolean writeSettings) { 10956 if (packageName == null) { 10957 Slog.w(TAG, "Attempt to delete null packageName."); 10958 return false; 10959 } 10960 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10961 PackageSetting ps; 10962 boolean dataOnly = false; 10963 int removeUser = -1; 10964 int appId = -1; 10965 synchronized (mPackages) { 10966 ps = mSettings.mPackages.get(packageName); 10967 if (ps == null) { 10968 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10969 return false; 10970 } 10971 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10972 && user.getIdentifier() != UserHandle.USER_ALL) { 10973 // The caller is asking that the package only be deleted for a single 10974 // user. To do this, we just mark its uninstalled state and delete 10975 // its data. If this is a system app, we only allow this to happen if 10976 // they have set the special DELETE_SYSTEM_APP which requests different 10977 // semantics than normal for uninstalling system apps. 10978 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10979 ps.setUserState(user.getIdentifier(), 10980 COMPONENT_ENABLED_STATE_DEFAULT, 10981 false, //installed 10982 true, //stopped 10983 true, //notLaunched 10984 false, //blocked 10985 null, null, null); 10986 if (!isSystemApp(ps)) { 10987 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10988 // Other user still have this package installed, so all 10989 // we need to do is clear this user's data and save that 10990 // it is uninstalled. 10991 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10992 removeUser = user.getIdentifier(); 10993 appId = ps.appId; 10994 mSettings.writePackageRestrictionsLPr(removeUser); 10995 } else { 10996 // We need to set it back to 'installed' so the uninstall 10997 // broadcasts will be sent correctly. 10998 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10999 ps.setInstalled(true, user.getIdentifier()); 11000 } 11001 } else { 11002 // This is a system app, so we assume that the 11003 // other users still have this package installed, so all 11004 // we need to do is clear this user's data and save that 11005 // it is uninstalled. 11006 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11007 removeUser = user.getIdentifier(); 11008 appId = ps.appId; 11009 mSettings.writePackageRestrictionsLPr(removeUser); 11010 } 11011 } 11012 } 11013 11014 if (removeUser >= 0) { 11015 // From above, we determined that we are deleting this only 11016 // for a single user. Continue the work here. 11017 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11018 if (outInfo != null) { 11019 outInfo.removedPackage = packageName; 11020 outInfo.removedAppId = appId; 11021 outInfo.removedUsers = new int[] {removeUser}; 11022 } 11023 mInstaller.clearUserData(packageName, removeUser); 11024 removeKeystoreDataIfNeeded(removeUser, appId); 11025 schedulePackageCleaning(packageName, removeUser, false); 11026 return true; 11027 } 11028 11029 if (dataOnly) { 11030 // Delete application data first 11031 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11032 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11033 return true; 11034 } 11035 11036 boolean ret = false; 11037 mSettings.mKeySetManager.removeAppKeySetData(packageName); 11038 if (isSystemApp(ps)) { 11039 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11040 // When an updated system application is deleted we delete the existing resources as well and 11041 // fall back to existing code in system partition 11042 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11043 flags, outInfo, writeSettings); 11044 } else { 11045 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11046 // Kill application pre-emptively especially for apps on sd. 11047 killApplication(packageName, ps.appId, "uninstall pkg"); 11048 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11049 allUserHandles, perUserInstalled, 11050 outInfo, writeSettings); 11051 } 11052 11053 return ret; 11054 } 11055 11056 private final class ClearStorageConnection implements ServiceConnection { 11057 IMediaContainerService mContainerService; 11058 11059 @Override 11060 public void onServiceConnected(ComponentName name, IBinder service) { 11061 synchronized (this) { 11062 mContainerService = IMediaContainerService.Stub.asInterface(service); 11063 notifyAll(); 11064 } 11065 } 11066 11067 @Override 11068 public void onServiceDisconnected(ComponentName name) { 11069 } 11070 } 11071 11072 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11073 final boolean mounted; 11074 if (Environment.isExternalStorageEmulated()) { 11075 mounted = true; 11076 } else { 11077 final String status = Environment.getExternalStorageState(); 11078 11079 mounted = status.equals(Environment.MEDIA_MOUNTED) 11080 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11081 } 11082 11083 if (!mounted) { 11084 return; 11085 } 11086 11087 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11088 int[] users; 11089 if (userId == UserHandle.USER_ALL) { 11090 users = sUserManager.getUserIds(); 11091 } else { 11092 users = new int[] { userId }; 11093 } 11094 final ClearStorageConnection conn = new ClearStorageConnection(); 11095 if (mContext.bindServiceAsUser( 11096 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11097 try { 11098 for (int curUser : users) { 11099 long timeout = SystemClock.uptimeMillis() + 5000; 11100 synchronized (conn) { 11101 long now = SystemClock.uptimeMillis(); 11102 while (conn.mContainerService == null && now < timeout) { 11103 try { 11104 conn.wait(timeout - now); 11105 } catch (InterruptedException e) { 11106 } 11107 } 11108 } 11109 if (conn.mContainerService == null) { 11110 return; 11111 } 11112 11113 final UserEnvironment userEnv = new UserEnvironment(curUser); 11114 clearDirectory(conn.mContainerService, 11115 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11116 if (allData) { 11117 clearDirectory(conn.mContainerService, 11118 userEnv.buildExternalStorageAppDataDirs(packageName)); 11119 clearDirectory(conn.mContainerService, 11120 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11121 } 11122 } 11123 } finally { 11124 mContext.unbindService(conn); 11125 } 11126 } 11127 } 11128 11129 @Override 11130 public void clearApplicationUserData(final String packageName, 11131 final IPackageDataObserver observer, final int userId) { 11132 mContext.enforceCallingOrSelfPermission( 11133 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11134 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11135 // Queue up an async operation since the package deletion may take a little while. 11136 mHandler.post(new Runnable() { 11137 public void run() { 11138 mHandler.removeCallbacks(this); 11139 final boolean succeeded; 11140 synchronized (mInstallLock) { 11141 succeeded = clearApplicationUserDataLI(packageName, userId); 11142 } 11143 clearExternalStorageDataSync(packageName, userId, true); 11144 if (succeeded) { 11145 // invoke DeviceStorageMonitor's update method to clear any notifications 11146 DeviceStorageMonitorInternal 11147 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11148 if (dsm != null) { 11149 dsm.checkMemory(); 11150 } 11151 } 11152 if(observer != null) { 11153 try { 11154 observer.onRemoveCompleted(packageName, succeeded); 11155 } catch (RemoteException e) { 11156 Log.i(TAG, "Observer no longer exists."); 11157 } 11158 } //end if observer 11159 } //end run 11160 }); 11161 } 11162 11163 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11164 if (packageName == null) { 11165 Slog.w(TAG, "Attempt to delete null packageName."); 11166 return false; 11167 } 11168 PackageParser.Package p; 11169 boolean dataOnly = false; 11170 final int appId; 11171 synchronized (mPackages) { 11172 p = mPackages.get(packageName); 11173 if (p == null) { 11174 dataOnly = true; 11175 PackageSetting ps = mSettings.mPackages.get(packageName); 11176 if ((ps == null) || (ps.pkg == null)) { 11177 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11178 return false; 11179 } 11180 p = ps.pkg; 11181 } 11182 if (!dataOnly) { 11183 // need to check this only for fully installed applications 11184 if (p == null) { 11185 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11186 return false; 11187 } 11188 final ApplicationInfo applicationInfo = p.applicationInfo; 11189 if (applicationInfo == null) { 11190 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11191 return false; 11192 } 11193 } 11194 if (p != null && p.applicationInfo != null) { 11195 appId = p.applicationInfo.uid; 11196 } else { 11197 appId = -1; 11198 } 11199 } 11200 int retCode = mInstaller.clearUserData(packageName, userId); 11201 if (retCode < 0) { 11202 Slog.w(TAG, "Couldn't remove cache files for package: " 11203 + packageName); 11204 return false; 11205 } 11206 removeKeystoreDataIfNeeded(userId, appId); 11207 return true; 11208 } 11209 11210 /** 11211 * Remove entries from the keystore daemon. Will only remove it if the 11212 * {@code appId} is valid. 11213 */ 11214 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11215 if (appId < 0) { 11216 return; 11217 } 11218 11219 final KeyStore keyStore = KeyStore.getInstance(); 11220 if (keyStore != null) { 11221 if (userId == UserHandle.USER_ALL) { 11222 for (final int individual : sUserManager.getUserIds()) { 11223 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11224 } 11225 } else { 11226 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11227 } 11228 } else { 11229 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11230 } 11231 } 11232 11233 @Override 11234 public void deleteApplicationCacheFiles(final String packageName, 11235 final IPackageDataObserver observer) { 11236 mContext.enforceCallingOrSelfPermission( 11237 android.Manifest.permission.DELETE_CACHE_FILES, null); 11238 // Queue up an async operation since the package deletion may take a little while. 11239 final int userId = UserHandle.getCallingUserId(); 11240 mHandler.post(new Runnable() { 11241 public void run() { 11242 mHandler.removeCallbacks(this); 11243 final boolean succeded; 11244 synchronized (mInstallLock) { 11245 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11246 } 11247 clearExternalStorageDataSync(packageName, userId, false); 11248 if(observer != null) { 11249 try { 11250 observer.onRemoveCompleted(packageName, succeded); 11251 } catch (RemoteException e) { 11252 Log.i(TAG, "Observer no longer exists."); 11253 } 11254 } //end if observer 11255 } //end run 11256 }); 11257 } 11258 11259 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11260 if (packageName == null) { 11261 Slog.w(TAG, "Attempt to delete null packageName."); 11262 return false; 11263 } 11264 PackageParser.Package p; 11265 synchronized (mPackages) { 11266 p = mPackages.get(packageName); 11267 } 11268 if (p == null) { 11269 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11270 return false; 11271 } 11272 final ApplicationInfo applicationInfo = p.applicationInfo; 11273 if (applicationInfo == null) { 11274 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11275 return false; 11276 } 11277 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11278 if (retCode < 0) { 11279 Slog.w(TAG, "Couldn't remove cache files for package: " 11280 + packageName + " u" + userId); 11281 return false; 11282 } 11283 return true; 11284 } 11285 11286 @Override 11287 public void getPackageSizeInfo(final String packageName, int userHandle, 11288 final IPackageStatsObserver observer) { 11289 mContext.enforceCallingOrSelfPermission( 11290 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11291 if (packageName == null) { 11292 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11293 } 11294 11295 PackageStats stats = new PackageStats(packageName, userHandle); 11296 11297 /* 11298 * Queue up an async operation since the package measurement may take a 11299 * little while. 11300 */ 11301 Message msg = mHandler.obtainMessage(INIT_COPY); 11302 msg.obj = new MeasureParams(stats, observer); 11303 mHandler.sendMessage(msg); 11304 } 11305 11306 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11307 PackageStats pStats) { 11308 if (packageName == null) { 11309 Slog.w(TAG, "Attempt to get size of null packageName."); 11310 return false; 11311 } 11312 PackageParser.Package p; 11313 boolean dataOnly = false; 11314 String libDirPath = null; 11315 String asecPath = null; 11316 PackageSetting ps = null; 11317 synchronized (mPackages) { 11318 p = mPackages.get(packageName); 11319 ps = mSettings.mPackages.get(packageName); 11320 if(p == null) { 11321 dataOnly = true; 11322 if((ps == null) || (ps.pkg == null)) { 11323 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11324 return false; 11325 } 11326 p = ps.pkg; 11327 } 11328 if (ps != null) { 11329 libDirPath = ps.nativeLibraryPathString; 11330 } 11331 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11332 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 11333 if (secureContainerId != null) { 11334 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11335 } 11336 } 11337 } 11338 String publicSrcDir = null; 11339 if(!dataOnly) { 11340 final ApplicationInfo applicationInfo = p.applicationInfo; 11341 if (applicationInfo == null) { 11342 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11343 return false; 11344 } 11345 if (isForwardLocked(p)) { 11346 publicSrcDir = applicationInfo.publicSourceDir; 11347 } 11348 } 11349 int res = mInstaller.getSizeInfo(packageName, userHandle, p.codePath, libDirPath, 11350 publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps), 11351 pStats); 11352 if (res < 0) { 11353 return false; 11354 } 11355 11356 // Fix-up for forward-locked applications in ASEC containers. 11357 if (!isExternal(p)) { 11358 pStats.codeSize += pStats.externalCodeSize; 11359 pStats.externalCodeSize = 0L; 11360 } 11361 11362 return true; 11363 } 11364 11365 11366 @Override 11367 public void addPackageToPreferred(String packageName) { 11368 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11369 } 11370 11371 @Override 11372 public void removePackageFromPreferred(String packageName) { 11373 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11374 } 11375 11376 @Override 11377 public List<PackageInfo> getPreferredPackages(int flags) { 11378 return new ArrayList<PackageInfo>(); 11379 } 11380 11381 private int getUidTargetSdkVersionLockedLPr(int uid) { 11382 Object obj = mSettings.getUserIdLPr(uid); 11383 if (obj instanceof SharedUserSetting) { 11384 final SharedUserSetting sus = (SharedUserSetting) obj; 11385 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11386 final Iterator<PackageSetting> it = sus.packages.iterator(); 11387 while (it.hasNext()) { 11388 final PackageSetting ps = it.next(); 11389 if (ps.pkg != null) { 11390 int v = ps.pkg.applicationInfo.targetSdkVersion; 11391 if (v < vers) vers = v; 11392 } 11393 } 11394 return vers; 11395 } else if (obj instanceof PackageSetting) { 11396 final PackageSetting ps = (PackageSetting) obj; 11397 if (ps.pkg != null) { 11398 return ps.pkg.applicationInfo.targetSdkVersion; 11399 } 11400 } 11401 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11402 } 11403 11404 @Override 11405 public void addPreferredActivity(IntentFilter filter, int match, 11406 ComponentName[] set, ComponentName activity, int userId) { 11407 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11408 } 11409 11410 private void addPreferredActivityInternal(IntentFilter filter, int match, 11411 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11412 // writer 11413 int callingUid = Binder.getCallingUid(); 11414 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11415 if (filter.countActions() == 0) { 11416 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11417 return; 11418 } 11419 synchronized (mPackages) { 11420 if (mContext.checkCallingOrSelfPermission( 11421 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11422 != PackageManager.PERMISSION_GRANTED) { 11423 if (getUidTargetSdkVersionLockedLPr(callingUid) 11424 < Build.VERSION_CODES.FROYO) { 11425 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11426 + callingUid); 11427 return; 11428 } 11429 mContext.enforceCallingOrSelfPermission( 11430 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11431 } 11432 11433 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11434 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11435 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11436 new PreferredActivity(filter, match, set, activity, always)); 11437 mSettings.writePackageRestrictionsLPr(userId); 11438 } 11439 } 11440 11441 @Override 11442 public void replacePreferredActivity(IntentFilter filter, int match, 11443 ComponentName[] set, ComponentName activity) { 11444 if (filter.countActions() != 1) { 11445 throw new IllegalArgumentException( 11446 "replacePreferredActivity expects filter to have only 1 action."); 11447 } 11448 if (filter.countDataAuthorities() != 0 11449 || filter.countDataPaths() != 0 11450 || filter.countDataSchemes() > 1 11451 || filter.countDataTypes() != 0) { 11452 throw new IllegalArgumentException( 11453 "replacePreferredActivity expects filter to have no data authorities, " + 11454 "paths, or types; and at most one scheme."); 11455 } 11456 synchronized (mPackages) { 11457 if (mContext.checkCallingOrSelfPermission( 11458 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11459 != PackageManager.PERMISSION_GRANTED) { 11460 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11461 < Build.VERSION_CODES.FROYO) { 11462 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11463 + Binder.getCallingUid()); 11464 return; 11465 } 11466 mContext.enforceCallingOrSelfPermission( 11467 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11468 } 11469 11470 final int callingUserId = UserHandle.getCallingUserId(); 11471 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11472 if (pir != null) { 11473 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11474 if (filter.countDataSchemes() == 1) { 11475 Uri.Builder builder = new Uri.Builder(); 11476 builder.scheme(filter.getDataScheme(0)); 11477 intent.setData(builder.build()); 11478 } 11479 List<PreferredActivity> matches = pir.queryIntent( 11480 intent, null, true, callingUserId); 11481 if (DEBUG_PREFERRED) { 11482 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11483 } 11484 for (int i = 0; i < matches.size(); i++) { 11485 PreferredActivity pa = matches.get(i); 11486 if (DEBUG_PREFERRED) { 11487 Slog.i(TAG, "Removing preferred activity " 11488 + pa.mPref.mComponent + ":"); 11489 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11490 } 11491 pir.removeFilter(pa); 11492 } 11493 } 11494 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11495 } 11496 } 11497 11498 @Override 11499 public void clearPackagePreferredActivities(String packageName) { 11500 final int uid = Binder.getCallingUid(); 11501 // writer 11502 synchronized (mPackages) { 11503 PackageParser.Package pkg = mPackages.get(packageName); 11504 if (pkg == null || pkg.applicationInfo.uid != uid) { 11505 if (mContext.checkCallingOrSelfPermission( 11506 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11507 != PackageManager.PERMISSION_GRANTED) { 11508 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11509 < Build.VERSION_CODES.FROYO) { 11510 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11511 + Binder.getCallingUid()); 11512 return; 11513 } 11514 mContext.enforceCallingOrSelfPermission( 11515 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11516 } 11517 } 11518 11519 int user = UserHandle.getCallingUserId(); 11520 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11521 mSettings.writePackageRestrictionsLPr(user); 11522 scheduleWriteSettingsLocked(); 11523 } 11524 } 11525 } 11526 11527 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11528 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11529 ArrayList<PreferredActivity> removed = null; 11530 boolean changed = false; 11531 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11532 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11533 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11534 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11535 continue; 11536 } 11537 Iterator<PreferredActivity> it = pir.filterIterator(); 11538 while (it.hasNext()) { 11539 PreferredActivity pa = it.next(); 11540 // Mark entry for removal only if it matches the package name 11541 // and the entry is of type "always". 11542 if (packageName == null || 11543 (pa.mPref.mComponent.getPackageName().equals(packageName) 11544 && pa.mPref.mAlways)) { 11545 if (removed == null) { 11546 removed = new ArrayList<PreferredActivity>(); 11547 } 11548 removed.add(pa); 11549 } 11550 } 11551 if (removed != null) { 11552 for (int j=0; j<removed.size(); j++) { 11553 PreferredActivity pa = removed.get(j); 11554 pir.removeFilter(pa); 11555 } 11556 changed = true; 11557 } 11558 } 11559 return changed; 11560 } 11561 11562 @Override 11563 public void resetPreferredActivities(int userId) { 11564 mContext.enforceCallingOrSelfPermission( 11565 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11566 // writer 11567 synchronized (mPackages) { 11568 int user = UserHandle.getCallingUserId(); 11569 clearPackagePreferredActivitiesLPw(null, user); 11570 mSettings.readDefaultPreferredAppsLPw(this, user); 11571 mSettings.writePackageRestrictionsLPr(user); 11572 scheduleWriteSettingsLocked(); 11573 } 11574 } 11575 11576 @Override 11577 public int getPreferredActivities(List<IntentFilter> outFilters, 11578 List<ComponentName> outActivities, String packageName) { 11579 11580 int num = 0; 11581 final int userId = UserHandle.getCallingUserId(); 11582 // reader 11583 synchronized (mPackages) { 11584 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11585 if (pir != null) { 11586 final Iterator<PreferredActivity> it = pir.filterIterator(); 11587 while (it.hasNext()) { 11588 final PreferredActivity pa = it.next(); 11589 if (packageName == null 11590 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11591 && pa.mPref.mAlways)) { 11592 if (outFilters != null) { 11593 outFilters.add(new IntentFilter(pa)); 11594 } 11595 if (outActivities != null) { 11596 outActivities.add(pa.mPref.mComponent); 11597 } 11598 } 11599 } 11600 } 11601 } 11602 11603 return num; 11604 } 11605 11606 @Override 11607 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11608 int userId) { 11609 int callingUid = Binder.getCallingUid(); 11610 if (callingUid != Process.SYSTEM_UID) { 11611 throw new SecurityException( 11612 "addPersistentPreferredActivity can only be run by the system"); 11613 } 11614 if (filter.countActions() == 0) { 11615 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11616 return; 11617 } 11618 synchronized (mPackages) { 11619 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11620 " :"); 11621 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11622 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11623 new PersistentPreferredActivity(filter, activity)); 11624 mSettings.writePackageRestrictionsLPr(userId); 11625 } 11626 } 11627 11628 @Override 11629 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11630 int callingUid = Binder.getCallingUid(); 11631 if (callingUid != Process.SYSTEM_UID) { 11632 throw new SecurityException( 11633 "clearPackagePersistentPreferredActivities can only be run by the system"); 11634 } 11635 ArrayList<PersistentPreferredActivity> removed = null; 11636 boolean changed = false; 11637 synchronized (mPackages) { 11638 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11639 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11640 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11641 .valueAt(i); 11642 if (userId != thisUserId) { 11643 continue; 11644 } 11645 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11646 while (it.hasNext()) { 11647 PersistentPreferredActivity ppa = it.next(); 11648 // Mark entry for removal only if it matches the package name. 11649 if (ppa.mComponent.getPackageName().equals(packageName)) { 11650 if (removed == null) { 11651 removed = new ArrayList<PersistentPreferredActivity>(); 11652 } 11653 removed.add(ppa); 11654 } 11655 } 11656 if (removed != null) { 11657 for (int j=0; j<removed.size(); j++) { 11658 PersistentPreferredActivity ppa = removed.get(j); 11659 ppir.removeFilter(ppa); 11660 } 11661 changed = true; 11662 } 11663 } 11664 11665 if (changed) { 11666 mSettings.writePackageRestrictionsLPr(userId); 11667 } 11668 } 11669 } 11670 11671 @Override 11672 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11673 int targetUserId, int flags) { 11674 mContext.enforceCallingOrSelfPermission( 11675 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11676 if (intentFilter.countActions() == 0) { 11677 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11678 return; 11679 } 11680 synchronized (mPackages) { 11681 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11682 targetUserId, flags); 11683 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11684 mSettings.writePackageRestrictionsLPr(sourceUserId); 11685 } 11686 } 11687 11688 public void addCrossProfileIntentsForPackage(String packageName, 11689 int sourceUserId, int targetUserId) { 11690 mContext.enforceCallingOrSelfPermission( 11691 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11692 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11693 mSettings.writePackageRestrictionsLPr(sourceUserId); 11694 } 11695 11696 public void removeCrossProfileIntentsForPackage(String packageName, 11697 int sourceUserId, int targetUserId) { 11698 mContext.enforceCallingOrSelfPermission( 11699 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11700 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11701 mSettings.writePackageRestrictionsLPr(sourceUserId); 11702 } 11703 11704 @Override 11705 public void clearCrossProfileIntentFilters(int sourceUserId) { 11706 mContext.enforceCallingOrSelfPermission( 11707 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11708 synchronized (mPackages) { 11709 CrossProfileIntentResolver resolver = 11710 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11711 HashSet<CrossProfileIntentFilter> set = 11712 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11713 for (CrossProfileIntentFilter filter : set) { 11714 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11715 resolver.removeFilter(filter); 11716 } 11717 } 11718 mSettings.writePackageRestrictionsLPr(sourceUserId); 11719 } 11720 } 11721 11722 @Override 11723 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11724 Intent intent = new Intent(Intent.ACTION_MAIN); 11725 intent.addCategory(Intent.CATEGORY_HOME); 11726 11727 final int callingUserId = UserHandle.getCallingUserId(); 11728 List<ResolveInfo> list = queryIntentActivities(intent, null, 11729 PackageManager.GET_META_DATA, callingUserId); 11730 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11731 true, false, false, callingUserId); 11732 11733 allHomeCandidates.clear(); 11734 if (list != null) { 11735 for (ResolveInfo ri : list) { 11736 allHomeCandidates.add(ri); 11737 } 11738 } 11739 return (preferred == null || preferred.activityInfo == null) 11740 ? null 11741 : new ComponentName(preferred.activityInfo.packageName, 11742 preferred.activityInfo.name); 11743 } 11744 11745 @Override 11746 public void setApplicationEnabledSetting(String appPackageName, 11747 int newState, int flags, int userId, String callingPackage) { 11748 if (!sUserManager.exists(userId)) return; 11749 if (callingPackage == null) { 11750 callingPackage = Integer.toString(Binder.getCallingUid()); 11751 } 11752 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11753 } 11754 11755 @Override 11756 public void setComponentEnabledSetting(ComponentName componentName, 11757 int newState, int flags, int userId) { 11758 if (!sUserManager.exists(userId)) return; 11759 setEnabledSetting(componentName.getPackageName(), 11760 componentName.getClassName(), newState, flags, userId, null); 11761 } 11762 11763 private void setEnabledSetting(final String packageName, String className, int newState, 11764 final int flags, int userId, String callingPackage) { 11765 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11766 || newState == COMPONENT_ENABLED_STATE_ENABLED 11767 || newState == COMPONENT_ENABLED_STATE_DISABLED 11768 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11769 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11770 throw new IllegalArgumentException("Invalid new component state: " 11771 + newState); 11772 } 11773 PackageSetting pkgSetting; 11774 final int uid = Binder.getCallingUid(); 11775 final int permission = mContext.checkCallingOrSelfPermission( 11776 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11777 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11778 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11779 boolean sendNow = false; 11780 boolean isApp = (className == null); 11781 String componentName = isApp ? packageName : className; 11782 int packageUid = -1; 11783 ArrayList<String> components; 11784 11785 // writer 11786 synchronized (mPackages) { 11787 pkgSetting = mSettings.mPackages.get(packageName); 11788 if (pkgSetting == null) { 11789 if (className == null) { 11790 throw new IllegalArgumentException( 11791 "Unknown package: " + packageName); 11792 } 11793 throw new IllegalArgumentException( 11794 "Unknown component: " + packageName 11795 + "/" + className); 11796 } 11797 // Allow root and verify that userId is not being specified by a different user 11798 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11799 throw new SecurityException( 11800 "Permission Denial: attempt to change component state from pid=" 11801 + Binder.getCallingPid() 11802 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11803 } 11804 if (className == null) { 11805 // We're dealing with an application/package level state change 11806 if (pkgSetting.getEnabled(userId) == newState) { 11807 // Nothing to do 11808 return; 11809 } 11810 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11811 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11812 // Don't care about who enables an app. 11813 callingPackage = null; 11814 } 11815 pkgSetting.setEnabled(newState, userId, callingPackage); 11816 // pkgSetting.pkg.mSetEnabled = newState; 11817 } else { 11818 // We're dealing with a component level state change 11819 // First, verify that this is a valid class name. 11820 PackageParser.Package pkg = pkgSetting.pkg; 11821 if (pkg == null || !pkg.hasComponentClassName(className)) { 11822 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11823 throw new IllegalArgumentException("Component class " + className 11824 + " does not exist in " + packageName); 11825 } else { 11826 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11827 + className + " does not exist in " + packageName); 11828 } 11829 } 11830 switch (newState) { 11831 case COMPONENT_ENABLED_STATE_ENABLED: 11832 if (!pkgSetting.enableComponentLPw(className, userId)) { 11833 return; 11834 } 11835 break; 11836 case COMPONENT_ENABLED_STATE_DISABLED: 11837 if (!pkgSetting.disableComponentLPw(className, userId)) { 11838 return; 11839 } 11840 break; 11841 case COMPONENT_ENABLED_STATE_DEFAULT: 11842 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11843 return; 11844 } 11845 break; 11846 default: 11847 Slog.e(TAG, "Invalid new component state: " + newState); 11848 return; 11849 } 11850 } 11851 mSettings.writePackageRestrictionsLPr(userId); 11852 components = mPendingBroadcasts.get(userId, packageName); 11853 final boolean newPackage = components == null; 11854 if (newPackage) { 11855 components = new ArrayList<String>(); 11856 } 11857 if (!components.contains(componentName)) { 11858 components.add(componentName); 11859 } 11860 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11861 sendNow = true; 11862 // Purge entry from pending broadcast list if another one exists already 11863 // since we are sending one right away. 11864 mPendingBroadcasts.remove(userId, packageName); 11865 } else { 11866 if (newPackage) { 11867 mPendingBroadcasts.put(userId, packageName, components); 11868 } 11869 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11870 // Schedule a message 11871 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11872 } 11873 } 11874 } 11875 11876 long callingId = Binder.clearCallingIdentity(); 11877 try { 11878 if (sendNow) { 11879 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11880 sendPackageChangedBroadcast(packageName, 11881 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11882 } 11883 } finally { 11884 Binder.restoreCallingIdentity(callingId); 11885 } 11886 } 11887 11888 private void sendPackageChangedBroadcast(String packageName, 11889 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11890 if (DEBUG_INSTALL) 11891 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11892 + componentNames); 11893 Bundle extras = new Bundle(4); 11894 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11895 String nameList[] = new String[componentNames.size()]; 11896 componentNames.toArray(nameList); 11897 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11898 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11899 extras.putInt(Intent.EXTRA_UID, packageUid); 11900 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11901 new int[] {UserHandle.getUserId(packageUid)}); 11902 } 11903 11904 @Override 11905 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11906 if (!sUserManager.exists(userId)) return; 11907 final int uid = Binder.getCallingUid(); 11908 final int permission = mContext.checkCallingOrSelfPermission( 11909 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11910 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11911 enforceCrossUserPermission(uid, userId, true, "stop package"); 11912 // writer 11913 synchronized (mPackages) { 11914 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11915 uid, userId)) { 11916 scheduleWritePackageRestrictionsLocked(userId); 11917 } 11918 } 11919 } 11920 11921 @Override 11922 public String getInstallerPackageName(String packageName) { 11923 // reader 11924 synchronized (mPackages) { 11925 return mSettings.getInstallerPackageNameLPr(packageName); 11926 } 11927 } 11928 11929 @Override 11930 public int getApplicationEnabledSetting(String packageName, int userId) { 11931 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11932 int uid = Binder.getCallingUid(); 11933 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11934 // reader 11935 synchronized (mPackages) { 11936 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11937 } 11938 } 11939 11940 @Override 11941 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11942 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11943 int uid = Binder.getCallingUid(); 11944 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11945 // reader 11946 synchronized (mPackages) { 11947 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11948 } 11949 } 11950 11951 @Override 11952 public void enterSafeMode() { 11953 enforceSystemOrRoot("Only the system can request entering safe mode"); 11954 11955 if (!mSystemReady) { 11956 mSafeMode = true; 11957 } 11958 } 11959 11960 @Override 11961 public void systemReady() { 11962 mSystemReady = true; 11963 11964 // Read the compatibilty setting when the system is ready. 11965 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11966 mContext.getContentResolver(), 11967 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11968 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11969 if (DEBUG_SETTINGS) { 11970 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11971 } 11972 11973 synchronized (mPackages) { 11974 // Verify that all of the preferred activity components actually 11975 // exist. It is possible for applications to be updated and at 11976 // that point remove a previously declared activity component that 11977 // had been set as a preferred activity. We try to clean this up 11978 // the next time we encounter that preferred activity, but it is 11979 // possible for the user flow to never be able to return to that 11980 // situation so here we do a sanity check to make sure we haven't 11981 // left any junk around. 11982 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11983 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11984 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11985 removed.clear(); 11986 for (PreferredActivity pa : pir.filterSet()) { 11987 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11988 removed.add(pa); 11989 } 11990 } 11991 if (removed.size() > 0) { 11992 for (int r=0; r<removed.size(); r++) { 11993 PreferredActivity pa = removed.get(r); 11994 Slog.w(TAG, "Removing dangling preferred activity: " 11995 + pa.mPref.mComponent); 11996 pir.removeFilter(pa); 11997 } 11998 mSettings.writePackageRestrictionsLPr( 11999 mSettings.mPreferredActivities.keyAt(i)); 12000 } 12001 } 12002 } 12003 sUserManager.systemReady(); 12004 } 12005 12006 @Override 12007 public boolean isSafeMode() { 12008 return mSafeMode; 12009 } 12010 12011 @Override 12012 public boolean hasSystemUidErrors() { 12013 return mHasSystemUidErrors; 12014 } 12015 12016 static String arrayToString(int[] array) { 12017 StringBuffer buf = new StringBuffer(128); 12018 buf.append('['); 12019 if (array != null) { 12020 for (int i=0; i<array.length; i++) { 12021 if (i > 0) buf.append(", "); 12022 buf.append(array[i]); 12023 } 12024 } 12025 buf.append(']'); 12026 return buf.toString(); 12027 } 12028 12029 static class DumpState { 12030 public static final int DUMP_LIBS = 1 << 0; 12031 12032 public static final int DUMP_FEATURES = 1 << 1; 12033 12034 public static final int DUMP_RESOLVERS = 1 << 2; 12035 12036 public static final int DUMP_PERMISSIONS = 1 << 3; 12037 12038 public static final int DUMP_PACKAGES = 1 << 4; 12039 12040 public static final int DUMP_SHARED_USERS = 1 << 5; 12041 12042 public static final int DUMP_MESSAGES = 1 << 6; 12043 12044 public static final int DUMP_PROVIDERS = 1 << 7; 12045 12046 public static final int DUMP_VERIFIERS = 1 << 8; 12047 12048 public static final int DUMP_PREFERRED = 1 << 9; 12049 12050 public static final int DUMP_PREFERRED_XML = 1 << 10; 12051 12052 public static final int DUMP_KEYSETS = 1 << 11; 12053 12054 public static final int DUMP_VERSION = 1 << 12; 12055 12056 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12057 12058 private int mTypes; 12059 12060 private int mOptions; 12061 12062 private boolean mTitlePrinted; 12063 12064 private SharedUserSetting mSharedUser; 12065 12066 public boolean isDumping(int type) { 12067 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12068 return true; 12069 } 12070 12071 return (mTypes & type) != 0; 12072 } 12073 12074 public void setDump(int type) { 12075 mTypes |= type; 12076 } 12077 12078 public boolean isOptionEnabled(int option) { 12079 return (mOptions & option) != 0; 12080 } 12081 12082 public void setOptionEnabled(int option) { 12083 mOptions |= option; 12084 } 12085 12086 public boolean onTitlePrinted() { 12087 final boolean printed = mTitlePrinted; 12088 mTitlePrinted = true; 12089 return printed; 12090 } 12091 12092 public boolean getTitlePrinted() { 12093 return mTitlePrinted; 12094 } 12095 12096 public void setTitlePrinted(boolean enabled) { 12097 mTitlePrinted = enabled; 12098 } 12099 12100 public SharedUserSetting getSharedUser() { 12101 return mSharedUser; 12102 } 12103 12104 public void setSharedUser(SharedUserSetting user) { 12105 mSharedUser = user; 12106 } 12107 } 12108 12109 @Override 12110 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12111 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12112 != PackageManager.PERMISSION_GRANTED) { 12113 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12114 + Binder.getCallingPid() 12115 + ", uid=" + Binder.getCallingUid() 12116 + " without permission " 12117 + android.Manifest.permission.DUMP); 12118 return; 12119 } 12120 12121 DumpState dumpState = new DumpState(); 12122 boolean fullPreferred = false; 12123 boolean checkin = false; 12124 12125 String packageName = null; 12126 12127 int opti = 0; 12128 while (opti < args.length) { 12129 String opt = args[opti]; 12130 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12131 break; 12132 } 12133 opti++; 12134 if ("-a".equals(opt)) { 12135 // Right now we only know how to print all. 12136 } else if ("-h".equals(opt)) { 12137 pw.println("Package manager dump options:"); 12138 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12139 pw.println(" --checkin: dump for a checkin"); 12140 pw.println(" -f: print details of intent filters"); 12141 pw.println(" -h: print this help"); 12142 pw.println(" cmd may be one of:"); 12143 pw.println(" l[ibraries]: list known shared libraries"); 12144 pw.println(" f[ibraries]: list device features"); 12145 pw.println(" k[eysets]: print known keysets"); 12146 pw.println(" r[esolvers]: dump intent resolvers"); 12147 pw.println(" perm[issions]: dump permissions"); 12148 pw.println(" pref[erred]: print preferred package settings"); 12149 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12150 pw.println(" prov[iders]: dump content providers"); 12151 pw.println(" p[ackages]: dump installed packages"); 12152 pw.println(" s[hared-users]: dump shared user IDs"); 12153 pw.println(" m[essages]: print collected runtime messages"); 12154 pw.println(" v[erifiers]: print package verifier info"); 12155 pw.println(" version: print database version info"); 12156 pw.println(" write: write current settings now"); 12157 pw.println(" <package.name>: info about given package"); 12158 return; 12159 } else if ("--checkin".equals(opt)) { 12160 checkin = true; 12161 } else if ("-f".equals(opt)) { 12162 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12163 } else { 12164 pw.println("Unknown argument: " + opt + "; use -h for help"); 12165 } 12166 } 12167 12168 // Is the caller requesting to dump a particular piece of data? 12169 if (opti < args.length) { 12170 String cmd = args[opti]; 12171 opti++; 12172 // Is this a package name? 12173 if ("android".equals(cmd) || cmd.contains(".")) { 12174 packageName = cmd; 12175 // When dumping a single package, we always dump all of its 12176 // filter information since the amount of data will be reasonable. 12177 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12178 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12179 dumpState.setDump(DumpState.DUMP_LIBS); 12180 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12181 dumpState.setDump(DumpState.DUMP_FEATURES); 12182 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12183 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12184 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12185 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12186 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12187 dumpState.setDump(DumpState.DUMP_PREFERRED); 12188 } else if ("preferred-xml".equals(cmd)) { 12189 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12190 if (opti < args.length && "--full".equals(args[opti])) { 12191 fullPreferred = true; 12192 opti++; 12193 } 12194 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12195 dumpState.setDump(DumpState.DUMP_PACKAGES); 12196 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12197 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12198 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12199 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12200 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12201 dumpState.setDump(DumpState.DUMP_MESSAGES); 12202 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12203 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12204 } else if ("version".equals(cmd)) { 12205 dumpState.setDump(DumpState.DUMP_VERSION); 12206 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12207 dumpState.setDump(DumpState.DUMP_KEYSETS); 12208 } else if ("write".equals(cmd)) { 12209 synchronized (mPackages) { 12210 mSettings.writeLPr(); 12211 pw.println("Settings written."); 12212 return; 12213 } 12214 } 12215 } 12216 12217 if (checkin) { 12218 pw.println("vers,1"); 12219 } 12220 12221 // reader 12222 synchronized (mPackages) { 12223 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12224 if (!checkin) { 12225 if (dumpState.onTitlePrinted()) 12226 pw.println(); 12227 pw.println("Database versions:"); 12228 pw.print(" SDK Version:"); 12229 pw.print(" internal="); 12230 pw.print(mSettings.mInternalSdkPlatform); 12231 pw.print(" external="); 12232 pw.println(mSettings.mExternalSdkPlatform); 12233 pw.print(" DB Version:"); 12234 pw.print(" internal="); 12235 pw.print(mSettings.mInternalDatabaseVersion); 12236 pw.print(" external="); 12237 pw.println(mSettings.mExternalDatabaseVersion); 12238 } 12239 } 12240 12241 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12242 if (!checkin) { 12243 if (dumpState.onTitlePrinted()) 12244 pw.println(); 12245 pw.println("Verifiers:"); 12246 pw.print(" Required: "); 12247 pw.print(mRequiredVerifierPackage); 12248 pw.print(" (uid="); 12249 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12250 pw.println(")"); 12251 } else if (mRequiredVerifierPackage != null) { 12252 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12253 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12254 } 12255 } 12256 12257 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12258 boolean printedHeader = false; 12259 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12260 while (it.hasNext()) { 12261 String name = it.next(); 12262 SharedLibraryEntry ent = mSharedLibraries.get(name); 12263 if (!checkin) { 12264 if (!printedHeader) { 12265 if (dumpState.onTitlePrinted()) 12266 pw.println(); 12267 pw.println("Libraries:"); 12268 printedHeader = true; 12269 } 12270 pw.print(" "); 12271 } else { 12272 pw.print("lib,"); 12273 } 12274 pw.print(name); 12275 if (!checkin) { 12276 pw.print(" -> "); 12277 } 12278 if (ent.path != null) { 12279 if (!checkin) { 12280 pw.print("(jar) "); 12281 pw.print(ent.path); 12282 } else { 12283 pw.print(",jar,"); 12284 pw.print(ent.path); 12285 } 12286 } else { 12287 if (!checkin) { 12288 pw.print("(apk) "); 12289 pw.print(ent.apk); 12290 } else { 12291 pw.print(",apk,"); 12292 pw.print(ent.apk); 12293 } 12294 } 12295 pw.println(); 12296 } 12297 } 12298 12299 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12300 if (dumpState.onTitlePrinted()) 12301 pw.println(); 12302 if (!checkin) { 12303 pw.println("Features:"); 12304 } 12305 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12306 while (it.hasNext()) { 12307 String name = it.next(); 12308 if (!checkin) { 12309 pw.print(" "); 12310 } else { 12311 pw.print("feat,"); 12312 } 12313 pw.println(name); 12314 } 12315 } 12316 12317 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12318 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12319 : "Activity Resolver Table:", " ", packageName, 12320 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12321 dumpState.setTitlePrinted(true); 12322 } 12323 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12324 : "Receiver Resolver Table:", " ", packageName, 12325 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12326 dumpState.setTitlePrinted(true); 12327 } 12328 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12329 : "Service Resolver Table:", " ", packageName, 12330 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12331 dumpState.setTitlePrinted(true); 12332 } 12333 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12334 : "Provider Resolver Table:", " ", packageName, 12335 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12336 dumpState.setTitlePrinted(true); 12337 } 12338 } 12339 12340 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12341 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12342 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12343 int user = mSettings.mPreferredActivities.keyAt(i); 12344 if (pir.dump(pw, 12345 dumpState.getTitlePrinted() 12346 ? "\nPreferred Activities User " + user + ":" 12347 : "Preferred Activities User " + user + ":", " ", 12348 packageName, true)) { 12349 dumpState.setTitlePrinted(true); 12350 } 12351 } 12352 } 12353 12354 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12355 pw.flush(); 12356 FileOutputStream fout = new FileOutputStream(fd); 12357 BufferedOutputStream str = new BufferedOutputStream(fout); 12358 XmlSerializer serializer = new FastXmlSerializer(); 12359 try { 12360 serializer.setOutput(str, "utf-8"); 12361 serializer.startDocument(null, true); 12362 serializer.setFeature( 12363 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12364 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12365 serializer.endDocument(); 12366 serializer.flush(); 12367 } catch (IllegalArgumentException e) { 12368 pw.println("Failed writing: " + e); 12369 } catch (IllegalStateException e) { 12370 pw.println("Failed writing: " + e); 12371 } catch (IOException e) { 12372 pw.println("Failed writing: " + e); 12373 } 12374 } 12375 12376 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12377 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12378 } 12379 12380 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12381 boolean printedSomething = false; 12382 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12383 if (packageName != null && !packageName.equals(p.info.packageName)) { 12384 continue; 12385 } 12386 if (!printedSomething) { 12387 if (dumpState.onTitlePrinted()) 12388 pw.println(); 12389 pw.println("Registered ContentProviders:"); 12390 printedSomething = true; 12391 } 12392 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12393 pw.print(" "); pw.println(p.toString()); 12394 } 12395 printedSomething = false; 12396 for (Map.Entry<String, PackageParser.Provider> entry : 12397 mProvidersByAuthority.entrySet()) { 12398 PackageParser.Provider p = entry.getValue(); 12399 if (packageName != null && !packageName.equals(p.info.packageName)) { 12400 continue; 12401 } 12402 if (!printedSomething) { 12403 if (dumpState.onTitlePrinted()) 12404 pw.println(); 12405 pw.println("ContentProvider Authorities:"); 12406 printedSomething = true; 12407 } 12408 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12409 pw.print(" "); pw.println(p.toString()); 12410 if (p.info != null && p.info.applicationInfo != null) { 12411 final String appInfo = p.info.applicationInfo.toString(); 12412 pw.print(" applicationInfo="); pw.println(appInfo); 12413 } 12414 } 12415 } 12416 12417 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12418 mSettings.mKeySetManager.dump(pw, packageName, dumpState); 12419 } 12420 12421 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12422 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12423 } 12424 12425 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12426 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12427 } 12428 12429 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12430 if (dumpState.onTitlePrinted()) 12431 pw.println(); 12432 mSettings.dumpReadMessagesLPr(pw, dumpState); 12433 12434 pw.println(); 12435 pw.println("Package warning messages:"); 12436 final File fname = getSettingsProblemFile(); 12437 FileInputStream in = null; 12438 try { 12439 in = new FileInputStream(fname); 12440 final int avail = in.available(); 12441 final byte[] data = new byte[avail]; 12442 in.read(data); 12443 pw.print(new String(data)); 12444 } catch (FileNotFoundException e) { 12445 } catch (IOException e) { 12446 } finally { 12447 if (in != null) { 12448 try { 12449 in.close(); 12450 } catch (IOException e) { 12451 } 12452 } 12453 } 12454 } 12455 } 12456 } 12457 12458 // ------- apps on sdcard specific code ------- 12459 static final boolean DEBUG_SD_INSTALL = false; 12460 12461 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12462 12463 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12464 12465 private boolean mMediaMounted = false; 12466 12467 private String getEncryptKey() { 12468 try { 12469 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12470 SD_ENCRYPTION_KEYSTORE_NAME); 12471 if (sdEncKey == null) { 12472 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12473 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12474 if (sdEncKey == null) { 12475 Slog.e(TAG, "Failed to create encryption keys"); 12476 return null; 12477 } 12478 } 12479 return sdEncKey; 12480 } catch (NoSuchAlgorithmException nsae) { 12481 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12482 return null; 12483 } catch (IOException ioe) { 12484 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12485 return null; 12486 } 12487 12488 } 12489 12490 /* package */static String getTempContainerId() { 12491 int tmpIdx = 1; 12492 String list[] = PackageHelper.getSecureContainerList(); 12493 if (list != null) { 12494 for (final String name : list) { 12495 // Ignore null and non-temporary container entries 12496 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12497 continue; 12498 } 12499 12500 String subStr = name.substring(mTempContainerPrefix.length()); 12501 try { 12502 int cid = Integer.parseInt(subStr); 12503 if (cid >= tmpIdx) { 12504 tmpIdx = cid + 1; 12505 } 12506 } catch (NumberFormatException e) { 12507 } 12508 } 12509 } 12510 return mTempContainerPrefix + tmpIdx; 12511 } 12512 12513 /* 12514 * Update media status on PackageManager. 12515 */ 12516 @Override 12517 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12518 int callingUid = Binder.getCallingUid(); 12519 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12520 throw new SecurityException("Media status can only be updated by the system"); 12521 } 12522 // reader; this apparently protects mMediaMounted, but should probably 12523 // be a different lock in that case. 12524 synchronized (mPackages) { 12525 Log.i(TAG, "Updating external media status from " 12526 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12527 + (mediaStatus ? "mounted" : "unmounted")); 12528 if (DEBUG_SD_INSTALL) 12529 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12530 + ", mMediaMounted=" + mMediaMounted); 12531 if (mediaStatus == mMediaMounted) { 12532 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12533 : 0, -1); 12534 mHandler.sendMessage(msg); 12535 return; 12536 } 12537 mMediaMounted = mediaStatus; 12538 } 12539 // Queue up an async operation since the package installation may take a 12540 // little while. 12541 mHandler.post(new Runnable() { 12542 public void run() { 12543 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12544 } 12545 }); 12546 } 12547 12548 /** 12549 * Called by MountService when the initial ASECs to scan are available. 12550 * Should block until all the ASEC containers are finished being scanned. 12551 */ 12552 public void scanAvailableAsecs() { 12553 updateExternalMediaStatusInner(true, false, false); 12554 if (mShouldRestoreconData) { 12555 SELinuxMMAC.setRestoreconDone(); 12556 mShouldRestoreconData = false; 12557 } 12558 } 12559 12560 /* 12561 * Collect information of applications on external media, map them against 12562 * existing containers and update information based on current mount status. 12563 * Please note that we always have to report status if reportStatus has been 12564 * set to true especially when unloading packages. 12565 */ 12566 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12567 boolean externalStorage) { 12568 // Collection of uids 12569 int uidArr[] = null; 12570 // Collection of stale containers 12571 HashSet<String> removeCids = new HashSet<String>(); 12572 // Collection of packages on external media with valid containers. 12573 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12574 // Get list of secure containers. 12575 final String list[] = PackageHelper.getSecureContainerList(); 12576 if (list == null || list.length == 0) { 12577 Log.i(TAG, "No secure containers on sdcard"); 12578 } else { 12579 // Process list of secure containers and categorize them 12580 // as active or stale based on their package internal state. 12581 int uidList[] = new int[list.length]; 12582 int num = 0; 12583 // reader 12584 synchronized (mPackages) { 12585 for (String cid : list) { 12586 if (DEBUG_SD_INSTALL) 12587 Log.i(TAG, "Processing container " + cid); 12588 String pkgName = getAsecPackageName(cid); 12589 if (pkgName == null) { 12590 if (DEBUG_SD_INSTALL) 12591 Log.i(TAG, "Container : " + cid + " stale"); 12592 removeCids.add(cid); 12593 continue; 12594 } 12595 if (DEBUG_SD_INSTALL) 12596 Log.i(TAG, "Looking for pkg : " + pkgName); 12597 12598 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12599 if (ps == null) { 12600 Log.i(TAG, "Deleting container with no matching settings " + cid); 12601 removeCids.add(cid); 12602 continue; 12603 } 12604 12605 /* 12606 * Skip packages that are not external if we're unmounting 12607 * external storage. 12608 */ 12609 if (externalStorage && !isMounted && !isExternal(ps)) { 12610 continue; 12611 } 12612 12613 final AsecInstallArgs args = new AsecInstallArgs(cid, 12614 getAppInstructionSetFromSettings(ps), 12615 isForwardLocked(ps)); 12616 // The package status is changed only if the code path 12617 // matches between settings and the container id. 12618 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12619 if (DEBUG_SD_INSTALL) { 12620 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12621 + " at code path: " + ps.codePathString); 12622 } 12623 12624 // We do have a valid package installed on sdcard 12625 processCids.put(args, ps.codePathString); 12626 final int uid = ps.appId; 12627 if (uid != -1) { 12628 uidList[num++] = uid; 12629 } 12630 } else { 12631 Log.i(TAG, "Deleting stale container for " + cid); 12632 removeCids.add(cid); 12633 } 12634 } 12635 } 12636 12637 if (num > 0) { 12638 // Sort uid list 12639 Arrays.sort(uidList, 0, num); 12640 // Throw away duplicates 12641 uidArr = new int[num]; 12642 uidArr[0] = uidList[0]; 12643 int di = 0; 12644 for (int i = 1; i < num; i++) { 12645 if (uidList[i - 1] != uidList[i]) { 12646 uidArr[di++] = uidList[i]; 12647 } 12648 } 12649 } 12650 } 12651 // Process packages with valid entries. 12652 if (isMounted) { 12653 if (DEBUG_SD_INSTALL) 12654 Log.i(TAG, "Loading packages"); 12655 loadMediaPackages(processCids, uidArr, removeCids); 12656 startCleaningPackages(); 12657 } else { 12658 if (DEBUG_SD_INSTALL) 12659 Log.i(TAG, "Unloading packages"); 12660 unloadMediaPackages(processCids, uidArr, reportStatus); 12661 } 12662 } 12663 12664 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12665 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12666 int size = pkgList.size(); 12667 if (size > 0) { 12668 // Send broadcasts here 12669 Bundle extras = new Bundle(); 12670 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12671 .toArray(new String[size])); 12672 if (uidArr != null) { 12673 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12674 } 12675 if (replacing) { 12676 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12677 } 12678 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12679 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12680 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12681 } 12682 } 12683 12684 /* 12685 * Look at potentially valid container ids from processCids If package 12686 * information doesn't match the one on record or package scanning fails, 12687 * the cid is added to list of removeCids. We currently don't delete stale 12688 * containers. 12689 */ 12690 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12691 HashSet<String> removeCids) { 12692 ArrayList<String> pkgList = new ArrayList<String>(); 12693 Set<AsecInstallArgs> keys = processCids.keySet(); 12694 boolean doGc = false; 12695 for (AsecInstallArgs args : keys) { 12696 String codePath = processCids.get(args); 12697 if (DEBUG_SD_INSTALL) 12698 Log.i(TAG, "Loading container : " + args.cid); 12699 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12700 try { 12701 // Make sure there are no container errors first. 12702 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12703 Slog.e(TAG, "Failed to mount cid : " + args.cid 12704 + " when installing from sdcard"); 12705 continue; 12706 } 12707 // Check code path here. 12708 if (codePath == null || !codePath.equals(args.getCodePath())) { 12709 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12710 + " does not match one in settings " + codePath); 12711 continue; 12712 } 12713 // Parse package 12714 int parseFlags = mDefParseFlags; 12715 if (args.isExternal()) { 12716 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12717 } 12718 if (args.isFwdLocked()) { 12719 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12720 } 12721 12722 doGc = true; 12723 synchronized (mInstallLock) { 12724 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 12725 0, 0, null, null); 12726 // Scan the package 12727 if (pkg != null) { 12728 /* 12729 * TODO why is the lock being held? doPostInstall is 12730 * called in other places without the lock. This needs 12731 * to be straightened out. 12732 */ 12733 // writer 12734 synchronized (mPackages) { 12735 retCode = PackageManager.INSTALL_SUCCEEDED; 12736 pkgList.add(pkg.packageName); 12737 // Post process args 12738 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12739 pkg.applicationInfo.uid); 12740 } 12741 } else { 12742 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12743 } 12744 } 12745 12746 } finally { 12747 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12748 // Don't destroy container here. Wait till gc clears things 12749 // up. 12750 removeCids.add(args.cid); 12751 } 12752 } 12753 } 12754 // writer 12755 synchronized (mPackages) { 12756 // If the platform SDK has changed since the last time we booted, 12757 // we need to re-grant app permission to catch any new ones that 12758 // appear. This is really a hack, and means that apps can in some 12759 // cases get permissions that the user didn't initially explicitly 12760 // allow... it would be nice to have some better way to handle 12761 // this situation. 12762 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12763 if (regrantPermissions) 12764 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12765 + mSdkVersion + "; regranting permissions for external storage"); 12766 mSettings.mExternalSdkPlatform = mSdkVersion; 12767 12768 // Make sure group IDs have been assigned, and any permission 12769 // changes in other apps are accounted for 12770 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12771 | (regrantPermissions 12772 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12773 : 0)); 12774 12775 mSettings.updateExternalDatabaseVersion(); 12776 12777 // can downgrade to reader 12778 // Persist settings 12779 mSettings.writeLPr(); 12780 } 12781 // Send a broadcast to let everyone know we are done processing 12782 if (pkgList.size() > 0) { 12783 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12784 } 12785 // Force gc to avoid any stale parser references that we might have. 12786 if (doGc) { 12787 Runtime.getRuntime().gc(); 12788 } 12789 // List stale containers and destroy stale temporary containers. 12790 if (removeCids != null) { 12791 for (String cid : removeCids) { 12792 if (cid.startsWith(mTempContainerPrefix)) { 12793 Log.i(TAG, "Destroying stale temporary container " + cid); 12794 PackageHelper.destroySdDir(cid); 12795 } else { 12796 Log.w(TAG, "Container " + cid + " is stale"); 12797 } 12798 } 12799 } 12800 } 12801 12802 /* 12803 * Utility method to unload a list of specified containers 12804 */ 12805 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12806 // Just unmount all valid containers. 12807 for (AsecInstallArgs arg : cidArgs) { 12808 synchronized (mInstallLock) { 12809 arg.doPostDeleteLI(false); 12810 } 12811 } 12812 } 12813 12814 /* 12815 * Unload packages mounted on external media. This involves deleting package 12816 * data from internal structures, sending broadcasts about diabled packages, 12817 * gc'ing to free up references, unmounting all secure containers 12818 * corresponding to packages on external media, and posting a 12819 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12820 * that we always have to post this message if status has been requested no 12821 * matter what. 12822 */ 12823 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12824 final boolean reportStatus) { 12825 if (DEBUG_SD_INSTALL) 12826 Log.i(TAG, "unloading media packages"); 12827 ArrayList<String> pkgList = new ArrayList<String>(); 12828 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12829 final Set<AsecInstallArgs> keys = processCids.keySet(); 12830 for (AsecInstallArgs args : keys) { 12831 String pkgName = args.getPackageName(); 12832 if (DEBUG_SD_INSTALL) 12833 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12834 // Delete package internally 12835 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12836 synchronized (mInstallLock) { 12837 boolean res = deletePackageLI(pkgName, null, false, null, null, 12838 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12839 if (res) { 12840 pkgList.add(pkgName); 12841 } else { 12842 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12843 failedList.add(args); 12844 } 12845 } 12846 } 12847 12848 // reader 12849 synchronized (mPackages) { 12850 // We didn't update the settings after removing each package; 12851 // write them now for all packages. 12852 mSettings.writeLPr(); 12853 } 12854 12855 // We have to absolutely send UPDATED_MEDIA_STATUS only 12856 // after confirming that all the receivers processed the ordered 12857 // broadcast when packages get disabled, force a gc to clean things up. 12858 // and unload all the containers. 12859 if (pkgList.size() > 0) { 12860 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12861 new IIntentReceiver.Stub() { 12862 public void performReceive(Intent intent, int resultCode, String data, 12863 Bundle extras, boolean ordered, boolean sticky, 12864 int sendingUser) throws RemoteException { 12865 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12866 reportStatus ? 1 : 0, 1, keys); 12867 mHandler.sendMessage(msg); 12868 } 12869 }); 12870 } else { 12871 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12872 keys); 12873 mHandler.sendMessage(msg); 12874 } 12875 } 12876 12877 /** Binder call */ 12878 @Override 12879 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12880 final int flags) { 12881 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12882 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12883 int returnCode = PackageManager.MOVE_SUCCEEDED; 12884 int currFlags = 0; 12885 int newFlags = 0; 12886 // reader 12887 synchronized (mPackages) { 12888 PackageParser.Package pkg = mPackages.get(packageName); 12889 if (pkg == null) { 12890 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12891 } else { 12892 // Disable moving fwd locked apps and system packages 12893 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12894 Slog.w(TAG, "Cannot move system application"); 12895 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12896 } else if (pkg.mOperationPending) { 12897 Slog.w(TAG, "Attempt to move package which has pending operations"); 12898 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12899 } else { 12900 // Find install location first 12901 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12902 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12903 Slog.w(TAG, "Ambigous flags specified for move location."); 12904 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12905 } else { 12906 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12907 : PackageManager.INSTALL_INTERNAL; 12908 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12909 : PackageManager.INSTALL_INTERNAL; 12910 12911 if (newFlags == currFlags) { 12912 Slog.w(TAG, "No move required. Trying to move to same location"); 12913 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12914 } else { 12915 if (isForwardLocked(pkg)) { 12916 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12917 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12918 } 12919 } 12920 } 12921 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12922 pkg.mOperationPending = true; 12923 } 12924 } 12925 } 12926 12927 /* 12928 * TODO this next block probably shouldn't be inside the lock. We 12929 * can't guarantee these won't change after this is fired off 12930 * anyway. 12931 */ 12932 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12933 processPendingMove(new MoveParams(null, observer, 0, packageName, null, 12934 null, -1, user), 12935 returnCode); 12936 } else { 12937 Message msg = mHandler.obtainMessage(INIT_COPY); 12938 final String instructionSet = getAppInstructionSet(pkg.applicationInfo); 12939 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir, 12940 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir, 12941 instructionSet); 12942 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12943 pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user); 12944 msg.obj = mp; 12945 mHandler.sendMessage(msg); 12946 } 12947 } 12948 } 12949 12950 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12951 // Queue up an async operation since the package deletion may take a 12952 // little while. 12953 mHandler.post(new Runnable() { 12954 public void run() { 12955 // TODO fix this; this does nothing. 12956 mHandler.removeCallbacks(this); 12957 int returnCode = currentStatus; 12958 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12959 int uidArr[] = null; 12960 ArrayList<String> pkgList = null; 12961 synchronized (mPackages) { 12962 PackageParser.Package pkg = mPackages.get(mp.packageName); 12963 if (pkg == null) { 12964 Slog.w(TAG, " Package " + mp.packageName 12965 + " doesn't exist. Aborting move"); 12966 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12967 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 12968 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12969 + mp.srcArgs.getCodePath() + " to " 12970 + pkg.applicationInfo.sourceDir 12971 + " Aborting move and returning error"); 12972 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12973 } else { 12974 uidArr = new int[] { 12975 pkg.applicationInfo.uid 12976 }; 12977 pkgList = new ArrayList<String>(); 12978 pkgList.add(mp.packageName); 12979 } 12980 } 12981 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12982 // Send resources unavailable broadcast 12983 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12984 // Update package code and resource paths 12985 synchronized (mInstallLock) { 12986 synchronized (mPackages) { 12987 PackageParser.Package pkg = mPackages.get(mp.packageName); 12988 // Recheck for package again. 12989 if (pkg == null) { 12990 Slog.w(TAG, " Package " + mp.packageName 12991 + " doesn't exist. Aborting move"); 12992 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12993 } else if (!mp.srcArgs.getCodePath().equals( 12994 pkg.applicationInfo.sourceDir)) { 12995 Slog.w(TAG, "Package " + mp.packageName 12996 + " code path changed from " + mp.srcArgs.getCodePath() 12997 + " to " + pkg.applicationInfo.sourceDir 12998 + " Aborting move and returning error"); 12999 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13000 } else { 13001 final String oldCodePath = pkg.codePath; 13002 final String newCodePath = mp.targetArgs.getCodePath(); 13003 final String newResPath = mp.targetArgs.getResourcePath(); 13004 final String newNativePath = mp.targetArgs 13005 .getNativeLibraryPath(); 13006 13007 final File newNativeDir = new File(newNativePath); 13008 13009 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 13010 // NOTE: We do not report any errors from the APK scan and library 13011 // copy at this point. 13012 NativeLibraryHelper.ApkHandle handle = 13013 new NativeLibraryHelper.ApkHandle(newCodePath); 13014 final int abi = NativeLibraryHelper.findSupportedAbi( 13015 handle, Build.SUPPORTED_ABIS); 13016 if (abi >= 0) { 13017 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 13018 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 13019 } 13020 handle.close(); 13021 } 13022 final int[] users = sUserManager.getUserIds(); 13023 for (int user : users) { 13024 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13025 newNativePath, user) < 0) { 13026 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13027 } 13028 } 13029 13030 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13031 pkg.codePath = newCodePath; 13032 // Move dex files around 13033 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13034 // Moving of dex files failed. Set 13035 // error code and abort move. 13036 pkg.codePath = oldCodePath; 13037 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13038 } 13039 } 13040 13041 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13042 pkg.applicationInfo.sourceDir = newCodePath; 13043 pkg.applicationInfo.publicSourceDir = newResPath; 13044 pkg.applicationInfo.nativeLibraryDir = newNativePath; 13045 PackageSetting ps = (PackageSetting) pkg.mExtras; 13046 ps.codePath = new File(pkg.applicationInfo.sourceDir); 13047 ps.codePathString = ps.codePath.getPath(); 13048 ps.resourcePath = new File( 13049 pkg.applicationInfo.publicSourceDir); 13050 ps.resourcePathString = ps.resourcePath.getPath(); 13051 ps.nativeLibraryPathString = newNativePath; 13052 // Set the application info flag 13053 // correctly. 13054 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13055 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13056 } else { 13057 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13058 } 13059 ps.setFlags(pkg.applicationInfo.flags); 13060 mAppDirs.remove(oldCodePath); 13061 mAppDirs.put(newCodePath, pkg); 13062 // Persist settings 13063 mSettings.writeLPr(); 13064 } 13065 } 13066 } 13067 } 13068 // Send resources available broadcast 13069 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13070 } 13071 } 13072 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13073 // Clean up failed installation 13074 if (mp.targetArgs != null) { 13075 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13076 -1); 13077 } 13078 } else { 13079 // Force a gc to clear things up. 13080 Runtime.getRuntime().gc(); 13081 // Delete older code 13082 synchronized (mInstallLock) { 13083 mp.srcArgs.doPostDeleteLI(true); 13084 } 13085 } 13086 13087 // Allow more operations on this file if we didn't fail because 13088 // an operation was already pending for this package. 13089 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13090 synchronized (mPackages) { 13091 PackageParser.Package pkg = mPackages.get(mp.packageName); 13092 if (pkg != null) { 13093 pkg.mOperationPending = false; 13094 } 13095 } 13096 } 13097 13098 IPackageMoveObserver observer = mp.observer; 13099 if (observer != null) { 13100 try { 13101 observer.packageMoved(mp.packageName, returnCode); 13102 } catch (RemoteException e) { 13103 Log.i(TAG, "Observer no longer exists."); 13104 } 13105 } 13106 } 13107 }); 13108 } 13109 13110 @Override 13111 public boolean setInstallLocation(int loc) { 13112 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13113 null); 13114 if (getInstallLocation() == loc) { 13115 return true; 13116 } 13117 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13118 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13119 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13120 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13121 return true; 13122 } 13123 return false; 13124 } 13125 13126 @Override 13127 public int getInstallLocation() { 13128 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13129 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13130 PackageHelper.APP_INSTALL_AUTO); 13131 } 13132 13133 /** Called by UserManagerService */ 13134 void cleanUpUserLILPw(int userHandle) { 13135 mDirtyUsers.remove(userHandle); 13136 mSettings.removeUserLPr(userHandle); 13137 mPendingBroadcasts.remove(userHandle); 13138 if (mInstaller != null) { 13139 // Technically, we shouldn't be doing this with the package lock 13140 // held. However, this is very rare, and there is already so much 13141 // other disk I/O going on, that we'll let it slide for now. 13142 mInstaller.removeUserDataDirs(userHandle); 13143 } 13144 } 13145 13146 /** Called by UserManagerService */ 13147 void createNewUserLILPw(int userHandle, File path) { 13148 if (mInstaller != null) { 13149 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13150 } 13151 } 13152 13153 @Override 13154 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13155 mContext.enforceCallingOrSelfPermission( 13156 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13157 "Only package verification agents can read the verifier device identity"); 13158 13159 synchronized (mPackages) { 13160 return mSettings.getVerifierDeviceIdentityLPw(); 13161 } 13162 } 13163 13164 @Override 13165 public void setPermissionEnforced(String permission, boolean enforced) { 13166 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13167 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13168 synchronized (mPackages) { 13169 if (mSettings.mReadExternalStorageEnforced == null 13170 || mSettings.mReadExternalStorageEnforced != enforced) { 13171 mSettings.mReadExternalStorageEnforced = enforced; 13172 mSettings.writeLPr(); 13173 } 13174 } 13175 // kill any non-foreground processes so we restart them and 13176 // grant/revoke the GID. 13177 final IActivityManager am = ActivityManagerNative.getDefault(); 13178 if (am != null) { 13179 final long token = Binder.clearCallingIdentity(); 13180 try { 13181 am.killProcessesBelowForeground("setPermissionEnforcement"); 13182 } catch (RemoteException e) { 13183 } finally { 13184 Binder.restoreCallingIdentity(token); 13185 } 13186 } 13187 } else { 13188 throw new IllegalArgumentException("No selective enforcement for " + permission); 13189 } 13190 } 13191 13192 @Override 13193 @Deprecated 13194 public boolean isPermissionEnforced(String permission) { 13195 return true; 13196 } 13197 13198 @Override 13199 public boolean isStorageLow() { 13200 final long token = Binder.clearCallingIdentity(); 13201 try { 13202 final DeviceStorageMonitorInternal 13203 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13204 if (dsm != null) { 13205 return dsm.isMemoryLow(); 13206 } else { 13207 return false; 13208 } 13209 } finally { 13210 Binder.restoreCallingIdentity(token); 13211 } 13212 } 13213 13214 @Override 13215 public IPackageInstaller getPackageInstaller() { 13216 return mInstallerService; 13217 } 13218} 13219