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