PackageManagerService.java revision 63798c596dc757135950313eb4bb44ca58696c68
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; 56import com.android.server.storage.DeviceStorageMonitorInternal; 57 58import org.xmlpull.v1.XmlPullParser; 59import org.xmlpull.v1.XmlPullParserException; 60import org.xmlpull.v1.XmlSerializer; 61 62import android.app.ActivityManager; 63import android.app.ActivityManagerNative; 64import android.app.IActivityManager; 65import android.app.PackageInstallObserver; 66import android.app.admin.IDevicePolicyManager; 67import android.app.backup.IBackupManager; 68import android.content.BroadcastReceiver; 69import android.content.ComponentName; 70import android.content.Context; 71import android.content.IIntentReceiver; 72import android.content.Intent; 73import android.content.IntentFilter; 74import android.content.IntentSender; 75import android.content.IntentSender.SendIntentException; 76import android.content.ServiceConnection; 77import android.content.pm.ActivityInfo; 78import android.content.pm.ApplicationInfo; 79import android.content.pm.ContainerEncryptionParams; 80import android.content.pm.FeatureInfo; 81import android.content.pm.IPackageDataObserver; 82import android.content.pm.IPackageDeleteObserver; 83import android.content.pm.IPackageInstallObserver; 84import android.content.pm.IPackageInstallObserver2; 85import android.content.pm.IPackageInstaller; 86import android.content.pm.IPackageManager; 87import android.content.pm.IPackageMoveObserver; 88import android.content.pm.IPackageStatsObserver; 89import android.content.pm.InstrumentationInfo; 90import android.content.pm.ManifestDigest; 91import android.content.pm.PackageCleanItem; 92import android.content.pm.PackageInfo; 93import android.content.pm.PackageInfoLite; 94import android.content.pm.PackageInstallerParams; 95import android.content.pm.PackageManager; 96import android.content.pm.PackageParser.ActivityIntentInfo; 97import android.content.pm.PackageParser.PackageParserException; 98import android.content.pm.PackageParser; 99import android.content.pm.PackageStats; 100import android.content.pm.PackageUserState; 101import android.content.pm.ParceledListSlice; 102import android.content.pm.PermissionGroupInfo; 103import android.content.pm.PermissionInfo; 104import android.content.pm.ProviderInfo; 105import android.content.pm.ResolveInfo; 106import android.content.pm.ServiceInfo; 107import android.content.pm.Signature; 108import android.content.pm.VerificationParams; 109import android.content.pm.VerifierDeviceIdentity; 110import android.content.pm.VerifierInfo; 111import android.content.res.Resources; 112import android.hardware.display.DisplayManager; 113import android.net.Uri; 114import android.os.Binder; 115import android.os.Build; 116import android.os.Bundle; 117import android.os.Environment; 118import android.os.Environment.UserEnvironment; 119import android.os.FileObserver; 120import android.os.FileUtils; 121import android.os.Handler; 122import android.os.IBinder; 123import android.os.Looper; 124import android.os.Message; 125import android.os.Parcel; 126import android.os.ParcelFileDescriptor; 127import android.os.Process; 128import android.os.RemoteException; 129import android.os.SELinux; 130import android.os.ServiceManager; 131import android.os.SystemClock; 132import android.os.SystemProperties; 133import android.os.UserHandle; 134import android.os.UserManager; 135import android.security.KeyStore; 136import android.security.SystemKeyStore; 137import android.system.ErrnoException; 138import android.system.Os; 139import android.system.StructStat; 140import android.text.TextUtils; 141import android.util.ArraySet; 142import android.util.AtomicFile; 143import android.util.DisplayMetrics; 144import android.util.EventLog; 145import android.util.Log; 146import android.util.LogPrinter; 147import android.util.PrintStreamPrinter; 148import android.util.Slog; 149import android.util.SparseArray; 150import android.util.SparseBooleanArray; 151import android.util.Xml; 152import android.view.Display; 153 154import java.io.BufferedInputStream; 155import java.io.BufferedOutputStream; 156import java.io.File; 157import java.io.FileDescriptor; 158import java.io.FileInputStream; 159import java.io.FileNotFoundException; 160import java.io.FileOutputStream; 161import java.io.FileReader; 162import java.io.FilenameFilter; 163import java.io.IOException; 164import java.io.InputStream; 165import java.io.PrintWriter; 166import java.nio.charset.StandardCharsets; 167import java.security.NoSuchAlgorithmException; 168import java.security.PublicKey; 169import java.security.cert.CertificateEncodingException; 170import java.security.cert.CertificateException; 171import java.text.SimpleDateFormat; 172import java.util.ArrayList; 173import java.util.Arrays; 174import java.util.Collection; 175import java.util.Collections; 176import java.util.Comparator; 177import java.util.Date; 178import java.util.HashMap; 179import java.util.HashSet; 180import java.util.Iterator; 181import java.util.List; 182import java.util.Map; 183import java.util.Set; 184import java.util.concurrent.atomic.AtomicBoolean; 185import java.util.concurrent.atomic.AtomicLong; 186 187import dalvik.system.DexFile; 188import dalvik.system.StaleDexCacheError; 189import dalvik.system.VMRuntime; 190 191import libcore.io.IoUtils; 192 193/** 194 * Keep track of all those .apks everywhere. 195 * 196 * This is very central to the platform's security; please run the unit 197 * tests whenever making modifications here: 198 * 199mmm frameworks/base/tests/AndroidTests 200adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 201adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 202 * 203 * {@hide} 204 */ 205public class PackageManagerService extends IPackageManager.Stub { 206 static final String TAG = "PackageManager"; 207 static final boolean DEBUG_SETTINGS = false; 208 static final boolean DEBUG_PREFERRED = false; 209 static final boolean DEBUG_UPGRADE = false; 210 private static final boolean DEBUG_INSTALL = false; 211 private static final boolean DEBUG_REMOVE = false; 212 private static final boolean DEBUG_BROADCASTS = false; 213 private static final boolean DEBUG_SHOW_INFO = false; 214 private static final boolean DEBUG_PACKAGE_INFO = false; 215 private static final boolean DEBUG_INTENT_MATCHING = false; 216 private static final boolean DEBUG_PACKAGE_SCANNING = false; 217 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 218 private static final boolean DEBUG_VERIFY = false; 219 private static final boolean DEBUG_DEXOPT = false; 220 221 private static final int RADIO_UID = Process.PHONE_UID; 222 private static final int LOG_UID = Process.LOG_UID; 223 private static final int NFC_UID = Process.NFC_UID; 224 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 225 private static final int SHELL_UID = Process.SHELL_UID; 226 227 // Cap the size of permission trees that 3rd party apps can define 228 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 229 230 private static final int REMOVE_EVENTS = 231 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 232 private static final int ADD_EVENTS = 233 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 234 235 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 236 // Suffix used during package installation when copying/moving 237 // package apks to install directory. 238 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 239 240 static final int SCAN_MONITOR = 1<<0; 241 static final int SCAN_NO_DEX = 1<<1; 242 static final int SCAN_FORCE_DEX = 1<<2; 243 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 244 static final int SCAN_NEW_INSTALL = 1<<4; 245 static final int SCAN_NO_PATHS = 1<<5; 246 static final int SCAN_UPDATE_TIME = 1<<6; 247 static final int SCAN_DEFER_DEX = 1<<7; 248 static final int SCAN_BOOTING = 1<<8; 249 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 250 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 251 252 static final int REMOVE_CHATTY = 1<<16; 253 254 /** 255 * Timeout (in milliseconds) after which the watchdog should declare that 256 * our handler thread is wedged. The usual default for such things is one 257 * minute but we sometimes do very lengthy I/O operations on this thread, 258 * such as installing multi-gigabyte applications, so ours needs to be longer. 259 */ 260 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 261 262 /** 263 * Whether verification is enabled by default. 264 */ 265 private static final boolean DEFAULT_VERIFY_ENABLE = true; 266 267 /** 268 * The default maximum time to wait for the verification agent to return in 269 * milliseconds. 270 */ 271 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 272 273 /** 274 * The default response for package verification timeout. 275 * 276 * This can be either PackageManager.VERIFICATION_ALLOW or 277 * PackageManager.VERIFICATION_REJECT. 278 */ 279 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 280 281 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 282 283 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 284 DEFAULT_CONTAINER_PACKAGE, 285 "com.android.defcontainer.DefaultContainerService"); 286 287 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 288 289 private static final String LIB_DIR_NAME = "lib"; 290 private static final String LIB64_DIR_NAME = "lib64"; 291 292 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 293 294 static final String mTempContainerPrefix = "smdl2tmp"; 295 296 private static String sPreferredInstructionSet; 297 298 final ServiceThread mHandlerThread; 299 300 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 301 private static final String IDMAP_SUFFIX = "@idmap"; 302 303 final PackageHandler mHandler; 304 305 final int mSdkVersion = Build.VERSION.SDK_INT; 306 307 final Context mContext; 308 final boolean mFactoryTest; 309 final boolean mOnlyCore; 310 final DisplayMetrics mMetrics; 311 final int mDefParseFlags; 312 final String[] mSeparateProcesses; 313 314 // This is where all application persistent data goes. 315 final File mAppDataDir; 316 317 // This is where all application persistent data goes for secondary users. 318 final File mUserAppDataDir; 319 320 /** The location for ASEC container files on internal storage. */ 321 final String mAsecInternalPath; 322 323 // This is the object monitoring the framework dir. 324 final FileObserver mFrameworkInstallObserver; 325 326 // This is the object monitoring the system app dir. 327 final FileObserver mSystemInstallObserver; 328 329 // This is the object monitoring the privileged system app dir. 330 final FileObserver mPrivilegedInstallObserver; 331 332 // This is the object monitoring the vendor app dir. 333 final FileObserver mVendorInstallObserver; 334 335 // This is the object monitoring the vendor overlay package dir. 336 final FileObserver mVendorOverlayInstallObserver; 337 338 // This is the object monitoring the OEM app dir. 339 final FileObserver mOemInstallObserver; 340 341 // This is the object monitoring mAppInstallDir. 342 final FileObserver mAppInstallObserver; 343 344 // This is the object monitoring mDrmAppPrivateInstallDir. 345 final FileObserver mDrmAppInstallObserver; 346 347 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 348 // LOCK HELD. Can be called with mInstallLock held. 349 final Installer mInstaller; 350 351 final File mAppInstallDir; 352 353 /** 354 * Directory to which applications installed internally have native 355 * libraries copied. 356 */ 357 private File mAppLibInstallDir; 358 359 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 360 // apps. 361 final File mDrmAppPrivateInstallDir; 362 363 final File mAppStagingDir; 364 365 // ---------------------------------------------------------------- 366 367 // Lock for state used when installing and doing other long running 368 // operations. Methods that must be called with this lock held have 369 // the suffix "LI". 370 final Object mInstallLock = new Object(); 371 372 // These are the directories in the 3rd party applications installed dir 373 // that we have currently loaded packages from. Keys are the application's 374 // installed zip file (absolute codePath), and values are Package. 375 final HashMap<String, PackageParser.Package> mAppDirs = 376 new HashMap<String, PackageParser.Package>(); 377 378 // Information for the parser to write more useful error messages. 379 int mLastScanError; 380 381 // ---------------------------------------------------------------- 382 383 // Keys are String (package name), values are Package. This also serves 384 // as the lock for the global state. Methods that must be called with 385 // this lock held have the prefix "LP". 386 final HashMap<String, PackageParser.Package> mPackages = 387 new HashMap<String, PackageParser.Package>(); 388 389 // Tracks available target package names -> overlay package paths. 390 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 391 new HashMap<String, HashMap<String, PackageParser.Package>>(); 392 393 final Settings mSettings; 394 boolean mRestoredSettings; 395 396 // Group-ids that are given to all packages as read from etc/permissions/*.xml. 397 int[] mGlobalGids; 398 399 // These are the built-in uid -> permission mappings that were read from the 400 // etc/permissions.xml file. 401 final SparseArray<HashSet<String>> mSystemPermissions = 402 new SparseArray<HashSet<String>>(); 403 404 static final class SharedLibraryEntry { 405 final String path; 406 final String apk; 407 408 SharedLibraryEntry(String _path, String _apk) { 409 path = _path; 410 apk = _apk; 411 } 412 } 413 414 // These are the built-in shared libraries that were read from the 415 // etc/permissions.xml file. 416 final HashMap<String, SharedLibraryEntry> mSharedLibraries 417 = new HashMap<String, SharedLibraryEntry>(); 418 419 // These are the features this devices supports that were read from the 420 // etc/permissions.xml file. 421 final HashMap<String, FeatureInfo> mAvailableFeatures = 422 new HashMap<String, FeatureInfo>(); 423 424 // If mac_permissions.xml was found for seinfo labeling. 425 boolean mFoundPolicyFile; 426 427 // If a recursive restorecon of /data/data/<pkg> is needed. 428 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 429 430 // All available activities, for your resolving pleasure. 431 final ActivityIntentResolver mActivities = 432 new ActivityIntentResolver(); 433 434 // All available receivers, for your resolving pleasure. 435 final ActivityIntentResolver mReceivers = 436 new ActivityIntentResolver(); 437 438 // All available services, for your resolving pleasure. 439 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 440 441 // All available providers, for your resolving pleasure. 442 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 443 444 // Mapping from provider base names (first directory in content URI codePath) 445 // to the provider information. 446 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 447 new HashMap<String, PackageParser.Provider>(); 448 449 // Mapping from instrumentation class names to info about them. 450 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 451 new HashMap<ComponentName, PackageParser.Instrumentation>(); 452 453 // Mapping from permission names to info about them. 454 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 455 new HashMap<String, PackageParser.PermissionGroup>(); 456 457 // Packages whose data we have transfered into another package, thus 458 // should no longer exist. 459 final HashSet<String> mTransferedPackages = new HashSet<String>(); 460 461 // Broadcast actions that are only available to the system. 462 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 463 464 /** List of packages waiting for verification. */ 465 final SparseArray<PackageVerificationState> mPendingVerification 466 = new SparseArray<PackageVerificationState>(); 467 468 final PackageInstallerService mInstallerService; 469 470 HashSet<PackageParser.Package> mDeferredDexOpt = null; 471 472 /** Token for keys in mPendingVerification. */ 473 private int mPendingVerificationToken = 0; 474 475 boolean mSystemReady; 476 boolean mSafeMode; 477 boolean mHasSystemUidErrors; 478 479 ApplicationInfo mAndroidApplication; 480 final ActivityInfo mResolveActivity = new ActivityInfo(); 481 final ResolveInfo mResolveInfo = new ResolveInfo(); 482 ComponentName mResolveComponentName; 483 PackageParser.Package mPlatformPackage; 484 ComponentName mCustomResolverComponentName; 485 486 boolean mResolverReplaced = false; 487 488 // Set of pending broadcasts for aggregating enable/disable of components. 489 static class PendingPackageBroadcasts { 490 // for each user id, a map of <package name -> components within that package> 491 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 492 493 public PendingPackageBroadcasts() { 494 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 495 } 496 497 public ArrayList<String> get(int userId, String packageName) { 498 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 499 return packages.get(packageName); 500 } 501 502 public void put(int userId, String packageName, ArrayList<String> components) { 503 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 504 packages.put(packageName, components); 505 } 506 507 public void remove(int userId, String packageName) { 508 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 509 if (packages != null) { 510 packages.remove(packageName); 511 } 512 } 513 514 public void remove(int userId) { 515 mUidMap.remove(userId); 516 } 517 518 public int userIdCount() { 519 return mUidMap.size(); 520 } 521 522 public int userIdAt(int n) { 523 return mUidMap.keyAt(n); 524 } 525 526 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 527 return mUidMap.get(userId); 528 } 529 530 public int size() { 531 // total number of pending broadcast entries across all userIds 532 int num = 0; 533 for (int i = 0; i< mUidMap.size(); i++) { 534 num += mUidMap.valueAt(i).size(); 535 } 536 return num; 537 } 538 539 public void clear() { 540 mUidMap.clear(); 541 } 542 543 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 544 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 545 if (map == null) { 546 map = new HashMap<String, ArrayList<String>>(); 547 mUidMap.put(userId, map); 548 } 549 return map; 550 } 551 } 552 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 553 554 // Service Connection to remote media container service to copy 555 // package uri's from external media onto secure containers 556 // or internal storage. 557 private IMediaContainerService mContainerService = null; 558 559 static final int SEND_PENDING_BROADCAST = 1; 560 static final int MCS_BOUND = 3; 561 static final int END_COPY = 4; 562 static final int INIT_COPY = 5; 563 static final int MCS_UNBIND = 6; 564 static final int START_CLEANING_PACKAGE = 7; 565 static final int FIND_INSTALL_LOC = 8; 566 static final int POST_INSTALL = 9; 567 static final int MCS_RECONNECT = 10; 568 static final int MCS_GIVE_UP = 11; 569 static final int UPDATED_MEDIA_STATUS = 12; 570 static final int WRITE_SETTINGS = 13; 571 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 572 static final int PACKAGE_VERIFIED = 15; 573 static final int CHECK_PENDING_VERIFICATION = 16; 574 575 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 576 577 // Delay time in millisecs 578 static final int BROADCAST_DELAY = 10 * 1000; 579 580 static UserManagerService sUserManager; 581 582 // Stores a list of users whose package restrictions file needs to be updated 583 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 584 585 final private DefaultContainerConnection mDefContainerConn = 586 new DefaultContainerConnection(); 587 class DefaultContainerConnection implements ServiceConnection { 588 public void onServiceConnected(ComponentName name, IBinder service) { 589 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 590 IMediaContainerService imcs = 591 IMediaContainerService.Stub.asInterface(service); 592 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 593 } 594 595 public void onServiceDisconnected(ComponentName name) { 596 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 597 } 598 }; 599 600 // Recordkeeping of restore-after-install operations that are currently in flight 601 // between the Package Manager and the Backup Manager 602 class PostInstallData { 603 public InstallArgs args; 604 public PackageInstalledInfo res; 605 606 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 607 args = _a; 608 res = _r; 609 } 610 }; 611 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 612 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 613 614 private final String mRequiredVerifierPackage; 615 616 private final PackageUsage mPackageUsage = new PackageUsage(); 617 618 private class PackageUsage { 619 private static final int WRITE_INTERVAL 620 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 621 622 private final Object mFileLock = new Object(); 623 private final AtomicLong mLastWritten = new AtomicLong(0); 624 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 625 626 private boolean mIsFirstBoot = false; 627 628 boolean isFirstBoot() { 629 return mIsFirstBoot; 630 } 631 632 void write(boolean force) { 633 if (force) { 634 writeInternal(); 635 return; 636 } 637 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 638 && !DEBUG_DEXOPT) { 639 return; 640 } 641 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 642 new Thread("PackageUsage_DiskWriter") { 643 @Override 644 public void run() { 645 try { 646 writeInternal(); 647 } finally { 648 mBackgroundWriteRunning.set(false); 649 } 650 } 651 }.start(); 652 } 653 } 654 655 private void writeInternal() { 656 synchronized (mPackages) { 657 synchronized (mFileLock) { 658 AtomicFile file = getFile(); 659 FileOutputStream f = null; 660 try { 661 f = file.startWrite(); 662 BufferedOutputStream out = new BufferedOutputStream(f); 663 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 664 StringBuilder sb = new StringBuilder(); 665 for (PackageParser.Package pkg : mPackages.values()) { 666 if (pkg.mLastPackageUsageTimeInMills == 0) { 667 continue; 668 } 669 sb.setLength(0); 670 sb.append(pkg.packageName); 671 sb.append(' '); 672 sb.append((long)pkg.mLastPackageUsageTimeInMills); 673 sb.append('\n'); 674 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 675 } 676 out.flush(); 677 file.finishWrite(f); 678 } catch (IOException e) { 679 if (f != null) { 680 file.failWrite(f); 681 } 682 Log.e(TAG, "Failed to write package usage times", e); 683 } 684 } 685 } 686 mLastWritten.set(SystemClock.elapsedRealtime()); 687 } 688 689 void readLP() { 690 synchronized (mFileLock) { 691 AtomicFile file = getFile(); 692 BufferedInputStream in = null; 693 try { 694 in = new BufferedInputStream(file.openRead()); 695 StringBuffer sb = new StringBuffer(); 696 while (true) { 697 String packageName = readToken(in, sb, ' '); 698 if (packageName == null) { 699 break; 700 } 701 String timeInMillisString = readToken(in, sb, '\n'); 702 if (timeInMillisString == null) { 703 throw new IOException("Failed to find last usage time for package " 704 + packageName); 705 } 706 PackageParser.Package pkg = mPackages.get(packageName); 707 if (pkg == null) { 708 continue; 709 } 710 long timeInMillis; 711 try { 712 timeInMillis = Long.parseLong(timeInMillisString.toString()); 713 } catch (NumberFormatException e) { 714 throw new IOException("Failed to parse " + timeInMillisString 715 + " as a long.", e); 716 } 717 pkg.mLastPackageUsageTimeInMills = timeInMillis; 718 } 719 } catch (FileNotFoundException expected) { 720 mIsFirstBoot = true; 721 } catch (IOException e) { 722 Log.w(TAG, "Failed to read package usage times", e); 723 } finally { 724 IoUtils.closeQuietly(in); 725 } 726 } 727 mLastWritten.set(SystemClock.elapsedRealtime()); 728 } 729 730 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 731 throws IOException { 732 sb.setLength(0); 733 while (true) { 734 int ch = in.read(); 735 if (ch == -1) { 736 if (sb.length() == 0) { 737 return null; 738 } 739 throw new IOException("Unexpected EOF"); 740 } 741 if (ch == endOfToken) { 742 return sb.toString(); 743 } 744 sb.append((char)ch); 745 } 746 } 747 748 private AtomicFile getFile() { 749 File dataDir = Environment.getDataDirectory(); 750 File systemDir = new File(dataDir, "system"); 751 File fname = new File(systemDir, "package-usage.list"); 752 return new AtomicFile(fname); 753 } 754 } 755 756 class PackageHandler extends Handler { 757 private boolean mBound = false; 758 final ArrayList<HandlerParams> mPendingInstalls = 759 new ArrayList<HandlerParams>(); 760 761 private boolean connectToService() { 762 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 763 " DefaultContainerService"); 764 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 765 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 766 if (mContext.bindServiceAsUser(service, mDefContainerConn, 767 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 768 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 769 mBound = true; 770 return true; 771 } 772 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 773 return false; 774 } 775 776 private void disconnectService() { 777 mContainerService = null; 778 mBound = false; 779 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 780 mContext.unbindService(mDefContainerConn); 781 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 782 } 783 784 PackageHandler(Looper looper) { 785 super(looper); 786 } 787 788 public void handleMessage(Message msg) { 789 try { 790 doHandleMessage(msg); 791 } finally { 792 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 793 } 794 } 795 796 void doHandleMessage(Message msg) { 797 switch (msg.what) { 798 case INIT_COPY: { 799 HandlerParams params = (HandlerParams) msg.obj; 800 int idx = mPendingInstalls.size(); 801 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 802 // If a bind was already initiated we dont really 803 // need to do anything. The pending install 804 // will be processed later on. 805 if (!mBound) { 806 // If this is the only one pending we might 807 // have to bind to the service again. 808 if (!connectToService()) { 809 Slog.e(TAG, "Failed to bind to media container service"); 810 params.serviceError(); 811 return; 812 } else { 813 // Once we bind to the service, the first 814 // pending request will be processed. 815 mPendingInstalls.add(idx, params); 816 } 817 } else { 818 mPendingInstalls.add(idx, params); 819 // Already bound to the service. Just make 820 // sure we trigger off processing the first request. 821 if (idx == 0) { 822 mHandler.sendEmptyMessage(MCS_BOUND); 823 } 824 } 825 break; 826 } 827 case MCS_BOUND: { 828 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 829 if (msg.obj != null) { 830 mContainerService = (IMediaContainerService) msg.obj; 831 } 832 if (mContainerService == null) { 833 // Something seriously wrong. Bail out 834 Slog.e(TAG, "Cannot bind to media container service"); 835 for (HandlerParams params : mPendingInstalls) { 836 // Indicate service bind error 837 params.serviceError(); 838 } 839 mPendingInstalls.clear(); 840 } else if (mPendingInstalls.size() > 0) { 841 HandlerParams params = mPendingInstalls.get(0); 842 if (params != null) { 843 if (params.startCopy()) { 844 // We are done... look for more work or to 845 // go idle. 846 if (DEBUG_SD_INSTALL) Log.i(TAG, 847 "Checking for more work or unbind..."); 848 // Delete pending install 849 if (mPendingInstalls.size() > 0) { 850 mPendingInstalls.remove(0); 851 } 852 if (mPendingInstalls.size() == 0) { 853 if (mBound) { 854 if (DEBUG_SD_INSTALL) Log.i(TAG, 855 "Posting delayed MCS_UNBIND"); 856 removeMessages(MCS_UNBIND); 857 Message ubmsg = obtainMessage(MCS_UNBIND); 858 // Unbind after a little delay, to avoid 859 // continual thrashing. 860 sendMessageDelayed(ubmsg, 10000); 861 } 862 } else { 863 // There are more pending requests in queue. 864 // Just post MCS_BOUND message to trigger processing 865 // of next pending install. 866 if (DEBUG_SD_INSTALL) Log.i(TAG, 867 "Posting MCS_BOUND for next work"); 868 mHandler.sendEmptyMessage(MCS_BOUND); 869 } 870 } 871 } 872 } else { 873 // Should never happen ideally. 874 Slog.w(TAG, "Empty queue"); 875 } 876 break; 877 } 878 case MCS_RECONNECT: { 879 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 880 if (mPendingInstalls.size() > 0) { 881 if (mBound) { 882 disconnectService(); 883 } 884 if (!connectToService()) { 885 Slog.e(TAG, "Failed to bind to media container service"); 886 for (HandlerParams params : mPendingInstalls) { 887 // Indicate service bind error 888 params.serviceError(); 889 } 890 mPendingInstalls.clear(); 891 } 892 } 893 break; 894 } 895 case MCS_UNBIND: { 896 // If there is no actual work left, then time to unbind. 897 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 898 899 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 900 if (mBound) { 901 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 902 903 disconnectService(); 904 } 905 } else if (mPendingInstalls.size() > 0) { 906 // There are more pending requests in queue. 907 // Just post MCS_BOUND message to trigger processing 908 // of next pending install. 909 mHandler.sendEmptyMessage(MCS_BOUND); 910 } 911 912 break; 913 } 914 case MCS_GIVE_UP: { 915 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 916 mPendingInstalls.remove(0); 917 break; 918 } 919 case SEND_PENDING_BROADCAST: { 920 String packages[]; 921 ArrayList<String> components[]; 922 int size = 0; 923 int uids[]; 924 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 925 synchronized (mPackages) { 926 if (mPendingBroadcasts == null) { 927 return; 928 } 929 size = mPendingBroadcasts.size(); 930 if (size <= 0) { 931 // Nothing to be done. Just return 932 return; 933 } 934 packages = new String[size]; 935 components = new ArrayList[size]; 936 uids = new int[size]; 937 int i = 0; // filling out the above arrays 938 939 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 940 int packageUserId = mPendingBroadcasts.userIdAt(n); 941 Iterator<Map.Entry<String, ArrayList<String>>> it 942 = mPendingBroadcasts.packagesForUserId(packageUserId) 943 .entrySet().iterator(); 944 while (it.hasNext() && i < size) { 945 Map.Entry<String, ArrayList<String>> ent = it.next(); 946 packages[i] = ent.getKey(); 947 components[i] = ent.getValue(); 948 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 949 uids[i] = (ps != null) 950 ? UserHandle.getUid(packageUserId, ps.appId) 951 : -1; 952 i++; 953 } 954 } 955 size = i; 956 mPendingBroadcasts.clear(); 957 } 958 // Send broadcasts 959 for (int i = 0; i < size; i++) { 960 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 961 } 962 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 963 break; 964 } 965 case START_CLEANING_PACKAGE: { 966 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 967 final String packageName = (String)msg.obj; 968 final int userId = msg.arg1; 969 final boolean andCode = msg.arg2 != 0; 970 synchronized (mPackages) { 971 if (userId == UserHandle.USER_ALL) { 972 int[] users = sUserManager.getUserIds(); 973 for (int user : users) { 974 mSettings.addPackageToCleanLPw( 975 new PackageCleanItem(user, packageName, andCode)); 976 } 977 } else { 978 mSettings.addPackageToCleanLPw( 979 new PackageCleanItem(userId, packageName, andCode)); 980 } 981 } 982 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 983 startCleaningPackages(); 984 } break; 985 case POST_INSTALL: { 986 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 987 PostInstallData data = mRunningInstalls.get(msg.arg1); 988 mRunningInstalls.delete(msg.arg1); 989 boolean deleteOld = false; 990 991 if (data != null) { 992 InstallArgs args = data.args; 993 PackageInstalledInfo res = data.res; 994 995 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 996 res.removedInfo.sendBroadcast(false, true, false); 997 Bundle extras = new Bundle(1); 998 extras.putInt(Intent.EXTRA_UID, res.uid); 999 // Determine the set of users who are adding this 1000 // package for the first time vs. those who are seeing 1001 // an update. 1002 int[] firstUsers; 1003 int[] updateUsers = new int[0]; 1004 if (res.origUsers == null || res.origUsers.length == 0) { 1005 firstUsers = res.newUsers; 1006 } else { 1007 firstUsers = new int[0]; 1008 for (int i=0; i<res.newUsers.length; i++) { 1009 int user = res.newUsers[i]; 1010 boolean isNew = true; 1011 for (int j=0; j<res.origUsers.length; j++) { 1012 if (res.origUsers[j] == user) { 1013 isNew = false; 1014 break; 1015 } 1016 } 1017 if (isNew) { 1018 int[] newFirst = new int[firstUsers.length+1]; 1019 System.arraycopy(firstUsers, 0, newFirst, 0, 1020 firstUsers.length); 1021 newFirst[firstUsers.length] = user; 1022 firstUsers = newFirst; 1023 } else { 1024 int[] newUpdate = new int[updateUsers.length+1]; 1025 System.arraycopy(updateUsers, 0, newUpdate, 0, 1026 updateUsers.length); 1027 newUpdate[updateUsers.length] = user; 1028 updateUsers = newUpdate; 1029 } 1030 } 1031 } 1032 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1033 res.pkg.applicationInfo.packageName, 1034 extras, null, null, firstUsers); 1035 final boolean update = res.removedInfo.removedPackage != null; 1036 if (update) { 1037 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1038 } 1039 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1040 res.pkg.applicationInfo.packageName, 1041 extras, null, null, updateUsers); 1042 if (update) { 1043 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1044 res.pkg.applicationInfo.packageName, 1045 extras, null, null, updateUsers); 1046 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1047 null, null, 1048 res.pkg.applicationInfo.packageName, null, updateUsers); 1049 1050 // treat asec-hosted packages like removable media on upgrade 1051 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1052 if (DEBUG_INSTALL) { 1053 Slog.i(TAG, "upgrading pkg " + res.pkg 1054 + " is ASEC-hosted -> AVAILABLE"); 1055 } 1056 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1057 ArrayList<String> pkgList = new ArrayList<String>(1); 1058 pkgList.add(res.pkg.applicationInfo.packageName); 1059 sendResourcesChangedBroadcast(true, true, 1060 pkgList,uidArray, null); 1061 } 1062 } 1063 if (res.removedInfo.args != null) { 1064 // Remove the replaced package's older resources safely now 1065 deleteOld = true; 1066 } 1067 1068 // Log current value of "unknown sources" setting 1069 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1070 getUnknownSourcesSettings()); 1071 } 1072 // Force a gc to clear up things 1073 Runtime.getRuntime().gc(); 1074 // We delete after a gc for applications on sdcard. 1075 if (deleteOld) { 1076 synchronized (mInstallLock) { 1077 res.removedInfo.args.doPostDeleteLI(true); 1078 } 1079 } 1080 if (args.observer != null) { 1081 try { 1082 args.observer.packageInstalled(res.name, res.returnCode); 1083 } catch (RemoteException e) { 1084 Slog.i(TAG, "Observer no longer exists."); 1085 } 1086 } 1087 if (args.observer2 != null) { 1088 try { 1089 Bundle extras = extrasForInstallResult(res); 1090 args.observer2.packageInstalled(res.name, extras, res.returnCode); 1091 } catch (RemoteException e) { 1092 Slog.i(TAG, "Observer no longer exists."); 1093 } 1094 } 1095 } else { 1096 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1097 } 1098 } break; 1099 case UPDATED_MEDIA_STATUS: { 1100 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1101 boolean reportStatus = msg.arg1 == 1; 1102 boolean doGc = msg.arg2 == 1; 1103 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1104 if (doGc) { 1105 // Force a gc to clear up stale containers. 1106 Runtime.getRuntime().gc(); 1107 } 1108 if (msg.obj != null) { 1109 @SuppressWarnings("unchecked") 1110 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1111 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1112 // Unload containers 1113 unloadAllContainers(args); 1114 } 1115 if (reportStatus) { 1116 try { 1117 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1118 PackageHelper.getMountService().finishMediaUpdate(); 1119 } catch (RemoteException e) { 1120 Log.e(TAG, "MountService not running?"); 1121 } 1122 } 1123 } break; 1124 case WRITE_SETTINGS: { 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1126 synchronized (mPackages) { 1127 removeMessages(WRITE_SETTINGS); 1128 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1129 mSettings.writeLPr(); 1130 mDirtyUsers.clear(); 1131 } 1132 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1133 } break; 1134 case WRITE_PACKAGE_RESTRICTIONS: { 1135 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1136 synchronized (mPackages) { 1137 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1138 for (int userId : mDirtyUsers) { 1139 mSettings.writePackageRestrictionsLPr(userId); 1140 } 1141 mDirtyUsers.clear(); 1142 } 1143 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1144 } break; 1145 case CHECK_PENDING_VERIFICATION: { 1146 final int verificationId = msg.arg1; 1147 final PackageVerificationState state = mPendingVerification.get(verificationId); 1148 1149 if ((state != null) && !state.timeoutExtended()) { 1150 final InstallArgs args = state.getInstallArgs(); 1151 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString()); 1152 mPendingVerification.remove(verificationId); 1153 1154 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1155 1156 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1157 Slog.i(TAG, "Continuing with installation of " 1158 + args.packageURI.toString()); 1159 state.setVerifierResponse(Binder.getCallingUid(), 1160 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1161 broadcastPackageVerified(verificationId, args.packageURI, 1162 PackageManager.VERIFICATION_ALLOW, 1163 state.getInstallArgs().getUser()); 1164 try { 1165 ret = args.copyApk(mContainerService, true); 1166 } catch (RemoteException e) { 1167 Slog.e(TAG, "Could not contact the ContainerService"); 1168 } 1169 } else { 1170 broadcastPackageVerified(verificationId, args.packageURI, 1171 PackageManager.VERIFICATION_REJECT, 1172 state.getInstallArgs().getUser()); 1173 } 1174 1175 processPendingInstall(args, ret); 1176 mHandler.sendEmptyMessage(MCS_UNBIND); 1177 } 1178 break; 1179 } 1180 case PACKAGE_VERIFIED: { 1181 final int verificationId = msg.arg1; 1182 1183 final PackageVerificationState state = mPendingVerification.get(verificationId); 1184 if (state == null) { 1185 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1186 break; 1187 } 1188 1189 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1190 1191 state.setVerifierResponse(response.callerUid, response.code); 1192 1193 if (state.isVerificationComplete()) { 1194 mPendingVerification.remove(verificationId); 1195 1196 final InstallArgs args = state.getInstallArgs(); 1197 1198 int ret; 1199 if (state.isInstallAllowed()) { 1200 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1201 broadcastPackageVerified(verificationId, args.packageURI, 1202 response.code, state.getInstallArgs().getUser()); 1203 try { 1204 ret = args.copyApk(mContainerService, true); 1205 } catch (RemoteException e) { 1206 Slog.e(TAG, "Could not contact the ContainerService"); 1207 } 1208 } else { 1209 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1210 } 1211 1212 processPendingInstall(args, ret); 1213 1214 mHandler.sendEmptyMessage(MCS_UNBIND); 1215 } 1216 1217 break; 1218 } 1219 } 1220 } 1221 } 1222 1223 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1224 Bundle extras = null; 1225 switch (res.returnCode) { 1226 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1227 extras = new Bundle(); 1228 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1229 res.origPermission); 1230 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1231 res.origPackage); 1232 break; 1233 } 1234 } 1235 return extras; 1236 } 1237 1238 void scheduleWriteSettingsLocked() { 1239 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1240 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1241 } 1242 } 1243 1244 void scheduleWritePackageRestrictionsLocked(int userId) { 1245 if (!sUserManager.exists(userId)) return; 1246 mDirtyUsers.add(userId); 1247 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1248 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1249 } 1250 } 1251 1252 public static final PackageManagerService main(Context context, Installer installer, 1253 boolean factoryTest, boolean onlyCore) { 1254 PackageManagerService m = new PackageManagerService(context, installer, 1255 factoryTest, onlyCore); 1256 ServiceManager.addService("package", m); 1257 return m; 1258 } 1259 1260 static String[] splitString(String str, char sep) { 1261 int count = 1; 1262 int i = 0; 1263 while ((i=str.indexOf(sep, i)) >= 0) { 1264 count++; 1265 i++; 1266 } 1267 1268 String[] res = new String[count]; 1269 i=0; 1270 count = 0; 1271 int lastI=0; 1272 while ((i=str.indexOf(sep, i)) >= 0) { 1273 res[count] = str.substring(lastI, i); 1274 count++; 1275 i++; 1276 lastI = i; 1277 } 1278 res[count] = str.substring(lastI, str.length()); 1279 return res; 1280 } 1281 1282 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1283 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1284 Context.DISPLAY_SERVICE); 1285 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1286 } 1287 1288 public PackageManagerService(Context context, Installer installer, 1289 boolean factoryTest, boolean onlyCore) { 1290 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1291 SystemClock.uptimeMillis()); 1292 1293 if (mSdkVersion <= 0) { 1294 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1295 } 1296 1297 mContext = context; 1298 mFactoryTest = factoryTest; 1299 mOnlyCore = onlyCore; 1300 mMetrics = new DisplayMetrics(); 1301 mSettings = new Settings(context); 1302 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1303 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1304 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1305 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1306 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1307 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1308 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1309 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1310 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1311 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1312 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1313 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1314 1315 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1316 if (separateProcesses != null && separateProcesses.length() > 0) { 1317 if ("*".equals(separateProcesses)) { 1318 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1319 mSeparateProcesses = null; 1320 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1321 } else { 1322 mDefParseFlags = 0; 1323 mSeparateProcesses = separateProcesses.split(","); 1324 Slog.w(TAG, "Running with debug.separate_processes: " 1325 + separateProcesses); 1326 } 1327 } else { 1328 mDefParseFlags = 0; 1329 mSeparateProcesses = null; 1330 } 1331 1332 mInstaller = installer; 1333 1334 getDefaultDisplayMetrics(context, mMetrics); 1335 1336 synchronized (mInstallLock) { 1337 // writer 1338 synchronized (mPackages) { 1339 mHandlerThread = new ServiceThread(TAG, 1340 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1341 mHandlerThread.start(); 1342 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1343 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1344 1345 File dataDir = Environment.getDataDirectory(); 1346 mAppDataDir = new File(dataDir, "data"); 1347 mAppInstallDir = new File(dataDir, "app"); 1348 mAppLibInstallDir = new File(dataDir, "app-lib"); 1349 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1350 mUserAppDataDir = new File(dataDir, "user"); 1351 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1352 mAppStagingDir = new File(dataDir, "app-staging"); 1353 1354 sUserManager = new UserManagerService(context, this, 1355 mInstallLock, mPackages); 1356 1357 // Read permissions and features from system 1358 readPermissions(Environment.buildPath( 1359 Environment.getRootDirectory(), "etc", "permissions"), false); 1360 // Only read features from OEM 1361 readPermissions(Environment.buildPath( 1362 Environment.getOemDirectory(), "etc", "permissions"), true); 1363 1364 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1365 1366 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1367 mSdkVersion, mOnlyCore); 1368 1369 String customResolverActivity = Resources.getSystem().getString( 1370 R.string.config_customResolverActivity); 1371 if (TextUtils.isEmpty(customResolverActivity)) { 1372 customResolverActivity = null; 1373 } else { 1374 mCustomResolverComponentName = ComponentName.unflattenFromString( 1375 customResolverActivity); 1376 } 1377 1378 long startTime = SystemClock.uptimeMillis(); 1379 1380 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1381 startTime); 1382 1383 // Set flag to monitor and not change apk file paths when 1384 // scanning install directories. 1385 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1386 1387 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1388 1389 /** 1390 * Add everything in the in the boot class path to the 1391 * list of process files because dexopt will have been run 1392 * if necessary during zygote startup. 1393 */ 1394 String bootClassPath = System.getProperty("java.boot.class.path"); 1395 if (bootClassPath != null) { 1396 String[] paths = splitString(bootClassPath, ':'); 1397 for (int i=0; i<paths.length; i++) { 1398 alreadyDexOpted.add(paths[i]); 1399 } 1400 } else { 1401 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1402 } 1403 1404 boolean didDexOptLibraryOrTool = false; 1405 1406 final List<String> instructionSets = getAllInstructionSets(); 1407 1408 /** 1409 * Ensure all external libraries have had dexopt run on them. 1410 */ 1411 if (mSharedLibraries.size() > 0) { 1412 // NOTE: For now, we're compiling these system "shared libraries" 1413 // (and framework jars) into all available architectures. It's possible 1414 // to compile them only when we come across an app that uses them (there's 1415 // already logic for that in scanPackageLI) but that adds some complexity. 1416 for (String instructionSet : instructionSets) { 1417 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1418 final String lib = libEntry.path; 1419 if (lib == null) { 1420 continue; 1421 } 1422 1423 try { 1424 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1425 alreadyDexOpted.add(lib); 1426 1427 // The list of "shared libraries" we have at this point is 1428 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1429 didDexOptLibraryOrTool = true; 1430 } 1431 } catch (FileNotFoundException e) { 1432 Slog.w(TAG, "Library not found: " + lib); 1433 } catch (IOException e) { 1434 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1435 + e.getMessage()); 1436 } 1437 } 1438 } 1439 } 1440 1441 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1442 1443 // Gross hack for now: we know this file doesn't contain any 1444 // code, so don't dexopt it to avoid the resulting log spew. 1445 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1446 1447 // Gross hack for now: we know this file is only part of 1448 // the boot class path for art, so don't dexopt it to 1449 // avoid the resulting log spew. 1450 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1451 1452 /** 1453 * And there are a number of commands implemented in Java, which 1454 * we currently need to do the dexopt on so that they can be 1455 * run from a non-root shell. 1456 */ 1457 String[] frameworkFiles = frameworkDir.list(); 1458 if (frameworkFiles != null) { 1459 // TODO: We could compile these only for the most preferred ABI. We should 1460 // first double check that the dex files for these commands are not referenced 1461 // by other system apps. 1462 for (String instructionSet : instructionSets) { 1463 for (int i=0; i<frameworkFiles.length; i++) { 1464 File libPath = new File(frameworkDir, frameworkFiles[i]); 1465 String path = libPath.getPath(); 1466 // Skip the file if we already did it. 1467 if (alreadyDexOpted.contains(path)) { 1468 continue; 1469 } 1470 // Skip the file if it is not a type we want to dexopt. 1471 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1472 continue; 1473 } 1474 try { 1475 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1476 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1477 didDexOptLibraryOrTool = true; 1478 } 1479 } catch (FileNotFoundException e) { 1480 Slog.w(TAG, "Jar not found: " + path); 1481 } catch (IOException e) { 1482 Slog.w(TAG, "Exception reading jar: " + path, e); 1483 } 1484 } 1485 } 1486 } 1487 1488 if (didDexOptLibraryOrTool) { 1489 // If we dexopted a library or tool, then something on the system has 1490 // changed. Consider this significant, and wipe away all other 1491 // existing dexopt files to ensure we don't leave any dangling around. 1492 // 1493 // Additionally, delete all dex files from the root directory 1494 // since there shouldn't be any there anyway. 1495 // 1496 // TODO: This should be revisited because it isn't as good an indicator 1497 // as it used to be. It used to include the boot classpath but at some point 1498 // DexFile.isDexOptNeeded started returning false for the boot 1499 // class path files in all cases. It is very possible in a 1500 // small maintenance release update that the library and tool 1501 // jars may be unchanged but APK could be removed resulting in 1502 // unused dalvik-cache files. 1503 mInstaller.pruneDexCache(); 1504 } 1505 1506 // Collect vendor overlay packages. 1507 // (Do this before scanning any apps.) 1508 // For security and version matching reason, only consider 1509 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1510 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1511 mVendorOverlayInstallObserver = new AppDirObserver( 1512 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1513 mVendorOverlayInstallObserver.startWatching(); 1514 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1515 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1516 1517 // Find base frameworks (resource packages without code). 1518 mFrameworkInstallObserver = new AppDirObserver( 1519 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1520 mFrameworkInstallObserver.startWatching(); 1521 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1522 | PackageParser.PARSE_IS_SYSTEM_DIR 1523 | PackageParser.PARSE_IS_PRIVILEGED, 1524 scanMode | SCAN_NO_DEX, 0); 1525 1526 // Collected privileged system packages. 1527 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1528 mPrivilegedInstallObserver = new AppDirObserver( 1529 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1530 mPrivilegedInstallObserver.startWatching(); 1531 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1532 | PackageParser.PARSE_IS_SYSTEM_DIR 1533 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1534 1535 // Collect ordinary system packages. 1536 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1537 mSystemInstallObserver = new AppDirObserver( 1538 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1539 mSystemInstallObserver.startWatching(); 1540 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1541 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1542 1543 // Collect all vendor packages. 1544 File vendorAppDir = new File("/vendor/app"); 1545 try { 1546 vendorAppDir = vendorAppDir.getCanonicalFile(); 1547 } catch (IOException e) { 1548 // failed to look up canonical path, continue with original one 1549 } 1550 mVendorInstallObserver = new AppDirObserver( 1551 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1552 mVendorInstallObserver.startWatching(); 1553 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1554 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1555 1556 // Collect all OEM packages. 1557 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1558 mOemInstallObserver = new AppDirObserver( 1559 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1560 mOemInstallObserver.startWatching(); 1561 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1562 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1563 1564 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1565 mInstaller.moveFiles(); 1566 1567 // Prune any system packages that no longer exist. 1568 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1569 if (!mOnlyCore) { 1570 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1571 while (psit.hasNext()) { 1572 PackageSetting ps = psit.next(); 1573 1574 /* 1575 * If this is not a system app, it can't be a 1576 * disable system app. 1577 */ 1578 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1579 continue; 1580 } 1581 1582 /* 1583 * If the package is scanned, it's not erased. 1584 */ 1585 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1586 if (scannedPkg != null) { 1587 /* 1588 * If the system app is both scanned and in the 1589 * disabled packages list, then it must have been 1590 * added via OTA. Remove it from the currently 1591 * scanned package so the previously user-installed 1592 * application can be scanned. 1593 */ 1594 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1595 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1596 + "; removing system app"); 1597 removePackageLI(ps, true); 1598 } 1599 1600 continue; 1601 } 1602 1603 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1604 psit.remove(); 1605 String msg = "System package " + ps.name 1606 + " no longer exists; wiping its data"; 1607 reportSettingsProblem(Log.WARN, msg); 1608 removeDataDirsLI(ps.name); 1609 } else { 1610 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1611 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1612 possiblyDeletedUpdatedSystemApps.add(ps.name); 1613 } 1614 } 1615 } 1616 } 1617 1618 //look for any incomplete package installations 1619 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1620 //clean up list 1621 for(int i = 0; i < deletePkgsList.size(); i++) { 1622 //clean up here 1623 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1624 } 1625 //delete tmp files 1626 deleteTempPackageFiles(); 1627 1628 // Remove any shared userIDs that have no associated packages 1629 mSettings.pruneSharedUsersLPw(); 1630 1631 if (!mOnlyCore) { 1632 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1633 SystemClock.uptimeMillis()); 1634 mAppInstallObserver = new AppDirObserver( 1635 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1636 mAppInstallObserver.startWatching(); 1637 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1638 1639 mDrmAppInstallObserver = new AppDirObserver( 1640 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1641 mDrmAppInstallObserver.startWatching(); 1642 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1643 scanMode, 0); 1644 1645 /** 1646 * Remove disable package settings for any updated system 1647 * apps that were removed via an OTA. If they're not a 1648 * previously-updated app, remove them completely. 1649 * Otherwise, just revoke their system-level permissions. 1650 */ 1651 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1652 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1653 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1654 1655 String msg; 1656 if (deletedPkg == null) { 1657 msg = "Updated system package " + deletedAppName 1658 + " no longer exists; wiping its data"; 1659 removeDataDirsLI(deletedAppName); 1660 } else { 1661 msg = "Updated system app + " + deletedAppName 1662 + " no longer present; removing system privileges for " 1663 + deletedAppName; 1664 1665 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1666 1667 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1668 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1669 } 1670 reportSettingsProblem(Log.WARN, msg); 1671 } 1672 } else { 1673 mAppInstallObserver = null; 1674 mDrmAppInstallObserver = null; 1675 } 1676 1677 // Now that we know all of the shared libraries, update all clients to have 1678 // the correct library paths. 1679 updateAllSharedLibrariesLPw(); 1680 1681 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1682 // NOTE: We ignore potential failures here during a system scan (like 1683 // the rest of the commands above) because there's precious little we 1684 // can do about it. A settings error is reported, though. 1685 adjustCpuAbisForSharedUserLPw(setting.packages, null, 1686 false /* force dexopt */, false /* defer dexopt */); 1687 } 1688 1689 // Now that we know all the packages we are keeping, 1690 // read and update their last usage times. 1691 mPackageUsage.readLP(); 1692 1693 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1694 SystemClock.uptimeMillis()); 1695 Slog.i(TAG, "Time to scan packages: " 1696 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1697 + " seconds"); 1698 1699 // If the platform SDK has changed since the last time we booted, 1700 // we need to re-grant app permission to catch any new ones that 1701 // appear. This is really a hack, and means that apps can in some 1702 // cases get permissions that the user didn't initially explicitly 1703 // allow... it would be nice to have some better way to handle 1704 // this situation. 1705 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1706 != mSdkVersion; 1707 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1708 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1709 + "; regranting permissions for internal storage"); 1710 mSettings.mInternalSdkPlatform = mSdkVersion; 1711 1712 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1713 | (regrantPermissions 1714 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1715 : 0)); 1716 1717 // If this is the first boot, and it is a normal boot, then 1718 // we need to initialize the default preferred apps. 1719 if (!mRestoredSettings && !onlyCore) { 1720 mSettings.readDefaultPreferredAppsLPw(this, 0); 1721 } 1722 1723 // All the changes are done during package scanning. 1724 mSettings.updateInternalDatabaseVersion(); 1725 1726 // can downgrade to reader 1727 mSettings.writeLPr(); 1728 1729 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1730 SystemClock.uptimeMillis()); 1731 1732 1733 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1734 } // synchronized (mPackages) 1735 } // synchronized (mInstallLock) 1736 1737 mInstallerService = new PackageInstallerService(context, this, mAppStagingDir); 1738 1739 // Now after opening every single application zip, make sure they 1740 // are all flushed. Not really needed, but keeps things nice and 1741 // tidy. 1742 Runtime.getRuntime().gc(); 1743 } 1744 1745 @Override 1746 public boolean isFirstBoot() { 1747 return !mRestoredSettings || mPackageUsage.isFirstBoot(); 1748 } 1749 1750 @Override 1751 public boolean isOnlyCoreApps() { 1752 return mOnlyCore; 1753 } 1754 1755 private String getRequiredVerifierLPr() { 1756 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1757 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1758 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1759 1760 String requiredVerifier = null; 1761 1762 final int N = receivers.size(); 1763 for (int i = 0; i < N; i++) { 1764 final ResolveInfo info = receivers.get(i); 1765 1766 if (info.activityInfo == null) { 1767 continue; 1768 } 1769 1770 final String packageName = info.activityInfo.packageName; 1771 1772 final PackageSetting ps = mSettings.mPackages.get(packageName); 1773 if (ps == null) { 1774 continue; 1775 } 1776 1777 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1778 if (!gp.grantedPermissions 1779 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1780 continue; 1781 } 1782 1783 if (requiredVerifier != null) { 1784 throw new RuntimeException("There can be only one required verifier"); 1785 } 1786 1787 requiredVerifier = packageName; 1788 } 1789 1790 return requiredVerifier; 1791 } 1792 1793 @Override 1794 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1795 throws RemoteException { 1796 try { 1797 return super.onTransact(code, data, reply, flags); 1798 } catch (RuntimeException e) { 1799 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1800 Slog.wtf(TAG, "Package Manager Crash", e); 1801 } 1802 throw e; 1803 } 1804 } 1805 1806 void cleanupInstallFailedPackage(PackageSetting ps) { 1807 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1808 removeDataDirsLI(ps.name); 1809 if (ps.codePath != null) { 1810 if (!ps.codePath.delete()) { 1811 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1812 } 1813 } 1814 if (ps.resourcePath != null) { 1815 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1816 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1817 } 1818 } 1819 mSettings.removePackageLPw(ps.name); 1820 } 1821 1822 void readPermissions(File libraryDir, boolean onlyFeatures) { 1823 // Read permissions from .../etc/permission directory. 1824 if (!libraryDir.exists() || !libraryDir.isDirectory()) { 1825 Slog.w(TAG, "No directory " + libraryDir + ", skipping"); 1826 return; 1827 } 1828 if (!libraryDir.canRead()) { 1829 Slog.w(TAG, "Directory " + libraryDir + " cannot be read"); 1830 return; 1831 } 1832 1833 // Iterate over the files in the directory and scan .xml files 1834 for (File f : libraryDir.listFiles()) { 1835 // We'll read platform.xml last 1836 if (f.getPath().endsWith("etc/permissions/platform.xml")) { 1837 continue; 1838 } 1839 1840 if (!f.getPath().endsWith(".xml")) { 1841 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring"); 1842 continue; 1843 } 1844 if (!f.canRead()) { 1845 Slog.w(TAG, "Permissions library file " + f + " cannot be read"); 1846 continue; 1847 } 1848 1849 readPermissionsFromXml(f, onlyFeatures); 1850 } 1851 1852 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence 1853 final File permFile = new File(Environment.getRootDirectory(), 1854 "etc/permissions/platform.xml"); 1855 readPermissionsFromXml(permFile, onlyFeatures); 1856 } 1857 1858 private void readPermissionsFromXml(File permFile, boolean onlyFeatures) { 1859 FileReader permReader = null; 1860 try { 1861 permReader = new FileReader(permFile); 1862 } catch (FileNotFoundException e) { 1863 Slog.w(TAG, "Couldn't find or open permissions file " + permFile); 1864 return; 1865 } 1866 1867 try { 1868 XmlPullParser parser = Xml.newPullParser(); 1869 parser.setInput(permReader); 1870 1871 XmlUtils.beginDocument(parser, "permissions"); 1872 1873 while (true) { 1874 XmlUtils.nextElement(parser); 1875 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) { 1876 break; 1877 } 1878 1879 String name = parser.getName(); 1880 if ("group".equals(name) && !onlyFeatures) { 1881 String gidStr = parser.getAttributeValue(null, "gid"); 1882 if (gidStr != null) { 1883 int gid = Process.getGidForName(gidStr); 1884 mGlobalGids = appendInt(mGlobalGids, gid); 1885 } else { 1886 Slog.w(TAG, "<group> without gid at " 1887 + parser.getPositionDescription()); 1888 } 1889 1890 XmlUtils.skipCurrentTag(parser); 1891 continue; 1892 } else if ("permission".equals(name) && !onlyFeatures) { 1893 String perm = parser.getAttributeValue(null, "name"); 1894 if (perm == null) { 1895 Slog.w(TAG, "<permission> without name at " 1896 + parser.getPositionDescription()); 1897 XmlUtils.skipCurrentTag(parser); 1898 continue; 1899 } 1900 perm = perm.intern(); 1901 readPermission(parser, perm); 1902 1903 } else if ("assign-permission".equals(name) && !onlyFeatures) { 1904 String perm = parser.getAttributeValue(null, "name"); 1905 if (perm == null) { 1906 Slog.w(TAG, "<assign-permission> without name at " 1907 + parser.getPositionDescription()); 1908 XmlUtils.skipCurrentTag(parser); 1909 continue; 1910 } 1911 String uidStr = parser.getAttributeValue(null, "uid"); 1912 if (uidStr == null) { 1913 Slog.w(TAG, "<assign-permission> without uid at " 1914 + parser.getPositionDescription()); 1915 XmlUtils.skipCurrentTag(parser); 1916 continue; 1917 } 1918 int uid = Process.getUidForName(uidStr); 1919 if (uid < 0) { 1920 Slog.w(TAG, "<assign-permission> with unknown uid \"" 1921 + uidStr + "\" at " 1922 + parser.getPositionDescription()); 1923 XmlUtils.skipCurrentTag(parser); 1924 continue; 1925 } 1926 perm = perm.intern(); 1927 HashSet<String> perms = mSystemPermissions.get(uid); 1928 if (perms == null) { 1929 perms = new HashSet<String>(); 1930 mSystemPermissions.put(uid, perms); 1931 } 1932 perms.add(perm); 1933 XmlUtils.skipCurrentTag(parser); 1934 1935 } else if ("library".equals(name) && !onlyFeatures) { 1936 String lname = parser.getAttributeValue(null, "name"); 1937 String lfile = parser.getAttributeValue(null, "file"); 1938 if (lname == null) { 1939 Slog.w(TAG, "<library> without name at " 1940 + parser.getPositionDescription()); 1941 } else if (lfile == null) { 1942 Slog.w(TAG, "<library> without file at " 1943 + parser.getPositionDescription()); 1944 } else { 1945 //Log.i(TAG, "Got library " + lname + " in " + lfile); 1946 mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null)); 1947 } 1948 XmlUtils.skipCurrentTag(parser); 1949 continue; 1950 1951 } else if ("feature".equals(name)) { 1952 String fname = parser.getAttributeValue(null, "name"); 1953 if (fname == null) { 1954 Slog.w(TAG, "<feature> without name at " 1955 + parser.getPositionDescription()); 1956 } else { 1957 //Log.i(TAG, "Got feature " + fname); 1958 FeatureInfo fi = new FeatureInfo(); 1959 fi.name = fname; 1960 mAvailableFeatures.put(fname, fi); 1961 } 1962 XmlUtils.skipCurrentTag(parser); 1963 continue; 1964 1965 } else { 1966 XmlUtils.skipCurrentTag(parser); 1967 continue; 1968 } 1969 1970 } 1971 permReader.close(); 1972 } catch (XmlPullParserException e) { 1973 Slog.w(TAG, "Got execption parsing permissions.", e); 1974 } catch (IOException e) { 1975 Slog.w(TAG, "Got execption parsing permissions.", e); 1976 } 1977 } 1978 1979 void readPermission(XmlPullParser parser, String name) 1980 throws IOException, XmlPullParserException { 1981 1982 name = name.intern(); 1983 1984 BasePermission bp = mSettings.mPermissions.get(name); 1985 if (bp == null) { 1986 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN); 1987 mSettings.mPermissions.put(name, bp); 1988 } 1989 int outerDepth = parser.getDepth(); 1990 int type; 1991 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 1992 && (type != XmlPullParser.END_TAG 1993 || parser.getDepth() > outerDepth)) { 1994 if (type == XmlPullParser.END_TAG 1995 || type == XmlPullParser.TEXT) { 1996 continue; 1997 } 1998 1999 String tagName = parser.getName(); 2000 if ("group".equals(tagName)) { 2001 String gidStr = parser.getAttributeValue(null, "gid"); 2002 if (gidStr != null) { 2003 int gid = Process.getGidForName(gidStr); 2004 bp.gids = appendInt(bp.gids, gid); 2005 } else { 2006 Slog.w(TAG, "<group> without gid at " 2007 + parser.getPositionDescription()); 2008 } 2009 } 2010 XmlUtils.skipCurrentTag(parser); 2011 } 2012 } 2013 2014 static int[] appendInts(int[] cur, int[] add) { 2015 if (add == null) return cur; 2016 if (cur == null) return add; 2017 final int N = add.length; 2018 for (int i=0; i<N; i++) { 2019 cur = appendInt(cur, add[i]); 2020 } 2021 return cur; 2022 } 2023 2024 static int[] removeInts(int[] cur, int[] rem) { 2025 if (rem == null) return cur; 2026 if (cur == null) return cur; 2027 final int N = rem.length; 2028 for (int i=0; i<N; i++) { 2029 cur = removeInt(cur, rem[i]); 2030 } 2031 return cur; 2032 } 2033 2034 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2035 if (!sUserManager.exists(userId)) return null; 2036 final PackageSetting ps = (PackageSetting) p.mExtras; 2037 if (ps == null) { 2038 return null; 2039 } 2040 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 2041 final PackageUserState state = ps.readUserState(userId); 2042 return PackageParser.generatePackageInfo(p, gp.gids, flags, 2043 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 2044 state, userId); 2045 } 2046 2047 @Override 2048 public boolean isPackageAvailable(String packageName, int userId) { 2049 if (!sUserManager.exists(userId)) return false; 2050 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 2051 synchronized (mPackages) { 2052 PackageParser.Package p = mPackages.get(packageName); 2053 if (p != null) { 2054 final PackageSetting ps = (PackageSetting) p.mExtras; 2055 if (ps != null) { 2056 final PackageUserState state = ps.readUserState(userId); 2057 if (state != null) { 2058 return PackageParser.isAvailable(state); 2059 } 2060 } 2061 } 2062 } 2063 return false; 2064 } 2065 2066 @Override 2067 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2068 if (!sUserManager.exists(userId)) return null; 2069 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 2070 // reader 2071 synchronized (mPackages) { 2072 PackageParser.Package p = mPackages.get(packageName); 2073 if (DEBUG_PACKAGE_INFO) 2074 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2075 if (p != null) { 2076 return generatePackageInfo(p, flags, userId); 2077 } 2078 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2079 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2080 } 2081 } 2082 return null; 2083 } 2084 2085 @Override 2086 public String[] currentToCanonicalPackageNames(String[] names) { 2087 String[] out = new String[names.length]; 2088 // reader 2089 synchronized (mPackages) { 2090 for (int i=names.length-1; i>=0; i--) { 2091 PackageSetting ps = mSettings.mPackages.get(names[i]); 2092 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2093 } 2094 } 2095 return out; 2096 } 2097 2098 @Override 2099 public String[] canonicalToCurrentPackageNames(String[] names) { 2100 String[] out = new String[names.length]; 2101 // reader 2102 synchronized (mPackages) { 2103 for (int i=names.length-1; i>=0; i--) { 2104 String cur = mSettings.mRenamedPackages.get(names[i]); 2105 out[i] = cur != null ? cur : names[i]; 2106 } 2107 } 2108 return out; 2109 } 2110 2111 @Override 2112 public int getPackageUid(String packageName, int userId) { 2113 if (!sUserManager.exists(userId)) return -1; 2114 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 2115 // reader 2116 synchronized (mPackages) { 2117 PackageParser.Package p = mPackages.get(packageName); 2118 if(p != null) { 2119 return UserHandle.getUid(userId, p.applicationInfo.uid); 2120 } 2121 PackageSetting ps = mSettings.mPackages.get(packageName); 2122 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2123 return -1; 2124 } 2125 p = ps.pkg; 2126 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2127 } 2128 } 2129 2130 @Override 2131 public int[] getPackageGids(String packageName) { 2132 // reader 2133 synchronized (mPackages) { 2134 PackageParser.Package p = mPackages.get(packageName); 2135 if (DEBUG_PACKAGE_INFO) 2136 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2137 if (p != null) { 2138 final PackageSetting ps = (PackageSetting)p.mExtras; 2139 return ps.getGids(); 2140 } 2141 } 2142 // stupid thing to indicate an error. 2143 return new int[0]; 2144 } 2145 2146 static final PermissionInfo generatePermissionInfo( 2147 BasePermission bp, int flags) { 2148 if (bp.perm != null) { 2149 return PackageParser.generatePermissionInfo(bp.perm, flags); 2150 } 2151 PermissionInfo pi = new PermissionInfo(); 2152 pi.name = bp.name; 2153 pi.packageName = bp.sourcePackage; 2154 pi.nonLocalizedLabel = bp.name; 2155 pi.protectionLevel = bp.protectionLevel; 2156 return pi; 2157 } 2158 2159 @Override 2160 public PermissionInfo getPermissionInfo(String name, int flags) { 2161 // reader 2162 synchronized (mPackages) { 2163 final BasePermission p = mSettings.mPermissions.get(name); 2164 if (p != null) { 2165 return generatePermissionInfo(p, flags); 2166 } 2167 return null; 2168 } 2169 } 2170 2171 @Override 2172 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2173 // reader 2174 synchronized (mPackages) { 2175 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2176 for (BasePermission p : mSettings.mPermissions.values()) { 2177 if (group == null) { 2178 if (p.perm == null || p.perm.info.group == null) { 2179 out.add(generatePermissionInfo(p, flags)); 2180 } 2181 } else { 2182 if (p.perm != null && group.equals(p.perm.info.group)) { 2183 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2184 } 2185 } 2186 } 2187 2188 if (out.size() > 0) { 2189 return out; 2190 } 2191 return mPermissionGroups.containsKey(group) ? out : null; 2192 } 2193 } 2194 2195 @Override 2196 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2197 // reader 2198 synchronized (mPackages) { 2199 return PackageParser.generatePermissionGroupInfo( 2200 mPermissionGroups.get(name), flags); 2201 } 2202 } 2203 2204 @Override 2205 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2206 // reader 2207 synchronized (mPackages) { 2208 final int N = mPermissionGroups.size(); 2209 ArrayList<PermissionGroupInfo> out 2210 = new ArrayList<PermissionGroupInfo>(N); 2211 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2212 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2213 } 2214 return out; 2215 } 2216 } 2217 2218 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2219 int userId) { 2220 if (!sUserManager.exists(userId)) return null; 2221 PackageSetting ps = mSettings.mPackages.get(packageName); 2222 if (ps != null) { 2223 if (ps.pkg == null) { 2224 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2225 flags, userId); 2226 if (pInfo != null) { 2227 return pInfo.applicationInfo; 2228 } 2229 return null; 2230 } 2231 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2232 ps.readUserState(userId), userId); 2233 } 2234 return null; 2235 } 2236 2237 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2238 int userId) { 2239 if (!sUserManager.exists(userId)) return null; 2240 PackageSetting ps = mSettings.mPackages.get(packageName); 2241 if (ps != null) { 2242 PackageParser.Package pkg = ps.pkg; 2243 if (pkg == null) { 2244 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2245 return null; 2246 } 2247 // App code is gone, so we aren't worried about split paths 2248 pkg = new PackageParser.Package(packageName); 2249 pkg.applicationInfo.packageName = packageName; 2250 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2251 pkg.applicationInfo.sourceDir = ps.codePathString; 2252 pkg.applicationInfo.publicSourceDir = ps.resourcePathString; 2253 pkg.applicationInfo.dataDir = 2254 getDataPathForPackage(packageName, 0).getPath(); 2255 pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString; 2256 pkg.applicationInfo.cpuAbi = ps.cpuAbiString; 2257 } 2258 return generatePackageInfo(pkg, flags, userId); 2259 } 2260 return null; 2261 } 2262 2263 @Override 2264 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2265 if (!sUserManager.exists(userId)) return null; 2266 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2267 // writer 2268 synchronized (mPackages) { 2269 PackageParser.Package p = mPackages.get(packageName); 2270 if (DEBUG_PACKAGE_INFO) Log.v( 2271 TAG, "getApplicationInfo " + packageName 2272 + ": " + p); 2273 if (p != null) { 2274 PackageSetting ps = mSettings.mPackages.get(packageName); 2275 if (ps == null) return null; 2276 // Note: isEnabledLP() does not apply here - always return info 2277 return PackageParser.generateApplicationInfo( 2278 p, flags, ps.readUserState(userId), userId); 2279 } 2280 if ("android".equals(packageName)||"system".equals(packageName)) { 2281 return mAndroidApplication; 2282 } 2283 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2284 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2285 } 2286 } 2287 return null; 2288 } 2289 2290 2291 @Override 2292 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2293 mContext.enforceCallingOrSelfPermission( 2294 android.Manifest.permission.CLEAR_APP_CACHE, null); 2295 // Queue up an async operation since clearing cache may take a little while. 2296 mHandler.post(new Runnable() { 2297 public void run() { 2298 mHandler.removeCallbacks(this); 2299 int retCode = -1; 2300 synchronized (mInstallLock) { 2301 retCode = mInstaller.freeCache(freeStorageSize); 2302 if (retCode < 0) { 2303 Slog.w(TAG, "Couldn't clear application caches"); 2304 } 2305 } 2306 if (observer != null) { 2307 try { 2308 observer.onRemoveCompleted(null, (retCode >= 0)); 2309 } catch (RemoteException e) { 2310 Slog.w(TAG, "RemoveException when invoking call back"); 2311 } 2312 } 2313 } 2314 }); 2315 } 2316 2317 @Override 2318 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2319 mContext.enforceCallingOrSelfPermission( 2320 android.Manifest.permission.CLEAR_APP_CACHE, null); 2321 // Queue up an async operation since clearing cache may take a little while. 2322 mHandler.post(new Runnable() { 2323 public void run() { 2324 mHandler.removeCallbacks(this); 2325 int retCode = -1; 2326 synchronized (mInstallLock) { 2327 retCode = mInstaller.freeCache(freeStorageSize); 2328 if (retCode < 0) { 2329 Slog.w(TAG, "Couldn't clear application caches"); 2330 } 2331 } 2332 if(pi != null) { 2333 try { 2334 // Callback via pending intent 2335 int code = (retCode >= 0) ? 1 : 0; 2336 pi.sendIntent(null, code, null, 2337 null, null); 2338 } catch (SendIntentException e1) { 2339 Slog.i(TAG, "Failed to send pending intent"); 2340 } 2341 } 2342 } 2343 }); 2344 } 2345 2346 void freeStorage(long freeStorageSize) throws IOException { 2347 synchronized (mInstallLock) { 2348 if (mInstaller.freeCache(freeStorageSize) < 0) { 2349 throw new IOException("Failed to free enough space"); 2350 } 2351 } 2352 } 2353 2354 @Override 2355 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2356 if (!sUserManager.exists(userId)) return null; 2357 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2358 synchronized (mPackages) { 2359 PackageParser.Activity a = mActivities.mActivities.get(component); 2360 2361 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2362 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2363 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2364 if (ps == null) return null; 2365 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2366 userId); 2367 } 2368 if (mResolveComponentName.equals(component)) { 2369 return mResolveActivity; 2370 } 2371 } 2372 return null; 2373 } 2374 2375 @Override 2376 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2377 String resolvedType) { 2378 synchronized (mPackages) { 2379 PackageParser.Activity a = mActivities.mActivities.get(component); 2380 if (a == null) { 2381 return false; 2382 } 2383 for (int i=0; i<a.intents.size(); i++) { 2384 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2385 intent.getData(), intent.getCategories(), TAG) >= 0) { 2386 return true; 2387 } 2388 } 2389 return false; 2390 } 2391 } 2392 2393 @Override 2394 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2395 if (!sUserManager.exists(userId)) return null; 2396 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2397 synchronized (mPackages) { 2398 PackageParser.Activity a = mReceivers.mActivities.get(component); 2399 if (DEBUG_PACKAGE_INFO) Log.v( 2400 TAG, "getReceiverInfo " + component + ": " + a); 2401 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2402 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2403 if (ps == null) return null; 2404 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2405 userId); 2406 } 2407 } 2408 return null; 2409 } 2410 2411 @Override 2412 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2413 if (!sUserManager.exists(userId)) return null; 2414 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2415 synchronized (mPackages) { 2416 PackageParser.Service s = mServices.mServices.get(component); 2417 if (DEBUG_PACKAGE_INFO) Log.v( 2418 TAG, "getServiceInfo " + component + ": " + s); 2419 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2420 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2421 if (ps == null) return null; 2422 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2423 userId); 2424 } 2425 } 2426 return null; 2427 } 2428 2429 @Override 2430 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2431 if (!sUserManager.exists(userId)) return null; 2432 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2433 synchronized (mPackages) { 2434 PackageParser.Provider p = mProviders.mProviders.get(component); 2435 if (DEBUG_PACKAGE_INFO) Log.v( 2436 TAG, "getProviderInfo " + component + ": " + p); 2437 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2438 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2439 if (ps == null) return null; 2440 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2441 userId); 2442 } 2443 } 2444 return null; 2445 } 2446 2447 @Override 2448 public String[] getSystemSharedLibraryNames() { 2449 Set<String> libSet; 2450 synchronized (mPackages) { 2451 libSet = mSharedLibraries.keySet(); 2452 int size = libSet.size(); 2453 if (size > 0) { 2454 String[] libs = new String[size]; 2455 libSet.toArray(libs); 2456 return libs; 2457 } 2458 } 2459 return null; 2460 } 2461 2462 @Override 2463 public FeatureInfo[] getSystemAvailableFeatures() { 2464 Collection<FeatureInfo> featSet; 2465 synchronized (mPackages) { 2466 featSet = mAvailableFeatures.values(); 2467 int size = featSet.size(); 2468 if (size > 0) { 2469 FeatureInfo[] features = new FeatureInfo[size+1]; 2470 featSet.toArray(features); 2471 FeatureInfo fi = new FeatureInfo(); 2472 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2473 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2474 features[size] = fi; 2475 return features; 2476 } 2477 } 2478 return null; 2479 } 2480 2481 @Override 2482 public boolean hasSystemFeature(String name) { 2483 synchronized (mPackages) { 2484 return mAvailableFeatures.containsKey(name); 2485 } 2486 } 2487 2488 private void checkValidCaller(int uid, int userId) { 2489 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2490 return; 2491 2492 throw new SecurityException("Caller uid=" + uid 2493 + " is not privileged to communicate with user=" + userId); 2494 } 2495 2496 @Override 2497 public int checkPermission(String permName, String pkgName) { 2498 synchronized (mPackages) { 2499 PackageParser.Package p = mPackages.get(pkgName); 2500 if (p != null && p.mExtras != null) { 2501 PackageSetting ps = (PackageSetting)p.mExtras; 2502 if (ps.sharedUser != null) { 2503 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2504 return PackageManager.PERMISSION_GRANTED; 2505 } 2506 } else if (ps.grantedPermissions.contains(permName)) { 2507 return PackageManager.PERMISSION_GRANTED; 2508 } 2509 } 2510 } 2511 return PackageManager.PERMISSION_DENIED; 2512 } 2513 2514 @Override 2515 public int checkUidPermission(String permName, int uid) { 2516 synchronized (mPackages) { 2517 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2518 if (obj != null) { 2519 GrantedPermissions gp = (GrantedPermissions)obj; 2520 if (gp.grantedPermissions.contains(permName)) { 2521 return PackageManager.PERMISSION_GRANTED; 2522 } 2523 } else { 2524 HashSet<String> perms = mSystemPermissions.get(uid); 2525 if (perms != null && perms.contains(permName)) { 2526 return PackageManager.PERMISSION_GRANTED; 2527 } 2528 } 2529 } 2530 return PackageManager.PERMISSION_DENIED; 2531 } 2532 2533 /** 2534 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2535 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2536 * @param message the message to log on security exception 2537 */ 2538 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2539 String message) { 2540 if (userId < 0) { 2541 throw new IllegalArgumentException("Invalid userId " + userId); 2542 } 2543 if (userId == UserHandle.getUserId(callingUid)) return; 2544 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2545 if (requireFullPermission) { 2546 mContext.enforceCallingOrSelfPermission( 2547 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2548 } else { 2549 try { 2550 mContext.enforceCallingOrSelfPermission( 2551 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2552 } catch (SecurityException se) { 2553 mContext.enforceCallingOrSelfPermission( 2554 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2555 } 2556 } 2557 } 2558 } 2559 2560 private BasePermission findPermissionTreeLP(String permName) { 2561 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2562 if (permName.startsWith(bp.name) && 2563 permName.length() > bp.name.length() && 2564 permName.charAt(bp.name.length()) == '.') { 2565 return bp; 2566 } 2567 } 2568 return null; 2569 } 2570 2571 private BasePermission checkPermissionTreeLP(String permName) { 2572 if (permName != null) { 2573 BasePermission bp = findPermissionTreeLP(permName); 2574 if (bp != null) { 2575 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2576 return bp; 2577 } 2578 throw new SecurityException("Calling uid " 2579 + Binder.getCallingUid() 2580 + " is not allowed to add to permission tree " 2581 + bp.name + " owned by uid " + bp.uid); 2582 } 2583 } 2584 throw new SecurityException("No permission tree found for " + permName); 2585 } 2586 2587 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2588 if (s1 == null) { 2589 return s2 == null; 2590 } 2591 if (s2 == null) { 2592 return false; 2593 } 2594 if (s1.getClass() != s2.getClass()) { 2595 return false; 2596 } 2597 return s1.equals(s2); 2598 } 2599 2600 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2601 if (pi1.icon != pi2.icon) return false; 2602 if (pi1.logo != pi2.logo) return false; 2603 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2604 if (!compareStrings(pi1.name, pi2.name)) return false; 2605 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2606 // We'll take care of setting this one. 2607 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2608 // These are not currently stored in settings. 2609 //if (!compareStrings(pi1.group, pi2.group)) return false; 2610 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2611 //if (pi1.labelRes != pi2.labelRes) return false; 2612 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2613 return true; 2614 } 2615 2616 int permissionInfoFootprint(PermissionInfo info) { 2617 int size = info.name.length(); 2618 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2619 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2620 return size; 2621 } 2622 2623 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2624 int size = 0; 2625 for (BasePermission perm : mSettings.mPermissions.values()) { 2626 if (perm.uid == tree.uid) { 2627 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2628 } 2629 } 2630 return size; 2631 } 2632 2633 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2634 // We calculate the max size of permissions defined by this uid and throw 2635 // if that plus the size of 'info' would exceed our stated maximum. 2636 if (tree.uid != Process.SYSTEM_UID) { 2637 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2638 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2639 throw new SecurityException("Permission tree size cap exceeded"); 2640 } 2641 } 2642 } 2643 2644 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2645 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2646 throw new SecurityException("Label must be specified in permission"); 2647 } 2648 BasePermission tree = checkPermissionTreeLP(info.name); 2649 BasePermission bp = mSettings.mPermissions.get(info.name); 2650 boolean added = bp == null; 2651 boolean changed = true; 2652 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2653 if (added) { 2654 enforcePermissionCapLocked(info, tree); 2655 bp = new BasePermission(info.name, tree.sourcePackage, 2656 BasePermission.TYPE_DYNAMIC); 2657 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2658 throw new SecurityException( 2659 "Not allowed to modify non-dynamic permission " 2660 + info.name); 2661 } else { 2662 if (bp.protectionLevel == fixedLevel 2663 && bp.perm.owner.equals(tree.perm.owner) 2664 && bp.uid == tree.uid 2665 && comparePermissionInfos(bp.perm.info, info)) { 2666 changed = false; 2667 } 2668 } 2669 bp.protectionLevel = fixedLevel; 2670 info = new PermissionInfo(info); 2671 info.protectionLevel = fixedLevel; 2672 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2673 bp.perm.info.packageName = tree.perm.info.packageName; 2674 bp.uid = tree.uid; 2675 if (added) { 2676 mSettings.mPermissions.put(info.name, bp); 2677 } 2678 if (changed) { 2679 if (!async) { 2680 mSettings.writeLPr(); 2681 } else { 2682 scheduleWriteSettingsLocked(); 2683 } 2684 } 2685 return added; 2686 } 2687 2688 @Override 2689 public boolean addPermission(PermissionInfo info) { 2690 synchronized (mPackages) { 2691 return addPermissionLocked(info, false); 2692 } 2693 } 2694 2695 @Override 2696 public boolean addPermissionAsync(PermissionInfo info) { 2697 synchronized (mPackages) { 2698 return addPermissionLocked(info, true); 2699 } 2700 } 2701 2702 @Override 2703 public void removePermission(String name) { 2704 synchronized (mPackages) { 2705 checkPermissionTreeLP(name); 2706 BasePermission bp = mSettings.mPermissions.get(name); 2707 if (bp != null) { 2708 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2709 throw new SecurityException( 2710 "Not allowed to modify non-dynamic permission " 2711 + name); 2712 } 2713 mSettings.mPermissions.remove(name); 2714 mSettings.writeLPr(); 2715 } 2716 } 2717 } 2718 2719 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2720 int index = pkg.requestedPermissions.indexOf(bp.name); 2721 if (index == -1) { 2722 throw new SecurityException("Package " + pkg.packageName 2723 + " has not requested permission " + bp.name); 2724 } 2725 boolean isNormal = 2726 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2727 == PermissionInfo.PROTECTION_NORMAL); 2728 boolean isDangerous = 2729 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2730 == PermissionInfo.PROTECTION_DANGEROUS); 2731 boolean isDevelopment = 2732 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2733 2734 if (!isNormal && !isDangerous && !isDevelopment) { 2735 throw new SecurityException("Permission " + bp.name 2736 + " is not a changeable permission type"); 2737 } 2738 2739 if (isNormal || isDangerous) { 2740 if (pkg.requestedPermissionsRequired.get(index)) { 2741 throw new SecurityException("Can't change " + bp.name 2742 + ". It is required by the application"); 2743 } 2744 } 2745 } 2746 2747 @Override 2748 public void grantPermission(String packageName, String permissionName) { 2749 mContext.enforceCallingOrSelfPermission( 2750 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2751 synchronized (mPackages) { 2752 final PackageParser.Package pkg = mPackages.get(packageName); 2753 if (pkg == null) { 2754 throw new IllegalArgumentException("Unknown package: " + packageName); 2755 } 2756 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2757 if (bp == null) { 2758 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2759 } 2760 2761 checkGrantRevokePermissions(pkg, bp); 2762 2763 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2764 if (ps == null) { 2765 return; 2766 } 2767 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2768 if (gp.grantedPermissions.add(permissionName)) { 2769 if (ps.haveGids) { 2770 gp.gids = appendInts(gp.gids, bp.gids); 2771 } 2772 mSettings.writeLPr(); 2773 } 2774 } 2775 } 2776 2777 @Override 2778 public void revokePermission(String packageName, String permissionName) { 2779 int changedAppId = -1; 2780 2781 synchronized (mPackages) { 2782 final PackageParser.Package pkg = mPackages.get(packageName); 2783 if (pkg == null) { 2784 throw new IllegalArgumentException("Unknown package: " + packageName); 2785 } 2786 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2787 mContext.enforceCallingOrSelfPermission( 2788 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2789 } 2790 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2791 if (bp == null) { 2792 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2793 } 2794 2795 checkGrantRevokePermissions(pkg, bp); 2796 2797 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2798 if (ps == null) { 2799 return; 2800 } 2801 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2802 if (gp.grantedPermissions.remove(permissionName)) { 2803 gp.grantedPermissions.remove(permissionName); 2804 if (ps.haveGids) { 2805 gp.gids = removeInts(gp.gids, bp.gids); 2806 } 2807 mSettings.writeLPr(); 2808 changedAppId = ps.appId; 2809 } 2810 } 2811 2812 if (changedAppId >= 0) { 2813 // We changed the perm on someone, kill its processes. 2814 IActivityManager am = ActivityManagerNative.getDefault(); 2815 if (am != null) { 2816 final int callingUserId = UserHandle.getCallingUserId(); 2817 final long ident = Binder.clearCallingIdentity(); 2818 try { 2819 //XXX we should only revoke for the calling user's app permissions, 2820 // but for now we impact all users. 2821 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2822 // "revoke " + permissionName); 2823 int[] users = sUserManager.getUserIds(); 2824 for (int user : users) { 2825 am.killUid(UserHandle.getUid(user, changedAppId), 2826 "revoke " + permissionName); 2827 } 2828 } catch (RemoteException e) { 2829 } finally { 2830 Binder.restoreCallingIdentity(ident); 2831 } 2832 } 2833 } 2834 } 2835 2836 @Override 2837 public boolean isProtectedBroadcast(String actionName) { 2838 synchronized (mPackages) { 2839 return mProtectedBroadcasts.contains(actionName); 2840 } 2841 } 2842 2843 @Override 2844 public int checkSignatures(String pkg1, String pkg2) { 2845 synchronized (mPackages) { 2846 final PackageParser.Package p1 = mPackages.get(pkg1); 2847 final PackageParser.Package p2 = mPackages.get(pkg2); 2848 if (p1 == null || p1.mExtras == null 2849 || p2 == null || p2.mExtras == null) { 2850 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2851 } 2852 return compareSignatures(p1.mSignatures, p2.mSignatures); 2853 } 2854 } 2855 2856 @Override 2857 public int checkUidSignatures(int uid1, int uid2) { 2858 // Map to base uids. 2859 uid1 = UserHandle.getAppId(uid1); 2860 uid2 = UserHandle.getAppId(uid2); 2861 // reader 2862 synchronized (mPackages) { 2863 Signature[] s1; 2864 Signature[] s2; 2865 Object obj = mSettings.getUserIdLPr(uid1); 2866 if (obj != null) { 2867 if (obj instanceof SharedUserSetting) { 2868 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2869 } else if (obj instanceof PackageSetting) { 2870 s1 = ((PackageSetting)obj).signatures.mSignatures; 2871 } else { 2872 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2873 } 2874 } else { 2875 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2876 } 2877 obj = mSettings.getUserIdLPr(uid2); 2878 if (obj != null) { 2879 if (obj instanceof SharedUserSetting) { 2880 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2881 } else if (obj instanceof PackageSetting) { 2882 s2 = ((PackageSetting)obj).signatures.mSignatures; 2883 } else { 2884 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2885 } 2886 } else { 2887 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2888 } 2889 return compareSignatures(s1, s2); 2890 } 2891 } 2892 2893 /** 2894 * Compares two sets of signatures. Returns: 2895 * <br /> 2896 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2897 * <br /> 2898 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2899 * <br /> 2900 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2901 * <br /> 2902 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2903 * <br /> 2904 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2905 */ 2906 static int compareSignatures(Signature[] s1, Signature[] s2) { 2907 if (s1 == null) { 2908 return s2 == null 2909 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2910 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2911 } 2912 2913 if (s2 == null) { 2914 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2915 } 2916 2917 if (s1.length != s2.length) { 2918 return PackageManager.SIGNATURE_NO_MATCH; 2919 } 2920 2921 // Since both signature sets are of size 1, we can compare without HashSets. 2922 if (s1.length == 1) { 2923 return s1[0].equals(s2[0]) ? 2924 PackageManager.SIGNATURE_MATCH : 2925 PackageManager.SIGNATURE_NO_MATCH; 2926 } 2927 2928 HashSet<Signature> set1 = new HashSet<Signature>(); 2929 for (Signature sig : s1) { 2930 set1.add(sig); 2931 } 2932 HashSet<Signature> set2 = new HashSet<Signature>(); 2933 for (Signature sig : s2) { 2934 set2.add(sig); 2935 } 2936 // Make sure s2 contains all signatures in s1. 2937 if (set1.equals(set2)) { 2938 return PackageManager.SIGNATURE_MATCH; 2939 } 2940 return PackageManager.SIGNATURE_NO_MATCH; 2941 } 2942 2943 /** 2944 * If the database version for this type of package (internal storage or 2945 * external storage) is less than the version where package signatures 2946 * were updated, return true. 2947 */ 2948 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2949 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2950 DatabaseVersion.SIGNATURE_END_ENTITY)) 2951 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2952 DatabaseVersion.SIGNATURE_END_ENTITY)); 2953 } 2954 2955 /** 2956 * Used for backward compatibility to make sure any packages with 2957 * certificate chains get upgraded to the new style. {@code existingSigs} 2958 * will be in the old format (since they were stored on disk from before the 2959 * system upgrade) and {@code scannedSigs} will be in the newer format. 2960 */ 2961 private int compareSignaturesCompat(PackageSignatures existingSigs, 2962 PackageParser.Package scannedPkg) { 2963 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2964 return PackageManager.SIGNATURE_NO_MATCH; 2965 } 2966 2967 HashSet<Signature> existingSet = new HashSet<Signature>(); 2968 for (Signature sig : existingSigs.mSignatures) { 2969 existingSet.add(sig); 2970 } 2971 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2972 for (Signature sig : scannedPkg.mSignatures) { 2973 try { 2974 Signature[] chainSignatures = sig.getChainSignatures(); 2975 for (Signature chainSig : chainSignatures) { 2976 scannedCompatSet.add(chainSig); 2977 } 2978 } catch (CertificateEncodingException e) { 2979 scannedCompatSet.add(sig); 2980 } 2981 } 2982 /* 2983 * Make sure the expanded scanned set contains all signatures in the 2984 * existing one. 2985 */ 2986 if (scannedCompatSet.equals(existingSet)) { 2987 // Migrate the old signatures to the new scheme. 2988 existingSigs.assignSignatures(scannedPkg.mSignatures); 2989 // The new KeySets will be re-added later in the scanning process. 2990 mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName); 2991 return PackageManager.SIGNATURE_MATCH; 2992 } 2993 return PackageManager.SIGNATURE_NO_MATCH; 2994 } 2995 2996 @Override 2997 public String[] getPackagesForUid(int uid) { 2998 uid = UserHandle.getAppId(uid); 2999 // reader 3000 synchronized (mPackages) { 3001 Object obj = mSettings.getUserIdLPr(uid); 3002 if (obj instanceof SharedUserSetting) { 3003 final SharedUserSetting sus = (SharedUserSetting) obj; 3004 final int N = sus.packages.size(); 3005 final String[] res = new String[N]; 3006 final Iterator<PackageSetting> it = sus.packages.iterator(); 3007 int i = 0; 3008 while (it.hasNext()) { 3009 res[i++] = it.next().name; 3010 } 3011 return res; 3012 } else if (obj instanceof PackageSetting) { 3013 final PackageSetting ps = (PackageSetting) obj; 3014 return new String[] { ps.name }; 3015 } 3016 } 3017 return null; 3018 } 3019 3020 @Override 3021 public String getNameForUid(int uid) { 3022 // reader 3023 synchronized (mPackages) { 3024 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3025 if (obj instanceof SharedUserSetting) { 3026 final SharedUserSetting sus = (SharedUserSetting) obj; 3027 return sus.name + ":" + sus.userId; 3028 } else if (obj instanceof PackageSetting) { 3029 final PackageSetting ps = (PackageSetting) obj; 3030 return ps.name; 3031 } 3032 } 3033 return null; 3034 } 3035 3036 @Override 3037 public int getUidForSharedUser(String sharedUserName) { 3038 if(sharedUserName == null) { 3039 return -1; 3040 } 3041 // reader 3042 synchronized (mPackages) { 3043 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 3044 if (suid == null) { 3045 return -1; 3046 } 3047 return suid.userId; 3048 } 3049 } 3050 3051 @Override 3052 public int getFlagsForUid(int uid) { 3053 synchronized (mPackages) { 3054 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3055 if (obj instanceof SharedUserSetting) { 3056 final SharedUserSetting sus = (SharedUserSetting) obj; 3057 return sus.pkgFlags; 3058 } else if (obj instanceof PackageSetting) { 3059 final PackageSetting ps = (PackageSetting) obj; 3060 return ps.pkgFlags; 3061 } 3062 } 3063 return 0; 3064 } 3065 3066 @Override 3067 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3068 int flags, int userId) { 3069 if (!sUserManager.exists(userId)) return null; 3070 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 3071 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3072 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3073 } 3074 3075 @Override 3076 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3077 IntentFilter filter, int match, ComponentName activity) { 3078 final int userId = UserHandle.getCallingUserId(); 3079 if (DEBUG_PREFERRED) { 3080 Log.v(TAG, "setLastChosenActivity intent=" + intent 3081 + " resolvedType=" + resolvedType 3082 + " flags=" + flags 3083 + " filter=" + filter 3084 + " match=" + match 3085 + " activity=" + activity); 3086 filter.dump(new PrintStreamPrinter(System.out), " "); 3087 } 3088 intent.setComponent(null); 3089 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3090 // Find any earlier preferred or last chosen entries and nuke them 3091 findPreferredActivity(intent, resolvedType, 3092 flags, query, 0, false, true, false, userId); 3093 // Add the new activity as the last chosen for this filter 3094 addPreferredActivityInternal(filter, match, null, activity, false, userId); 3095 } 3096 3097 @Override 3098 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3099 final int userId = UserHandle.getCallingUserId(); 3100 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3101 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3102 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3103 false, false, false, userId); 3104 } 3105 3106 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3107 int flags, List<ResolveInfo> query, int userId) { 3108 if (query != null) { 3109 final int N = query.size(); 3110 if (N == 1) { 3111 return query.get(0); 3112 } else if (N > 1) { 3113 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3114 // If there is more than one activity with the same priority, 3115 // then let the user decide between them. 3116 ResolveInfo r0 = query.get(0); 3117 ResolveInfo r1 = query.get(1); 3118 if (DEBUG_INTENT_MATCHING || debug) { 3119 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3120 + r1.activityInfo.name + "=" + r1.priority); 3121 } 3122 // If the first activity has a higher priority, or a different 3123 // default, then it is always desireable to pick it. 3124 if (r0.priority != r1.priority 3125 || r0.preferredOrder != r1.preferredOrder 3126 || r0.isDefault != r1.isDefault) { 3127 return query.get(0); 3128 } 3129 // If we have saved a preference for a preferred activity for 3130 // this Intent, use that. 3131 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3132 flags, query, r0.priority, true, false, debug, userId); 3133 if (ri != null) { 3134 return ri; 3135 } 3136 if (userId != 0) { 3137 ri = new ResolveInfo(mResolveInfo); 3138 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3139 ri.activityInfo.applicationInfo = new ApplicationInfo( 3140 ri.activityInfo.applicationInfo); 3141 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3142 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3143 return ri; 3144 } 3145 return mResolveInfo; 3146 } 3147 } 3148 return null; 3149 } 3150 3151 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3152 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3153 final int N = query.size(); 3154 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3155 .get(userId); 3156 // Get the list of persistent preferred activities that handle the intent 3157 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3158 List<PersistentPreferredActivity> pprefs = ppir != null 3159 ? ppir.queryIntent(intent, resolvedType, 3160 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3161 : null; 3162 if (pprefs != null && pprefs.size() > 0) { 3163 final int M = pprefs.size(); 3164 for (int i=0; i<M; i++) { 3165 final PersistentPreferredActivity ppa = pprefs.get(i); 3166 if (DEBUG_PREFERRED || debug) { 3167 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3168 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3169 + "\n component=" + ppa.mComponent); 3170 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3171 } 3172 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3173 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3174 if (DEBUG_PREFERRED || debug) { 3175 Slog.v(TAG, "Found persistent preferred activity:"); 3176 if (ai != null) { 3177 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3178 } else { 3179 Slog.v(TAG, " null"); 3180 } 3181 } 3182 if (ai == null) { 3183 // This previously registered persistent preferred activity 3184 // component is no longer known. Ignore it and do NOT remove it. 3185 continue; 3186 } 3187 for (int j=0; j<N; j++) { 3188 final ResolveInfo ri = query.get(j); 3189 if (!ri.activityInfo.applicationInfo.packageName 3190 .equals(ai.applicationInfo.packageName)) { 3191 continue; 3192 } 3193 if (!ri.activityInfo.name.equals(ai.name)) { 3194 continue; 3195 } 3196 // Found a persistent preference that can handle the intent. 3197 if (DEBUG_PREFERRED || debug) { 3198 Slog.v(TAG, "Returning persistent preferred activity: " + 3199 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3200 } 3201 return ri; 3202 } 3203 } 3204 } 3205 return null; 3206 } 3207 3208 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3209 List<ResolveInfo> query, int priority, boolean always, 3210 boolean removeMatches, boolean debug, int userId) { 3211 if (!sUserManager.exists(userId)) return null; 3212 // writer 3213 synchronized (mPackages) { 3214 if (intent.getSelector() != null) { 3215 intent = intent.getSelector(); 3216 } 3217 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3218 3219 // Try to find a matching persistent preferred activity. 3220 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3221 debug, userId); 3222 3223 // If a persistent preferred activity matched, use it. 3224 if (pri != null) { 3225 return pri; 3226 } 3227 3228 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3229 // Get the list of preferred activities that handle the intent 3230 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3231 List<PreferredActivity> prefs = pir != null 3232 ? pir.queryIntent(intent, resolvedType, 3233 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3234 : null; 3235 if (prefs != null && prefs.size() > 0) { 3236 // First figure out how good the original match set is. 3237 // We will only allow preferred activities that came 3238 // from the same match quality. 3239 int match = 0; 3240 3241 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3242 3243 final int N = query.size(); 3244 for (int j=0; j<N; j++) { 3245 final ResolveInfo ri = query.get(j); 3246 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3247 + ": 0x" + Integer.toHexString(match)); 3248 if (ri.match > match) { 3249 match = ri.match; 3250 } 3251 } 3252 3253 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3254 + Integer.toHexString(match)); 3255 3256 match &= IntentFilter.MATCH_CATEGORY_MASK; 3257 final int M = prefs.size(); 3258 for (int i=0; i<M; i++) { 3259 final PreferredActivity pa = prefs.get(i); 3260 if (DEBUG_PREFERRED || debug) { 3261 Slog.v(TAG, "Checking PreferredActivity ds=" 3262 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3263 + "\n component=" + pa.mPref.mComponent); 3264 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3265 } 3266 if (pa.mPref.mMatch != match) { 3267 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3268 + Integer.toHexString(pa.mPref.mMatch)); 3269 continue; 3270 } 3271 // If it's not an "always" type preferred activity and that's what we're 3272 // looking for, skip it. 3273 if (always && !pa.mPref.mAlways) { 3274 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3275 continue; 3276 } 3277 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3278 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3279 if (DEBUG_PREFERRED || debug) { 3280 Slog.v(TAG, "Found preferred activity:"); 3281 if (ai != null) { 3282 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3283 } else { 3284 Slog.v(TAG, " null"); 3285 } 3286 } 3287 if (ai == null) { 3288 // This previously registered preferred activity 3289 // component is no longer known. Most likely an update 3290 // to the app was installed and in the new version this 3291 // component no longer exists. Clean it up by removing 3292 // it from the preferred activities list, and skip it. 3293 Slog.w(TAG, "Removing dangling preferred activity: " 3294 + pa.mPref.mComponent); 3295 pir.removeFilter(pa); 3296 continue; 3297 } 3298 for (int j=0; j<N; j++) { 3299 final ResolveInfo ri = query.get(j); 3300 if (!ri.activityInfo.applicationInfo.packageName 3301 .equals(ai.applicationInfo.packageName)) { 3302 continue; 3303 } 3304 if (!ri.activityInfo.name.equals(ai.name)) { 3305 continue; 3306 } 3307 3308 if (removeMatches) { 3309 pir.removeFilter(pa); 3310 if (DEBUG_PREFERRED) { 3311 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3312 } 3313 break; 3314 } 3315 3316 // Okay we found a previously set preferred or last chosen app. 3317 // If the result set is different from when this 3318 // was created, we need to clear it and re-ask the 3319 // user their preference, if we're looking for an "always" type entry. 3320 if (always && !pa.mPref.sameSet(query, priority)) { 3321 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3322 + intent + " type " + resolvedType); 3323 if (DEBUG_PREFERRED) { 3324 Slog.v(TAG, "Removing preferred activity since set changed " 3325 + pa.mPref.mComponent); 3326 } 3327 pir.removeFilter(pa); 3328 // Re-add the filter as a "last chosen" entry (!always) 3329 PreferredActivity lastChosen = new PreferredActivity( 3330 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3331 pir.addFilter(lastChosen); 3332 mSettings.writePackageRestrictionsLPr(userId); 3333 return null; 3334 } 3335 3336 // Yay! Either the set matched or we're looking for the last chosen 3337 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3338 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3339 mSettings.writePackageRestrictionsLPr(userId); 3340 return ri; 3341 } 3342 } 3343 } 3344 mSettings.writePackageRestrictionsLPr(userId); 3345 } 3346 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3347 return null; 3348 } 3349 3350 /* 3351 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3352 */ 3353 @Override 3354 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3355 int targetUserId) { 3356 mContext.enforceCallingOrSelfPermission( 3357 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3358 List<CrossProfileIntentFilter> matches = 3359 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3360 if (matches != null) { 3361 int size = matches.size(); 3362 for (int i = 0; i < size; i++) { 3363 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3364 } 3365 } 3366 return false; 3367 } 3368 3369 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3370 String resolvedType, int userId) { 3371 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3372 if (resolver != null) { 3373 return resolver.queryIntent(intent, resolvedType, false, userId); 3374 } 3375 return null; 3376 } 3377 3378 @Override 3379 public List<ResolveInfo> queryIntentActivities(Intent intent, 3380 String resolvedType, int flags, int userId) { 3381 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3382 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3383 ComponentName comp = intent.getComponent(); 3384 if (comp == null) { 3385 if (intent.getSelector() != null) { 3386 intent = intent.getSelector(); 3387 comp = intent.getComponent(); 3388 } 3389 } 3390 3391 if (comp != null) { 3392 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3393 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3394 if (ai != null) { 3395 final ResolveInfo ri = new ResolveInfo(); 3396 ri.activityInfo = ai; 3397 list.add(ri); 3398 } 3399 return list; 3400 } 3401 3402 // reader 3403 synchronized (mPackages) { 3404 final String pkgName = intent.getPackage(); 3405 if (pkgName == null) { 3406 List<ResolveInfo> result; 3407 List<CrossProfileIntentFilter> matchingFilters = 3408 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3409 // Check for results that need to skip the current profile. 3410 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3411 resolvedType, flags, userId); 3412 if (resolveInfo != null) { 3413 result = new ArrayList<ResolveInfo>(1); 3414 result.add(resolveInfo); 3415 return result; 3416 } 3417 // Check for results in the current profile. 3418 result = mActivities.queryIntent(intent, resolvedType, flags, userId); 3419 // Check for cross profile results. 3420 resolveInfo = queryCrossProfileIntents( 3421 matchingFilters, intent, resolvedType, flags, userId); 3422 if (resolveInfo != null) { 3423 result.add(resolveInfo); 3424 } 3425 return result; 3426 } 3427 final PackageParser.Package pkg = mPackages.get(pkgName); 3428 if (pkg != null) { 3429 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3430 pkg.activities, userId); 3431 } 3432 return new ArrayList<ResolveInfo>(); 3433 } 3434 } 3435 3436 private ResolveInfo querySkipCurrentProfileIntents( 3437 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3438 int flags, int sourceUserId) { 3439 if (matchingFilters != null) { 3440 int size = matchingFilters.size(); 3441 for (int i = 0; i < size; i ++) { 3442 CrossProfileIntentFilter filter = matchingFilters.get(i); 3443 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3444 // Checking if there are activities in the target user that can handle the 3445 // intent. 3446 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3447 flags, sourceUserId); 3448 if (resolveInfo != null) { 3449 return createForwardingResolveInfo(filter, sourceUserId); 3450 } 3451 } 3452 } 3453 } 3454 return null; 3455 } 3456 3457 // Return matching ResolveInfo if any for skip current profile intent filters. 3458 private ResolveInfo queryCrossProfileIntents( 3459 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3460 int flags, int sourceUserId) { 3461 if (matchingFilters != null) { 3462 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3463 // match the same intent. For performance reasons, it is better not to 3464 // run queryIntent twice for the same userId 3465 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3466 int size = matchingFilters.size(); 3467 for (int i = 0; i < size; i++) { 3468 CrossProfileIntentFilter filter = matchingFilters.get(i); 3469 int targetUserId = filter.getTargetUserId(); 3470 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3471 && !alreadyTriedUserIds.get(targetUserId)) { 3472 // Checking if there are activities in the target user that can handle the 3473 // intent. 3474 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3475 flags, sourceUserId); 3476 if (resolveInfo != null) return resolveInfo; 3477 alreadyTriedUserIds.put(targetUserId, true); 3478 } 3479 } 3480 } 3481 return null; 3482 } 3483 3484 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3485 String resolvedType, int flags, int sourceUserId) { 3486 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3487 resolvedType, flags, filter.getTargetUserId()); 3488 if (resultTargetUser != null) { 3489 return createForwardingResolveInfo(filter, sourceUserId); 3490 } 3491 return null; 3492 } 3493 3494 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, 3495 int sourceUserId) { 3496 String className; 3497 int targetUserId = filter.getTargetUserId(); 3498 if (targetUserId == UserHandle.USER_OWNER) { 3499 className = FORWARD_INTENT_TO_USER_OWNER; 3500 } else { 3501 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3502 } 3503 ComponentName forwardingActivityComponentName = new ComponentName( 3504 mAndroidApplication.packageName, className); 3505 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3506 sourceUserId); 3507 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3508 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3509 forwardingResolveInfo.priority = 0; 3510 forwardingResolveInfo.preferredOrder = 0; 3511 forwardingResolveInfo.match = 0; 3512 forwardingResolveInfo.isDefault = true; 3513 forwardingResolveInfo.filter = filter; 3514 return forwardingResolveInfo; 3515 } 3516 3517 @Override 3518 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3519 Intent[] specifics, String[] specificTypes, Intent intent, 3520 String resolvedType, int flags, int userId) { 3521 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3522 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3523 "query intent activity options"); 3524 final String resultsAction = intent.getAction(); 3525 3526 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3527 | PackageManager.GET_RESOLVED_FILTER, userId); 3528 3529 if (DEBUG_INTENT_MATCHING) { 3530 Log.v(TAG, "Query " + intent + ": " + results); 3531 } 3532 3533 int specificsPos = 0; 3534 int N; 3535 3536 // todo: note that the algorithm used here is O(N^2). This 3537 // isn't a problem in our current environment, but if we start running 3538 // into situations where we have more than 5 or 10 matches then this 3539 // should probably be changed to something smarter... 3540 3541 // First we go through and resolve each of the specific items 3542 // that were supplied, taking care of removing any corresponding 3543 // duplicate items in the generic resolve list. 3544 if (specifics != null) { 3545 for (int i=0; i<specifics.length; i++) { 3546 final Intent sintent = specifics[i]; 3547 if (sintent == null) { 3548 continue; 3549 } 3550 3551 if (DEBUG_INTENT_MATCHING) { 3552 Log.v(TAG, "Specific #" + i + ": " + sintent); 3553 } 3554 3555 String action = sintent.getAction(); 3556 if (resultsAction != null && resultsAction.equals(action)) { 3557 // If this action was explicitly requested, then don't 3558 // remove things that have it. 3559 action = null; 3560 } 3561 3562 ResolveInfo ri = null; 3563 ActivityInfo ai = null; 3564 3565 ComponentName comp = sintent.getComponent(); 3566 if (comp == null) { 3567 ri = resolveIntent( 3568 sintent, 3569 specificTypes != null ? specificTypes[i] : null, 3570 flags, userId); 3571 if (ri == null) { 3572 continue; 3573 } 3574 if (ri == mResolveInfo) { 3575 // ACK! Must do something better with this. 3576 } 3577 ai = ri.activityInfo; 3578 comp = new ComponentName(ai.applicationInfo.packageName, 3579 ai.name); 3580 } else { 3581 ai = getActivityInfo(comp, flags, userId); 3582 if (ai == null) { 3583 continue; 3584 } 3585 } 3586 3587 // Look for any generic query activities that are duplicates 3588 // of this specific one, and remove them from the results. 3589 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3590 N = results.size(); 3591 int j; 3592 for (j=specificsPos; j<N; j++) { 3593 ResolveInfo sri = results.get(j); 3594 if ((sri.activityInfo.name.equals(comp.getClassName()) 3595 && sri.activityInfo.applicationInfo.packageName.equals( 3596 comp.getPackageName())) 3597 || (action != null && sri.filter.matchAction(action))) { 3598 results.remove(j); 3599 if (DEBUG_INTENT_MATCHING) Log.v( 3600 TAG, "Removing duplicate item from " + j 3601 + " due to specific " + specificsPos); 3602 if (ri == null) { 3603 ri = sri; 3604 } 3605 j--; 3606 N--; 3607 } 3608 } 3609 3610 // Add this specific item to its proper place. 3611 if (ri == null) { 3612 ri = new ResolveInfo(); 3613 ri.activityInfo = ai; 3614 } 3615 results.add(specificsPos, ri); 3616 ri.specificIndex = i; 3617 specificsPos++; 3618 } 3619 } 3620 3621 // Now we go through the remaining generic results and remove any 3622 // duplicate actions that are found here. 3623 N = results.size(); 3624 for (int i=specificsPos; i<N-1; i++) { 3625 final ResolveInfo rii = results.get(i); 3626 if (rii.filter == null) { 3627 continue; 3628 } 3629 3630 // Iterate over all of the actions of this result's intent 3631 // filter... typically this should be just one. 3632 final Iterator<String> it = rii.filter.actionsIterator(); 3633 if (it == null) { 3634 continue; 3635 } 3636 while (it.hasNext()) { 3637 final String action = it.next(); 3638 if (resultsAction != null && resultsAction.equals(action)) { 3639 // If this action was explicitly requested, then don't 3640 // remove things that have it. 3641 continue; 3642 } 3643 for (int j=i+1; j<N; j++) { 3644 final ResolveInfo rij = results.get(j); 3645 if (rij.filter != null && rij.filter.hasAction(action)) { 3646 results.remove(j); 3647 if (DEBUG_INTENT_MATCHING) Log.v( 3648 TAG, "Removing duplicate item from " + j 3649 + " due to action " + action + " at " + i); 3650 j--; 3651 N--; 3652 } 3653 } 3654 } 3655 3656 // If the caller didn't request filter information, drop it now 3657 // so we don't have to marshall/unmarshall it. 3658 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3659 rii.filter = null; 3660 } 3661 } 3662 3663 // Filter out the caller activity if so requested. 3664 if (caller != null) { 3665 N = results.size(); 3666 for (int i=0; i<N; i++) { 3667 ActivityInfo ainfo = results.get(i).activityInfo; 3668 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3669 && caller.getClassName().equals(ainfo.name)) { 3670 results.remove(i); 3671 break; 3672 } 3673 } 3674 } 3675 3676 // If the caller didn't request filter information, 3677 // drop them now so we don't have to 3678 // marshall/unmarshall it. 3679 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3680 N = results.size(); 3681 for (int i=0; i<N; i++) { 3682 results.get(i).filter = null; 3683 } 3684 } 3685 3686 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3687 return results; 3688 } 3689 3690 @Override 3691 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3692 int userId) { 3693 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3694 ComponentName comp = intent.getComponent(); 3695 if (comp == null) { 3696 if (intent.getSelector() != null) { 3697 intent = intent.getSelector(); 3698 comp = intent.getComponent(); 3699 } 3700 } 3701 if (comp != null) { 3702 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3703 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3704 if (ai != null) { 3705 ResolveInfo ri = new ResolveInfo(); 3706 ri.activityInfo = ai; 3707 list.add(ri); 3708 } 3709 return list; 3710 } 3711 3712 // reader 3713 synchronized (mPackages) { 3714 String pkgName = intent.getPackage(); 3715 if (pkgName == null) { 3716 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3717 } 3718 final PackageParser.Package pkg = mPackages.get(pkgName); 3719 if (pkg != null) { 3720 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3721 userId); 3722 } 3723 return null; 3724 } 3725 } 3726 3727 @Override 3728 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3729 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3730 if (!sUserManager.exists(userId)) return null; 3731 if (query != null) { 3732 if (query.size() >= 1) { 3733 // If there is more than one service with the same priority, 3734 // just arbitrarily pick the first one. 3735 return query.get(0); 3736 } 3737 } 3738 return null; 3739 } 3740 3741 @Override 3742 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3743 int userId) { 3744 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3745 ComponentName comp = intent.getComponent(); 3746 if (comp == null) { 3747 if (intent.getSelector() != null) { 3748 intent = intent.getSelector(); 3749 comp = intent.getComponent(); 3750 } 3751 } 3752 if (comp != null) { 3753 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3754 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3755 if (si != null) { 3756 final ResolveInfo ri = new ResolveInfo(); 3757 ri.serviceInfo = si; 3758 list.add(ri); 3759 } 3760 return list; 3761 } 3762 3763 // reader 3764 synchronized (mPackages) { 3765 String pkgName = intent.getPackage(); 3766 if (pkgName == null) { 3767 return mServices.queryIntent(intent, resolvedType, flags, userId); 3768 } 3769 final PackageParser.Package pkg = mPackages.get(pkgName); 3770 if (pkg != null) { 3771 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3772 userId); 3773 } 3774 return null; 3775 } 3776 } 3777 3778 @Override 3779 public List<ResolveInfo> queryIntentContentProviders( 3780 Intent intent, String resolvedType, int flags, int userId) { 3781 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3782 ComponentName comp = intent.getComponent(); 3783 if (comp == null) { 3784 if (intent.getSelector() != null) { 3785 intent = intent.getSelector(); 3786 comp = intent.getComponent(); 3787 } 3788 } 3789 if (comp != null) { 3790 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3791 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3792 if (pi != null) { 3793 final ResolveInfo ri = new ResolveInfo(); 3794 ri.providerInfo = pi; 3795 list.add(ri); 3796 } 3797 return list; 3798 } 3799 3800 // reader 3801 synchronized (mPackages) { 3802 String pkgName = intent.getPackage(); 3803 if (pkgName == null) { 3804 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3805 } 3806 final PackageParser.Package pkg = mPackages.get(pkgName); 3807 if (pkg != null) { 3808 return mProviders.queryIntentForPackage( 3809 intent, resolvedType, flags, pkg.providers, userId); 3810 } 3811 return null; 3812 } 3813 } 3814 3815 @Override 3816 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3817 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3818 3819 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3820 3821 // writer 3822 synchronized (mPackages) { 3823 ArrayList<PackageInfo> list; 3824 if (listUninstalled) { 3825 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3826 for (PackageSetting ps : mSettings.mPackages.values()) { 3827 PackageInfo pi; 3828 if (ps.pkg != null) { 3829 pi = generatePackageInfo(ps.pkg, flags, userId); 3830 } else { 3831 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3832 } 3833 if (pi != null) { 3834 list.add(pi); 3835 } 3836 } 3837 } else { 3838 list = new ArrayList<PackageInfo>(mPackages.size()); 3839 for (PackageParser.Package p : mPackages.values()) { 3840 PackageInfo pi = generatePackageInfo(p, flags, userId); 3841 if (pi != null) { 3842 list.add(pi); 3843 } 3844 } 3845 } 3846 3847 return new ParceledListSlice<PackageInfo>(list); 3848 } 3849 } 3850 3851 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3852 String[] permissions, boolean[] tmp, int flags, int userId) { 3853 int numMatch = 0; 3854 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3855 for (int i=0; i<permissions.length; i++) { 3856 if (gp.grantedPermissions.contains(permissions[i])) { 3857 tmp[i] = true; 3858 numMatch++; 3859 } else { 3860 tmp[i] = false; 3861 } 3862 } 3863 if (numMatch == 0) { 3864 return; 3865 } 3866 PackageInfo pi; 3867 if (ps.pkg != null) { 3868 pi = generatePackageInfo(ps.pkg, flags, userId); 3869 } else { 3870 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3871 } 3872 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3873 if (numMatch == permissions.length) { 3874 pi.requestedPermissions = permissions; 3875 } else { 3876 pi.requestedPermissions = new String[numMatch]; 3877 numMatch = 0; 3878 for (int i=0; i<permissions.length; i++) { 3879 if (tmp[i]) { 3880 pi.requestedPermissions[numMatch] = permissions[i]; 3881 numMatch++; 3882 } 3883 } 3884 } 3885 } 3886 list.add(pi); 3887 } 3888 3889 @Override 3890 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3891 String[] permissions, int flags, int userId) { 3892 if (!sUserManager.exists(userId)) return null; 3893 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3894 3895 // writer 3896 synchronized (mPackages) { 3897 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3898 boolean[] tmpBools = new boolean[permissions.length]; 3899 if (listUninstalled) { 3900 for (PackageSetting ps : mSettings.mPackages.values()) { 3901 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3902 } 3903 } else { 3904 for (PackageParser.Package pkg : mPackages.values()) { 3905 PackageSetting ps = (PackageSetting)pkg.mExtras; 3906 if (ps != null) { 3907 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3908 userId); 3909 } 3910 } 3911 } 3912 3913 return new ParceledListSlice<PackageInfo>(list); 3914 } 3915 } 3916 3917 @Override 3918 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3919 if (!sUserManager.exists(userId)) return null; 3920 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3921 3922 // writer 3923 synchronized (mPackages) { 3924 ArrayList<ApplicationInfo> list; 3925 if (listUninstalled) { 3926 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3927 for (PackageSetting ps : mSettings.mPackages.values()) { 3928 ApplicationInfo ai; 3929 if (ps.pkg != null) { 3930 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3931 ps.readUserState(userId), userId); 3932 } else { 3933 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3934 } 3935 if (ai != null) { 3936 list.add(ai); 3937 } 3938 } 3939 } else { 3940 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3941 for (PackageParser.Package p : mPackages.values()) { 3942 if (p.mExtras != null) { 3943 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3944 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3945 if (ai != null) { 3946 list.add(ai); 3947 } 3948 } 3949 } 3950 } 3951 3952 return new ParceledListSlice<ApplicationInfo>(list); 3953 } 3954 } 3955 3956 public List<ApplicationInfo> getPersistentApplications(int flags) { 3957 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3958 3959 // reader 3960 synchronized (mPackages) { 3961 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3962 final int userId = UserHandle.getCallingUserId(); 3963 while (i.hasNext()) { 3964 final PackageParser.Package p = i.next(); 3965 if (p.applicationInfo != null 3966 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3967 && (!mSafeMode || isSystemApp(p))) { 3968 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3969 if (ps != null) { 3970 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3971 ps.readUserState(userId), userId); 3972 if (ai != null) { 3973 finalList.add(ai); 3974 } 3975 } 3976 } 3977 } 3978 } 3979 3980 return finalList; 3981 } 3982 3983 @Override 3984 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3985 if (!sUserManager.exists(userId)) return null; 3986 // reader 3987 synchronized (mPackages) { 3988 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3989 PackageSetting ps = provider != null 3990 ? mSettings.mPackages.get(provider.owner.packageName) 3991 : null; 3992 return ps != null 3993 && mSettings.isEnabledLPr(provider.info, flags, userId) 3994 && (!mSafeMode || (provider.info.applicationInfo.flags 3995 &ApplicationInfo.FLAG_SYSTEM) != 0) 3996 ? PackageParser.generateProviderInfo(provider, flags, 3997 ps.readUserState(userId), userId) 3998 : null; 3999 } 4000 } 4001 4002 /** 4003 * @deprecated 4004 */ 4005 @Deprecated 4006 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4007 // reader 4008 synchronized (mPackages) { 4009 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4010 .entrySet().iterator(); 4011 final int userId = UserHandle.getCallingUserId(); 4012 while (i.hasNext()) { 4013 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4014 PackageParser.Provider p = entry.getValue(); 4015 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4016 4017 if (ps != null && p.syncable 4018 && (!mSafeMode || (p.info.applicationInfo.flags 4019 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4020 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4021 ps.readUserState(userId), userId); 4022 if (info != null) { 4023 outNames.add(entry.getKey()); 4024 outInfo.add(info); 4025 } 4026 } 4027 } 4028 } 4029 } 4030 4031 @Override 4032 public List<ProviderInfo> queryContentProviders(String processName, 4033 int uid, int flags) { 4034 ArrayList<ProviderInfo> finalList = null; 4035 // reader 4036 synchronized (mPackages) { 4037 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4038 final int userId = processName != null ? 4039 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4040 while (i.hasNext()) { 4041 final PackageParser.Provider p = i.next(); 4042 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4043 if (ps != null && p.info.authority != null 4044 && (processName == null 4045 || (p.info.processName.equals(processName) 4046 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4047 && mSettings.isEnabledLPr(p.info, flags, userId) 4048 && (!mSafeMode 4049 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4050 if (finalList == null) { 4051 finalList = new ArrayList<ProviderInfo>(3); 4052 } 4053 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4054 ps.readUserState(userId), userId); 4055 if (info != null) { 4056 finalList.add(info); 4057 } 4058 } 4059 } 4060 } 4061 4062 if (finalList != null) { 4063 Collections.sort(finalList, mProviderInitOrderSorter); 4064 } 4065 4066 return finalList; 4067 } 4068 4069 @Override 4070 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4071 int flags) { 4072 // reader 4073 synchronized (mPackages) { 4074 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4075 return PackageParser.generateInstrumentationInfo(i, flags); 4076 } 4077 } 4078 4079 @Override 4080 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4081 int flags) { 4082 ArrayList<InstrumentationInfo> finalList = 4083 new ArrayList<InstrumentationInfo>(); 4084 4085 // reader 4086 synchronized (mPackages) { 4087 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4088 while (i.hasNext()) { 4089 final PackageParser.Instrumentation p = i.next(); 4090 if (targetPackage == null 4091 || targetPackage.equals(p.info.targetPackage)) { 4092 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4093 flags); 4094 if (ii != null) { 4095 finalList.add(ii); 4096 } 4097 } 4098 } 4099 } 4100 4101 return finalList; 4102 } 4103 4104 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4105 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4106 if (overlays == null) { 4107 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4108 return; 4109 } 4110 for (PackageParser.Package opkg : overlays.values()) { 4111 // Not much to do if idmap fails: we already logged the error 4112 // and we certainly don't want to abort installation of pkg simply 4113 // because an overlay didn't fit properly. For these reasons, 4114 // ignore the return value of createIdmapForPackagePairLI. 4115 createIdmapForPackagePairLI(pkg, opkg); 4116 } 4117 } 4118 4119 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4120 PackageParser.Package opkg) { 4121 if (!opkg.mTrustedOverlay) { 4122 Slog.w(TAG, "Skipping target and overlay pair " + pkg.codePath + " and " + 4123 opkg.codePath + ": overlay not trusted"); 4124 return false; 4125 } 4126 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4127 if (overlaySet == null) { 4128 Slog.e(TAG, "was about to create idmap for " + pkg.codePath + " and " + 4129 opkg.codePath + " but target package has no known overlays"); 4130 return false; 4131 } 4132 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4133 // TODO: generate idmap for split APKs 4134 if (mInstaller.idmap(pkg.codePath, opkg.codePath, sharedGid) != 0) { 4135 Slog.e(TAG, "Failed to generate idmap for " + pkg.codePath + " and " + opkg.codePath); 4136 return false; 4137 } 4138 PackageParser.Package[] overlayArray = 4139 overlaySet.values().toArray(new PackageParser.Package[0]); 4140 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4141 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4142 return p1.mOverlayPriority - p2.mOverlayPriority; 4143 } 4144 }; 4145 Arrays.sort(overlayArray, cmp); 4146 4147 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4148 int i = 0; 4149 for (PackageParser.Package p : overlayArray) { 4150 pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir; 4151 } 4152 return true; 4153 } 4154 4155 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4156 String[] files = dir.list(); 4157 if (files == null) { 4158 Log.d(TAG, "No files in app dir " + dir); 4159 return; 4160 } 4161 4162 if (DEBUG_PACKAGE_SCANNING) { 4163 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4164 + " flags=0x" + Integer.toHexString(flags)); 4165 } 4166 4167 int i; 4168 for (i=0; i<files.length; i++) { 4169 File file = new File(dir, files[i]); 4170 if (!isPackageFilename(files[i])) { 4171 // Ignore entries which are not apk's 4172 continue; 4173 } 4174 PackageParser.Package pkg = scanPackageLI(file, 4175 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null); 4176 // Don't mess around with apps in system partition. 4177 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4178 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 4179 // Delete the apk 4180 Slog.w(TAG, "Cleaning up failed install of " + file); 4181 file.delete(); 4182 } 4183 } 4184 } 4185 4186 private static File getSettingsProblemFile() { 4187 File dataDir = Environment.getDataDirectory(); 4188 File systemDir = new File(dataDir, "system"); 4189 File fname = new File(systemDir, "uiderrors.txt"); 4190 return fname; 4191 } 4192 4193 static void reportSettingsProblem(int priority, String msg) { 4194 try { 4195 File fname = getSettingsProblemFile(); 4196 FileOutputStream out = new FileOutputStream(fname, true); 4197 PrintWriter pw = new FastPrintWriter(out); 4198 SimpleDateFormat formatter = new SimpleDateFormat(); 4199 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4200 pw.println(dateString + ": " + msg); 4201 pw.close(); 4202 FileUtils.setPermissions( 4203 fname.toString(), 4204 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4205 -1, -1); 4206 } catch (java.io.IOException e) { 4207 } 4208 Slog.println(priority, TAG, msg); 4209 } 4210 4211 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 4212 PackageParser.Package pkg, File srcFile, int parseFlags) { 4213 if (ps != null 4214 && ps.codePath.equals(srcFile) 4215 && ps.timeStamp == srcFile.lastModified() 4216 && !isCompatSignatureUpdateNeeded(pkg)) { 4217 if (ps.signatures.mSignatures != null 4218 && ps.signatures.mSignatures.length != 0) { 4219 // Optimization: reuse the existing cached certificates 4220 // if the package appears to be unchanged. 4221 pkg.mSignatures = ps.signatures.mSignatures; 4222 return true; 4223 } 4224 4225 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 4226 } else { 4227 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4228 } 4229 4230 try { 4231 pp.collectCertificates(pkg, parseFlags); 4232 } catch (PackageParserException e) { 4233 mLastScanError = e.error; 4234 return false; 4235 } 4236 return true; 4237 } 4238 4239 /* 4240 * Scan a package and return the newly parsed package. 4241 * Returns null in case of errors and the error code is stored in mLastScanError 4242 */ 4243 private PackageParser.Package scanPackageLI(File scanFile, 4244 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4245 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 4246 String scanPath = scanFile.getPath(); 4247 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath); 4248 parseFlags |= mDefParseFlags; 4249 PackageParser pp = new PackageParser(scanPath); 4250 pp.setSeparateProcesses(mSeparateProcesses); 4251 pp.setOnlyCoreApps(mOnlyCore); 4252 4253 final PackageParser.Package pkg; 4254 try { 4255 pkg = pp.parseMonolithicPackage(scanFile, mMetrics, parseFlags, 4256 (scanMode & SCAN_TRUSTED_OVERLAY) != 0); 4257 } catch (PackageParserException e) { 4258 mLastScanError = e.error; 4259 return null; 4260 } 4261 4262 PackageSetting ps = null; 4263 PackageSetting updatedPkg; 4264 // reader 4265 synchronized (mPackages) { 4266 // Look to see if we already know about this package. 4267 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4268 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4269 // This package has been renamed to its original name. Let's 4270 // use that. 4271 ps = mSettings.peekPackageLPr(oldName); 4272 } 4273 // If there was no original package, see one for the real package name. 4274 if (ps == null) { 4275 ps = mSettings.peekPackageLPr(pkg.packageName); 4276 } 4277 // Check to see if this package could be hiding/updating a system 4278 // package. Must look for it either under the original or real 4279 // package name depending on our state. 4280 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4281 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4282 } 4283 boolean updatedPkgBetter = false; 4284 // First check if this is a system package that may involve an update 4285 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4286 if (ps != null && !ps.codePath.equals(scanFile)) { 4287 // The path has changed from what was last scanned... check the 4288 // version of the new path against what we have stored to determine 4289 // what to do. 4290 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4291 if (pkg.mVersionCode < ps.versionCode) { 4292 // The system package has been updated and the code path does not match 4293 // Ignore entry. Skip it. 4294 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4295 + " ignored: updated version " + ps.versionCode 4296 + " better than this " + pkg.mVersionCode); 4297 if (!updatedPkg.codePath.equals(scanFile)) { 4298 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4299 + ps.name + " changing from " + updatedPkg.codePathString 4300 + " to " + scanFile); 4301 updatedPkg.codePath = scanFile; 4302 updatedPkg.codePathString = scanFile.toString(); 4303 // This is the point at which we know that the system-disk APK 4304 // for this package has moved during a reboot (e.g. due to an OTA), 4305 // so we need to reevaluate it for privilege policy. 4306 if (locationIsPrivileged(scanFile)) { 4307 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4308 } 4309 } 4310 updatedPkg.pkg = pkg; 4311 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4312 return null; 4313 } else { 4314 // The current app on the system partition is better than 4315 // what we have updated to on the data partition; switch 4316 // back to the system partition version. 4317 // At this point, its safely assumed that package installation for 4318 // apps in system partition will go through. If not there won't be a working 4319 // version of the app 4320 // writer 4321 synchronized (mPackages) { 4322 // Just remove the loaded entries from package lists. 4323 mPackages.remove(ps.name); 4324 } 4325 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4326 + "reverting from " + ps.codePathString 4327 + ": new version " + pkg.mVersionCode 4328 + " better than installed " + ps.versionCode); 4329 4330 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4331 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4332 getAppInstructionSetFromSettings(ps)); 4333 synchronized (mInstallLock) { 4334 args.cleanUpResourcesLI(); 4335 } 4336 synchronized (mPackages) { 4337 mSettings.enableSystemPackageLPw(ps.name); 4338 } 4339 updatedPkgBetter = true; 4340 } 4341 } 4342 } 4343 4344 if (updatedPkg != null) { 4345 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4346 // initially 4347 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4348 4349 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4350 // flag set initially 4351 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4352 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4353 } 4354 } 4355 // Verify certificates against what was last scanned 4356 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 4357 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 4358 return null; 4359 } 4360 4361 /* 4362 * A new system app appeared, but we already had a non-system one of the 4363 * same name installed earlier. 4364 */ 4365 boolean shouldHideSystemApp = false; 4366 if (updatedPkg == null && ps != null 4367 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4368 /* 4369 * Check to make sure the signatures match first. If they don't, 4370 * wipe the installed application and its data. 4371 */ 4372 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4373 != PackageManager.SIGNATURE_MATCH) { 4374 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4375 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4376 ps = null; 4377 } else { 4378 /* 4379 * If the newly-added system app is an older version than the 4380 * already installed version, hide it. It will be scanned later 4381 * and re-added like an update. 4382 */ 4383 if (pkg.mVersionCode < ps.versionCode) { 4384 shouldHideSystemApp = true; 4385 } else { 4386 /* 4387 * The newly found system app is a newer version that the 4388 * one previously installed. Simply remove the 4389 * already-installed application and replace it with our own 4390 * while keeping the application data. 4391 */ 4392 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4393 + ps.codePathString + ": new version " + pkg.mVersionCode 4394 + " better than installed " + ps.versionCode); 4395 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4396 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4397 getAppInstructionSetFromSettings(ps)); 4398 synchronized (mInstallLock) { 4399 args.cleanUpResourcesLI(); 4400 } 4401 } 4402 } 4403 } 4404 4405 // The apk is forward locked (not public) if its code and resources 4406 // are kept in different files. (except for app in either system or 4407 // vendor path). 4408 // TODO grab this value from PackageSettings 4409 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4410 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4411 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4412 } 4413 } 4414 4415 final String codePath = pkg.codePath; 4416 final String[] splitCodePaths = pkg.splitCodePaths; 4417 4418 String resPath = null; 4419 String[] splitResPaths = null; 4420 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4421 if (ps != null && ps.resourcePathString != null) { 4422 resPath = ps.resourcePathString; 4423 splitResPaths = deriveSplitResPaths(pkg.splitCodePaths); 4424 } else { 4425 // Should not happen at all. Just log an error. 4426 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4427 } 4428 } else { 4429 resPath = pkg.codePath; 4430 splitResPaths = pkg.splitCodePaths; 4431 } 4432 4433 // Set application objects path explicitly. 4434 pkg.applicationInfo.sourceDir = codePath; 4435 pkg.applicationInfo.publicSourceDir = resPath; 4436 pkg.applicationInfo.splitSourceDirs = splitCodePaths; 4437 pkg.applicationInfo.splitPublicSourceDirs = splitResPaths; 4438 4439 // Note that we invoke the following method only if we are about to unpack an application 4440 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4441 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4442 4443 /* 4444 * If the system app should be overridden by a previously installed 4445 * data, hide the system app now and let the /data/app scan pick it up 4446 * again. 4447 */ 4448 if (shouldHideSystemApp) { 4449 synchronized (mPackages) { 4450 /* 4451 * We have to grant systems permissions before we hide, because 4452 * grantPermissions will assume the package update is trying to 4453 * expand its permissions. 4454 */ 4455 grantPermissionsLPw(pkg, true); 4456 mSettings.disableSystemPackageLPw(pkg.packageName); 4457 } 4458 } 4459 4460 return scannedPkg; 4461 } 4462 4463 private static String fixProcessName(String defProcessName, 4464 String processName, int uid) { 4465 if (processName == null) { 4466 return defProcessName; 4467 } 4468 return processName; 4469 } 4470 4471 private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) { 4472 if (pkgSetting.signatures.mSignatures != null) { 4473 // Already existing package. Make sure signatures match 4474 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4475 == PackageManager.SIGNATURE_MATCH; 4476 if (!match) { 4477 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4478 == PackageManager.SIGNATURE_MATCH; 4479 } 4480 if (!match) { 4481 Slog.e(TAG, "Package " + pkg.packageName 4482 + " signatures do not match the previously installed version; ignoring!"); 4483 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4484 return false; 4485 } 4486 } 4487 // Check for shared user signatures 4488 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4489 // Already existing package. Make sure signatures match 4490 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4491 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4492 if (!match) { 4493 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4494 == PackageManager.SIGNATURE_MATCH; 4495 } 4496 if (!match) { 4497 Slog.e(TAG, "Package " + pkg.packageName 4498 + " has no signatures that match those in shared user " 4499 + pkgSetting.sharedUser.name + "; ignoring!"); 4500 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4501 return false; 4502 } 4503 } 4504 return true; 4505 } 4506 4507 /** 4508 * Enforces that only the system UID or root's UID can call a method exposed 4509 * via Binder. 4510 * 4511 * @param message used as message if SecurityException is thrown 4512 * @throws SecurityException if the caller is not system or root 4513 */ 4514 private static final void enforceSystemOrRoot(String message) { 4515 final int uid = Binder.getCallingUid(); 4516 if (uid != Process.SYSTEM_UID && uid != 0) { 4517 throw new SecurityException(message); 4518 } 4519 } 4520 4521 @Override 4522 public void performBootDexOpt() { 4523 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4524 4525 final HashSet<PackageParser.Package> pkgs; 4526 synchronized (mPackages) { 4527 pkgs = mDeferredDexOpt; 4528 mDeferredDexOpt = null; 4529 } 4530 4531 if (pkgs != null) { 4532 // Filter out packages that aren't recently used. 4533 // 4534 // The exception is first boot of a non-eng device, which 4535 // should do a full dexopt. 4536 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4537 if (eng || !isFirstBoot()) { 4538 // TODO: add a property to control this? 4539 long dexOptLRUThresholdInMinutes; 4540 if (eng) { 4541 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4542 } else { 4543 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4544 } 4545 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4546 4547 int total = pkgs.size(); 4548 int skipped = 0; 4549 long now = System.currentTimeMillis(); 4550 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4551 PackageParser.Package pkg = i.next(); 4552 long then = pkg.mLastPackageUsageTimeInMills; 4553 if (then + dexOptLRUThresholdInMills < now) { 4554 if (DEBUG_DEXOPT) { 4555 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4556 ((then == 0) ? "never" : new Date(then))); 4557 } 4558 i.remove(); 4559 skipped++; 4560 } 4561 } 4562 if (DEBUG_DEXOPT) { 4563 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4564 } 4565 } 4566 4567 int i = 0; 4568 for (PackageParser.Package pkg : pkgs) { 4569 i++; 4570 if (DEBUG_DEXOPT) { 4571 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4572 + ": " + pkg.packageName); 4573 } 4574 if (!isFirstBoot()) { 4575 try { 4576 ActivityManagerNative.getDefault().showBootMessage( 4577 mContext.getResources().getString( 4578 R.string.android_upgrading_apk, 4579 i, pkgs.size()), true); 4580 } catch (RemoteException e) { 4581 } 4582 } 4583 PackageParser.Package p = pkg; 4584 synchronized (mInstallLock) { 4585 if (p.mDexOptNeeded) { 4586 performDexOptLI(p, false /* force dex */, false /* defer */, 4587 true /* include dependencies */); 4588 } 4589 } 4590 } 4591 } 4592 } 4593 4594 @Override 4595 public boolean performDexOpt(String packageName) { 4596 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4597 return performDexOpt(packageName, true); 4598 } 4599 4600 public boolean performDexOpt(String packageName, boolean updateUsage) { 4601 4602 PackageParser.Package p; 4603 synchronized (mPackages) { 4604 p = mPackages.get(packageName); 4605 if (p == null) { 4606 return false; 4607 } 4608 if (updateUsage) { 4609 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4610 } 4611 mPackageUsage.write(false); 4612 if (!p.mDexOptNeeded) { 4613 return false; 4614 } 4615 } 4616 4617 synchronized (mInstallLock) { 4618 return performDexOptLI(p, false /* force dex */, false /* defer */, 4619 true /* include dependencies */) == DEX_OPT_PERFORMED; 4620 } 4621 } 4622 4623 public HashSet<String> getPackagesThatNeedDexOpt() { 4624 HashSet<String> pkgs = null; 4625 synchronized (mPackages) { 4626 for (PackageParser.Package p : mPackages.values()) { 4627 if (DEBUG_DEXOPT) { 4628 Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded); 4629 } 4630 if (!p.mDexOptNeeded) { 4631 continue; 4632 } 4633 if (pkgs == null) { 4634 pkgs = new HashSet<String>(); 4635 } 4636 pkgs.add(p.packageName); 4637 } 4638 } 4639 return pkgs; 4640 } 4641 4642 public void shutdown() { 4643 mPackageUsage.write(true); 4644 } 4645 4646 private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, 4647 boolean forceDex, boolean defer, HashSet<String> done) { 4648 for (int i=0; i<libs.size(); i++) { 4649 PackageParser.Package libPkg; 4650 String libName; 4651 synchronized (mPackages) { 4652 libName = libs.get(i); 4653 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4654 if (lib != null && lib.apk != null) { 4655 libPkg = mPackages.get(lib.apk); 4656 } else { 4657 libPkg = null; 4658 } 4659 } 4660 if (libPkg != null && !done.contains(libName)) { 4661 performDexOptLI(libPkg, instructionSet, forceDex, defer, done); 4662 } 4663 } 4664 } 4665 4666 static final int DEX_OPT_SKIPPED = 0; 4667 static final int DEX_OPT_PERFORMED = 1; 4668 static final int DEX_OPT_DEFERRED = 2; 4669 static final int DEX_OPT_FAILED = -1; 4670 4671 private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride, 4672 boolean forceDex, boolean defer, HashSet<String> done) { 4673 final String instructionSet = instructionSetOverride != null ? 4674 instructionSetOverride : getAppInstructionSet(pkg.applicationInfo); 4675 4676 if (done != null) { 4677 done.add(pkg.packageName); 4678 if (pkg.usesLibraries != null) { 4679 performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done); 4680 } 4681 if (pkg.usesOptionalLibraries != null) { 4682 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done); 4683 } 4684 } 4685 4686 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) { 4687 final ArrayList<String> paths = new ArrayList<>(); 4688 paths.add(pkg.codePath); 4689 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 4690 Collections.addAll(paths, pkg.splitCodePaths); 4691 } 4692 4693 for (String path : paths) { 4694 try { 4695 boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path, 4696 pkg.packageName, instructionSet, defer); 4697 // There are three basic cases here: 4698 // 1.) we need to dexopt, either because we are forced or it is needed 4699 // 2.) we are defering a needed dexopt 4700 // 3.) we are skipping an unneeded dexopt 4701 if (forceDex || (!defer && isDexOptNeededInternal)) { 4702 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName); 4703 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4704 int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4705 pkg.packageName, instructionSet); 4706 // Note that we ran dexopt, since rerunning will 4707 // probably just result in an error again. 4708 pkg.mDexOptNeeded = false; 4709 if (ret < 0) { 4710 return DEX_OPT_FAILED; 4711 } 4712 return DEX_OPT_PERFORMED; 4713 } 4714 if (defer && isDexOptNeededInternal) { 4715 if (mDeferredDexOpt == null) { 4716 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4717 } 4718 mDeferredDexOpt.add(pkg); 4719 return DEX_OPT_DEFERRED; 4720 } 4721 pkg.mDexOptNeeded = false; 4722 return DEX_OPT_SKIPPED; 4723 } catch (FileNotFoundException e) { 4724 Slog.w(TAG, "Apk not found for dexopt: " + path); 4725 return DEX_OPT_FAILED; 4726 } catch (IOException e) { 4727 Slog.w(TAG, "IOException reading apk: " + path, e); 4728 return DEX_OPT_FAILED; 4729 } catch (StaleDexCacheError e) { 4730 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4731 return DEX_OPT_FAILED; 4732 } catch (Exception e) { 4733 Slog.w(TAG, "Exception when doing dexopt : ", e); 4734 return DEX_OPT_FAILED; 4735 } 4736 } 4737 } 4738 return DEX_OPT_SKIPPED; 4739 } 4740 4741 private String getAppInstructionSet(ApplicationInfo info) { 4742 String instructionSet = getPreferredInstructionSet(); 4743 4744 if (info.cpuAbi != null) { 4745 instructionSet = VMRuntime.getInstructionSet(info.cpuAbi); 4746 } 4747 4748 return instructionSet; 4749 } 4750 4751 private String getAppInstructionSetFromSettings(PackageSetting ps) { 4752 String instructionSet = getPreferredInstructionSet(); 4753 4754 if (ps.cpuAbiString != null) { 4755 instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 4756 } 4757 4758 return instructionSet; 4759 } 4760 4761 private static String getPreferredInstructionSet() { 4762 if (sPreferredInstructionSet == null) { 4763 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4764 } 4765 4766 return sPreferredInstructionSet; 4767 } 4768 4769 private static List<String> getAllInstructionSets() { 4770 final String[] allAbis = Build.SUPPORTED_ABIS; 4771 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4772 4773 for (String abi : allAbis) { 4774 final String instructionSet = VMRuntime.getInstructionSet(abi); 4775 if (!allInstructionSets.contains(instructionSet)) { 4776 allInstructionSets.add(instructionSet); 4777 } 4778 } 4779 4780 return allInstructionSets; 4781 } 4782 4783 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4784 boolean inclDependencies) { 4785 HashSet<String> done; 4786 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4787 done = new HashSet<String>(); 4788 done.add(pkg.packageName); 4789 } else { 4790 done = null; 4791 } 4792 return performDexOptLI(pkg, null /* instruction set override */, forceDex, defer, done); 4793 } 4794 4795 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4796 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4797 Slog.w(TAG, "Unable to update from " + oldPkg.name 4798 + " to " + newPkg.packageName 4799 + ": old package not in system partition"); 4800 return false; 4801 } else if (mPackages.get(oldPkg.name) != null) { 4802 Slog.w(TAG, "Unable to update from " + oldPkg.name 4803 + " to " + newPkg.packageName 4804 + ": old package still exists"); 4805 return false; 4806 } 4807 return true; 4808 } 4809 4810 File getDataPathForUser(int userId) { 4811 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4812 } 4813 4814 private File getDataPathForPackage(String packageName, int userId) { 4815 /* 4816 * Until we fully support multiple users, return the directory we 4817 * previously would have. The PackageManagerTests will need to be 4818 * revised when this is changed back.. 4819 */ 4820 if (userId == 0) { 4821 return new File(mAppDataDir, packageName); 4822 } else { 4823 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4824 + File.separator + packageName); 4825 } 4826 } 4827 4828 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4829 int[] users = sUserManager.getUserIds(); 4830 int res = mInstaller.install(packageName, uid, uid, seinfo); 4831 if (res < 0) { 4832 return res; 4833 } 4834 for (int user : users) { 4835 if (user != 0) { 4836 res = mInstaller.createUserData(packageName, 4837 UserHandle.getUid(user, uid), user, seinfo); 4838 if (res < 0) { 4839 return res; 4840 } 4841 } 4842 } 4843 return res; 4844 } 4845 4846 private int removeDataDirsLI(String packageName) { 4847 int[] users = sUserManager.getUserIds(); 4848 int res = 0; 4849 for (int user : users) { 4850 int resInner = mInstaller.remove(packageName, user); 4851 if (resInner < 0) { 4852 res = resInner; 4853 } 4854 } 4855 4856 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4857 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4858 if (!nativeLibraryFile.delete()) { 4859 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4860 } 4861 4862 return res; 4863 } 4864 4865 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4866 PackageParser.Package changingLib) { 4867 if (file.path != null) { 4868 usesLibraryFiles.add(file.path); 4869 return; 4870 } 4871 PackageParser.Package p = mPackages.get(file.apk); 4872 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4873 // If we are doing this while in the middle of updating a library apk, 4874 // then we need to make sure to use that new apk for determining the 4875 // dependencies here. (We haven't yet finished committing the new apk 4876 // to the package manager state.) 4877 if (p == null || p.packageName.equals(changingLib.packageName)) { 4878 p = changingLib; 4879 } 4880 } 4881 if (p != null) { 4882 usesLibraryFiles.add(p.codePath); 4883 if (!ArrayUtils.isEmpty(p.splitCodePaths)) { 4884 Collections.addAll(usesLibraryFiles, p.splitCodePaths); 4885 } 4886 } 4887 } 4888 4889 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4890 PackageParser.Package changingLib) { 4891 // We might be upgrading from a version of the platform that did not 4892 // provide per-package native library directories for system apps. 4893 // Fix that up here. 4894 if (isSystemApp(pkg)) { 4895 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4896 setInternalAppNativeLibraryPath(pkg, ps); 4897 } 4898 4899 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4900 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4901 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4902 for (int i=0; i<N; i++) { 4903 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4904 if (file == null) { 4905 Slog.e(TAG, "Package " + pkg.packageName 4906 + " requires unavailable shared library " 4907 + pkg.usesLibraries.get(i) + "; failing!"); 4908 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4909 return false; 4910 } 4911 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4912 } 4913 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4914 for (int i=0; i<N; i++) { 4915 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4916 if (file == null) { 4917 Slog.w(TAG, "Package " + pkg.packageName 4918 + " desires unavailable shared library " 4919 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4920 } else { 4921 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4922 } 4923 } 4924 N = usesLibraryFiles.size(); 4925 if (N > 0) { 4926 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4927 } else { 4928 pkg.usesLibraryFiles = null; 4929 } 4930 } 4931 return true; 4932 } 4933 4934 private static boolean hasString(List<String> list, List<String> which) { 4935 if (list == null) { 4936 return false; 4937 } 4938 for (int i=list.size()-1; i>=0; i--) { 4939 for (int j=which.size()-1; j>=0; j--) { 4940 if (which.get(j).equals(list.get(i))) { 4941 return true; 4942 } 4943 } 4944 } 4945 return false; 4946 } 4947 4948 private void updateAllSharedLibrariesLPw() { 4949 for (PackageParser.Package pkg : mPackages.values()) { 4950 updateSharedLibrariesLPw(pkg, null); 4951 } 4952 } 4953 4954 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4955 PackageParser.Package changingPkg) { 4956 ArrayList<PackageParser.Package> res = null; 4957 for (PackageParser.Package pkg : mPackages.values()) { 4958 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4959 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4960 if (res == null) { 4961 res = new ArrayList<PackageParser.Package>(); 4962 } 4963 res.add(pkg); 4964 updateSharedLibrariesLPw(pkg, changingPkg); 4965 } 4966 } 4967 return res; 4968 } 4969 4970 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4971 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4972 final File scanFile = new File(pkg.codePath); 4973 if (pkg.applicationInfo.sourceDir == null || 4974 pkg.applicationInfo.publicSourceDir == null) { 4975 // Bail out. The resource and code paths haven't been set. 4976 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4977 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4978 return null; 4979 } 4980 4981 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4982 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4983 } 4984 4985 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4986 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4987 } 4988 4989 if (mCustomResolverComponentName != null && 4990 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4991 setUpCustomResolverActivity(pkg); 4992 } 4993 4994 if (pkg.packageName.equals("android")) { 4995 synchronized (mPackages) { 4996 if (mAndroidApplication != null) { 4997 Slog.w(TAG, "*************************************************"); 4998 Slog.w(TAG, "Core android package being redefined. Skipping."); 4999 Slog.w(TAG, " file=" + scanFile); 5000 Slog.w(TAG, "*************************************************"); 5001 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 5002 return null; 5003 } 5004 5005 // Set up information for our fall-back user intent resolution activity. 5006 mPlatformPackage = pkg; 5007 pkg.mVersionCode = mSdkVersion; 5008 mAndroidApplication = pkg.applicationInfo; 5009 5010 if (!mResolverReplaced) { 5011 mResolveActivity.applicationInfo = mAndroidApplication; 5012 mResolveActivity.name = ResolverActivity.class.getName(); 5013 mResolveActivity.packageName = mAndroidApplication.packageName; 5014 mResolveActivity.processName = "system:ui"; 5015 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5016 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5017 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5018 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5019 mResolveActivity.exported = true; 5020 mResolveActivity.enabled = true; 5021 mResolveInfo.activityInfo = mResolveActivity; 5022 mResolveInfo.priority = 0; 5023 mResolveInfo.preferredOrder = 0; 5024 mResolveInfo.match = 0; 5025 mResolveComponentName = new ComponentName( 5026 mAndroidApplication.packageName, mResolveActivity.name); 5027 } 5028 } 5029 } 5030 5031 if (DEBUG_PACKAGE_SCANNING) { 5032 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5033 Log.d(TAG, "Scanning package " + pkg.packageName); 5034 } 5035 5036 if (mPackages.containsKey(pkg.packageName) 5037 || mSharedLibraries.containsKey(pkg.packageName)) { 5038 Slog.w(TAG, "Application package " + pkg.packageName 5039 + " already installed. Skipping duplicate."); 5040 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 5041 return null; 5042 } 5043 5044 // Initialize package source and resource directories 5045 File destCodeFile = new File(pkg.applicationInfo.sourceDir); 5046 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir); 5047 5048 SharedUserSetting suid = null; 5049 PackageSetting pkgSetting = null; 5050 5051 if (!isSystemApp(pkg)) { 5052 // Only system apps can use these features. 5053 pkg.mOriginalPackages = null; 5054 pkg.mRealPackage = null; 5055 pkg.mAdoptPermissions = null; 5056 } 5057 5058 // writer 5059 synchronized (mPackages) { 5060 if (pkg.mSharedUserId != null) { 5061 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5062 if (suid == null) { 5063 Slog.w(TAG, "Creating application package " + pkg.packageName 5064 + " for shared user failed"); 5065 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5066 return null; 5067 } 5068 if (DEBUG_PACKAGE_SCANNING) { 5069 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5070 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5071 + "): packages=" + suid.packages); 5072 } 5073 } 5074 5075 // Check if we are renaming from an original package name. 5076 PackageSetting origPackage = null; 5077 String realName = null; 5078 if (pkg.mOriginalPackages != null) { 5079 // This package may need to be renamed to a previously 5080 // installed name. Let's check on that... 5081 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5082 if (pkg.mOriginalPackages.contains(renamed)) { 5083 // This package had originally been installed as the 5084 // original name, and we have already taken care of 5085 // transitioning to the new one. Just update the new 5086 // one to continue using the old name. 5087 realName = pkg.mRealPackage; 5088 if (!pkg.packageName.equals(renamed)) { 5089 // Callers into this function may have already taken 5090 // care of renaming the package; only do it here if 5091 // it is not already done. 5092 pkg.setPackageName(renamed); 5093 } 5094 5095 } else { 5096 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5097 if ((origPackage = mSettings.peekPackageLPr( 5098 pkg.mOriginalPackages.get(i))) != null) { 5099 // We do have the package already installed under its 5100 // original name... should we use it? 5101 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5102 // New package is not compatible with original. 5103 origPackage = null; 5104 continue; 5105 } else if (origPackage.sharedUser != null) { 5106 // Make sure uid is compatible between packages. 5107 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5108 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5109 + " to " + pkg.packageName + ": old uid " 5110 + origPackage.sharedUser.name 5111 + " differs from " + pkg.mSharedUserId); 5112 origPackage = null; 5113 continue; 5114 } 5115 } else { 5116 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5117 + pkg.packageName + " to old name " + origPackage.name); 5118 } 5119 break; 5120 } 5121 } 5122 } 5123 } 5124 5125 if (mTransferedPackages.contains(pkg.packageName)) { 5126 Slog.w(TAG, "Package " + pkg.packageName 5127 + " was transferred to another, but its .apk remains"); 5128 } 5129 5130 // Just create the setting, don't add it yet. For already existing packages 5131 // the PkgSetting exists already and doesn't have to be created. 5132 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5133 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 5134 pkg.applicationInfo.cpuAbi, 5135 pkg.applicationInfo.flags, user, false); 5136 if (pkgSetting == null) { 5137 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 5138 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5139 return null; 5140 } 5141 5142 if (pkgSetting.origPackage != null) { 5143 // If we are first transitioning from an original package, 5144 // fix up the new package's name now. We need to do this after 5145 // looking up the package under its new name, so getPackageLP 5146 // can take care of fiddling things correctly. 5147 pkg.setPackageName(origPackage.name); 5148 5149 // File a report about this. 5150 String msg = "New package " + pkgSetting.realName 5151 + " renamed to replace old package " + pkgSetting.name; 5152 reportSettingsProblem(Log.WARN, msg); 5153 5154 // Make a note of it. 5155 mTransferedPackages.add(origPackage.name); 5156 5157 // No longer need to retain this. 5158 pkgSetting.origPackage = null; 5159 } 5160 5161 if (realName != null) { 5162 // Make a note of it. 5163 mTransferedPackages.add(pkg.packageName); 5164 } 5165 5166 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5167 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5168 } 5169 5170 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5171 // Check all shared libraries and map to their actual file path. 5172 // We only do this here for apps not on a system dir, because those 5173 // are the only ones that can fail an install due to this. We 5174 // will take care of the system apps by updating all of their 5175 // library paths after the scan is done. 5176 if (!updateSharedLibrariesLPw(pkg, null)) { 5177 return null; 5178 } 5179 } 5180 5181 if (mFoundPolicyFile) { 5182 SELinuxMMAC.assignSeinfoValue(pkg); 5183 } 5184 5185 pkg.applicationInfo.uid = pkgSetting.appId; 5186 pkg.mExtras = pkgSetting; 5187 5188 if (!verifySignaturesLP(pkgSetting, pkg)) { 5189 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5190 return null; 5191 } 5192 // The signature has changed, but this package is in the system 5193 // image... let's recover! 5194 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5195 // However... if this package is part of a shared user, but it 5196 // doesn't match the signature of the shared user, let's fail. 5197 // What this means is that you can't change the signatures 5198 // associated with an overall shared user, which doesn't seem all 5199 // that unreasonable. 5200 if (pkgSetting.sharedUser != null) { 5201 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5202 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5203 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 5204 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 5205 return null; 5206 } 5207 } 5208 // File a report about this. 5209 String msg = "System package " + pkg.packageName 5210 + " signature changed; retaining data."; 5211 reportSettingsProblem(Log.WARN, msg); 5212 } 5213 5214 // Verify that this new package doesn't have any content providers 5215 // that conflict with existing packages. Only do this if the 5216 // package isn't already installed, since we don't want to break 5217 // things that are installed. 5218 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5219 final int N = pkg.providers.size(); 5220 int i; 5221 for (i=0; i<N; i++) { 5222 PackageParser.Provider p = pkg.providers.get(i); 5223 if (p.info.authority != null) { 5224 String names[] = p.info.authority.split(";"); 5225 for (int j = 0; j < names.length; j++) { 5226 if (mProvidersByAuthority.containsKey(names[j])) { 5227 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5228 Slog.w(TAG, "Can't install because provider name " + names[j] + 5229 " (in package " + pkg.applicationInfo.packageName + 5230 ") is already used by " 5231 + ((other != null && other.getComponentName() != null) 5232 ? other.getComponentName().getPackageName() : "?")); 5233 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 5234 return null; 5235 } 5236 } 5237 } 5238 } 5239 } 5240 5241 if (pkg.mAdoptPermissions != null) { 5242 // This package wants to adopt ownership of permissions from 5243 // another package. 5244 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5245 final String origName = pkg.mAdoptPermissions.get(i); 5246 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5247 if (orig != null) { 5248 if (verifyPackageUpdateLPr(orig, pkg)) { 5249 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5250 + pkg.packageName); 5251 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5252 } 5253 } 5254 } 5255 } 5256 } 5257 5258 final String pkgName = pkg.packageName; 5259 5260 final long scanFileTime = scanFile.lastModified(); 5261 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5262 pkg.applicationInfo.processName = fixProcessName( 5263 pkg.applicationInfo.packageName, 5264 pkg.applicationInfo.processName, 5265 pkg.applicationInfo.uid); 5266 5267 File dataPath; 5268 if (mPlatformPackage == pkg) { 5269 // The system package is special. 5270 dataPath = new File (Environment.getDataDirectory(), "system"); 5271 pkg.applicationInfo.dataDir = dataPath.getPath(); 5272 } else { 5273 // This is a normal package, need to make its data directory. 5274 dataPath = getDataPathForPackage(pkg.packageName, 0); 5275 5276 boolean uidError = false; 5277 5278 if (dataPath.exists()) { 5279 int currentUid = 0; 5280 try { 5281 StructStat stat = Os.stat(dataPath.getPath()); 5282 currentUid = stat.st_uid; 5283 } catch (ErrnoException e) { 5284 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5285 } 5286 5287 // If we have mismatched owners for the data path, we have a problem. 5288 if (currentUid != pkg.applicationInfo.uid) { 5289 boolean recovered = false; 5290 if (currentUid == 0) { 5291 // The directory somehow became owned by root. Wow. 5292 // This is probably because the system was stopped while 5293 // installd was in the middle of messing with its libs 5294 // directory. Ask installd to fix that. 5295 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5296 pkg.applicationInfo.uid); 5297 if (ret >= 0) { 5298 recovered = true; 5299 String msg = "Package " + pkg.packageName 5300 + " unexpectedly changed to uid 0; recovered to " + 5301 + pkg.applicationInfo.uid; 5302 reportSettingsProblem(Log.WARN, msg); 5303 } 5304 } 5305 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5306 || (scanMode&SCAN_BOOTING) != 0)) { 5307 // If this is a system app, we can at least delete its 5308 // current data so the application will still work. 5309 int ret = removeDataDirsLI(pkgName); 5310 if (ret >= 0) { 5311 // TODO: Kill the processes first 5312 // Old data gone! 5313 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5314 ? "System package " : "Third party package "; 5315 String msg = prefix + pkg.packageName 5316 + " has changed from uid: " 5317 + currentUid + " to " 5318 + pkg.applicationInfo.uid + "; old data erased"; 5319 reportSettingsProblem(Log.WARN, msg); 5320 recovered = true; 5321 5322 // And now re-install the app. 5323 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5324 pkg.applicationInfo.seinfo); 5325 if (ret == -1) { 5326 // Ack should not happen! 5327 msg = prefix + pkg.packageName 5328 + " could not have data directory re-created after delete."; 5329 reportSettingsProblem(Log.WARN, msg); 5330 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5331 return null; 5332 } 5333 } 5334 if (!recovered) { 5335 mHasSystemUidErrors = true; 5336 } 5337 } else if (!recovered) { 5338 // If we allow this install to proceed, we will be broken. 5339 // Abort, abort! 5340 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 5341 return null; 5342 } 5343 if (!recovered) { 5344 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5345 + pkg.applicationInfo.uid + "/fs_" 5346 + currentUid; 5347 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5348 String msg = "Package " + pkg.packageName 5349 + " has mismatched uid: " 5350 + currentUid + " on disk, " 5351 + pkg.applicationInfo.uid + " in settings"; 5352 // writer 5353 synchronized (mPackages) { 5354 mSettings.mReadMessages.append(msg); 5355 mSettings.mReadMessages.append('\n'); 5356 uidError = true; 5357 if (!pkgSetting.uidError) { 5358 reportSettingsProblem(Log.ERROR, msg); 5359 } 5360 } 5361 } 5362 } 5363 pkg.applicationInfo.dataDir = dataPath.getPath(); 5364 if (mShouldRestoreconData) { 5365 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5366 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5367 pkg.applicationInfo.uid); 5368 } 5369 } else { 5370 if (DEBUG_PACKAGE_SCANNING) { 5371 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5372 Log.v(TAG, "Want this data dir: " + dataPath); 5373 } 5374 //invoke installer to do the actual installation 5375 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5376 pkg.applicationInfo.seinfo); 5377 if (ret < 0) { 5378 // Error from installer 5379 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5380 return null; 5381 } 5382 5383 if (dataPath.exists()) { 5384 pkg.applicationInfo.dataDir = dataPath.getPath(); 5385 } else { 5386 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5387 pkg.applicationInfo.dataDir = null; 5388 } 5389 } 5390 5391 /* 5392 * Set the data dir to the default "/data/data/<package name>/lib" 5393 * if we got here without anyone telling us different (e.g., apps 5394 * stored on SD card have their native libraries stored in the ASEC 5395 * container with the APK). 5396 * 5397 * This happens during an upgrade from a package settings file that 5398 * doesn't have a native library path attribute at all. 5399 */ 5400 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 5401 if (pkgSetting.nativeLibraryPathString == null) { 5402 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5403 } else { 5404 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 5405 } 5406 } 5407 pkgSetting.uidError = uidError; 5408 } 5409 5410 final String path = scanFile.getPath(); 5411 /* Note: We don't want to unpack the native binaries for 5412 * system applications, unless they have been updated 5413 * (the binaries are already under /system/lib). 5414 * Also, don't unpack libs for apps on the external card 5415 * since they should have their libraries in the ASEC 5416 * container already. 5417 * 5418 * In other words, we're going to unpack the binaries 5419 * only for non-system apps and system app upgrades. 5420 */ 5421 if (pkg.applicationInfo.nativeLibraryDir != null) { 5422 // TODO: extend to extract native code from split APKs 5423 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile); 5424 try { 5425 // Enable gross and lame hacks for apps that are built with old 5426 // SDK tools. We must scan their APKs for renderscript bitcode and 5427 // not launch them if it's present. Don't bother checking on devices 5428 // that don't have 64 bit support. 5429 String[] abiList = Build.SUPPORTED_ABIS; 5430 boolean hasLegacyRenderscriptBitcode = false; 5431 if (abiOverride != null) { 5432 abiList = new String[] { abiOverride }; 5433 } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 5434 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5435 abiList = Build.SUPPORTED_32_BIT_ABIS; 5436 hasLegacyRenderscriptBitcode = true; 5437 } 5438 5439 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5440 final String dataPathString = dataPath.getCanonicalPath(); 5441 5442 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5443 /* 5444 * Upgrading from a previous version of the OS sometimes 5445 * leaves native libraries in the /data/data/<app>/lib 5446 * directory for system apps even when they shouldn't be. 5447 * Recent changes in the JNI library search path 5448 * necessitates we remove those to match previous behavior. 5449 */ 5450 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 5451 Log.i(TAG, "removed obsolete native libraries for system package " 5452 + path); 5453 } 5454 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5455 pkg.applicationInfo.cpuAbi = abiList[0]; 5456 pkgSetting.cpuAbiString = abiList[0]; 5457 } else { 5458 setInternalAppAbi(pkg, pkgSetting); 5459 } 5460 } else { 5461 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 5462 /* 5463 * Update native library dir if it starts with 5464 * /data/data 5465 */ 5466 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 5467 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5468 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5469 } 5470 5471 try { 5472 int copyRet = copyNativeLibrariesForInternalApp(handle, 5473 nativeLibraryDir, abiList); 5474 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5475 Slog.e(TAG, "Unable to copy native libraries"); 5476 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5477 return null; 5478 } 5479 5480 // We've successfully copied native libraries across, so we make a 5481 // note of what ABI we're using 5482 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5483 pkg.applicationInfo.cpuAbi = abiList[copyRet]; 5484 } else if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5485 pkg.applicationInfo.cpuAbi = abiList[0]; 5486 } else { 5487 pkg.applicationInfo.cpuAbi = null; 5488 } 5489 } catch (IOException e) { 5490 Slog.e(TAG, "Unable to copy native libraries", e); 5491 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5492 return null; 5493 } 5494 } else { 5495 // We don't have to copy the shared libraries if we're in the ASEC container 5496 // but we still need to scan the file to figure out what ABI the app needs. 5497 // 5498 // TODO: This duplicates work done in the default container service. It's possible 5499 // to clean this up but we'll need to change the interface between this service 5500 // and IMediaContainerService (but doing so will spread this logic out, rather 5501 // than centralizing it). 5502 final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5503 if (abi >= 0) { 5504 pkg.applicationInfo.cpuAbi = abiList[abi]; 5505 } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) { 5506 // Note that (non upgraded) system apps will not have any native 5507 // libraries bundled in their APK, but we're guaranteed not to be 5508 // such an app at this point. 5509 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5510 pkg.applicationInfo.cpuAbi = abiList[0]; 5511 } else { 5512 pkg.applicationInfo.cpuAbi = null; 5513 } 5514 } else { 5515 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5516 return null; 5517 } 5518 } 5519 5520 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5521 final int[] userIds = sUserManager.getUserIds(); 5522 synchronized (mInstallLock) { 5523 for (int userId : userIds) { 5524 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 5525 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 5526 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5527 + ")"); 5528 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5529 return null; 5530 } 5531 } 5532 } 5533 } 5534 5535 pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi; 5536 } catch (IOException ioe) { 5537 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5538 } finally { 5539 handle.close(); 5540 } 5541 } 5542 5543 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5544 // We don't do this here during boot because we can do it all 5545 // at once after scanning all existing packages. 5546 // 5547 // We also do this *before* we perform dexopt on this package, so that 5548 // we can avoid redundant dexopts, and also to make sure we've got the 5549 // code and package path correct. 5550 if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5551 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) { 5552 mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE; 5553 return null; 5554 } 5555 } 5556 5557 if ((scanMode&SCAN_NO_DEX) == 0) { 5558 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5559 == DEX_OPT_FAILED) { 5560 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5561 removeDataDirsLI(pkg.packageName); 5562 } 5563 5564 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5565 return null; 5566 } 5567 } 5568 5569 if (mFactoryTest && pkg.requestedPermissions.contains( 5570 android.Manifest.permission.FACTORY_TEST)) { 5571 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5572 } 5573 5574 ArrayList<PackageParser.Package> clientLibPkgs = null; 5575 5576 // writer 5577 synchronized (mPackages) { 5578 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5579 // Only system apps can add new shared libraries. 5580 if (pkg.libraryNames != null) { 5581 for (int i=0; i<pkg.libraryNames.size(); i++) { 5582 String name = pkg.libraryNames.get(i); 5583 boolean allowed = false; 5584 if (isUpdatedSystemApp(pkg)) { 5585 // New library entries can only be added through the 5586 // system image. This is important to get rid of a lot 5587 // of nasty edge cases: for example if we allowed a non- 5588 // system update of the app to add a library, then uninstalling 5589 // the update would make the library go away, and assumptions 5590 // we made such as through app install filtering would now 5591 // have allowed apps on the device which aren't compatible 5592 // with it. Better to just have the restriction here, be 5593 // conservative, and create many fewer cases that can negatively 5594 // impact the user experience. 5595 final PackageSetting sysPs = mSettings 5596 .getDisabledSystemPkgLPr(pkg.packageName); 5597 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5598 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5599 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5600 allowed = true; 5601 allowed = true; 5602 break; 5603 } 5604 } 5605 } 5606 } else { 5607 allowed = true; 5608 } 5609 if (allowed) { 5610 if (!mSharedLibraries.containsKey(name)) { 5611 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5612 } else if (!name.equals(pkg.packageName)) { 5613 Slog.w(TAG, "Package " + pkg.packageName + " library " 5614 + name + " already exists; skipping"); 5615 } 5616 } else { 5617 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5618 + name + " that is not declared on system image; skipping"); 5619 } 5620 } 5621 if ((scanMode&SCAN_BOOTING) == 0) { 5622 // If we are not booting, we need to update any applications 5623 // that are clients of our shared library. If we are booting, 5624 // this will all be done once the scan is complete. 5625 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5626 } 5627 } 5628 } 5629 } 5630 5631 // We also need to dexopt any apps that are dependent on this library. Note that 5632 // if these fail, we should abort the install since installing the library will 5633 // result in some apps being broken. 5634 if (clientLibPkgs != null) { 5635 if ((scanMode&SCAN_NO_DEX) == 0) { 5636 for (int i=0; i<clientLibPkgs.size(); i++) { 5637 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5638 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5639 == DEX_OPT_FAILED) { 5640 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5641 removeDataDirsLI(pkg.packageName); 5642 } 5643 5644 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5645 return null; 5646 } 5647 } 5648 } 5649 } 5650 5651 // Request the ActivityManager to kill the process(only for existing packages) 5652 // so that we do not end up in a confused state while the user is still using the older 5653 // version of the application while the new one gets installed. 5654 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5655 // If the package lives in an asec, tell everyone that the container is going 5656 // away so they can clean up any references to its resources (which would prevent 5657 // vold from being able to unmount the asec) 5658 if (isForwardLocked(pkg) || isExternal(pkg)) { 5659 if (DEBUG_INSTALL) { 5660 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5661 } 5662 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5663 final ArrayList<String> pkgList = new ArrayList<String>(1); 5664 pkgList.add(pkg.applicationInfo.packageName); 5665 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5666 } 5667 5668 // Post the request that it be killed now that the going-away broadcast is en route 5669 killApplication(pkg.applicationInfo.packageName, 5670 pkg.applicationInfo.uid, "update pkg"); 5671 } 5672 5673 // Also need to kill any apps that are dependent on the library. 5674 if (clientLibPkgs != null) { 5675 for (int i=0; i<clientLibPkgs.size(); i++) { 5676 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5677 killApplication(clientPkg.applicationInfo.packageName, 5678 clientPkg.applicationInfo.uid, "update lib"); 5679 } 5680 } 5681 5682 // writer 5683 synchronized (mPackages) { 5684 // We don't expect installation to fail beyond this point, 5685 if ((scanMode&SCAN_MONITOR) != 0) { 5686 mAppDirs.put(pkg.codePath, pkg); 5687 } 5688 // Add the new setting to mSettings 5689 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5690 // Add the new setting to mPackages 5691 mPackages.put(pkg.applicationInfo.packageName, pkg); 5692 // Make sure we don't accidentally delete its data. 5693 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5694 while (iter.hasNext()) { 5695 PackageCleanItem item = iter.next(); 5696 if (pkgName.equals(item.packageName)) { 5697 iter.remove(); 5698 } 5699 } 5700 5701 // Take care of first install / last update times. 5702 if (currentTime != 0) { 5703 if (pkgSetting.firstInstallTime == 0) { 5704 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5705 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5706 pkgSetting.lastUpdateTime = currentTime; 5707 } 5708 } else if (pkgSetting.firstInstallTime == 0) { 5709 // We need *something*. Take time time stamp of the file. 5710 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5711 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5712 if (scanFileTime != pkgSetting.timeStamp) { 5713 // A package on the system image has changed; consider this 5714 // to be an update. 5715 pkgSetting.lastUpdateTime = scanFileTime; 5716 } 5717 } 5718 5719 // Add the package's KeySets to the global KeySetManager 5720 KeySetManager ksm = mSettings.mKeySetManager; 5721 try { 5722 ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5723 if (pkg.mKeySetMapping != null) { 5724 for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) { 5725 if (entry.getValue() != null) { 5726 ksm.addDefinedKeySetToPackage(pkg.packageName, 5727 entry.getValue(), entry.getKey()); 5728 } 5729 } 5730 } 5731 } catch (NullPointerException e) { 5732 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5733 } catch (IllegalArgumentException e) { 5734 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5735 } 5736 5737 int N = pkg.providers.size(); 5738 StringBuilder r = null; 5739 int i; 5740 for (i=0; i<N; i++) { 5741 PackageParser.Provider p = pkg.providers.get(i); 5742 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5743 p.info.processName, pkg.applicationInfo.uid); 5744 mProviders.addProvider(p); 5745 p.syncable = p.info.isSyncable; 5746 if (p.info.authority != null) { 5747 String names[] = p.info.authority.split(";"); 5748 p.info.authority = null; 5749 for (int j = 0; j < names.length; j++) { 5750 if (j == 1 && p.syncable) { 5751 // We only want the first authority for a provider to possibly be 5752 // syncable, so if we already added this provider using a different 5753 // authority clear the syncable flag. We copy the provider before 5754 // changing it because the mProviders object contains a reference 5755 // to a provider that we don't want to change. 5756 // Only do this for the second authority since the resulting provider 5757 // object can be the same for all future authorities for this provider. 5758 p = new PackageParser.Provider(p); 5759 p.syncable = false; 5760 } 5761 if (!mProvidersByAuthority.containsKey(names[j])) { 5762 mProvidersByAuthority.put(names[j], p); 5763 if (p.info.authority == null) { 5764 p.info.authority = names[j]; 5765 } else { 5766 p.info.authority = p.info.authority + ";" + names[j]; 5767 } 5768 if (DEBUG_PACKAGE_SCANNING) { 5769 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5770 Log.d(TAG, "Registered content provider: " + names[j] 5771 + ", className = " + p.info.name + ", isSyncable = " 5772 + p.info.isSyncable); 5773 } 5774 } else { 5775 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5776 Slog.w(TAG, "Skipping provider name " + names[j] + 5777 " (in package " + pkg.applicationInfo.packageName + 5778 "): name already used by " 5779 + ((other != null && other.getComponentName() != null) 5780 ? other.getComponentName().getPackageName() : "?")); 5781 } 5782 } 5783 } 5784 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5785 if (r == null) { 5786 r = new StringBuilder(256); 5787 } else { 5788 r.append(' '); 5789 } 5790 r.append(p.info.name); 5791 } 5792 } 5793 if (r != null) { 5794 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5795 } 5796 5797 N = pkg.services.size(); 5798 r = null; 5799 for (i=0; i<N; i++) { 5800 PackageParser.Service s = pkg.services.get(i); 5801 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5802 s.info.processName, pkg.applicationInfo.uid); 5803 mServices.addService(s); 5804 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5805 if (r == null) { 5806 r = new StringBuilder(256); 5807 } else { 5808 r.append(' '); 5809 } 5810 r.append(s.info.name); 5811 } 5812 } 5813 if (r != null) { 5814 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5815 } 5816 5817 N = pkg.receivers.size(); 5818 r = null; 5819 for (i=0; i<N; i++) { 5820 PackageParser.Activity a = pkg.receivers.get(i); 5821 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5822 a.info.processName, pkg.applicationInfo.uid); 5823 mReceivers.addActivity(a, "receiver"); 5824 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5825 if (r == null) { 5826 r = new StringBuilder(256); 5827 } else { 5828 r.append(' '); 5829 } 5830 r.append(a.info.name); 5831 } 5832 } 5833 if (r != null) { 5834 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5835 } 5836 5837 N = pkg.activities.size(); 5838 r = null; 5839 for (i=0; i<N; i++) { 5840 PackageParser.Activity a = pkg.activities.get(i); 5841 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5842 a.info.processName, pkg.applicationInfo.uid); 5843 mActivities.addActivity(a, "activity"); 5844 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5845 if (r == null) { 5846 r = new StringBuilder(256); 5847 } else { 5848 r.append(' '); 5849 } 5850 r.append(a.info.name); 5851 } 5852 } 5853 if (r != null) { 5854 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5855 } 5856 5857 N = pkg.permissionGroups.size(); 5858 r = null; 5859 for (i=0; i<N; i++) { 5860 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5861 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5862 if (cur == null) { 5863 mPermissionGroups.put(pg.info.name, pg); 5864 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5865 if (r == null) { 5866 r = new StringBuilder(256); 5867 } else { 5868 r.append(' '); 5869 } 5870 r.append(pg.info.name); 5871 } 5872 } else { 5873 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5874 + pg.info.packageName + " ignored: original from " 5875 + cur.info.packageName); 5876 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5877 if (r == null) { 5878 r = new StringBuilder(256); 5879 } else { 5880 r.append(' '); 5881 } 5882 r.append("DUP:"); 5883 r.append(pg.info.name); 5884 } 5885 } 5886 } 5887 if (r != null) { 5888 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5889 } 5890 5891 N = pkg.permissions.size(); 5892 r = null; 5893 for (i=0; i<N; i++) { 5894 PackageParser.Permission p = pkg.permissions.get(i); 5895 HashMap<String, BasePermission> permissionMap = 5896 p.tree ? mSettings.mPermissionTrees 5897 : mSettings.mPermissions; 5898 p.group = mPermissionGroups.get(p.info.group); 5899 if (p.info.group == null || p.group != null) { 5900 BasePermission bp = permissionMap.get(p.info.name); 5901 if (bp == null) { 5902 bp = new BasePermission(p.info.name, p.info.packageName, 5903 BasePermission.TYPE_NORMAL); 5904 permissionMap.put(p.info.name, bp); 5905 } 5906 if (bp.perm == null) { 5907 if (bp.sourcePackage != null 5908 && !bp.sourcePackage.equals(p.info.packageName)) { 5909 // If this is a permission that was formerly defined by a non-system 5910 // app, but is now defined by a system app (following an upgrade), 5911 // discard the previous declaration and consider the system's to be 5912 // canonical. 5913 if (isSystemApp(p.owner)) { 5914 String msg = "New decl " + p.owner + " of permission " 5915 + p.info.name + " is system"; 5916 reportSettingsProblem(Log.WARN, msg); 5917 bp.sourcePackage = null; 5918 } 5919 } 5920 if (bp.sourcePackage == null 5921 || bp.sourcePackage.equals(p.info.packageName)) { 5922 BasePermission tree = findPermissionTreeLP(p.info.name); 5923 if (tree == null 5924 || tree.sourcePackage.equals(p.info.packageName)) { 5925 bp.packageSetting = pkgSetting; 5926 bp.perm = p; 5927 bp.uid = pkg.applicationInfo.uid; 5928 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5929 if (r == null) { 5930 r = new StringBuilder(256); 5931 } else { 5932 r.append(' '); 5933 } 5934 r.append(p.info.name); 5935 } 5936 } else { 5937 Slog.w(TAG, "Permission " + p.info.name + " from package " 5938 + p.info.packageName + " ignored: base tree " 5939 + tree.name + " is from package " 5940 + tree.sourcePackage); 5941 } 5942 } else { 5943 Slog.w(TAG, "Permission " + p.info.name + " from package " 5944 + p.info.packageName + " ignored: original from " 5945 + bp.sourcePackage); 5946 } 5947 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5948 if (r == null) { 5949 r = new StringBuilder(256); 5950 } else { 5951 r.append(' '); 5952 } 5953 r.append("DUP:"); 5954 r.append(p.info.name); 5955 } 5956 if (bp.perm == p) { 5957 bp.protectionLevel = p.info.protectionLevel; 5958 } 5959 } else { 5960 Slog.w(TAG, "Permission " + p.info.name + " from package " 5961 + p.info.packageName + " ignored: no group " 5962 + p.group); 5963 } 5964 } 5965 if (r != null) { 5966 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5967 } 5968 5969 N = pkg.instrumentation.size(); 5970 r = null; 5971 for (i=0; i<N; i++) { 5972 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5973 a.info.packageName = pkg.applicationInfo.packageName; 5974 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5975 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5976 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 5977 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 5978 a.info.dataDir = pkg.applicationInfo.dataDir; 5979 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5980 mInstrumentation.put(a.getComponentName(), a); 5981 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5982 if (r == null) { 5983 r = new StringBuilder(256); 5984 } else { 5985 r.append(' '); 5986 } 5987 r.append(a.info.name); 5988 } 5989 } 5990 if (r != null) { 5991 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5992 } 5993 5994 if (pkg.protectedBroadcasts != null) { 5995 N = pkg.protectedBroadcasts.size(); 5996 for (i=0; i<N; i++) { 5997 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5998 } 5999 } 6000 6001 pkgSetting.setTimeStamp(scanFileTime); 6002 6003 // Create idmap files for pairs of (packages, overlay packages). 6004 // Note: "android", ie framework-res.apk, is handled by native layers. 6005 if (pkg.mOverlayTarget != null) { 6006 // This is an overlay package. 6007 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6008 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6009 mOverlays.put(pkg.mOverlayTarget, 6010 new HashMap<String, PackageParser.Package>()); 6011 } 6012 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6013 map.put(pkg.packageName, pkg); 6014 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6015 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6016 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 6017 return null; 6018 } 6019 } 6020 } else if (mOverlays.containsKey(pkg.packageName) && 6021 !pkg.packageName.equals("android")) { 6022 // This is a regular package, with one or more known overlay packages. 6023 createIdmapsForPackageLI(pkg); 6024 } 6025 } 6026 6027 return pkg; 6028 } 6029 6030 /** 6031 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6032 * i.e, so that all packages can be run inside a single process if required. 6033 * 6034 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6035 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6036 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6037 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6038 * updating a package that belongs to a shared user. 6039 */ 6040 private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6041 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6042 String requiredInstructionSet = null; 6043 if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) { 6044 requiredInstructionSet = VMRuntime.getInstructionSet( 6045 scannedPackage.applicationInfo.cpuAbi); 6046 } 6047 6048 PackageSetting requirer = null; 6049 for (PackageSetting ps : packagesForUser) { 6050 // If packagesForUser contains scannedPackage, we skip it. This will happen 6051 // when scannedPackage is an update of an existing package. Without this check, 6052 // we will never be able to change the ABI of any package belonging to a shared 6053 // user, even if it's compatible with other packages. 6054 if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) { 6055 if (ps.cpuAbiString == null) { 6056 continue; 6057 } 6058 6059 final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 6060 if (requiredInstructionSet != null) { 6061 if (!instructionSet.equals(requiredInstructionSet)) { 6062 // We have a mismatch between instruction sets (say arm vs arm64). 6063 // bail out. 6064 String errorMessage = "Instruction set mismatch, " 6065 + ((requirer == null) ? "[caller]" : requirer) 6066 + " requires " + requiredInstructionSet + " whereas " + ps 6067 + " requires " + instructionSet; 6068 Slog.e(TAG, errorMessage); 6069 6070 reportSettingsProblem(Log.WARN, errorMessage); 6071 // Give up, don't bother making any other changes to the package settings. 6072 return false; 6073 } 6074 } else { 6075 requiredInstructionSet = instructionSet; 6076 requirer = ps; 6077 } 6078 } 6079 } 6080 6081 if (requiredInstructionSet != null) { 6082 String adjustedAbi; 6083 if (requirer != null) { 6084 // requirer != null implies that either scannedPackage was null or that scannedPackage 6085 // did not require an ABI, in which case we have to adjust scannedPackage to match 6086 // the ABI of the set (which is the same as requirer's ABI) 6087 adjustedAbi = requirer.cpuAbiString; 6088 if (scannedPackage != null) { 6089 scannedPackage.applicationInfo.cpuAbi = adjustedAbi; 6090 } 6091 } else { 6092 // requirer == null implies that we're updating all ABIs in the set to 6093 // match scannedPackage. 6094 adjustedAbi = scannedPackage.applicationInfo.cpuAbi; 6095 } 6096 6097 for (PackageSetting ps : packagesForUser) { 6098 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6099 if (ps.cpuAbiString != null) { 6100 continue; 6101 } 6102 6103 ps.cpuAbiString = adjustedAbi; 6104 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6105 ps.pkg.applicationInfo.cpuAbi = adjustedAbi; 6106 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6107 6108 if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) { 6109 ps.cpuAbiString = null; 6110 ps.pkg.applicationInfo.cpuAbi = null; 6111 return false; 6112 } else { 6113 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6114 } 6115 } 6116 } 6117 } 6118 } 6119 6120 return true; 6121 } 6122 6123 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6124 synchronized (mPackages) { 6125 mResolverReplaced = true; 6126 // Set up information for custom user intent resolution activity. 6127 mResolveActivity.applicationInfo = pkg.applicationInfo; 6128 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6129 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6130 mResolveActivity.processName = null; 6131 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6132 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6133 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6134 mResolveActivity.theme = 0; 6135 mResolveActivity.exported = true; 6136 mResolveActivity.enabled = true; 6137 mResolveInfo.activityInfo = mResolveActivity; 6138 mResolveInfo.priority = 0; 6139 mResolveInfo.preferredOrder = 0; 6140 mResolveInfo.match = 0; 6141 mResolveComponentName = mCustomResolverComponentName; 6142 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6143 mResolveComponentName); 6144 } 6145 } 6146 6147 private String calculateApkRoot(final String codePathString) { 6148 final File codePath = new File(codePathString); 6149 final File codeRoot; 6150 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6151 codeRoot = Environment.getRootDirectory(); 6152 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6153 codeRoot = Environment.getOemDirectory(); 6154 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6155 codeRoot = Environment.getVendorDirectory(); 6156 } else { 6157 // Unrecognized code path; take its top real segment as the apk root: 6158 // e.g. /something/app/blah.apk => /something 6159 try { 6160 File f = codePath.getCanonicalFile(); 6161 File parent = f.getParentFile(); // non-null because codePath is a file 6162 File tmp; 6163 while ((tmp = parent.getParentFile()) != null) { 6164 f = parent; 6165 parent = tmp; 6166 } 6167 codeRoot = f; 6168 Slog.w(TAG, "Unrecognized code path " 6169 + codePath + " - using " + codeRoot); 6170 } catch (IOException e) { 6171 // Can't canonicalize the lib path -- shenanigans? 6172 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6173 return Environment.getRootDirectory().getPath(); 6174 } 6175 } 6176 return codeRoot.getPath(); 6177 } 6178 6179 // This is the initial scan-time determination of how to handle a given 6180 // package for purposes of native library location. 6181 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 6182 PackageSetting pkgSetting) { 6183 // "bundled" here means system-installed with no overriding update 6184 final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg); 6185 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 6186 final File libDir; 6187 if (bundledApk) { 6188 // If "/system/lib64/apkname" exists, assume that is the per-package 6189 // native library directory to use; otherwise use "/system/lib/apkname". 6190 String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6191 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 6192 File packLib64 = new File(lib64, apkName); 6193 libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 6194 } else { 6195 libDir = mAppLibInstallDir; 6196 } 6197 final String nativeLibraryPath = (new File(libDir, apkName)).getPath(); 6198 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 6199 // pkgSetting might be null during rescan following uninstall of updates 6200 // to a bundled app, so accommodate that possibility. The settings in 6201 // that case will be established later from the parsed package. 6202 if (pkgSetting != null) { 6203 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 6204 } 6205 } 6206 6207 // Deduces the required ABI of an upgraded system app. 6208 private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) { 6209 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6210 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 6211 6212 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 6213 // or similar. 6214 final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath()); 6215 final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath()); 6216 6217 // Assume that the bundled native libraries always correspond to the 6218 // most preferred 32 or 64 bit ABI. 6219 if (lib64.exists()) { 6220 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6221 pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0]; 6222 } else if (lib.exists()) { 6223 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6224 pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0]; 6225 } else { 6226 // This is the case where the app has no native code. 6227 pkg.applicationInfo.cpuAbi = null; 6228 pkgSetting.cpuAbiString = null; 6229 } 6230 } 6231 6232 private static int copyNativeLibrariesForInternalApp(ApkHandle handle, 6233 final File nativeLibraryDir, String[] abiList) throws IOException { 6234 if (!nativeLibraryDir.isDirectory()) { 6235 nativeLibraryDir.delete(); 6236 6237 if (!nativeLibraryDir.mkdir()) { 6238 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 6239 } 6240 6241 try { 6242 Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6243 } catch (ErrnoException e) { 6244 throw new IOException("Cannot chmod native library directory " 6245 + nativeLibraryDir.getPath(), e); 6246 } 6247 } else if (!SELinux.restorecon(nativeLibraryDir)) { 6248 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 6249 } 6250 6251 /* 6252 * If this is an internal application or our nativeLibraryPath points to 6253 * the app-lib directory, unpack the libraries if necessary. 6254 */ 6255 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6256 if (abi >= 0) { 6257 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 6258 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 6259 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6260 return copyRet; 6261 } 6262 } 6263 6264 return abi; 6265 } 6266 6267 private void killApplication(String pkgName, int appId, String reason) { 6268 // Request the ActivityManager to kill the process(only for existing packages) 6269 // so that we do not end up in a confused state while the user is still using the older 6270 // version of the application while the new one gets installed. 6271 IActivityManager am = ActivityManagerNative.getDefault(); 6272 if (am != null) { 6273 try { 6274 am.killApplicationWithAppId(pkgName, appId, reason); 6275 } catch (RemoteException e) { 6276 } 6277 } 6278 } 6279 6280 void removePackageLI(PackageSetting ps, boolean chatty) { 6281 if (DEBUG_INSTALL) { 6282 if (chatty) 6283 Log.d(TAG, "Removing package " + ps.name); 6284 } 6285 6286 // writer 6287 synchronized (mPackages) { 6288 mPackages.remove(ps.name); 6289 if (ps.codePathString != null) { 6290 mAppDirs.remove(ps.codePathString); 6291 } 6292 6293 final PackageParser.Package pkg = ps.pkg; 6294 if (pkg != null) { 6295 cleanPackageDataStructuresLILPw(pkg, chatty); 6296 } 6297 } 6298 } 6299 6300 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6301 if (DEBUG_INSTALL) { 6302 if (chatty) 6303 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6304 } 6305 6306 // writer 6307 synchronized (mPackages) { 6308 mPackages.remove(pkg.applicationInfo.packageName); 6309 if (pkg.codePath != null) { 6310 mAppDirs.remove(pkg.codePath); 6311 } 6312 cleanPackageDataStructuresLILPw(pkg, chatty); 6313 } 6314 } 6315 6316 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6317 int N = pkg.providers.size(); 6318 StringBuilder r = null; 6319 int i; 6320 for (i=0; i<N; i++) { 6321 PackageParser.Provider p = pkg.providers.get(i); 6322 mProviders.removeProvider(p); 6323 if (p.info.authority == null) { 6324 6325 /* There was another ContentProvider with this authority when 6326 * this app was installed so this authority is null, 6327 * Ignore it as we don't have to unregister the provider. 6328 */ 6329 continue; 6330 } 6331 String names[] = p.info.authority.split(";"); 6332 for (int j = 0; j < names.length; j++) { 6333 if (mProvidersByAuthority.get(names[j]) == p) { 6334 mProvidersByAuthority.remove(names[j]); 6335 if (DEBUG_REMOVE) { 6336 if (chatty) 6337 Log.d(TAG, "Unregistered content provider: " + names[j] 6338 + ", className = " + p.info.name + ", isSyncable = " 6339 + p.info.isSyncable); 6340 } 6341 } 6342 } 6343 if (DEBUG_REMOVE && chatty) { 6344 if (r == null) { 6345 r = new StringBuilder(256); 6346 } else { 6347 r.append(' '); 6348 } 6349 r.append(p.info.name); 6350 } 6351 } 6352 if (r != null) { 6353 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6354 } 6355 6356 N = pkg.services.size(); 6357 r = null; 6358 for (i=0; i<N; i++) { 6359 PackageParser.Service s = pkg.services.get(i); 6360 mServices.removeService(s); 6361 if (chatty) { 6362 if (r == null) { 6363 r = new StringBuilder(256); 6364 } else { 6365 r.append(' '); 6366 } 6367 r.append(s.info.name); 6368 } 6369 } 6370 if (r != null) { 6371 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6372 } 6373 6374 N = pkg.receivers.size(); 6375 r = null; 6376 for (i=0; i<N; i++) { 6377 PackageParser.Activity a = pkg.receivers.get(i); 6378 mReceivers.removeActivity(a, "receiver"); 6379 if (DEBUG_REMOVE && chatty) { 6380 if (r == null) { 6381 r = new StringBuilder(256); 6382 } else { 6383 r.append(' '); 6384 } 6385 r.append(a.info.name); 6386 } 6387 } 6388 if (r != null) { 6389 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6390 } 6391 6392 N = pkg.activities.size(); 6393 r = null; 6394 for (i=0; i<N; i++) { 6395 PackageParser.Activity a = pkg.activities.get(i); 6396 mActivities.removeActivity(a, "activity"); 6397 if (DEBUG_REMOVE && chatty) { 6398 if (r == null) { 6399 r = new StringBuilder(256); 6400 } else { 6401 r.append(' '); 6402 } 6403 r.append(a.info.name); 6404 } 6405 } 6406 if (r != null) { 6407 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6408 } 6409 6410 N = pkg.permissions.size(); 6411 r = null; 6412 for (i=0; i<N; i++) { 6413 PackageParser.Permission p = pkg.permissions.get(i); 6414 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6415 if (bp == null) { 6416 bp = mSettings.mPermissionTrees.get(p.info.name); 6417 } 6418 if (bp != null && bp.perm == p) { 6419 bp.perm = null; 6420 if (DEBUG_REMOVE && chatty) { 6421 if (r == null) { 6422 r = new StringBuilder(256); 6423 } else { 6424 r.append(' '); 6425 } 6426 r.append(p.info.name); 6427 } 6428 } 6429 } 6430 if (r != null) { 6431 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6432 } 6433 6434 N = pkg.instrumentation.size(); 6435 r = null; 6436 for (i=0; i<N; i++) { 6437 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6438 mInstrumentation.remove(a.getComponentName()); 6439 if (DEBUG_REMOVE && chatty) { 6440 if (r == null) { 6441 r = new StringBuilder(256); 6442 } else { 6443 r.append(' '); 6444 } 6445 r.append(a.info.name); 6446 } 6447 } 6448 if (r != null) { 6449 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6450 } 6451 6452 r = null; 6453 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6454 // Only system apps can hold shared libraries. 6455 if (pkg.libraryNames != null) { 6456 for (i=0; i<pkg.libraryNames.size(); i++) { 6457 String name = pkg.libraryNames.get(i); 6458 SharedLibraryEntry cur = mSharedLibraries.get(name); 6459 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6460 mSharedLibraries.remove(name); 6461 if (DEBUG_REMOVE && chatty) { 6462 if (r == null) { 6463 r = new StringBuilder(256); 6464 } else { 6465 r.append(' '); 6466 } 6467 r.append(name); 6468 } 6469 } 6470 } 6471 } 6472 } 6473 if (r != null) { 6474 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6475 } 6476 } 6477 6478 private static final boolean isPackageFilename(String name) { 6479 return name != null && name.endsWith(".apk"); 6480 } 6481 6482 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6483 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6484 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6485 return true; 6486 } 6487 } 6488 return false; 6489 } 6490 6491 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6492 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6493 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6494 6495 private void updatePermissionsLPw(String changingPkg, 6496 PackageParser.Package pkgInfo, int flags) { 6497 // Make sure there are no dangling permission trees. 6498 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6499 while (it.hasNext()) { 6500 final BasePermission bp = it.next(); 6501 if (bp.packageSetting == null) { 6502 // We may not yet have parsed the package, so just see if 6503 // we still know about its settings. 6504 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6505 } 6506 if (bp.packageSetting == null) { 6507 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6508 + " from package " + bp.sourcePackage); 6509 it.remove(); 6510 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6511 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6512 Slog.i(TAG, "Removing old permission tree: " + bp.name 6513 + " from package " + bp.sourcePackage); 6514 flags |= UPDATE_PERMISSIONS_ALL; 6515 it.remove(); 6516 } 6517 } 6518 } 6519 6520 // Make sure all dynamic permissions have been assigned to a package, 6521 // and make sure there are no dangling permissions. 6522 it = mSettings.mPermissions.values().iterator(); 6523 while (it.hasNext()) { 6524 final BasePermission bp = it.next(); 6525 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6526 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6527 + bp.name + " pkg=" + bp.sourcePackage 6528 + " info=" + bp.pendingInfo); 6529 if (bp.packageSetting == null && bp.pendingInfo != null) { 6530 final BasePermission tree = findPermissionTreeLP(bp.name); 6531 if (tree != null && tree.perm != null) { 6532 bp.packageSetting = tree.packageSetting; 6533 bp.perm = new PackageParser.Permission(tree.perm.owner, 6534 new PermissionInfo(bp.pendingInfo)); 6535 bp.perm.info.packageName = tree.perm.info.packageName; 6536 bp.perm.info.name = bp.name; 6537 bp.uid = tree.uid; 6538 } 6539 } 6540 } 6541 if (bp.packageSetting == null) { 6542 // We may not yet have parsed the package, so just see if 6543 // we still know about its settings. 6544 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6545 } 6546 if (bp.packageSetting == null) { 6547 Slog.w(TAG, "Removing dangling permission: " + bp.name 6548 + " from package " + bp.sourcePackage); 6549 it.remove(); 6550 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6551 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6552 Slog.i(TAG, "Removing old permission: " + bp.name 6553 + " from package " + bp.sourcePackage); 6554 flags |= UPDATE_PERMISSIONS_ALL; 6555 it.remove(); 6556 } 6557 } 6558 } 6559 6560 // Now update the permissions for all packages, in particular 6561 // replace the granted permissions of the system packages. 6562 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6563 for (PackageParser.Package pkg : mPackages.values()) { 6564 if (pkg != pkgInfo) { 6565 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6566 } 6567 } 6568 } 6569 6570 if (pkgInfo != null) { 6571 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6572 } 6573 } 6574 6575 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6576 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6577 if (ps == null) { 6578 return; 6579 } 6580 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6581 HashSet<String> origPermissions = gp.grantedPermissions; 6582 boolean changedPermission = false; 6583 6584 if (replace) { 6585 ps.permissionsFixed = false; 6586 if (gp == ps) { 6587 origPermissions = new HashSet<String>(gp.grantedPermissions); 6588 gp.grantedPermissions.clear(); 6589 gp.gids = mGlobalGids; 6590 } 6591 } 6592 6593 if (gp.gids == null) { 6594 gp.gids = mGlobalGids; 6595 } 6596 6597 final int N = pkg.requestedPermissions.size(); 6598 for (int i=0; i<N; i++) { 6599 final String name = pkg.requestedPermissions.get(i); 6600 final boolean required = pkg.requestedPermissionsRequired.get(i); 6601 final BasePermission bp = mSettings.mPermissions.get(name); 6602 if (DEBUG_INSTALL) { 6603 if (gp != ps) { 6604 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6605 } 6606 } 6607 6608 if (bp == null || bp.packageSetting == null) { 6609 Slog.w(TAG, "Unknown permission " + name 6610 + " in package " + pkg.packageName); 6611 continue; 6612 } 6613 6614 final String perm = bp.name; 6615 boolean allowed; 6616 boolean allowedSig = false; 6617 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6618 if (level == PermissionInfo.PROTECTION_NORMAL 6619 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6620 // We grant a normal or dangerous permission if any of the following 6621 // are true: 6622 // 1) The permission is required 6623 // 2) The permission is optional, but was granted in the past 6624 // 3) The permission is optional, but was requested by an 6625 // app in /system (not /data) 6626 // 6627 // Otherwise, reject the permission. 6628 allowed = (required || origPermissions.contains(perm) 6629 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6630 } else if (bp.packageSetting == null) { 6631 // This permission is invalid; skip it. 6632 allowed = false; 6633 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6634 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6635 if (allowed) { 6636 allowedSig = true; 6637 } 6638 } else { 6639 allowed = false; 6640 } 6641 if (DEBUG_INSTALL) { 6642 if (gp != ps) { 6643 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6644 } 6645 } 6646 if (allowed) { 6647 if (!isSystemApp(ps) && ps.permissionsFixed) { 6648 // If this is an existing, non-system package, then 6649 // we can't add any new permissions to it. 6650 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6651 // Except... if this is a permission that was added 6652 // to the platform (note: need to only do this when 6653 // updating the platform). 6654 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6655 } 6656 } 6657 if (allowed) { 6658 if (!gp.grantedPermissions.contains(perm)) { 6659 changedPermission = true; 6660 gp.grantedPermissions.add(perm); 6661 gp.gids = appendInts(gp.gids, bp.gids); 6662 } else if (!ps.haveGids) { 6663 gp.gids = appendInts(gp.gids, bp.gids); 6664 } 6665 } else { 6666 Slog.w(TAG, "Not granting permission " + perm 6667 + " to package " + pkg.packageName 6668 + " because it was previously installed without"); 6669 } 6670 } else { 6671 if (gp.grantedPermissions.remove(perm)) { 6672 changedPermission = true; 6673 gp.gids = removeInts(gp.gids, bp.gids); 6674 Slog.i(TAG, "Un-granting permission " + perm 6675 + " from package " + pkg.packageName 6676 + " (protectionLevel=" + bp.protectionLevel 6677 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6678 + ")"); 6679 } else { 6680 Slog.w(TAG, "Not granting permission " + perm 6681 + " to package " + pkg.packageName 6682 + " (protectionLevel=" + bp.protectionLevel 6683 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6684 + ")"); 6685 } 6686 } 6687 } 6688 6689 if ((changedPermission || replace) && !ps.permissionsFixed && 6690 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6691 // This is the first that we have heard about this package, so the 6692 // permissions we have now selected are fixed until explicitly 6693 // changed. 6694 ps.permissionsFixed = true; 6695 } 6696 ps.haveGids = true; 6697 } 6698 6699 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6700 boolean allowed = false; 6701 final int NP = PackageParser.NEW_PERMISSIONS.length; 6702 for (int ip=0; ip<NP; ip++) { 6703 final PackageParser.NewPermissionInfo npi 6704 = PackageParser.NEW_PERMISSIONS[ip]; 6705 if (npi.name.equals(perm) 6706 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6707 allowed = true; 6708 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6709 + pkg.packageName); 6710 break; 6711 } 6712 } 6713 return allowed; 6714 } 6715 6716 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6717 BasePermission bp, HashSet<String> origPermissions) { 6718 boolean allowed; 6719 allowed = (compareSignatures( 6720 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6721 == PackageManager.SIGNATURE_MATCH) 6722 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6723 == PackageManager.SIGNATURE_MATCH); 6724 if (!allowed && (bp.protectionLevel 6725 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6726 if (isSystemApp(pkg)) { 6727 // For updated system applications, a system permission 6728 // is granted only if it had been defined by the original application. 6729 if (isUpdatedSystemApp(pkg)) { 6730 final PackageSetting sysPs = mSettings 6731 .getDisabledSystemPkgLPr(pkg.packageName); 6732 final GrantedPermissions origGp = sysPs.sharedUser != null 6733 ? sysPs.sharedUser : sysPs; 6734 6735 if (origGp.grantedPermissions.contains(perm)) { 6736 // If the original was granted this permission, we take 6737 // that grant decision as read and propagate it to the 6738 // update. 6739 allowed = true; 6740 } else { 6741 // The system apk may have been updated with an older 6742 // version of the one on the data partition, but which 6743 // granted a new system permission that it didn't have 6744 // before. In this case we do want to allow the app to 6745 // now get the new permission if the ancestral apk is 6746 // privileged to get it. 6747 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6748 for (int j=0; 6749 j<sysPs.pkg.requestedPermissions.size(); j++) { 6750 if (perm.equals( 6751 sysPs.pkg.requestedPermissions.get(j))) { 6752 allowed = true; 6753 break; 6754 } 6755 } 6756 } 6757 } 6758 } else { 6759 allowed = isPrivilegedApp(pkg); 6760 } 6761 } 6762 } 6763 if (!allowed && (bp.protectionLevel 6764 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6765 // For development permissions, a development permission 6766 // is granted only if it was already granted. 6767 allowed = origPermissions.contains(perm); 6768 } 6769 return allowed; 6770 } 6771 6772 final class ActivityIntentResolver 6773 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6774 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6775 boolean defaultOnly, int userId) { 6776 if (!sUserManager.exists(userId)) return null; 6777 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6778 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6779 } 6780 6781 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6782 int userId) { 6783 if (!sUserManager.exists(userId)) return null; 6784 mFlags = flags; 6785 return super.queryIntent(intent, resolvedType, 6786 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6787 } 6788 6789 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6790 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6791 if (!sUserManager.exists(userId)) return null; 6792 if (packageActivities == null) { 6793 return null; 6794 } 6795 mFlags = flags; 6796 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6797 final int N = packageActivities.size(); 6798 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6799 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6800 6801 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6802 for (int i = 0; i < N; ++i) { 6803 intentFilters = packageActivities.get(i).intents; 6804 if (intentFilters != null && intentFilters.size() > 0) { 6805 PackageParser.ActivityIntentInfo[] array = 6806 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6807 intentFilters.toArray(array); 6808 listCut.add(array); 6809 } 6810 } 6811 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6812 } 6813 6814 public final void addActivity(PackageParser.Activity a, String type) { 6815 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6816 mActivities.put(a.getComponentName(), a); 6817 if (DEBUG_SHOW_INFO) 6818 Log.v( 6819 TAG, " " + type + " " + 6820 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6821 if (DEBUG_SHOW_INFO) 6822 Log.v(TAG, " Class=" + a.info.name); 6823 final int NI = a.intents.size(); 6824 for (int j=0; j<NI; j++) { 6825 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6826 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6827 intent.setPriority(0); 6828 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6829 + a.className + " with priority > 0, forcing to 0"); 6830 } 6831 if (DEBUG_SHOW_INFO) { 6832 Log.v(TAG, " IntentFilter:"); 6833 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6834 } 6835 if (!intent.debugCheck()) { 6836 Log.w(TAG, "==> For Activity " + a.info.name); 6837 } 6838 addFilter(intent); 6839 } 6840 } 6841 6842 public final void removeActivity(PackageParser.Activity a, String type) { 6843 mActivities.remove(a.getComponentName()); 6844 if (DEBUG_SHOW_INFO) { 6845 Log.v(TAG, " " + type + " " 6846 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6847 : a.info.name) + ":"); 6848 Log.v(TAG, " Class=" + a.info.name); 6849 } 6850 final int NI = a.intents.size(); 6851 for (int j=0; j<NI; j++) { 6852 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6853 if (DEBUG_SHOW_INFO) { 6854 Log.v(TAG, " IntentFilter:"); 6855 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6856 } 6857 removeFilter(intent); 6858 } 6859 } 6860 6861 @Override 6862 protected boolean allowFilterResult( 6863 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6864 ActivityInfo filterAi = filter.activity.info; 6865 for (int i=dest.size()-1; i>=0; i--) { 6866 ActivityInfo destAi = dest.get(i).activityInfo; 6867 if (destAi.name == filterAi.name 6868 && destAi.packageName == filterAi.packageName) { 6869 return false; 6870 } 6871 } 6872 return true; 6873 } 6874 6875 @Override 6876 protected ActivityIntentInfo[] newArray(int size) { 6877 return new ActivityIntentInfo[size]; 6878 } 6879 6880 @Override 6881 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6882 if (!sUserManager.exists(userId)) return true; 6883 PackageParser.Package p = filter.activity.owner; 6884 if (p != null) { 6885 PackageSetting ps = (PackageSetting)p.mExtras; 6886 if (ps != null) { 6887 // System apps are never considered stopped for purposes of 6888 // filtering, because there may be no way for the user to 6889 // actually re-launch them. 6890 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6891 && ps.getStopped(userId); 6892 } 6893 } 6894 return false; 6895 } 6896 6897 @Override 6898 protected boolean isPackageForFilter(String packageName, 6899 PackageParser.ActivityIntentInfo info) { 6900 return packageName.equals(info.activity.owner.packageName); 6901 } 6902 6903 @Override 6904 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6905 int match, int userId) { 6906 if (!sUserManager.exists(userId)) return null; 6907 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6908 return null; 6909 } 6910 final PackageParser.Activity activity = info.activity; 6911 if (mSafeMode && (activity.info.applicationInfo.flags 6912 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6913 return null; 6914 } 6915 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6916 if (ps == null) { 6917 return null; 6918 } 6919 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6920 ps.readUserState(userId), userId); 6921 if (ai == null) { 6922 return null; 6923 } 6924 final ResolveInfo res = new ResolveInfo(); 6925 res.activityInfo = ai; 6926 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6927 res.filter = info; 6928 } 6929 res.priority = info.getPriority(); 6930 res.preferredOrder = activity.owner.mPreferredOrder; 6931 //System.out.println("Result: " + res.activityInfo.className + 6932 // " = " + res.priority); 6933 res.match = match; 6934 res.isDefault = info.hasDefault; 6935 res.labelRes = info.labelRes; 6936 res.nonLocalizedLabel = info.nonLocalizedLabel; 6937 res.icon = info.icon; 6938 res.system = isSystemApp(res.activityInfo.applicationInfo); 6939 return res; 6940 } 6941 6942 @Override 6943 protected void sortResults(List<ResolveInfo> results) { 6944 Collections.sort(results, mResolvePrioritySorter); 6945 } 6946 6947 @Override 6948 protected void dumpFilter(PrintWriter out, String prefix, 6949 PackageParser.ActivityIntentInfo filter) { 6950 out.print(prefix); out.print( 6951 Integer.toHexString(System.identityHashCode(filter.activity))); 6952 out.print(' '); 6953 filter.activity.printComponentShortName(out); 6954 out.print(" filter "); 6955 out.println(Integer.toHexString(System.identityHashCode(filter))); 6956 } 6957 6958// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6959// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6960// final List<ResolveInfo> retList = Lists.newArrayList(); 6961// while (i.hasNext()) { 6962// final ResolveInfo resolveInfo = i.next(); 6963// if (isEnabledLP(resolveInfo.activityInfo)) { 6964// retList.add(resolveInfo); 6965// } 6966// } 6967// return retList; 6968// } 6969 6970 // Keys are String (activity class name), values are Activity. 6971 private final HashMap<ComponentName, PackageParser.Activity> mActivities 6972 = new HashMap<ComponentName, PackageParser.Activity>(); 6973 private int mFlags; 6974 } 6975 6976 private final class ServiceIntentResolver 6977 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 6978 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6979 boolean defaultOnly, int userId) { 6980 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6981 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6982 } 6983 6984 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6985 int userId) { 6986 if (!sUserManager.exists(userId)) return null; 6987 mFlags = flags; 6988 return super.queryIntent(intent, resolvedType, 6989 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6990 } 6991 6992 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6993 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 6994 if (!sUserManager.exists(userId)) return null; 6995 if (packageServices == null) { 6996 return null; 6997 } 6998 mFlags = flags; 6999 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7000 final int N = packageServices.size(); 7001 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7002 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7003 7004 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7005 for (int i = 0; i < N; ++i) { 7006 intentFilters = packageServices.get(i).intents; 7007 if (intentFilters != null && intentFilters.size() > 0) { 7008 PackageParser.ServiceIntentInfo[] array = 7009 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7010 intentFilters.toArray(array); 7011 listCut.add(array); 7012 } 7013 } 7014 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7015 } 7016 7017 public final void addService(PackageParser.Service s) { 7018 mServices.put(s.getComponentName(), s); 7019 if (DEBUG_SHOW_INFO) { 7020 Log.v(TAG, " " 7021 + (s.info.nonLocalizedLabel != null 7022 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7023 Log.v(TAG, " Class=" + s.info.name); 7024 } 7025 final int NI = s.intents.size(); 7026 int j; 7027 for (j=0; j<NI; j++) { 7028 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7029 if (DEBUG_SHOW_INFO) { 7030 Log.v(TAG, " IntentFilter:"); 7031 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7032 } 7033 if (!intent.debugCheck()) { 7034 Log.w(TAG, "==> For Service " + s.info.name); 7035 } 7036 addFilter(intent); 7037 } 7038 } 7039 7040 public final void removeService(PackageParser.Service s) { 7041 mServices.remove(s.getComponentName()); 7042 if (DEBUG_SHOW_INFO) { 7043 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7044 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7045 Log.v(TAG, " Class=" + s.info.name); 7046 } 7047 final int NI = s.intents.size(); 7048 int j; 7049 for (j=0; j<NI; j++) { 7050 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7051 if (DEBUG_SHOW_INFO) { 7052 Log.v(TAG, " IntentFilter:"); 7053 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7054 } 7055 removeFilter(intent); 7056 } 7057 } 7058 7059 @Override 7060 protected boolean allowFilterResult( 7061 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7062 ServiceInfo filterSi = filter.service.info; 7063 for (int i=dest.size()-1; i>=0; i--) { 7064 ServiceInfo destAi = dest.get(i).serviceInfo; 7065 if (destAi.name == filterSi.name 7066 && destAi.packageName == filterSi.packageName) { 7067 return false; 7068 } 7069 } 7070 return true; 7071 } 7072 7073 @Override 7074 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7075 return new PackageParser.ServiceIntentInfo[size]; 7076 } 7077 7078 @Override 7079 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7080 if (!sUserManager.exists(userId)) return true; 7081 PackageParser.Package p = filter.service.owner; 7082 if (p != null) { 7083 PackageSetting ps = (PackageSetting)p.mExtras; 7084 if (ps != null) { 7085 // System apps are never considered stopped for purposes of 7086 // filtering, because there may be no way for the user to 7087 // actually re-launch them. 7088 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7089 && ps.getStopped(userId); 7090 } 7091 } 7092 return false; 7093 } 7094 7095 @Override 7096 protected boolean isPackageForFilter(String packageName, 7097 PackageParser.ServiceIntentInfo info) { 7098 return packageName.equals(info.service.owner.packageName); 7099 } 7100 7101 @Override 7102 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7103 int match, int userId) { 7104 if (!sUserManager.exists(userId)) return null; 7105 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7106 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7107 return null; 7108 } 7109 final PackageParser.Service service = info.service; 7110 if (mSafeMode && (service.info.applicationInfo.flags 7111 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7112 return null; 7113 } 7114 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7115 if (ps == null) { 7116 return null; 7117 } 7118 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7119 ps.readUserState(userId), userId); 7120 if (si == null) { 7121 return null; 7122 } 7123 final ResolveInfo res = new ResolveInfo(); 7124 res.serviceInfo = si; 7125 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7126 res.filter = filter; 7127 } 7128 res.priority = info.getPriority(); 7129 res.preferredOrder = service.owner.mPreferredOrder; 7130 //System.out.println("Result: " + res.activityInfo.className + 7131 // " = " + res.priority); 7132 res.match = match; 7133 res.isDefault = info.hasDefault; 7134 res.labelRes = info.labelRes; 7135 res.nonLocalizedLabel = info.nonLocalizedLabel; 7136 res.icon = info.icon; 7137 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7138 return res; 7139 } 7140 7141 @Override 7142 protected void sortResults(List<ResolveInfo> results) { 7143 Collections.sort(results, mResolvePrioritySorter); 7144 } 7145 7146 @Override 7147 protected void dumpFilter(PrintWriter out, String prefix, 7148 PackageParser.ServiceIntentInfo filter) { 7149 out.print(prefix); out.print( 7150 Integer.toHexString(System.identityHashCode(filter.service))); 7151 out.print(' '); 7152 filter.service.printComponentShortName(out); 7153 out.print(" filter "); 7154 out.println(Integer.toHexString(System.identityHashCode(filter))); 7155 } 7156 7157// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7158// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7159// final List<ResolveInfo> retList = Lists.newArrayList(); 7160// while (i.hasNext()) { 7161// final ResolveInfo resolveInfo = (ResolveInfo) i; 7162// if (isEnabledLP(resolveInfo.serviceInfo)) { 7163// retList.add(resolveInfo); 7164// } 7165// } 7166// return retList; 7167// } 7168 7169 // Keys are String (activity class name), values are Activity. 7170 private final HashMap<ComponentName, PackageParser.Service> mServices 7171 = new HashMap<ComponentName, PackageParser.Service>(); 7172 private int mFlags; 7173 }; 7174 7175 private final class ProviderIntentResolver 7176 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7177 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7178 boolean defaultOnly, int userId) { 7179 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7180 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7181 } 7182 7183 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7184 int userId) { 7185 if (!sUserManager.exists(userId)) 7186 return null; 7187 mFlags = flags; 7188 return super.queryIntent(intent, resolvedType, 7189 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7190 } 7191 7192 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7193 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7194 if (!sUserManager.exists(userId)) 7195 return null; 7196 if (packageProviders == null) { 7197 return null; 7198 } 7199 mFlags = flags; 7200 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7201 final int N = packageProviders.size(); 7202 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7203 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7204 7205 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7206 for (int i = 0; i < N; ++i) { 7207 intentFilters = packageProviders.get(i).intents; 7208 if (intentFilters != null && intentFilters.size() > 0) { 7209 PackageParser.ProviderIntentInfo[] array = 7210 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7211 intentFilters.toArray(array); 7212 listCut.add(array); 7213 } 7214 } 7215 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7216 } 7217 7218 public final void addProvider(PackageParser.Provider p) { 7219 if (mProviders.containsKey(p.getComponentName())) { 7220 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7221 return; 7222 } 7223 7224 mProviders.put(p.getComponentName(), p); 7225 if (DEBUG_SHOW_INFO) { 7226 Log.v(TAG, " " 7227 + (p.info.nonLocalizedLabel != null 7228 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7229 Log.v(TAG, " Class=" + p.info.name); 7230 } 7231 final int NI = p.intents.size(); 7232 int j; 7233 for (j = 0; j < NI; j++) { 7234 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7235 if (DEBUG_SHOW_INFO) { 7236 Log.v(TAG, " IntentFilter:"); 7237 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7238 } 7239 if (!intent.debugCheck()) { 7240 Log.w(TAG, "==> For Provider " + p.info.name); 7241 } 7242 addFilter(intent); 7243 } 7244 } 7245 7246 public final void removeProvider(PackageParser.Provider p) { 7247 mProviders.remove(p.getComponentName()); 7248 if (DEBUG_SHOW_INFO) { 7249 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7250 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7251 Log.v(TAG, " Class=" + p.info.name); 7252 } 7253 final int NI = p.intents.size(); 7254 int j; 7255 for (j = 0; j < NI; j++) { 7256 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7257 if (DEBUG_SHOW_INFO) { 7258 Log.v(TAG, " IntentFilter:"); 7259 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7260 } 7261 removeFilter(intent); 7262 } 7263 } 7264 7265 @Override 7266 protected boolean allowFilterResult( 7267 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7268 ProviderInfo filterPi = filter.provider.info; 7269 for (int i = dest.size() - 1; i >= 0; i--) { 7270 ProviderInfo destPi = dest.get(i).providerInfo; 7271 if (destPi.name == filterPi.name 7272 && destPi.packageName == filterPi.packageName) { 7273 return false; 7274 } 7275 } 7276 return true; 7277 } 7278 7279 @Override 7280 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7281 return new PackageParser.ProviderIntentInfo[size]; 7282 } 7283 7284 @Override 7285 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7286 if (!sUserManager.exists(userId)) 7287 return true; 7288 PackageParser.Package p = filter.provider.owner; 7289 if (p != null) { 7290 PackageSetting ps = (PackageSetting) p.mExtras; 7291 if (ps != null) { 7292 // System apps are never considered stopped for purposes of 7293 // filtering, because there may be no way for the user to 7294 // actually re-launch them. 7295 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7296 && ps.getStopped(userId); 7297 } 7298 } 7299 return false; 7300 } 7301 7302 @Override 7303 protected boolean isPackageForFilter(String packageName, 7304 PackageParser.ProviderIntentInfo info) { 7305 return packageName.equals(info.provider.owner.packageName); 7306 } 7307 7308 @Override 7309 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7310 int match, int userId) { 7311 if (!sUserManager.exists(userId)) 7312 return null; 7313 final PackageParser.ProviderIntentInfo info = filter; 7314 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7315 return null; 7316 } 7317 final PackageParser.Provider provider = info.provider; 7318 if (mSafeMode && (provider.info.applicationInfo.flags 7319 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7320 return null; 7321 } 7322 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7323 if (ps == null) { 7324 return null; 7325 } 7326 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7327 ps.readUserState(userId), userId); 7328 if (pi == null) { 7329 return null; 7330 } 7331 final ResolveInfo res = new ResolveInfo(); 7332 res.providerInfo = pi; 7333 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7334 res.filter = filter; 7335 } 7336 res.priority = info.getPriority(); 7337 res.preferredOrder = provider.owner.mPreferredOrder; 7338 res.match = match; 7339 res.isDefault = info.hasDefault; 7340 res.labelRes = info.labelRes; 7341 res.nonLocalizedLabel = info.nonLocalizedLabel; 7342 res.icon = info.icon; 7343 res.system = isSystemApp(res.providerInfo.applicationInfo); 7344 return res; 7345 } 7346 7347 @Override 7348 protected void sortResults(List<ResolveInfo> results) { 7349 Collections.sort(results, mResolvePrioritySorter); 7350 } 7351 7352 @Override 7353 protected void dumpFilter(PrintWriter out, String prefix, 7354 PackageParser.ProviderIntentInfo filter) { 7355 out.print(prefix); 7356 out.print( 7357 Integer.toHexString(System.identityHashCode(filter.provider))); 7358 out.print(' '); 7359 filter.provider.printComponentShortName(out); 7360 out.print(" filter "); 7361 out.println(Integer.toHexString(System.identityHashCode(filter))); 7362 } 7363 7364 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7365 = new HashMap<ComponentName, PackageParser.Provider>(); 7366 private int mFlags; 7367 }; 7368 7369 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7370 new Comparator<ResolveInfo>() { 7371 public int compare(ResolveInfo r1, ResolveInfo r2) { 7372 int v1 = r1.priority; 7373 int v2 = r2.priority; 7374 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7375 if (v1 != v2) { 7376 return (v1 > v2) ? -1 : 1; 7377 } 7378 v1 = r1.preferredOrder; 7379 v2 = r2.preferredOrder; 7380 if (v1 != v2) { 7381 return (v1 > v2) ? -1 : 1; 7382 } 7383 if (r1.isDefault != r2.isDefault) { 7384 return r1.isDefault ? -1 : 1; 7385 } 7386 v1 = r1.match; 7387 v2 = r2.match; 7388 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7389 if (v1 != v2) { 7390 return (v1 > v2) ? -1 : 1; 7391 } 7392 if (r1.system != r2.system) { 7393 return r1.system ? -1 : 1; 7394 } 7395 return 0; 7396 } 7397 }; 7398 7399 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7400 new Comparator<ProviderInfo>() { 7401 public int compare(ProviderInfo p1, ProviderInfo p2) { 7402 final int v1 = p1.initOrder; 7403 final int v2 = p2.initOrder; 7404 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7405 } 7406 }; 7407 7408 static final void sendPackageBroadcast(String action, String pkg, 7409 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7410 int[] userIds) { 7411 IActivityManager am = ActivityManagerNative.getDefault(); 7412 if (am != null) { 7413 try { 7414 if (userIds == null) { 7415 userIds = am.getRunningUserIds(); 7416 } 7417 for (int id : userIds) { 7418 final Intent intent = new Intent(action, 7419 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7420 if (extras != null) { 7421 intent.putExtras(extras); 7422 } 7423 if (targetPkg != null) { 7424 intent.setPackage(targetPkg); 7425 } 7426 // Modify the UID when posting to other users 7427 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7428 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7429 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7430 intent.putExtra(Intent.EXTRA_UID, uid); 7431 } 7432 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7433 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7434 if (DEBUG_BROADCASTS) { 7435 RuntimeException here = new RuntimeException("here"); 7436 here.fillInStackTrace(); 7437 Slog.d(TAG, "Sending to user " + id + ": " 7438 + intent.toShortString(false, true, false, false) 7439 + " " + intent.getExtras(), here); 7440 } 7441 am.broadcastIntent(null, intent, null, finishedReceiver, 7442 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7443 finishedReceiver != null, false, id); 7444 } 7445 } catch (RemoteException ex) { 7446 } 7447 } 7448 } 7449 7450 /** 7451 * Check if the external storage media is available. This is true if there 7452 * is a mounted external storage medium or if the external storage is 7453 * emulated. 7454 */ 7455 private boolean isExternalMediaAvailable() { 7456 return mMediaMounted || Environment.isExternalStorageEmulated(); 7457 } 7458 7459 @Override 7460 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7461 // writer 7462 synchronized (mPackages) { 7463 if (!isExternalMediaAvailable()) { 7464 // If the external storage is no longer mounted at this point, 7465 // the caller may not have been able to delete all of this 7466 // packages files and can not delete any more. Bail. 7467 return null; 7468 } 7469 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7470 if (lastPackage != null) { 7471 pkgs.remove(lastPackage); 7472 } 7473 if (pkgs.size() > 0) { 7474 return pkgs.get(0); 7475 } 7476 } 7477 return null; 7478 } 7479 7480 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7481 if (false) { 7482 RuntimeException here = new RuntimeException("here"); 7483 here.fillInStackTrace(); 7484 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7485 + " andCode=" + andCode, here); 7486 } 7487 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7488 userId, andCode ? 1 : 0, packageName)); 7489 } 7490 7491 void startCleaningPackages() { 7492 // reader 7493 synchronized (mPackages) { 7494 if (!isExternalMediaAvailable()) { 7495 return; 7496 } 7497 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7498 return; 7499 } 7500 } 7501 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7502 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7503 IActivityManager am = ActivityManagerNative.getDefault(); 7504 if (am != null) { 7505 try { 7506 am.startService(null, intent, null, UserHandle.USER_OWNER); 7507 } catch (RemoteException e) { 7508 } 7509 } 7510 } 7511 7512 private final class AppDirObserver extends FileObserver { 7513 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7514 super(path, mask); 7515 mRootDir = path; 7516 mIsRom = isrom; 7517 mIsPrivileged = isPrivileged; 7518 } 7519 7520 public void onEvent(int event, String path) { 7521 String removedPackage = null; 7522 int removedAppId = -1; 7523 int[] removedUsers = null; 7524 String addedPackage = null; 7525 int addedAppId = -1; 7526 int[] addedUsers = null; 7527 7528 // TODO post a message to the handler to obtain serial ordering 7529 synchronized (mInstallLock) { 7530 String fullPathStr = null; 7531 File fullPath = null; 7532 if (path != null) { 7533 fullPath = new File(mRootDir, path); 7534 fullPathStr = fullPath.getPath(); 7535 } 7536 7537 if (DEBUG_APP_DIR_OBSERVER) 7538 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7539 7540 if (!isPackageFilename(path)) { 7541 if (DEBUG_APP_DIR_OBSERVER) 7542 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7543 return; 7544 } 7545 7546 // Ignore packages that are being installed or 7547 // have just been installed. 7548 if (ignoreCodePath(fullPathStr)) { 7549 return; 7550 } 7551 PackageParser.Package p = null; 7552 PackageSetting ps = null; 7553 // reader 7554 synchronized (mPackages) { 7555 p = mAppDirs.get(fullPathStr); 7556 if (p != null) { 7557 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7558 if (ps != null) { 7559 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7560 } else { 7561 removedUsers = sUserManager.getUserIds(); 7562 } 7563 } 7564 addedUsers = sUserManager.getUserIds(); 7565 } 7566 if ((event&REMOVE_EVENTS) != 0) { 7567 if (ps != null) { 7568 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7569 removePackageLI(ps, true); 7570 removedPackage = ps.name; 7571 removedAppId = ps.appId; 7572 } 7573 } 7574 7575 if ((event&ADD_EVENTS) != 0) { 7576 if (p == null) { 7577 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7578 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7579 if (mIsRom) { 7580 flags |= PackageParser.PARSE_IS_SYSTEM 7581 | PackageParser.PARSE_IS_SYSTEM_DIR; 7582 if (mIsPrivileged) { 7583 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7584 } 7585 } 7586 p = scanPackageLI(fullPath, flags, 7587 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7588 System.currentTimeMillis(), UserHandle.ALL, null); 7589 if (p != null) { 7590 /* 7591 * TODO this seems dangerous as the package may have 7592 * changed since we last acquired the mPackages 7593 * lock. 7594 */ 7595 // writer 7596 synchronized (mPackages) { 7597 updatePermissionsLPw(p.packageName, p, 7598 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7599 } 7600 addedPackage = p.applicationInfo.packageName; 7601 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7602 } 7603 } 7604 } 7605 7606 // reader 7607 synchronized (mPackages) { 7608 mSettings.writeLPr(); 7609 } 7610 } 7611 7612 if (removedPackage != null) { 7613 Bundle extras = new Bundle(1); 7614 extras.putInt(Intent.EXTRA_UID, removedAppId); 7615 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7616 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7617 extras, null, null, removedUsers); 7618 } 7619 if (addedPackage != null) { 7620 Bundle extras = new Bundle(1); 7621 extras.putInt(Intent.EXTRA_UID, addedAppId); 7622 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7623 extras, null, null, addedUsers); 7624 } 7625 } 7626 7627 private final String mRootDir; 7628 private final boolean mIsRom; 7629 private final boolean mIsPrivileged; 7630 } 7631 7632 /* 7633 * The old-style observer methods all just trampoline to the newer signature with 7634 * expanded install observer API. The older API continues to work but does not 7635 * supply the additional details of the Observer2 API. 7636 */ 7637 7638 /* Called when a downloaded package installation has been confirmed by the user */ 7639 public void installPackage( 7640 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 7641 installPackageEtc(packageURI, observer, null, flags, null); 7642 } 7643 7644 /* Called when a downloaded package installation has been confirmed by the user */ 7645 @Override 7646 public void installPackage( 7647 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 7648 final String installerPackageName) { 7649 installPackageWithVerificationEtc(packageURI, observer, null, flags, 7650 installerPackageName, null, null, null); 7651 } 7652 7653 @Override 7654 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 7655 int flags, String installerPackageName, Uri verificationURI, 7656 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7657 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7658 VerificationParams.NO_UID, manifestDigest); 7659 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7660 installerPackageName, verificationParams, encryptionParams); 7661 } 7662 7663 @Override 7664 public void installPackageWithVerificationAndEncryption(Uri packageURI, 7665 IPackageInstallObserver observer, int flags, String installerPackageName, 7666 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7667 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7668 installerPackageName, verificationParams, encryptionParams); 7669 } 7670 7671 /* 7672 * And here are the "live" versions that take both observer arguments 7673 */ 7674 public void installPackageEtc( 7675 final Uri packageURI, final IPackageInstallObserver observer, 7676 IPackageInstallObserver2 observer2, final int flags) { 7677 installPackageEtc(packageURI, observer, observer2, flags, null); 7678 } 7679 7680 public void installPackageEtc( 7681 final Uri packageURI, final IPackageInstallObserver observer, 7682 final IPackageInstallObserver2 observer2, final int flags, 7683 final String installerPackageName) { 7684 installPackageWithVerificationEtc(packageURI, observer, observer2, flags, 7685 installerPackageName, null, null, null); 7686 } 7687 7688 @Override 7689 public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer, 7690 IPackageInstallObserver2 observer2, 7691 int flags, String installerPackageName, Uri verificationURI, 7692 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7693 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7694 VerificationParams.NO_UID, manifestDigest); 7695 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags, 7696 installerPackageName, verificationParams, encryptionParams); 7697 } 7698 7699 /* 7700 * All of the installPackage...*() methods redirect to this one for the master implementation 7701 */ 7702 public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI, 7703 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7704 int flags, String installerPackageName, 7705 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7706 if (observer == null && observer2 == null) { 7707 throw new IllegalArgumentException("No install observer supplied"); 7708 } 7709 installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2, 7710 flags, installerPackageName, verificationParams, encryptionParams, null); 7711 } 7712 7713 @Override 7714 public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI, 7715 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7716 int flags, String installerPackageName, 7717 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams, 7718 String packageAbiOverride) { 7719 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7720 null); 7721 7722 final int uid = Binder.getCallingUid(); 7723 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7724 try { 7725 if (observer != null) { 7726 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7727 } 7728 if (observer2 != null) { 7729 observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7730 } 7731 } catch (RemoteException re) { 7732 } 7733 return; 7734 } 7735 7736 UserHandle user; 7737 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7738 user = UserHandle.ALL; 7739 } else { 7740 user = new UserHandle(UserHandle.getUserId(uid)); 7741 } 7742 7743 final int filteredFlags; 7744 7745 if (uid == Process.SHELL_UID || uid == 0) { 7746 if (DEBUG_INSTALL) { 7747 Slog.v(TAG, "Install from ADB"); 7748 } 7749 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7750 } else { 7751 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7752 } 7753 7754 verificationParams.setInstallerUid(uid); 7755 7756 final Message msg = mHandler.obtainMessage(INIT_COPY); 7757 msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags, 7758 installerPackageName, verificationParams, encryptionParams, user, 7759 packageAbiOverride); 7760 mHandler.sendMessage(msg); 7761 } 7762 7763 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7764 Bundle extras = new Bundle(1); 7765 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7766 7767 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7768 packageName, extras, null, null, new int[] {userId}); 7769 try { 7770 IActivityManager am = ActivityManagerNative.getDefault(); 7771 final boolean isSystem = 7772 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7773 if (isSystem && am.isUserRunning(userId, false)) { 7774 // The just-installed/enabled app is bundled on the system, so presumed 7775 // to be able to run automatically without needing an explicit launch. 7776 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7777 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7778 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7779 .setPackage(packageName); 7780 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7781 android.app.AppOpsManager.OP_NONE, false, false, userId); 7782 } 7783 } catch (RemoteException e) { 7784 // shouldn't happen 7785 Slog.w(TAG, "Unable to bootstrap installed package", e); 7786 } 7787 } 7788 7789 @Override 7790 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7791 int userId) { 7792 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7793 PackageSetting pkgSetting; 7794 final int uid = Binder.getCallingUid(); 7795 if (UserHandle.getUserId(uid) != userId) { 7796 mContext.enforceCallingOrSelfPermission( 7797 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7798 "setApplicationBlockedSetting for user " + userId); 7799 } 7800 7801 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7802 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7803 return false; 7804 } 7805 7806 long callingId = Binder.clearCallingIdentity(); 7807 try { 7808 boolean sendAdded = false; 7809 boolean sendRemoved = false; 7810 // writer 7811 synchronized (mPackages) { 7812 pkgSetting = mSettings.mPackages.get(packageName); 7813 if (pkgSetting == null) { 7814 return false; 7815 } 7816 if (pkgSetting.getBlocked(userId) != blocked) { 7817 pkgSetting.setBlocked(blocked, userId); 7818 mSettings.writePackageRestrictionsLPr(userId); 7819 if (blocked) { 7820 sendRemoved = true; 7821 } else { 7822 sendAdded = true; 7823 } 7824 } 7825 } 7826 if (sendAdded) { 7827 sendPackageAddedForUser(packageName, pkgSetting, userId); 7828 return true; 7829 } 7830 if (sendRemoved) { 7831 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7832 "blocking pkg"); 7833 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7834 } 7835 } finally { 7836 Binder.restoreCallingIdentity(callingId); 7837 } 7838 return false; 7839 } 7840 7841 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7842 int userId) { 7843 final PackageRemovedInfo info = new PackageRemovedInfo(); 7844 info.removedPackage = packageName; 7845 info.removedUsers = new int[] {userId}; 7846 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7847 info.sendBroadcast(false, false, false); 7848 } 7849 7850 /** 7851 * Returns true if application is not found or there was an error. Otherwise it returns 7852 * the blocked state of the package for the given user. 7853 */ 7854 @Override 7855 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7856 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7857 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7858 "getApplicationBlocked for user " + userId); 7859 PackageSetting pkgSetting; 7860 long callingId = Binder.clearCallingIdentity(); 7861 try { 7862 // writer 7863 synchronized (mPackages) { 7864 pkgSetting = mSettings.mPackages.get(packageName); 7865 if (pkgSetting == null) { 7866 return true; 7867 } 7868 return pkgSetting.getBlocked(userId); 7869 } 7870 } finally { 7871 Binder.restoreCallingIdentity(callingId); 7872 } 7873 } 7874 7875 void installStage(String basePackageName, File stageDir, IPackageInstallObserver2 observer, 7876 int flags) { 7877 // TODO: install stage! 7878 try { 7879 observer.packageInstalled(basePackageName, null, 7880 PackageManager.INSTALL_FAILED_INTERNAL_ERROR); 7881 } catch (RemoteException ignored) { 7882 } 7883 } 7884 7885 /** 7886 * @hide 7887 */ 7888 @Override 7889 public int installExistingPackageAsUser(String packageName, int userId) { 7890 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7891 null); 7892 PackageSetting pkgSetting; 7893 final int uid = Binder.getCallingUid(); 7894 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7895 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7896 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7897 } 7898 7899 long callingId = Binder.clearCallingIdentity(); 7900 try { 7901 boolean sendAdded = false; 7902 Bundle extras = new Bundle(1); 7903 7904 // writer 7905 synchronized (mPackages) { 7906 pkgSetting = mSettings.mPackages.get(packageName); 7907 if (pkgSetting == null) { 7908 return PackageManager.INSTALL_FAILED_INVALID_URI; 7909 } 7910 if (!pkgSetting.getInstalled(userId)) { 7911 pkgSetting.setInstalled(true, userId); 7912 pkgSetting.setBlocked(false, userId); 7913 mSettings.writePackageRestrictionsLPr(userId); 7914 sendAdded = true; 7915 } 7916 } 7917 7918 if (sendAdded) { 7919 sendPackageAddedForUser(packageName, pkgSetting, userId); 7920 } 7921 } finally { 7922 Binder.restoreCallingIdentity(callingId); 7923 } 7924 7925 return PackageManager.INSTALL_SUCCEEDED; 7926 } 7927 7928 boolean isUserRestricted(int userId, String restrictionKey) { 7929 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7930 if (restrictions.getBoolean(restrictionKey, false)) { 7931 Log.w(TAG, "User is restricted: " + restrictionKey); 7932 return true; 7933 } 7934 return false; 7935 } 7936 7937 @Override 7938 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7939 mContext.enforceCallingOrSelfPermission( 7940 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7941 "Only package verification agents can verify applications"); 7942 7943 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7944 final PackageVerificationResponse response = new PackageVerificationResponse( 7945 verificationCode, Binder.getCallingUid()); 7946 msg.arg1 = id; 7947 msg.obj = response; 7948 mHandler.sendMessage(msg); 7949 } 7950 7951 @Override 7952 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7953 long millisecondsToDelay) { 7954 mContext.enforceCallingOrSelfPermission( 7955 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7956 "Only package verification agents can extend verification timeouts"); 7957 7958 final PackageVerificationState state = mPendingVerification.get(id); 7959 final PackageVerificationResponse response = new PackageVerificationResponse( 7960 verificationCodeAtTimeout, Binder.getCallingUid()); 7961 7962 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7963 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7964 } 7965 if (millisecondsToDelay < 0) { 7966 millisecondsToDelay = 0; 7967 } 7968 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7969 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7970 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7971 } 7972 7973 if ((state != null) && !state.timeoutExtended()) { 7974 state.extendTimeout(); 7975 7976 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7977 msg.arg1 = id; 7978 msg.obj = response; 7979 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7980 } 7981 } 7982 7983 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7984 int verificationCode, UserHandle user) { 7985 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7986 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7987 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7988 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7989 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7990 7991 mContext.sendBroadcastAsUser(intent, user, 7992 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7993 } 7994 7995 private ComponentName matchComponentForVerifier(String packageName, 7996 List<ResolveInfo> receivers) { 7997 ActivityInfo targetReceiver = null; 7998 7999 final int NR = receivers.size(); 8000 for (int i = 0; i < NR; i++) { 8001 final ResolveInfo info = receivers.get(i); 8002 if (info.activityInfo == null) { 8003 continue; 8004 } 8005 8006 if (packageName.equals(info.activityInfo.packageName)) { 8007 targetReceiver = info.activityInfo; 8008 break; 8009 } 8010 } 8011 8012 if (targetReceiver == null) { 8013 return null; 8014 } 8015 8016 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8017 } 8018 8019 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8020 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8021 if (pkgInfo.verifiers.length == 0) { 8022 return null; 8023 } 8024 8025 final int N = pkgInfo.verifiers.length; 8026 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8027 for (int i = 0; i < N; i++) { 8028 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8029 8030 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8031 receivers); 8032 if (comp == null) { 8033 continue; 8034 } 8035 8036 final int verifierUid = getUidForVerifier(verifierInfo); 8037 if (verifierUid == -1) { 8038 continue; 8039 } 8040 8041 if (DEBUG_VERIFY) { 8042 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8043 + " with the correct signature"); 8044 } 8045 sufficientVerifiers.add(comp); 8046 verificationState.addSufficientVerifier(verifierUid); 8047 } 8048 8049 return sufficientVerifiers; 8050 } 8051 8052 private int getUidForVerifier(VerifierInfo verifierInfo) { 8053 synchronized (mPackages) { 8054 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8055 if (pkg == null) { 8056 return -1; 8057 } else if (pkg.mSignatures.length != 1) { 8058 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8059 + " has more than one signature; ignoring"); 8060 return -1; 8061 } 8062 8063 /* 8064 * If the public key of the package's signature does not match 8065 * our expected public key, then this is a different package and 8066 * we should skip. 8067 */ 8068 8069 final byte[] expectedPublicKey; 8070 try { 8071 final Signature verifierSig = pkg.mSignatures[0]; 8072 final PublicKey publicKey = verifierSig.getPublicKey(); 8073 expectedPublicKey = publicKey.getEncoded(); 8074 } catch (CertificateException e) { 8075 return -1; 8076 } 8077 8078 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8079 8080 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8081 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8082 + " does not have the expected public key; ignoring"); 8083 return -1; 8084 } 8085 8086 return pkg.applicationInfo.uid; 8087 } 8088 } 8089 8090 @Override 8091 public void finishPackageInstall(int token) { 8092 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8093 8094 if (DEBUG_INSTALL) { 8095 Slog.v(TAG, "BM finishing package install for " + token); 8096 } 8097 8098 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8099 mHandler.sendMessage(msg); 8100 } 8101 8102 /** 8103 * Get the verification agent timeout. 8104 * 8105 * @return verification timeout in milliseconds 8106 */ 8107 private long getVerificationTimeout() { 8108 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8109 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8110 DEFAULT_VERIFICATION_TIMEOUT); 8111 } 8112 8113 /** 8114 * Get the default verification agent response code. 8115 * 8116 * @return default verification response code 8117 */ 8118 private int getDefaultVerificationResponse() { 8119 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8120 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8121 DEFAULT_VERIFICATION_RESPONSE); 8122 } 8123 8124 /** 8125 * Check whether or not package verification has been enabled. 8126 * 8127 * @return true if verification should be performed 8128 */ 8129 private boolean isVerificationEnabled(int flags) { 8130 if (!DEFAULT_VERIFY_ENABLE) { 8131 return false; 8132 } 8133 8134 // Check if installing from ADB 8135 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8136 // Do not run verification in a test harness environment 8137 if (ActivityManager.isRunningInTestHarness()) { 8138 return false; 8139 } 8140 // Check if the developer does not want package verification for ADB installs 8141 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8142 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8143 return false; 8144 } 8145 } 8146 8147 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8148 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8149 } 8150 8151 /** 8152 * Get the "allow unknown sources" setting. 8153 * 8154 * @return the current "allow unknown sources" setting 8155 */ 8156 private int getUnknownSourcesSettings() { 8157 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8158 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8159 -1); 8160 } 8161 8162 @Override 8163 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8164 final int uid = Binder.getCallingUid(); 8165 // writer 8166 synchronized (mPackages) { 8167 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8168 if (targetPackageSetting == null) { 8169 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8170 } 8171 8172 PackageSetting installerPackageSetting; 8173 if (installerPackageName != null) { 8174 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8175 if (installerPackageSetting == null) { 8176 throw new IllegalArgumentException("Unknown installer package: " 8177 + installerPackageName); 8178 } 8179 } else { 8180 installerPackageSetting = null; 8181 } 8182 8183 Signature[] callerSignature; 8184 Object obj = mSettings.getUserIdLPr(uid); 8185 if (obj != null) { 8186 if (obj instanceof SharedUserSetting) { 8187 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8188 } else if (obj instanceof PackageSetting) { 8189 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8190 } else { 8191 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8192 } 8193 } else { 8194 throw new SecurityException("Unknown calling uid " + uid); 8195 } 8196 8197 // Verify: can't set installerPackageName to a package that is 8198 // not signed with the same cert as the caller. 8199 if (installerPackageSetting != null) { 8200 if (compareSignatures(callerSignature, 8201 installerPackageSetting.signatures.mSignatures) 8202 != PackageManager.SIGNATURE_MATCH) { 8203 throw new SecurityException( 8204 "Caller does not have same cert as new installer package " 8205 + installerPackageName); 8206 } 8207 } 8208 8209 // Verify: if target already has an installer package, it must 8210 // be signed with the same cert as the caller. 8211 if (targetPackageSetting.installerPackageName != null) { 8212 PackageSetting setting = mSettings.mPackages.get( 8213 targetPackageSetting.installerPackageName); 8214 // If the currently set package isn't valid, then it's always 8215 // okay to change it. 8216 if (setting != null) { 8217 if (compareSignatures(callerSignature, 8218 setting.signatures.mSignatures) 8219 != PackageManager.SIGNATURE_MATCH) { 8220 throw new SecurityException( 8221 "Caller does not have same cert as old installer package " 8222 + targetPackageSetting.installerPackageName); 8223 } 8224 } 8225 } 8226 8227 // Okay! 8228 targetPackageSetting.installerPackageName = installerPackageName; 8229 scheduleWriteSettingsLocked(); 8230 } 8231 } 8232 8233 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8234 // Queue up an async operation since the package installation may take a little while. 8235 mHandler.post(new Runnable() { 8236 public void run() { 8237 mHandler.removeCallbacks(this); 8238 // Result object to be returned 8239 PackageInstalledInfo res = new PackageInstalledInfo(); 8240 res.returnCode = currentStatus; 8241 res.uid = -1; 8242 res.pkg = null; 8243 res.removedInfo = new PackageRemovedInfo(); 8244 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8245 args.doPreInstall(res.returnCode); 8246 synchronized (mInstallLock) { 8247 installPackageLI(args, true, res); 8248 } 8249 args.doPostInstall(res.returnCode, res.uid); 8250 } 8251 8252 // A restore should be performed at this point if (a) the install 8253 // succeeded, (b) the operation is not an update, and (c) the new 8254 // package has a backupAgent defined. 8255 final boolean update = res.removedInfo.removedPackage != null; 8256 boolean doRestore = (!update 8257 && res.pkg != null 8258 && res.pkg.applicationInfo.backupAgentName != null); 8259 8260 // Set up the post-install work request bookkeeping. This will be used 8261 // and cleaned up by the post-install event handling regardless of whether 8262 // there's a restore pass performed. Token values are >= 1. 8263 int token; 8264 if (mNextInstallToken < 0) mNextInstallToken = 1; 8265 token = mNextInstallToken++; 8266 8267 PostInstallData data = new PostInstallData(args, res); 8268 mRunningInstalls.put(token, data); 8269 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8270 8271 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8272 // Pass responsibility to the Backup Manager. It will perform a 8273 // restore if appropriate, then pass responsibility back to the 8274 // Package Manager to run the post-install observer callbacks 8275 // and broadcasts. 8276 IBackupManager bm = IBackupManager.Stub.asInterface( 8277 ServiceManager.getService(Context.BACKUP_SERVICE)); 8278 if (bm != null) { 8279 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8280 + " to BM for possible restore"); 8281 try { 8282 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8283 } catch (RemoteException e) { 8284 // can't happen; the backup manager is local 8285 } catch (Exception e) { 8286 Slog.e(TAG, "Exception trying to enqueue restore", e); 8287 doRestore = false; 8288 } 8289 } else { 8290 Slog.e(TAG, "Backup Manager not found!"); 8291 doRestore = false; 8292 } 8293 } 8294 8295 if (!doRestore) { 8296 // No restore possible, or the Backup Manager was mysteriously not 8297 // available -- just fire the post-install work request directly. 8298 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8299 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8300 mHandler.sendMessage(msg); 8301 } 8302 } 8303 }); 8304 } 8305 8306 private abstract class HandlerParams { 8307 private static final int MAX_RETRIES = 4; 8308 8309 /** 8310 * Number of times startCopy() has been attempted and had a non-fatal 8311 * error. 8312 */ 8313 private int mRetries = 0; 8314 8315 /** User handle for the user requesting the information or installation. */ 8316 private final UserHandle mUser; 8317 8318 HandlerParams(UserHandle user) { 8319 mUser = user; 8320 } 8321 8322 UserHandle getUser() { 8323 return mUser; 8324 } 8325 8326 final boolean startCopy() { 8327 boolean res; 8328 try { 8329 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8330 8331 if (++mRetries > MAX_RETRIES) { 8332 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8333 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8334 handleServiceError(); 8335 return false; 8336 } else { 8337 handleStartCopy(); 8338 res = true; 8339 } 8340 } catch (RemoteException e) { 8341 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8342 mHandler.sendEmptyMessage(MCS_RECONNECT); 8343 res = false; 8344 } 8345 handleReturnCode(); 8346 return res; 8347 } 8348 8349 final void serviceError() { 8350 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8351 handleServiceError(); 8352 handleReturnCode(); 8353 } 8354 8355 abstract void handleStartCopy() throws RemoteException; 8356 abstract void handleServiceError(); 8357 abstract void handleReturnCode(); 8358 } 8359 8360 class MeasureParams extends HandlerParams { 8361 private final PackageStats mStats; 8362 private boolean mSuccess; 8363 8364 private final IPackageStatsObserver mObserver; 8365 8366 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8367 super(new UserHandle(stats.userHandle)); 8368 mObserver = observer; 8369 mStats = stats; 8370 } 8371 8372 @Override 8373 public String toString() { 8374 return "MeasureParams{" 8375 + Integer.toHexString(System.identityHashCode(this)) 8376 + " " + mStats.packageName + "}"; 8377 } 8378 8379 @Override 8380 void handleStartCopy() throws RemoteException { 8381 synchronized (mInstallLock) { 8382 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8383 } 8384 8385 if (mSuccess) { 8386 final boolean mounted; 8387 if (Environment.isExternalStorageEmulated()) { 8388 mounted = true; 8389 } else { 8390 final String status = Environment.getExternalStorageState(); 8391 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8392 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8393 } 8394 8395 if (mounted) { 8396 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8397 8398 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8399 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8400 8401 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8402 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8403 8404 // Always subtract cache size, since it's a subdirectory 8405 mStats.externalDataSize -= mStats.externalCacheSize; 8406 8407 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8408 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8409 8410 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8411 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8412 } 8413 } 8414 } 8415 8416 @Override 8417 void handleReturnCode() { 8418 if (mObserver != null) { 8419 try { 8420 mObserver.onGetStatsCompleted(mStats, mSuccess); 8421 } catch (RemoteException e) { 8422 Slog.i(TAG, "Observer no longer exists."); 8423 } 8424 } 8425 } 8426 8427 @Override 8428 void handleServiceError() { 8429 Slog.e(TAG, "Could not measure application " + mStats.packageName 8430 + " external storage"); 8431 } 8432 } 8433 8434 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8435 throws RemoteException { 8436 long result = 0; 8437 for (File path : paths) { 8438 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8439 } 8440 return result; 8441 } 8442 8443 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8444 for (File path : paths) { 8445 try { 8446 mcs.clearDirectory(path.getAbsolutePath()); 8447 } catch (RemoteException e) { 8448 } 8449 } 8450 } 8451 8452 class InstallParams extends HandlerParams { 8453 final IPackageInstallObserver observer; 8454 final IPackageInstallObserver2 observer2; 8455 int flags; 8456 8457 private final Uri mPackageURI; 8458 final String installerPackageName; 8459 final VerificationParams verificationParams; 8460 private InstallArgs mArgs; 8461 private int mRet; 8462 private File mTempPackage; 8463 final ContainerEncryptionParams encryptionParams; 8464 final String packageAbiOverride; 8465 final String packageInstructionSetOverride; 8466 8467 InstallParams(Uri packageURI, 8468 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 8469 int flags, String installerPackageName, VerificationParams verificationParams, 8470 ContainerEncryptionParams encryptionParams, UserHandle user, 8471 String packageAbiOverride) { 8472 super(user); 8473 this.mPackageURI = packageURI; 8474 this.flags = flags; 8475 this.observer = observer; 8476 this.observer2 = observer2; 8477 this.installerPackageName = installerPackageName; 8478 this.verificationParams = verificationParams; 8479 this.encryptionParams = encryptionParams; 8480 this.packageAbiOverride = packageAbiOverride; 8481 this.packageInstructionSetOverride = (packageAbiOverride == null) ? 8482 packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride); 8483 } 8484 8485 @Override 8486 public String toString() { 8487 return "InstallParams{" 8488 + Integer.toHexString(System.identityHashCode(this)) 8489 + " " + mPackageURI + "}"; 8490 } 8491 8492 public ManifestDigest getManifestDigest() { 8493 if (verificationParams == null) { 8494 return null; 8495 } 8496 return verificationParams.getManifestDigest(); 8497 } 8498 8499 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8500 String packageName = pkgLite.packageName; 8501 int installLocation = pkgLite.installLocation; 8502 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8503 // reader 8504 synchronized (mPackages) { 8505 PackageParser.Package pkg = mPackages.get(packageName); 8506 if (pkg != null) { 8507 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8508 // Check for downgrading. 8509 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8510 if (pkgLite.versionCode < pkg.mVersionCode) { 8511 Slog.w(TAG, "Can't install update of " + packageName 8512 + " update version " + pkgLite.versionCode 8513 + " is older than installed version " 8514 + pkg.mVersionCode); 8515 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8516 } 8517 } 8518 // Check for updated system application. 8519 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8520 if (onSd) { 8521 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8522 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8523 } 8524 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8525 } else { 8526 if (onSd) { 8527 // Install flag overrides everything. 8528 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8529 } 8530 // If current upgrade specifies particular preference 8531 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8532 // Application explicitly specified internal. 8533 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8534 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8535 // App explictly prefers external. Let policy decide 8536 } else { 8537 // Prefer previous location 8538 if (isExternal(pkg)) { 8539 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8540 } 8541 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8542 } 8543 } 8544 } else { 8545 // Invalid install. Return error code 8546 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8547 } 8548 } 8549 } 8550 // All the special cases have been taken care of. 8551 // Return result based on recommended install location. 8552 if (onSd) { 8553 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8554 } 8555 return pkgLite.recommendedInstallLocation; 8556 } 8557 8558 private long getMemoryLowThreshold() { 8559 final DeviceStorageMonitorInternal 8560 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8561 if (dsm == null) { 8562 return 0L; 8563 } 8564 return dsm.getMemoryLowThreshold(); 8565 } 8566 8567 /* 8568 * Invoke remote method to get package information and install 8569 * location values. Override install location based on default 8570 * policy if needed and then create install arguments based 8571 * on the install location. 8572 */ 8573 public void handleStartCopy() throws RemoteException { 8574 int ret = PackageManager.INSTALL_SUCCEEDED; 8575 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8576 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8577 PackageInfoLite pkgLite = null; 8578 8579 if (onInt && onSd) { 8580 // Check if both bits are set. 8581 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8582 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8583 } else { 8584 final long lowThreshold = getMemoryLowThreshold(); 8585 if (lowThreshold == 0L) { 8586 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8587 } 8588 8589 try { 8590 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI, 8591 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8592 8593 final File packageFile; 8594 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) { 8595 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir); 8596 if (mTempPackage != null) { 8597 ParcelFileDescriptor out; 8598 try { 8599 out = ParcelFileDescriptor.open(mTempPackage, 8600 ParcelFileDescriptor.MODE_READ_WRITE); 8601 } catch (FileNotFoundException e) { 8602 out = null; 8603 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI); 8604 } 8605 8606 // Make a temporary file for decryption. 8607 ret = mContainerService 8608 .copyResource(mPackageURI, encryptionParams, out); 8609 IoUtils.closeQuietly(out); 8610 8611 packageFile = mTempPackage; 8612 8613 FileUtils.setPermissions(packageFile.getAbsolutePath(), 8614 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP 8615 | FileUtils.S_IROTH, 8616 -1, -1); 8617 } else { 8618 packageFile = null; 8619 } 8620 } else { 8621 packageFile = new File(mPackageURI.getPath()); 8622 } 8623 8624 if (packageFile != null) { 8625 // Remote call to find out default install location 8626 final String packageFilePath = packageFile.getAbsolutePath(); 8627 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags, 8628 lowThreshold, packageAbiOverride); 8629 8630 /* 8631 * If we have too little free space, try to free cache 8632 * before giving up. 8633 */ 8634 if (pkgLite.recommendedInstallLocation 8635 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8636 final long size = mContainerService.calculateInstalledSize( 8637 packageFilePath, isForwardLocked(), packageAbiOverride); 8638 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8639 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, 8640 flags, lowThreshold, packageAbiOverride); 8641 } 8642 /* 8643 * The cache free must have deleted the file we 8644 * downloaded to install. 8645 * 8646 * TODO: fix the "freeCache" call to not delete 8647 * the file we care about. 8648 */ 8649 if (pkgLite.recommendedInstallLocation 8650 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8651 pkgLite.recommendedInstallLocation 8652 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8653 } 8654 } 8655 } 8656 } finally { 8657 mContext.revokeUriPermission(mPackageURI, 8658 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8659 } 8660 } 8661 8662 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8663 int loc = pkgLite.recommendedInstallLocation; 8664 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8665 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8666 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8667 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8668 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8669 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8670 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8671 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8672 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8673 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8674 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8675 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8676 } else { 8677 // Override with defaults if needed. 8678 loc = installLocationPolicy(pkgLite, flags); 8679 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8680 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8681 } else if (!onSd && !onInt) { 8682 // Override install location with flags 8683 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8684 // Set the flag to install on external media. 8685 flags |= PackageManager.INSTALL_EXTERNAL; 8686 flags &= ~PackageManager.INSTALL_INTERNAL; 8687 } else { 8688 // Make sure the flag for installing on external 8689 // media is unset 8690 flags |= PackageManager.INSTALL_INTERNAL; 8691 flags &= ~PackageManager.INSTALL_EXTERNAL; 8692 } 8693 } 8694 } 8695 } 8696 8697 final InstallArgs args = createInstallArgs(this); 8698 mArgs = args; 8699 8700 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8701 /* 8702 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8703 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8704 */ 8705 int userIdentifier = getUser().getIdentifier(); 8706 if (userIdentifier == UserHandle.USER_ALL 8707 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8708 userIdentifier = UserHandle.USER_OWNER; 8709 } 8710 8711 /* 8712 * Determine if we have any installed package verifiers. If we 8713 * do, then we'll defer to them to verify the packages. 8714 */ 8715 final int requiredUid = mRequiredVerifierPackage == null ? -1 8716 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8717 if (requiredUid != -1 && isVerificationEnabled(flags)) { 8718 final Intent verification = new Intent( 8719 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8720 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE); 8721 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8722 8723 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8724 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8725 0 /* TODO: Which userId? */); 8726 8727 if (DEBUG_VERIFY) { 8728 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8729 + verification.toString() + " with " + pkgLite.verifiers.length 8730 + " optional verifiers"); 8731 } 8732 8733 final int verificationId = mPendingVerificationToken++; 8734 8735 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8736 8737 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8738 installerPackageName); 8739 8740 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8741 8742 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8743 pkgLite.packageName); 8744 8745 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8746 pkgLite.versionCode); 8747 8748 if (verificationParams != null) { 8749 if (verificationParams.getVerificationURI() != null) { 8750 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8751 verificationParams.getVerificationURI()); 8752 } 8753 if (verificationParams.getOriginatingURI() != null) { 8754 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8755 verificationParams.getOriginatingURI()); 8756 } 8757 if (verificationParams.getReferrer() != null) { 8758 verification.putExtra(Intent.EXTRA_REFERRER, 8759 verificationParams.getReferrer()); 8760 } 8761 if (verificationParams.getOriginatingUid() >= 0) { 8762 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8763 verificationParams.getOriginatingUid()); 8764 } 8765 if (verificationParams.getInstallerUid() >= 0) { 8766 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8767 verificationParams.getInstallerUid()); 8768 } 8769 } 8770 8771 final PackageVerificationState verificationState = new PackageVerificationState( 8772 requiredUid, args); 8773 8774 mPendingVerification.append(verificationId, verificationState); 8775 8776 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8777 receivers, verificationState); 8778 8779 /* 8780 * If any sufficient verifiers were listed in the package 8781 * manifest, attempt to ask them. 8782 */ 8783 if (sufficientVerifiers != null) { 8784 final int N = sufficientVerifiers.size(); 8785 if (N == 0) { 8786 Slog.i(TAG, "Additional verifiers required, but none installed."); 8787 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8788 } else { 8789 for (int i = 0; i < N; i++) { 8790 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8791 8792 final Intent sufficientIntent = new Intent(verification); 8793 sufficientIntent.setComponent(verifierComponent); 8794 8795 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8796 } 8797 } 8798 } 8799 8800 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8801 mRequiredVerifierPackage, receivers); 8802 if (ret == PackageManager.INSTALL_SUCCEEDED 8803 && mRequiredVerifierPackage != null) { 8804 /* 8805 * Send the intent to the required verification agent, 8806 * but only start the verification timeout after the 8807 * target BroadcastReceivers have run. 8808 */ 8809 verification.setComponent(requiredVerifierComponent); 8810 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8811 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8812 new BroadcastReceiver() { 8813 @Override 8814 public void onReceive(Context context, Intent intent) { 8815 final Message msg = mHandler 8816 .obtainMessage(CHECK_PENDING_VERIFICATION); 8817 msg.arg1 = verificationId; 8818 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8819 } 8820 }, null, 0, null, null); 8821 8822 /* 8823 * We don't want the copy to proceed until verification 8824 * succeeds, so null out this field. 8825 */ 8826 mArgs = null; 8827 } 8828 } else { 8829 /* 8830 * No package verification is enabled, so immediately start 8831 * the remote call to initiate copy using temporary file. 8832 */ 8833 ret = args.copyApk(mContainerService, true); 8834 } 8835 } 8836 8837 mRet = ret; 8838 } 8839 8840 @Override 8841 void handleReturnCode() { 8842 // If mArgs is null, then MCS couldn't be reached. When it 8843 // reconnects, it will try again to install. At that point, this 8844 // will succeed. 8845 if (mArgs != null) { 8846 processPendingInstall(mArgs, mRet); 8847 8848 if (mTempPackage != null) { 8849 if (!mTempPackage.delete()) { 8850 Slog.w(TAG, "Couldn't delete temporary file: " + 8851 mTempPackage.getAbsolutePath()); 8852 } 8853 } 8854 } 8855 } 8856 8857 @Override 8858 void handleServiceError() { 8859 mArgs = createInstallArgs(this); 8860 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8861 } 8862 8863 public boolean isForwardLocked() { 8864 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8865 } 8866 8867 public Uri getPackageUri() { 8868 if (mTempPackage != null) { 8869 return Uri.fromFile(mTempPackage); 8870 } else { 8871 return mPackageURI; 8872 } 8873 } 8874 } 8875 8876 /* 8877 * Utility class used in movePackage api. 8878 * srcArgs and targetArgs are not set for invalid flags and make 8879 * sure to do null checks when invoking methods on them. 8880 * We probably want to return ErrorPrams for both failed installs 8881 * and moves. 8882 */ 8883 class MoveParams extends HandlerParams { 8884 final IPackageMoveObserver observer; 8885 final int flags; 8886 final String packageName; 8887 final InstallArgs srcArgs; 8888 final InstallArgs targetArgs; 8889 int uid; 8890 int mRet; 8891 8892 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8893 String packageName, String dataDir, String instructionSet, 8894 int uid, UserHandle user) { 8895 super(user); 8896 this.srcArgs = srcArgs; 8897 this.observer = observer; 8898 this.flags = flags; 8899 this.packageName = packageName; 8900 this.uid = uid; 8901 if (srcArgs != null) { 8902 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath())); 8903 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet); 8904 } else { 8905 targetArgs = null; 8906 } 8907 } 8908 8909 @Override 8910 public String toString() { 8911 return "MoveParams{" 8912 + Integer.toHexString(System.identityHashCode(this)) 8913 + " " + packageName + "}"; 8914 } 8915 8916 public void handleStartCopy() throws RemoteException { 8917 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8918 // Check for storage space on target medium 8919 if (!targetArgs.checkFreeStorage(mContainerService)) { 8920 Log.w(TAG, "Insufficient storage to install"); 8921 return; 8922 } 8923 8924 mRet = srcArgs.doPreCopy(); 8925 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8926 return; 8927 } 8928 8929 mRet = targetArgs.copyApk(mContainerService, false); 8930 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8931 srcArgs.doPostCopy(uid); 8932 return; 8933 } 8934 8935 mRet = srcArgs.doPostCopy(uid); 8936 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8937 return; 8938 } 8939 8940 mRet = targetArgs.doPreInstall(mRet); 8941 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8942 return; 8943 } 8944 8945 if (DEBUG_SD_INSTALL) { 8946 StringBuilder builder = new StringBuilder(); 8947 if (srcArgs != null) { 8948 builder.append("src: "); 8949 builder.append(srcArgs.getCodePath()); 8950 } 8951 if (targetArgs != null) { 8952 builder.append(" target : "); 8953 builder.append(targetArgs.getCodePath()); 8954 } 8955 Log.i(TAG, builder.toString()); 8956 } 8957 } 8958 8959 @Override 8960 void handleReturnCode() { 8961 targetArgs.doPostInstall(mRet, uid); 8962 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8963 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8964 currentStatus = PackageManager.MOVE_SUCCEEDED; 8965 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8966 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8967 } 8968 processPendingMove(this, currentStatus); 8969 } 8970 8971 @Override 8972 void handleServiceError() { 8973 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8974 } 8975 } 8976 8977 /** 8978 * Used during creation of InstallArgs 8979 * 8980 * @param flags package installation flags 8981 * @return true if should be installed on external storage 8982 */ 8983 private static boolean installOnSd(int flags) { 8984 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8985 return false; 8986 } 8987 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8988 return true; 8989 } 8990 return false; 8991 } 8992 8993 /** 8994 * Used during creation of InstallArgs 8995 * 8996 * @param flags package installation flags 8997 * @return true if should be installed as forward locked 8998 */ 8999 private static boolean installForwardLocked(int flags) { 9000 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9001 } 9002 9003 private InstallArgs createInstallArgs(InstallParams params) { 9004 if (installOnSd(params.flags) || params.isForwardLocked()) { 9005 return new AsecInstallArgs(params); 9006 } else { 9007 return new FileInstallArgs(params); 9008 } 9009 } 9010 9011 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath, 9012 String nativeLibraryPath, String instructionSet) { 9013 final boolean isInAsec; 9014 if (installOnSd(flags)) { 9015 /* Apps on SD card are always in ASEC containers. */ 9016 isInAsec = true; 9017 } else if (installForwardLocked(flags) 9018 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9019 /* 9020 * Forward-locked apps are only in ASEC containers if they're the 9021 * new style 9022 */ 9023 isInAsec = true; 9024 } else { 9025 isInAsec = false; 9026 } 9027 9028 if (isInAsec) { 9029 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 9030 instructionSet, installOnSd(flags), installForwardLocked(flags)); 9031 } else { 9032 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 9033 instructionSet); 9034 } 9035 } 9036 9037 // Used by package mover 9038 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir, 9039 String instructionSet) { 9040 if (installOnSd(flags) || installForwardLocked(flags)) { 9041 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/" 9042 + AsecInstallArgs.RES_FILE_NAME); 9043 return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags), 9044 installForwardLocked(flags)); 9045 } else { 9046 return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet); 9047 } 9048 } 9049 9050 static abstract class InstallArgs { 9051 final IPackageInstallObserver observer; 9052 final IPackageInstallObserver2 observer2; 9053 // Always refers to PackageManager flags only 9054 final int flags; 9055 final Uri packageURI; 9056 final String installerPackageName; 9057 final ManifestDigest manifestDigest; 9058 final UserHandle user; 9059 final String instructionSet; 9060 final String abiOverride; 9061 9062 InstallArgs(Uri packageURI, 9063 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 9064 int flags, String installerPackageName, ManifestDigest manifestDigest, 9065 UserHandle user, String instructionSet, String abiOverride) { 9066 this.packageURI = packageURI; 9067 this.flags = flags; 9068 this.observer = observer; 9069 this.observer2 = observer2; 9070 this.installerPackageName = installerPackageName; 9071 this.manifestDigest = manifestDigest; 9072 this.user = user; 9073 this.instructionSet = instructionSet; 9074 this.abiOverride = abiOverride; 9075 } 9076 9077 abstract void createCopyFile(); 9078 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9079 abstract int doPreInstall(int status); 9080 abstract boolean doRename(int status, String pkgName, String oldCodePath); 9081 9082 abstract int doPostInstall(int status, int uid); 9083 abstract String getCodePath(); 9084 abstract String getResourcePath(); 9085 abstract String getNativeLibraryPath(); 9086 // Need installer lock especially for dex file removal. 9087 abstract void cleanUpResourcesLI(); 9088 abstract boolean doPostDeleteLI(boolean delete); 9089 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9090 9091 String[] getSplitCodePaths() { 9092 return null; 9093 } 9094 9095 /** 9096 * Called before the source arguments are copied. This is used mostly 9097 * for MoveParams when it needs to read the source file to put it in the 9098 * destination. 9099 */ 9100 int doPreCopy() { 9101 return PackageManager.INSTALL_SUCCEEDED; 9102 } 9103 9104 /** 9105 * Called after the source arguments are copied. This is used mostly for 9106 * MoveParams when it needs to read the source file to put it in the 9107 * destination. 9108 * 9109 * @return 9110 */ 9111 int doPostCopy(int uid) { 9112 return PackageManager.INSTALL_SUCCEEDED; 9113 } 9114 9115 protected boolean isFwdLocked() { 9116 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9117 } 9118 9119 UserHandle getUser() { 9120 return user; 9121 } 9122 } 9123 9124 class FileInstallArgs extends InstallArgs { 9125 File installDir; 9126 String codeFileName; 9127 String resourceFileName; 9128 String libraryPath; 9129 boolean created = false; 9130 9131 FileInstallArgs(InstallParams params) { 9132 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 9133 params.installerPackageName, params.getManifestDigest(), 9134 params.getUser(), params.packageInstructionSetOverride, 9135 params.packageAbiOverride); 9136 } 9137 9138 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9139 String instructionSet) { 9140 super(null, null, null, 0, null, null, null, instructionSet, null); 9141 File codeFile = new File(fullCodePath); 9142 installDir = codeFile.getParentFile(); 9143 codeFileName = fullCodePath; 9144 resourceFileName = fullResourcePath; 9145 libraryPath = nativeLibraryPath; 9146 } 9147 9148 FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) { 9149 super(packageURI, null, null, 0, null, null, null, instructionSet, null); 9150 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 9151 String apkName = getNextCodePath(null, pkgName, ".apk"); 9152 codeFileName = new File(installDir, apkName + ".apk").getPath(); 9153 resourceFileName = getResourcePathFromCodePath(); 9154 libraryPath = new File(mAppLibInstallDir, pkgName).getPath(); 9155 } 9156 9157 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9158 final long lowThreshold; 9159 9160 final DeviceStorageMonitorInternal 9161 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9162 if (dsm == null) { 9163 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9164 lowThreshold = 0L; 9165 } else { 9166 if (dsm.isMemoryLow()) { 9167 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9168 return false; 9169 } 9170 9171 lowThreshold = dsm.getMemoryLowThreshold(); 9172 } 9173 9174 try { 9175 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9176 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9177 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold); 9178 } finally { 9179 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9180 } 9181 } 9182 9183 void createCopyFile() { 9184 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 9185 codeFileName = createTempPackageFile(installDir).getPath(); 9186 resourceFileName = getResourcePathFromCodePath(); 9187 libraryPath = getLibraryPathFromCodePath(); 9188 created = true; 9189 } 9190 9191 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9192 if (temp) { 9193 // Generate temp file name 9194 createCopyFile(); 9195 } 9196 // Get a ParcelFileDescriptor to write to the output file 9197 File codeFile = new File(codeFileName); 9198 if (!created) { 9199 try { 9200 codeFile.createNewFile(); 9201 // Set permissions 9202 if (!setPermissions()) { 9203 // Failed setting permissions. 9204 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9205 } 9206 } catch (IOException e) { 9207 Slog.w(TAG, "Failed to create file " + codeFile); 9208 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9209 } 9210 } 9211 ParcelFileDescriptor out = null; 9212 try { 9213 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 9214 } catch (FileNotFoundException e) { 9215 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 9216 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9217 } 9218 // Copy the resource now 9219 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9220 try { 9221 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9222 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9223 ret = imcs.copyResource(packageURI, null, out); 9224 } finally { 9225 IoUtils.closeQuietly(out); 9226 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9227 } 9228 9229 if (isFwdLocked()) { 9230 final File destResourceFile = new File(getResourcePath()); 9231 9232 // Copy the public files 9233 try { 9234 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 9235 } catch (IOException e) { 9236 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 9237 + " forward-locked app."); 9238 destResourceFile.delete(); 9239 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9240 } 9241 } 9242 9243 final File nativeLibraryFile = new File(getNativeLibraryPath()); 9244 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath()); 9245 if (nativeLibraryFile.exists()) { 9246 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 9247 nativeLibraryFile.delete(); 9248 } 9249 9250 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(codeFile); 9251 String[] abiList = (abiOverride != null) ? 9252 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9253 try { 9254 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 9255 abiOverride == null && 9256 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9257 abiList = Build.SUPPORTED_32_BIT_ABIS; 9258 } 9259 9260 int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList); 9261 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9262 return copyRet; 9263 } 9264 } catch (IOException e) { 9265 Slog.e(TAG, "Copying native libraries failed", e); 9266 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9267 } finally { 9268 handle.close(); 9269 } 9270 9271 return ret; 9272 } 9273 9274 int doPreInstall(int status) { 9275 if (status != PackageManager.INSTALL_SUCCEEDED) { 9276 cleanUp(); 9277 } 9278 return status; 9279 } 9280 9281 boolean doRename(int status, final String pkgName, String oldCodePath) { 9282 if (status != PackageManager.INSTALL_SUCCEEDED) { 9283 cleanUp(); 9284 return false; 9285 } else { 9286 final File oldCodeFile = new File(getCodePath()); 9287 final File oldResourceFile = new File(getResourcePath()); 9288 final File oldLibraryFile = new File(getNativeLibraryPath()); 9289 9290 // Rename APK file based on packageName 9291 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 9292 final File newCodeFile = new File(installDir, apkName + ".apk"); 9293 if (!oldCodeFile.renameTo(newCodeFile)) { 9294 return false; 9295 } 9296 codeFileName = newCodeFile.getPath(); 9297 9298 // Rename public resource file if it's forward-locked. 9299 final File newResFile = new File(getResourcePathFromCodePath()); 9300 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 9301 return false; 9302 } 9303 resourceFileName = newResFile.getPath(); 9304 9305 // Rename library path 9306 final File newLibraryFile = new File(getLibraryPathFromCodePath()); 9307 if (newLibraryFile.exists()) { 9308 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile); 9309 newLibraryFile.delete(); 9310 } 9311 if (!oldLibraryFile.renameTo(newLibraryFile)) { 9312 Slog.e(TAG, "Cannot rename native library directory " 9313 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath()); 9314 return false; 9315 } 9316 libraryPath = newLibraryFile.getPath(); 9317 9318 // Attempt to set permissions 9319 if (!setPermissions()) { 9320 return false; 9321 } 9322 9323 if (!SELinux.restorecon(newCodeFile)) { 9324 return false; 9325 } 9326 9327 return true; 9328 } 9329 } 9330 9331 int doPostInstall(int status, int uid) { 9332 if (status != PackageManager.INSTALL_SUCCEEDED) { 9333 cleanUp(); 9334 } 9335 return status; 9336 } 9337 9338 private String getResourcePathFromCodePath() { 9339 final String codePath = getCodePath(); 9340 if (isFwdLocked()) { 9341 final StringBuilder sb = new StringBuilder(); 9342 9343 sb.append(mAppInstallDir.getPath()); 9344 sb.append('/'); 9345 sb.append(getApkName(codePath)); 9346 sb.append(".zip"); 9347 9348 /* 9349 * If our APK is a temporary file, mark the resource as a 9350 * temporary file as well so it can be cleaned up after 9351 * catastrophic failure. 9352 */ 9353 if (codePath.endsWith(".tmp")) { 9354 sb.append(".tmp"); 9355 } 9356 9357 return sb.toString(); 9358 } else { 9359 return codePath; 9360 } 9361 } 9362 9363 private String getLibraryPathFromCodePath() { 9364 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath(); 9365 } 9366 9367 @Override 9368 String getCodePath() { 9369 return codeFileName; 9370 } 9371 9372 @Override 9373 String getResourcePath() { 9374 return resourceFileName; 9375 } 9376 9377 @Override 9378 String getNativeLibraryPath() { 9379 if (libraryPath == null) { 9380 libraryPath = getLibraryPathFromCodePath(); 9381 } 9382 return libraryPath; 9383 } 9384 9385 private boolean cleanUp() { 9386 boolean ret = true; 9387 String sourceDir = getCodePath(); 9388 String publicSourceDir = getResourcePath(); 9389 if (sourceDir != null) { 9390 File sourceFile = new File(sourceDir); 9391 if (!sourceFile.exists()) { 9392 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 9393 ret = false; 9394 } 9395 // Delete application's code and resources 9396 sourceFile.delete(); 9397 } 9398 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 9399 final File publicSourceFile = new File(publicSourceDir); 9400 if (!publicSourceFile.exists()) { 9401 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 9402 } 9403 if (publicSourceFile.exists()) { 9404 publicSourceFile.delete(); 9405 } 9406 } 9407 9408 if (libraryPath != null) { 9409 File nativeLibraryFile = new File(libraryPath); 9410 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 9411 if (!nativeLibraryFile.delete()) { 9412 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath); 9413 } 9414 } 9415 9416 return ret; 9417 } 9418 9419 void cleanUpResourcesLI() { 9420 String sourceDir = getCodePath(); 9421 if (cleanUp()) { 9422 if (instructionSet == null) { 9423 throw new IllegalStateException("instructionSet == null"); 9424 } 9425 int retCode = mInstaller.rmdex(sourceDir, instructionSet); 9426 if (retCode < 0) { 9427 Slog.w(TAG, "Couldn't remove dex file for package: " 9428 + " at location " 9429 + sourceDir + ", retcode=" + retCode); 9430 // we don't consider this to be a failure of the core package deletion 9431 } 9432 } 9433 } 9434 9435 private boolean setPermissions() { 9436 // TODO Do this in a more elegant way later on. for now just a hack 9437 if (!isFwdLocked()) { 9438 final int filePermissions = 9439 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 9440 |FileUtils.S_IROTH; 9441 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 9442 if (retCode != 0) { 9443 Slog.e(TAG, "Couldn't set new package file permissions for " + 9444 getCodePath() 9445 + ". The return code was: " + retCode); 9446 // TODO Define new internal error 9447 return false; 9448 } 9449 return true; 9450 } 9451 return true; 9452 } 9453 9454 boolean doPostDeleteLI(boolean delete) { 9455 // XXX err, shouldn't we respect the delete flag? 9456 cleanUpResourcesLI(); 9457 return true; 9458 } 9459 } 9460 9461 private boolean isAsecExternal(String cid) { 9462 final String asecPath = PackageHelper.getSdFilesystem(cid); 9463 return !asecPath.startsWith(mAsecInternalPath); 9464 } 9465 9466 /** 9467 * Extract the MountService "container ID" from the full code path of an 9468 * .apk. 9469 */ 9470 static String cidFromCodePath(String fullCodePath) { 9471 int eidx = fullCodePath.lastIndexOf("/"); 9472 String subStr1 = fullCodePath.substring(0, eidx); 9473 int sidx = subStr1.lastIndexOf("/"); 9474 return subStr1.substring(sidx+1, eidx); 9475 } 9476 9477 class AsecInstallArgs extends InstallArgs { 9478 static final String RES_FILE_NAME = "pkg.apk"; 9479 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9480 9481 String cid; 9482 String packagePath; 9483 String resourcePath; 9484 String libraryPath; 9485 9486 AsecInstallArgs(InstallParams params) { 9487 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 9488 params.installerPackageName, params.getManifestDigest(), 9489 params.getUser(), params.packageInstructionSetOverride, 9490 params.packageAbiOverride); 9491 } 9492 9493 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9494 String instructionSet, boolean isExternal, boolean isForwardLocked) { 9495 super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9496 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9497 null, null, null, instructionSet, null); 9498 // Extract cid from fullCodePath 9499 int eidx = fullCodePath.lastIndexOf("/"); 9500 String subStr1 = fullCodePath.substring(0, eidx); 9501 int sidx = subStr1.lastIndexOf("/"); 9502 cid = subStr1.substring(sidx+1, eidx); 9503 setCachePath(subStr1); 9504 } 9505 9506 AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) { 9507 super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 9508 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9509 null, null, null, instructionSet, null); 9510 this.cid = cid; 9511 setCachePath(PackageHelper.getSdDir(cid)); 9512 } 9513 9514 AsecInstallArgs(Uri packageURI, String cid, String instructionSet, 9515 boolean isExternal, boolean isForwardLocked) { 9516 super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9517 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9518 null, null, null, instructionSet, null); 9519 this.cid = cid; 9520 } 9521 9522 void createCopyFile() { 9523 cid = getTempContainerId(); 9524 } 9525 9526 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9527 try { 9528 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9529 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9530 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked(), abiOverride); 9531 } finally { 9532 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9533 } 9534 } 9535 9536 private final boolean isExternal() { 9537 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9538 } 9539 9540 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9541 if (temp) { 9542 createCopyFile(); 9543 } else { 9544 /* 9545 * Pre-emptively destroy the container since it's destroyed if 9546 * copying fails due to it existing anyway. 9547 */ 9548 PackageHelper.destroySdDir(cid); 9549 } 9550 9551 final String newCachePath; 9552 try { 9553 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9554 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9555 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(), 9556 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked(), 9557 abiOverride); 9558 } finally { 9559 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9560 } 9561 9562 if (newCachePath != null) { 9563 setCachePath(newCachePath); 9564 return PackageManager.INSTALL_SUCCEEDED; 9565 } else { 9566 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9567 } 9568 } 9569 9570 @Override 9571 String getCodePath() { 9572 return packagePath; 9573 } 9574 9575 @Override 9576 String getResourcePath() { 9577 return resourcePath; 9578 } 9579 9580 @Override 9581 String getNativeLibraryPath() { 9582 return libraryPath; 9583 } 9584 9585 int doPreInstall(int status) { 9586 if (status != PackageManager.INSTALL_SUCCEEDED) { 9587 // Destroy container 9588 PackageHelper.destroySdDir(cid); 9589 } else { 9590 boolean mounted = PackageHelper.isContainerMounted(cid); 9591 if (!mounted) { 9592 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9593 Process.SYSTEM_UID); 9594 if (newCachePath != null) { 9595 setCachePath(newCachePath); 9596 } else { 9597 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9598 } 9599 } 9600 } 9601 return status; 9602 } 9603 9604 boolean doRename(int status, final String pkgName, 9605 String oldCodePath) { 9606 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 9607 String newCachePath = null; 9608 if (PackageHelper.isContainerMounted(cid)) { 9609 // Unmount the container 9610 if (!PackageHelper.unMountSdDir(cid)) { 9611 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9612 return false; 9613 } 9614 } 9615 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9616 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9617 " which might be stale. Will try to clean up."); 9618 // Clean up the stale container and proceed to recreate. 9619 if (!PackageHelper.destroySdDir(newCacheId)) { 9620 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9621 return false; 9622 } 9623 // Successfully cleaned up stale container. Try to rename again. 9624 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9625 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9626 + " inspite of cleaning it up."); 9627 return false; 9628 } 9629 } 9630 if (!PackageHelper.isContainerMounted(newCacheId)) { 9631 Slog.w(TAG, "Mounting container " + newCacheId); 9632 newCachePath = PackageHelper.mountSdDir(newCacheId, 9633 getEncryptKey(), Process.SYSTEM_UID); 9634 } else { 9635 newCachePath = PackageHelper.getSdDir(newCacheId); 9636 } 9637 if (newCachePath == null) { 9638 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9639 return false; 9640 } 9641 Log.i(TAG, "Succesfully renamed " + cid + 9642 " to " + newCacheId + 9643 " at new path: " + newCachePath); 9644 cid = newCacheId; 9645 setCachePath(newCachePath); 9646 return true; 9647 } 9648 9649 private void setCachePath(String newCachePath) { 9650 File cachePath = new File(newCachePath); 9651 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 9652 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9653 9654 if (isFwdLocked()) { 9655 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9656 } else { 9657 resourcePath = packagePath; 9658 } 9659 } 9660 9661 int doPostInstall(int status, int uid) { 9662 if (status != PackageManager.INSTALL_SUCCEEDED) { 9663 cleanUp(); 9664 } else { 9665 final int groupOwner; 9666 final String protectedFile; 9667 if (isFwdLocked()) { 9668 groupOwner = UserHandle.getSharedAppGid(uid); 9669 protectedFile = RES_FILE_NAME; 9670 } else { 9671 groupOwner = -1; 9672 protectedFile = null; 9673 } 9674 9675 if (uid < Process.FIRST_APPLICATION_UID 9676 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9677 Slog.e(TAG, "Failed to finalize " + cid); 9678 PackageHelper.destroySdDir(cid); 9679 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9680 } 9681 9682 boolean mounted = PackageHelper.isContainerMounted(cid); 9683 if (!mounted) { 9684 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9685 } 9686 } 9687 return status; 9688 } 9689 9690 private void cleanUp() { 9691 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9692 9693 // Destroy secure container 9694 PackageHelper.destroySdDir(cid); 9695 } 9696 9697 void cleanUpResourcesLI() { 9698 String sourceFile = getCodePath(); 9699 // Remove dex file 9700 if (instructionSet == null) { 9701 throw new IllegalStateException("instructionSet == null"); 9702 } 9703 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9704 if (retCode < 0) { 9705 Slog.w(TAG, "Couldn't remove dex file for package: " 9706 + " at location " 9707 + sourceFile.toString() + ", retcode=" + retCode); 9708 // we don't consider this to be a failure of the core package deletion 9709 } 9710 cleanUp(); 9711 } 9712 9713 boolean matchContainer(String app) { 9714 if (cid.startsWith(app)) { 9715 return true; 9716 } 9717 return false; 9718 } 9719 9720 String getPackageName() { 9721 return getAsecPackageName(cid); 9722 } 9723 9724 boolean doPostDeleteLI(boolean delete) { 9725 boolean ret = false; 9726 boolean mounted = PackageHelper.isContainerMounted(cid); 9727 if (mounted) { 9728 // Unmount first 9729 ret = PackageHelper.unMountSdDir(cid); 9730 } 9731 if (ret && delete) { 9732 cleanUpResourcesLI(); 9733 } 9734 return ret; 9735 } 9736 9737 @Override 9738 int doPreCopy() { 9739 if (isFwdLocked()) { 9740 if (!PackageHelper.fixSdPermissions(cid, 9741 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9742 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9743 } 9744 } 9745 9746 return PackageManager.INSTALL_SUCCEEDED; 9747 } 9748 9749 @Override 9750 int doPostCopy(int uid) { 9751 if (isFwdLocked()) { 9752 if (uid < Process.FIRST_APPLICATION_UID 9753 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9754 RES_FILE_NAME)) { 9755 Slog.e(TAG, "Failed to finalize " + cid); 9756 PackageHelper.destroySdDir(cid); 9757 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9758 } 9759 } 9760 9761 return PackageManager.INSTALL_SUCCEEDED; 9762 } 9763 }; 9764 9765 static String getAsecPackageName(String packageCid) { 9766 int idx = packageCid.lastIndexOf("-"); 9767 if (idx == -1) { 9768 return packageCid; 9769 } 9770 return packageCid.substring(0, idx); 9771 } 9772 9773 // Utility method used to create code paths based on package name and available index. 9774 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9775 String idxStr = ""; 9776 int idx = 1; 9777 // Fall back to default value of idx=1 if prefix is not 9778 // part of oldCodePath 9779 if (oldCodePath != null) { 9780 String subStr = oldCodePath; 9781 // Drop the suffix right away 9782 if (subStr.endsWith(suffix)) { 9783 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9784 } 9785 // If oldCodePath already contains prefix find out the 9786 // ending index to either increment or decrement. 9787 int sidx = subStr.lastIndexOf(prefix); 9788 if (sidx != -1) { 9789 subStr = subStr.substring(sidx + prefix.length()); 9790 if (subStr != null) { 9791 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9792 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9793 } 9794 try { 9795 idx = Integer.parseInt(subStr); 9796 if (idx <= 1) { 9797 idx++; 9798 } else { 9799 idx--; 9800 } 9801 } catch(NumberFormatException e) { 9802 } 9803 } 9804 } 9805 } 9806 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9807 return prefix + idxStr; 9808 } 9809 9810 // Utility method used to ignore ADD/REMOVE events 9811 // by directory observer. 9812 private static boolean ignoreCodePath(String fullPathStr) { 9813 String apkName = getApkName(fullPathStr); 9814 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9815 if (idx != -1 && ((idx+1) < apkName.length())) { 9816 // Make sure the package ends with a numeral 9817 String version = apkName.substring(idx+1); 9818 try { 9819 Integer.parseInt(version); 9820 return true; 9821 } catch (NumberFormatException e) {} 9822 } 9823 return false; 9824 } 9825 9826 // Utility method that returns the relative package path with respect 9827 // to the installation directory. Like say for /data/data/com.test-1.apk 9828 // string com.test-1 is returned. 9829 static String getApkName(String codePath) { 9830 if (codePath == null) { 9831 return null; 9832 } 9833 int sidx = codePath.lastIndexOf("/"); 9834 int eidx = codePath.lastIndexOf("."); 9835 if (eidx == -1) { 9836 eidx = codePath.length(); 9837 } else if (eidx == 0) { 9838 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 9839 return null; 9840 } 9841 return codePath.substring(sidx+1, eidx); 9842 } 9843 9844 private static String[] deriveSplitResPaths(String[] splitCodePaths) { 9845 String[] splitResPaths = null; 9846 if (!ArrayUtils.isEmpty(splitCodePaths)) { 9847 splitResPaths = new String[splitCodePaths.length]; 9848 for (int i = 0; i < splitCodePaths.length; i++) { 9849 final String splitCodePath = splitCodePaths[i]; 9850 final String resName = getApkName(splitCodePath) + ".zip"; 9851 splitResPaths[i] = new File(new File(splitCodePath).getParentFile(), 9852 resName).getAbsolutePath(); 9853 } 9854 } 9855 return splitResPaths; 9856 } 9857 9858 class PackageInstalledInfo { 9859 String name; 9860 int uid; 9861 // The set of users that originally had this package installed. 9862 int[] origUsers; 9863 // The set of users that now have this package installed. 9864 int[] newUsers; 9865 PackageParser.Package pkg; 9866 int returnCode; 9867 PackageRemovedInfo removedInfo; 9868 9869 // In some error cases we want to convey more info back to the observer 9870 String origPackage; 9871 String origPermission; 9872 } 9873 9874 /* 9875 * Install a non-existing package. 9876 */ 9877 private void installNewPackageLI(PackageParser.Package pkg, 9878 int parseFlags, int scanMode, UserHandle user, 9879 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9880 // Remember this for later, in case we need to rollback this install 9881 String pkgName = pkg.packageName; 9882 9883 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9884 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9885 synchronized(mPackages) { 9886 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9887 // A package with the same name is already installed, though 9888 // it has been renamed to an older name. The package we 9889 // are trying to install should be installed as an update to 9890 // the existing one, but that has not been requested, so bail. 9891 Slog.w(TAG, "Attempt to re-install " + pkgName 9892 + " without first uninstalling package running as " 9893 + mSettings.mRenamedPackages.get(pkgName)); 9894 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9895 return; 9896 } 9897 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9898 // Don't allow installation over an existing package with the same name. 9899 Slog.w(TAG, "Attempt to re-install " + pkgName 9900 + " without first uninstalling."); 9901 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9902 return; 9903 } 9904 } 9905 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9906 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9907 System.currentTimeMillis(), user, abiOverride); 9908 if (newPackage == null) { 9909 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9910 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9911 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9912 } 9913 } else { 9914 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9915 // delete the partially installed application. the data directory will have to be 9916 // restored if it was already existing 9917 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9918 // remove package from internal structures. Note that we want deletePackageX to 9919 // delete the package data and cache directories that it created in 9920 // scanPackageLocked, unless those directories existed before we even tried to 9921 // install. 9922 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9923 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9924 res.removedInfo, true); 9925 } 9926 } 9927 } 9928 9929 private void replacePackageLI(PackageParser.Package pkg, 9930 int parseFlags, int scanMode, UserHandle user, 9931 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9932 9933 PackageParser.Package oldPackage; 9934 String pkgName = pkg.packageName; 9935 int[] allUsers; 9936 boolean[] perUserInstalled; 9937 9938 // First find the old package info and check signatures 9939 synchronized(mPackages) { 9940 oldPackage = mPackages.get(pkgName); 9941 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9942 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9943 != PackageManager.SIGNATURE_MATCH) { 9944 Slog.w(TAG, "New package has a different signature: " + pkgName); 9945 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9946 return; 9947 } 9948 9949 // In case of rollback, remember per-user/profile install state 9950 PackageSetting ps = mSettings.mPackages.get(pkgName); 9951 allUsers = sUserManager.getUserIds(); 9952 perUserInstalled = new boolean[allUsers.length]; 9953 for (int i = 0; i < allUsers.length; i++) { 9954 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9955 } 9956 } 9957 boolean sysPkg = (isSystemApp(oldPackage)); 9958 if (sysPkg) { 9959 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9960 user, allUsers, perUserInstalled, installerPackageName, res, 9961 abiOverride); 9962 } else { 9963 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9964 user, allUsers, perUserInstalled, installerPackageName, res, 9965 abiOverride); 9966 } 9967 } 9968 9969 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9970 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9971 int[] allUsers, boolean[] perUserInstalled, 9972 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9973 PackageParser.Package newPackage = null; 9974 String pkgName = deletedPackage.packageName; 9975 boolean deletedPkg = true; 9976 boolean updatedSettings = false; 9977 9978 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9979 + deletedPackage); 9980 long origUpdateTime; 9981 if (pkg.mExtras != null) { 9982 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9983 } else { 9984 origUpdateTime = 0; 9985 } 9986 9987 // First delete the existing package while retaining the data directory 9988 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9989 res.removedInfo, true)) { 9990 // If the existing package wasn't successfully deleted 9991 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9992 deletedPkg = false; 9993 } else { 9994 // Successfully deleted the old package. Now proceed with re-installation 9995 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9996 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9997 System.currentTimeMillis(), user, abiOverride); 9998 if (newPackage == null) { 9999 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 10000 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 10001 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 10002 } 10003 } else { 10004 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10005 updatedSettings = true; 10006 } 10007 } 10008 10009 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10010 // remove package from internal structures. Note that we want deletePackageX to 10011 // delete the package data and cache directories that it created in 10012 // scanPackageLocked, unless those directories existed before we even tried to 10013 // install. 10014 if(updatedSettings) { 10015 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10016 deletePackageLI( 10017 pkgName, null, true, allUsers, perUserInstalled, 10018 PackageManager.DELETE_KEEP_DATA, 10019 res.removedInfo, true); 10020 } 10021 // Since we failed to install the new package we need to restore the old 10022 // package that we deleted. 10023 if (deletedPkg) { 10024 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10025 File restoreFile = new File(deletedPackage.codePath); 10026 // Parse old package 10027 boolean oldOnSd = isExternal(deletedPackage); 10028 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10029 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10030 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10031 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10032 | SCAN_UPDATE_TIME; 10033 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 10034 origUpdateTime, null, null) == null) { 10035 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 10036 return; 10037 } 10038 // Restore of old package succeeded. Update permissions. 10039 // writer 10040 synchronized (mPackages) { 10041 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10042 UPDATE_PERMISSIONS_ALL); 10043 // can downgrade to reader 10044 mSettings.writeLPr(); 10045 } 10046 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10047 } 10048 } 10049 } 10050 10051 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10052 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10053 int[] allUsers, boolean[] perUserInstalled, 10054 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10055 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10056 + ", old=" + deletedPackage); 10057 PackageParser.Package newPackage = null; 10058 boolean updatedSettings = false; 10059 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10060 PackageParser.PARSE_IS_SYSTEM; 10061 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10062 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10063 } 10064 String packageName = deletedPackage.packageName; 10065 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 10066 if (packageName == null) { 10067 Slog.w(TAG, "Attempt to delete null packageName."); 10068 return; 10069 } 10070 PackageParser.Package oldPkg; 10071 PackageSetting oldPkgSetting; 10072 // reader 10073 synchronized (mPackages) { 10074 oldPkg = mPackages.get(packageName); 10075 oldPkgSetting = mSettings.mPackages.get(packageName); 10076 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10077 (oldPkgSetting == null)) { 10078 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 10079 return; 10080 } 10081 } 10082 10083 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10084 10085 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10086 res.removedInfo.removedPackage = packageName; 10087 // Remove existing system package 10088 removePackageLI(oldPkgSetting, true); 10089 // writer 10090 synchronized (mPackages) { 10091 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10092 // We didn't need to disable the .apk as a current system package, 10093 // which means we are replacing another update that is already 10094 // installed. We need to make sure to delete the older one's .apk. 10095 res.removedInfo.args = createInstallArgs(0, 10096 deletedPackage.applicationInfo.sourceDir, 10097 deletedPackage.applicationInfo.publicSourceDir, 10098 deletedPackage.applicationInfo.nativeLibraryDir, 10099 getAppInstructionSet(deletedPackage.applicationInfo)); 10100 } else { 10101 res.removedInfo.args = null; 10102 } 10103 } 10104 10105 // Successfully disabled the old package. Now proceed with re-installation 10106 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 10107 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10108 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10109 if (newPackage == null) { 10110 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 10111 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 10112 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 10113 } 10114 } else { 10115 if (newPackage.mExtras != null) { 10116 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 10117 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10118 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10119 10120 // is the update attempting to change shared user? that isn't going to work... 10121 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10122 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 10123 + " to " + newPkgSetting.sharedUser); 10124 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 10125 updatedSettings = true; 10126 } 10127 } 10128 10129 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10130 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10131 updatedSettings = true; 10132 } 10133 } 10134 10135 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10136 // Re installation failed. Restore old information 10137 // Remove new pkg information 10138 if (newPackage != null) { 10139 removeInstalledPackageLI(newPackage, true); 10140 } 10141 // Add back the old system package 10142 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null); 10143 // Restore the old system information in Settings 10144 synchronized(mPackages) { 10145 if (updatedSettings) { 10146 mSettings.enableSystemPackageLPw(packageName); 10147 mSettings.setInstallerPackageName(packageName, 10148 oldPkgSetting.installerPackageName); 10149 } 10150 mSettings.writeLPr(); 10151 } 10152 } 10153 } 10154 10155 // Utility method used to move dex files during install. 10156 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10157 // TODO: extend to move split APK dex files 10158 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10159 final String instructionSet = getAppInstructionSet(newPackage.applicationInfo); 10160 int retCode = mInstaller.movedex(oldCodePath, newPackage.codePath, 10161 instructionSet); 10162 if (retCode != 0) { 10163 /* 10164 * Programs may be lazily run through dexopt, so the 10165 * source may not exist. However, something seems to 10166 * have gone wrong, so note that dexopt needs to be 10167 * run again and remove the source file. In addition, 10168 * remove the target to make sure there isn't a stale 10169 * file from a previous version of the package. 10170 */ 10171 newPackage.mDexOptNeeded = true; 10172 mInstaller.rmdex(oldCodePath, instructionSet); 10173 mInstaller.rmdex(newPackage.codePath, instructionSet); 10174 } 10175 } 10176 return PackageManager.INSTALL_SUCCEEDED; 10177 } 10178 10179 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10180 int[] allUsers, boolean[] perUserInstalled, 10181 PackageInstalledInfo res) { 10182 String pkgName = newPackage.packageName; 10183 synchronized (mPackages) { 10184 //write settings. the installStatus will be incomplete at this stage. 10185 //note that the new package setting would have already been 10186 //added to mPackages. It hasn't been persisted yet. 10187 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10188 mSettings.writeLPr(); 10189 } 10190 10191 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10192 10193 synchronized (mPackages) { 10194 updatePermissionsLPw(newPackage.packageName, newPackage, 10195 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10196 ? UPDATE_PERMISSIONS_ALL : 0)); 10197 // For system-bundled packages, we assume that installing an upgraded version 10198 // of the package implies that the user actually wants to run that new code, 10199 // so we enable the package. 10200 if (isSystemApp(newPackage)) { 10201 // NB: implicit assumption that system package upgrades apply to all users 10202 if (DEBUG_INSTALL) { 10203 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10204 } 10205 PackageSetting ps = mSettings.mPackages.get(pkgName); 10206 if (ps != null) { 10207 if (res.origUsers != null) { 10208 for (int userHandle : res.origUsers) { 10209 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10210 userHandle, installerPackageName); 10211 } 10212 } 10213 // Also convey the prior install/uninstall state 10214 if (allUsers != null && perUserInstalled != null) { 10215 for (int i = 0; i < allUsers.length; i++) { 10216 if (DEBUG_INSTALL) { 10217 Slog.d(TAG, " user " + allUsers[i] 10218 + " => " + perUserInstalled[i]); 10219 } 10220 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10221 } 10222 // these install state changes will be persisted in the 10223 // upcoming call to mSettings.writeLPr(). 10224 } 10225 } 10226 } 10227 res.name = pkgName; 10228 res.uid = newPackage.applicationInfo.uid; 10229 res.pkg = newPackage; 10230 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10231 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10232 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10233 //to update install status 10234 mSettings.writeLPr(); 10235 } 10236 } 10237 10238 private void installPackageLI(InstallArgs args, 10239 boolean newInstall, PackageInstalledInfo res) { 10240 int pFlags = args.flags; 10241 String installerPackageName = args.installerPackageName; 10242 File tmpPackageFile = new File(args.getCodePath()); 10243 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10244 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10245 boolean replace = false; 10246 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10247 | (newInstall ? SCAN_NEW_INSTALL : 0); 10248 // Result object to be returned 10249 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10250 10251 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10252 // Retrieve PackageSettings and parse package 10253 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10254 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10255 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10256 PackageParser pp = new PackageParser(tmpPackageFile.getPath()); 10257 pp.setSeparateProcesses(mSeparateProcesses); 10258 10259 final PackageParser.Package pkg; 10260 try { 10261 pkg = pp.parseMonolithicPackage(tmpPackageFile, mMetrics, 10262 parseFlags); 10263 } catch (PackageParserException e) { 10264 res.returnCode = e.error; 10265 return; 10266 } 10267 10268 String pkgName = res.name = pkg.packageName; 10269 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10270 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10271 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 10272 return; 10273 } 10274 } 10275 10276 try { 10277 pp.collectCertificates(pkg, parseFlags); 10278 } catch (PackageParserException e) { 10279 res.returnCode = e.error; 10280 return; 10281 } 10282 10283 /* If the installer passed in a manifest digest, compare it now. */ 10284 if (args.manifestDigest != null) { 10285 if (DEBUG_INSTALL) { 10286 final String parsedManifest = pkg.manifestDigest == null ? "null" 10287 : pkg.manifestDigest.toString(); 10288 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10289 + parsedManifest); 10290 } 10291 10292 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10293 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 10294 return; 10295 } 10296 } else if (DEBUG_INSTALL) { 10297 final String parsedManifest = pkg.manifestDigest == null 10298 ? "null" : pkg.manifestDigest.toString(); 10299 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10300 } 10301 10302 // Get rid of all references to package scan path via parser. 10303 pp = null; 10304 String oldCodePath = null; 10305 boolean systemApp = false; 10306 synchronized (mPackages) { 10307 // Check whether the newly-scanned package wants to define an already-defined perm 10308 int N = pkg.permissions.size(); 10309 for (int i = N-1; i >= 0; i--) { 10310 PackageParser.Permission perm = pkg.permissions.get(i); 10311 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10312 if (bp != null) { 10313 // If the defining package is signed with our cert, it's okay. This 10314 // also includes the "updating the same package" case, of course. 10315 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10316 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10317 // If the owning package is the system itself, we log but allow 10318 // install to proceed; we fail the install on all other permission 10319 // redefinitions. 10320 if (!bp.sourcePackage.equals("android")) { 10321 Slog.w(TAG, "Package " + pkg.packageName 10322 + " attempting to redeclare permission " + perm.info.name 10323 + " already owned by " + bp.sourcePackage); 10324 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 10325 res.origPermission = perm.info.name; 10326 res.origPackage = bp.sourcePackage; 10327 return; 10328 } else { 10329 Slog.w(TAG, "Package " + pkg.packageName 10330 + " attempting to redeclare system permission " 10331 + perm.info.name + "; ignoring new declaration"); 10332 pkg.permissions.remove(i); 10333 } 10334 } 10335 } 10336 } 10337 10338 // Check if installing already existing package 10339 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10340 String oldName = mSettings.mRenamedPackages.get(pkgName); 10341 if (pkg.mOriginalPackages != null 10342 && pkg.mOriginalPackages.contains(oldName) 10343 && mPackages.containsKey(oldName)) { 10344 // This package is derived from an original package, 10345 // and this device has been updating from that original 10346 // name. We must continue using the original name, so 10347 // rename the new package here. 10348 pkg.setPackageName(oldName); 10349 pkgName = pkg.packageName; 10350 replace = true; 10351 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10352 + oldName + " pkgName=" + pkgName); 10353 } else if (mPackages.containsKey(pkgName)) { 10354 // This package, under its official name, already exists 10355 // on the device; we should replace it. 10356 replace = true; 10357 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10358 } 10359 } 10360 PackageSetting ps = mSettings.mPackages.get(pkgName); 10361 if (ps != null) { 10362 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10363 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10364 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10365 systemApp = (ps.pkg.applicationInfo.flags & 10366 ApplicationInfo.FLAG_SYSTEM) != 0; 10367 } 10368 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10369 } 10370 } 10371 10372 if (systemApp && onSd) { 10373 // Disable updates to system apps on sdcard 10374 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 10375 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10376 return; 10377 } 10378 10379 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 10380 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10381 return; 10382 } 10383 // Set application objects path explicitly after the rename 10384 pkg.codePath = args.getCodePath(); 10385 pkg.applicationInfo.sourceDir = args.getCodePath(); 10386 pkg.applicationInfo.publicSourceDir = args.getResourcePath(); 10387 pkg.applicationInfo.splitSourceDirs = args.getSplitCodePaths(); 10388 pkg.applicationInfo.splitPublicSourceDirs = deriveSplitResPaths( 10389 pkg.applicationInfo.splitSourceDirs); 10390 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 10391 if (replace) { 10392 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10393 installerPackageName, res, args.abiOverride); 10394 } else { 10395 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10396 installerPackageName, res, args.abiOverride); 10397 } 10398 synchronized (mPackages) { 10399 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10400 if (ps != null) { 10401 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10402 } 10403 } 10404 } 10405 10406 private static boolean isForwardLocked(PackageParser.Package pkg) { 10407 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10408 } 10409 10410 10411 private boolean isForwardLocked(PackageSetting ps) { 10412 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10413 } 10414 10415 private static boolean isExternal(PackageParser.Package pkg) { 10416 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10417 } 10418 10419 private static boolean isExternal(PackageSetting ps) { 10420 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10421 } 10422 10423 private static boolean isSystemApp(PackageParser.Package pkg) { 10424 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10425 } 10426 10427 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10428 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10429 } 10430 10431 private static boolean isSystemApp(ApplicationInfo info) { 10432 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10433 } 10434 10435 private static boolean isSystemApp(PackageSetting ps) { 10436 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10437 } 10438 10439 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10440 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10441 } 10442 10443 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10444 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10445 } 10446 10447 private int packageFlagsToInstallFlags(PackageSetting ps) { 10448 int installFlags = 0; 10449 if (isExternal(ps)) { 10450 installFlags |= PackageManager.INSTALL_EXTERNAL; 10451 } 10452 if (isForwardLocked(ps)) { 10453 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10454 } 10455 return installFlags; 10456 } 10457 10458 private void deleteTempPackageFiles() { 10459 final FilenameFilter filter = new FilenameFilter() { 10460 public boolean accept(File dir, String name) { 10461 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10462 } 10463 }; 10464 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 10465 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 10466 } 10467 10468 private static final void deleteTempPackageFilesInDirectory(File directory, 10469 FilenameFilter filter) { 10470 final String[] tmpFilesList = directory.list(filter); 10471 if (tmpFilesList == null) { 10472 return; 10473 } 10474 for (int i = 0; i < tmpFilesList.length; i++) { 10475 final File tmpFile = new File(directory, tmpFilesList[i]); 10476 tmpFile.delete(); 10477 } 10478 } 10479 10480 private File createTempPackageFile(File installDir) { 10481 File tmpPackageFile; 10482 try { 10483 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 10484 } catch (IOException e) { 10485 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 10486 return null; 10487 } 10488 try { 10489 FileUtils.setPermissions( 10490 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 10491 -1, -1); 10492 if (!SELinux.restorecon(tmpPackageFile)) { 10493 return null; 10494 } 10495 } catch (IOException e) { 10496 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 10497 return null; 10498 } 10499 return tmpPackageFile; 10500 } 10501 10502 @Override 10503 public void deletePackageAsUser(final String packageName, 10504 final IPackageDeleteObserver observer, 10505 final int userId, final int flags) { 10506 mContext.enforceCallingOrSelfPermission( 10507 android.Manifest.permission.DELETE_PACKAGES, null); 10508 final int uid = Binder.getCallingUid(); 10509 if (UserHandle.getUserId(uid) != userId) { 10510 mContext.enforceCallingPermission( 10511 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10512 "deletePackage for user " + userId); 10513 } 10514 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10515 try { 10516 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10517 } catch (RemoteException re) { 10518 } 10519 return; 10520 } 10521 10522 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10523 // Queue up an async operation since the package deletion may take a little while. 10524 mHandler.post(new Runnable() { 10525 public void run() { 10526 mHandler.removeCallbacks(this); 10527 final int returnCode = deletePackageX(packageName, userId, flags); 10528 if (observer != null) { 10529 try { 10530 observer.packageDeleted(packageName, returnCode); 10531 } catch (RemoteException e) { 10532 Log.i(TAG, "Observer no longer exists."); 10533 } //end catch 10534 } //end if 10535 } //end run 10536 }); 10537 } 10538 10539 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10540 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10541 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10542 try { 10543 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10544 || dpm.isDeviceOwner(packageName))) { 10545 return true; 10546 } 10547 } catch (RemoteException e) { 10548 } 10549 return false; 10550 } 10551 10552 /** 10553 * This method is an internal method that could be get invoked either 10554 * to delete an installed package or to clean up a failed installation. 10555 * After deleting an installed package, a broadcast is sent to notify any 10556 * listeners that the package has been installed. For cleaning up a failed 10557 * installation, the broadcast is not necessary since the package's 10558 * installation wouldn't have sent the initial broadcast either 10559 * The key steps in deleting a package are 10560 * deleting the package information in internal structures like mPackages, 10561 * deleting the packages base directories through installd 10562 * updating mSettings to reflect current status 10563 * persisting settings for later use 10564 * sending a broadcast if necessary 10565 */ 10566 private int deletePackageX(String packageName, int userId, int flags) { 10567 final PackageRemovedInfo info = new PackageRemovedInfo(); 10568 final boolean res; 10569 10570 if (isPackageDeviceAdmin(packageName, userId)) { 10571 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10572 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10573 } 10574 10575 boolean removedForAllUsers = false; 10576 boolean systemUpdate = false; 10577 10578 // for the uninstall-updates case and restricted profiles, remember the per- 10579 // userhandle installed state 10580 int[] allUsers; 10581 boolean[] perUserInstalled; 10582 synchronized (mPackages) { 10583 PackageSetting ps = mSettings.mPackages.get(packageName); 10584 allUsers = sUserManager.getUserIds(); 10585 perUserInstalled = new boolean[allUsers.length]; 10586 for (int i = 0; i < allUsers.length; i++) { 10587 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10588 } 10589 } 10590 10591 synchronized (mInstallLock) { 10592 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10593 res = deletePackageLI(packageName, 10594 (flags & PackageManager.DELETE_ALL_USERS) != 0 10595 ? UserHandle.ALL : new UserHandle(userId), 10596 true, allUsers, perUserInstalled, 10597 flags | REMOVE_CHATTY, info, true); 10598 systemUpdate = info.isRemovedPackageSystemUpdate; 10599 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10600 removedForAllUsers = true; 10601 } 10602 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10603 + " removedForAllUsers=" + removedForAllUsers); 10604 } 10605 10606 if (res) { 10607 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10608 10609 // If the removed package was a system update, the old system package 10610 // was re-enabled; we need to broadcast this information 10611 if (systemUpdate) { 10612 Bundle extras = new Bundle(1); 10613 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10614 ? info.removedAppId : info.uid); 10615 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10616 10617 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10618 extras, null, null, null); 10619 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10620 extras, null, null, null); 10621 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10622 null, packageName, null, null); 10623 } 10624 } 10625 // Force a gc here. 10626 Runtime.getRuntime().gc(); 10627 // Delete the resources here after sending the broadcast to let 10628 // other processes clean up before deleting resources. 10629 if (info.args != null) { 10630 synchronized (mInstallLock) { 10631 info.args.doPostDeleteLI(true); 10632 } 10633 } 10634 10635 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10636 } 10637 10638 static class PackageRemovedInfo { 10639 String removedPackage; 10640 int uid = -1; 10641 int removedAppId = -1; 10642 int[] removedUsers = null; 10643 boolean isRemovedPackageSystemUpdate = false; 10644 // Clean up resources deleted packages. 10645 InstallArgs args = null; 10646 10647 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10648 Bundle extras = new Bundle(1); 10649 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10650 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10651 if (replacing) { 10652 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10653 } 10654 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10655 if (removedPackage != null) { 10656 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10657 extras, null, null, removedUsers); 10658 if (fullRemove && !replacing) { 10659 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10660 extras, null, null, removedUsers); 10661 } 10662 } 10663 if (removedAppId >= 0) { 10664 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10665 removedUsers); 10666 } 10667 } 10668 } 10669 10670 /* 10671 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10672 * flag is not set, the data directory is removed as well. 10673 * make sure this flag is set for partially installed apps. If not its meaningless to 10674 * delete a partially installed application. 10675 */ 10676 private void removePackageDataLI(PackageSetting ps, 10677 int[] allUserHandles, boolean[] perUserInstalled, 10678 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10679 String packageName = ps.name; 10680 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10681 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10682 // Retrieve object to delete permissions for shared user later on 10683 final PackageSetting deletedPs; 10684 // reader 10685 synchronized (mPackages) { 10686 deletedPs = mSettings.mPackages.get(packageName); 10687 if (outInfo != null) { 10688 outInfo.removedPackage = packageName; 10689 outInfo.removedUsers = deletedPs != null 10690 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10691 : null; 10692 } 10693 } 10694 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10695 removeDataDirsLI(packageName); 10696 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10697 } 10698 // writer 10699 synchronized (mPackages) { 10700 if (deletedPs != null) { 10701 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10702 if (outInfo != null) { 10703 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10704 } 10705 if (deletedPs != null) { 10706 updatePermissionsLPw(deletedPs.name, null, 0); 10707 if (deletedPs.sharedUser != null) { 10708 // remove permissions associated with package 10709 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10710 } 10711 } 10712 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10713 } 10714 // make sure to preserve per-user disabled state if this removal was just 10715 // a downgrade of a system app to the factory package 10716 if (allUserHandles != null && perUserInstalled != null) { 10717 if (DEBUG_REMOVE) { 10718 Slog.d(TAG, "Propagating install state across downgrade"); 10719 } 10720 for (int i = 0; i < allUserHandles.length; i++) { 10721 if (DEBUG_REMOVE) { 10722 Slog.d(TAG, " user " + allUserHandles[i] 10723 + " => " + perUserInstalled[i]); 10724 } 10725 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10726 } 10727 } 10728 } 10729 // can downgrade to reader 10730 if (writeSettings) { 10731 // Save settings now 10732 mSettings.writeLPr(); 10733 } 10734 } 10735 if (outInfo != null) { 10736 // A user ID was deleted here. Go through all users and remove it 10737 // from KeyStore. 10738 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10739 } 10740 } 10741 10742 static boolean locationIsPrivileged(File path) { 10743 try { 10744 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10745 .getCanonicalPath(); 10746 return path.getCanonicalPath().startsWith(privilegedAppDir); 10747 } catch (IOException e) { 10748 Slog.e(TAG, "Unable to access code path " + path); 10749 } 10750 return false; 10751 } 10752 10753 /* 10754 * Tries to delete system package. 10755 */ 10756 private boolean deleteSystemPackageLI(PackageSetting newPs, 10757 int[] allUserHandles, boolean[] perUserInstalled, 10758 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10759 final boolean applyUserRestrictions 10760 = (allUserHandles != null) && (perUserInstalled != null); 10761 PackageSetting disabledPs = null; 10762 // Confirm if the system package has been updated 10763 // An updated system app can be deleted. This will also have to restore 10764 // the system pkg from system partition 10765 // reader 10766 synchronized (mPackages) { 10767 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10768 } 10769 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10770 + " disabledPs=" + disabledPs); 10771 if (disabledPs == null) { 10772 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10773 return false; 10774 } else if (DEBUG_REMOVE) { 10775 Slog.d(TAG, "Deleting system pkg from data partition"); 10776 } 10777 if (DEBUG_REMOVE) { 10778 if (applyUserRestrictions) { 10779 Slog.d(TAG, "Remembering install states:"); 10780 for (int i = 0; i < allUserHandles.length; i++) { 10781 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10782 } 10783 } 10784 } 10785 // Delete the updated package 10786 outInfo.isRemovedPackageSystemUpdate = true; 10787 if (disabledPs.versionCode < newPs.versionCode) { 10788 // Delete data for downgrades 10789 flags &= ~PackageManager.DELETE_KEEP_DATA; 10790 } else { 10791 // Preserve data by setting flag 10792 flags |= PackageManager.DELETE_KEEP_DATA; 10793 } 10794 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10795 allUserHandles, perUserInstalled, outInfo, writeSettings); 10796 if (!ret) { 10797 return false; 10798 } 10799 // writer 10800 synchronized (mPackages) { 10801 // Reinstate the old system package 10802 mSettings.enableSystemPackageLPw(newPs.name); 10803 // Remove any native libraries from the upgraded package. 10804 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 10805 } 10806 // Install the system package 10807 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10808 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10809 if (locationIsPrivileged(disabledPs.codePath)) { 10810 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10811 } 10812 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10813 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null); 10814 10815 if (newPkg == null) { 10816 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10817 + " with error:" + mLastScanError); 10818 return false; 10819 } 10820 // writer 10821 synchronized (mPackages) { 10822 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10823 setInternalAppNativeLibraryPath(newPkg, ps); 10824 updatePermissionsLPw(newPkg.packageName, newPkg, 10825 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10826 if (applyUserRestrictions) { 10827 if (DEBUG_REMOVE) { 10828 Slog.d(TAG, "Propagating install state across reinstall"); 10829 } 10830 for (int i = 0; i < allUserHandles.length; i++) { 10831 if (DEBUG_REMOVE) { 10832 Slog.d(TAG, " user " + allUserHandles[i] 10833 + " => " + perUserInstalled[i]); 10834 } 10835 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10836 } 10837 // Regardless of writeSettings we need to ensure that this restriction 10838 // state propagation is persisted 10839 mSettings.writeAllUsersPackageRestrictionsLPr(); 10840 } 10841 // can downgrade to reader here 10842 if (writeSettings) { 10843 mSettings.writeLPr(); 10844 } 10845 } 10846 return true; 10847 } 10848 10849 private boolean deleteInstalledPackageLI(PackageSetting ps, 10850 boolean deleteCodeAndResources, int flags, 10851 int[] allUserHandles, boolean[] perUserInstalled, 10852 PackageRemovedInfo outInfo, boolean writeSettings) { 10853 if (outInfo != null) { 10854 outInfo.uid = ps.appId; 10855 } 10856 10857 // Delete package data from internal structures and also remove data if flag is set 10858 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10859 10860 // Delete application code and resources 10861 if (deleteCodeAndResources && (outInfo != null)) { 10862 outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString, 10863 ps.resourcePathString, ps.nativeLibraryPathString, 10864 getAppInstructionSetFromSettings(ps)); 10865 } 10866 return true; 10867 } 10868 10869 /* 10870 * This method handles package deletion in general 10871 */ 10872 private boolean deletePackageLI(String packageName, UserHandle user, 10873 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10874 int flags, PackageRemovedInfo outInfo, 10875 boolean writeSettings) { 10876 if (packageName == null) { 10877 Slog.w(TAG, "Attempt to delete null packageName."); 10878 return false; 10879 } 10880 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10881 PackageSetting ps; 10882 boolean dataOnly = false; 10883 int removeUser = -1; 10884 int appId = -1; 10885 synchronized (mPackages) { 10886 ps = mSettings.mPackages.get(packageName); 10887 if (ps == null) { 10888 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10889 return false; 10890 } 10891 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10892 && user.getIdentifier() != UserHandle.USER_ALL) { 10893 // The caller is asking that the package only be deleted for a single 10894 // user. To do this, we just mark its uninstalled state and delete 10895 // its data. If this is a system app, we only allow this to happen if 10896 // they have set the special DELETE_SYSTEM_APP which requests different 10897 // semantics than normal for uninstalling system apps. 10898 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10899 ps.setUserState(user.getIdentifier(), 10900 COMPONENT_ENABLED_STATE_DEFAULT, 10901 false, //installed 10902 true, //stopped 10903 true, //notLaunched 10904 false, //blocked 10905 null, null, null); 10906 if (!isSystemApp(ps)) { 10907 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10908 // Other user still have this package installed, so all 10909 // we need to do is clear this user's data and save that 10910 // it is uninstalled. 10911 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10912 removeUser = user.getIdentifier(); 10913 appId = ps.appId; 10914 mSettings.writePackageRestrictionsLPr(removeUser); 10915 } else { 10916 // We need to set it back to 'installed' so the uninstall 10917 // broadcasts will be sent correctly. 10918 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10919 ps.setInstalled(true, user.getIdentifier()); 10920 } 10921 } else { 10922 // This is a system app, so we assume that the 10923 // other users still have this package installed, so all 10924 // we need to do is clear this user's data and save that 10925 // it is uninstalled. 10926 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10927 removeUser = user.getIdentifier(); 10928 appId = ps.appId; 10929 mSettings.writePackageRestrictionsLPr(removeUser); 10930 } 10931 } 10932 } 10933 10934 if (removeUser >= 0) { 10935 // From above, we determined that we are deleting this only 10936 // for a single user. Continue the work here. 10937 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10938 if (outInfo != null) { 10939 outInfo.removedPackage = packageName; 10940 outInfo.removedAppId = appId; 10941 outInfo.removedUsers = new int[] {removeUser}; 10942 } 10943 mInstaller.clearUserData(packageName, removeUser); 10944 removeKeystoreDataIfNeeded(removeUser, appId); 10945 schedulePackageCleaning(packageName, removeUser, false); 10946 return true; 10947 } 10948 10949 if (dataOnly) { 10950 // Delete application data first 10951 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10952 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10953 return true; 10954 } 10955 10956 boolean ret = false; 10957 mSettings.mKeySetManager.removeAppKeySetData(packageName); 10958 if (isSystemApp(ps)) { 10959 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10960 // When an updated system application is deleted we delete the existing resources as well and 10961 // fall back to existing code in system partition 10962 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10963 flags, outInfo, writeSettings); 10964 } else { 10965 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10966 // Kill application pre-emptively especially for apps on sd. 10967 killApplication(packageName, ps.appId, "uninstall pkg"); 10968 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10969 allUserHandles, perUserInstalled, 10970 outInfo, writeSettings); 10971 } 10972 10973 return ret; 10974 } 10975 10976 private final class ClearStorageConnection implements ServiceConnection { 10977 IMediaContainerService mContainerService; 10978 10979 @Override 10980 public void onServiceConnected(ComponentName name, IBinder service) { 10981 synchronized (this) { 10982 mContainerService = IMediaContainerService.Stub.asInterface(service); 10983 notifyAll(); 10984 } 10985 } 10986 10987 @Override 10988 public void onServiceDisconnected(ComponentName name) { 10989 } 10990 } 10991 10992 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10993 final boolean mounted; 10994 if (Environment.isExternalStorageEmulated()) { 10995 mounted = true; 10996 } else { 10997 final String status = Environment.getExternalStorageState(); 10998 10999 mounted = status.equals(Environment.MEDIA_MOUNTED) 11000 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11001 } 11002 11003 if (!mounted) { 11004 return; 11005 } 11006 11007 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11008 int[] users; 11009 if (userId == UserHandle.USER_ALL) { 11010 users = sUserManager.getUserIds(); 11011 } else { 11012 users = new int[] { userId }; 11013 } 11014 final ClearStorageConnection conn = new ClearStorageConnection(); 11015 if (mContext.bindServiceAsUser( 11016 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11017 try { 11018 for (int curUser : users) { 11019 long timeout = SystemClock.uptimeMillis() + 5000; 11020 synchronized (conn) { 11021 long now = SystemClock.uptimeMillis(); 11022 while (conn.mContainerService == null && now < timeout) { 11023 try { 11024 conn.wait(timeout - now); 11025 } catch (InterruptedException e) { 11026 } 11027 } 11028 } 11029 if (conn.mContainerService == null) { 11030 return; 11031 } 11032 11033 final UserEnvironment userEnv = new UserEnvironment(curUser); 11034 clearDirectory(conn.mContainerService, 11035 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11036 if (allData) { 11037 clearDirectory(conn.mContainerService, 11038 userEnv.buildExternalStorageAppDataDirs(packageName)); 11039 clearDirectory(conn.mContainerService, 11040 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11041 } 11042 } 11043 } finally { 11044 mContext.unbindService(conn); 11045 } 11046 } 11047 } 11048 11049 @Override 11050 public void clearApplicationUserData(final String packageName, 11051 final IPackageDataObserver observer, final int userId) { 11052 mContext.enforceCallingOrSelfPermission( 11053 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11054 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11055 // Queue up an async operation since the package deletion may take a little while. 11056 mHandler.post(new Runnable() { 11057 public void run() { 11058 mHandler.removeCallbacks(this); 11059 final boolean succeeded; 11060 synchronized (mInstallLock) { 11061 succeeded = clearApplicationUserDataLI(packageName, userId); 11062 } 11063 clearExternalStorageDataSync(packageName, userId, true); 11064 if (succeeded) { 11065 // invoke DeviceStorageMonitor's update method to clear any notifications 11066 DeviceStorageMonitorInternal 11067 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11068 if (dsm != null) { 11069 dsm.checkMemory(); 11070 } 11071 } 11072 if(observer != null) { 11073 try { 11074 observer.onRemoveCompleted(packageName, succeeded); 11075 } catch (RemoteException e) { 11076 Log.i(TAG, "Observer no longer exists."); 11077 } 11078 } //end if observer 11079 } //end run 11080 }); 11081 } 11082 11083 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11084 if (packageName == null) { 11085 Slog.w(TAG, "Attempt to delete null packageName."); 11086 return false; 11087 } 11088 PackageParser.Package p; 11089 boolean dataOnly = false; 11090 final int appId; 11091 synchronized (mPackages) { 11092 p = mPackages.get(packageName); 11093 if (p == null) { 11094 dataOnly = true; 11095 PackageSetting ps = mSettings.mPackages.get(packageName); 11096 if ((ps == null) || (ps.pkg == null)) { 11097 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11098 return false; 11099 } 11100 p = ps.pkg; 11101 } 11102 if (!dataOnly) { 11103 // need to check this only for fully installed applications 11104 if (p == null) { 11105 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11106 return false; 11107 } 11108 final ApplicationInfo applicationInfo = p.applicationInfo; 11109 if (applicationInfo == null) { 11110 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11111 return false; 11112 } 11113 } 11114 if (p != null && p.applicationInfo != null) { 11115 appId = p.applicationInfo.uid; 11116 } else { 11117 appId = -1; 11118 } 11119 } 11120 int retCode = mInstaller.clearUserData(packageName, userId); 11121 if (retCode < 0) { 11122 Slog.w(TAG, "Couldn't remove cache files for package: " 11123 + packageName); 11124 return false; 11125 } 11126 removeKeystoreDataIfNeeded(userId, appId); 11127 return true; 11128 } 11129 11130 /** 11131 * Remove entries from the keystore daemon. Will only remove it if the 11132 * {@code appId} is valid. 11133 */ 11134 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11135 if (appId < 0) { 11136 return; 11137 } 11138 11139 final KeyStore keyStore = KeyStore.getInstance(); 11140 if (keyStore != null) { 11141 if (userId == UserHandle.USER_ALL) { 11142 for (final int individual : sUserManager.getUserIds()) { 11143 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11144 } 11145 } else { 11146 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11147 } 11148 } else { 11149 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11150 } 11151 } 11152 11153 @Override 11154 public void deleteApplicationCacheFiles(final String packageName, 11155 final IPackageDataObserver observer) { 11156 mContext.enforceCallingOrSelfPermission( 11157 android.Manifest.permission.DELETE_CACHE_FILES, null); 11158 // Queue up an async operation since the package deletion may take a little while. 11159 final int userId = UserHandle.getCallingUserId(); 11160 mHandler.post(new Runnable() { 11161 public void run() { 11162 mHandler.removeCallbacks(this); 11163 final boolean succeded; 11164 synchronized (mInstallLock) { 11165 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11166 } 11167 clearExternalStorageDataSync(packageName, userId, false); 11168 if(observer != null) { 11169 try { 11170 observer.onRemoveCompleted(packageName, succeded); 11171 } catch (RemoteException e) { 11172 Log.i(TAG, "Observer no longer exists."); 11173 } 11174 } //end if observer 11175 } //end run 11176 }); 11177 } 11178 11179 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11180 if (packageName == null) { 11181 Slog.w(TAG, "Attempt to delete null packageName."); 11182 return false; 11183 } 11184 PackageParser.Package p; 11185 synchronized (mPackages) { 11186 p = mPackages.get(packageName); 11187 } 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 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11198 if (retCode < 0) { 11199 Slog.w(TAG, "Couldn't remove cache files for package: " 11200 + packageName + " u" + userId); 11201 return false; 11202 } 11203 return true; 11204 } 11205 11206 @Override 11207 public void getPackageSizeInfo(final String packageName, int userHandle, 11208 final IPackageStatsObserver observer) { 11209 mContext.enforceCallingOrSelfPermission( 11210 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11211 if (packageName == null) { 11212 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11213 } 11214 11215 PackageStats stats = new PackageStats(packageName, userHandle); 11216 11217 /* 11218 * Queue up an async operation since the package measurement may take a 11219 * little while. 11220 */ 11221 Message msg = mHandler.obtainMessage(INIT_COPY); 11222 msg.obj = new MeasureParams(stats, observer); 11223 mHandler.sendMessage(msg); 11224 } 11225 11226 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11227 PackageStats pStats) { 11228 if (packageName == null) { 11229 Slog.w(TAG, "Attempt to get size of null packageName."); 11230 return false; 11231 } 11232 PackageParser.Package p; 11233 boolean dataOnly = false; 11234 String libDirPath = null; 11235 String asecPath = null; 11236 PackageSetting ps = null; 11237 synchronized (mPackages) { 11238 p = mPackages.get(packageName); 11239 ps = mSettings.mPackages.get(packageName); 11240 if(p == null) { 11241 dataOnly = true; 11242 if((ps == null) || (ps.pkg == null)) { 11243 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11244 return false; 11245 } 11246 p = ps.pkg; 11247 } 11248 if (ps != null) { 11249 libDirPath = ps.nativeLibraryPathString; 11250 } 11251 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11252 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 11253 if (secureContainerId != null) { 11254 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11255 } 11256 } 11257 } 11258 String publicSrcDir = null; 11259 if(!dataOnly) { 11260 final ApplicationInfo applicationInfo = p.applicationInfo; 11261 if (applicationInfo == null) { 11262 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11263 return false; 11264 } 11265 if (isForwardLocked(p)) { 11266 publicSrcDir = applicationInfo.publicSourceDir; 11267 } 11268 } 11269 int res = mInstaller.getSizeInfo(packageName, userHandle, p.codePath, libDirPath, 11270 publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps), 11271 pStats); 11272 if (res < 0) { 11273 return false; 11274 } 11275 11276 // Fix-up for forward-locked applications in ASEC containers. 11277 if (!isExternal(p)) { 11278 pStats.codeSize += pStats.externalCodeSize; 11279 pStats.externalCodeSize = 0L; 11280 } 11281 11282 return true; 11283 } 11284 11285 11286 @Override 11287 public void addPackageToPreferred(String packageName) { 11288 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11289 } 11290 11291 @Override 11292 public void removePackageFromPreferred(String packageName) { 11293 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11294 } 11295 11296 @Override 11297 public List<PackageInfo> getPreferredPackages(int flags) { 11298 return new ArrayList<PackageInfo>(); 11299 } 11300 11301 private int getUidTargetSdkVersionLockedLPr(int uid) { 11302 Object obj = mSettings.getUserIdLPr(uid); 11303 if (obj instanceof SharedUserSetting) { 11304 final SharedUserSetting sus = (SharedUserSetting) obj; 11305 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11306 final Iterator<PackageSetting> it = sus.packages.iterator(); 11307 while (it.hasNext()) { 11308 final PackageSetting ps = it.next(); 11309 if (ps.pkg != null) { 11310 int v = ps.pkg.applicationInfo.targetSdkVersion; 11311 if (v < vers) vers = v; 11312 } 11313 } 11314 return vers; 11315 } else if (obj instanceof PackageSetting) { 11316 final PackageSetting ps = (PackageSetting) obj; 11317 if (ps.pkg != null) { 11318 return ps.pkg.applicationInfo.targetSdkVersion; 11319 } 11320 } 11321 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11322 } 11323 11324 @Override 11325 public void addPreferredActivity(IntentFilter filter, int match, 11326 ComponentName[] set, ComponentName activity, int userId) { 11327 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11328 } 11329 11330 private void addPreferredActivityInternal(IntentFilter filter, int match, 11331 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11332 // writer 11333 int callingUid = Binder.getCallingUid(); 11334 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11335 if (filter.countActions() == 0) { 11336 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11337 return; 11338 } 11339 synchronized (mPackages) { 11340 if (mContext.checkCallingOrSelfPermission( 11341 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11342 != PackageManager.PERMISSION_GRANTED) { 11343 if (getUidTargetSdkVersionLockedLPr(callingUid) 11344 < Build.VERSION_CODES.FROYO) { 11345 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11346 + callingUid); 11347 return; 11348 } 11349 mContext.enforceCallingOrSelfPermission( 11350 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11351 } 11352 11353 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11354 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11355 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11356 new PreferredActivity(filter, match, set, activity, always)); 11357 mSettings.writePackageRestrictionsLPr(userId); 11358 } 11359 } 11360 11361 @Override 11362 public void replacePreferredActivity(IntentFilter filter, int match, 11363 ComponentName[] set, ComponentName activity) { 11364 if (filter.countActions() != 1) { 11365 throw new IllegalArgumentException( 11366 "replacePreferredActivity expects filter to have only 1 action."); 11367 } 11368 if (filter.countDataAuthorities() != 0 11369 || filter.countDataPaths() != 0 11370 || filter.countDataSchemes() > 1 11371 || filter.countDataTypes() != 0) { 11372 throw new IllegalArgumentException( 11373 "replacePreferredActivity expects filter to have no data authorities, " + 11374 "paths, or types; and at most one scheme."); 11375 } 11376 synchronized (mPackages) { 11377 if (mContext.checkCallingOrSelfPermission( 11378 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11379 != PackageManager.PERMISSION_GRANTED) { 11380 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11381 < Build.VERSION_CODES.FROYO) { 11382 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11383 + Binder.getCallingUid()); 11384 return; 11385 } 11386 mContext.enforceCallingOrSelfPermission( 11387 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11388 } 11389 11390 final int callingUserId = UserHandle.getCallingUserId(); 11391 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11392 if (pir != null) { 11393 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11394 if (filter.countDataSchemes() == 1) { 11395 Uri.Builder builder = new Uri.Builder(); 11396 builder.scheme(filter.getDataScheme(0)); 11397 intent.setData(builder.build()); 11398 } 11399 List<PreferredActivity> matches = pir.queryIntent( 11400 intent, null, true, callingUserId); 11401 if (DEBUG_PREFERRED) { 11402 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11403 } 11404 for (int i = 0; i < matches.size(); i++) { 11405 PreferredActivity pa = matches.get(i); 11406 if (DEBUG_PREFERRED) { 11407 Slog.i(TAG, "Removing preferred activity " 11408 + pa.mPref.mComponent + ":"); 11409 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11410 } 11411 pir.removeFilter(pa); 11412 } 11413 } 11414 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11415 } 11416 } 11417 11418 @Override 11419 public void clearPackagePreferredActivities(String packageName) { 11420 final int uid = Binder.getCallingUid(); 11421 // writer 11422 synchronized (mPackages) { 11423 PackageParser.Package pkg = mPackages.get(packageName); 11424 if (pkg == null || pkg.applicationInfo.uid != uid) { 11425 if (mContext.checkCallingOrSelfPermission( 11426 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11427 != PackageManager.PERMISSION_GRANTED) { 11428 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11429 < Build.VERSION_CODES.FROYO) { 11430 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11431 + Binder.getCallingUid()); 11432 return; 11433 } 11434 mContext.enforceCallingOrSelfPermission( 11435 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11436 } 11437 } 11438 11439 int user = UserHandle.getCallingUserId(); 11440 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11441 mSettings.writePackageRestrictionsLPr(user); 11442 scheduleWriteSettingsLocked(); 11443 } 11444 } 11445 } 11446 11447 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11448 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11449 ArrayList<PreferredActivity> removed = null; 11450 boolean changed = false; 11451 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11452 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11453 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11454 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11455 continue; 11456 } 11457 Iterator<PreferredActivity> it = pir.filterIterator(); 11458 while (it.hasNext()) { 11459 PreferredActivity pa = it.next(); 11460 // Mark entry for removal only if it matches the package name 11461 // and the entry is of type "always". 11462 if (packageName == null || 11463 (pa.mPref.mComponent.getPackageName().equals(packageName) 11464 && pa.mPref.mAlways)) { 11465 if (removed == null) { 11466 removed = new ArrayList<PreferredActivity>(); 11467 } 11468 removed.add(pa); 11469 } 11470 } 11471 if (removed != null) { 11472 for (int j=0; j<removed.size(); j++) { 11473 PreferredActivity pa = removed.get(j); 11474 pir.removeFilter(pa); 11475 } 11476 changed = true; 11477 } 11478 } 11479 return changed; 11480 } 11481 11482 @Override 11483 public void resetPreferredActivities(int userId) { 11484 mContext.enforceCallingOrSelfPermission( 11485 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11486 // writer 11487 synchronized (mPackages) { 11488 int user = UserHandle.getCallingUserId(); 11489 clearPackagePreferredActivitiesLPw(null, user); 11490 mSettings.readDefaultPreferredAppsLPw(this, user); 11491 mSettings.writePackageRestrictionsLPr(user); 11492 scheduleWriteSettingsLocked(); 11493 } 11494 } 11495 11496 @Override 11497 public int getPreferredActivities(List<IntentFilter> outFilters, 11498 List<ComponentName> outActivities, String packageName) { 11499 11500 int num = 0; 11501 final int userId = UserHandle.getCallingUserId(); 11502 // reader 11503 synchronized (mPackages) { 11504 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11505 if (pir != null) { 11506 final Iterator<PreferredActivity> it = pir.filterIterator(); 11507 while (it.hasNext()) { 11508 final PreferredActivity pa = it.next(); 11509 if (packageName == null 11510 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11511 && pa.mPref.mAlways)) { 11512 if (outFilters != null) { 11513 outFilters.add(new IntentFilter(pa)); 11514 } 11515 if (outActivities != null) { 11516 outActivities.add(pa.mPref.mComponent); 11517 } 11518 } 11519 } 11520 } 11521 } 11522 11523 return num; 11524 } 11525 11526 @Override 11527 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11528 int userId) { 11529 int callingUid = Binder.getCallingUid(); 11530 if (callingUid != Process.SYSTEM_UID) { 11531 throw new SecurityException( 11532 "addPersistentPreferredActivity can only be run by the system"); 11533 } 11534 if (filter.countActions() == 0) { 11535 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11536 return; 11537 } 11538 synchronized (mPackages) { 11539 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11540 " :"); 11541 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11542 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11543 new PersistentPreferredActivity(filter, activity)); 11544 mSettings.writePackageRestrictionsLPr(userId); 11545 } 11546 } 11547 11548 @Override 11549 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11550 int callingUid = Binder.getCallingUid(); 11551 if (callingUid != Process.SYSTEM_UID) { 11552 throw new SecurityException( 11553 "clearPackagePersistentPreferredActivities can only be run by the system"); 11554 } 11555 ArrayList<PersistentPreferredActivity> removed = null; 11556 boolean changed = false; 11557 synchronized (mPackages) { 11558 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11559 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11560 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11561 .valueAt(i); 11562 if (userId != thisUserId) { 11563 continue; 11564 } 11565 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11566 while (it.hasNext()) { 11567 PersistentPreferredActivity ppa = it.next(); 11568 // Mark entry for removal only if it matches the package name. 11569 if (ppa.mComponent.getPackageName().equals(packageName)) { 11570 if (removed == null) { 11571 removed = new ArrayList<PersistentPreferredActivity>(); 11572 } 11573 removed.add(ppa); 11574 } 11575 } 11576 if (removed != null) { 11577 for (int j=0; j<removed.size(); j++) { 11578 PersistentPreferredActivity ppa = removed.get(j); 11579 ppir.removeFilter(ppa); 11580 } 11581 changed = true; 11582 } 11583 } 11584 11585 if (changed) { 11586 mSettings.writePackageRestrictionsLPr(userId); 11587 } 11588 } 11589 } 11590 11591 @Override 11592 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11593 int targetUserId, int flags) { 11594 mContext.enforceCallingOrSelfPermission( 11595 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11596 if (intentFilter.countActions() == 0) { 11597 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11598 return; 11599 } 11600 synchronized (mPackages) { 11601 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11602 targetUserId, flags); 11603 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11604 mSettings.writePackageRestrictionsLPr(sourceUserId); 11605 } 11606 } 11607 11608 @Override 11609 public void clearCrossProfileIntentFilters(int sourceUserId) { 11610 mContext.enforceCallingOrSelfPermission( 11611 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11612 synchronized (mPackages) { 11613 CrossProfileIntentResolver resolver = 11614 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11615 HashSet<CrossProfileIntentFilter> set = 11616 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11617 for (CrossProfileIntentFilter filter : set) { 11618 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11619 resolver.removeFilter(filter); 11620 } 11621 } 11622 mSettings.writePackageRestrictionsLPr(sourceUserId); 11623 } 11624 } 11625 11626 @Override 11627 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11628 Intent intent = new Intent(Intent.ACTION_MAIN); 11629 intent.addCategory(Intent.CATEGORY_HOME); 11630 11631 final int callingUserId = UserHandle.getCallingUserId(); 11632 List<ResolveInfo> list = queryIntentActivities(intent, null, 11633 PackageManager.GET_META_DATA, callingUserId); 11634 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11635 true, false, false, callingUserId); 11636 11637 allHomeCandidates.clear(); 11638 if (list != null) { 11639 for (ResolveInfo ri : list) { 11640 allHomeCandidates.add(ri); 11641 } 11642 } 11643 return (preferred == null || preferred.activityInfo == null) 11644 ? null 11645 : new ComponentName(preferred.activityInfo.packageName, 11646 preferred.activityInfo.name); 11647 } 11648 11649 @Override 11650 public void setApplicationEnabledSetting(String appPackageName, 11651 int newState, int flags, int userId, String callingPackage) { 11652 if (!sUserManager.exists(userId)) return; 11653 if (callingPackage == null) { 11654 callingPackage = Integer.toString(Binder.getCallingUid()); 11655 } 11656 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11657 } 11658 11659 @Override 11660 public void setComponentEnabledSetting(ComponentName componentName, 11661 int newState, int flags, int userId) { 11662 if (!sUserManager.exists(userId)) return; 11663 setEnabledSetting(componentName.getPackageName(), 11664 componentName.getClassName(), newState, flags, userId, null); 11665 } 11666 11667 private void setEnabledSetting(final String packageName, String className, int newState, 11668 final int flags, int userId, String callingPackage) { 11669 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11670 || newState == COMPONENT_ENABLED_STATE_ENABLED 11671 || newState == COMPONENT_ENABLED_STATE_DISABLED 11672 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11673 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11674 throw new IllegalArgumentException("Invalid new component state: " 11675 + newState); 11676 } 11677 PackageSetting pkgSetting; 11678 final int uid = Binder.getCallingUid(); 11679 final int permission = mContext.checkCallingOrSelfPermission( 11680 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11681 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11682 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11683 boolean sendNow = false; 11684 boolean isApp = (className == null); 11685 String componentName = isApp ? packageName : className; 11686 int packageUid = -1; 11687 ArrayList<String> components; 11688 11689 // writer 11690 synchronized (mPackages) { 11691 pkgSetting = mSettings.mPackages.get(packageName); 11692 if (pkgSetting == null) { 11693 if (className == null) { 11694 throw new IllegalArgumentException( 11695 "Unknown package: " + packageName); 11696 } 11697 throw new IllegalArgumentException( 11698 "Unknown component: " + packageName 11699 + "/" + className); 11700 } 11701 // Allow root and verify that userId is not being specified by a different user 11702 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11703 throw new SecurityException( 11704 "Permission Denial: attempt to change component state from pid=" 11705 + Binder.getCallingPid() 11706 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11707 } 11708 if (className == null) { 11709 // We're dealing with an application/package level state change 11710 if (pkgSetting.getEnabled(userId) == newState) { 11711 // Nothing to do 11712 return; 11713 } 11714 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11715 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11716 // Don't care about who enables an app. 11717 callingPackage = null; 11718 } 11719 pkgSetting.setEnabled(newState, userId, callingPackage); 11720 // pkgSetting.pkg.mSetEnabled = newState; 11721 } else { 11722 // We're dealing with a component level state change 11723 // First, verify that this is a valid class name. 11724 PackageParser.Package pkg = pkgSetting.pkg; 11725 if (pkg == null || !pkg.hasComponentClassName(className)) { 11726 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11727 throw new IllegalArgumentException("Component class " + className 11728 + " does not exist in " + packageName); 11729 } else { 11730 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11731 + className + " does not exist in " + packageName); 11732 } 11733 } 11734 switch (newState) { 11735 case COMPONENT_ENABLED_STATE_ENABLED: 11736 if (!pkgSetting.enableComponentLPw(className, userId)) { 11737 return; 11738 } 11739 break; 11740 case COMPONENT_ENABLED_STATE_DISABLED: 11741 if (!pkgSetting.disableComponentLPw(className, userId)) { 11742 return; 11743 } 11744 break; 11745 case COMPONENT_ENABLED_STATE_DEFAULT: 11746 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11747 return; 11748 } 11749 break; 11750 default: 11751 Slog.e(TAG, "Invalid new component state: " + newState); 11752 return; 11753 } 11754 } 11755 mSettings.writePackageRestrictionsLPr(userId); 11756 components = mPendingBroadcasts.get(userId, packageName); 11757 final boolean newPackage = components == null; 11758 if (newPackage) { 11759 components = new ArrayList<String>(); 11760 } 11761 if (!components.contains(componentName)) { 11762 components.add(componentName); 11763 } 11764 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11765 sendNow = true; 11766 // Purge entry from pending broadcast list if another one exists already 11767 // since we are sending one right away. 11768 mPendingBroadcasts.remove(userId, packageName); 11769 } else { 11770 if (newPackage) { 11771 mPendingBroadcasts.put(userId, packageName, components); 11772 } 11773 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11774 // Schedule a message 11775 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11776 } 11777 } 11778 } 11779 11780 long callingId = Binder.clearCallingIdentity(); 11781 try { 11782 if (sendNow) { 11783 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11784 sendPackageChangedBroadcast(packageName, 11785 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11786 } 11787 } finally { 11788 Binder.restoreCallingIdentity(callingId); 11789 } 11790 } 11791 11792 private void sendPackageChangedBroadcast(String packageName, 11793 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11794 if (DEBUG_INSTALL) 11795 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11796 + componentNames); 11797 Bundle extras = new Bundle(4); 11798 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11799 String nameList[] = new String[componentNames.size()]; 11800 componentNames.toArray(nameList); 11801 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11802 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11803 extras.putInt(Intent.EXTRA_UID, packageUid); 11804 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11805 new int[] {UserHandle.getUserId(packageUid)}); 11806 } 11807 11808 @Override 11809 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11810 if (!sUserManager.exists(userId)) return; 11811 final int uid = Binder.getCallingUid(); 11812 final int permission = mContext.checkCallingOrSelfPermission( 11813 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11814 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11815 enforceCrossUserPermission(uid, userId, true, "stop package"); 11816 // writer 11817 synchronized (mPackages) { 11818 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11819 uid, userId)) { 11820 scheduleWritePackageRestrictionsLocked(userId); 11821 } 11822 } 11823 } 11824 11825 @Override 11826 public String getInstallerPackageName(String packageName) { 11827 // reader 11828 synchronized (mPackages) { 11829 return mSettings.getInstallerPackageNameLPr(packageName); 11830 } 11831 } 11832 11833 @Override 11834 public int getApplicationEnabledSetting(String packageName, int userId) { 11835 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11836 int uid = Binder.getCallingUid(); 11837 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11838 // reader 11839 synchronized (mPackages) { 11840 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11841 } 11842 } 11843 11844 @Override 11845 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11846 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11847 int uid = Binder.getCallingUid(); 11848 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11849 // reader 11850 synchronized (mPackages) { 11851 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11852 } 11853 } 11854 11855 @Override 11856 public void enterSafeMode() { 11857 enforceSystemOrRoot("Only the system can request entering safe mode"); 11858 11859 if (!mSystemReady) { 11860 mSafeMode = true; 11861 } 11862 } 11863 11864 @Override 11865 public void systemReady() { 11866 mSystemReady = true; 11867 11868 // Read the compatibilty setting when the system is ready. 11869 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11870 mContext.getContentResolver(), 11871 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11872 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11873 if (DEBUG_SETTINGS) { 11874 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11875 } 11876 11877 synchronized (mPackages) { 11878 // Verify that all of the preferred activity components actually 11879 // exist. It is possible for applications to be updated and at 11880 // that point remove a previously declared activity component that 11881 // had been set as a preferred activity. We try to clean this up 11882 // the next time we encounter that preferred activity, but it is 11883 // possible for the user flow to never be able to return to that 11884 // situation so here we do a sanity check to make sure we haven't 11885 // left any junk around. 11886 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11887 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11888 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11889 removed.clear(); 11890 for (PreferredActivity pa : pir.filterSet()) { 11891 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11892 removed.add(pa); 11893 } 11894 } 11895 if (removed.size() > 0) { 11896 for (int r=0; r<removed.size(); r++) { 11897 PreferredActivity pa = removed.get(r); 11898 Slog.w(TAG, "Removing dangling preferred activity: " 11899 + pa.mPref.mComponent); 11900 pir.removeFilter(pa); 11901 } 11902 mSettings.writePackageRestrictionsLPr( 11903 mSettings.mPreferredActivities.keyAt(i)); 11904 } 11905 } 11906 } 11907 sUserManager.systemReady(); 11908 } 11909 11910 @Override 11911 public boolean isSafeMode() { 11912 return mSafeMode; 11913 } 11914 11915 @Override 11916 public boolean hasSystemUidErrors() { 11917 return mHasSystemUidErrors; 11918 } 11919 11920 static String arrayToString(int[] array) { 11921 StringBuffer buf = new StringBuffer(128); 11922 buf.append('['); 11923 if (array != null) { 11924 for (int i=0; i<array.length; i++) { 11925 if (i > 0) buf.append(", "); 11926 buf.append(array[i]); 11927 } 11928 } 11929 buf.append(']'); 11930 return buf.toString(); 11931 } 11932 11933 static class DumpState { 11934 public static final int DUMP_LIBS = 1 << 0; 11935 11936 public static final int DUMP_FEATURES = 1 << 1; 11937 11938 public static final int DUMP_RESOLVERS = 1 << 2; 11939 11940 public static final int DUMP_PERMISSIONS = 1 << 3; 11941 11942 public static final int DUMP_PACKAGES = 1 << 4; 11943 11944 public static final int DUMP_SHARED_USERS = 1 << 5; 11945 11946 public static final int DUMP_MESSAGES = 1 << 6; 11947 11948 public static final int DUMP_PROVIDERS = 1 << 7; 11949 11950 public static final int DUMP_VERIFIERS = 1 << 8; 11951 11952 public static final int DUMP_PREFERRED = 1 << 9; 11953 11954 public static final int DUMP_PREFERRED_XML = 1 << 10; 11955 11956 public static final int DUMP_KEYSETS = 1 << 11; 11957 11958 public static final int DUMP_VERSION = 1 << 12; 11959 11960 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11961 11962 private int mTypes; 11963 11964 private int mOptions; 11965 11966 private boolean mTitlePrinted; 11967 11968 private SharedUserSetting mSharedUser; 11969 11970 public boolean isDumping(int type) { 11971 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11972 return true; 11973 } 11974 11975 return (mTypes & type) != 0; 11976 } 11977 11978 public void setDump(int type) { 11979 mTypes |= type; 11980 } 11981 11982 public boolean isOptionEnabled(int option) { 11983 return (mOptions & option) != 0; 11984 } 11985 11986 public void setOptionEnabled(int option) { 11987 mOptions |= option; 11988 } 11989 11990 public boolean onTitlePrinted() { 11991 final boolean printed = mTitlePrinted; 11992 mTitlePrinted = true; 11993 return printed; 11994 } 11995 11996 public boolean getTitlePrinted() { 11997 return mTitlePrinted; 11998 } 11999 12000 public void setTitlePrinted(boolean enabled) { 12001 mTitlePrinted = enabled; 12002 } 12003 12004 public SharedUserSetting getSharedUser() { 12005 return mSharedUser; 12006 } 12007 12008 public void setSharedUser(SharedUserSetting user) { 12009 mSharedUser = user; 12010 } 12011 } 12012 12013 @Override 12014 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12015 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12016 != PackageManager.PERMISSION_GRANTED) { 12017 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12018 + Binder.getCallingPid() 12019 + ", uid=" + Binder.getCallingUid() 12020 + " without permission " 12021 + android.Manifest.permission.DUMP); 12022 return; 12023 } 12024 12025 DumpState dumpState = new DumpState(); 12026 boolean fullPreferred = false; 12027 boolean checkin = false; 12028 12029 String packageName = null; 12030 12031 int opti = 0; 12032 while (opti < args.length) { 12033 String opt = args[opti]; 12034 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12035 break; 12036 } 12037 opti++; 12038 if ("-a".equals(opt)) { 12039 // Right now we only know how to print all. 12040 } else if ("-h".equals(opt)) { 12041 pw.println("Package manager dump options:"); 12042 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12043 pw.println(" --checkin: dump for a checkin"); 12044 pw.println(" -f: print details of intent filters"); 12045 pw.println(" -h: print this help"); 12046 pw.println(" cmd may be one of:"); 12047 pw.println(" l[ibraries]: list known shared libraries"); 12048 pw.println(" f[ibraries]: list device features"); 12049 pw.println(" k[eysets]: print known keysets"); 12050 pw.println(" r[esolvers]: dump intent resolvers"); 12051 pw.println(" perm[issions]: dump permissions"); 12052 pw.println(" pref[erred]: print preferred package settings"); 12053 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12054 pw.println(" prov[iders]: dump content providers"); 12055 pw.println(" p[ackages]: dump installed packages"); 12056 pw.println(" s[hared-users]: dump shared user IDs"); 12057 pw.println(" m[essages]: print collected runtime messages"); 12058 pw.println(" v[erifiers]: print package verifier info"); 12059 pw.println(" version: print database version info"); 12060 pw.println(" write: write current settings now"); 12061 pw.println(" <package.name>: info about given package"); 12062 return; 12063 } else if ("--checkin".equals(opt)) { 12064 checkin = true; 12065 } else if ("-f".equals(opt)) { 12066 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12067 } else { 12068 pw.println("Unknown argument: " + opt + "; use -h for help"); 12069 } 12070 } 12071 12072 // Is the caller requesting to dump a particular piece of data? 12073 if (opti < args.length) { 12074 String cmd = args[opti]; 12075 opti++; 12076 // Is this a package name? 12077 if ("android".equals(cmd) || cmd.contains(".")) { 12078 packageName = cmd; 12079 // When dumping a single package, we always dump all of its 12080 // filter information since the amount of data will be reasonable. 12081 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12082 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12083 dumpState.setDump(DumpState.DUMP_LIBS); 12084 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12085 dumpState.setDump(DumpState.DUMP_FEATURES); 12086 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12087 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12088 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12089 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12090 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12091 dumpState.setDump(DumpState.DUMP_PREFERRED); 12092 } else if ("preferred-xml".equals(cmd)) { 12093 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12094 if (opti < args.length && "--full".equals(args[opti])) { 12095 fullPreferred = true; 12096 opti++; 12097 } 12098 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12099 dumpState.setDump(DumpState.DUMP_PACKAGES); 12100 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12101 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12102 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12103 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12104 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12105 dumpState.setDump(DumpState.DUMP_MESSAGES); 12106 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12107 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12108 } else if ("version".equals(cmd)) { 12109 dumpState.setDump(DumpState.DUMP_VERSION); 12110 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12111 dumpState.setDump(DumpState.DUMP_KEYSETS); 12112 } else if ("write".equals(cmd)) { 12113 synchronized (mPackages) { 12114 mSettings.writeLPr(); 12115 pw.println("Settings written."); 12116 return; 12117 } 12118 } 12119 } 12120 12121 if (checkin) { 12122 pw.println("vers,1"); 12123 } 12124 12125 // reader 12126 synchronized (mPackages) { 12127 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12128 if (!checkin) { 12129 if (dumpState.onTitlePrinted()) 12130 pw.println(); 12131 pw.println("Database versions:"); 12132 pw.print(" SDK Version:"); 12133 pw.print(" internal="); 12134 pw.print(mSettings.mInternalSdkPlatform); 12135 pw.print(" external="); 12136 pw.println(mSettings.mExternalSdkPlatform); 12137 pw.print(" DB Version:"); 12138 pw.print(" internal="); 12139 pw.print(mSettings.mInternalDatabaseVersion); 12140 pw.print(" external="); 12141 pw.println(mSettings.mExternalDatabaseVersion); 12142 } 12143 } 12144 12145 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12146 if (!checkin) { 12147 if (dumpState.onTitlePrinted()) 12148 pw.println(); 12149 pw.println("Verifiers:"); 12150 pw.print(" Required: "); 12151 pw.print(mRequiredVerifierPackage); 12152 pw.print(" (uid="); 12153 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12154 pw.println(")"); 12155 } else if (mRequiredVerifierPackage != null) { 12156 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12157 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12158 } 12159 } 12160 12161 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12162 boolean printedHeader = false; 12163 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12164 while (it.hasNext()) { 12165 String name = it.next(); 12166 SharedLibraryEntry ent = mSharedLibraries.get(name); 12167 if (!checkin) { 12168 if (!printedHeader) { 12169 if (dumpState.onTitlePrinted()) 12170 pw.println(); 12171 pw.println("Libraries:"); 12172 printedHeader = true; 12173 } 12174 pw.print(" "); 12175 } else { 12176 pw.print("lib,"); 12177 } 12178 pw.print(name); 12179 if (!checkin) { 12180 pw.print(" -> "); 12181 } 12182 if (ent.path != null) { 12183 if (!checkin) { 12184 pw.print("(jar) "); 12185 pw.print(ent.path); 12186 } else { 12187 pw.print(",jar,"); 12188 pw.print(ent.path); 12189 } 12190 } else { 12191 if (!checkin) { 12192 pw.print("(apk) "); 12193 pw.print(ent.apk); 12194 } else { 12195 pw.print(",apk,"); 12196 pw.print(ent.apk); 12197 } 12198 } 12199 pw.println(); 12200 } 12201 } 12202 12203 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12204 if (dumpState.onTitlePrinted()) 12205 pw.println(); 12206 if (!checkin) { 12207 pw.println("Features:"); 12208 } 12209 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12210 while (it.hasNext()) { 12211 String name = it.next(); 12212 if (!checkin) { 12213 pw.print(" "); 12214 } else { 12215 pw.print("feat,"); 12216 } 12217 pw.println(name); 12218 } 12219 } 12220 12221 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12222 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12223 : "Activity Resolver Table:", " ", packageName, 12224 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12225 dumpState.setTitlePrinted(true); 12226 } 12227 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12228 : "Receiver Resolver Table:", " ", packageName, 12229 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12230 dumpState.setTitlePrinted(true); 12231 } 12232 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12233 : "Service Resolver Table:", " ", packageName, 12234 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12235 dumpState.setTitlePrinted(true); 12236 } 12237 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12238 : "Provider Resolver Table:", " ", packageName, 12239 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12240 dumpState.setTitlePrinted(true); 12241 } 12242 } 12243 12244 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12245 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12246 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12247 int user = mSettings.mPreferredActivities.keyAt(i); 12248 if (pir.dump(pw, 12249 dumpState.getTitlePrinted() 12250 ? "\nPreferred Activities User " + user + ":" 12251 : "Preferred Activities User " + user + ":", " ", 12252 packageName, true)) { 12253 dumpState.setTitlePrinted(true); 12254 } 12255 } 12256 } 12257 12258 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12259 pw.flush(); 12260 FileOutputStream fout = new FileOutputStream(fd); 12261 BufferedOutputStream str = new BufferedOutputStream(fout); 12262 XmlSerializer serializer = new FastXmlSerializer(); 12263 try { 12264 serializer.setOutput(str, "utf-8"); 12265 serializer.startDocument(null, true); 12266 serializer.setFeature( 12267 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12268 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12269 serializer.endDocument(); 12270 serializer.flush(); 12271 } catch (IllegalArgumentException e) { 12272 pw.println("Failed writing: " + e); 12273 } catch (IllegalStateException e) { 12274 pw.println("Failed writing: " + e); 12275 } catch (IOException e) { 12276 pw.println("Failed writing: " + e); 12277 } 12278 } 12279 12280 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12281 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12282 } 12283 12284 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12285 boolean printedSomething = false; 12286 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12287 if (packageName != null && !packageName.equals(p.info.packageName)) { 12288 continue; 12289 } 12290 if (!printedSomething) { 12291 if (dumpState.onTitlePrinted()) 12292 pw.println(); 12293 pw.println("Registered ContentProviders:"); 12294 printedSomething = true; 12295 } 12296 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12297 pw.print(" "); pw.println(p.toString()); 12298 } 12299 printedSomething = false; 12300 for (Map.Entry<String, PackageParser.Provider> entry : 12301 mProvidersByAuthority.entrySet()) { 12302 PackageParser.Provider p = entry.getValue(); 12303 if (packageName != null && !packageName.equals(p.info.packageName)) { 12304 continue; 12305 } 12306 if (!printedSomething) { 12307 if (dumpState.onTitlePrinted()) 12308 pw.println(); 12309 pw.println("ContentProvider Authorities:"); 12310 printedSomething = true; 12311 } 12312 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12313 pw.print(" "); pw.println(p.toString()); 12314 if (p.info != null && p.info.applicationInfo != null) { 12315 final String appInfo = p.info.applicationInfo.toString(); 12316 pw.print(" applicationInfo="); pw.println(appInfo); 12317 } 12318 } 12319 } 12320 12321 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12322 mSettings.mKeySetManager.dump(pw, packageName, dumpState); 12323 } 12324 12325 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12326 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12327 } 12328 12329 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12330 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12331 } 12332 12333 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12334 if (dumpState.onTitlePrinted()) 12335 pw.println(); 12336 mSettings.dumpReadMessagesLPr(pw, dumpState); 12337 12338 pw.println(); 12339 pw.println("Package warning messages:"); 12340 final File fname = getSettingsProblemFile(); 12341 FileInputStream in = null; 12342 try { 12343 in = new FileInputStream(fname); 12344 final int avail = in.available(); 12345 final byte[] data = new byte[avail]; 12346 in.read(data); 12347 pw.print(new String(data)); 12348 } catch (FileNotFoundException e) { 12349 } catch (IOException e) { 12350 } finally { 12351 if (in != null) { 12352 try { 12353 in.close(); 12354 } catch (IOException e) { 12355 } 12356 } 12357 } 12358 } 12359 } 12360 } 12361 12362 // ------- apps on sdcard specific code ------- 12363 static final boolean DEBUG_SD_INSTALL = false; 12364 12365 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12366 12367 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12368 12369 private boolean mMediaMounted = false; 12370 12371 private String getEncryptKey() { 12372 try { 12373 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12374 SD_ENCRYPTION_KEYSTORE_NAME); 12375 if (sdEncKey == null) { 12376 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12377 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12378 if (sdEncKey == null) { 12379 Slog.e(TAG, "Failed to create encryption keys"); 12380 return null; 12381 } 12382 } 12383 return sdEncKey; 12384 } catch (NoSuchAlgorithmException nsae) { 12385 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12386 return null; 12387 } catch (IOException ioe) { 12388 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12389 return null; 12390 } 12391 12392 } 12393 12394 /* package */static String getTempContainerId() { 12395 int tmpIdx = 1; 12396 String list[] = PackageHelper.getSecureContainerList(); 12397 if (list != null) { 12398 for (final String name : list) { 12399 // Ignore null and non-temporary container entries 12400 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12401 continue; 12402 } 12403 12404 String subStr = name.substring(mTempContainerPrefix.length()); 12405 try { 12406 int cid = Integer.parseInt(subStr); 12407 if (cid >= tmpIdx) { 12408 tmpIdx = cid + 1; 12409 } 12410 } catch (NumberFormatException e) { 12411 } 12412 } 12413 } 12414 return mTempContainerPrefix + tmpIdx; 12415 } 12416 12417 /* 12418 * Update media status on PackageManager. 12419 */ 12420 @Override 12421 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12422 int callingUid = Binder.getCallingUid(); 12423 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12424 throw new SecurityException("Media status can only be updated by the system"); 12425 } 12426 // reader; this apparently protects mMediaMounted, but should probably 12427 // be a different lock in that case. 12428 synchronized (mPackages) { 12429 Log.i(TAG, "Updating external media status from " 12430 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12431 + (mediaStatus ? "mounted" : "unmounted")); 12432 if (DEBUG_SD_INSTALL) 12433 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12434 + ", mMediaMounted=" + mMediaMounted); 12435 if (mediaStatus == mMediaMounted) { 12436 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12437 : 0, -1); 12438 mHandler.sendMessage(msg); 12439 return; 12440 } 12441 mMediaMounted = mediaStatus; 12442 } 12443 // Queue up an async operation since the package installation may take a 12444 // little while. 12445 mHandler.post(new Runnable() { 12446 public void run() { 12447 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12448 } 12449 }); 12450 } 12451 12452 /** 12453 * Called by MountService when the initial ASECs to scan are available. 12454 * Should block until all the ASEC containers are finished being scanned. 12455 */ 12456 public void scanAvailableAsecs() { 12457 updateExternalMediaStatusInner(true, false, false); 12458 if (mShouldRestoreconData) { 12459 SELinuxMMAC.setRestoreconDone(); 12460 mShouldRestoreconData = false; 12461 } 12462 } 12463 12464 /* 12465 * Collect information of applications on external media, map them against 12466 * existing containers and update information based on current mount status. 12467 * Please note that we always have to report status if reportStatus has been 12468 * set to true especially when unloading packages. 12469 */ 12470 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12471 boolean externalStorage) { 12472 // Collection of uids 12473 int uidArr[] = null; 12474 // Collection of stale containers 12475 HashSet<String> removeCids = new HashSet<String>(); 12476 // Collection of packages on external media with valid containers. 12477 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12478 // Get list of secure containers. 12479 final String list[] = PackageHelper.getSecureContainerList(); 12480 if (list == null || list.length == 0) { 12481 Log.i(TAG, "No secure containers on sdcard"); 12482 } else { 12483 // Process list of secure containers and categorize them 12484 // as active or stale based on their package internal state. 12485 int uidList[] = new int[list.length]; 12486 int num = 0; 12487 // reader 12488 synchronized (mPackages) { 12489 for (String cid : list) { 12490 if (DEBUG_SD_INSTALL) 12491 Log.i(TAG, "Processing container " + cid); 12492 String pkgName = getAsecPackageName(cid); 12493 if (pkgName == null) { 12494 if (DEBUG_SD_INSTALL) 12495 Log.i(TAG, "Container : " + cid + " stale"); 12496 removeCids.add(cid); 12497 continue; 12498 } 12499 if (DEBUG_SD_INSTALL) 12500 Log.i(TAG, "Looking for pkg : " + pkgName); 12501 12502 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12503 if (ps == null) { 12504 Log.i(TAG, "Deleting container with no matching settings " + cid); 12505 removeCids.add(cid); 12506 continue; 12507 } 12508 12509 /* 12510 * Skip packages that are not external if we're unmounting 12511 * external storage. 12512 */ 12513 if (externalStorage && !isMounted && !isExternal(ps)) { 12514 continue; 12515 } 12516 12517 final AsecInstallArgs args = new AsecInstallArgs(cid, 12518 getAppInstructionSetFromSettings(ps), 12519 isForwardLocked(ps)); 12520 // The package status is changed only if the code path 12521 // matches between settings and the container id. 12522 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12523 if (DEBUG_SD_INSTALL) { 12524 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12525 + " at code path: " + ps.codePathString); 12526 } 12527 12528 // We do have a valid package installed on sdcard 12529 processCids.put(args, ps.codePathString); 12530 final int uid = ps.appId; 12531 if (uid != -1) { 12532 uidList[num++] = uid; 12533 } 12534 } else { 12535 Log.i(TAG, "Deleting stale container for " + cid); 12536 removeCids.add(cid); 12537 } 12538 } 12539 } 12540 12541 if (num > 0) { 12542 // Sort uid list 12543 Arrays.sort(uidList, 0, num); 12544 // Throw away duplicates 12545 uidArr = new int[num]; 12546 uidArr[0] = uidList[0]; 12547 int di = 0; 12548 for (int i = 1; i < num; i++) { 12549 if (uidList[i - 1] != uidList[i]) { 12550 uidArr[di++] = uidList[i]; 12551 } 12552 } 12553 } 12554 } 12555 // Process packages with valid entries. 12556 if (isMounted) { 12557 if (DEBUG_SD_INSTALL) 12558 Log.i(TAG, "Loading packages"); 12559 loadMediaPackages(processCids, uidArr, removeCids); 12560 startCleaningPackages(); 12561 } else { 12562 if (DEBUG_SD_INSTALL) 12563 Log.i(TAG, "Unloading packages"); 12564 unloadMediaPackages(processCids, uidArr, reportStatus); 12565 } 12566 } 12567 12568 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12569 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12570 int size = pkgList.size(); 12571 if (size > 0) { 12572 // Send broadcasts here 12573 Bundle extras = new Bundle(); 12574 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12575 .toArray(new String[size])); 12576 if (uidArr != null) { 12577 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12578 } 12579 if (replacing) { 12580 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12581 } 12582 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12583 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12584 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12585 } 12586 } 12587 12588 /* 12589 * Look at potentially valid container ids from processCids If package 12590 * information doesn't match the one on record or package scanning fails, 12591 * the cid is added to list of removeCids. We currently don't delete stale 12592 * containers. 12593 */ 12594 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12595 HashSet<String> removeCids) { 12596 ArrayList<String> pkgList = new ArrayList<String>(); 12597 Set<AsecInstallArgs> keys = processCids.keySet(); 12598 boolean doGc = false; 12599 for (AsecInstallArgs args : keys) { 12600 String codePath = processCids.get(args); 12601 if (DEBUG_SD_INSTALL) 12602 Log.i(TAG, "Loading container : " + args.cid); 12603 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12604 try { 12605 // Make sure there are no container errors first. 12606 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12607 Slog.e(TAG, "Failed to mount cid : " + args.cid 12608 + " when installing from sdcard"); 12609 continue; 12610 } 12611 // Check code path here. 12612 if (codePath == null || !codePath.equals(args.getCodePath())) { 12613 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12614 + " does not match one in settings " + codePath); 12615 continue; 12616 } 12617 // Parse package 12618 int parseFlags = mDefParseFlags; 12619 if (args.isExternal()) { 12620 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12621 } 12622 if (args.isFwdLocked()) { 12623 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12624 } 12625 12626 doGc = true; 12627 synchronized (mInstallLock) { 12628 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 12629 0, 0, null, null); 12630 // Scan the package 12631 if (pkg != null) { 12632 /* 12633 * TODO why is the lock being held? doPostInstall is 12634 * called in other places without the lock. This needs 12635 * to be straightened out. 12636 */ 12637 // writer 12638 synchronized (mPackages) { 12639 retCode = PackageManager.INSTALL_SUCCEEDED; 12640 pkgList.add(pkg.packageName); 12641 // Post process args 12642 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12643 pkg.applicationInfo.uid); 12644 } 12645 } else { 12646 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12647 } 12648 } 12649 12650 } finally { 12651 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12652 // Don't destroy container here. Wait till gc clears things 12653 // up. 12654 removeCids.add(args.cid); 12655 } 12656 } 12657 } 12658 // writer 12659 synchronized (mPackages) { 12660 // If the platform SDK has changed since the last time we booted, 12661 // we need to re-grant app permission to catch any new ones that 12662 // appear. This is really a hack, and means that apps can in some 12663 // cases get permissions that the user didn't initially explicitly 12664 // allow... it would be nice to have some better way to handle 12665 // this situation. 12666 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12667 if (regrantPermissions) 12668 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12669 + mSdkVersion + "; regranting permissions for external storage"); 12670 mSettings.mExternalSdkPlatform = mSdkVersion; 12671 12672 // Make sure group IDs have been assigned, and any permission 12673 // changes in other apps are accounted for 12674 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12675 | (regrantPermissions 12676 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12677 : 0)); 12678 12679 mSettings.updateExternalDatabaseVersion(); 12680 12681 // can downgrade to reader 12682 // Persist settings 12683 mSettings.writeLPr(); 12684 } 12685 // Send a broadcast to let everyone know we are done processing 12686 if (pkgList.size() > 0) { 12687 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12688 } 12689 // Force gc to avoid any stale parser references that we might have. 12690 if (doGc) { 12691 Runtime.getRuntime().gc(); 12692 } 12693 // List stale containers and destroy stale temporary containers. 12694 if (removeCids != null) { 12695 for (String cid : removeCids) { 12696 if (cid.startsWith(mTempContainerPrefix)) { 12697 Log.i(TAG, "Destroying stale temporary container " + cid); 12698 PackageHelper.destroySdDir(cid); 12699 } else { 12700 Log.w(TAG, "Container " + cid + " is stale"); 12701 } 12702 } 12703 } 12704 } 12705 12706 /* 12707 * Utility method to unload a list of specified containers 12708 */ 12709 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12710 // Just unmount all valid containers. 12711 for (AsecInstallArgs arg : cidArgs) { 12712 synchronized (mInstallLock) { 12713 arg.doPostDeleteLI(false); 12714 } 12715 } 12716 } 12717 12718 /* 12719 * Unload packages mounted on external media. This involves deleting package 12720 * data from internal structures, sending broadcasts about diabled packages, 12721 * gc'ing to free up references, unmounting all secure containers 12722 * corresponding to packages on external media, and posting a 12723 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12724 * that we always have to post this message if status has been requested no 12725 * matter what. 12726 */ 12727 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12728 final boolean reportStatus) { 12729 if (DEBUG_SD_INSTALL) 12730 Log.i(TAG, "unloading media packages"); 12731 ArrayList<String> pkgList = new ArrayList<String>(); 12732 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12733 final Set<AsecInstallArgs> keys = processCids.keySet(); 12734 for (AsecInstallArgs args : keys) { 12735 String pkgName = args.getPackageName(); 12736 if (DEBUG_SD_INSTALL) 12737 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12738 // Delete package internally 12739 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12740 synchronized (mInstallLock) { 12741 boolean res = deletePackageLI(pkgName, null, false, null, null, 12742 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12743 if (res) { 12744 pkgList.add(pkgName); 12745 } else { 12746 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12747 failedList.add(args); 12748 } 12749 } 12750 } 12751 12752 // reader 12753 synchronized (mPackages) { 12754 // We didn't update the settings after removing each package; 12755 // write them now for all packages. 12756 mSettings.writeLPr(); 12757 } 12758 12759 // We have to absolutely send UPDATED_MEDIA_STATUS only 12760 // after confirming that all the receivers processed the ordered 12761 // broadcast when packages get disabled, force a gc to clean things up. 12762 // and unload all the containers. 12763 if (pkgList.size() > 0) { 12764 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12765 new IIntentReceiver.Stub() { 12766 public void performReceive(Intent intent, int resultCode, String data, 12767 Bundle extras, boolean ordered, boolean sticky, 12768 int sendingUser) throws RemoteException { 12769 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12770 reportStatus ? 1 : 0, 1, keys); 12771 mHandler.sendMessage(msg); 12772 } 12773 }); 12774 } else { 12775 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12776 keys); 12777 mHandler.sendMessage(msg); 12778 } 12779 } 12780 12781 /** Binder call */ 12782 @Override 12783 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12784 final int flags) { 12785 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12786 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12787 int returnCode = PackageManager.MOVE_SUCCEEDED; 12788 int currFlags = 0; 12789 int newFlags = 0; 12790 // reader 12791 synchronized (mPackages) { 12792 PackageParser.Package pkg = mPackages.get(packageName); 12793 if (pkg == null) { 12794 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12795 } else { 12796 // Disable moving fwd locked apps and system packages 12797 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12798 Slog.w(TAG, "Cannot move system application"); 12799 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12800 } else if (pkg.mOperationPending) { 12801 Slog.w(TAG, "Attempt to move package which has pending operations"); 12802 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12803 } else { 12804 // Find install location first 12805 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12806 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12807 Slog.w(TAG, "Ambigous flags specified for move location."); 12808 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12809 } else { 12810 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12811 : PackageManager.INSTALL_INTERNAL; 12812 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12813 : PackageManager.INSTALL_INTERNAL; 12814 12815 if (newFlags == currFlags) { 12816 Slog.w(TAG, "No move required. Trying to move to same location"); 12817 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12818 } else { 12819 if (isForwardLocked(pkg)) { 12820 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12821 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12822 } 12823 } 12824 } 12825 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12826 pkg.mOperationPending = true; 12827 } 12828 } 12829 } 12830 12831 /* 12832 * TODO this next block probably shouldn't be inside the lock. We 12833 * can't guarantee these won't change after this is fired off 12834 * anyway. 12835 */ 12836 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12837 processPendingMove(new MoveParams(null, observer, 0, packageName, null, 12838 null, -1, user), 12839 returnCode); 12840 } else { 12841 Message msg = mHandler.obtainMessage(INIT_COPY); 12842 final String instructionSet = getAppInstructionSet(pkg.applicationInfo); 12843 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir, 12844 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir, 12845 instructionSet); 12846 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12847 pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user); 12848 msg.obj = mp; 12849 mHandler.sendMessage(msg); 12850 } 12851 } 12852 } 12853 12854 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12855 // Queue up an async operation since the package deletion may take a 12856 // little while. 12857 mHandler.post(new Runnable() { 12858 public void run() { 12859 // TODO fix this; this does nothing. 12860 mHandler.removeCallbacks(this); 12861 int returnCode = currentStatus; 12862 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12863 int uidArr[] = null; 12864 ArrayList<String> pkgList = null; 12865 synchronized (mPackages) { 12866 PackageParser.Package pkg = mPackages.get(mp.packageName); 12867 if (pkg == null) { 12868 Slog.w(TAG, " Package " + mp.packageName 12869 + " doesn't exist. Aborting move"); 12870 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12871 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 12872 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12873 + mp.srcArgs.getCodePath() + " to " 12874 + pkg.applicationInfo.sourceDir 12875 + " Aborting move and returning error"); 12876 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12877 } else { 12878 uidArr = new int[] { 12879 pkg.applicationInfo.uid 12880 }; 12881 pkgList = new ArrayList<String>(); 12882 pkgList.add(mp.packageName); 12883 } 12884 } 12885 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12886 // Send resources unavailable broadcast 12887 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12888 // Update package code and resource paths 12889 synchronized (mInstallLock) { 12890 synchronized (mPackages) { 12891 PackageParser.Package pkg = mPackages.get(mp.packageName); 12892 // Recheck for package again. 12893 if (pkg == null) { 12894 Slog.w(TAG, " Package " + mp.packageName 12895 + " doesn't exist. Aborting move"); 12896 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12897 } else if (!mp.srcArgs.getCodePath().equals( 12898 pkg.applicationInfo.sourceDir)) { 12899 Slog.w(TAG, "Package " + mp.packageName 12900 + " code path changed from " + mp.srcArgs.getCodePath() 12901 + " to " + pkg.applicationInfo.sourceDir 12902 + " Aborting move and returning error"); 12903 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12904 } else { 12905 final String oldCodePath = pkg.codePath; 12906 final String newCodePath = mp.targetArgs.getCodePath(); 12907 final String newResPath = mp.targetArgs.getResourcePath(); 12908 final String newNativePath = mp.targetArgs 12909 .getNativeLibraryPath(); 12910 12911 final File newNativeDir = new File(newNativePath); 12912 12913 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12914 // NOTE: We do not report any errors from the APK scan and library 12915 // copy at this point. 12916 NativeLibraryHelper.ApkHandle handle = 12917 new NativeLibraryHelper.ApkHandle(newCodePath); 12918 final int abi = NativeLibraryHelper.findSupportedAbi( 12919 handle, Build.SUPPORTED_ABIS); 12920 if (abi >= 0) { 12921 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12922 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12923 } 12924 handle.close(); 12925 } 12926 final int[] users = sUserManager.getUserIds(); 12927 for (int user : users) { 12928 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 12929 newNativePath, user) < 0) { 12930 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12931 } 12932 } 12933 12934 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12935 pkg.codePath = newCodePath; 12936 // Move dex files around 12937 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 12938 // Moving of dex files failed. Set 12939 // error code and abort move. 12940 pkg.codePath = oldCodePath; 12941 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12942 } 12943 } 12944 12945 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12946 pkg.applicationInfo.sourceDir = newCodePath; 12947 pkg.applicationInfo.publicSourceDir = newResPath; 12948 pkg.applicationInfo.nativeLibraryDir = newNativePath; 12949 PackageSetting ps = (PackageSetting) pkg.mExtras; 12950 ps.codePath = new File(pkg.applicationInfo.sourceDir); 12951 ps.codePathString = ps.codePath.getPath(); 12952 ps.resourcePath = new File( 12953 pkg.applicationInfo.publicSourceDir); 12954 ps.resourcePathString = ps.resourcePath.getPath(); 12955 ps.nativeLibraryPathString = newNativePath; 12956 // Set the application info flag 12957 // correctly. 12958 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 12959 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12960 } else { 12961 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12962 } 12963 ps.setFlags(pkg.applicationInfo.flags); 12964 mAppDirs.remove(oldCodePath); 12965 mAppDirs.put(newCodePath, pkg); 12966 // Persist settings 12967 mSettings.writeLPr(); 12968 } 12969 } 12970 } 12971 } 12972 // Send resources available broadcast 12973 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12974 } 12975 } 12976 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12977 // Clean up failed installation 12978 if (mp.targetArgs != null) { 12979 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 12980 -1); 12981 } 12982 } else { 12983 // Force a gc to clear things up. 12984 Runtime.getRuntime().gc(); 12985 // Delete older code 12986 synchronized (mInstallLock) { 12987 mp.srcArgs.doPostDeleteLI(true); 12988 } 12989 } 12990 12991 // Allow more operations on this file if we didn't fail because 12992 // an operation was already pending for this package. 12993 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 12994 synchronized (mPackages) { 12995 PackageParser.Package pkg = mPackages.get(mp.packageName); 12996 if (pkg != null) { 12997 pkg.mOperationPending = false; 12998 } 12999 } 13000 } 13001 13002 IPackageMoveObserver observer = mp.observer; 13003 if (observer != null) { 13004 try { 13005 observer.packageMoved(mp.packageName, returnCode); 13006 } catch (RemoteException e) { 13007 Log.i(TAG, "Observer no longer exists."); 13008 } 13009 } 13010 } 13011 }); 13012 } 13013 13014 @Override 13015 public boolean setInstallLocation(int loc) { 13016 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13017 null); 13018 if (getInstallLocation() == loc) { 13019 return true; 13020 } 13021 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13022 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13023 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13024 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13025 return true; 13026 } 13027 return false; 13028 } 13029 13030 @Override 13031 public int getInstallLocation() { 13032 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13033 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13034 PackageHelper.APP_INSTALL_AUTO); 13035 } 13036 13037 /** Called by UserManagerService */ 13038 void cleanUpUserLILPw(int userHandle) { 13039 mDirtyUsers.remove(userHandle); 13040 mSettings.removeUserLPr(userHandle); 13041 mPendingBroadcasts.remove(userHandle); 13042 if (mInstaller != null) { 13043 // Technically, we shouldn't be doing this with the package lock 13044 // held. However, this is very rare, and there is already so much 13045 // other disk I/O going on, that we'll let it slide for now. 13046 mInstaller.removeUserDataDirs(userHandle); 13047 } 13048 } 13049 13050 /** Called by UserManagerService */ 13051 void createNewUserLILPw(int userHandle, File path) { 13052 if (mInstaller != null) { 13053 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13054 } 13055 } 13056 13057 @Override 13058 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13059 mContext.enforceCallingOrSelfPermission( 13060 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13061 "Only package verification agents can read the verifier device identity"); 13062 13063 synchronized (mPackages) { 13064 return mSettings.getVerifierDeviceIdentityLPw(); 13065 } 13066 } 13067 13068 @Override 13069 public void setPermissionEnforced(String permission, boolean enforced) { 13070 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13071 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13072 synchronized (mPackages) { 13073 if (mSettings.mReadExternalStorageEnforced == null 13074 || mSettings.mReadExternalStorageEnforced != enforced) { 13075 mSettings.mReadExternalStorageEnforced = enforced; 13076 mSettings.writeLPr(); 13077 } 13078 } 13079 // kill any non-foreground processes so we restart them and 13080 // grant/revoke the GID. 13081 final IActivityManager am = ActivityManagerNative.getDefault(); 13082 if (am != null) { 13083 final long token = Binder.clearCallingIdentity(); 13084 try { 13085 am.killProcessesBelowForeground("setPermissionEnforcement"); 13086 } catch (RemoteException e) { 13087 } finally { 13088 Binder.restoreCallingIdentity(token); 13089 } 13090 } 13091 } else { 13092 throw new IllegalArgumentException("No selective enforcement for " + permission); 13093 } 13094 } 13095 13096 @Override 13097 @Deprecated 13098 public boolean isPermissionEnforced(String permission) { 13099 return true; 13100 } 13101 13102 @Override 13103 public boolean isStorageLow() { 13104 final long token = Binder.clearCallingIdentity(); 13105 try { 13106 final DeviceStorageMonitorInternal 13107 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13108 if (dsm != null) { 13109 return dsm.isMemoryLow(); 13110 } else { 13111 return false; 13112 } 13113 } finally { 13114 Binder.restoreCallingIdentity(token); 13115 } 13116 } 13117 13118 @Override 13119 public IPackageInstaller getPackageInstaller() { 13120 return mInstallerService; 13121 } 13122} 13123