PackageManagerService.java revision be7c50e0a14e91330ce13161bc14a33d34ff6aca
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 android.util.ArrayMap; 40import com.android.internal.R; 41import com.android.internal.app.IMediaContainerService; 42import com.android.internal.app.ResolverActivity; 43import com.android.internal.content.NativeLibraryHelper; 44import com.android.internal.content.NativeLibraryHelper.ApkHandle; 45import com.android.internal.content.PackageHelper; 46import com.android.internal.util.ArrayUtils; 47import com.android.internal.util.FastPrintWriter; 48import com.android.internal.util.FastXmlSerializer; 49import com.android.internal.util.XmlUtils; 50import com.android.server.EventLogTags; 51import com.android.server.IntentResolver; 52import com.android.server.LocalServices; 53import com.android.server.ServiceThread; 54import com.android.server.SystemConfig; 55import com.android.server.Watchdog; 56import com.android.server.pm.Settings.DatabaseVersion; 57import com.android.server.storage.DeviceStorageMonitorInternal; 58 59import org.xmlpull.v1.XmlPullParser; 60import org.xmlpull.v1.XmlPullParserException; 61import org.xmlpull.v1.XmlSerializer; 62 63import android.app.ActivityManager; 64import android.app.ActivityManagerNative; 65import android.app.IActivityManager; 66import android.app.PackageInstallObserver; 67import android.app.admin.IDevicePolicyManager; 68import android.app.backup.IBackupManager; 69import android.content.BroadcastReceiver; 70import android.content.ComponentName; 71import android.content.Context; 72import android.content.IIntentReceiver; 73import android.content.Intent; 74import android.content.IntentFilter; 75import android.content.IntentSender; 76import android.content.IntentSender.SendIntentException; 77import android.content.ServiceConnection; 78import android.content.pm.ActivityInfo; 79import android.content.pm.ApplicationInfo; 80import android.content.pm.ContainerEncryptionParams; 81import android.content.pm.FeatureInfo; 82import android.content.pm.IPackageDataObserver; 83import android.content.pm.IPackageDeleteObserver; 84import android.content.pm.IPackageInstallObserver; 85import android.content.pm.IPackageInstallObserver2; 86import android.content.pm.IPackageInstaller; 87import android.content.pm.IPackageManager; 88import android.content.pm.IPackageMoveObserver; 89import android.content.pm.IPackageStatsObserver; 90import android.content.pm.InstrumentationInfo; 91import android.content.pm.ManifestDigest; 92import android.content.pm.PackageCleanItem; 93import android.content.pm.PackageInfo; 94import android.content.pm.PackageInfoLite; 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 // System configuration read by SystemConfig. 397 final int[] mGlobalGids; 398 final SparseArray<HashSet<String>> mSystemPermissions; 399 final HashMap<String, FeatureInfo> mAvailableFeatures; 400 401 // If mac_permissions.xml was found for seinfo labeling. 402 boolean mFoundPolicyFile; 403 404 // If a recursive restorecon of /data/data/<pkg> is needed. 405 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 406 407 public static final class SharedLibraryEntry { 408 public final String path; 409 public final String apk; 410 411 SharedLibraryEntry(String _path, String _apk) { 412 path = _path; 413 apk = _apk; 414 } 415 } 416 417 // Currently known shared libraries. 418 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 419 new HashMap<String, SharedLibraryEntry>(); 420 421 // All available activities, for your resolving pleasure. 422 final ActivityIntentResolver mActivities = 423 new ActivityIntentResolver(); 424 425 // All available receivers, for your resolving pleasure. 426 final ActivityIntentResolver mReceivers = 427 new ActivityIntentResolver(); 428 429 // All available services, for your resolving pleasure. 430 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 431 432 // All available providers, for your resolving pleasure. 433 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 434 435 // Mapping from provider base names (first directory in content URI codePath) 436 // to the provider information. 437 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 438 new HashMap<String, PackageParser.Provider>(); 439 440 // Mapping from instrumentation class names to info about them. 441 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 442 new HashMap<ComponentName, PackageParser.Instrumentation>(); 443 444 // Mapping from permission names to info about them. 445 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 446 new HashMap<String, PackageParser.PermissionGroup>(); 447 448 // Packages whose data we have transfered into another package, thus 449 // should no longer exist. 450 final HashSet<String> mTransferedPackages = new HashSet<String>(); 451 452 // Broadcast actions that are only available to the system. 453 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 454 455 /** List of packages waiting for verification. */ 456 final SparseArray<PackageVerificationState> mPendingVerification 457 = new SparseArray<PackageVerificationState>(); 458 459 final PackageInstallerService mInstallerService; 460 461 HashSet<PackageParser.Package> mDeferredDexOpt = null; 462 463 /** Token for keys in mPendingVerification. */ 464 private int mPendingVerificationToken = 0; 465 466 boolean mSystemReady; 467 boolean mSafeMode; 468 boolean mHasSystemUidErrors; 469 470 ApplicationInfo mAndroidApplication; 471 final ActivityInfo mResolveActivity = new ActivityInfo(); 472 final ResolveInfo mResolveInfo = new ResolveInfo(); 473 ComponentName mResolveComponentName; 474 PackageParser.Package mPlatformPackage; 475 ComponentName mCustomResolverComponentName; 476 477 boolean mResolverReplaced = false; 478 479 // Set of pending broadcasts for aggregating enable/disable of components. 480 static class PendingPackageBroadcasts { 481 // for each user id, a map of <package name -> components within that package> 482 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 483 484 public PendingPackageBroadcasts() { 485 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 486 } 487 488 public ArrayList<String> get(int userId, String packageName) { 489 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 490 return packages.get(packageName); 491 } 492 493 public void put(int userId, String packageName, ArrayList<String> components) { 494 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 495 packages.put(packageName, components); 496 } 497 498 public void remove(int userId, String packageName) { 499 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 500 if (packages != null) { 501 packages.remove(packageName); 502 } 503 } 504 505 public void remove(int userId) { 506 mUidMap.remove(userId); 507 } 508 509 public int userIdCount() { 510 return mUidMap.size(); 511 } 512 513 public int userIdAt(int n) { 514 return mUidMap.keyAt(n); 515 } 516 517 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 518 return mUidMap.get(userId); 519 } 520 521 public int size() { 522 // total number of pending broadcast entries across all userIds 523 int num = 0; 524 for (int i = 0; i< mUidMap.size(); i++) { 525 num += mUidMap.valueAt(i).size(); 526 } 527 return num; 528 } 529 530 public void clear() { 531 mUidMap.clear(); 532 } 533 534 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 535 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 536 if (map == null) { 537 map = new HashMap<String, ArrayList<String>>(); 538 mUidMap.put(userId, map); 539 } 540 return map; 541 } 542 } 543 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 544 545 // Service Connection to remote media container service to copy 546 // package uri's from external media onto secure containers 547 // or internal storage. 548 private IMediaContainerService mContainerService = null; 549 550 static final int SEND_PENDING_BROADCAST = 1; 551 static final int MCS_BOUND = 3; 552 static final int END_COPY = 4; 553 static final int INIT_COPY = 5; 554 static final int MCS_UNBIND = 6; 555 static final int START_CLEANING_PACKAGE = 7; 556 static final int FIND_INSTALL_LOC = 8; 557 static final int POST_INSTALL = 9; 558 static final int MCS_RECONNECT = 10; 559 static final int MCS_GIVE_UP = 11; 560 static final int UPDATED_MEDIA_STATUS = 12; 561 static final int WRITE_SETTINGS = 13; 562 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 563 static final int PACKAGE_VERIFIED = 15; 564 static final int CHECK_PENDING_VERIFICATION = 16; 565 566 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 567 568 // Delay time in millisecs 569 static final int BROADCAST_DELAY = 10 * 1000; 570 571 static UserManagerService sUserManager; 572 573 // Stores a list of users whose package restrictions file needs to be updated 574 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 575 576 final private DefaultContainerConnection mDefContainerConn = 577 new DefaultContainerConnection(); 578 class DefaultContainerConnection implements ServiceConnection { 579 public void onServiceConnected(ComponentName name, IBinder service) { 580 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 581 IMediaContainerService imcs = 582 IMediaContainerService.Stub.asInterface(service); 583 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 584 } 585 586 public void onServiceDisconnected(ComponentName name) { 587 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 588 } 589 }; 590 591 // Recordkeeping of restore-after-install operations that are currently in flight 592 // between the Package Manager and the Backup Manager 593 class PostInstallData { 594 public InstallArgs args; 595 public PackageInstalledInfo res; 596 597 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 598 args = _a; 599 res = _r; 600 } 601 }; 602 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 603 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 604 605 private final String mRequiredVerifierPackage; 606 607 private final PackageUsage mPackageUsage = new PackageUsage(); 608 609 private class PackageUsage { 610 private static final int WRITE_INTERVAL 611 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 612 613 private final Object mFileLock = new Object(); 614 private final AtomicLong mLastWritten = new AtomicLong(0); 615 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 616 617 private boolean mIsHistoricalPackageUsageAvailable = true; 618 619 boolean isHistoricalPackageUsageAvailable() { 620 return mIsHistoricalPackageUsageAvailable; 621 } 622 623 void write(boolean force) { 624 if (force) { 625 writeInternal(); 626 return; 627 } 628 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 629 && !DEBUG_DEXOPT) { 630 return; 631 } 632 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 633 new Thread("PackageUsage_DiskWriter") { 634 @Override 635 public void run() { 636 try { 637 writeInternal(); 638 } finally { 639 mBackgroundWriteRunning.set(false); 640 } 641 } 642 }.start(); 643 } 644 } 645 646 private void writeInternal() { 647 synchronized (mPackages) { 648 synchronized (mFileLock) { 649 AtomicFile file = getFile(); 650 FileOutputStream f = null; 651 try { 652 f = file.startWrite(); 653 BufferedOutputStream out = new BufferedOutputStream(f); 654 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 655 StringBuilder sb = new StringBuilder(); 656 for (PackageParser.Package pkg : mPackages.values()) { 657 if (pkg.mLastPackageUsageTimeInMills == 0) { 658 continue; 659 } 660 sb.setLength(0); 661 sb.append(pkg.packageName); 662 sb.append(' '); 663 sb.append((long)pkg.mLastPackageUsageTimeInMills); 664 sb.append('\n'); 665 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 666 } 667 out.flush(); 668 file.finishWrite(f); 669 } catch (IOException e) { 670 if (f != null) { 671 file.failWrite(f); 672 } 673 Log.e(TAG, "Failed to write package usage times", e); 674 } 675 } 676 } 677 mLastWritten.set(SystemClock.elapsedRealtime()); 678 } 679 680 void readLP() { 681 synchronized (mFileLock) { 682 AtomicFile file = getFile(); 683 BufferedInputStream in = null; 684 try { 685 in = new BufferedInputStream(file.openRead()); 686 StringBuffer sb = new StringBuffer(); 687 while (true) { 688 String packageName = readToken(in, sb, ' '); 689 if (packageName == null) { 690 break; 691 } 692 String timeInMillisString = readToken(in, sb, '\n'); 693 if (timeInMillisString == null) { 694 throw new IOException("Failed to find last usage time for package " 695 + packageName); 696 } 697 PackageParser.Package pkg = mPackages.get(packageName); 698 if (pkg == null) { 699 continue; 700 } 701 long timeInMillis; 702 try { 703 timeInMillis = Long.parseLong(timeInMillisString.toString()); 704 } catch (NumberFormatException e) { 705 throw new IOException("Failed to parse " + timeInMillisString 706 + " as a long.", e); 707 } 708 pkg.mLastPackageUsageTimeInMills = timeInMillis; 709 } 710 } catch (FileNotFoundException expected) { 711 mIsHistoricalPackageUsageAvailable = false; 712 } catch (IOException e) { 713 Log.w(TAG, "Failed to read package usage times", e); 714 } finally { 715 IoUtils.closeQuietly(in); 716 } 717 } 718 mLastWritten.set(SystemClock.elapsedRealtime()); 719 } 720 721 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 722 throws IOException { 723 sb.setLength(0); 724 while (true) { 725 int ch = in.read(); 726 if (ch == -1) { 727 if (sb.length() == 0) { 728 return null; 729 } 730 throw new IOException("Unexpected EOF"); 731 } 732 if (ch == endOfToken) { 733 return sb.toString(); 734 } 735 sb.append((char)ch); 736 } 737 } 738 739 private AtomicFile getFile() { 740 File dataDir = Environment.getDataDirectory(); 741 File systemDir = new File(dataDir, "system"); 742 File fname = new File(systemDir, "package-usage.list"); 743 return new AtomicFile(fname); 744 } 745 } 746 747 class PackageHandler extends Handler { 748 private boolean mBound = false; 749 final ArrayList<HandlerParams> mPendingInstalls = 750 new ArrayList<HandlerParams>(); 751 752 private boolean connectToService() { 753 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 754 " DefaultContainerService"); 755 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 756 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 757 if (mContext.bindServiceAsUser(service, mDefContainerConn, 758 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 759 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 760 mBound = true; 761 return true; 762 } 763 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 764 return false; 765 } 766 767 private void disconnectService() { 768 mContainerService = null; 769 mBound = false; 770 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 771 mContext.unbindService(mDefContainerConn); 772 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 773 } 774 775 PackageHandler(Looper looper) { 776 super(looper); 777 } 778 779 public void handleMessage(Message msg) { 780 try { 781 doHandleMessage(msg); 782 } finally { 783 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 784 } 785 } 786 787 void doHandleMessage(Message msg) { 788 switch (msg.what) { 789 case INIT_COPY: { 790 HandlerParams params = (HandlerParams) msg.obj; 791 int idx = mPendingInstalls.size(); 792 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 793 // If a bind was already initiated we dont really 794 // need to do anything. The pending install 795 // will be processed later on. 796 if (!mBound) { 797 // If this is the only one pending we might 798 // have to bind to the service again. 799 if (!connectToService()) { 800 Slog.e(TAG, "Failed to bind to media container service"); 801 params.serviceError(); 802 return; 803 } else { 804 // Once we bind to the service, the first 805 // pending request will be processed. 806 mPendingInstalls.add(idx, params); 807 } 808 } else { 809 mPendingInstalls.add(idx, params); 810 // Already bound to the service. Just make 811 // sure we trigger off processing the first request. 812 if (idx == 0) { 813 mHandler.sendEmptyMessage(MCS_BOUND); 814 } 815 } 816 break; 817 } 818 case MCS_BOUND: { 819 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 820 if (msg.obj != null) { 821 mContainerService = (IMediaContainerService) msg.obj; 822 } 823 if (mContainerService == null) { 824 // Something seriously wrong. Bail out 825 Slog.e(TAG, "Cannot bind to media container service"); 826 for (HandlerParams params : mPendingInstalls) { 827 // Indicate service bind error 828 params.serviceError(); 829 } 830 mPendingInstalls.clear(); 831 } else if (mPendingInstalls.size() > 0) { 832 HandlerParams params = mPendingInstalls.get(0); 833 if (params != null) { 834 if (params.startCopy()) { 835 // We are done... look for more work or to 836 // go idle. 837 if (DEBUG_SD_INSTALL) Log.i(TAG, 838 "Checking for more work or unbind..."); 839 // Delete pending install 840 if (mPendingInstalls.size() > 0) { 841 mPendingInstalls.remove(0); 842 } 843 if (mPendingInstalls.size() == 0) { 844 if (mBound) { 845 if (DEBUG_SD_INSTALL) Log.i(TAG, 846 "Posting delayed MCS_UNBIND"); 847 removeMessages(MCS_UNBIND); 848 Message ubmsg = obtainMessage(MCS_UNBIND); 849 // Unbind after a little delay, to avoid 850 // continual thrashing. 851 sendMessageDelayed(ubmsg, 10000); 852 } 853 } else { 854 // There are more pending requests in queue. 855 // Just post MCS_BOUND message to trigger processing 856 // of next pending install. 857 if (DEBUG_SD_INSTALL) Log.i(TAG, 858 "Posting MCS_BOUND for next work"); 859 mHandler.sendEmptyMessage(MCS_BOUND); 860 } 861 } 862 } 863 } else { 864 // Should never happen ideally. 865 Slog.w(TAG, "Empty queue"); 866 } 867 break; 868 } 869 case MCS_RECONNECT: { 870 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 871 if (mPendingInstalls.size() > 0) { 872 if (mBound) { 873 disconnectService(); 874 } 875 if (!connectToService()) { 876 Slog.e(TAG, "Failed to bind to media container service"); 877 for (HandlerParams params : mPendingInstalls) { 878 // Indicate service bind error 879 params.serviceError(); 880 } 881 mPendingInstalls.clear(); 882 } 883 } 884 break; 885 } 886 case MCS_UNBIND: { 887 // If there is no actual work left, then time to unbind. 888 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 889 890 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 891 if (mBound) { 892 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 893 894 disconnectService(); 895 } 896 } else if (mPendingInstalls.size() > 0) { 897 // There are more pending requests in queue. 898 // Just post MCS_BOUND message to trigger processing 899 // of next pending install. 900 mHandler.sendEmptyMessage(MCS_BOUND); 901 } 902 903 break; 904 } 905 case MCS_GIVE_UP: { 906 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 907 mPendingInstalls.remove(0); 908 break; 909 } 910 case SEND_PENDING_BROADCAST: { 911 String packages[]; 912 ArrayList<String> components[]; 913 int size = 0; 914 int uids[]; 915 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 916 synchronized (mPackages) { 917 if (mPendingBroadcasts == null) { 918 return; 919 } 920 size = mPendingBroadcasts.size(); 921 if (size <= 0) { 922 // Nothing to be done. Just return 923 return; 924 } 925 packages = new String[size]; 926 components = new ArrayList[size]; 927 uids = new int[size]; 928 int i = 0; // filling out the above arrays 929 930 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 931 int packageUserId = mPendingBroadcasts.userIdAt(n); 932 Iterator<Map.Entry<String, ArrayList<String>>> it 933 = mPendingBroadcasts.packagesForUserId(packageUserId) 934 .entrySet().iterator(); 935 while (it.hasNext() && i < size) { 936 Map.Entry<String, ArrayList<String>> ent = it.next(); 937 packages[i] = ent.getKey(); 938 components[i] = ent.getValue(); 939 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 940 uids[i] = (ps != null) 941 ? UserHandle.getUid(packageUserId, ps.appId) 942 : -1; 943 i++; 944 } 945 } 946 size = i; 947 mPendingBroadcasts.clear(); 948 } 949 // Send broadcasts 950 for (int i = 0; i < size; i++) { 951 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 952 } 953 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 954 break; 955 } 956 case START_CLEANING_PACKAGE: { 957 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 958 final String packageName = (String)msg.obj; 959 final int userId = msg.arg1; 960 final boolean andCode = msg.arg2 != 0; 961 synchronized (mPackages) { 962 if (userId == UserHandle.USER_ALL) { 963 int[] users = sUserManager.getUserIds(); 964 for (int user : users) { 965 mSettings.addPackageToCleanLPw( 966 new PackageCleanItem(user, packageName, andCode)); 967 } 968 } else { 969 mSettings.addPackageToCleanLPw( 970 new PackageCleanItem(userId, packageName, andCode)); 971 } 972 } 973 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 974 startCleaningPackages(); 975 } break; 976 case POST_INSTALL: { 977 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 978 PostInstallData data = mRunningInstalls.get(msg.arg1); 979 mRunningInstalls.delete(msg.arg1); 980 boolean deleteOld = false; 981 982 if (data != null) { 983 InstallArgs args = data.args; 984 PackageInstalledInfo res = data.res; 985 986 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 987 res.removedInfo.sendBroadcast(false, true, false); 988 Bundle extras = new Bundle(1); 989 extras.putInt(Intent.EXTRA_UID, res.uid); 990 // Determine the set of users who are adding this 991 // package for the first time vs. those who are seeing 992 // an update. 993 int[] firstUsers; 994 int[] updateUsers = new int[0]; 995 if (res.origUsers == null || res.origUsers.length == 0) { 996 firstUsers = res.newUsers; 997 } else { 998 firstUsers = new int[0]; 999 for (int i=0; i<res.newUsers.length; i++) { 1000 int user = res.newUsers[i]; 1001 boolean isNew = true; 1002 for (int j=0; j<res.origUsers.length; j++) { 1003 if (res.origUsers[j] == user) { 1004 isNew = false; 1005 break; 1006 } 1007 } 1008 if (isNew) { 1009 int[] newFirst = new int[firstUsers.length+1]; 1010 System.arraycopy(firstUsers, 0, newFirst, 0, 1011 firstUsers.length); 1012 newFirst[firstUsers.length] = user; 1013 firstUsers = newFirst; 1014 } else { 1015 int[] newUpdate = new int[updateUsers.length+1]; 1016 System.arraycopy(updateUsers, 0, newUpdate, 0, 1017 updateUsers.length); 1018 newUpdate[updateUsers.length] = user; 1019 updateUsers = newUpdate; 1020 } 1021 } 1022 } 1023 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1024 res.pkg.applicationInfo.packageName, 1025 extras, null, null, firstUsers); 1026 final boolean update = res.removedInfo.removedPackage != null; 1027 if (update) { 1028 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1029 } 1030 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1031 res.pkg.applicationInfo.packageName, 1032 extras, null, null, updateUsers); 1033 if (update) { 1034 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1035 res.pkg.applicationInfo.packageName, 1036 extras, null, null, updateUsers); 1037 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1038 null, null, 1039 res.pkg.applicationInfo.packageName, null, updateUsers); 1040 1041 // treat asec-hosted packages like removable media on upgrade 1042 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1043 if (DEBUG_INSTALL) { 1044 Slog.i(TAG, "upgrading pkg " + res.pkg 1045 + " is ASEC-hosted -> AVAILABLE"); 1046 } 1047 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1048 ArrayList<String> pkgList = new ArrayList<String>(1); 1049 pkgList.add(res.pkg.applicationInfo.packageName); 1050 sendResourcesChangedBroadcast(true, true, 1051 pkgList,uidArray, null); 1052 } 1053 } 1054 if (res.removedInfo.args != null) { 1055 // Remove the replaced package's older resources safely now 1056 deleteOld = true; 1057 } 1058 1059 // Log current value of "unknown sources" setting 1060 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1061 getUnknownSourcesSettings()); 1062 } 1063 // Force a gc to clear up things 1064 Runtime.getRuntime().gc(); 1065 // We delete after a gc for applications on sdcard. 1066 if (deleteOld) { 1067 synchronized (mInstallLock) { 1068 res.removedInfo.args.doPostDeleteLI(true); 1069 } 1070 } 1071 if (args.observer != null) { 1072 try { 1073 args.observer.packageInstalled(res.name, res.returnCode); 1074 } catch (RemoteException e) { 1075 Slog.i(TAG, "Observer no longer exists."); 1076 } 1077 } 1078 if (args.observer2 != null) { 1079 try { 1080 Bundle extras = extrasForInstallResult(res); 1081 args.observer2.packageInstalled(res.name, extras, res.returnCode); 1082 } catch (RemoteException e) { 1083 Slog.i(TAG, "Observer no longer exists."); 1084 } 1085 } 1086 } else { 1087 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1088 } 1089 } break; 1090 case UPDATED_MEDIA_STATUS: { 1091 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1092 boolean reportStatus = msg.arg1 == 1; 1093 boolean doGc = msg.arg2 == 1; 1094 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1095 if (doGc) { 1096 // Force a gc to clear up stale containers. 1097 Runtime.getRuntime().gc(); 1098 } 1099 if (msg.obj != null) { 1100 @SuppressWarnings("unchecked") 1101 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1102 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1103 // Unload containers 1104 unloadAllContainers(args); 1105 } 1106 if (reportStatus) { 1107 try { 1108 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1109 PackageHelper.getMountService().finishMediaUpdate(); 1110 } catch (RemoteException e) { 1111 Log.e(TAG, "MountService not running?"); 1112 } 1113 } 1114 } break; 1115 case WRITE_SETTINGS: { 1116 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1117 synchronized (mPackages) { 1118 removeMessages(WRITE_SETTINGS); 1119 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1120 mSettings.writeLPr(); 1121 mDirtyUsers.clear(); 1122 } 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1124 } break; 1125 case WRITE_PACKAGE_RESTRICTIONS: { 1126 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1127 synchronized (mPackages) { 1128 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1129 for (int userId : mDirtyUsers) { 1130 mSettings.writePackageRestrictionsLPr(userId); 1131 } 1132 mDirtyUsers.clear(); 1133 } 1134 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1135 } break; 1136 case CHECK_PENDING_VERIFICATION: { 1137 final int verificationId = msg.arg1; 1138 final PackageVerificationState state = mPendingVerification.get(verificationId); 1139 1140 if ((state != null) && !state.timeoutExtended()) { 1141 final InstallArgs args = state.getInstallArgs(); 1142 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString()); 1143 mPendingVerification.remove(verificationId); 1144 1145 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1146 1147 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1148 Slog.i(TAG, "Continuing with installation of " 1149 + args.packageURI.toString()); 1150 state.setVerifierResponse(Binder.getCallingUid(), 1151 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1152 broadcastPackageVerified(verificationId, args.packageURI, 1153 PackageManager.VERIFICATION_ALLOW, 1154 state.getInstallArgs().getUser()); 1155 try { 1156 ret = args.copyApk(mContainerService, true); 1157 } catch (RemoteException e) { 1158 Slog.e(TAG, "Could not contact the ContainerService"); 1159 } 1160 } else { 1161 broadcastPackageVerified(verificationId, args.packageURI, 1162 PackageManager.VERIFICATION_REJECT, 1163 state.getInstallArgs().getUser()); 1164 } 1165 1166 processPendingInstall(args, ret); 1167 mHandler.sendEmptyMessage(MCS_UNBIND); 1168 } 1169 break; 1170 } 1171 case PACKAGE_VERIFIED: { 1172 final int verificationId = msg.arg1; 1173 1174 final PackageVerificationState state = mPendingVerification.get(verificationId); 1175 if (state == null) { 1176 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1177 break; 1178 } 1179 1180 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1181 1182 state.setVerifierResponse(response.callerUid, response.code); 1183 1184 if (state.isVerificationComplete()) { 1185 mPendingVerification.remove(verificationId); 1186 1187 final InstallArgs args = state.getInstallArgs(); 1188 1189 int ret; 1190 if (state.isInstallAllowed()) { 1191 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1192 broadcastPackageVerified(verificationId, args.packageURI, 1193 response.code, state.getInstallArgs().getUser()); 1194 try { 1195 ret = args.copyApk(mContainerService, true); 1196 } catch (RemoteException e) { 1197 Slog.e(TAG, "Could not contact the ContainerService"); 1198 } 1199 } else { 1200 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1201 } 1202 1203 processPendingInstall(args, ret); 1204 1205 mHandler.sendEmptyMessage(MCS_UNBIND); 1206 } 1207 1208 break; 1209 } 1210 } 1211 } 1212 } 1213 1214 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1215 Bundle extras = null; 1216 switch (res.returnCode) { 1217 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1218 extras = new Bundle(); 1219 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1220 res.origPermission); 1221 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1222 res.origPackage); 1223 break; 1224 } 1225 } 1226 return extras; 1227 } 1228 1229 void scheduleWriteSettingsLocked() { 1230 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1231 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1232 } 1233 } 1234 1235 void scheduleWritePackageRestrictionsLocked(int userId) { 1236 if (!sUserManager.exists(userId)) return; 1237 mDirtyUsers.add(userId); 1238 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1239 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1240 } 1241 } 1242 1243 public static final PackageManagerService main(Context context, Installer installer, 1244 boolean factoryTest, boolean onlyCore) { 1245 PackageManagerService m = new PackageManagerService(context, installer, 1246 factoryTest, onlyCore); 1247 ServiceManager.addService("package", m); 1248 return m; 1249 } 1250 1251 static String[] splitString(String str, char sep) { 1252 int count = 1; 1253 int i = 0; 1254 while ((i=str.indexOf(sep, i)) >= 0) { 1255 count++; 1256 i++; 1257 } 1258 1259 String[] res = new String[count]; 1260 i=0; 1261 count = 0; 1262 int lastI=0; 1263 while ((i=str.indexOf(sep, i)) >= 0) { 1264 res[count] = str.substring(lastI, i); 1265 count++; 1266 i++; 1267 lastI = i; 1268 } 1269 res[count] = str.substring(lastI, str.length()); 1270 return res; 1271 } 1272 1273 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1274 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1275 Context.DISPLAY_SERVICE); 1276 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1277 } 1278 1279 public PackageManagerService(Context context, Installer installer, 1280 boolean factoryTest, boolean onlyCore) { 1281 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1282 SystemClock.uptimeMillis()); 1283 1284 if (mSdkVersion <= 0) { 1285 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1286 } 1287 1288 mContext = context; 1289 mFactoryTest = factoryTest; 1290 mOnlyCore = onlyCore; 1291 mMetrics = new DisplayMetrics(); 1292 mSettings = new Settings(context); 1293 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1294 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1295 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1296 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1297 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1298 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1299 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1300 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1301 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1302 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1303 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1304 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1305 1306 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1307 if (separateProcesses != null && separateProcesses.length() > 0) { 1308 if ("*".equals(separateProcesses)) { 1309 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1310 mSeparateProcesses = null; 1311 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1312 } else { 1313 mDefParseFlags = 0; 1314 mSeparateProcesses = separateProcesses.split(","); 1315 Slog.w(TAG, "Running with debug.separate_processes: " 1316 + separateProcesses); 1317 } 1318 } else { 1319 mDefParseFlags = 0; 1320 mSeparateProcesses = null; 1321 } 1322 1323 mInstaller = installer; 1324 1325 getDefaultDisplayMetrics(context, mMetrics); 1326 1327 SystemConfig systemConfig = SystemConfig.getInstance(); 1328 mGlobalGids = systemConfig.getGlobalGids(); 1329 mSystemPermissions = systemConfig.getSystemPermissions(); 1330 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1331 1332 synchronized (mInstallLock) { 1333 // writer 1334 synchronized (mPackages) { 1335 mHandlerThread = new ServiceThread(TAG, 1336 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1337 mHandlerThread.start(); 1338 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1339 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1340 1341 File dataDir = Environment.getDataDirectory(); 1342 mAppDataDir = new File(dataDir, "data"); 1343 mAppInstallDir = new File(dataDir, "app"); 1344 mAppLibInstallDir = new File(dataDir, "app-lib"); 1345 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1346 mUserAppDataDir = new File(dataDir, "user"); 1347 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1348 mAppStagingDir = new File(dataDir, "app-staging"); 1349 1350 sUserManager = new UserManagerService(context, this, 1351 mInstallLock, mPackages); 1352 1353 // Propagate permission configuration in to package manager. 1354 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1355 = systemConfig.getPermissions(); 1356 for (int i=0; i<permConfig.size(); i++) { 1357 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1358 BasePermission bp = mSettings.mPermissions.get(perm.name); 1359 if (bp == null) { 1360 bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN); 1361 mSettings.mPermissions.put(perm.name, bp); 1362 } 1363 if (perm.gids != null) { 1364 bp.gids = appendInts(bp.gids, perm.gids); 1365 } 1366 } 1367 1368 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1369 for (int i=0; i<libConfig.size(); i++) { 1370 mSharedLibraries.put(libConfig.keyAt(i), 1371 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1372 } 1373 1374 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1375 1376 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1377 mSdkVersion, mOnlyCore); 1378 1379 String customResolverActivity = Resources.getSystem().getString( 1380 R.string.config_customResolverActivity); 1381 if (TextUtils.isEmpty(customResolverActivity)) { 1382 customResolverActivity = null; 1383 } else { 1384 mCustomResolverComponentName = ComponentName.unflattenFromString( 1385 customResolverActivity); 1386 } 1387 1388 long startTime = SystemClock.uptimeMillis(); 1389 1390 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1391 startTime); 1392 1393 // Set flag to monitor and not change apk file paths when 1394 // scanning install directories. 1395 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1396 1397 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1398 1399 /** 1400 * Add everything in the in the boot class path to the 1401 * list of process files because dexopt will have been run 1402 * if necessary during zygote startup. 1403 */ 1404 String bootClassPath = System.getProperty("java.boot.class.path"); 1405 if (bootClassPath != null) { 1406 String[] paths = splitString(bootClassPath, ':'); 1407 for (int i=0; i<paths.length; i++) { 1408 alreadyDexOpted.add(paths[i]); 1409 } 1410 } else { 1411 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1412 } 1413 1414 boolean didDexOptLibraryOrTool = false; 1415 1416 final List<String> instructionSets = getAllInstructionSets(); 1417 1418 /** 1419 * Ensure all external libraries have had dexopt run on them. 1420 */ 1421 if (mSharedLibraries.size() > 0) { 1422 // NOTE: For now, we're compiling these system "shared libraries" 1423 // (and framework jars) into all available architectures. It's possible 1424 // to compile them only when we come across an app that uses them (there's 1425 // already logic for that in scanPackageLI) but that adds some complexity. 1426 for (String instructionSet : instructionSets) { 1427 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1428 final String lib = libEntry.path; 1429 if (lib == null) { 1430 continue; 1431 } 1432 1433 try { 1434 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1435 alreadyDexOpted.add(lib); 1436 1437 // The list of "shared libraries" we have at this point is 1438 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1439 didDexOptLibraryOrTool = true; 1440 } 1441 } catch (FileNotFoundException e) { 1442 Slog.w(TAG, "Library not found: " + lib); 1443 } catch (IOException e) { 1444 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1445 + e.getMessage()); 1446 } 1447 } 1448 } 1449 } 1450 1451 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1452 1453 // Gross hack for now: we know this file doesn't contain any 1454 // code, so don't dexopt it to avoid the resulting log spew. 1455 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1456 1457 // Gross hack for now: we know this file is only part of 1458 // the boot class path for art, so don't dexopt it to 1459 // avoid the resulting log spew. 1460 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1461 1462 /** 1463 * And there are a number of commands implemented in Java, which 1464 * we currently need to do the dexopt on so that they can be 1465 * run from a non-root shell. 1466 */ 1467 String[] frameworkFiles = frameworkDir.list(); 1468 if (frameworkFiles != null) { 1469 // TODO: We could compile these only for the most preferred ABI. We should 1470 // first double check that the dex files for these commands are not referenced 1471 // by other system apps. 1472 for (String instructionSet : instructionSets) { 1473 for (int i=0; i<frameworkFiles.length; i++) { 1474 File libPath = new File(frameworkDir, frameworkFiles[i]); 1475 String path = libPath.getPath(); 1476 // Skip the file if we already did it. 1477 if (alreadyDexOpted.contains(path)) { 1478 continue; 1479 } 1480 // Skip the file if it is not a type we want to dexopt. 1481 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1482 continue; 1483 } 1484 try { 1485 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1486 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1487 didDexOptLibraryOrTool = true; 1488 } 1489 } catch (FileNotFoundException e) { 1490 Slog.w(TAG, "Jar not found: " + path); 1491 } catch (IOException e) { 1492 Slog.w(TAG, "Exception reading jar: " + path, e); 1493 } 1494 } 1495 } 1496 } 1497 1498 if (didDexOptLibraryOrTool) { 1499 // If we dexopted a library or tool, then something on the system has 1500 // changed. Consider this significant, and wipe away all other 1501 // existing dexopt files to ensure we don't leave any dangling around. 1502 // 1503 // TODO: This should be revisited because it isn't as good an indicator 1504 // as it used to be. It used to include the boot classpath but at some point 1505 // DexFile.isDexOptNeeded started returning false for the boot 1506 // class path files in all cases. It is very possible in a 1507 // small maintenance release update that the library and tool 1508 // jars may be unchanged but APK could be removed resulting in 1509 // unused dalvik-cache files. 1510 for (String instructionSet : instructionSets) { 1511 mInstaller.pruneDexCache(instructionSet); 1512 } 1513 1514 // Additionally, delete all dex files from the root directory 1515 // since there shouldn't be any there anyway, unless we're upgrading 1516 // from an older OS version or a build that contained the "old" style 1517 // flat scheme. 1518 mInstaller.pruneDexCache("."); 1519 } 1520 1521 // Collect vendor overlay packages. 1522 // (Do this before scanning any apps.) 1523 // For security and version matching reason, only consider 1524 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1525 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1526 mVendorOverlayInstallObserver = new AppDirObserver( 1527 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1528 mVendorOverlayInstallObserver.startWatching(); 1529 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1530 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1531 1532 // Find base frameworks (resource packages without code). 1533 mFrameworkInstallObserver = new AppDirObserver( 1534 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1535 mFrameworkInstallObserver.startWatching(); 1536 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1537 | PackageParser.PARSE_IS_SYSTEM_DIR 1538 | PackageParser.PARSE_IS_PRIVILEGED, 1539 scanMode | SCAN_NO_DEX, 0); 1540 1541 // Collected privileged system packages. 1542 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1543 mPrivilegedInstallObserver = new AppDirObserver( 1544 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1545 mPrivilegedInstallObserver.startWatching(); 1546 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1547 | PackageParser.PARSE_IS_SYSTEM_DIR 1548 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1549 1550 // Collect ordinary system packages. 1551 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1552 mSystemInstallObserver = new AppDirObserver( 1553 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1554 mSystemInstallObserver.startWatching(); 1555 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1556 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1557 1558 // Collect all vendor packages. 1559 File vendorAppDir = new File("/vendor/app"); 1560 try { 1561 vendorAppDir = vendorAppDir.getCanonicalFile(); 1562 } catch (IOException e) { 1563 // failed to look up canonical path, continue with original one 1564 } 1565 mVendorInstallObserver = new AppDirObserver( 1566 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1567 mVendorInstallObserver.startWatching(); 1568 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1569 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1570 1571 // Collect all OEM packages. 1572 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1573 mOemInstallObserver = new AppDirObserver( 1574 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1575 mOemInstallObserver.startWatching(); 1576 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1577 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1578 1579 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1580 mInstaller.moveFiles(); 1581 1582 // Prune any system packages that no longer exist. 1583 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1584 if (!mOnlyCore) { 1585 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1586 while (psit.hasNext()) { 1587 PackageSetting ps = psit.next(); 1588 1589 /* 1590 * If this is not a system app, it can't be a 1591 * disable system app. 1592 */ 1593 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1594 continue; 1595 } 1596 1597 /* 1598 * If the package is scanned, it's not erased. 1599 */ 1600 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1601 if (scannedPkg != null) { 1602 /* 1603 * If the system app is both scanned and in the 1604 * disabled packages list, then it must have been 1605 * added via OTA. Remove it from the currently 1606 * scanned package so the previously user-installed 1607 * application can be scanned. 1608 */ 1609 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1610 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1611 + "; removing system app"); 1612 removePackageLI(ps, true); 1613 } 1614 1615 continue; 1616 } 1617 1618 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1619 psit.remove(); 1620 String msg = "System package " + ps.name 1621 + " no longer exists; wiping its data"; 1622 reportSettingsProblem(Log.WARN, msg); 1623 removeDataDirsLI(ps.name); 1624 } else { 1625 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1626 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1627 possiblyDeletedUpdatedSystemApps.add(ps.name); 1628 } 1629 } 1630 } 1631 } 1632 1633 //look for any incomplete package installations 1634 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1635 //clean up list 1636 for(int i = 0; i < deletePkgsList.size(); i++) { 1637 //clean up here 1638 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1639 } 1640 //delete tmp files 1641 deleteTempPackageFiles(); 1642 1643 // Remove any shared userIDs that have no associated packages 1644 mSettings.pruneSharedUsersLPw(); 1645 1646 if (!mOnlyCore) { 1647 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1648 SystemClock.uptimeMillis()); 1649 mAppInstallObserver = new AppDirObserver( 1650 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1651 mAppInstallObserver.startWatching(); 1652 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1653 1654 mDrmAppInstallObserver = new AppDirObserver( 1655 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1656 mDrmAppInstallObserver.startWatching(); 1657 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1658 scanMode, 0); 1659 1660 /** 1661 * Remove disable package settings for any updated system 1662 * apps that were removed via an OTA. If they're not a 1663 * previously-updated app, remove them completely. 1664 * Otherwise, just revoke their system-level permissions. 1665 */ 1666 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1667 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1668 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1669 1670 String msg; 1671 if (deletedPkg == null) { 1672 msg = "Updated system package " + deletedAppName 1673 + " no longer exists; wiping its data"; 1674 removeDataDirsLI(deletedAppName); 1675 } else { 1676 msg = "Updated system app + " + deletedAppName 1677 + " no longer present; removing system privileges for " 1678 + deletedAppName; 1679 1680 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1681 1682 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1683 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1684 } 1685 reportSettingsProblem(Log.WARN, msg); 1686 } 1687 } else { 1688 mAppInstallObserver = null; 1689 mDrmAppInstallObserver = null; 1690 } 1691 1692 // Now that we know all of the shared libraries, update all clients to have 1693 // the correct library paths. 1694 updateAllSharedLibrariesLPw(); 1695 1696 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1697 // NOTE: We ignore potential failures here during a system scan (like 1698 // the rest of the commands above) because there's precious little we 1699 // can do about it. A settings error is reported, though. 1700 adjustCpuAbisForSharedUserLPw(setting.packages, null, 1701 false /* force dexopt */, false /* defer dexopt */); 1702 } 1703 1704 // Now that we know all the packages we are keeping, 1705 // read and update their last usage times. 1706 mPackageUsage.readLP(); 1707 1708 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1709 SystemClock.uptimeMillis()); 1710 Slog.i(TAG, "Time to scan packages: " 1711 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1712 + " seconds"); 1713 1714 // If the platform SDK has changed since the last time we booted, 1715 // we need to re-grant app permission to catch any new ones that 1716 // appear. This is really a hack, and means that apps can in some 1717 // cases get permissions that the user didn't initially explicitly 1718 // allow... it would be nice to have some better way to handle 1719 // this situation. 1720 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1721 != mSdkVersion; 1722 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1723 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1724 + "; regranting permissions for internal storage"); 1725 mSettings.mInternalSdkPlatform = mSdkVersion; 1726 1727 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1728 | (regrantPermissions 1729 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1730 : 0)); 1731 1732 // If this is the first boot, and it is a normal boot, then 1733 // we need to initialize the default preferred apps. 1734 if (!mRestoredSettings && !onlyCore) { 1735 mSettings.readDefaultPreferredAppsLPw(this, 0); 1736 } 1737 1738 // All the changes are done during package scanning. 1739 mSettings.updateInternalDatabaseVersion(); 1740 1741 // can downgrade to reader 1742 mSettings.writeLPr(); 1743 1744 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1745 SystemClock.uptimeMillis()); 1746 1747 1748 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1749 } // synchronized (mPackages) 1750 } // synchronized (mInstallLock) 1751 1752 mInstallerService = new PackageInstallerService(context, this, mAppStagingDir); 1753 1754 // Now after opening every single application zip, make sure they 1755 // are all flushed. Not really needed, but keeps things nice and 1756 // tidy. 1757 Runtime.getRuntime().gc(); 1758 } 1759 1760 @Override 1761 public boolean isFirstBoot() { 1762 return !mRestoredSettings; 1763 } 1764 1765 @Override 1766 public boolean isOnlyCoreApps() { 1767 return mOnlyCore; 1768 } 1769 1770 private String getRequiredVerifierLPr() { 1771 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1772 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1773 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1774 1775 String requiredVerifier = null; 1776 1777 final int N = receivers.size(); 1778 for (int i = 0; i < N; i++) { 1779 final ResolveInfo info = receivers.get(i); 1780 1781 if (info.activityInfo == null) { 1782 continue; 1783 } 1784 1785 final String packageName = info.activityInfo.packageName; 1786 1787 final PackageSetting ps = mSettings.mPackages.get(packageName); 1788 if (ps == null) { 1789 continue; 1790 } 1791 1792 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1793 if (!gp.grantedPermissions 1794 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1795 continue; 1796 } 1797 1798 if (requiredVerifier != null) { 1799 throw new RuntimeException("There can be only one required verifier"); 1800 } 1801 1802 requiredVerifier = packageName; 1803 } 1804 1805 return requiredVerifier; 1806 } 1807 1808 @Override 1809 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1810 throws RemoteException { 1811 try { 1812 return super.onTransact(code, data, reply, flags); 1813 } catch (RuntimeException e) { 1814 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1815 Slog.wtf(TAG, "Package Manager Crash", e); 1816 } 1817 throw e; 1818 } 1819 } 1820 1821 void cleanupInstallFailedPackage(PackageSetting ps) { 1822 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1823 removeDataDirsLI(ps.name); 1824 if (ps.codePath != null) { 1825 if (!ps.codePath.delete()) { 1826 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1827 } 1828 } 1829 if (ps.resourcePath != null) { 1830 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1831 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1832 } 1833 } 1834 mSettings.removePackageLPw(ps.name); 1835 } 1836 1837 static int[] appendInts(int[] cur, int[] add) { 1838 if (add == null) return cur; 1839 if (cur == null) return add; 1840 final int N = add.length; 1841 for (int i=0; i<N; i++) { 1842 cur = appendInt(cur, add[i]); 1843 } 1844 return cur; 1845 } 1846 1847 static int[] removeInts(int[] cur, int[] rem) { 1848 if (rem == null) return cur; 1849 if (cur == null) return cur; 1850 final int N = rem.length; 1851 for (int i=0; i<N; i++) { 1852 cur = removeInt(cur, rem[i]); 1853 } 1854 return cur; 1855 } 1856 1857 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1858 if (!sUserManager.exists(userId)) return null; 1859 final PackageSetting ps = (PackageSetting) p.mExtras; 1860 if (ps == null) { 1861 return null; 1862 } 1863 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1864 final PackageUserState state = ps.readUserState(userId); 1865 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1866 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1867 state, userId); 1868 } 1869 1870 @Override 1871 public boolean isPackageAvailable(String packageName, int userId) { 1872 if (!sUserManager.exists(userId)) return false; 1873 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1874 synchronized (mPackages) { 1875 PackageParser.Package p = mPackages.get(packageName); 1876 if (p != null) { 1877 final PackageSetting ps = (PackageSetting) p.mExtras; 1878 if (ps != null) { 1879 final PackageUserState state = ps.readUserState(userId); 1880 if (state != null) { 1881 return PackageParser.isAvailable(state); 1882 } 1883 } 1884 } 1885 } 1886 return false; 1887 } 1888 1889 @Override 1890 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1891 if (!sUserManager.exists(userId)) return null; 1892 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1893 // reader 1894 synchronized (mPackages) { 1895 PackageParser.Package p = mPackages.get(packageName); 1896 if (DEBUG_PACKAGE_INFO) 1897 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1898 if (p != null) { 1899 return generatePackageInfo(p, flags, userId); 1900 } 1901 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1902 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1903 } 1904 } 1905 return null; 1906 } 1907 1908 @Override 1909 public String[] currentToCanonicalPackageNames(String[] names) { 1910 String[] out = new String[names.length]; 1911 // reader 1912 synchronized (mPackages) { 1913 for (int i=names.length-1; i>=0; i--) { 1914 PackageSetting ps = mSettings.mPackages.get(names[i]); 1915 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1916 } 1917 } 1918 return out; 1919 } 1920 1921 @Override 1922 public String[] canonicalToCurrentPackageNames(String[] names) { 1923 String[] out = new String[names.length]; 1924 // reader 1925 synchronized (mPackages) { 1926 for (int i=names.length-1; i>=0; i--) { 1927 String cur = mSettings.mRenamedPackages.get(names[i]); 1928 out[i] = cur != null ? cur : names[i]; 1929 } 1930 } 1931 return out; 1932 } 1933 1934 @Override 1935 public int getPackageUid(String packageName, int userId) { 1936 if (!sUserManager.exists(userId)) return -1; 1937 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1938 // reader 1939 synchronized (mPackages) { 1940 PackageParser.Package p = mPackages.get(packageName); 1941 if(p != null) { 1942 return UserHandle.getUid(userId, p.applicationInfo.uid); 1943 } 1944 PackageSetting ps = mSettings.mPackages.get(packageName); 1945 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1946 return -1; 1947 } 1948 p = ps.pkg; 1949 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1950 } 1951 } 1952 1953 @Override 1954 public int[] getPackageGids(String packageName) { 1955 // reader 1956 synchronized (mPackages) { 1957 PackageParser.Package p = mPackages.get(packageName); 1958 if (DEBUG_PACKAGE_INFO) 1959 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1960 if (p != null) { 1961 final PackageSetting ps = (PackageSetting)p.mExtras; 1962 return ps.getGids(); 1963 } 1964 } 1965 // stupid thing to indicate an error. 1966 return new int[0]; 1967 } 1968 1969 static final PermissionInfo generatePermissionInfo( 1970 BasePermission bp, int flags) { 1971 if (bp.perm != null) { 1972 return PackageParser.generatePermissionInfo(bp.perm, flags); 1973 } 1974 PermissionInfo pi = new PermissionInfo(); 1975 pi.name = bp.name; 1976 pi.packageName = bp.sourcePackage; 1977 pi.nonLocalizedLabel = bp.name; 1978 pi.protectionLevel = bp.protectionLevel; 1979 return pi; 1980 } 1981 1982 @Override 1983 public PermissionInfo getPermissionInfo(String name, int flags) { 1984 // reader 1985 synchronized (mPackages) { 1986 final BasePermission p = mSettings.mPermissions.get(name); 1987 if (p != null) { 1988 return generatePermissionInfo(p, flags); 1989 } 1990 return null; 1991 } 1992 } 1993 1994 @Override 1995 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1996 // reader 1997 synchronized (mPackages) { 1998 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1999 for (BasePermission p : mSettings.mPermissions.values()) { 2000 if (group == null) { 2001 if (p.perm == null || p.perm.info.group == null) { 2002 out.add(generatePermissionInfo(p, flags)); 2003 } 2004 } else { 2005 if (p.perm != null && group.equals(p.perm.info.group)) { 2006 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2007 } 2008 } 2009 } 2010 2011 if (out.size() > 0) { 2012 return out; 2013 } 2014 return mPermissionGroups.containsKey(group) ? out : null; 2015 } 2016 } 2017 2018 @Override 2019 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2020 // reader 2021 synchronized (mPackages) { 2022 return PackageParser.generatePermissionGroupInfo( 2023 mPermissionGroups.get(name), flags); 2024 } 2025 } 2026 2027 @Override 2028 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2029 // reader 2030 synchronized (mPackages) { 2031 final int N = mPermissionGroups.size(); 2032 ArrayList<PermissionGroupInfo> out 2033 = new ArrayList<PermissionGroupInfo>(N); 2034 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2035 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2036 } 2037 return out; 2038 } 2039 } 2040 2041 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2042 int userId) { 2043 if (!sUserManager.exists(userId)) return null; 2044 PackageSetting ps = mSettings.mPackages.get(packageName); 2045 if (ps != null) { 2046 if (ps.pkg == null) { 2047 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2048 flags, userId); 2049 if (pInfo != null) { 2050 return pInfo.applicationInfo; 2051 } 2052 return null; 2053 } 2054 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2055 ps.readUserState(userId), userId); 2056 } 2057 return null; 2058 } 2059 2060 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2061 int userId) { 2062 if (!sUserManager.exists(userId)) return null; 2063 PackageSetting ps = mSettings.mPackages.get(packageName); 2064 if (ps != null) { 2065 PackageParser.Package pkg = ps.pkg; 2066 if (pkg == null) { 2067 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2068 return null; 2069 } 2070 // App code is gone, so we aren't worried about split paths 2071 pkg = new PackageParser.Package(packageName); 2072 pkg.applicationInfo.packageName = packageName; 2073 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2074 pkg.applicationInfo.sourceDir = ps.codePathString; 2075 pkg.applicationInfo.publicSourceDir = ps.resourcePathString; 2076 pkg.applicationInfo.dataDir = 2077 getDataPathForPackage(packageName, 0).getPath(); 2078 pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString; 2079 pkg.applicationInfo.cpuAbi = ps.cpuAbiString; 2080 } 2081 return generatePackageInfo(pkg, flags, userId); 2082 } 2083 return null; 2084 } 2085 2086 @Override 2087 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2088 if (!sUserManager.exists(userId)) return null; 2089 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2090 // writer 2091 synchronized (mPackages) { 2092 PackageParser.Package p = mPackages.get(packageName); 2093 if (DEBUG_PACKAGE_INFO) Log.v( 2094 TAG, "getApplicationInfo " + packageName 2095 + ": " + p); 2096 if (p != null) { 2097 PackageSetting ps = mSettings.mPackages.get(packageName); 2098 if (ps == null) return null; 2099 // Note: isEnabledLP() does not apply here - always return info 2100 return PackageParser.generateApplicationInfo( 2101 p, flags, ps.readUserState(userId), userId); 2102 } 2103 if ("android".equals(packageName)||"system".equals(packageName)) { 2104 return mAndroidApplication; 2105 } 2106 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2107 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2108 } 2109 } 2110 return null; 2111 } 2112 2113 2114 @Override 2115 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2116 mContext.enforceCallingOrSelfPermission( 2117 android.Manifest.permission.CLEAR_APP_CACHE, null); 2118 // Queue up an async operation since clearing cache may take a little while. 2119 mHandler.post(new Runnable() { 2120 public void run() { 2121 mHandler.removeCallbacks(this); 2122 int retCode = -1; 2123 synchronized (mInstallLock) { 2124 retCode = mInstaller.freeCache(freeStorageSize); 2125 if (retCode < 0) { 2126 Slog.w(TAG, "Couldn't clear application caches"); 2127 } 2128 } 2129 if (observer != null) { 2130 try { 2131 observer.onRemoveCompleted(null, (retCode >= 0)); 2132 } catch (RemoteException e) { 2133 Slog.w(TAG, "RemoveException when invoking call back"); 2134 } 2135 } 2136 } 2137 }); 2138 } 2139 2140 @Override 2141 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2142 mContext.enforceCallingOrSelfPermission( 2143 android.Manifest.permission.CLEAR_APP_CACHE, null); 2144 // Queue up an async operation since clearing cache may take a little while. 2145 mHandler.post(new Runnable() { 2146 public void run() { 2147 mHandler.removeCallbacks(this); 2148 int retCode = -1; 2149 synchronized (mInstallLock) { 2150 retCode = mInstaller.freeCache(freeStorageSize); 2151 if (retCode < 0) { 2152 Slog.w(TAG, "Couldn't clear application caches"); 2153 } 2154 } 2155 if(pi != null) { 2156 try { 2157 // Callback via pending intent 2158 int code = (retCode >= 0) ? 1 : 0; 2159 pi.sendIntent(null, code, null, 2160 null, null); 2161 } catch (SendIntentException e1) { 2162 Slog.i(TAG, "Failed to send pending intent"); 2163 } 2164 } 2165 } 2166 }); 2167 } 2168 2169 void freeStorage(long freeStorageSize) throws IOException { 2170 synchronized (mInstallLock) { 2171 if (mInstaller.freeCache(freeStorageSize) < 0) { 2172 throw new IOException("Failed to free enough space"); 2173 } 2174 } 2175 } 2176 2177 @Override 2178 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2179 if (!sUserManager.exists(userId)) return null; 2180 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2181 synchronized (mPackages) { 2182 PackageParser.Activity a = mActivities.mActivities.get(component); 2183 2184 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2185 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2186 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2187 if (ps == null) return null; 2188 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2189 userId); 2190 } 2191 if (mResolveComponentName.equals(component)) { 2192 return mResolveActivity; 2193 } 2194 } 2195 return null; 2196 } 2197 2198 @Override 2199 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2200 String resolvedType) { 2201 synchronized (mPackages) { 2202 PackageParser.Activity a = mActivities.mActivities.get(component); 2203 if (a == null) { 2204 return false; 2205 } 2206 for (int i=0; i<a.intents.size(); i++) { 2207 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2208 intent.getData(), intent.getCategories(), TAG) >= 0) { 2209 return true; 2210 } 2211 } 2212 return false; 2213 } 2214 } 2215 2216 @Override 2217 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2218 if (!sUserManager.exists(userId)) return null; 2219 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2220 synchronized (mPackages) { 2221 PackageParser.Activity a = mReceivers.mActivities.get(component); 2222 if (DEBUG_PACKAGE_INFO) Log.v( 2223 TAG, "getReceiverInfo " + component + ": " + a); 2224 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2225 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2226 if (ps == null) return null; 2227 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2228 userId); 2229 } 2230 } 2231 return null; 2232 } 2233 2234 @Override 2235 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2236 if (!sUserManager.exists(userId)) return null; 2237 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2238 synchronized (mPackages) { 2239 PackageParser.Service s = mServices.mServices.get(component); 2240 if (DEBUG_PACKAGE_INFO) Log.v( 2241 TAG, "getServiceInfo " + component + ": " + s); 2242 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2243 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2244 if (ps == null) return null; 2245 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2246 userId); 2247 } 2248 } 2249 return null; 2250 } 2251 2252 @Override 2253 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2254 if (!sUserManager.exists(userId)) return null; 2255 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2256 synchronized (mPackages) { 2257 PackageParser.Provider p = mProviders.mProviders.get(component); 2258 if (DEBUG_PACKAGE_INFO) Log.v( 2259 TAG, "getProviderInfo " + component + ": " + p); 2260 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2261 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2262 if (ps == null) return null; 2263 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2264 userId); 2265 } 2266 } 2267 return null; 2268 } 2269 2270 @Override 2271 public String[] getSystemSharedLibraryNames() { 2272 Set<String> libSet; 2273 synchronized (mPackages) { 2274 libSet = mSharedLibraries.keySet(); 2275 int size = libSet.size(); 2276 if (size > 0) { 2277 String[] libs = new String[size]; 2278 libSet.toArray(libs); 2279 return libs; 2280 } 2281 } 2282 return null; 2283 } 2284 2285 @Override 2286 public FeatureInfo[] getSystemAvailableFeatures() { 2287 Collection<FeatureInfo> featSet; 2288 synchronized (mPackages) { 2289 featSet = mAvailableFeatures.values(); 2290 int size = featSet.size(); 2291 if (size > 0) { 2292 FeatureInfo[] features = new FeatureInfo[size+1]; 2293 featSet.toArray(features); 2294 FeatureInfo fi = new FeatureInfo(); 2295 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2296 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2297 features[size] = fi; 2298 return features; 2299 } 2300 } 2301 return null; 2302 } 2303 2304 @Override 2305 public boolean hasSystemFeature(String name) { 2306 synchronized (mPackages) { 2307 return mAvailableFeatures.containsKey(name); 2308 } 2309 } 2310 2311 private void checkValidCaller(int uid, int userId) { 2312 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2313 return; 2314 2315 throw new SecurityException("Caller uid=" + uid 2316 + " is not privileged to communicate with user=" + userId); 2317 } 2318 2319 @Override 2320 public int checkPermission(String permName, String pkgName) { 2321 synchronized (mPackages) { 2322 PackageParser.Package p = mPackages.get(pkgName); 2323 if (p != null && p.mExtras != null) { 2324 PackageSetting ps = (PackageSetting)p.mExtras; 2325 if (ps.sharedUser != null) { 2326 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2327 return PackageManager.PERMISSION_GRANTED; 2328 } 2329 } else if (ps.grantedPermissions.contains(permName)) { 2330 return PackageManager.PERMISSION_GRANTED; 2331 } 2332 } 2333 } 2334 return PackageManager.PERMISSION_DENIED; 2335 } 2336 2337 @Override 2338 public int checkUidPermission(String permName, int uid) { 2339 synchronized (mPackages) { 2340 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2341 if (obj != null) { 2342 GrantedPermissions gp = (GrantedPermissions)obj; 2343 if (gp.grantedPermissions.contains(permName)) { 2344 return PackageManager.PERMISSION_GRANTED; 2345 } 2346 } else { 2347 HashSet<String> perms = mSystemPermissions.get(uid); 2348 if (perms != null && perms.contains(permName)) { 2349 return PackageManager.PERMISSION_GRANTED; 2350 } 2351 } 2352 } 2353 return PackageManager.PERMISSION_DENIED; 2354 } 2355 2356 /** 2357 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2358 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2359 * @param message the message to log on security exception 2360 */ 2361 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2362 String message) { 2363 if (userId < 0) { 2364 throw new IllegalArgumentException("Invalid userId " + userId); 2365 } 2366 if (userId == UserHandle.getUserId(callingUid)) return; 2367 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2368 if (requireFullPermission) { 2369 mContext.enforceCallingOrSelfPermission( 2370 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2371 } else { 2372 try { 2373 mContext.enforceCallingOrSelfPermission( 2374 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2375 } catch (SecurityException se) { 2376 mContext.enforceCallingOrSelfPermission( 2377 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2378 } 2379 } 2380 } 2381 } 2382 2383 private BasePermission findPermissionTreeLP(String permName) { 2384 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2385 if (permName.startsWith(bp.name) && 2386 permName.length() > bp.name.length() && 2387 permName.charAt(bp.name.length()) == '.') { 2388 return bp; 2389 } 2390 } 2391 return null; 2392 } 2393 2394 private BasePermission checkPermissionTreeLP(String permName) { 2395 if (permName != null) { 2396 BasePermission bp = findPermissionTreeLP(permName); 2397 if (bp != null) { 2398 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2399 return bp; 2400 } 2401 throw new SecurityException("Calling uid " 2402 + Binder.getCallingUid() 2403 + " is not allowed to add to permission tree " 2404 + bp.name + " owned by uid " + bp.uid); 2405 } 2406 } 2407 throw new SecurityException("No permission tree found for " + permName); 2408 } 2409 2410 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2411 if (s1 == null) { 2412 return s2 == null; 2413 } 2414 if (s2 == null) { 2415 return false; 2416 } 2417 if (s1.getClass() != s2.getClass()) { 2418 return false; 2419 } 2420 return s1.equals(s2); 2421 } 2422 2423 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2424 if (pi1.icon != pi2.icon) return false; 2425 if (pi1.logo != pi2.logo) return false; 2426 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2427 if (!compareStrings(pi1.name, pi2.name)) return false; 2428 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2429 // We'll take care of setting this one. 2430 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2431 // These are not currently stored in settings. 2432 //if (!compareStrings(pi1.group, pi2.group)) return false; 2433 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2434 //if (pi1.labelRes != pi2.labelRes) return false; 2435 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2436 return true; 2437 } 2438 2439 int permissionInfoFootprint(PermissionInfo info) { 2440 int size = info.name.length(); 2441 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2442 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2443 return size; 2444 } 2445 2446 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2447 int size = 0; 2448 for (BasePermission perm : mSettings.mPermissions.values()) { 2449 if (perm.uid == tree.uid) { 2450 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2451 } 2452 } 2453 return size; 2454 } 2455 2456 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2457 // We calculate the max size of permissions defined by this uid and throw 2458 // if that plus the size of 'info' would exceed our stated maximum. 2459 if (tree.uid != Process.SYSTEM_UID) { 2460 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2461 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2462 throw new SecurityException("Permission tree size cap exceeded"); 2463 } 2464 } 2465 } 2466 2467 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2468 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2469 throw new SecurityException("Label must be specified in permission"); 2470 } 2471 BasePermission tree = checkPermissionTreeLP(info.name); 2472 BasePermission bp = mSettings.mPermissions.get(info.name); 2473 boolean added = bp == null; 2474 boolean changed = true; 2475 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2476 if (added) { 2477 enforcePermissionCapLocked(info, tree); 2478 bp = new BasePermission(info.name, tree.sourcePackage, 2479 BasePermission.TYPE_DYNAMIC); 2480 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2481 throw new SecurityException( 2482 "Not allowed to modify non-dynamic permission " 2483 + info.name); 2484 } else { 2485 if (bp.protectionLevel == fixedLevel 2486 && bp.perm.owner.equals(tree.perm.owner) 2487 && bp.uid == tree.uid 2488 && comparePermissionInfos(bp.perm.info, info)) { 2489 changed = false; 2490 } 2491 } 2492 bp.protectionLevel = fixedLevel; 2493 info = new PermissionInfo(info); 2494 info.protectionLevel = fixedLevel; 2495 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2496 bp.perm.info.packageName = tree.perm.info.packageName; 2497 bp.uid = tree.uid; 2498 if (added) { 2499 mSettings.mPermissions.put(info.name, bp); 2500 } 2501 if (changed) { 2502 if (!async) { 2503 mSettings.writeLPr(); 2504 } else { 2505 scheduleWriteSettingsLocked(); 2506 } 2507 } 2508 return added; 2509 } 2510 2511 @Override 2512 public boolean addPermission(PermissionInfo info) { 2513 synchronized (mPackages) { 2514 return addPermissionLocked(info, false); 2515 } 2516 } 2517 2518 @Override 2519 public boolean addPermissionAsync(PermissionInfo info) { 2520 synchronized (mPackages) { 2521 return addPermissionLocked(info, true); 2522 } 2523 } 2524 2525 @Override 2526 public void removePermission(String name) { 2527 synchronized (mPackages) { 2528 checkPermissionTreeLP(name); 2529 BasePermission bp = mSettings.mPermissions.get(name); 2530 if (bp != null) { 2531 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2532 throw new SecurityException( 2533 "Not allowed to modify non-dynamic permission " 2534 + name); 2535 } 2536 mSettings.mPermissions.remove(name); 2537 mSettings.writeLPr(); 2538 } 2539 } 2540 } 2541 2542 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2543 int index = pkg.requestedPermissions.indexOf(bp.name); 2544 if (index == -1) { 2545 throw new SecurityException("Package " + pkg.packageName 2546 + " has not requested permission " + bp.name); 2547 } 2548 boolean isNormal = 2549 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2550 == PermissionInfo.PROTECTION_NORMAL); 2551 boolean isDangerous = 2552 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2553 == PermissionInfo.PROTECTION_DANGEROUS); 2554 boolean isDevelopment = 2555 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2556 2557 if (!isNormal && !isDangerous && !isDevelopment) { 2558 throw new SecurityException("Permission " + bp.name 2559 + " is not a changeable permission type"); 2560 } 2561 2562 if (isNormal || isDangerous) { 2563 if (pkg.requestedPermissionsRequired.get(index)) { 2564 throw new SecurityException("Can't change " + bp.name 2565 + ". It is required by the application"); 2566 } 2567 } 2568 } 2569 2570 @Override 2571 public void grantPermission(String packageName, String permissionName) { 2572 mContext.enforceCallingOrSelfPermission( 2573 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2574 synchronized (mPackages) { 2575 final PackageParser.Package pkg = mPackages.get(packageName); 2576 if (pkg == null) { 2577 throw new IllegalArgumentException("Unknown package: " + packageName); 2578 } 2579 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2580 if (bp == null) { 2581 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2582 } 2583 2584 checkGrantRevokePermissions(pkg, bp); 2585 2586 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2587 if (ps == null) { 2588 return; 2589 } 2590 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2591 if (gp.grantedPermissions.add(permissionName)) { 2592 if (ps.haveGids) { 2593 gp.gids = appendInts(gp.gids, bp.gids); 2594 } 2595 mSettings.writeLPr(); 2596 } 2597 } 2598 } 2599 2600 @Override 2601 public void revokePermission(String packageName, String permissionName) { 2602 int changedAppId = -1; 2603 2604 synchronized (mPackages) { 2605 final PackageParser.Package pkg = mPackages.get(packageName); 2606 if (pkg == null) { 2607 throw new IllegalArgumentException("Unknown package: " + packageName); 2608 } 2609 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2610 mContext.enforceCallingOrSelfPermission( 2611 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2612 } 2613 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2614 if (bp == null) { 2615 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2616 } 2617 2618 checkGrantRevokePermissions(pkg, bp); 2619 2620 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2621 if (ps == null) { 2622 return; 2623 } 2624 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2625 if (gp.grantedPermissions.remove(permissionName)) { 2626 gp.grantedPermissions.remove(permissionName); 2627 if (ps.haveGids) { 2628 gp.gids = removeInts(gp.gids, bp.gids); 2629 } 2630 mSettings.writeLPr(); 2631 changedAppId = ps.appId; 2632 } 2633 } 2634 2635 if (changedAppId >= 0) { 2636 // We changed the perm on someone, kill its processes. 2637 IActivityManager am = ActivityManagerNative.getDefault(); 2638 if (am != null) { 2639 final int callingUserId = UserHandle.getCallingUserId(); 2640 final long ident = Binder.clearCallingIdentity(); 2641 try { 2642 //XXX we should only revoke for the calling user's app permissions, 2643 // but for now we impact all users. 2644 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2645 // "revoke " + permissionName); 2646 int[] users = sUserManager.getUserIds(); 2647 for (int user : users) { 2648 am.killUid(UserHandle.getUid(user, changedAppId), 2649 "revoke " + permissionName); 2650 } 2651 } catch (RemoteException e) { 2652 } finally { 2653 Binder.restoreCallingIdentity(ident); 2654 } 2655 } 2656 } 2657 } 2658 2659 @Override 2660 public boolean isProtectedBroadcast(String actionName) { 2661 synchronized (mPackages) { 2662 return mProtectedBroadcasts.contains(actionName); 2663 } 2664 } 2665 2666 @Override 2667 public int checkSignatures(String pkg1, String pkg2) { 2668 synchronized (mPackages) { 2669 final PackageParser.Package p1 = mPackages.get(pkg1); 2670 final PackageParser.Package p2 = mPackages.get(pkg2); 2671 if (p1 == null || p1.mExtras == null 2672 || p2 == null || p2.mExtras == null) { 2673 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2674 } 2675 return compareSignatures(p1.mSignatures, p2.mSignatures); 2676 } 2677 } 2678 2679 @Override 2680 public int checkUidSignatures(int uid1, int uid2) { 2681 // Map to base uids. 2682 uid1 = UserHandle.getAppId(uid1); 2683 uid2 = UserHandle.getAppId(uid2); 2684 // reader 2685 synchronized (mPackages) { 2686 Signature[] s1; 2687 Signature[] s2; 2688 Object obj = mSettings.getUserIdLPr(uid1); 2689 if (obj != null) { 2690 if (obj instanceof SharedUserSetting) { 2691 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2692 } else if (obj instanceof PackageSetting) { 2693 s1 = ((PackageSetting)obj).signatures.mSignatures; 2694 } else { 2695 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2696 } 2697 } else { 2698 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2699 } 2700 obj = mSettings.getUserIdLPr(uid2); 2701 if (obj != null) { 2702 if (obj instanceof SharedUserSetting) { 2703 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2704 } else if (obj instanceof PackageSetting) { 2705 s2 = ((PackageSetting)obj).signatures.mSignatures; 2706 } else { 2707 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2708 } 2709 } else { 2710 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2711 } 2712 return compareSignatures(s1, s2); 2713 } 2714 } 2715 2716 /** 2717 * Compares two sets of signatures. Returns: 2718 * <br /> 2719 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2720 * <br /> 2721 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2722 * <br /> 2723 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2724 * <br /> 2725 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2726 * <br /> 2727 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2728 */ 2729 static int compareSignatures(Signature[] s1, Signature[] s2) { 2730 if (s1 == null) { 2731 return s2 == null 2732 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2733 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2734 } 2735 2736 if (s2 == null) { 2737 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2738 } 2739 2740 if (s1.length != s2.length) { 2741 return PackageManager.SIGNATURE_NO_MATCH; 2742 } 2743 2744 // Since both signature sets are of size 1, we can compare without HashSets. 2745 if (s1.length == 1) { 2746 return s1[0].equals(s2[0]) ? 2747 PackageManager.SIGNATURE_MATCH : 2748 PackageManager.SIGNATURE_NO_MATCH; 2749 } 2750 2751 HashSet<Signature> set1 = new HashSet<Signature>(); 2752 for (Signature sig : s1) { 2753 set1.add(sig); 2754 } 2755 HashSet<Signature> set2 = new HashSet<Signature>(); 2756 for (Signature sig : s2) { 2757 set2.add(sig); 2758 } 2759 // Make sure s2 contains all signatures in s1. 2760 if (set1.equals(set2)) { 2761 return PackageManager.SIGNATURE_MATCH; 2762 } 2763 return PackageManager.SIGNATURE_NO_MATCH; 2764 } 2765 2766 /** 2767 * If the database version for this type of package (internal storage or 2768 * external storage) is less than the version where package signatures 2769 * were updated, return true. 2770 */ 2771 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2772 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2773 DatabaseVersion.SIGNATURE_END_ENTITY)) 2774 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2775 DatabaseVersion.SIGNATURE_END_ENTITY)); 2776 } 2777 2778 /** 2779 * Used for backward compatibility to make sure any packages with 2780 * certificate chains get upgraded to the new style. {@code existingSigs} 2781 * will be in the old format (since they were stored on disk from before the 2782 * system upgrade) and {@code scannedSigs} will be in the newer format. 2783 */ 2784 private int compareSignaturesCompat(PackageSignatures existingSigs, 2785 PackageParser.Package scannedPkg) { 2786 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2787 return PackageManager.SIGNATURE_NO_MATCH; 2788 } 2789 2790 HashSet<Signature> existingSet = new HashSet<Signature>(); 2791 for (Signature sig : existingSigs.mSignatures) { 2792 existingSet.add(sig); 2793 } 2794 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2795 for (Signature sig : scannedPkg.mSignatures) { 2796 try { 2797 Signature[] chainSignatures = sig.getChainSignatures(); 2798 for (Signature chainSig : chainSignatures) { 2799 scannedCompatSet.add(chainSig); 2800 } 2801 } catch (CertificateEncodingException e) { 2802 scannedCompatSet.add(sig); 2803 } 2804 } 2805 /* 2806 * Make sure the expanded scanned set contains all signatures in the 2807 * existing one. 2808 */ 2809 if (scannedCompatSet.equals(existingSet)) { 2810 // Migrate the old signatures to the new scheme. 2811 existingSigs.assignSignatures(scannedPkg.mSignatures); 2812 // The new KeySets will be re-added later in the scanning process. 2813 mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName); 2814 return PackageManager.SIGNATURE_MATCH; 2815 } 2816 return PackageManager.SIGNATURE_NO_MATCH; 2817 } 2818 2819 @Override 2820 public String[] getPackagesForUid(int uid) { 2821 uid = UserHandle.getAppId(uid); 2822 // reader 2823 synchronized (mPackages) { 2824 Object obj = mSettings.getUserIdLPr(uid); 2825 if (obj instanceof SharedUserSetting) { 2826 final SharedUserSetting sus = (SharedUserSetting) obj; 2827 final int N = sus.packages.size(); 2828 final String[] res = new String[N]; 2829 final Iterator<PackageSetting> it = sus.packages.iterator(); 2830 int i = 0; 2831 while (it.hasNext()) { 2832 res[i++] = it.next().name; 2833 } 2834 return res; 2835 } else if (obj instanceof PackageSetting) { 2836 final PackageSetting ps = (PackageSetting) obj; 2837 return new String[] { ps.name }; 2838 } 2839 } 2840 return null; 2841 } 2842 2843 @Override 2844 public String getNameForUid(int uid) { 2845 // reader 2846 synchronized (mPackages) { 2847 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2848 if (obj instanceof SharedUserSetting) { 2849 final SharedUserSetting sus = (SharedUserSetting) obj; 2850 return sus.name + ":" + sus.userId; 2851 } else if (obj instanceof PackageSetting) { 2852 final PackageSetting ps = (PackageSetting) obj; 2853 return ps.name; 2854 } 2855 } 2856 return null; 2857 } 2858 2859 @Override 2860 public int getUidForSharedUser(String sharedUserName) { 2861 if(sharedUserName == null) { 2862 return -1; 2863 } 2864 // reader 2865 synchronized (mPackages) { 2866 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2867 if (suid == null) { 2868 return -1; 2869 } 2870 return suid.userId; 2871 } 2872 } 2873 2874 @Override 2875 public int getFlagsForUid(int uid) { 2876 synchronized (mPackages) { 2877 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2878 if (obj instanceof SharedUserSetting) { 2879 final SharedUserSetting sus = (SharedUserSetting) obj; 2880 return sus.pkgFlags; 2881 } else if (obj instanceof PackageSetting) { 2882 final PackageSetting ps = (PackageSetting) obj; 2883 return ps.pkgFlags; 2884 } 2885 } 2886 return 0; 2887 } 2888 2889 @Override 2890 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2891 int flags, int userId) { 2892 if (!sUserManager.exists(userId)) return null; 2893 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2894 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2895 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2896 } 2897 2898 @Override 2899 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2900 IntentFilter filter, int match, ComponentName activity) { 2901 final int userId = UserHandle.getCallingUserId(); 2902 if (DEBUG_PREFERRED) { 2903 Log.v(TAG, "setLastChosenActivity intent=" + intent 2904 + " resolvedType=" + resolvedType 2905 + " flags=" + flags 2906 + " filter=" + filter 2907 + " match=" + match 2908 + " activity=" + activity); 2909 filter.dump(new PrintStreamPrinter(System.out), " "); 2910 } 2911 intent.setComponent(null); 2912 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2913 // Find any earlier preferred or last chosen entries and nuke them 2914 findPreferredActivity(intent, resolvedType, 2915 flags, query, 0, false, true, false, userId); 2916 // Add the new activity as the last chosen for this filter 2917 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2918 } 2919 2920 @Override 2921 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2922 final int userId = UserHandle.getCallingUserId(); 2923 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2924 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2925 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2926 false, false, false, userId); 2927 } 2928 2929 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2930 int flags, List<ResolveInfo> query, int userId) { 2931 if (query != null) { 2932 final int N = query.size(); 2933 if (N == 1) { 2934 return query.get(0); 2935 } else if (N > 1) { 2936 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2937 // If there is more than one activity with the same priority, 2938 // then let the user decide between them. 2939 ResolveInfo r0 = query.get(0); 2940 ResolveInfo r1 = query.get(1); 2941 if (DEBUG_INTENT_MATCHING || debug) { 2942 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2943 + r1.activityInfo.name + "=" + r1.priority); 2944 } 2945 // If the first activity has a higher priority, or a different 2946 // default, then it is always desireable to pick it. 2947 if (r0.priority != r1.priority 2948 || r0.preferredOrder != r1.preferredOrder 2949 || r0.isDefault != r1.isDefault) { 2950 return query.get(0); 2951 } 2952 // If we have saved a preference for a preferred activity for 2953 // this Intent, use that. 2954 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2955 flags, query, r0.priority, true, false, debug, userId); 2956 if (ri != null) { 2957 return ri; 2958 } 2959 if (userId != 0) { 2960 ri = new ResolveInfo(mResolveInfo); 2961 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2962 ri.activityInfo.applicationInfo = new ApplicationInfo( 2963 ri.activityInfo.applicationInfo); 2964 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2965 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2966 return ri; 2967 } 2968 return mResolveInfo; 2969 } 2970 } 2971 return null; 2972 } 2973 2974 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2975 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2976 final int N = query.size(); 2977 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2978 .get(userId); 2979 // Get the list of persistent preferred activities that handle the intent 2980 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2981 List<PersistentPreferredActivity> pprefs = ppir != null 2982 ? ppir.queryIntent(intent, resolvedType, 2983 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2984 : null; 2985 if (pprefs != null && pprefs.size() > 0) { 2986 final int M = pprefs.size(); 2987 for (int i=0; i<M; i++) { 2988 final PersistentPreferredActivity ppa = pprefs.get(i); 2989 if (DEBUG_PREFERRED || debug) { 2990 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2991 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2992 + "\n component=" + ppa.mComponent); 2993 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2994 } 2995 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2996 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2997 if (DEBUG_PREFERRED || debug) { 2998 Slog.v(TAG, "Found persistent preferred activity:"); 2999 if (ai != null) { 3000 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3001 } else { 3002 Slog.v(TAG, " null"); 3003 } 3004 } 3005 if (ai == null) { 3006 // This previously registered persistent preferred activity 3007 // component is no longer known. Ignore it and do NOT remove it. 3008 continue; 3009 } 3010 for (int j=0; j<N; j++) { 3011 final ResolveInfo ri = query.get(j); 3012 if (!ri.activityInfo.applicationInfo.packageName 3013 .equals(ai.applicationInfo.packageName)) { 3014 continue; 3015 } 3016 if (!ri.activityInfo.name.equals(ai.name)) { 3017 continue; 3018 } 3019 // Found a persistent preference that can handle the intent. 3020 if (DEBUG_PREFERRED || debug) { 3021 Slog.v(TAG, "Returning persistent preferred activity: " + 3022 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3023 } 3024 return ri; 3025 } 3026 } 3027 } 3028 return null; 3029 } 3030 3031 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3032 List<ResolveInfo> query, int priority, boolean always, 3033 boolean removeMatches, boolean debug, int userId) { 3034 if (!sUserManager.exists(userId)) return null; 3035 // writer 3036 synchronized (mPackages) { 3037 if (intent.getSelector() != null) { 3038 intent = intent.getSelector(); 3039 } 3040 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3041 3042 // Try to find a matching persistent preferred activity. 3043 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3044 debug, userId); 3045 3046 // If a persistent preferred activity matched, use it. 3047 if (pri != null) { 3048 return pri; 3049 } 3050 3051 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3052 // Get the list of preferred activities that handle the intent 3053 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3054 List<PreferredActivity> prefs = pir != null 3055 ? pir.queryIntent(intent, resolvedType, 3056 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3057 : null; 3058 if (prefs != null && prefs.size() > 0) { 3059 // First figure out how good the original match set is. 3060 // We will only allow preferred activities that came 3061 // from the same match quality. 3062 int match = 0; 3063 3064 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3065 3066 final int N = query.size(); 3067 for (int j=0; j<N; j++) { 3068 final ResolveInfo ri = query.get(j); 3069 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3070 + ": 0x" + Integer.toHexString(match)); 3071 if (ri.match > match) { 3072 match = ri.match; 3073 } 3074 } 3075 3076 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3077 + Integer.toHexString(match)); 3078 3079 match &= IntentFilter.MATCH_CATEGORY_MASK; 3080 final int M = prefs.size(); 3081 for (int i=0; i<M; i++) { 3082 final PreferredActivity pa = prefs.get(i); 3083 if (DEBUG_PREFERRED || debug) { 3084 Slog.v(TAG, "Checking PreferredActivity ds=" 3085 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3086 + "\n component=" + pa.mPref.mComponent); 3087 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3088 } 3089 if (pa.mPref.mMatch != match) { 3090 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3091 + Integer.toHexString(pa.mPref.mMatch)); 3092 continue; 3093 } 3094 // If it's not an "always" type preferred activity and that's what we're 3095 // looking for, skip it. 3096 if (always && !pa.mPref.mAlways) { 3097 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3098 continue; 3099 } 3100 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3101 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3102 if (DEBUG_PREFERRED || debug) { 3103 Slog.v(TAG, "Found preferred activity:"); 3104 if (ai != null) { 3105 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3106 } else { 3107 Slog.v(TAG, " null"); 3108 } 3109 } 3110 if (ai == null) { 3111 // This previously registered preferred activity 3112 // component is no longer known. Most likely an update 3113 // to the app was installed and in the new version this 3114 // component no longer exists. Clean it up by removing 3115 // it from the preferred activities list, and skip it. 3116 Slog.w(TAG, "Removing dangling preferred activity: " 3117 + pa.mPref.mComponent); 3118 pir.removeFilter(pa); 3119 continue; 3120 } 3121 for (int j=0; j<N; j++) { 3122 final ResolveInfo ri = query.get(j); 3123 if (!ri.activityInfo.applicationInfo.packageName 3124 .equals(ai.applicationInfo.packageName)) { 3125 continue; 3126 } 3127 if (!ri.activityInfo.name.equals(ai.name)) { 3128 continue; 3129 } 3130 3131 if (removeMatches) { 3132 pir.removeFilter(pa); 3133 if (DEBUG_PREFERRED) { 3134 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3135 } 3136 break; 3137 } 3138 3139 // Okay we found a previously set preferred or last chosen app. 3140 // If the result set is different from when this 3141 // was created, we need to clear it and re-ask the 3142 // user their preference, if we're looking for an "always" type entry. 3143 if (always && !pa.mPref.sameSet(query, priority)) { 3144 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3145 + intent + " type " + resolvedType); 3146 if (DEBUG_PREFERRED) { 3147 Slog.v(TAG, "Removing preferred activity since set changed " 3148 + pa.mPref.mComponent); 3149 } 3150 pir.removeFilter(pa); 3151 // Re-add the filter as a "last chosen" entry (!always) 3152 PreferredActivity lastChosen = new PreferredActivity( 3153 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3154 pir.addFilter(lastChosen); 3155 mSettings.writePackageRestrictionsLPr(userId); 3156 return null; 3157 } 3158 3159 // Yay! Either the set matched or we're looking for the last chosen 3160 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3161 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3162 mSettings.writePackageRestrictionsLPr(userId); 3163 return ri; 3164 } 3165 } 3166 } 3167 mSettings.writePackageRestrictionsLPr(userId); 3168 } 3169 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3170 return null; 3171 } 3172 3173 /* 3174 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3175 */ 3176 @Override 3177 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3178 int targetUserId) { 3179 mContext.enforceCallingOrSelfPermission( 3180 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3181 List<CrossProfileIntentFilter> matches = 3182 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3183 if (matches != null) { 3184 int size = matches.size(); 3185 for (int i = 0; i < size; i++) { 3186 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3187 } 3188 } 3189 3190 ArrayList<String> packageNames = null; 3191 SparseArray<ArrayList<String>> fromSource = 3192 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3193 if (fromSource != null) { 3194 packageNames = fromSource.get(targetUserId); 3195 } 3196 if (packageNames.contains(intent.getPackage())) { 3197 return true; 3198 } 3199 // We need the package name, so we try to resolve with the loosest flags possible 3200 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3201 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3202 int count = resolveInfos.size(); 3203 for (int i = 0; i < count; i++) { 3204 ResolveInfo resolveInfo = resolveInfos.get(i); 3205 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3206 return true; 3207 } 3208 } 3209 return false; 3210 } 3211 3212 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3213 String resolvedType, int userId) { 3214 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3215 if (resolver != null) { 3216 return resolver.queryIntent(intent, resolvedType, false, userId); 3217 } 3218 return null; 3219 } 3220 3221 @Override 3222 public List<ResolveInfo> queryIntentActivities(Intent intent, 3223 String resolvedType, int flags, int userId) { 3224 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3225 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3226 ComponentName comp = intent.getComponent(); 3227 if (comp == null) { 3228 if (intent.getSelector() != null) { 3229 intent = intent.getSelector(); 3230 comp = intent.getComponent(); 3231 } 3232 } 3233 3234 if (comp != null) { 3235 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3236 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3237 if (ai != null) { 3238 final ResolveInfo ri = new ResolveInfo(); 3239 ri.activityInfo = ai; 3240 list.add(ri); 3241 } 3242 return list; 3243 } 3244 3245 // reader 3246 synchronized (mPackages) { 3247 final String pkgName = intent.getPackage(); 3248 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3249 if (pkgName == null) { 3250 ResolveInfo resolveInfo = null; 3251 if (queryCrossProfile) { 3252 // Check if the intent needs to be forwarded to another user for this package 3253 ArrayList<ResolveInfo> crossProfileResult = 3254 queryIntentActivitiesCrossProfilePackage( 3255 intent, resolvedType, flags, userId); 3256 if (!crossProfileResult.isEmpty()) { 3257 // Skip the current profile 3258 return crossProfileResult; 3259 } 3260 List<CrossProfileIntentFilter> matchingFilters = 3261 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3262 // Check for results that need to skip the current profile. 3263 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3264 resolvedType, flags, userId); 3265 if (resolveInfo != null) { 3266 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3267 result.add(resolveInfo); 3268 return result; 3269 } 3270 // Check for cross profile results. 3271 resolveInfo = queryCrossProfileIntents( 3272 matchingFilters, intent, resolvedType, flags, userId); 3273 } 3274 // Check for results in the current profile. 3275 List<ResolveInfo> result = mActivities.queryIntent( 3276 intent, resolvedType, flags, userId); 3277 if (resolveInfo != null) { 3278 result.add(resolveInfo); 3279 } 3280 return result; 3281 } 3282 final PackageParser.Package pkg = mPackages.get(pkgName); 3283 if (pkg != null) { 3284 if (queryCrossProfile) { 3285 ArrayList<ResolveInfo> crossProfileResult = 3286 queryIntentActivitiesCrossProfilePackage( 3287 intent, resolvedType, flags, userId, pkg, pkgName); 3288 if (!crossProfileResult.isEmpty()) { 3289 // Skip the current profile 3290 return crossProfileResult; 3291 } 3292 } 3293 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3294 pkg.activities, userId); 3295 } 3296 return new ArrayList<ResolveInfo>(); 3297 } 3298 } 3299 3300 private ResolveInfo querySkipCurrentProfileIntents( 3301 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3302 int flags, int sourceUserId) { 3303 if (matchingFilters != null) { 3304 int size = matchingFilters.size(); 3305 for (int i = 0; i < size; i ++) { 3306 CrossProfileIntentFilter filter = matchingFilters.get(i); 3307 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3308 // Checking if there are activities in the target user that can handle the 3309 // intent. 3310 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3311 flags, sourceUserId); 3312 if (resolveInfo != null) { 3313 return resolveInfo; 3314 } 3315 } 3316 } 3317 } 3318 return null; 3319 } 3320 3321 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3322 Intent intent, String resolvedType, int flags, int userId) { 3323 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3324 SparseArray<ArrayList<String>> sourceForwardingInfo = 3325 mSettings.mCrossProfilePackageInfo.get(userId); 3326 if (sourceForwardingInfo != null) { 3327 int NI = sourceForwardingInfo.size(); 3328 for (int i = 0; i < NI; i++) { 3329 int targetUserId = sourceForwardingInfo.keyAt(i); 3330 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3331 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3332 intent, resolvedType, flags, targetUserId); 3333 int NJ = resolveInfos.size(); 3334 for (int j = 0; j < NJ; j++) { 3335 ResolveInfo resolveInfo = resolveInfos.get(j); 3336 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3337 matchingResolveInfos.add(createForwardingResolveInfo( 3338 resolveInfo.filter, userId, targetUserId)); 3339 } 3340 } 3341 } 3342 } 3343 return matchingResolveInfos; 3344 } 3345 3346 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3347 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3348 String packageName) { 3349 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3350 SparseArray<ArrayList<String>> sourceForwardingInfo = 3351 mSettings.mCrossProfilePackageInfo.get(userId); 3352 if (sourceForwardingInfo != null) { 3353 int NI = sourceForwardingInfo.size(); 3354 for (int i = 0; i < NI; i++) { 3355 int targetUserId = sourceForwardingInfo.keyAt(i); 3356 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3357 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3358 intent, resolvedType, flags, pkg.activities, targetUserId); 3359 int NJ = resolveInfos.size(); 3360 for (int j = 0; j < NJ; j++) { 3361 ResolveInfo resolveInfo = resolveInfos.get(j); 3362 matchingResolveInfos.add(createForwardingResolveInfo( 3363 resolveInfo.filter, userId, targetUserId)); 3364 } 3365 } 3366 } 3367 } 3368 return matchingResolveInfos; 3369 } 3370 3371 // Return matching ResolveInfo if any for skip current profile intent filters. 3372 private ResolveInfo queryCrossProfileIntents( 3373 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3374 int flags, int sourceUserId) { 3375 if (matchingFilters != null) { 3376 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3377 // match the same intent. For performance reasons, it is better not to 3378 // run queryIntent twice for the same userId 3379 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3380 int size = matchingFilters.size(); 3381 for (int i = 0; i < size; i++) { 3382 CrossProfileIntentFilter filter = matchingFilters.get(i); 3383 int targetUserId = filter.getTargetUserId(); 3384 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3385 && !alreadyTriedUserIds.get(targetUserId)) { 3386 // Checking if there are activities in the target user that can handle the 3387 // intent. 3388 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3389 flags, sourceUserId); 3390 if (resolveInfo != null) return resolveInfo; 3391 alreadyTriedUserIds.put(targetUserId, true); 3392 } 3393 } 3394 } 3395 return null; 3396 } 3397 3398 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3399 String resolvedType, int flags, int sourceUserId) { 3400 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3401 resolvedType, flags, filter.getTargetUserId()); 3402 if (resultTargetUser != null) { 3403 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3404 } 3405 return null; 3406 } 3407 3408 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3409 int sourceUserId, int targetUserId) { 3410 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3411 String className; 3412 if (targetUserId == UserHandle.USER_OWNER) { 3413 className = FORWARD_INTENT_TO_USER_OWNER; 3414 forwardingResolveInfo.showTargetUserIcon = true; 3415 } else { 3416 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3417 } 3418 ComponentName forwardingActivityComponentName = new ComponentName( 3419 mAndroidApplication.packageName, className); 3420 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3421 sourceUserId); 3422 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3423 forwardingResolveInfo.priority = 0; 3424 forwardingResolveInfo.preferredOrder = 0; 3425 forwardingResolveInfo.match = 0; 3426 forwardingResolveInfo.isDefault = true; 3427 forwardingResolveInfo.filter = filter; 3428 forwardingResolveInfo.targetUserId = targetUserId; 3429 return forwardingResolveInfo; 3430 } 3431 3432 @Override 3433 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3434 Intent[] specifics, String[] specificTypes, Intent intent, 3435 String resolvedType, int flags, int userId) { 3436 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3437 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3438 "query intent activity options"); 3439 final String resultsAction = intent.getAction(); 3440 3441 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3442 | PackageManager.GET_RESOLVED_FILTER, userId); 3443 3444 if (DEBUG_INTENT_MATCHING) { 3445 Log.v(TAG, "Query " + intent + ": " + results); 3446 } 3447 3448 int specificsPos = 0; 3449 int N; 3450 3451 // todo: note that the algorithm used here is O(N^2). This 3452 // isn't a problem in our current environment, but if we start running 3453 // into situations where we have more than 5 or 10 matches then this 3454 // should probably be changed to something smarter... 3455 3456 // First we go through and resolve each of the specific items 3457 // that were supplied, taking care of removing any corresponding 3458 // duplicate items in the generic resolve list. 3459 if (specifics != null) { 3460 for (int i=0; i<specifics.length; i++) { 3461 final Intent sintent = specifics[i]; 3462 if (sintent == null) { 3463 continue; 3464 } 3465 3466 if (DEBUG_INTENT_MATCHING) { 3467 Log.v(TAG, "Specific #" + i + ": " + sintent); 3468 } 3469 3470 String action = sintent.getAction(); 3471 if (resultsAction != null && resultsAction.equals(action)) { 3472 // If this action was explicitly requested, then don't 3473 // remove things that have it. 3474 action = null; 3475 } 3476 3477 ResolveInfo ri = null; 3478 ActivityInfo ai = null; 3479 3480 ComponentName comp = sintent.getComponent(); 3481 if (comp == null) { 3482 ri = resolveIntent( 3483 sintent, 3484 specificTypes != null ? specificTypes[i] : null, 3485 flags, userId); 3486 if (ri == null) { 3487 continue; 3488 } 3489 if (ri == mResolveInfo) { 3490 // ACK! Must do something better with this. 3491 } 3492 ai = ri.activityInfo; 3493 comp = new ComponentName(ai.applicationInfo.packageName, 3494 ai.name); 3495 } else { 3496 ai = getActivityInfo(comp, flags, userId); 3497 if (ai == null) { 3498 continue; 3499 } 3500 } 3501 3502 // Look for any generic query activities that are duplicates 3503 // of this specific one, and remove them from the results. 3504 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3505 N = results.size(); 3506 int j; 3507 for (j=specificsPos; j<N; j++) { 3508 ResolveInfo sri = results.get(j); 3509 if ((sri.activityInfo.name.equals(comp.getClassName()) 3510 && sri.activityInfo.applicationInfo.packageName.equals( 3511 comp.getPackageName())) 3512 || (action != null && sri.filter.matchAction(action))) { 3513 results.remove(j); 3514 if (DEBUG_INTENT_MATCHING) Log.v( 3515 TAG, "Removing duplicate item from " + j 3516 + " due to specific " + specificsPos); 3517 if (ri == null) { 3518 ri = sri; 3519 } 3520 j--; 3521 N--; 3522 } 3523 } 3524 3525 // Add this specific item to its proper place. 3526 if (ri == null) { 3527 ri = new ResolveInfo(); 3528 ri.activityInfo = ai; 3529 } 3530 results.add(specificsPos, ri); 3531 ri.specificIndex = i; 3532 specificsPos++; 3533 } 3534 } 3535 3536 // Now we go through the remaining generic results and remove any 3537 // duplicate actions that are found here. 3538 N = results.size(); 3539 for (int i=specificsPos; i<N-1; i++) { 3540 final ResolveInfo rii = results.get(i); 3541 if (rii.filter == null) { 3542 continue; 3543 } 3544 3545 // Iterate over all of the actions of this result's intent 3546 // filter... typically this should be just one. 3547 final Iterator<String> it = rii.filter.actionsIterator(); 3548 if (it == null) { 3549 continue; 3550 } 3551 while (it.hasNext()) { 3552 final String action = it.next(); 3553 if (resultsAction != null && resultsAction.equals(action)) { 3554 // If this action was explicitly requested, then don't 3555 // remove things that have it. 3556 continue; 3557 } 3558 for (int j=i+1; j<N; j++) { 3559 final ResolveInfo rij = results.get(j); 3560 if (rij.filter != null && rij.filter.hasAction(action)) { 3561 results.remove(j); 3562 if (DEBUG_INTENT_MATCHING) Log.v( 3563 TAG, "Removing duplicate item from " + j 3564 + " due to action " + action + " at " + i); 3565 j--; 3566 N--; 3567 } 3568 } 3569 } 3570 3571 // If the caller didn't request filter information, drop it now 3572 // so we don't have to marshall/unmarshall it. 3573 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3574 rii.filter = null; 3575 } 3576 } 3577 3578 // Filter out the caller activity if so requested. 3579 if (caller != null) { 3580 N = results.size(); 3581 for (int i=0; i<N; i++) { 3582 ActivityInfo ainfo = results.get(i).activityInfo; 3583 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3584 && caller.getClassName().equals(ainfo.name)) { 3585 results.remove(i); 3586 break; 3587 } 3588 } 3589 } 3590 3591 // If the caller didn't request filter information, 3592 // drop them now so we don't have to 3593 // marshall/unmarshall it. 3594 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3595 N = results.size(); 3596 for (int i=0; i<N; i++) { 3597 results.get(i).filter = null; 3598 } 3599 } 3600 3601 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3602 return results; 3603 } 3604 3605 @Override 3606 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3607 int userId) { 3608 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3609 ComponentName comp = intent.getComponent(); 3610 if (comp == null) { 3611 if (intent.getSelector() != null) { 3612 intent = intent.getSelector(); 3613 comp = intent.getComponent(); 3614 } 3615 } 3616 if (comp != null) { 3617 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3618 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3619 if (ai != null) { 3620 ResolveInfo ri = new ResolveInfo(); 3621 ri.activityInfo = ai; 3622 list.add(ri); 3623 } 3624 return list; 3625 } 3626 3627 // reader 3628 synchronized (mPackages) { 3629 String pkgName = intent.getPackage(); 3630 if (pkgName == null) { 3631 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3632 } 3633 final PackageParser.Package pkg = mPackages.get(pkgName); 3634 if (pkg != null) { 3635 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3636 userId); 3637 } 3638 return null; 3639 } 3640 } 3641 3642 @Override 3643 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3644 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3645 if (!sUserManager.exists(userId)) return null; 3646 if (query != null) { 3647 if (query.size() >= 1) { 3648 // If there is more than one service with the same priority, 3649 // just arbitrarily pick the first one. 3650 return query.get(0); 3651 } 3652 } 3653 return null; 3654 } 3655 3656 @Override 3657 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3658 int userId) { 3659 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3660 ComponentName comp = intent.getComponent(); 3661 if (comp == null) { 3662 if (intent.getSelector() != null) { 3663 intent = intent.getSelector(); 3664 comp = intent.getComponent(); 3665 } 3666 } 3667 if (comp != null) { 3668 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3669 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3670 if (si != null) { 3671 final ResolveInfo ri = new ResolveInfo(); 3672 ri.serviceInfo = si; 3673 list.add(ri); 3674 } 3675 return list; 3676 } 3677 3678 // reader 3679 synchronized (mPackages) { 3680 String pkgName = intent.getPackage(); 3681 if (pkgName == null) { 3682 return mServices.queryIntent(intent, resolvedType, flags, userId); 3683 } 3684 final PackageParser.Package pkg = mPackages.get(pkgName); 3685 if (pkg != null) { 3686 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3687 userId); 3688 } 3689 return null; 3690 } 3691 } 3692 3693 @Override 3694 public List<ResolveInfo> queryIntentContentProviders( 3695 Intent intent, String resolvedType, int flags, int userId) { 3696 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3697 ComponentName comp = intent.getComponent(); 3698 if (comp == null) { 3699 if (intent.getSelector() != null) { 3700 intent = intent.getSelector(); 3701 comp = intent.getComponent(); 3702 } 3703 } 3704 if (comp != null) { 3705 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3706 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3707 if (pi != null) { 3708 final ResolveInfo ri = new ResolveInfo(); 3709 ri.providerInfo = pi; 3710 list.add(ri); 3711 } 3712 return list; 3713 } 3714 3715 // reader 3716 synchronized (mPackages) { 3717 String pkgName = intent.getPackage(); 3718 if (pkgName == null) { 3719 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3720 } 3721 final PackageParser.Package pkg = mPackages.get(pkgName); 3722 if (pkg != null) { 3723 return mProviders.queryIntentForPackage( 3724 intent, resolvedType, flags, pkg.providers, userId); 3725 } 3726 return null; 3727 } 3728 } 3729 3730 @Override 3731 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3732 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3733 3734 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3735 3736 // writer 3737 synchronized (mPackages) { 3738 ArrayList<PackageInfo> list; 3739 if (listUninstalled) { 3740 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3741 for (PackageSetting ps : mSettings.mPackages.values()) { 3742 PackageInfo pi; 3743 if (ps.pkg != null) { 3744 pi = generatePackageInfo(ps.pkg, flags, userId); 3745 } else { 3746 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3747 } 3748 if (pi != null) { 3749 list.add(pi); 3750 } 3751 } 3752 } else { 3753 list = new ArrayList<PackageInfo>(mPackages.size()); 3754 for (PackageParser.Package p : mPackages.values()) { 3755 PackageInfo pi = generatePackageInfo(p, flags, userId); 3756 if (pi != null) { 3757 list.add(pi); 3758 } 3759 } 3760 } 3761 3762 return new ParceledListSlice<PackageInfo>(list); 3763 } 3764 } 3765 3766 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3767 String[] permissions, boolean[] tmp, int flags, int userId) { 3768 int numMatch = 0; 3769 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3770 for (int i=0; i<permissions.length; i++) { 3771 if (gp.grantedPermissions.contains(permissions[i])) { 3772 tmp[i] = true; 3773 numMatch++; 3774 } else { 3775 tmp[i] = false; 3776 } 3777 } 3778 if (numMatch == 0) { 3779 return; 3780 } 3781 PackageInfo pi; 3782 if (ps.pkg != null) { 3783 pi = generatePackageInfo(ps.pkg, flags, userId); 3784 } else { 3785 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3786 } 3787 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3788 if (numMatch == permissions.length) { 3789 pi.requestedPermissions = permissions; 3790 } else { 3791 pi.requestedPermissions = new String[numMatch]; 3792 numMatch = 0; 3793 for (int i=0; i<permissions.length; i++) { 3794 if (tmp[i]) { 3795 pi.requestedPermissions[numMatch] = permissions[i]; 3796 numMatch++; 3797 } 3798 } 3799 } 3800 } 3801 list.add(pi); 3802 } 3803 3804 @Override 3805 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3806 String[] permissions, int flags, int userId) { 3807 if (!sUserManager.exists(userId)) return null; 3808 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3809 3810 // writer 3811 synchronized (mPackages) { 3812 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3813 boolean[] tmpBools = new boolean[permissions.length]; 3814 if (listUninstalled) { 3815 for (PackageSetting ps : mSettings.mPackages.values()) { 3816 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3817 } 3818 } else { 3819 for (PackageParser.Package pkg : mPackages.values()) { 3820 PackageSetting ps = (PackageSetting)pkg.mExtras; 3821 if (ps != null) { 3822 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3823 userId); 3824 } 3825 } 3826 } 3827 3828 return new ParceledListSlice<PackageInfo>(list); 3829 } 3830 } 3831 3832 @Override 3833 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3834 if (!sUserManager.exists(userId)) return null; 3835 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3836 3837 // writer 3838 synchronized (mPackages) { 3839 ArrayList<ApplicationInfo> list; 3840 if (listUninstalled) { 3841 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3842 for (PackageSetting ps : mSettings.mPackages.values()) { 3843 ApplicationInfo ai; 3844 if (ps.pkg != null) { 3845 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3846 ps.readUserState(userId), userId); 3847 } else { 3848 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3849 } 3850 if (ai != null) { 3851 list.add(ai); 3852 } 3853 } 3854 } else { 3855 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3856 for (PackageParser.Package p : mPackages.values()) { 3857 if (p.mExtras != null) { 3858 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3859 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3860 if (ai != null) { 3861 list.add(ai); 3862 } 3863 } 3864 } 3865 } 3866 3867 return new ParceledListSlice<ApplicationInfo>(list); 3868 } 3869 } 3870 3871 public List<ApplicationInfo> getPersistentApplications(int flags) { 3872 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3873 3874 // reader 3875 synchronized (mPackages) { 3876 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3877 final int userId = UserHandle.getCallingUserId(); 3878 while (i.hasNext()) { 3879 final PackageParser.Package p = i.next(); 3880 if (p.applicationInfo != null 3881 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3882 && (!mSafeMode || isSystemApp(p))) { 3883 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3884 if (ps != null) { 3885 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3886 ps.readUserState(userId), userId); 3887 if (ai != null) { 3888 finalList.add(ai); 3889 } 3890 } 3891 } 3892 } 3893 } 3894 3895 return finalList; 3896 } 3897 3898 @Override 3899 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3900 if (!sUserManager.exists(userId)) return null; 3901 // reader 3902 synchronized (mPackages) { 3903 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3904 PackageSetting ps = provider != null 3905 ? mSettings.mPackages.get(provider.owner.packageName) 3906 : null; 3907 return ps != null 3908 && mSettings.isEnabledLPr(provider.info, flags, userId) 3909 && (!mSafeMode || (provider.info.applicationInfo.flags 3910 &ApplicationInfo.FLAG_SYSTEM) != 0) 3911 ? PackageParser.generateProviderInfo(provider, flags, 3912 ps.readUserState(userId), userId) 3913 : null; 3914 } 3915 } 3916 3917 /** 3918 * @deprecated 3919 */ 3920 @Deprecated 3921 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3922 // reader 3923 synchronized (mPackages) { 3924 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3925 .entrySet().iterator(); 3926 final int userId = UserHandle.getCallingUserId(); 3927 while (i.hasNext()) { 3928 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3929 PackageParser.Provider p = entry.getValue(); 3930 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3931 3932 if (ps != null && p.syncable 3933 && (!mSafeMode || (p.info.applicationInfo.flags 3934 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3935 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3936 ps.readUserState(userId), userId); 3937 if (info != null) { 3938 outNames.add(entry.getKey()); 3939 outInfo.add(info); 3940 } 3941 } 3942 } 3943 } 3944 } 3945 3946 @Override 3947 public List<ProviderInfo> queryContentProviders(String processName, 3948 int uid, int flags) { 3949 ArrayList<ProviderInfo> finalList = null; 3950 // reader 3951 synchronized (mPackages) { 3952 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3953 final int userId = processName != null ? 3954 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3955 while (i.hasNext()) { 3956 final PackageParser.Provider p = i.next(); 3957 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3958 if (ps != null && p.info.authority != null 3959 && (processName == null 3960 || (p.info.processName.equals(processName) 3961 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3962 && mSettings.isEnabledLPr(p.info, flags, userId) 3963 && (!mSafeMode 3964 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3965 if (finalList == null) { 3966 finalList = new ArrayList<ProviderInfo>(3); 3967 } 3968 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3969 ps.readUserState(userId), userId); 3970 if (info != null) { 3971 finalList.add(info); 3972 } 3973 } 3974 } 3975 } 3976 3977 if (finalList != null) { 3978 Collections.sort(finalList, mProviderInitOrderSorter); 3979 } 3980 3981 return finalList; 3982 } 3983 3984 @Override 3985 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3986 int flags) { 3987 // reader 3988 synchronized (mPackages) { 3989 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3990 return PackageParser.generateInstrumentationInfo(i, flags); 3991 } 3992 } 3993 3994 @Override 3995 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3996 int flags) { 3997 ArrayList<InstrumentationInfo> finalList = 3998 new ArrayList<InstrumentationInfo>(); 3999 4000 // reader 4001 synchronized (mPackages) { 4002 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4003 while (i.hasNext()) { 4004 final PackageParser.Instrumentation p = i.next(); 4005 if (targetPackage == null 4006 || targetPackage.equals(p.info.targetPackage)) { 4007 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4008 flags); 4009 if (ii != null) { 4010 finalList.add(ii); 4011 } 4012 } 4013 } 4014 } 4015 4016 return finalList; 4017 } 4018 4019 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4020 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4021 if (overlays == null) { 4022 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4023 return; 4024 } 4025 for (PackageParser.Package opkg : overlays.values()) { 4026 // Not much to do if idmap fails: we already logged the error 4027 // and we certainly don't want to abort installation of pkg simply 4028 // because an overlay didn't fit properly. For these reasons, 4029 // ignore the return value of createIdmapForPackagePairLI. 4030 createIdmapForPackagePairLI(pkg, opkg); 4031 } 4032 } 4033 4034 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4035 PackageParser.Package opkg) { 4036 if (!opkg.mTrustedOverlay) { 4037 Slog.w(TAG, "Skipping target and overlay pair " + pkg.codePath + " and " + 4038 opkg.codePath + ": overlay not trusted"); 4039 return false; 4040 } 4041 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4042 if (overlaySet == null) { 4043 Slog.e(TAG, "was about to create idmap for " + pkg.codePath + " and " + 4044 opkg.codePath + " but target package has no known overlays"); 4045 return false; 4046 } 4047 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4048 // TODO: generate idmap for split APKs 4049 if (mInstaller.idmap(pkg.codePath, opkg.codePath, sharedGid) != 0) { 4050 Slog.e(TAG, "Failed to generate idmap for " + pkg.codePath + " and " + opkg.codePath); 4051 return false; 4052 } 4053 PackageParser.Package[] overlayArray = 4054 overlaySet.values().toArray(new PackageParser.Package[0]); 4055 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4056 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4057 return p1.mOverlayPriority - p2.mOverlayPriority; 4058 } 4059 }; 4060 Arrays.sort(overlayArray, cmp); 4061 4062 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4063 int i = 0; 4064 for (PackageParser.Package p : overlayArray) { 4065 pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir; 4066 } 4067 return true; 4068 } 4069 4070 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4071 String[] files = dir.list(); 4072 if (files == null) { 4073 Log.d(TAG, "No files in app dir " + dir); 4074 return; 4075 } 4076 4077 if (DEBUG_PACKAGE_SCANNING) { 4078 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4079 + " flags=0x" + Integer.toHexString(flags)); 4080 } 4081 4082 int i; 4083 for (i=0; i<files.length; i++) { 4084 File file = new File(dir, files[i]); 4085 if (!isPackageFilename(files[i])) { 4086 // Ignore entries which are not apk's 4087 continue; 4088 } 4089 PackageParser.Package pkg = scanPackageLI(file, 4090 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null); 4091 // Don't mess around with apps in system partition. 4092 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4093 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 4094 // Delete the apk 4095 Slog.w(TAG, "Cleaning up failed install of " + file); 4096 file.delete(); 4097 } 4098 } 4099 } 4100 4101 private static File getSettingsProblemFile() { 4102 File dataDir = Environment.getDataDirectory(); 4103 File systemDir = new File(dataDir, "system"); 4104 File fname = new File(systemDir, "uiderrors.txt"); 4105 return fname; 4106 } 4107 4108 static void reportSettingsProblem(int priority, String msg) { 4109 try { 4110 File fname = getSettingsProblemFile(); 4111 FileOutputStream out = new FileOutputStream(fname, true); 4112 PrintWriter pw = new FastPrintWriter(out); 4113 SimpleDateFormat formatter = new SimpleDateFormat(); 4114 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4115 pw.println(dateString + ": " + msg); 4116 pw.close(); 4117 FileUtils.setPermissions( 4118 fname.toString(), 4119 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4120 -1, -1); 4121 } catch (java.io.IOException e) { 4122 } 4123 Slog.println(priority, TAG, msg); 4124 } 4125 4126 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 4127 PackageParser.Package pkg, File srcFile, int parseFlags) { 4128 if (ps != null 4129 && ps.codePath.equals(srcFile) 4130 && ps.timeStamp == srcFile.lastModified() 4131 && !isCompatSignatureUpdateNeeded(pkg)) { 4132 if (ps.signatures.mSignatures != null 4133 && ps.signatures.mSignatures.length != 0) { 4134 // Optimization: reuse the existing cached certificates 4135 // if the package appears to be unchanged. 4136 pkg.mSignatures = ps.signatures.mSignatures; 4137 return true; 4138 } 4139 4140 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 4141 } else { 4142 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4143 } 4144 4145 try { 4146 pp.collectCertificates(pkg, parseFlags); 4147 pp.collectManifestDigest(pkg); 4148 } catch (PackageParserException e) { 4149 mLastScanError = e.error; 4150 return false; 4151 } 4152 return true; 4153 } 4154 4155 /* 4156 * Scan a package and return the newly parsed package. 4157 * Returns null in case of errors and the error code is stored in mLastScanError 4158 */ 4159 private PackageParser.Package scanPackageLI(File scanFile, 4160 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4161 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 4162 String scanPath = scanFile.getPath(); 4163 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath); 4164 parseFlags |= mDefParseFlags; 4165 PackageParser pp = new PackageParser(); 4166 pp.setSeparateProcesses(mSeparateProcesses); 4167 pp.setOnlyCoreApps(mOnlyCore); 4168 pp.setDisplayMetrics(mMetrics); 4169 4170 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4171 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4172 } 4173 4174 final PackageParser.Package pkg; 4175 try { 4176 pkg = pp.parseMonolithicPackage(scanFile, parseFlags); 4177 } catch (PackageParserException e) { 4178 mLastScanError = e.error; 4179 return null; 4180 } 4181 4182 PackageSetting ps = null; 4183 PackageSetting updatedPkg; 4184 // reader 4185 synchronized (mPackages) { 4186 // Look to see if we already know about this package. 4187 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4188 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4189 // This package has been renamed to its original name. Let's 4190 // use that. 4191 ps = mSettings.peekPackageLPr(oldName); 4192 } 4193 // If there was no original package, see one for the real package name. 4194 if (ps == null) { 4195 ps = mSettings.peekPackageLPr(pkg.packageName); 4196 } 4197 // Check to see if this package could be hiding/updating a system 4198 // package. Must look for it either under the original or real 4199 // package name depending on our state. 4200 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4201 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4202 } 4203 boolean updatedPkgBetter = false; 4204 // First check if this is a system package that may involve an update 4205 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4206 if (ps != null && !ps.codePath.equals(scanFile)) { 4207 // The path has changed from what was last scanned... check the 4208 // version of the new path against what we have stored to determine 4209 // what to do. 4210 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4211 if (pkg.mVersionCode < ps.versionCode) { 4212 // The system package has been updated and the code path does not match 4213 // Ignore entry. Skip it. 4214 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4215 + " ignored: updated version " + ps.versionCode 4216 + " better than this " + pkg.mVersionCode); 4217 if (!updatedPkg.codePath.equals(scanFile)) { 4218 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4219 + ps.name + " changing from " + updatedPkg.codePathString 4220 + " to " + scanFile); 4221 updatedPkg.codePath = scanFile; 4222 updatedPkg.codePathString = scanFile.toString(); 4223 // This is the point at which we know that the system-disk APK 4224 // for this package has moved during a reboot (e.g. due to an OTA), 4225 // so we need to reevaluate it for privilege policy. 4226 if (locationIsPrivileged(scanFile)) { 4227 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4228 } 4229 } 4230 updatedPkg.pkg = pkg; 4231 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4232 return null; 4233 } else { 4234 // The current app on the system partition is better than 4235 // what we have updated to on the data partition; switch 4236 // back to the system partition version. 4237 // At this point, its safely assumed that package installation for 4238 // apps in system partition will go through. If not there won't be a working 4239 // version of the app 4240 // writer 4241 synchronized (mPackages) { 4242 // Just remove the loaded entries from package lists. 4243 mPackages.remove(ps.name); 4244 } 4245 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4246 + "reverting from " + ps.codePathString 4247 + ": new version " + pkg.mVersionCode 4248 + " better than installed " + ps.versionCode); 4249 4250 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4251 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4252 getAppInstructionSetFromSettings(ps)); 4253 synchronized (mInstallLock) { 4254 args.cleanUpResourcesLI(); 4255 } 4256 synchronized (mPackages) { 4257 mSettings.enableSystemPackageLPw(ps.name); 4258 } 4259 updatedPkgBetter = true; 4260 } 4261 } 4262 } 4263 4264 if (updatedPkg != null) { 4265 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4266 // initially 4267 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4268 4269 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4270 // flag set initially 4271 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4272 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4273 } 4274 } 4275 // Verify certificates against what was last scanned 4276 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 4277 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 4278 return null; 4279 } 4280 4281 /* 4282 * A new system app appeared, but we already had a non-system one of the 4283 * same name installed earlier. 4284 */ 4285 boolean shouldHideSystemApp = false; 4286 if (updatedPkg == null && ps != null 4287 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4288 /* 4289 * Check to make sure the signatures match first. If they don't, 4290 * wipe the installed application and its data. 4291 */ 4292 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4293 != PackageManager.SIGNATURE_MATCH) { 4294 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4295 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4296 ps = null; 4297 } else { 4298 /* 4299 * If the newly-added system app is an older version than the 4300 * already installed version, hide it. It will be scanned later 4301 * and re-added like an update. 4302 */ 4303 if (pkg.mVersionCode < ps.versionCode) { 4304 shouldHideSystemApp = true; 4305 } else { 4306 /* 4307 * The newly found system app is a newer version that the 4308 * one previously installed. Simply remove the 4309 * already-installed application and replace it with our own 4310 * while keeping the application data. 4311 */ 4312 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4313 + ps.codePathString + ": new version " + pkg.mVersionCode 4314 + " better than installed " + ps.versionCode); 4315 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4316 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4317 getAppInstructionSetFromSettings(ps)); 4318 synchronized (mInstallLock) { 4319 args.cleanUpResourcesLI(); 4320 } 4321 } 4322 } 4323 } 4324 4325 // The apk is forward locked (not public) if its code and resources 4326 // are kept in different files. (except for app in either system or 4327 // vendor path). 4328 // TODO grab this value from PackageSettings 4329 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4330 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4331 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4332 } 4333 } 4334 4335 final String codePath = pkg.codePath; 4336 final String[] splitCodePaths = pkg.splitCodePaths; 4337 4338 String resPath = null; 4339 String[] splitResPaths = null; 4340 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4341 if (ps != null && ps.resourcePathString != null) { 4342 resPath = ps.resourcePathString; 4343 splitResPaths = deriveSplitResPaths(pkg.splitCodePaths); 4344 } else { 4345 // Should not happen at all. Just log an error. 4346 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4347 } 4348 } else { 4349 resPath = pkg.codePath; 4350 splitResPaths = pkg.splitCodePaths; 4351 } 4352 4353 // Set application objects path explicitly. 4354 pkg.applicationInfo.sourceDir = codePath; 4355 pkg.applicationInfo.publicSourceDir = resPath; 4356 pkg.applicationInfo.splitSourceDirs = splitCodePaths; 4357 pkg.applicationInfo.splitPublicSourceDirs = splitResPaths; 4358 4359 // Note that we invoke the following method only if we are about to unpack an application 4360 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4361 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4362 4363 /* 4364 * If the system app should be overridden by a previously installed 4365 * data, hide the system app now and let the /data/app scan pick it up 4366 * again. 4367 */ 4368 if (shouldHideSystemApp) { 4369 synchronized (mPackages) { 4370 /* 4371 * We have to grant systems permissions before we hide, because 4372 * grantPermissions will assume the package update is trying to 4373 * expand its permissions. 4374 */ 4375 grantPermissionsLPw(pkg, true); 4376 mSettings.disableSystemPackageLPw(pkg.packageName); 4377 } 4378 } 4379 4380 return scannedPkg; 4381 } 4382 4383 private static String fixProcessName(String defProcessName, 4384 String processName, int uid) { 4385 if (processName == null) { 4386 return defProcessName; 4387 } 4388 return processName; 4389 } 4390 4391 private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) { 4392 if (pkgSetting.signatures.mSignatures != null) { 4393 // Already existing package. Make sure signatures match 4394 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4395 == PackageManager.SIGNATURE_MATCH; 4396 if (!match) { 4397 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4398 == PackageManager.SIGNATURE_MATCH; 4399 } 4400 if (!match) { 4401 Slog.e(TAG, "Package " + pkg.packageName 4402 + " signatures do not match the previously installed version; ignoring!"); 4403 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4404 return false; 4405 } 4406 } 4407 // Check for shared user signatures 4408 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4409 // Already existing package. Make sure signatures match 4410 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4411 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4412 if (!match) { 4413 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4414 == PackageManager.SIGNATURE_MATCH; 4415 } 4416 if (!match) { 4417 Slog.e(TAG, "Package " + pkg.packageName 4418 + " has no signatures that match those in shared user " 4419 + pkgSetting.sharedUser.name + "; ignoring!"); 4420 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4421 return false; 4422 } 4423 } 4424 return true; 4425 } 4426 4427 /** 4428 * Enforces that only the system UID or root's UID can call a method exposed 4429 * via Binder. 4430 * 4431 * @param message used as message if SecurityException is thrown 4432 * @throws SecurityException if the caller is not system or root 4433 */ 4434 private static final void enforceSystemOrRoot(String message) { 4435 final int uid = Binder.getCallingUid(); 4436 if (uid != Process.SYSTEM_UID && uid != 0) { 4437 throw new SecurityException(message); 4438 } 4439 } 4440 4441 @Override 4442 public void performBootDexOpt() { 4443 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4444 4445 final HashSet<PackageParser.Package> pkgs; 4446 synchronized (mPackages) { 4447 pkgs = mDeferredDexOpt; 4448 mDeferredDexOpt = null; 4449 } 4450 4451 if (pkgs != null) { 4452 // Filter out packages that aren't recently used. 4453 // 4454 // The exception is first boot of a non-eng device, which 4455 // should do a full dexopt. 4456 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4457 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4458 // TODO: add a property to control this? 4459 long dexOptLRUThresholdInMinutes; 4460 if (eng) { 4461 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4462 } else { 4463 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4464 } 4465 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4466 4467 int total = pkgs.size(); 4468 int skipped = 0; 4469 long now = System.currentTimeMillis(); 4470 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4471 PackageParser.Package pkg = i.next(); 4472 long then = pkg.mLastPackageUsageTimeInMills; 4473 if (then + dexOptLRUThresholdInMills < now) { 4474 if (DEBUG_DEXOPT) { 4475 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4476 ((then == 0) ? "never" : new Date(then))); 4477 } 4478 i.remove(); 4479 skipped++; 4480 } 4481 } 4482 if (DEBUG_DEXOPT) { 4483 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4484 } 4485 } 4486 4487 int i = 0; 4488 for (PackageParser.Package pkg : pkgs) { 4489 i++; 4490 if (DEBUG_DEXOPT) { 4491 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4492 + ": " + pkg.packageName); 4493 } 4494 if (!isFirstBoot()) { 4495 try { 4496 ActivityManagerNative.getDefault().showBootMessage( 4497 mContext.getResources().getString( 4498 R.string.android_upgrading_apk, 4499 i, pkgs.size()), true); 4500 } catch (RemoteException e) { 4501 } 4502 } 4503 PackageParser.Package p = pkg; 4504 synchronized (mInstallLock) { 4505 if (p.mDexOptNeeded) { 4506 performDexOptLI(p, false /* force dex */, false /* defer */, 4507 true /* include dependencies */); 4508 } 4509 } 4510 } 4511 } 4512 } 4513 4514 @Override 4515 public boolean performDexOpt(String packageName) { 4516 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4517 return performDexOpt(packageName, true); 4518 } 4519 4520 public boolean performDexOpt(String packageName, boolean updateUsage) { 4521 4522 PackageParser.Package p; 4523 synchronized (mPackages) { 4524 p = mPackages.get(packageName); 4525 if (p == null) { 4526 return false; 4527 } 4528 if (updateUsage) { 4529 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4530 } 4531 mPackageUsage.write(false); 4532 if (!p.mDexOptNeeded) { 4533 return false; 4534 } 4535 } 4536 4537 synchronized (mInstallLock) { 4538 return performDexOptLI(p, false /* force dex */, false /* defer */, 4539 true /* include dependencies */) == DEX_OPT_PERFORMED; 4540 } 4541 } 4542 4543 public HashSet<String> getPackagesThatNeedDexOpt() { 4544 HashSet<String> pkgs = null; 4545 synchronized (mPackages) { 4546 for (PackageParser.Package p : mPackages.values()) { 4547 if (DEBUG_DEXOPT) { 4548 Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded); 4549 } 4550 if (!p.mDexOptNeeded) { 4551 continue; 4552 } 4553 if (pkgs == null) { 4554 pkgs = new HashSet<String>(); 4555 } 4556 pkgs.add(p.packageName); 4557 } 4558 } 4559 return pkgs; 4560 } 4561 4562 public void shutdown() { 4563 mPackageUsage.write(true); 4564 } 4565 4566 private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, 4567 boolean forceDex, boolean defer, HashSet<String> done) { 4568 for (int i=0; i<libs.size(); i++) { 4569 PackageParser.Package libPkg; 4570 String libName; 4571 synchronized (mPackages) { 4572 libName = libs.get(i); 4573 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4574 if (lib != null && lib.apk != null) { 4575 libPkg = mPackages.get(lib.apk); 4576 } else { 4577 libPkg = null; 4578 } 4579 } 4580 if (libPkg != null && !done.contains(libName)) { 4581 performDexOptLI(libPkg, instructionSet, forceDex, defer, done); 4582 } 4583 } 4584 } 4585 4586 static final int DEX_OPT_SKIPPED = 0; 4587 static final int DEX_OPT_PERFORMED = 1; 4588 static final int DEX_OPT_DEFERRED = 2; 4589 static final int DEX_OPT_FAILED = -1; 4590 4591 private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride, 4592 boolean forceDex, boolean defer, HashSet<String> done) { 4593 final String instructionSet = instructionSetOverride != null ? 4594 instructionSetOverride : getAppInstructionSet(pkg.applicationInfo); 4595 4596 if (done != null) { 4597 done.add(pkg.packageName); 4598 if (pkg.usesLibraries != null) { 4599 performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done); 4600 } 4601 if (pkg.usesOptionalLibraries != null) { 4602 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done); 4603 } 4604 } 4605 4606 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) { 4607 final Collection<String> paths = pkg.getAllCodePaths(); 4608 for (String path : paths) { 4609 try { 4610 boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path, 4611 pkg.packageName, instructionSet, defer); 4612 // There are three basic cases here: 4613 // 1.) we need to dexopt, either because we are forced or it is needed 4614 // 2.) we are defering a needed dexopt 4615 // 3.) we are skipping an unneeded dexopt 4616 if (forceDex || (!defer && isDexOptNeededInternal)) { 4617 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName); 4618 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4619 int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4620 pkg.packageName, instructionSet); 4621 // Note that we ran dexopt, since rerunning will 4622 // probably just result in an error again. 4623 pkg.mDexOptNeeded = false; 4624 if (ret < 0) { 4625 return DEX_OPT_FAILED; 4626 } 4627 return DEX_OPT_PERFORMED; 4628 } 4629 if (defer && isDexOptNeededInternal) { 4630 if (mDeferredDexOpt == null) { 4631 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4632 } 4633 mDeferredDexOpt.add(pkg); 4634 return DEX_OPT_DEFERRED; 4635 } 4636 pkg.mDexOptNeeded = false; 4637 return DEX_OPT_SKIPPED; 4638 } catch (FileNotFoundException e) { 4639 Slog.w(TAG, "Apk not found for dexopt: " + path); 4640 return DEX_OPT_FAILED; 4641 } catch (IOException e) { 4642 Slog.w(TAG, "IOException reading apk: " + path, e); 4643 return DEX_OPT_FAILED; 4644 } catch (StaleDexCacheError e) { 4645 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4646 return DEX_OPT_FAILED; 4647 } catch (Exception e) { 4648 Slog.w(TAG, "Exception when doing dexopt : ", e); 4649 return DEX_OPT_FAILED; 4650 } 4651 } 4652 } 4653 return DEX_OPT_SKIPPED; 4654 } 4655 4656 private String getAppInstructionSet(ApplicationInfo info) { 4657 String instructionSet = getPreferredInstructionSet(); 4658 4659 if (info.cpuAbi != null) { 4660 instructionSet = VMRuntime.getInstructionSet(info.cpuAbi); 4661 } 4662 4663 return instructionSet; 4664 } 4665 4666 private String getAppInstructionSetFromSettings(PackageSetting ps) { 4667 String instructionSet = getPreferredInstructionSet(); 4668 4669 if (ps.cpuAbiString != null) { 4670 instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 4671 } 4672 4673 return instructionSet; 4674 } 4675 4676 private static String getPreferredInstructionSet() { 4677 if (sPreferredInstructionSet == null) { 4678 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4679 } 4680 4681 return sPreferredInstructionSet; 4682 } 4683 4684 private static List<String> getAllInstructionSets() { 4685 final String[] allAbis = Build.SUPPORTED_ABIS; 4686 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4687 4688 for (String abi : allAbis) { 4689 final String instructionSet = VMRuntime.getInstructionSet(abi); 4690 if (!allInstructionSets.contains(instructionSet)) { 4691 allInstructionSets.add(instructionSet); 4692 } 4693 } 4694 4695 return allInstructionSets; 4696 } 4697 4698 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4699 boolean inclDependencies) { 4700 HashSet<String> done; 4701 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4702 done = new HashSet<String>(); 4703 done.add(pkg.packageName); 4704 } else { 4705 done = null; 4706 } 4707 return performDexOptLI(pkg, null /* instruction set override */, forceDex, defer, done); 4708 } 4709 4710 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4711 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4712 Slog.w(TAG, "Unable to update from " + oldPkg.name 4713 + " to " + newPkg.packageName 4714 + ": old package not in system partition"); 4715 return false; 4716 } else if (mPackages.get(oldPkg.name) != null) { 4717 Slog.w(TAG, "Unable to update from " + oldPkg.name 4718 + " to " + newPkg.packageName 4719 + ": old package still exists"); 4720 return false; 4721 } 4722 return true; 4723 } 4724 4725 File getDataPathForUser(int userId) { 4726 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4727 } 4728 4729 private File getDataPathForPackage(String packageName, int userId) { 4730 /* 4731 * Until we fully support multiple users, return the directory we 4732 * previously would have. The PackageManagerTests will need to be 4733 * revised when this is changed back.. 4734 */ 4735 if (userId == 0) { 4736 return new File(mAppDataDir, packageName); 4737 } else { 4738 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4739 + File.separator + packageName); 4740 } 4741 } 4742 4743 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4744 int[] users = sUserManager.getUserIds(); 4745 int res = mInstaller.install(packageName, uid, uid, seinfo); 4746 if (res < 0) { 4747 return res; 4748 } 4749 for (int user : users) { 4750 if (user != 0) { 4751 res = mInstaller.createUserData(packageName, 4752 UserHandle.getUid(user, uid), user, seinfo); 4753 if (res < 0) { 4754 return res; 4755 } 4756 } 4757 } 4758 return res; 4759 } 4760 4761 private int removeDataDirsLI(String packageName) { 4762 int[] users = sUserManager.getUserIds(); 4763 int res = 0; 4764 for (int user : users) { 4765 int resInner = mInstaller.remove(packageName, user); 4766 if (resInner < 0) { 4767 res = resInner; 4768 } 4769 } 4770 4771 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4772 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4773 if (!nativeLibraryFile.delete()) { 4774 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4775 } 4776 4777 return res; 4778 } 4779 4780 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4781 PackageParser.Package changingLib) { 4782 if (file.path != null) { 4783 usesLibraryFiles.add(file.path); 4784 return; 4785 } 4786 PackageParser.Package p = mPackages.get(file.apk); 4787 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4788 // If we are doing this while in the middle of updating a library apk, 4789 // then we need to make sure to use that new apk for determining the 4790 // dependencies here. (We haven't yet finished committing the new apk 4791 // to the package manager state.) 4792 if (p == null || p.packageName.equals(changingLib.packageName)) { 4793 p = changingLib; 4794 } 4795 } 4796 if (p != null) { 4797 usesLibraryFiles.addAll(p.getAllCodePaths()); 4798 } 4799 } 4800 4801 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4802 PackageParser.Package changingLib) { 4803 // We might be upgrading from a version of the platform that did not 4804 // provide per-package native library directories for system apps. 4805 // Fix that up here. 4806 if (isSystemApp(pkg)) { 4807 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4808 setInternalAppNativeLibraryPath(pkg, ps); 4809 } 4810 4811 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4812 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4813 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4814 for (int i=0; i<N; i++) { 4815 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4816 if (file == null) { 4817 Slog.e(TAG, "Package " + pkg.packageName 4818 + " requires unavailable shared library " 4819 + pkg.usesLibraries.get(i) + "; failing!"); 4820 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4821 return false; 4822 } 4823 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4824 } 4825 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4826 for (int i=0; i<N; i++) { 4827 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4828 if (file == null) { 4829 Slog.w(TAG, "Package " + pkg.packageName 4830 + " desires unavailable shared library " 4831 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4832 } else { 4833 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4834 } 4835 } 4836 N = usesLibraryFiles.size(); 4837 if (N > 0) { 4838 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4839 } else { 4840 pkg.usesLibraryFiles = null; 4841 } 4842 } 4843 return true; 4844 } 4845 4846 private static boolean hasString(List<String> list, List<String> which) { 4847 if (list == null) { 4848 return false; 4849 } 4850 for (int i=list.size()-1; i>=0; i--) { 4851 for (int j=which.size()-1; j>=0; j--) { 4852 if (which.get(j).equals(list.get(i))) { 4853 return true; 4854 } 4855 } 4856 } 4857 return false; 4858 } 4859 4860 private void updateAllSharedLibrariesLPw() { 4861 for (PackageParser.Package pkg : mPackages.values()) { 4862 updateSharedLibrariesLPw(pkg, null); 4863 } 4864 } 4865 4866 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4867 PackageParser.Package changingPkg) { 4868 ArrayList<PackageParser.Package> res = null; 4869 for (PackageParser.Package pkg : mPackages.values()) { 4870 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4871 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4872 if (res == null) { 4873 res = new ArrayList<PackageParser.Package>(); 4874 } 4875 res.add(pkg); 4876 updateSharedLibrariesLPw(pkg, changingPkg); 4877 } 4878 } 4879 return res; 4880 } 4881 4882 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4883 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4884 final File scanFile = new File(pkg.codePath); 4885 if (pkg.applicationInfo.sourceDir == null || 4886 pkg.applicationInfo.publicSourceDir == null) { 4887 // Bail out. The resource and code paths haven't been set. 4888 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4889 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4890 return null; 4891 } 4892 4893 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4894 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4895 } 4896 4897 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4898 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4899 } 4900 4901 if (mCustomResolverComponentName != null && 4902 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4903 setUpCustomResolverActivity(pkg); 4904 } 4905 4906 if (pkg.packageName.equals("android")) { 4907 synchronized (mPackages) { 4908 if (mAndroidApplication != null) { 4909 Slog.w(TAG, "*************************************************"); 4910 Slog.w(TAG, "Core android package being redefined. Skipping."); 4911 Slog.w(TAG, " file=" + scanFile); 4912 Slog.w(TAG, "*************************************************"); 4913 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4914 return null; 4915 } 4916 4917 // Set up information for our fall-back user intent resolution activity. 4918 mPlatformPackage = pkg; 4919 pkg.mVersionCode = mSdkVersion; 4920 mAndroidApplication = pkg.applicationInfo; 4921 4922 if (!mResolverReplaced) { 4923 mResolveActivity.applicationInfo = mAndroidApplication; 4924 mResolveActivity.name = ResolverActivity.class.getName(); 4925 mResolveActivity.packageName = mAndroidApplication.packageName; 4926 mResolveActivity.processName = "system:ui"; 4927 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4928 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 4929 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4930 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 4931 mResolveActivity.exported = true; 4932 mResolveActivity.enabled = true; 4933 mResolveInfo.activityInfo = mResolveActivity; 4934 mResolveInfo.priority = 0; 4935 mResolveInfo.preferredOrder = 0; 4936 mResolveInfo.match = 0; 4937 mResolveComponentName = new ComponentName( 4938 mAndroidApplication.packageName, mResolveActivity.name); 4939 } 4940 } 4941 } 4942 4943 if (DEBUG_PACKAGE_SCANNING) { 4944 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4945 Log.d(TAG, "Scanning package " + pkg.packageName); 4946 } 4947 4948 if (mPackages.containsKey(pkg.packageName) 4949 || mSharedLibraries.containsKey(pkg.packageName)) { 4950 Slog.w(TAG, "Application package " + pkg.packageName 4951 + " already installed. Skipping duplicate."); 4952 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4953 return null; 4954 } 4955 4956 // Initialize package source and resource directories 4957 File destCodeFile = new File(pkg.applicationInfo.sourceDir); 4958 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir); 4959 4960 SharedUserSetting suid = null; 4961 PackageSetting pkgSetting = null; 4962 4963 if (!isSystemApp(pkg)) { 4964 // Only system apps can use these features. 4965 pkg.mOriginalPackages = null; 4966 pkg.mRealPackage = null; 4967 pkg.mAdoptPermissions = null; 4968 } 4969 4970 // writer 4971 synchronized (mPackages) { 4972 if (pkg.mSharedUserId != null) { 4973 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 4974 if (suid == null) { 4975 Slog.w(TAG, "Creating application package " + pkg.packageName 4976 + " for shared user failed"); 4977 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4978 return null; 4979 } 4980 if (DEBUG_PACKAGE_SCANNING) { 4981 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4982 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 4983 + "): packages=" + suid.packages); 4984 } 4985 } 4986 4987 // Check if we are renaming from an original package name. 4988 PackageSetting origPackage = null; 4989 String realName = null; 4990 if (pkg.mOriginalPackages != null) { 4991 // This package may need to be renamed to a previously 4992 // installed name. Let's check on that... 4993 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 4994 if (pkg.mOriginalPackages.contains(renamed)) { 4995 // This package had originally been installed as the 4996 // original name, and we have already taken care of 4997 // transitioning to the new one. Just update the new 4998 // one to continue using the old name. 4999 realName = pkg.mRealPackage; 5000 if (!pkg.packageName.equals(renamed)) { 5001 // Callers into this function may have already taken 5002 // care of renaming the package; only do it here if 5003 // it is not already done. 5004 pkg.setPackageName(renamed); 5005 } 5006 5007 } else { 5008 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5009 if ((origPackage = mSettings.peekPackageLPr( 5010 pkg.mOriginalPackages.get(i))) != null) { 5011 // We do have the package already installed under its 5012 // original name... should we use it? 5013 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5014 // New package is not compatible with original. 5015 origPackage = null; 5016 continue; 5017 } else if (origPackage.sharedUser != null) { 5018 // Make sure uid is compatible between packages. 5019 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5020 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5021 + " to " + pkg.packageName + ": old uid " 5022 + origPackage.sharedUser.name 5023 + " differs from " + pkg.mSharedUserId); 5024 origPackage = null; 5025 continue; 5026 } 5027 } else { 5028 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5029 + pkg.packageName + " to old name " + origPackage.name); 5030 } 5031 break; 5032 } 5033 } 5034 } 5035 } 5036 5037 if (mTransferedPackages.contains(pkg.packageName)) { 5038 Slog.w(TAG, "Package " + pkg.packageName 5039 + " was transferred to another, but its .apk remains"); 5040 } 5041 5042 // Just create the setting, don't add it yet. For already existing packages 5043 // the PkgSetting exists already and doesn't have to be created. 5044 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5045 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 5046 pkg.applicationInfo.cpuAbi, 5047 pkg.applicationInfo.flags, user, false); 5048 if (pkgSetting == null) { 5049 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 5050 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5051 return null; 5052 } 5053 5054 if (pkgSetting.origPackage != null) { 5055 // If we are first transitioning from an original package, 5056 // fix up the new package's name now. We need to do this after 5057 // looking up the package under its new name, so getPackageLP 5058 // can take care of fiddling things correctly. 5059 pkg.setPackageName(origPackage.name); 5060 5061 // File a report about this. 5062 String msg = "New package " + pkgSetting.realName 5063 + " renamed to replace old package " + pkgSetting.name; 5064 reportSettingsProblem(Log.WARN, msg); 5065 5066 // Make a note of it. 5067 mTransferedPackages.add(origPackage.name); 5068 5069 // No longer need to retain this. 5070 pkgSetting.origPackage = null; 5071 } 5072 5073 if (realName != null) { 5074 // Make a note of it. 5075 mTransferedPackages.add(pkg.packageName); 5076 } 5077 5078 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5079 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5080 } 5081 5082 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5083 // Check all shared libraries and map to their actual file path. 5084 // We only do this here for apps not on a system dir, because those 5085 // are the only ones that can fail an install due to this. We 5086 // will take care of the system apps by updating all of their 5087 // library paths after the scan is done. 5088 if (!updateSharedLibrariesLPw(pkg, null)) { 5089 return null; 5090 } 5091 } 5092 5093 if (mFoundPolicyFile) { 5094 SELinuxMMAC.assignSeinfoValue(pkg); 5095 } 5096 5097 pkg.applicationInfo.uid = pkgSetting.appId; 5098 pkg.mExtras = pkgSetting; 5099 5100 if (!verifySignaturesLP(pkgSetting, pkg)) { 5101 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5102 return null; 5103 } 5104 // The signature has changed, but this package is in the system 5105 // image... let's recover! 5106 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5107 // However... if this package is part of a shared user, but it 5108 // doesn't match the signature of the shared user, let's fail. 5109 // What this means is that you can't change the signatures 5110 // associated with an overall shared user, which doesn't seem all 5111 // that unreasonable. 5112 if (pkgSetting.sharedUser != null) { 5113 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5114 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5115 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 5116 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 5117 return null; 5118 } 5119 } 5120 // File a report about this. 5121 String msg = "System package " + pkg.packageName 5122 + " signature changed; retaining data."; 5123 reportSettingsProblem(Log.WARN, msg); 5124 } 5125 5126 // Verify that this new package doesn't have any content providers 5127 // that conflict with existing packages. Only do this if the 5128 // package isn't already installed, since we don't want to break 5129 // things that are installed. 5130 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5131 final int N = pkg.providers.size(); 5132 int i; 5133 for (i=0; i<N; i++) { 5134 PackageParser.Provider p = pkg.providers.get(i); 5135 if (p.info.authority != null) { 5136 String names[] = p.info.authority.split(";"); 5137 for (int j = 0; j < names.length; j++) { 5138 if (mProvidersByAuthority.containsKey(names[j])) { 5139 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5140 Slog.w(TAG, "Can't install because provider name " + names[j] + 5141 " (in package " + pkg.applicationInfo.packageName + 5142 ") is already used by " 5143 + ((other != null && other.getComponentName() != null) 5144 ? other.getComponentName().getPackageName() : "?")); 5145 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 5146 return null; 5147 } 5148 } 5149 } 5150 } 5151 } 5152 5153 if (pkg.mAdoptPermissions != null) { 5154 // This package wants to adopt ownership of permissions from 5155 // another package. 5156 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5157 final String origName = pkg.mAdoptPermissions.get(i); 5158 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5159 if (orig != null) { 5160 if (verifyPackageUpdateLPr(orig, pkg)) { 5161 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5162 + pkg.packageName); 5163 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5164 } 5165 } 5166 } 5167 } 5168 } 5169 5170 final String pkgName = pkg.packageName; 5171 5172 final long scanFileTime = scanFile.lastModified(); 5173 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5174 pkg.applicationInfo.processName = fixProcessName( 5175 pkg.applicationInfo.packageName, 5176 pkg.applicationInfo.processName, 5177 pkg.applicationInfo.uid); 5178 5179 File dataPath; 5180 if (mPlatformPackage == pkg) { 5181 // The system package is special. 5182 dataPath = new File (Environment.getDataDirectory(), "system"); 5183 pkg.applicationInfo.dataDir = dataPath.getPath(); 5184 } else { 5185 // This is a normal package, need to make its data directory. 5186 dataPath = getDataPathForPackage(pkg.packageName, 0); 5187 5188 boolean uidError = false; 5189 5190 if (dataPath.exists()) { 5191 int currentUid = 0; 5192 try { 5193 StructStat stat = Os.stat(dataPath.getPath()); 5194 currentUid = stat.st_uid; 5195 } catch (ErrnoException e) { 5196 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5197 } 5198 5199 // If we have mismatched owners for the data path, we have a problem. 5200 if (currentUid != pkg.applicationInfo.uid) { 5201 boolean recovered = false; 5202 if (currentUid == 0) { 5203 // The directory somehow became owned by root. Wow. 5204 // This is probably because the system was stopped while 5205 // installd was in the middle of messing with its libs 5206 // directory. Ask installd to fix that. 5207 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5208 pkg.applicationInfo.uid); 5209 if (ret >= 0) { 5210 recovered = true; 5211 String msg = "Package " + pkg.packageName 5212 + " unexpectedly changed to uid 0; recovered to " + 5213 + pkg.applicationInfo.uid; 5214 reportSettingsProblem(Log.WARN, msg); 5215 } 5216 } 5217 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5218 || (scanMode&SCAN_BOOTING) != 0)) { 5219 // If this is a system app, we can at least delete its 5220 // current data so the application will still work. 5221 int ret = removeDataDirsLI(pkgName); 5222 if (ret >= 0) { 5223 // TODO: Kill the processes first 5224 // Old data gone! 5225 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5226 ? "System package " : "Third party package "; 5227 String msg = prefix + pkg.packageName 5228 + " has changed from uid: " 5229 + currentUid + " to " 5230 + pkg.applicationInfo.uid + "; old data erased"; 5231 reportSettingsProblem(Log.WARN, msg); 5232 recovered = true; 5233 5234 // And now re-install the app. 5235 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5236 pkg.applicationInfo.seinfo); 5237 if (ret == -1) { 5238 // Ack should not happen! 5239 msg = prefix + pkg.packageName 5240 + " could not have data directory re-created after delete."; 5241 reportSettingsProblem(Log.WARN, msg); 5242 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5243 return null; 5244 } 5245 } 5246 if (!recovered) { 5247 mHasSystemUidErrors = true; 5248 } 5249 } else if (!recovered) { 5250 // If we allow this install to proceed, we will be broken. 5251 // Abort, abort! 5252 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 5253 return null; 5254 } 5255 if (!recovered) { 5256 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5257 + pkg.applicationInfo.uid + "/fs_" 5258 + currentUid; 5259 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5260 String msg = "Package " + pkg.packageName 5261 + " has mismatched uid: " 5262 + currentUid + " on disk, " 5263 + pkg.applicationInfo.uid + " in settings"; 5264 // writer 5265 synchronized (mPackages) { 5266 mSettings.mReadMessages.append(msg); 5267 mSettings.mReadMessages.append('\n'); 5268 uidError = true; 5269 if (!pkgSetting.uidError) { 5270 reportSettingsProblem(Log.ERROR, msg); 5271 } 5272 } 5273 } 5274 } 5275 pkg.applicationInfo.dataDir = dataPath.getPath(); 5276 if (mShouldRestoreconData) { 5277 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5278 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5279 pkg.applicationInfo.uid); 5280 } 5281 } else { 5282 if (DEBUG_PACKAGE_SCANNING) { 5283 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5284 Log.v(TAG, "Want this data dir: " + dataPath); 5285 } 5286 //invoke installer to do the actual installation 5287 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5288 pkg.applicationInfo.seinfo); 5289 if (ret < 0) { 5290 // Error from installer 5291 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5292 return null; 5293 } 5294 5295 if (dataPath.exists()) { 5296 pkg.applicationInfo.dataDir = dataPath.getPath(); 5297 } else { 5298 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5299 pkg.applicationInfo.dataDir = null; 5300 } 5301 } 5302 5303 /* 5304 * Set the data dir to the default "/data/data/<package name>/lib" 5305 * if we got here without anyone telling us different (e.g., apps 5306 * stored on SD card have their native libraries stored in the ASEC 5307 * container with the APK). 5308 * 5309 * This happens during an upgrade from a package settings file that 5310 * doesn't have a native library path attribute at all. 5311 */ 5312 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 5313 if (pkgSetting.nativeLibraryPathString == null) { 5314 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5315 } else { 5316 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 5317 } 5318 } 5319 pkgSetting.uidError = uidError; 5320 } 5321 5322 final String path = scanFile.getPath(); 5323 /* Note: We don't want to unpack the native binaries for 5324 * system applications, unless they have been updated 5325 * (the binaries are already under /system/lib). 5326 * Also, don't unpack libs for apps on the external card 5327 * since they should have their libraries in the ASEC 5328 * container already. 5329 * 5330 * In other words, we're going to unpack the binaries 5331 * only for non-system apps and system app upgrades. 5332 */ 5333 if (pkg.applicationInfo.nativeLibraryDir != null) { 5334 // TODO: extend to extract native code from split APKs 5335 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile); 5336 try { 5337 // Enable gross and lame hacks for apps that are built with old 5338 // SDK tools. We must scan their APKs for renderscript bitcode and 5339 // not launch them if it's present. Don't bother checking on devices 5340 // that don't have 64 bit support. 5341 String[] abiList = Build.SUPPORTED_ABIS; 5342 boolean hasLegacyRenderscriptBitcode = false; 5343 if (abiOverride != null) { 5344 abiList = new String[] { abiOverride }; 5345 } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 5346 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5347 abiList = Build.SUPPORTED_32_BIT_ABIS; 5348 hasLegacyRenderscriptBitcode = true; 5349 } 5350 5351 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5352 final String dataPathString = dataPath.getCanonicalPath(); 5353 5354 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5355 /* 5356 * Upgrading from a previous version of the OS sometimes 5357 * leaves native libraries in the /data/data/<app>/lib 5358 * directory for system apps even when they shouldn't be. 5359 * Recent changes in the JNI library search path 5360 * necessitates we remove those to match previous behavior. 5361 */ 5362 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 5363 Log.i(TAG, "removed obsolete native libraries for system package " 5364 + path); 5365 } 5366 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5367 pkg.applicationInfo.cpuAbi = abiList[0]; 5368 pkgSetting.cpuAbiString = abiList[0]; 5369 } else { 5370 setInternalAppAbi(pkg, pkgSetting); 5371 } 5372 } else { 5373 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 5374 /* 5375 * Update native library dir if it starts with 5376 * /data/data 5377 */ 5378 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 5379 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5380 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5381 } 5382 5383 try { 5384 int copyRet = copyNativeLibrariesForInternalApp(handle, 5385 nativeLibraryDir, abiList); 5386 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5387 Slog.e(TAG, "Unable to copy native libraries"); 5388 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5389 return null; 5390 } 5391 5392 // We've successfully copied native libraries across, so we make a 5393 // note of what ABI we're using 5394 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5395 pkg.applicationInfo.cpuAbi = abiList[copyRet]; 5396 } else if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5397 pkg.applicationInfo.cpuAbi = abiList[0]; 5398 } else { 5399 pkg.applicationInfo.cpuAbi = null; 5400 } 5401 } catch (IOException e) { 5402 Slog.e(TAG, "Unable to copy native libraries", e); 5403 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5404 return null; 5405 } 5406 } else { 5407 // We don't have to copy the shared libraries if we're in the ASEC container 5408 // but we still need to scan the file to figure out what ABI the app needs. 5409 // 5410 // TODO: This duplicates work done in the default container service. It's possible 5411 // to clean this up but we'll need to change the interface between this service 5412 // and IMediaContainerService (but doing so will spread this logic out, rather 5413 // than centralizing it). 5414 final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5415 if (abi >= 0) { 5416 pkg.applicationInfo.cpuAbi = abiList[abi]; 5417 } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) { 5418 // Note that (non upgraded) system apps will not have any native 5419 // libraries bundled in their APK, but we're guaranteed not to be 5420 // such an app at this point. 5421 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5422 pkg.applicationInfo.cpuAbi = abiList[0]; 5423 } else { 5424 pkg.applicationInfo.cpuAbi = null; 5425 } 5426 } else { 5427 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5428 return null; 5429 } 5430 } 5431 5432 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5433 final int[] userIds = sUserManager.getUserIds(); 5434 synchronized (mInstallLock) { 5435 for (int userId : userIds) { 5436 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 5437 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 5438 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5439 + ")"); 5440 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5441 return null; 5442 } 5443 } 5444 } 5445 } 5446 5447 pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi; 5448 } catch (IOException ioe) { 5449 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5450 } finally { 5451 handle.close(); 5452 } 5453 } 5454 5455 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5456 // We don't do this here during boot because we can do it all 5457 // at once after scanning all existing packages. 5458 // 5459 // We also do this *before* we perform dexopt on this package, so that 5460 // we can avoid redundant dexopts, and also to make sure we've got the 5461 // code and package path correct. 5462 if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5463 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) { 5464 mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE; 5465 return null; 5466 } 5467 } 5468 5469 if ((scanMode&SCAN_NO_DEX) == 0) { 5470 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5471 == DEX_OPT_FAILED) { 5472 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5473 removeDataDirsLI(pkg.packageName); 5474 } 5475 5476 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5477 return null; 5478 } 5479 } 5480 5481 if (mFactoryTest && pkg.requestedPermissions.contains( 5482 android.Manifest.permission.FACTORY_TEST)) { 5483 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5484 } 5485 5486 ArrayList<PackageParser.Package> clientLibPkgs = null; 5487 5488 // writer 5489 synchronized (mPackages) { 5490 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5491 // Only system apps can add new shared libraries. 5492 if (pkg.libraryNames != null) { 5493 for (int i=0; i<pkg.libraryNames.size(); i++) { 5494 String name = pkg.libraryNames.get(i); 5495 boolean allowed = false; 5496 if (isUpdatedSystemApp(pkg)) { 5497 // New library entries can only be added through the 5498 // system image. This is important to get rid of a lot 5499 // of nasty edge cases: for example if we allowed a non- 5500 // system update of the app to add a library, then uninstalling 5501 // the update would make the library go away, and assumptions 5502 // we made such as through app install filtering would now 5503 // have allowed apps on the device which aren't compatible 5504 // with it. Better to just have the restriction here, be 5505 // conservative, and create many fewer cases that can negatively 5506 // impact the user experience. 5507 final PackageSetting sysPs = mSettings 5508 .getDisabledSystemPkgLPr(pkg.packageName); 5509 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5510 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5511 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5512 allowed = true; 5513 allowed = true; 5514 break; 5515 } 5516 } 5517 } 5518 } else { 5519 allowed = true; 5520 } 5521 if (allowed) { 5522 if (!mSharedLibraries.containsKey(name)) { 5523 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5524 } else if (!name.equals(pkg.packageName)) { 5525 Slog.w(TAG, "Package " + pkg.packageName + " library " 5526 + name + " already exists; skipping"); 5527 } 5528 } else { 5529 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5530 + name + " that is not declared on system image; skipping"); 5531 } 5532 } 5533 if ((scanMode&SCAN_BOOTING) == 0) { 5534 // If we are not booting, we need to update any applications 5535 // that are clients of our shared library. If we are booting, 5536 // this will all be done once the scan is complete. 5537 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5538 } 5539 } 5540 } 5541 } 5542 5543 // We also need to dexopt any apps that are dependent on this library. Note that 5544 // if these fail, we should abort the install since installing the library will 5545 // result in some apps being broken. 5546 if (clientLibPkgs != null) { 5547 if ((scanMode&SCAN_NO_DEX) == 0) { 5548 for (int i=0; i<clientLibPkgs.size(); i++) { 5549 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5550 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5551 == DEX_OPT_FAILED) { 5552 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5553 removeDataDirsLI(pkg.packageName); 5554 } 5555 5556 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5557 return null; 5558 } 5559 } 5560 } 5561 } 5562 5563 // Request the ActivityManager to kill the process(only for existing packages) 5564 // so that we do not end up in a confused state while the user is still using the older 5565 // version of the application while the new one gets installed. 5566 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5567 // If the package lives in an asec, tell everyone that the container is going 5568 // away so they can clean up any references to its resources (which would prevent 5569 // vold from being able to unmount the asec) 5570 if (isForwardLocked(pkg) || isExternal(pkg)) { 5571 if (DEBUG_INSTALL) { 5572 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5573 } 5574 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5575 final ArrayList<String> pkgList = new ArrayList<String>(1); 5576 pkgList.add(pkg.applicationInfo.packageName); 5577 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5578 } 5579 5580 // Post the request that it be killed now that the going-away broadcast is en route 5581 killApplication(pkg.applicationInfo.packageName, 5582 pkg.applicationInfo.uid, "update pkg"); 5583 } 5584 5585 // Also need to kill any apps that are dependent on the library. 5586 if (clientLibPkgs != null) { 5587 for (int i=0; i<clientLibPkgs.size(); i++) { 5588 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5589 killApplication(clientPkg.applicationInfo.packageName, 5590 clientPkg.applicationInfo.uid, "update lib"); 5591 } 5592 } 5593 5594 // writer 5595 synchronized (mPackages) { 5596 // We don't expect installation to fail beyond this point, 5597 if ((scanMode&SCAN_MONITOR) != 0) { 5598 mAppDirs.put(pkg.codePath, pkg); 5599 } 5600 // Add the new setting to mSettings 5601 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5602 // Add the new setting to mPackages 5603 mPackages.put(pkg.applicationInfo.packageName, pkg); 5604 // Make sure we don't accidentally delete its data. 5605 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5606 while (iter.hasNext()) { 5607 PackageCleanItem item = iter.next(); 5608 if (pkgName.equals(item.packageName)) { 5609 iter.remove(); 5610 } 5611 } 5612 5613 // Take care of first install / last update times. 5614 if (currentTime != 0) { 5615 if (pkgSetting.firstInstallTime == 0) { 5616 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5617 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5618 pkgSetting.lastUpdateTime = currentTime; 5619 } 5620 } else if (pkgSetting.firstInstallTime == 0) { 5621 // We need *something*. Take time time stamp of the file. 5622 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5623 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5624 if (scanFileTime != pkgSetting.timeStamp) { 5625 // A package on the system image has changed; consider this 5626 // to be an update. 5627 pkgSetting.lastUpdateTime = scanFileTime; 5628 } 5629 } 5630 5631 // Add the package's KeySets to the global KeySetManager 5632 KeySetManager ksm = mSettings.mKeySetManager; 5633 try { 5634 ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5635 if (pkg.mKeySetMapping != null) { 5636 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5637 pkg.mKeySetMapping.entrySet()) { 5638 if (entry.getValue() != null) { 5639 ksm.addDefinedKeySetToPackage(pkg.packageName, 5640 entry.getValue(), entry.getKey()); 5641 } 5642 } 5643 } 5644 } catch (NullPointerException e) { 5645 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5646 } catch (IllegalArgumentException e) { 5647 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5648 } 5649 5650 int N = pkg.providers.size(); 5651 StringBuilder r = null; 5652 int i; 5653 for (i=0; i<N; i++) { 5654 PackageParser.Provider p = pkg.providers.get(i); 5655 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5656 p.info.processName, pkg.applicationInfo.uid); 5657 mProviders.addProvider(p); 5658 p.syncable = p.info.isSyncable; 5659 if (p.info.authority != null) { 5660 String names[] = p.info.authority.split(";"); 5661 p.info.authority = null; 5662 for (int j = 0; j < names.length; j++) { 5663 if (j == 1 && p.syncable) { 5664 // We only want the first authority for a provider to possibly be 5665 // syncable, so if we already added this provider using a different 5666 // authority clear the syncable flag. We copy the provider before 5667 // changing it because the mProviders object contains a reference 5668 // to a provider that we don't want to change. 5669 // Only do this for the second authority since the resulting provider 5670 // object can be the same for all future authorities for this provider. 5671 p = new PackageParser.Provider(p); 5672 p.syncable = false; 5673 } 5674 if (!mProvidersByAuthority.containsKey(names[j])) { 5675 mProvidersByAuthority.put(names[j], p); 5676 if (p.info.authority == null) { 5677 p.info.authority = names[j]; 5678 } else { 5679 p.info.authority = p.info.authority + ";" + names[j]; 5680 } 5681 if (DEBUG_PACKAGE_SCANNING) { 5682 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5683 Log.d(TAG, "Registered content provider: " + names[j] 5684 + ", className = " + p.info.name + ", isSyncable = " 5685 + p.info.isSyncable); 5686 } 5687 } else { 5688 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5689 Slog.w(TAG, "Skipping provider name " + names[j] + 5690 " (in package " + pkg.applicationInfo.packageName + 5691 "): name already used by " 5692 + ((other != null && other.getComponentName() != null) 5693 ? other.getComponentName().getPackageName() : "?")); 5694 } 5695 } 5696 } 5697 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5698 if (r == null) { 5699 r = new StringBuilder(256); 5700 } else { 5701 r.append(' '); 5702 } 5703 r.append(p.info.name); 5704 } 5705 } 5706 if (r != null) { 5707 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5708 } 5709 5710 N = pkg.services.size(); 5711 r = null; 5712 for (i=0; i<N; i++) { 5713 PackageParser.Service s = pkg.services.get(i); 5714 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5715 s.info.processName, pkg.applicationInfo.uid); 5716 mServices.addService(s); 5717 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5718 if (r == null) { 5719 r = new StringBuilder(256); 5720 } else { 5721 r.append(' '); 5722 } 5723 r.append(s.info.name); 5724 } 5725 } 5726 if (r != null) { 5727 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5728 } 5729 5730 N = pkg.receivers.size(); 5731 r = null; 5732 for (i=0; i<N; i++) { 5733 PackageParser.Activity a = pkg.receivers.get(i); 5734 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5735 a.info.processName, pkg.applicationInfo.uid); 5736 mReceivers.addActivity(a, "receiver"); 5737 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5738 if (r == null) { 5739 r = new StringBuilder(256); 5740 } else { 5741 r.append(' '); 5742 } 5743 r.append(a.info.name); 5744 } 5745 } 5746 if (r != null) { 5747 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5748 } 5749 5750 N = pkg.activities.size(); 5751 r = null; 5752 for (i=0; i<N; i++) { 5753 PackageParser.Activity a = pkg.activities.get(i); 5754 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5755 a.info.processName, pkg.applicationInfo.uid); 5756 mActivities.addActivity(a, "activity"); 5757 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5758 if (r == null) { 5759 r = new StringBuilder(256); 5760 } else { 5761 r.append(' '); 5762 } 5763 r.append(a.info.name); 5764 } 5765 } 5766 if (r != null) { 5767 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5768 } 5769 5770 N = pkg.permissionGroups.size(); 5771 r = null; 5772 for (i=0; i<N; i++) { 5773 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5774 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5775 if (cur == null) { 5776 mPermissionGroups.put(pg.info.name, pg); 5777 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5778 if (r == null) { 5779 r = new StringBuilder(256); 5780 } else { 5781 r.append(' '); 5782 } 5783 r.append(pg.info.name); 5784 } 5785 } else { 5786 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5787 + pg.info.packageName + " ignored: original from " 5788 + cur.info.packageName); 5789 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5790 if (r == null) { 5791 r = new StringBuilder(256); 5792 } else { 5793 r.append(' '); 5794 } 5795 r.append("DUP:"); 5796 r.append(pg.info.name); 5797 } 5798 } 5799 } 5800 if (r != null) { 5801 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5802 } 5803 5804 N = pkg.permissions.size(); 5805 r = null; 5806 for (i=0; i<N; i++) { 5807 PackageParser.Permission p = pkg.permissions.get(i); 5808 HashMap<String, BasePermission> permissionMap = 5809 p.tree ? mSettings.mPermissionTrees 5810 : mSettings.mPermissions; 5811 p.group = mPermissionGroups.get(p.info.group); 5812 if (p.info.group == null || p.group != null) { 5813 BasePermission bp = permissionMap.get(p.info.name); 5814 if (bp == null) { 5815 bp = new BasePermission(p.info.name, p.info.packageName, 5816 BasePermission.TYPE_NORMAL); 5817 permissionMap.put(p.info.name, bp); 5818 } 5819 if (bp.perm == null) { 5820 if (bp.sourcePackage != null 5821 && !bp.sourcePackage.equals(p.info.packageName)) { 5822 // If this is a permission that was formerly defined by a non-system 5823 // app, but is now defined by a system app (following an upgrade), 5824 // discard the previous declaration and consider the system's to be 5825 // canonical. 5826 if (isSystemApp(p.owner)) { 5827 String msg = "New decl " + p.owner + " of permission " 5828 + p.info.name + " is system"; 5829 reportSettingsProblem(Log.WARN, msg); 5830 bp.sourcePackage = null; 5831 } 5832 } 5833 if (bp.sourcePackage == null 5834 || bp.sourcePackage.equals(p.info.packageName)) { 5835 BasePermission tree = findPermissionTreeLP(p.info.name); 5836 if (tree == null 5837 || tree.sourcePackage.equals(p.info.packageName)) { 5838 bp.packageSetting = pkgSetting; 5839 bp.perm = p; 5840 bp.uid = pkg.applicationInfo.uid; 5841 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5842 if (r == null) { 5843 r = new StringBuilder(256); 5844 } else { 5845 r.append(' '); 5846 } 5847 r.append(p.info.name); 5848 } 5849 } else { 5850 Slog.w(TAG, "Permission " + p.info.name + " from package " 5851 + p.info.packageName + " ignored: base tree " 5852 + tree.name + " is from package " 5853 + tree.sourcePackage); 5854 } 5855 } else { 5856 Slog.w(TAG, "Permission " + p.info.name + " from package " 5857 + p.info.packageName + " ignored: original from " 5858 + bp.sourcePackage); 5859 } 5860 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5861 if (r == null) { 5862 r = new StringBuilder(256); 5863 } else { 5864 r.append(' '); 5865 } 5866 r.append("DUP:"); 5867 r.append(p.info.name); 5868 } 5869 if (bp.perm == p) { 5870 bp.protectionLevel = p.info.protectionLevel; 5871 } 5872 } else { 5873 Slog.w(TAG, "Permission " + p.info.name + " from package " 5874 + p.info.packageName + " ignored: no group " 5875 + p.group); 5876 } 5877 } 5878 if (r != null) { 5879 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5880 } 5881 5882 N = pkg.instrumentation.size(); 5883 r = null; 5884 for (i=0; i<N; i++) { 5885 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5886 a.info.packageName = pkg.applicationInfo.packageName; 5887 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5888 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5889 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 5890 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 5891 a.info.dataDir = pkg.applicationInfo.dataDir; 5892 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5893 mInstrumentation.put(a.getComponentName(), a); 5894 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5895 if (r == null) { 5896 r = new StringBuilder(256); 5897 } else { 5898 r.append(' '); 5899 } 5900 r.append(a.info.name); 5901 } 5902 } 5903 if (r != null) { 5904 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5905 } 5906 5907 if (pkg.protectedBroadcasts != null) { 5908 N = pkg.protectedBroadcasts.size(); 5909 for (i=0; i<N; i++) { 5910 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5911 } 5912 } 5913 5914 pkgSetting.setTimeStamp(scanFileTime); 5915 5916 // Create idmap files for pairs of (packages, overlay packages). 5917 // Note: "android", ie framework-res.apk, is handled by native layers. 5918 if (pkg.mOverlayTarget != null) { 5919 // This is an overlay package. 5920 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 5921 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 5922 mOverlays.put(pkg.mOverlayTarget, 5923 new HashMap<String, PackageParser.Package>()); 5924 } 5925 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 5926 map.put(pkg.packageName, pkg); 5927 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 5928 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 5929 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5930 return null; 5931 } 5932 } 5933 } else if (mOverlays.containsKey(pkg.packageName) && 5934 !pkg.packageName.equals("android")) { 5935 // This is a regular package, with one or more known overlay packages. 5936 createIdmapsForPackageLI(pkg); 5937 } 5938 } 5939 5940 return pkg; 5941 } 5942 5943 /** 5944 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 5945 * i.e, so that all packages can be run inside a single process if required. 5946 * 5947 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 5948 * this function will either try and make the ABI for all packages in {@code packagesForUser} 5949 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 5950 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 5951 * updating a package that belongs to a shared user. 5952 */ 5953 private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 5954 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 5955 String requiredInstructionSet = null; 5956 if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) { 5957 requiredInstructionSet = VMRuntime.getInstructionSet( 5958 scannedPackage.applicationInfo.cpuAbi); 5959 } 5960 5961 PackageSetting requirer = null; 5962 for (PackageSetting ps : packagesForUser) { 5963 // If packagesForUser contains scannedPackage, we skip it. This will happen 5964 // when scannedPackage is an update of an existing package. Without this check, 5965 // we will never be able to change the ABI of any package belonging to a shared 5966 // user, even if it's compatible with other packages. 5967 if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) { 5968 if (ps.cpuAbiString == null) { 5969 continue; 5970 } 5971 5972 final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 5973 if (requiredInstructionSet != null) { 5974 if (!instructionSet.equals(requiredInstructionSet)) { 5975 // We have a mismatch between instruction sets (say arm vs arm64). 5976 // bail out. 5977 String errorMessage = "Instruction set mismatch, " 5978 + ((requirer == null) ? "[caller]" : requirer) 5979 + " requires " + requiredInstructionSet + " whereas " + ps 5980 + " requires " + instructionSet; 5981 Slog.e(TAG, errorMessage); 5982 5983 reportSettingsProblem(Log.WARN, errorMessage); 5984 // Give up, don't bother making any other changes to the package settings. 5985 return false; 5986 } 5987 } else { 5988 requiredInstructionSet = instructionSet; 5989 requirer = ps; 5990 } 5991 } 5992 } 5993 5994 if (requiredInstructionSet != null) { 5995 String adjustedAbi; 5996 if (requirer != null) { 5997 // requirer != null implies that either scannedPackage was null or that scannedPackage 5998 // did not require an ABI, in which case we have to adjust scannedPackage to match 5999 // the ABI of the set (which is the same as requirer's ABI) 6000 adjustedAbi = requirer.cpuAbiString; 6001 if (scannedPackage != null) { 6002 scannedPackage.applicationInfo.cpuAbi = adjustedAbi; 6003 } 6004 } else { 6005 // requirer == null implies that we're updating all ABIs in the set to 6006 // match scannedPackage. 6007 adjustedAbi = scannedPackage.applicationInfo.cpuAbi; 6008 } 6009 6010 for (PackageSetting ps : packagesForUser) { 6011 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6012 if (ps.cpuAbiString != null) { 6013 continue; 6014 } 6015 6016 ps.cpuAbiString = adjustedAbi; 6017 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6018 ps.pkg.applicationInfo.cpuAbi = adjustedAbi; 6019 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6020 6021 if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) { 6022 ps.cpuAbiString = null; 6023 ps.pkg.applicationInfo.cpuAbi = null; 6024 return false; 6025 } else { 6026 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6027 } 6028 } 6029 } 6030 } 6031 } 6032 6033 return true; 6034 } 6035 6036 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6037 synchronized (mPackages) { 6038 mResolverReplaced = true; 6039 // Set up information for custom user intent resolution activity. 6040 mResolveActivity.applicationInfo = pkg.applicationInfo; 6041 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6042 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6043 mResolveActivity.processName = null; 6044 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6045 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6046 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6047 mResolveActivity.theme = 0; 6048 mResolveActivity.exported = true; 6049 mResolveActivity.enabled = true; 6050 mResolveInfo.activityInfo = mResolveActivity; 6051 mResolveInfo.priority = 0; 6052 mResolveInfo.preferredOrder = 0; 6053 mResolveInfo.match = 0; 6054 mResolveComponentName = mCustomResolverComponentName; 6055 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6056 mResolveComponentName); 6057 } 6058 } 6059 6060 private String calculateApkRoot(final String codePathString) { 6061 final File codePath = new File(codePathString); 6062 final File codeRoot; 6063 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6064 codeRoot = Environment.getRootDirectory(); 6065 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6066 codeRoot = Environment.getOemDirectory(); 6067 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6068 codeRoot = Environment.getVendorDirectory(); 6069 } else { 6070 // Unrecognized code path; take its top real segment as the apk root: 6071 // e.g. /something/app/blah.apk => /something 6072 try { 6073 File f = codePath.getCanonicalFile(); 6074 File parent = f.getParentFile(); // non-null because codePath is a file 6075 File tmp; 6076 while ((tmp = parent.getParentFile()) != null) { 6077 f = parent; 6078 parent = tmp; 6079 } 6080 codeRoot = f; 6081 Slog.w(TAG, "Unrecognized code path " 6082 + codePath + " - using " + codeRoot); 6083 } catch (IOException e) { 6084 // Can't canonicalize the lib path -- shenanigans? 6085 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6086 return Environment.getRootDirectory().getPath(); 6087 } 6088 } 6089 return codeRoot.getPath(); 6090 } 6091 6092 // This is the initial scan-time determination of how to handle a given 6093 // package for purposes of native library location. 6094 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 6095 PackageSetting pkgSetting) { 6096 // "bundled" here means system-installed with no overriding update 6097 final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg); 6098 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 6099 final File libDir; 6100 if (bundledApk) { 6101 // If "/system/lib64/apkname" exists, assume that is the per-package 6102 // native library directory to use; otherwise use "/system/lib/apkname". 6103 String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6104 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 6105 File packLib64 = new File(lib64, apkName); 6106 libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 6107 } else { 6108 libDir = mAppLibInstallDir; 6109 } 6110 final String nativeLibraryPath = (new File(libDir, apkName)).getPath(); 6111 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 6112 // pkgSetting might be null during rescan following uninstall of updates 6113 // to a bundled app, so accommodate that possibility. The settings in 6114 // that case will be established later from the parsed package. 6115 if (pkgSetting != null) { 6116 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 6117 } 6118 } 6119 6120 // Deduces the required ABI of an upgraded system app. 6121 private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) { 6122 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6123 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 6124 6125 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 6126 // or similar. 6127 final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath()); 6128 final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath()); 6129 6130 // Assume that the bundled native libraries always correspond to the 6131 // most preferred 32 or 64 bit ABI. 6132 if (lib64.exists()) { 6133 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6134 pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0]; 6135 } else if (lib.exists()) { 6136 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6137 pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0]; 6138 } else { 6139 // This is the case where the app has no native code. 6140 pkg.applicationInfo.cpuAbi = null; 6141 pkgSetting.cpuAbiString = null; 6142 } 6143 } 6144 6145 private static int copyNativeLibrariesForInternalApp(ApkHandle handle, 6146 final File nativeLibraryDir, String[] abiList) throws IOException { 6147 if (!nativeLibraryDir.isDirectory()) { 6148 nativeLibraryDir.delete(); 6149 6150 if (!nativeLibraryDir.mkdir()) { 6151 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 6152 } 6153 6154 try { 6155 Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6156 } catch (ErrnoException e) { 6157 throw new IOException("Cannot chmod native library directory " 6158 + nativeLibraryDir.getPath(), e); 6159 } 6160 } else if (!SELinux.restorecon(nativeLibraryDir)) { 6161 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 6162 } 6163 6164 /* 6165 * If this is an internal application or our nativeLibraryPath points to 6166 * the app-lib directory, unpack the libraries if necessary. 6167 */ 6168 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6169 if (abi >= 0) { 6170 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 6171 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 6172 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6173 return copyRet; 6174 } 6175 } 6176 6177 return abi; 6178 } 6179 6180 private void killApplication(String pkgName, int appId, String reason) { 6181 // Request the ActivityManager to kill the process(only for existing packages) 6182 // so that we do not end up in a confused state while the user is still using the older 6183 // version of the application while the new one gets installed. 6184 IActivityManager am = ActivityManagerNative.getDefault(); 6185 if (am != null) { 6186 try { 6187 am.killApplicationWithAppId(pkgName, appId, reason); 6188 } catch (RemoteException e) { 6189 } 6190 } 6191 } 6192 6193 void removePackageLI(PackageSetting ps, boolean chatty) { 6194 if (DEBUG_INSTALL) { 6195 if (chatty) 6196 Log.d(TAG, "Removing package " + ps.name); 6197 } 6198 6199 // writer 6200 synchronized (mPackages) { 6201 mPackages.remove(ps.name); 6202 if (ps.codePathString != null) { 6203 mAppDirs.remove(ps.codePathString); 6204 } 6205 6206 final PackageParser.Package pkg = ps.pkg; 6207 if (pkg != null) { 6208 cleanPackageDataStructuresLILPw(pkg, chatty); 6209 } 6210 } 6211 } 6212 6213 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6214 if (DEBUG_INSTALL) { 6215 if (chatty) 6216 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6217 } 6218 6219 // writer 6220 synchronized (mPackages) { 6221 mPackages.remove(pkg.applicationInfo.packageName); 6222 if (pkg.codePath != null) { 6223 mAppDirs.remove(pkg.codePath); 6224 } 6225 cleanPackageDataStructuresLILPw(pkg, chatty); 6226 } 6227 } 6228 6229 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6230 int N = pkg.providers.size(); 6231 StringBuilder r = null; 6232 int i; 6233 for (i=0; i<N; i++) { 6234 PackageParser.Provider p = pkg.providers.get(i); 6235 mProviders.removeProvider(p); 6236 if (p.info.authority == null) { 6237 6238 /* There was another ContentProvider with this authority when 6239 * this app was installed so this authority is null, 6240 * Ignore it as we don't have to unregister the provider. 6241 */ 6242 continue; 6243 } 6244 String names[] = p.info.authority.split(";"); 6245 for (int j = 0; j < names.length; j++) { 6246 if (mProvidersByAuthority.get(names[j]) == p) { 6247 mProvidersByAuthority.remove(names[j]); 6248 if (DEBUG_REMOVE) { 6249 if (chatty) 6250 Log.d(TAG, "Unregistered content provider: " + names[j] 6251 + ", className = " + p.info.name + ", isSyncable = " 6252 + p.info.isSyncable); 6253 } 6254 } 6255 } 6256 if (DEBUG_REMOVE && chatty) { 6257 if (r == null) { 6258 r = new StringBuilder(256); 6259 } else { 6260 r.append(' '); 6261 } 6262 r.append(p.info.name); 6263 } 6264 } 6265 if (r != null) { 6266 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6267 } 6268 6269 N = pkg.services.size(); 6270 r = null; 6271 for (i=0; i<N; i++) { 6272 PackageParser.Service s = pkg.services.get(i); 6273 mServices.removeService(s); 6274 if (chatty) { 6275 if (r == null) { 6276 r = new StringBuilder(256); 6277 } else { 6278 r.append(' '); 6279 } 6280 r.append(s.info.name); 6281 } 6282 } 6283 if (r != null) { 6284 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6285 } 6286 6287 N = pkg.receivers.size(); 6288 r = null; 6289 for (i=0; i<N; i++) { 6290 PackageParser.Activity a = pkg.receivers.get(i); 6291 mReceivers.removeActivity(a, "receiver"); 6292 if (DEBUG_REMOVE && chatty) { 6293 if (r == null) { 6294 r = new StringBuilder(256); 6295 } else { 6296 r.append(' '); 6297 } 6298 r.append(a.info.name); 6299 } 6300 } 6301 if (r != null) { 6302 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6303 } 6304 6305 N = pkg.activities.size(); 6306 r = null; 6307 for (i=0; i<N; i++) { 6308 PackageParser.Activity a = pkg.activities.get(i); 6309 mActivities.removeActivity(a, "activity"); 6310 if (DEBUG_REMOVE && chatty) { 6311 if (r == null) { 6312 r = new StringBuilder(256); 6313 } else { 6314 r.append(' '); 6315 } 6316 r.append(a.info.name); 6317 } 6318 } 6319 if (r != null) { 6320 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6321 } 6322 6323 N = pkg.permissions.size(); 6324 r = null; 6325 for (i=0; i<N; i++) { 6326 PackageParser.Permission p = pkg.permissions.get(i); 6327 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6328 if (bp == null) { 6329 bp = mSettings.mPermissionTrees.get(p.info.name); 6330 } 6331 if (bp != null && bp.perm == p) { 6332 bp.perm = null; 6333 if (DEBUG_REMOVE && chatty) { 6334 if (r == null) { 6335 r = new StringBuilder(256); 6336 } else { 6337 r.append(' '); 6338 } 6339 r.append(p.info.name); 6340 } 6341 } 6342 } 6343 if (r != null) { 6344 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6345 } 6346 6347 N = pkg.instrumentation.size(); 6348 r = null; 6349 for (i=0; i<N; i++) { 6350 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6351 mInstrumentation.remove(a.getComponentName()); 6352 if (DEBUG_REMOVE && chatty) { 6353 if (r == null) { 6354 r = new StringBuilder(256); 6355 } else { 6356 r.append(' '); 6357 } 6358 r.append(a.info.name); 6359 } 6360 } 6361 if (r != null) { 6362 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6363 } 6364 6365 r = null; 6366 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6367 // Only system apps can hold shared libraries. 6368 if (pkg.libraryNames != null) { 6369 for (i=0; i<pkg.libraryNames.size(); i++) { 6370 String name = pkg.libraryNames.get(i); 6371 SharedLibraryEntry cur = mSharedLibraries.get(name); 6372 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6373 mSharedLibraries.remove(name); 6374 if (DEBUG_REMOVE && chatty) { 6375 if (r == null) { 6376 r = new StringBuilder(256); 6377 } else { 6378 r.append(' '); 6379 } 6380 r.append(name); 6381 } 6382 } 6383 } 6384 } 6385 } 6386 if (r != null) { 6387 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6388 } 6389 } 6390 6391 private static final boolean isPackageFilename(String name) { 6392 return name != null && name.endsWith(".apk"); 6393 } 6394 6395 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6396 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6397 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6398 return true; 6399 } 6400 } 6401 return false; 6402 } 6403 6404 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6405 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6406 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6407 6408 private void updatePermissionsLPw(String changingPkg, 6409 PackageParser.Package pkgInfo, int flags) { 6410 // Make sure there are no dangling permission trees. 6411 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6412 while (it.hasNext()) { 6413 final BasePermission bp = it.next(); 6414 if (bp.packageSetting == null) { 6415 // We may not yet have parsed the package, so just see if 6416 // we still know about its settings. 6417 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6418 } 6419 if (bp.packageSetting == null) { 6420 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6421 + " from package " + bp.sourcePackage); 6422 it.remove(); 6423 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6424 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6425 Slog.i(TAG, "Removing old permission tree: " + bp.name 6426 + " from package " + bp.sourcePackage); 6427 flags |= UPDATE_PERMISSIONS_ALL; 6428 it.remove(); 6429 } 6430 } 6431 } 6432 6433 // Make sure all dynamic permissions have been assigned to a package, 6434 // and make sure there are no dangling permissions. 6435 it = mSettings.mPermissions.values().iterator(); 6436 while (it.hasNext()) { 6437 final BasePermission bp = it.next(); 6438 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6439 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6440 + bp.name + " pkg=" + bp.sourcePackage 6441 + " info=" + bp.pendingInfo); 6442 if (bp.packageSetting == null && bp.pendingInfo != null) { 6443 final BasePermission tree = findPermissionTreeLP(bp.name); 6444 if (tree != null && tree.perm != null) { 6445 bp.packageSetting = tree.packageSetting; 6446 bp.perm = new PackageParser.Permission(tree.perm.owner, 6447 new PermissionInfo(bp.pendingInfo)); 6448 bp.perm.info.packageName = tree.perm.info.packageName; 6449 bp.perm.info.name = bp.name; 6450 bp.uid = tree.uid; 6451 } 6452 } 6453 } 6454 if (bp.packageSetting == null) { 6455 // We may not yet have parsed the package, so just see if 6456 // we still know about its settings. 6457 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6458 } 6459 if (bp.packageSetting == null) { 6460 Slog.w(TAG, "Removing dangling permission: " + bp.name 6461 + " from package " + bp.sourcePackage); 6462 it.remove(); 6463 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6464 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6465 Slog.i(TAG, "Removing old permission: " + bp.name 6466 + " from package " + bp.sourcePackage); 6467 flags |= UPDATE_PERMISSIONS_ALL; 6468 it.remove(); 6469 } 6470 } 6471 } 6472 6473 // Now update the permissions for all packages, in particular 6474 // replace the granted permissions of the system packages. 6475 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6476 for (PackageParser.Package pkg : mPackages.values()) { 6477 if (pkg != pkgInfo) { 6478 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6479 } 6480 } 6481 } 6482 6483 if (pkgInfo != null) { 6484 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6485 } 6486 } 6487 6488 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6489 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6490 if (ps == null) { 6491 return; 6492 } 6493 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6494 HashSet<String> origPermissions = gp.grantedPermissions; 6495 boolean changedPermission = false; 6496 6497 if (replace) { 6498 ps.permissionsFixed = false; 6499 if (gp == ps) { 6500 origPermissions = new HashSet<String>(gp.grantedPermissions); 6501 gp.grantedPermissions.clear(); 6502 gp.gids = mGlobalGids; 6503 } 6504 } 6505 6506 if (gp.gids == null) { 6507 gp.gids = mGlobalGids; 6508 } 6509 6510 final int N = pkg.requestedPermissions.size(); 6511 for (int i=0; i<N; i++) { 6512 final String name = pkg.requestedPermissions.get(i); 6513 final boolean required = pkg.requestedPermissionsRequired.get(i); 6514 final BasePermission bp = mSettings.mPermissions.get(name); 6515 if (DEBUG_INSTALL) { 6516 if (gp != ps) { 6517 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6518 } 6519 } 6520 6521 if (bp == null || bp.packageSetting == null) { 6522 Slog.w(TAG, "Unknown permission " + name 6523 + " in package " + pkg.packageName); 6524 continue; 6525 } 6526 6527 final String perm = bp.name; 6528 boolean allowed; 6529 boolean allowedSig = false; 6530 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6531 if (level == PermissionInfo.PROTECTION_NORMAL 6532 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6533 // We grant a normal or dangerous permission if any of the following 6534 // are true: 6535 // 1) The permission is required 6536 // 2) The permission is optional, but was granted in the past 6537 // 3) The permission is optional, but was requested by an 6538 // app in /system (not /data) 6539 // 6540 // Otherwise, reject the permission. 6541 allowed = (required || origPermissions.contains(perm) 6542 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6543 } else if (bp.packageSetting == null) { 6544 // This permission is invalid; skip it. 6545 allowed = false; 6546 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6547 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6548 if (allowed) { 6549 allowedSig = true; 6550 } 6551 } else { 6552 allowed = false; 6553 } 6554 if (DEBUG_INSTALL) { 6555 if (gp != ps) { 6556 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6557 } 6558 } 6559 if (allowed) { 6560 if (!isSystemApp(ps) && ps.permissionsFixed) { 6561 // If this is an existing, non-system package, then 6562 // we can't add any new permissions to it. 6563 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6564 // Except... if this is a permission that was added 6565 // to the platform (note: need to only do this when 6566 // updating the platform). 6567 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6568 } 6569 } 6570 if (allowed) { 6571 if (!gp.grantedPermissions.contains(perm)) { 6572 changedPermission = true; 6573 gp.grantedPermissions.add(perm); 6574 gp.gids = appendInts(gp.gids, bp.gids); 6575 } else if (!ps.haveGids) { 6576 gp.gids = appendInts(gp.gids, bp.gids); 6577 } 6578 } else { 6579 Slog.w(TAG, "Not granting permission " + perm 6580 + " to package " + pkg.packageName 6581 + " because it was previously installed without"); 6582 } 6583 } else { 6584 if (gp.grantedPermissions.remove(perm)) { 6585 changedPermission = true; 6586 gp.gids = removeInts(gp.gids, bp.gids); 6587 Slog.i(TAG, "Un-granting permission " + perm 6588 + " from package " + pkg.packageName 6589 + " (protectionLevel=" + bp.protectionLevel 6590 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6591 + ")"); 6592 } else { 6593 Slog.w(TAG, "Not granting permission " + perm 6594 + " to package " + pkg.packageName 6595 + " (protectionLevel=" + bp.protectionLevel 6596 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6597 + ")"); 6598 } 6599 } 6600 } 6601 6602 if ((changedPermission || replace) && !ps.permissionsFixed && 6603 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6604 // This is the first that we have heard about this package, so the 6605 // permissions we have now selected are fixed until explicitly 6606 // changed. 6607 ps.permissionsFixed = true; 6608 } 6609 ps.haveGids = true; 6610 } 6611 6612 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6613 boolean allowed = false; 6614 final int NP = PackageParser.NEW_PERMISSIONS.length; 6615 for (int ip=0; ip<NP; ip++) { 6616 final PackageParser.NewPermissionInfo npi 6617 = PackageParser.NEW_PERMISSIONS[ip]; 6618 if (npi.name.equals(perm) 6619 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6620 allowed = true; 6621 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6622 + pkg.packageName); 6623 break; 6624 } 6625 } 6626 return allowed; 6627 } 6628 6629 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6630 BasePermission bp, HashSet<String> origPermissions) { 6631 boolean allowed; 6632 allowed = (compareSignatures( 6633 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6634 == PackageManager.SIGNATURE_MATCH) 6635 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6636 == PackageManager.SIGNATURE_MATCH); 6637 if (!allowed && (bp.protectionLevel 6638 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6639 if (isSystemApp(pkg)) { 6640 // For updated system applications, a system permission 6641 // is granted only if it had been defined by the original application. 6642 if (isUpdatedSystemApp(pkg)) { 6643 final PackageSetting sysPs = mSettings 6644 .getDisabledSystemPkgLPr(pkg.packageName); 6645 final GrantedPermissions origGp = sysPs.sharedUser != null 6646 ? sysPs.sharedUser : sysPs; 6647 6648 if (origGp.grantedPermissions.contains(perm)) { 6649 // If the original was granted this permission, we take 6650 // that grant decision as read and propagate it to the 6651 // update. 6652 allowed = true; 6653 } else { 6654 // The system apk may have been updated with an older 6655 // version of the one on the data partition, but which 6656 // granted a new system permission that it didn't have 6657 // before. In this case we do want to allow the app to 6658 // now get the new permission if the ancestral apk is 6659 // privileged to get it. 6660 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6661 for (int j=0; 6662 j<sysPs.pkg.requestedPermissions.size(); j++) { 6663 if (perm.equals( 6664 sysPs.pkg.requestedPermissions.get(j))) { 6665 allowed = true; 6666 break; 6667 } 6668 } 6669 } 6670 } 6671 } else { 6672 allowed = isPrivilegedApp(pkg); 6673 } 6674 } 6675 } 6676 if (!allowed && (bp.protectionLevel 6677 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6678 // For development permissions, a development permission 6679 // is granted only if it was already granted. 6680 allowed = origPermissions.contains(perm); 6681 } 6682 return allowed; 6683 } 6684 6685 final class ActivityIntentResolver 6686 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6687 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6688 boolean defaultOnly, int userId) { 6689 if (!sUserManager.exists(userId)) return null; 6690 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6691 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6692 } 6693 6694 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6695 int userId) { 6696 if (!sUserManager.exists(userId)) return null; 6697 mFlags = flags; 6698 return super.queryIntent(intent, resolvedType, 6699 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6700 } 6701 6702 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6703 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6704 if (!sUserManager.exists(userId)) return null; 6705 if (packageActivities == null) { 6706 return null; 6707 } 6708 mFlags = flags; 6709 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6710 final int N = packageActivities.size(); 6711 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6712 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6713 6714 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6715 for (int i = 0; i < N; ++i) { 6716 intentFilters = packageActivities.get(i).intents; 6717 if (intentFilters != null && intentFilters.size() > 0) { 6718 PackageParser.ActivityIntentInfo[] array = 6719 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6720 intentFilters.toArray(array); 6721 listCut.add(array); 6722 } 6723 } 6724 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6725 } 6726 6727 public final void addActivity(PackageParser.Activity a, String type) { 6728 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6729 mActivities.put(a.getComponentName(), a); 6730 if (DEBUG_SHOW_INFO) 6731 Log.v( 6732 TAG, " " + type + " " + 6733 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6734 if (DEBUG_SHOW_INFO) 6735 Log.v(TAG, " Class=" + a.info.name); 6736 final int NI = a.intents.size(); 6737 for (int j=0; j<NI; j++) { 6738 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6739 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6740 intent.setPriority(0); 6741 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6742 + a.className + " with priority > 0, forcing to 0"); 6743 } 6744 if (DEBUG_SHOW_INFO) { 6745 Log.v(TAG, " IntentFilter:"); 6746 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6747 } 6748 if (!intent.debugCheck()) { 6749 Log.w(TAG, "==> For Activity " + a.info.name); 6750 } 6751 addFilter(intent); 6752 } 6753 } 6754 6755 public final void removeActivity(PackageParser.Activity a, String type) { 6756 mActivities.remove(a.getComponentName()); 6757 if (DEBUG_SHOW_INFO) { 6758 Log.v(TAG, " " + type + " " 6759 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6760 : a.info.name) + ":"); 6761 Log.v(TAG, " Class=" + a.info.name); 6762 } 6763 final int NI = a.intents.size(); 6764 for (int j=0; j<NI; j++) { 6765 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6766 if (DEBUG_SHOW_INFO) { 6767 Log.v(TAG, " IntentFilter:"); 6768 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6769 } 6770 removeFilter(intent); 6771 } 6772 } 6773 6774 @Override 6775 protected boolean allowFilterResult( 6776 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6777 ActivityInfo filterAi = filter.activity.info; 6778 for (int i=dest.size()-1; i>=0; i--) { 6779 ActivityInfo destAi = dest.get(i).activityInfo; 6780 if (destAi.name == filterAi.name 6781 && destAi.packageName == filterAi.packageName) { 6782 return false; 6783 } 6784 } 6785 return true; 6786 } 6787 6788 @Override 6789 protected ActivityIntentInfo[] newArray(int size) { 6790 return new ActivityIntentInfo[size]; 6791 } 6792 6793 @Override 6794 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6795 if (!sUserManager.exists(userId)) return true; 6796 PackageParser.Package p = filter.activity.owner; 6797 if (p != null) { 6798 PackageSetting ps = (PackageSetting)p.mExtras; 6799 if (ps != null) { 6800 // System apps are never considered stopped for purposes of 6801 // filtering, because there may be no way for the user to 6802 // actually re-launch them. 6803 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6804 && ps.getStopped(userId); 6805 } 6806 } 6807 return false; 6808 } 6809 6810 @Override 6811 protected boolean isPackageForFilter(String packageName, 6812 PackageParser.ActivityIntentInfo info) { 6813 return packageName.equals(info.activity.owner.packageName); 6814 } 6815 6816 @Override 6817 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6818 int match, int userId) { 6819 if (!sUserManager.exists(userId)) return null; 6820 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6821 return null; 6822 } 6823 final PackageParser.Activity activity = info.activity; 6824 if (mSafeMode && (activity.info.applicationInfo.flags 6825 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6826 return null; 6827 } 6828 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6829 if (ps == null) { 6830 return null; 6831 } 6832 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6833 ps.readUserState(userId), userId); 6834 if (ai == null) { 6835 return null; 6836 } 6837 final ResolveInfo res = new ResolveInfo(); 6838 res.activityInfo = ai; 6839 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6840 res.filter = info; 6841 } 6842 res.priority = info.getPriority(); 6843 res.preferredOrder = activity.owner.mPreferredOrder; 6844 //System.out.println("Result: " + res.activityInfo.className + 6845 // " = " + res.priority); 6846 res.match = match; 6847 res.isDefault = info.hasDefault; 6848 res.labelRes = info.labelRes; 6849 res.nonLocalizedLabel = info.nonLocalizedLabel; 6850 res.icon = info.icon; 6851 res.system = isSystemApp(res.activityInfo.applicationInfo); 6852 return res; 6853 } 6854 6855 @Override 6856 protected void sortResults(List<ResolveInfo> results) { 6857 Collections.sort(results, mResolvePrioritySorter); 6858 } 6859 6860 @Override 6861 protected void dumpFilter(PrintWriter out, String prefix, 6862 PackageParser.ActivityIntentInfo filter) { 6863 out.print(prefix); out.print( 6864 Integer.toHexString(System.identityHashCode(filter.activity))); 6865 out.print(' '); 6866 filter.activity.printComponentShortName(out); 6867 out.print(" filter "); 6868 out.println(Integer.toHexString(System.identityHashCode(filter))); 6869 } 6870 6871// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6872// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6873// final List<ResolveInfo> retList = Lists.newArrayList(); 6874// while (i.hasNext()) { 6875// final ResolveInfo resolveInfo = i.next(); 6876// if (isEnabledLP(resolveInfo.activityInfo)) { 6877// retList.add(resolveInfo); 6878// } 6879// } 6880// return retList; 6881// } 6882 6883 // Keys are String (activity class name), values are Activity. 6884 private final HashMap<ComponentName, PackageParser.Activity> mActivities 6885 = new HashMap<ComponentName, PackageParser.Activity>(); 6886 private int mFlags; 6887 } 6888 6889 private final class ServiceIntentResolver 6890 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 6891 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6892 boolean defaultOnly, int userId) { 6893 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6894 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6895 } 6896 6897 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6898 int userId) { 6899 if (!sUserManager.exists(userId)) return null; 6900 mFlags = flags; 6901 return super.queryIntent(intent, resolvedType, 6902 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6903 } 6904 6905 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6906 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 6907 if (!sUserManager.exists(userId)) return null; 6908 if (packageServices == null) { 6909 return null; 6910 } 6911 mFlags = flags; 6912 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6913 final int N = packageServices.size(); 6914 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 6915 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 6916 6917 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 6918 for (int i = 0; i < N; ++i) { 6919 intentFilters = packageServices.get(i).intents; 6920 if (intentFilters != null && intentFilters.size() > 0) { 6921 PackageParser.ServiceIntentInfo[] array = 6922 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 6923 intentFilters.toArray(array); 6924 listCut.add(array); 6925 } 6926 } 6927 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6928 } 6929 6930 public final void addService(PackageParser.Service s) { 6931 mServices.put(s.getComponentName(), s); 6932 if (DEBUG_SHOW_INFO) { 6933 Log.v(TAG, " " 6934 + (s.info.nonLocalizedLabel != null 6935 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6936 Log.v(TAG, " Class=" + s.info.name); 6937 } 6938 final int NI = s.intents.size(); 6939 int j; 6940 for (j=0; j<NI; j++) { 6941 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6942 if (DEBUG_SHOW_INFO) { 6943 Log.v(TAG, " IntentFilter:"); 6944 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6945 } 6946 if (!intent.debugCheck()) { 6947 Log.w(TAG, "==> For Service " + s.info.name); 6948 } 6949 addFilter(intent); 6950 } 6951 } 6952 6953 public final void removeService(PackageParser.Service s) { 6954 mServices.remove(s.getComponentName()); 6955 if (DEBUG_SHOW_INFO) { 6956 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 6957 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6958 Log.v(TAG, " Class=" + s.info.name); 6959 } 6960 final int NI = s.intents.size(); 6961 int j; 6962 for (j=0; j<NI; j++) { 6963 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6964 if (DEBUG_SHOW_INFO) { 6965 Log.v(TAG, " IntentFilter:"); 6966 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6967 } 6968 removeFilter(intent); 6969 } 6970 } 6971 6972 @Override 6973 protected boolean allowFilterResult( 6974 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 6975 ServiceInfo filterSi = filter.service.info; 6976 for (int i=dest.size()-1; i>=0; i--) { 6977 ServiceInfo destAi = dest.get(i).serviceInfo; 6978 if (destAi.name == filterSi.name 6979 && destAi.packageName == filterSi.packageName) { 6980 return false; 6981 } 6982 } 6983 return true; 6984 } 6985 6986 @Override 6987 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 6988 return new PackageParser.ServiceIntentInfo[size]; 6989 } 6990 6991 @Override 6992 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 6993 if (!sUserManager.exists(userId)) return true; 6994 PackageParser.Package p = filter.service.owner; 6995 if (p != null) { 6996 PackageSetting ps = (PackageSetting)p.mExtras; 6997 if (ps != null) { 6998 // System apps are never considered stopped for purposes of 6999 // filtering, because there may be no way for the user to 7000 // actually re-launch them. 7001 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7002 && ps.getStopped(userId); 7003 } 7004 } 7005 return false; 7006 } 7007 7008 @Override 7009 protected boolean isPackageForFilter(String packageName, 7010 PackageParser.ServiceIntentInfo info) { 7011 return packageName.equals(info.service.owner.packageName); 7012 } 7013 7014 @Override 7015 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7016 int match, int userId) { 7017 if (!sUserManager.exists(userId)) return null; 7018 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7019 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7020 return null; 7021 } 7022 final PackageParser.Service service = info.service; 7023 if (mSafeMode && (service.info.applicationInfo.flags 7024 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7025 return null; 7026 } 7027 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7028 if (ps == null) { 7029 return null; 7030 } 7031 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7032 ps.readUserState(userId), userId); 7033 if (si == null) { 7034 return null; 7035 } 7036 final ResolveInfo res = new ResolveInfo(); 7037 res.serviceInfo = si; 7038 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7039 res.filter = filter; 7040 } 7041 res.priority = info.getPriority(); 7042 res.preferredOrder = service.owner.mPreferredOrder; 7043 //System.out.println("Result: " + res.activityInfo.className + 7044 // " = " + res.priority); 7045 res.match = match; 7046 res.isDefault = info.hasDefault; 7047 res.labelRes = info.labelRes; 7048 res.nonLocalizedLabel = info.nonLocalizedLabel; 7049 res.icon = info.icon; 7050 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7051 return res; 7052 } 7053 7054 @Override 7055 protected void sortResults(List<ResolveInfo> results) { 7056 Collections.sort(results, mResolvePrioritySorter); 7057 } 7058 7059 @Override 7060 protected void dumpFilter(PrintWriter out, String prefix, 7061 PackageParser.ServiceIntentInfo filter) { 7062 out.print(prefix); out.print( 7063 Integer.toHexString(System.identityHashCode(filter.service))); 7064 out.print(' '); 7065 filter.service.printComponentShortName(out); 7066 out.print(" filter "); 7067 out.println(Integer.toHexString(System.identityHashCode(filter))); 7068 } 7069 7070// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7071// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7072// final List<ResolveInfo> retList = Lists.newArrayList(); 7073// while (i.hasNext()) { 7074// final ResolveInfo resolveInfo = (ResolveInfo) i; 7075// if (isEnabledLP(resolveInfo.serviceInfo)) { 7076// retList.add(resolveInfo); 7077// } 7078// } 7079// return retList; 7080// } 7081 7082 // Keys are String (activity class name), values are Activity. 7083 private final HashMap<ComponentName, PackageParser.Service> mServices 7084 = new HashMap<ComponentName, PackageParser.Service>(); 7085 private int mFlags; 7086 }; 7087 7088 private final class ProviderIntentResolver 7089 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7090 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7091 boolean defaultOnly, int userId) { 7092 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7093 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7094 } 7095 7096 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7097 int userId) { 7098 if (!sUserManager.exists(userId)) 7099 return null; 7100 mFlags = flags; 7101 return super.queryIntent(intent, resolvedType, 7102 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7103 } 7104 7105 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7106 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7107 if (!sUserManager.exists(userId)) 7108 return null; 7109 if (packageProviders == null) { 7110 return null; 7111 } 7112 mFlags = flags; 7113 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7114 final int N = packageProviders.size(); 7115 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7116 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7117 7118 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7119 for (int i = 0; i < N; ++i) { 7120 intentFilters = packageProviders.get(i).intents; 7121 if (intentFilters != null && intentFilters.size() > 0) { 7122 PackageParser.ProviderIntentInfo[] array = 7123 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7124 intentFilters.toArray(array); 7125 listCut.add(array); 7126 } 7127 } 7128 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7129 } 7130 7131 public final void addProvider(PackageParser.Provider p) { 7132 if (mProviders.containsKey(p.getComponentName())) { 7133 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7134 return; 7135 } 7136 7137 mProviders.put(p.getComponentName(), p); 7138 if (DEBUG_SHOW_INFO) { 7139 Log.v(TAG, " " 7140 + (p.info.nonLocalizedLabel != null 7141 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7142 Log.v(TAG, " Class=" + p.info.name); 7143 } 7144 final int NI = p.intents.size(); 7145 int j; 7146 for (j = 0; j < NI; j++) { 7147 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7148 if (DEBUG_SHOW_INFO) { 7149 Log.v(TAG, " IntentFilter:"); 7150 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7151 } 7152 if (!intent.debugCheck()) { 7153 Log.w(TAG, "==> For Provider " + p.info.name); 7154 } 7155 addFilter(intent); 7156 } 7157 } 7158 7159 public final void removeProvider(PackageParser.Provider p) { 7160 mProviders.remove(p.getComponentName()); 7161 if (DEBUG_SHOW_INFO) { 7162 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7163 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7164 Log.v(TAG, " Class=" + p.info.name); 7165 } 7166 final int NI = p.intents.size(); 7167 int j; 7168 for (j = 0; j < NI; j++) { 7169 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7170 if (DEBUG_SHOW_INFO) { 7171 Log.v(TAG, " IntentFilter:"); 7172 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7173 } 7174 removeFilter(intent); 7175 } 7176 } 7177 7178 @Override 7179 protected boolean allowFilterResult( 7180 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7181 ProviderInfo filterPi = filter.provider.info; 7182 for (int i = dest.size() - 1; i >= 0; i--) { 7183 ProviderInfo destPi = dest.get(i).providerInfo; 7184 if (destPi.name == filterPi.name 7185 && destPi.packageName == filterPi.packageName) { 7186 return false; 7187 } 7188 } 7189 return true; 7190 } 7191 7192 @Override 7193 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7194 return new PackageParser.ProviderIntentInfo[size]; 7195 } 7196 7197 @Override 7198 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7199 if (!sUserManager.exists(userId)) 7200 return true; 7201 PackageParser.Package p = filter.provider.owner; 7202 if (p != null) { 7203 PackageSetting ps = (PackageSetting) p.mExtras; 7204 if (ps != null) { 7205 // System apps are never considered stopped for purposes of 7206 // filtering, because there may be no way for the user to 7207 // actually re-launch them. 7208 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7209 && ps.getStopped(userId); 7210 } 7211 } 7212 return false; 7213 } 7214 7215 @Override 7216 protected boolean isPackageForFilter(String packageName, 7217 PackageParser.ProviderIntentInfo info) { 7218 return packageName.equals(info.provider.owner.packageName); 7219 } 7220 7221 @Override 7222 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7223 int match, int userId) { 7224 if (!sUserManager.exists(userId)) 7225 return null; 7226 final PackageParser.ProviderIntentInfo info = filter; 7227 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7228 return null; 7229 } 7230 final PackageParser.Provider provider = info.provider; 7231 if (mSafeMode && (provider.info.applicationInfo.flags 7232 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7233 return null; 7234 } 7235 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7236 if (ps == null) { 7237 return null; 7238 } 7239 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7240 ps.readUserState(userId), userId); 7241 if (pi == null) { 7242 return null; 7243 } 7244 final ResolveInfo res = new ResolveInfo(); 7245 res.providerInfo = pi; 7246 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7247 res.filter = filter; 7248 } 7249 res.priority = info.getPriority(); 7250 res.preferredOrder = provider.owner.mPreferredOrder; 7251 res.match = match; 7252 res.isDefault = info.hasDefault; 7253 res.labelRes = info.labelRes; 7254 res.nonLocalizedLabel = info.nonLocalizedLabel; 7255 res.icon = info.icon; 7256 res.system = isSystemApp(res.providerInfo.applicationInfo); 7257 return res; 7258 } 7259 7260 @Override 7261 protected void sortResults(List<ResolveInfo> results) { 7262 Collections.sort(results, mResolvePrioritySorter); 7263 } 7264 7265 @Override 7266 protected void dumpFilter(PrintWriter out, String prefix, 7267 PackageParser.ProviderIntentInfo filter) { 7268 out.print(prefix); 7269 out.print( 7270 Integer.toHexString(System.identityHashCode(filter.provider))); 7271 out.print(' '); 7272 filter.provider.printComponentShortName(out); 7273 out.print(" filter "); 7274 out.println(Integer.toHexString(System.identityHashCode(filter))); 7275 } 7276 7277 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7278 = new HashMap<ComponentName, PackageParser.Provider>(); 7279 private int mFlags; 7280 }; 7281 7282 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7283 new Comparator<ResolveInfo>() { 7284 public int compare(ResolveInfo r1, ResolveInfo r2) { 7285 int v1 = r1.priority; 7286 int v2 = r2.priority; 7287 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7288 if (v1 != v2) { 7289 return (v1 > v2) ? -1 : 1; 7290 } 7291 v1 = r1.preferredOrder; 7292 v2 = r2.preferredOrder; 7293 if (v1 != v2) { 7294 return (v1 > v2) ? -1 : 1; 7295 } 7296 if (r1.isDefault != r2.isDefault) { 7297 return r1.isDefault ? -1 : 1; 7298 } 7299 v1 = r1.match; 7300 v2 = r2.match; 7301 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7302 if (v1 != v2) { 7303 return (v1 > v2) ? -1 : 1; 7304 } 7305 if (r1.system != r2.system) { 7306 return r1.system ? -1 : 1; 7307 } 7308 return 0; 7309 } 7310 }; 7311 7312 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7313 new Comparator<ProviderInfo>() { 7314 public int compare(ProviderInfo p1, ProviderInfo p2) { 7315 final int v1 = p1.initOrder; 7316 final int v2 = p2.initOrder; 7317 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7318 } 7319 }; 7320 7321 static final void sendPackageBroadcast(String action, String pkg, 7322 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7323 int[] userIds) { 7324 IActivityManager am = ActivityManagerNative.getDefault(); 7325 if (am != null) { 7326 try { 7327 if (userIds == null) { 7328 userIds = am.getRunningUserIds(); 7329 } 7330 for (int id : userIds) { 7331 final Intent intent = new Intent(action, 7332 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7333 if (extras != null) { 7334 intent.putExtras(extras); 7335 } 7336 if (targetPkg != null) { 7337 intent.setPackage(targetPkg); 7338 } 7339 // Modify the UID when posting to other users 7340 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7341 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7342 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7343 intent.putExtra(Intent.EXTRA_UID, uid); 7344 } 7345 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7346 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7347 if (DEBUG_BROADCASTS) { 7348 RuntimeException here = new RuntimeException("here"); 7349 here.fillInStackTrace(); 7350 Slog.d(TAG, "Sending to user " + id + ": " 7351 + intent.toShortString(false, true, false, false) 7352 + " " + intent.getExtras(), here); 7353 } 7354 am.broadcastIntent(null, intent, null, finishedReceiver, 7355 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7356 finishedReceiver != null, false, id); 7357 } 7358 } catch (RemoteException ex) { 7359 } 7360 } 7361 } 7362 7363 /** 7364 * Check if the external storage media is available. This is true if there 7365 * is a mounted external storage medium or if the external storage is 7366 * emulated. 7367 */ 7368 private boolean isExternalMediaAvailable() { 7369 return mMediaMounted || Environment.isExternalStorageEmulated(); 7370 } 7371 7372 @Override 7373 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7374 // writer 7375 synchronized (mPackages) { 7376 if (!isExternalMediaAvailable()) { 7377 // If the external storage is no longer mounted at this point, 7378 // the caller may not have been able to delete all of this 7379 // packages files and can not delete any more. Bail. 7380 return null; 7381 } 7382 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7383 if (lastPackage != null) { 7384 pkgs.remove(lastPackage); 7385 } 7386 if (pkgs.size() > 0) { 7387 return pkgs.get(0); 7388 } 7389 } 7390 return null; 7391 } 7392 7393 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7394 if (false) { 7395 RuntimeException here = new RuntimeException("here"); 7396 here.fillInStackTrace(); 7397 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7398 + " andCode=" + andCode, here); 7399 } 7400 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7401 userId, andCode ? 1 : 0, packageName)); 7402 } 7403 7404 void startCleaningPackages() { 7405 // reader 7406 synchronized (mPackages) { 7407 if (!isExternalMediaAvailable()) { 7408 return; 7409 } 7410 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7411 return; 7412 } 7413 } 7414 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7415 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7416 IActivityManager am = ActivityManagerNative.getDefault(); 7417 if (am != null) { 7418 try { 7419 am.startService(null, intent, null, UserHandle.USER_OWNER); 7420 } catch (RemoteException e) { 7421 } 7422 } 7423 } 7424 7425 private final class AppDirObserver extends FileObserver { 7426 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7427 super(path, mask); 7428 mRootDir = path; 7429 mIsRom = isrom; 7430 mIsPrivileged = isPrivileged; 7431 } 7432 7433 public void onEvent(int event, String path) { 7434 String removedPackage = null; 7435 int removedAppId = -1; 7436 int[] removedUsers = null; 7437 String addedPackage = null; 7438 int addedAppId = -1; 7439 int[] addedUsers = null; 7440 7441 // TODO post a message to the handler to obtain serial ordering 7442 synchronized (mInstallLock) { 7443 String fullPathStr = null; 7444 File fullPath = null; 7445 if (path != null) { 7446 fullPath = new File(mRootDir, path); 7447 fullPathStr = fullPath.getPath(); 7448 } 7449 7450 if (DEBUG_APP_DIR_OBSERVER) 7451 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7452 7453 if (!isPackageFilename(path)) { 7454 if (DEBUG_APP_DIR_OBSERVER) 7455 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7456 return; 7457 } 7458 7459 // Ignore packages that are being installed or 7460 // have just been installed. 7461 if (ignoreCodePath(fullPathStr)) { 7462 return; 7463 } 7464 PackageParser.Package p = null; 7465 PackageSetting ps = null; 7466 // reader 7467 synchronized (mPackages) { 7468 p = mAppDirs.get(fullPathStr); 7469 if (p != null) { 7470 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7471 if (ps != null) { 7472 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7473 } else { 7474 removedUsers = sUserManager.getUserIds(); 7475 } 7476 } 7477 addedUsers = sUserManager.getUserIds(); 7478 } 7479 if ((event&REMOVE_EVENTS) != 0) { 7480 if (ps != null) { 7481 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7482 removePackageLI(ps, true); 7483 removedPackage = ps.name; 7484 removedAppId = ps.appId; 7485 } 7486 } 7487 7488 if ((event&ADD_EVENTS) != 0) { 7489 if (p == null) { 7490 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7491 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7492 if (mIsRom) { 7493 flags |= PackageParser.PARSE_IS_SYSTEM 7494 | PackageParser.PARSE_IS_SYSTEM_DIR; 7495 if (mIsPrivileged) { 7496 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7497 } 7498 } 7499 p = scanPackageLI(fullPath, flags, 7500 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7501 System.currentTimeMillis(), UserHandle.ALL, null); 7502 if (p != null) { 7503 /* 7504 * TODO this seems dangerous as the package may have 7505 * changed since we last acquired the mPackages 7506 * lock. 7507 */ 7508 // writer 7509 synchronized (mPackages) { 7510 updatePermissionsLPw(p.packageName, p, 7511 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7512 } 7513 addedPackage = p.applicationInfo.packageName; 7514 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7515 } 7516 } 7517 } 7518 7519 // reader 7520 synchronized (mPackages) { 7521 mSettings.writeLPr(); 7522 } 7523 } 7524 7525 if (removedPackage != null) { 7526 Bundle extras = new Bundle(1); 7527 extras.putInt(Intent.EXTRA_UID, removedAppId); 7528 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7529 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7530 extras, null, null, removedUsers); 7531 } 7532 if (addedPackage != null) { 7533 Bundle extras = new Bundle(1); 7534 extras.putInt(Intent.EXTRA_UID, addedAppId); 7535 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7536 extras, null, null, addedUsers); 7537 } 7538 } 7539 7540 private final String mRootDir; 7541 private final boolean mIsRom; 7542 private final boolean mIsPrivileged; 7543 } 7544 7545 /* 7546 * The old-style observer methods all just trampoline to the newer signature with 7547 * expanded install observer API. The older API continues to work but does not 7548 * supply the additional details of the Observer2 API. 7549 */ 7550 7551 /* Called when a downloaded package installation has been confirmed by the user */ 7552 public void installPackage( 7553 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 7554 installPackageEtc(packageURI, observer, null, flags, null); 7555 } 7556 7557 /* Called when a downloaded package installation has been confirmed by the user */ 7558 @Override 7559 public void installPackage( 7560 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 7561 final String installerPackageName) { 7562 installPackageWithVerificationEtc(packageURI, observer, null, flags, 7563 installerPackageName, null, null, null); 7564 } 7565 7566 @Override 7567 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 7568 int flags, String installerPackageName, Uri verificationURI, 7569 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7570 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7571 VerificationParams.NO_UID, manifestDigest); 7572 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7573 installerPackageName, verificationParams, encryptionParams); 7574 } 7575 7576 @Override 7577 public void installPackageWithVerificationAndEncryption(Uri packageURI, 7578 IPackageInstallObserver observer, int flags, String installerPackageName, 7579 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7580 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7581 installerPackageName, verificationParams, encryptionParams); 7582 } 7583 7584 /* 7585 * And here are the "live" versions that take both observer arguments 7586 */ 7587 public void installPackageEtc( 7588 final Uri packageURI, final IPackageInstallObserver observer, 7589 IPackageInstallObserver2 observer2, final int flags) { 7590 installPackageEtc(packageURI, observer, observer2, flags, null); 7591 } 7592 7593 public void installPackageEtc( 7594 final Uri packageURI, final IPackageInstallObserver observer, 7595 final IPackageInstallObserver2 observer2, final int flags, 7596 final String installerPackageName) { 7597 installPackageWithVerificationEtc(packageURI, observer, observer2, flags, 7598 installerPackageName, null, null, null); 7599 } 7600 7601 @Override 7602 public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer, 7603 IPackageInstallObserver2 observer2, 7604 int flags, String installerPackageName, Uri verificationURI, 7605 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7606 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7607 VerificationParams.NO_UID, manifestDigest); 7608 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags, 7609 installerPackageName, verificationParams, encryptionParams); 7610 } 7611 7612 /* 7613 * All of the installPackage...*() methods redirect to this one for the master implementation 7614 */ 7615 public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI, 7616 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7617 int flags, String installerPackageName, 7618 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7619 if (observer == null && observer2 == null) { 7620 throw new IllegalArgumentException("No install observer supplied"); 7621 } 7622 installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2, 7623 flags, installerPackageName, verificationParams, encryptionParams, null); 7624 } 7625 7626 @Override 7627 public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI, 7628 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7629 int flags, String installerPackageName, 7630 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams, 7631 String packageAbiOverride) { 7632 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7633 null); 7634 7635 final int uid = Binder.getCallingUid(); 7636 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7637 try { 7638 if (observer != null) { 7639 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7640 } 7641 if (observer2 != null) { 7642 observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7643 } 7644 } catch (RemoteException re) { 7645 } 7646 return; 7647 } 7648 7649 UserHandle user; 7650 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7651 user = UserHandle.ALL; 7652 } else { 7653 user = new UserHandle(UserHandle.getUserId(uid)); 7654 } 7655 7656 final int filteredFlags; 7657 7658 if (uid == Process.SHELL_UID || uid == 0) { 7659 if (DEBUG_INSTALL) { 7660 Slog.v(TAG, "Install from ADB"); 7661 } 7662 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7663 } else { 7664 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7665 } 7666 7667 verificationParams.setInstallerUid(uid); 7668 7669 final Message msg = mHandler.obtainMessage(INIT_COPY); 7670 msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags, 7671 installerPackageName, verificationParams, encryptionParams, user, 7672 packageAbiOverride); 7673 mHandler.sendMessage(msg); 7674 } 7675 7676 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7677 Bundle extras = new Bundle(1); 7678 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7679 7680 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7681 packageName, extras, null, null, new int[] {userId}); 7682 try { 7683 IActivityManager am = ActivityManagerNative.getDefault(); 7684 final boolean isSystem = 7685 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7686 if (isSystem && am.isUserRunning(userId, false)) { 7687 // The just-installed/enabled app is bundled on the system, so presumed 7688 // to be able to run automatically without needing an explicit launch. 7689 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7690 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7691 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7692 .setPackage(packageName); 7693 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7694 android.app.AppOpsManager.OP_NONE, false, false, userId); 7695 } 7696 } catch (RemoteException e) { 7697 // shouldn't happen 7698 Slog.w(TAG, "Unable to bootstrap installed package", e); 7699 } 7700 } 7701 7702 @Override 7703 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7704 int userId) { 7705 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7706 PackageSetting pkgSetting; 7707 final int uid = Binder.getCallingUid(); 7708 if (UserHandle.getUserId(uid) != userId) { 7709 mContext.enforceCallingOrSelfPermission( 7710 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7711 "setApplicationBlockedSetting for user " + userId); 7712 } 7713 7714 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7715 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7716 return false; 7717 } 7718 7719 long callingId = Binder.clearCallingIdentity(); 7720 try { 7721 boolean sendAdded = false; 7722 boolean sendRemoved = false; 7723 // writer 7724 synchronized (mPackages) { 7725 pkgSetting = mSettings.mPackages.get(packageName); 7726 if (pkgSetting == null) { 7727 return false; 7728 } 7729 if (pkgSetting.getBlocked(userId) != blocked) { 7730 pkgSetting.setBlocked(blocked, userId); 7731 mSettings.writePackageRestrictionsLPr(userId); 7732 if (blocked) { 7733 sendRemoved = true; 7734 } else { 7735 sendAdded = true; 7736 } 7737 } 7738 } 7739 if (sendAdded) { 7740 sendPackageAddedForUser(packageName, pkgSetting, userId); 7741 return true; 7742 } 7743 if (sendRemoved) { 7744 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7745 "blocking pkg"); 7746 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7747 } 7748 } finally { 7749 Binder.restoreCallingIdentity(callingId); 7750 } 7751 return false; 7752 } 7753 7754 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7755 int userId) { 7756 final PackageRemovedInfo info = new PackageRemovedInfo(); 7757 info.removedPackage = packageName; 7758 info.removedUsers = new int[] {userId}; 7759 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7760 info.sendBroadcast(false, false, false); 7761 } 7762 7763 /** 7764 * Returns true if application is not found or there was an error. Otherwise it returns 7765 * the blocked state of the package for the given user. 7766 */ 7767 @Override 7768 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7769 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7770 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7771 "getApplicationBlocked for user " + userId); 7772 PackageSetting pkgSetting; 7773 long callingId = Binder.clearCallingIdentity(); 7774 try { 7775 // writer 7776 synchronized (mPackages) { 7777 pkgSetting = mSettings.mPackages.get(packageName); 7778 if (pkgSetting == null) { 7779 return true; 7780 } 7781 return pkgSetting.getBlocked(userId); 7782 } 7783 } finally { 7784 Binder.restoreCallingIdentity(callingId); 7785 } 7786 } 7787 7788 void installStage(String basePackageName, File stageDir, IPackageInstallObserver2 observer, 7789 int flags) { 7790 // TODO: install stage! 7791 try { 7792 observer.packageInstalled(basePackageName, null, 7793 PackageManager.INSTALL_FAILED_INTERNAL_ERROR); 7794 } catch (RemoteException ignored) { 7795 } 7796 } 7797 7798 /** 7799 * @hide 7800 */ 7801 @Override 7802 public int installExistingPackageAsUser(String packageName, int userId) { 7803 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7804 null); 7805 PackageSetting pkgSetting; 7806 final int uid = Binder.getCallingUid(); 7807 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7808 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7809 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7810 } 7811 7812 long callingId = Binder.clearCallingIdentity(); 7813 try { 7814 boolean sendAdded = false; 7815 Bundle extras = new Bundle(1); 7816 7817 // writer 7818 synchronized (mPackages) { 7819 pkgSetting = mSettings.mPackages.get(packageName); 7820 if (pkgSetting == null) { 7821 return PackageManager.INSTALL_FAILED_INVALID_URI; 7822 } 7823 if (!pkgSetting.getInstalled(userId)) { 7824 pkgSetting.setInstalled(true, userId); 7825 pkgSetting.setBlocked(false, userId); 7826 mSettings.writePackageRestrictionsLPr(userId); 7827 sendAdded = true; 7828 } 7829 } 7830 7831 if (sendAdded) { 7832 sendPackageAddedForUser(packageName, pkgSetting, userId); 7833 } 7834 } finally { 7835 Binder.restoreCallingIdentity(callingId); 7836 } 7837 7838 return PackageManager.INSTALL_SUCCEEDED; 7839 } 7840 7841 boolean isUserRestricted(int userId, String restrictionKey) { 7842 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7843 if (restrictions.getBoolean(restrictionKey, false)) { 7844 Log.w(TAG, "User is restricted: " + restrictionKey); 7845 return true; 7846 } 7847 return false; 7848 } 7849 7850 @Override 7851 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7852 mContext.enforceCallingOrSelfPermission( 7853 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7854 "Only package verification agents can verify applications"); 7855 7856 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7857 final PackageVerificationResponse response = new PackageVerificationResponse( 7858 verificationCode, Binder.getCallingUid()); 7859 msg.arg1 = id; 7860 msg.obj = response; 7861 mHandler.sendMessage(msg); 7862 } 7863 7864 @Override 7865 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7866 long millisecondsToDelay) { 7867 mContext.enforceCallingOrSelfPermission( 7868 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7869 "Only package verification agents can extend verification timeouts"); 7870 7871 final PackageVerificationState state = mPendingVerification.get(id); 7872 final PackageVerificationResponse response = new PackageVerificationResponse( 7873 verificationCodeAtTimeout, Binder.getCallingUid()); 7874 7875 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7876 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7877 } 7878 if (millisecondsToDelay < 0) { 7879 millisecondsToDelay = 0; 7880 } 7881 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7882 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7883 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7884 } 7885 7886 if ((state != null) && !state.timeoutExtended()) { 7887 state.extendTimeout(); 7888 7889 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7890 msg.arg1 = id; 7891 msg.obj = response; 7892 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7893 } 7894 } 7895 7896 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7897 int verificationCode, UserHandle user) { 7898 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7899 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7900 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7901 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7902 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7903 7904 mContext.sendBroadcastAsUser(intent, user, 7905 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7906 } 7907 7908 private ComponentName matchComponentForVerifier(String packageName, 7909 List<ResolveInfo> receivers) { 7910 ActivityInfo targetReceiver = null; 7911 7912 final int NR = receivers.size(); 7913 for (int i = 0; i < NR; i++) { 7914 final ResolveInfo info = receivers.get(i); 7915 if (info.activityInfo == null) { 7916 continue; 7917 } 7918 7919 if (packageName.equals(info.activityInfo.packageName)) { 7920 targetReceiver = info.activityInfo; 7921 break; 7922 } 7923 } 7924 7925 if (targetReceiver == null) { 7926 return null; 7927 } 7928 7929 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 7930 } 7931 7932 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 7933 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 7934 if (pkgInfo.verifiers.length == 0) { 7935 return null; 7936 } 7937 7938 final int N = pkgInfo.verifiers.length; 7939 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 7940 for (int i = 0; i < N; i++) { 7941 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 7942 7943 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 7944 receivers); 7945 if (comp == null) { 7946 continue; 7947 } 7948 7949 final int verifierUid = getUidForVerifier(verifierInfo); 7950 if (verifierUid == -1) { 7951 continue; 7952 } 7953 7954 if (DEBUG_VERIFY) { 7955 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 7956 + " with the correct signature"); 7957 } 7958 sufficientVerifiers.add(comp); 7959 verificationState.addSufficientVerifier(verifierUid); 7960 } 7961 7962 return sufficientVerifiers; 7963 } 7964 7965 private int getUidForVerifier(VerifierInfo verifierInfo) { 7966 synchronized (mPackages) { 7967 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 7968 if (pkg == null) { 7969 return -1; 7970 } else if (pkg.mSignatures.length != 1) { 7971 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7972 + " has more than one signature; ignoring"); 7973 return -1; 7974 } 7975 7976 /* 7977 * If the public key of the package's signature does not match 7978 * our expected public key, then this is a different package and 7979 * we should skip. 7980 */ 7981 7982 final byte[] expectedPublicKey; 7983 try { 7984 final Signature verifierSig = pkg.mSignatures[0]; 7985 final PublicKey publicKey = verifierSig.getPublicKey(); 7986 expectedPublicKey = publicKey.getEncoded(); 7987 } catch (CertificateException e) { 7988 return -1; 7989 } 7990 7991 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 7992 7993 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 7994 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7995 + " does not have the expected public key; ignoring"); 7996 return -1; 7997 } 7998 7999 return pkg.applicationInfo.uid; 8000 } 8001 } 8002 8003 @Override 8004 public void finishPackageInstall(int token) { 8005 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8006 8007 if (DEBUG_INSTALL) { 8008 Slog.v(TAG, "BM finishing package install for " + token); 8009 } 8010 8011 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8012 mHandler.sendMessage(msg); 8013 } 8014 8015 /** 8016 * Get the verification agent timeout. 8017 * 8018 * @return verification timeout in milliseconds 8019 */ 8020 private long getVerificationTimeout() { 8021 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8022 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8023 DEFAULT_VERIFICATION_TIMEOUT); 8024 } 8025 8026 /** 8027 * Get the default verification agent response code. 8028 * 8029 * @return default verification response code 8030 */ 8031 private int getDefaultVerificationResponse() { 8032 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8033 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8034 DEFAULT_VERIFICATION_RESPONSE); 8035 } 8036 8037 /** 8038 * Check whether or not package verification has been enabled. 8039 * 8040 * @return true if verification should be performed 8041 */ 8042 private boolean isVerificationEnabled(int flags) { 8043 if (!DEFAULT_VERIFY_ENABLE) { 8044 return false; 8045 } 8046 8047 // Check if installing from ADB 8048 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8049 // Do not run verification in a test harness environment 8050 if (ActivityManager.isRunningInTestHarness()) { 8051 return false; 8052 } 8053 // Check if the developer does not want package verification for ADB installs 8054 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8055 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8056 return false; 8057 } 8058 } 8059 8060 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8061 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8062 } 8063 8064 /** 8065 * Get the "allow unknown sources" setting. 8066 * 8067 * @return the current "allow unknown sources" setting 8068 */ 8069 private int getUnknownSourcesSettings() { 8070 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8071 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8072 -1); 8073 } 8074 8075 @Override 8076 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8077 final int uid = Binder.getCallingUid(); 8078 // writer 8079 synchronized (mPackages) { 8080 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8081 if (targetPackageSetting == null) { 8082 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8083 } 8084 8085 PackageSetting installerPackageSetting; 8086 if (installerPackageName != null) { 8087 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8088 if (installerPackageSetting == null) { 8089 throw new IllegalArgumentException("Unknown installer package: " 8090 + installerPackageName); 8091 } 8092 } else { 8093 installerPackageSetting = null; 8094 } 8095 8096 Signature[] callerSignature; 8097 Object obj = mSettings.getUserIdLPr(uid); 8098 if (obj != null) { 8099 if (obj instanceof SharedUserSetting) { 8100 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8101 } else if (obj instanceof PackageSetting) { 8102 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8103 } else { 8104 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8105 } 8106 } else { 8107 throw new SecurityException("Unknown calling uid " + uid); 8108 } 8109 8110 // Verify: can't set installerPackageName to a package that is 8111 // not signed with the same cert as the caller. 8112 if (installerPackageSetting != null) { 8113 if (compareSignatures(callerSignature, 8114 installerPackageSetting.signatures.mSignatures) 8115 != PackageManager.SIGNATURE_MATCH) { 8116 throw new SecurityException( 8117 "Caller does not have same cert as new installer package " 8118 + installerPackageName); 8119 } 8120 } 8121 8122 // Verify: if target already has an installer package, it must 8123 // be signed with the same cert as the caller. 8124 if (targetPackageSetting.installerPackageName != null) { 8125 PackageSetting setting = mSettings.mPackages.get( 8126 targetPackageSetting.installerPackageName); 8127 // If the currently set package isn't valid, then it's always 8128 // okay to change it. 8129 if (setting != null) { 8130 if (compareSignatures(callerSignature, 8131 setting.signatures.mSignatures) 8132 != PackageManager.SIGNATURE_MATCH) { 8133 throw new SecurityException( 8134 "Caller does not have same cert as old installer package " 8135 + targetPackageSetting.installerPackageName); 8136 } 8137 } 8138 } 8139 8140 // Okay! 8141 targetPackageSetting.installerPackageName = installerPackageName; 8142 scheduleWriteSettingsLocked(); 8143 } 8144 } 8145 8146 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8147 // Queue up an async operation since the package installation may take a little while. 8148 mHandler.post(new Runnable() { 8149 public void run() { 8150 mHandler.removeCallbacks(this); 8151 // Result object to be returned 8152 PackageInstalledInfo res = new PackageInstalledInfo(); 8153 res.returnCode = currentStatus; 8154 res.uid = -1; 8155 res.pkg = null; 8156 res.removedInfo = new PackageRemovedInfo(); 8157 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8158 args.doPreInstall(res.returnCode); 8159 synchronized (mInstallLock) { 8160 installPackageLI(args, true, res); 8161 } 8162 args.doPostInstall(res.returnCode, res.uid); 8163 } 8164 8165 // A restore should be performed at this point if (a) the install 8166 // succeeded, (b) the operation is not an update, and (c) the new 8167 // package has a backupAgent defined. 8168 final boolean update = res.removedInfo.removedPackage != null; 8169 boolean doRestore = (!update 8170 && res.pkg != null 8171 && res.pkg.applicationInfo.backupAgentName != null); 8172 8173 // Set up the post-install work request bookkeeping. This will be used 8174 // and cleaned up by the post-install event handling regardless of whether 8175 // there's a restore pass performed. Token values are >= 1. 8176 int token; 8177 if (mNextInstallToken < 0) mNextInstallToken = 1; 8178 token = mNextInstallToken++; 8179 8180 PostInstallData data = new PostInstallData(args, res); 8181 mRunningInstalls.put(token, data); 8182 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8183 8184 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8185 // Pass responsibility to the Backup Manager. It will perform a 8186 // restore if appropriate, then pass responsibility back to the 8187 // Package Manager to run the post-install observer callbacks 8188 // and broadcasts. 8189 IBackupManager bm = IBackupManager.Stub.asInterface( 8190 ServiceManager.getService(Context.BACKUP_SERVICE)); 8191 if (bm != null) { 8192 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8193 + " to BM for possible restore"); 8194 try { 8195 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8196 } catch (RemoteException e) { 8197 // can't happen; the backup manager is local 8198 } catch (Exception e) { 8199 Slog.e(TAG, "Exception trying to enqueue restore", e); 8200 doRestore = false; 8201 } 8202 } else { 8203 Slog.e(TAG, "Backup Manager not found!"); 8204 doRestore = false; 8205 } 8206 } 8207 8208 if (!doRestore) { 8209 // No restore possible, or the Backup Manager was mysteriously not 8210 // available -- just fire the post-install work request directly. 8211 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8212 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8213 mHandler.sendMessage(msg); 8214 } 8215 } 8216 }); 8217 } 8218 8219 private abstract class HandlerParams { 8220 private static final int MAX_RETRIES = 4; 8221 8222 /** 8223 * Number of times startCopy() has been attempted and had a non-fatal 8224 * error. 8225 */ 8226 private int mRetries = 0; 8227 8228 /** User handle for the user requesting the information or installation. */ 8229 private final UserHandle mUser; 8230 8231 HandlerParams(UserHandle user) { 8232 mUser = user; 8233 } 8234 8235 UserHandle getUser() { 8236 return mUser; 8237 } 8238 8239 final boolean startCopy() { 8240 boolean res; 8241 try { 8242 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8243 8244 if (++mRetries > MAX_RETRIES) { 8245 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8246 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8247 handleServiceError(); 8248 return false; 8249 } else { 8250 handleStartCopy(); 8251 res = true; 8252 } 8253 } catch (RemoteException e) { 8254 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8255 mHandler.sendEmptyMessage(MCS_RECONNECT); 8256 res = false; 8257 } 8258 handleReturnCode(); 8259 return res; 8260 } 8261 8262 final void serviceError() { 8263 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8264 handleServiceError(); 8265 handleReturnCode(); 8266 } 8267 8268 abstract void handleStartCopy() throws RemoteException; 8269 abstract void handleServiceError(); 8270 abstract void handleReturnCode(); 8271 } 8272 8273 class MeasureParams extends HandlerParams { 8274 private final PackageStats mStats; 8275 private boolean mSuccess; 8276 8277 private final IPackageStatsObserver mObserver; 8278 8279 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8280 super(new UserHandle(stats.userHandle)); 8281 mObserver = observer; 8282 mStats = stats; 8283 } 8284 8285 @Override 8286 public String toString() { 8287 return "MeasureParams{" 8288 + Integer.toHexString(System.identityHashCode(this)) 8289 + " " + mStats.packageName + "}"; 8290 } 8291 8292 @Override 8293 void handleStartCopy() throws RemoteException { 8294 synchronized (mInstallLock) { 8295 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8296 } 8297 8298 if (mSuccess) { 8299 final boolean mounted; 8300 if (Environment.isExternalStorageEmulated()) { 8301 mounted = true; 8302 } else { 8303 final String status = Environment.getExternalStorageState(); 8304 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8305 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8306 } 8307 8308 if (mounted) { 8309 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8310 8311 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8312 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8313 8314 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8315 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8316 8317 // Always subtract cache size, since it's a subdirectory 8318 mStats.externalDataSize -= mStats.externalCacheSize; 8319 8320 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8321 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8322 8323 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8324 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8325 } 8326 } 8327 } 8328 8329 @Override 8330 void handleReturnCode() { 8331 if (mObserver != null) { 8332 try { 8333 mObserver.onGetStatsCompleted(mStats, mSuccess); 8334 } catch (RemoteException e) { 8335 Slog.i(TAG, "Observer no longer exists."); 8336 } 8337 } 8338 } 8339 8340 @Override 8341 void handleServiceError() { 8342 Slog.e(TAG, "Could not measure application " + mStats.packageName 8343 + " external storage"); 8344 } 8345 } 8346 8347 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8348 throws RemoteException { 8349 long result = 0; 8350 for (File path : paths) { 8351 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8352 } 8353 return result; 8354 } 8355 8356 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8357 for (File path : paths) { 8358 try { 8359 mcs.clearDirectory(path.getAbsolutePath()); 8360 } catch (RemoteException e) { 8361 } 8362 } 8363 } 8364 8365 class InstallParams extends HandlerParams { 8366 final IPackageInstallObserver observer; 8367 final IPackageInstallObserver2 observer2; 8368 int flags; 8369 8370 private final Uri mPackageURI; 8371 final String installerPackageName; 8372 final VerificationParams verificationParams; 8373 private InstallArgs mArgs; 8374 private int mRet; 8375 private File mTempPackage; 8376 final ContainerEncryptionParams encryptionParams; 8377 final String packageAbiOverride; 8378 final String packageInstructionSetOverride; 8379 8380 InstallParams(Uri packageURI, 8381 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 8382 int flags, String installerPackageName, VerificationParams verificationParams, 8383 ContainerEncryptionParams encryptionParams, UserHandle user, 8384 String packageAbiOverride) { 8385 super(user); 8386 this.mPackageURI = packageURI; 8387 this.flags = flags; 8388 this.observer = observer; 8389 this.observer2 = observer2; 8390 this.installerPackageName = installerPackageName; 8391 this.verificationParams = verificationParams; 8392 this.encryptionParams = encryptionParams; 8393 this.packageAbiOverride = packageAbiOverride; 8394 this.packageInstructionSetOverride = (packageAbiOverride == null) ? 8395 packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride); 8396 } 8397 8398 @Override 8399 public String toString() { 8400 return "InstallParams{" 8401 + Integer.toHexString(System.identityHashCode(this)) 8402 + " " + mPackageURI + "}"; 8403 } 8404 8405 public ManifestDigest getManifestDigest() { 8406 if (verificationParams == null) { 8407 return null; 8408 } 8409 return verificationParams.getManifestDigest(); 8410 } 8411 8412 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8413 String packageName = pkgLite.packageName; 8414 int installLocation = pkgLite.installLocation; 8415 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8416 // reader 8417 synchronized (mPackages) { 8418 PackageParser.Package pkg = mPackages.get(packageName); 8419 if (pkg != null) { 8420 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8421 // Check for downgrading. 8422 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8423 if (pkgLite.versionCode < pkg.mVersionCode) { 8424 Slog.w(TAG, "Can't install update of " + packageName 8425 + " update version " + pkgLite.versionCode 8426 + " is older than installed version " 8427 + pkg.mVersionCode); 8428 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8429 } 8430 } 8431 // Check for updated system application. 8432 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8433 if (onSd) { 8434 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8435 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8436 } 8437 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8438 } else { 8439 if (onSd) { 8440 // Install flag overrides everything. 8441 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8442 } 8443 // If current upgrade specifies particular preference 8444 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8445 // Application explicitly specified internal. 8446 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8447 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8448 // App explictly prefers external. Let policy decide 8449 } else { 8450 // Prefer previous location 8451 if (isExternal(pkg)) { 8452 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8453 } 8454 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8455 } 8456 } 8457 } else { 8458 // Invalid install. Return error code 8459 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8460 } 8461 } 8462 } 8463 // All the special cases have been taken care of. 8464 // Return result based on recommended install location. 8465 if (onSd) { 8466 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8467 } 8468 return pkgLite.recommendedInstallLocation; 8469 } 8470 8471 private long getMemoryLowThreshold() { 8472 final DeviceStorageMonitorInternal 8473 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8474 if (dsm == null) { 8475 return 0L; 8476 } 8477 return dsm.getMemoryLowThreshold(); 8478 } 8479 8480 /* 8481 * Invoke remote method to get package information and install 8482 * location values. Override install location based on default 8483 * policy if needed and then create install arguments based 8484 * on the install location. 8485 */ 8486 public void handleStartCopy() throws RemoteException { 8487 int ret = PackageManager.INSTALL_SUCCEEDED; 8488 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8489 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8490 PackageInfoLite pkgLite = null; 8491 8492 if (onInt && onSd) { 8493 // Check if both bits are set. 8494 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8495 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8496 } else { 8497 final long lowThreshold = getMemoryLowThreshold(); 8498 if (lowThreshold == 0L) { 8499 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8500 } 8501 8502 try { 8503 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI, 8504 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8505 8506 final File packageFile; 8507 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) { 8508 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir); 8509 if (mTempPackage != null) { 8510 ParcelFileDescriptor out; 8511 try { 8512 out = ParcelFileDescriptor.open(mTempPackage, 8513 ParcelFileDescriptor.MODE_READ_WRITE); 8514 } catch (FileNotFoundException e) { 8515 out = null; 8516 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI); 8517 } 8518 8519 // Make a temporary file for decryption. 8520 ret = mContainerService 8521 .copyResource(mPackageURI, encryptionParams, out); 8522 IoUtils.closeQuietly(out); 8523 8524 packageFile = mTempPackage; 8525 8526 FileUtils.setPermissions(packageFile.getAbsolutePath(), 8527 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP 8528 | FileUtils.S_IROTH, 8529 -1, -1); 8530 } else { 8531 packageFile = null; 8532 } 8533 } else { 8534 packageFile = new File(mPackageURI.getPath()); 8535 } 8536 8537 if (packageFile != null) { 8538 // Remote call to find out default install location 8539 final String packageFilePath = packageFile.getAbsolutePath(); 8540 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags, 8541 lowThreshold, packageAbiOverride); 8542 8543 /* 8544 * If we have too little free space, try to free cache 8545 * before giving up. 8546 */ 8547 if (pkgLite.recommendedInstallLocation 8548 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8549 final long size = mContainerService.calculateInstalledSize( 8550 packageFilePath, isForwardLocked(), packageAbiOverride); 8551 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8552 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, 8553 flags, lowThreshold, packageAbiOverride); 8554 } 8555 /* 8556 * The cache free must have deleted the file we 8557 * downloaded to install. 8558 * 8559 * TODO: fix the "freeCache" call to not delete 8560 * the file we care about. 8561 */ 8562 if (pkgLite.recommendedInstallLocation 8563 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8564 pkgLite.recommendedInstallLocation 8565 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8566 } 8567 } 8568 } 8569 } finally { 8570 mContext.revokeUriPermission(mPackageURI, 8571 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8572 } 8573 } 8574 8575 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8576 int loc = pkgLite.recommendedInstallLocation; 8577 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8578 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8579 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8580 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8581 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8582 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8583 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8584 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8585 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8586 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8587 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8588 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8589 } else { 8590 // Override with defaults if needed. 8591 loc = installLocationPolicy(pkgLite, flags); 8592 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8593 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8594 } else if (!onSd && !onInt) { 8595 // Override install location with flags 8596 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8597 // Set the flag to install on external media. 8598 flags |= PackageManager.INSTALL_EXTERNAL; 8599 flags &= ~PackageManager.INSTALL_INTERNAL; 8600 } else { 8601 // Make sure the flag for installing on external 8602 // media is unset 8603 flags |= PackageManager.INSTALL_INTERNAL; 8604 flags &= ~PackageManager.INSTALL_EXTERNAL; 8605 } 8606 } 8607 } 8608 } 8609 8610 final InstallArgs args = createInstallArgs(this); 8611 mArgs = args; 8612 8613 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8614 /* 8615 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8616 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8617 */ 8618 int userIdentifier = getUser().getIdentifier(); 8619 if (userIdentifier == UserHandle.USER_ALL 8620 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8621 userIdentifier = UserHandle.USER_OWNER; 8622 } 8623 8624 /* 8625 * Determine if we have any installed package verifiers. If we 8626 * do, then we'll defer to them to verify the packages. 8627 */ 8628 final int requiredUid = mRequiredVerifierPackage == null ? -1 8629 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8630 if (requiredUid != -1 && isVerificationEnabled(flags)) { 8631 final Intent verification = new Intent( 8632 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8633 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE); 8634 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8635 8636 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8637 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8638 0 /* TODO: Which userId? */); 8639 8640 if (DEBUG_VERIFY) { 8641 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8642 + verification.toString() + " with " + pkgLite.verifiers.length 8643 + " optional verifiers"); 8644 } 8645 8646 final int verificationId = mPendingVerificationToken++; 8647 8648 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8649 8650 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8651 installerPackageName); 8652 8653 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8654 8655 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8656 pkgLite.packageName); 8657 8658 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8659 pkgLite.versionCode); 8660 8661 if (verificationParams != null) { 8662 if (verificationParams.getVerificationURI() != null) { 8663 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8664 verificationParams.getVerificationURI()); 8665 } 8666 if (verificationParams.getOriginatingURI() != null) { 8667 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8668 verificationParams.getOriginatingURI()); 8669 } 8670 if (verificationParams.getReferrer() != null) { 8671 verification.putExtra(Intent.EXTRA_REFERRER, 8672 verificationParams.getReferrer()); 8673 } 8674 if (verificationParams.getOriginatingUid() >= 0) { 8675 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8676 verificationParams.getOriginatingUid()); 8677 } 8678 if (verificationParams.getInstallerUid() >= 0) { 8679 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8680 verificationParams.getInstallerUid()); 8681 } 8682 } 8683 8684 final PackageVerificationState verificationState = new PackageVerificationState( 8685 requiredUid, args); 8686 8687 mPendingVerification.append(verificationId, verificationState); 8688 8689 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8690 receivers, verificationState); 8691 8692 /* 8693 * If any sufficient verifiers were listed in the package 8694 * manifest, attempt to ask them. 8695 */ 8696 if (sufficientVerifiers != null) { 8697 final int N = sufficientVerifiers.size(); 8698 if (N == 0) { 8699 Slog.i(TAG, "Additional verifiers required, but none installed."); 8700 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8701 } else { 8702 for (int i = 0; i < N; i++) { 8703 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8704 8705 final Intent sufficientIntent = new Intent(verification); 8706 sufficientIntent.setComponent(verifierComponent); 8707 8708 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8709 } 8710 } 8711 } 8712 8713 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8714 mRequiredVerifierPackage, receivers); 8715 if (ret == PackageManager.INSTALL_SUCCEEDED 8716 && mRequiredVerifierPackage != null) { 8717 /* 8718 * Send the intent to the required verification agent, 8719 * but only start the verification timeout after the 8720 * target BroadcastReceivers have run. 8721 */ 8722 verification.setComponent(requiredVerifierComponent); 8723 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8724 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8725 new BroadcastReceiver() { 8726 @Override 8727 public void onReceive(Context context, Intent intent) { 8728 final Message msg = mHandler 8729 .obtainMessage(CHECK_PENDING_VERIFICATION); 8730 msg.arg1 = verificationId; 8731 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8732 } 8733 }, null, 0, null, null); 8734 8735 /* 8736 * We don't want the copy to proceed until verification 8737 * succeeds, so null out this field. 8738 */ 8739 mArgs = null; 8740 } 8741 } else { 8742 /* 8743 * No package verification is enabled, so immediately start 8744 * the remote call to initiate copy using temporary file. 8745 */ 8746 ret = args.copyApk(mContainerService, true); 8747 } 8748 } 8749 8750 mRet = ret; 8751 } 8752 8753 @Override 8754 void handleReturnCode() { 8755 // If mArgs is null, then MCS couldn't be reached. When it 8756 // reconnects, it will try again to install. At that point, this 8757 // will succeed. 8758 if (mArgs != null) { 8759 processPendingInstall(mArgs, mRet); 8760 8761 if (mTempPackage != null) { 8762 if (!mTempPackage.delete()) { 8763 Slog.w(TAG, "Couldn't delete temporary file: " + 8764 mTempPackage.getAbsolutePath()); 8765 } 8766 } 8767 } 8768 } 8769 8770 @Override 8771 void handleServiceError() { 8772 mArgs = createInstallArgs(this); 8773 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8774 } 8775 8776 public boolean isForwardLocked() { 8777 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8778 } 8779 8780 public Uri getPackageUri() { 8781 if (mTempPackage != null) { 8782 return Uri.fromFile(mTempPackage); 8783 } else { 8784 return mPackageURI; 8785 } 8786 } 8787 } 8788 8789 /* 8790 * Utility class used in movePackage api. 8791 * srcArgs and targetArgs are not set for invalid flags and make 8792 * sure to do null checks when invoking methods on them. 8793 * We probably want to return ErrorPrams for both failed installs 8794 * and moves. 8795 */ 8796 class MoveParams extends HandlerParams { 8797 final IPackageMoveObserver observer; 8798 final int flags; 8799 final String packageName; 8800 final InstallArgs srcArgs; 8801 final InstallArgs targetArgs; 8802 int uid; 8803 int mRet; 8804 8805 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8806 String packageName, String dataDir, String instructionSet, 8807 int uid, UserHandle user) { 8808 super(user); 8809 this.srcArgs = srcArgs; 8810 this.observer = observer; 8811 this.flags = flags; 8812 this.packageName = packageName; 8813 this.uid = uid; 8814 if (srcArgs != null) { 8815 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath())); 8816 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet); 8817 } else { 8818 targetArgs = null; 8819 } 8820 } 8821 8822 @Override 8823 public String toString() { 8824 return "MoveParams{" 8825 + Integer.toHexString(System.identityHashCode(this)) 8826 + " " + packageName + "}"; 8827 } 8828 8829 public void handleStartCopy() throws RemoteException { 8830 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8831 // Check for storage space on target medium 8832 if (!targetArgs.checkFreeStorage(mContainerService)) { 8833 Log.w(TAG, "Insufficient storage to install"); 8834 return; 8835 } 8836 8837 mRet = srcArgs.doPreCopy(); 8838 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8839 return; 8840 } 8841 8842 mRet = targetArgs.copyApk(mContainerService, false); 8843 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8844 srcArgs.doPostCopy(uid); 8845 return; 8846 } 8847 8848 mRet = srcArgs.doPostCopy(uid); 8849 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8850 return; 8851 } 8852 8853 mRet = targetArgs.doPreInstall(mRet); 8854 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8855 return; 8856 } 8857 8858 if (DEBUG_SD_INSTALL) { 8859 StringBuilder builder = new StringBuilder(); 8860 if (srcArgs != null) { 8861 builder.append("src: "); 8862 builder.append(srcArgs.getCodePath()); 8863 } 8864 if (targetArgs != null) { 8865 builder.append(" target : "); 8866 builder.append(targetArgs.getCodePath()); 8867 } 8868 Log.i(TAG, builder.toString()); 8869 } 8870 } 8871 8872 @Override 8873 void handleReturnCode() { 8874 targetArgs.doPostInstall(mRet, uid); 8875 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8876 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8877 currentStatus = PackageManager.MOVE_SUCCEEDED; 8878 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8879 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8880 } 8881 processPendingMove(this, currentStatus); 8882 } 8883 8884 @Override 8885 void handleServiceError() { 8886 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8887 } 8888 } 8889 8890 /** 8891 * Used during creation of InstallArgs 8892 * 8893 * @param flags package installation flags 8894 * @return true if should be installed on external storage 8895 */ 8896 private static boolean installOnSd(int flags) { 8897 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8898 return false; 8899 } 8900 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8901 return true; 8902 } 8903 return false; 8904 } 8905 8906 /** 8907 * Used during creation of InstallArgs 8908 * 8909 * @param flags package installation flags 8910 * @return true if should be installed as forward locked 8911 */ 8912 private static boolean installForwardLocked(int flags) { 8913 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8914 } 8915 8916 private InstallArgs createInstallArgs(InstallParams params) { 8917 if (installOnSd(params.flags) || params.isForwardLocked()) { 8918 return new AsecInstallArgs(params); 8919 } else { 8920 return new FileInstallArgs(params); 8921 } 8922 } 8923 8924 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath, 8925 String nativeLibraryPath, String instructionSet) { 8926 final boolean isInAsec; 8927 if (installOnSd(flags)) { 8928 /* Apps on SD card are always in ASEC containers. */ 8929 isInAsec = true; 8930 } else if (installForwardLocked(flags) 8931 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8932 /* 8933 * Forward-locked apps are only in ASEC containers if they're the 8934 * new style 8935 */ 8936 isInAsec = true; 8937 } else { 8938 isInAsec = false; 8939 } 8940 8941 if (isInAsec) { 8942 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8943 instructionSet, installOnSd(flags), installForwardLocked(flags)); 8944 } else { 8945 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8946 instructionSet); 8947 } 8948 } 8949 8950 // Used by package mover 8951 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir, 8952 String instructionSet) { 8953 if (installOnSd(flags) || installForwardLocked(flags)) { 8954 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/" 8955 + AsecInstallArgs.RES_FILE_NAME); 8956 return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags), 8957 installForwardLocked(flags)); 8958 } else { 8959 return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet); 8960 } 8961 } 8962 8963 static abstract class InstallArgs { 8964 final IPackageInstallObserver observer; 8965 final IPackageInstallObserver2 observer2; 8966 // Always refers to PackageManager flags only 8967 final int flags; 8968 final Uri packageURI; 8969 final String installerPackageName; 8970 final ManifestDigest manifestDigest; 8971 final UserHandle user; 8972 final String instructionSet; 8973 final String abiOverride; 8974 8975 InstallArgs(Uri packageURI, 8976 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 8977 int flags, String installerPackageName, ManifestDigest manifestDigest, 8978 UserHandle user, String instructionSet, String abiOverride) { 8979 this.packageURI = packageURI; 8980 this.flags = flags; 8981 this.observer = observer; 8982 this.observer2 = observer2; 8983 this.installerPackageName = installerPackageName; 8984 this.manifestDigest = manifestDigest; 8985 this.user = user; 8986 this.instructionSet = instructionSet; 8987 this.abiOverride = abiOverride; 8988 } 8989 8990 abstract void createCopyFile(); 8991 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 8992 abstract int doPreInstall(int status); 8993 abstract boolean doRename(int status, String pkgName, String oldCodePath); 8994 8995 abstract int doPostInstall(int status, int uid); 8996 abstract String getCodePath(); 8997 abstract String getResourcePath(); 8998 abstract String getNativeLibraryPath(); 8999 // Need installer lock especially for dex file removal. 9000 abstract void cleanUpResourcesLI(); 9001 abstract boolean doPostDeleteLI(boolean delete); 9002 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9003 9004 String[] getSplitCodePaths() { 9005 return null; 9006 } 9007 9008 /** 9009 * Called before the source arguments are copied. This is used mostly 9010 * for MoveParams when it needs to read the source file to put it in the 9011 * destination. 9012 */ 9013 int doPreCopy() { 9014 return PackageManager.INSTALL_SUCCEEDED; 9015 } 9016 9017 /** 9018 * Called after the source arguments are copied. This is used mostly for 9019 * MoveParams when it needs to read the source file to put it in the 9020 * destination. 9021 * 9022 * @return 9023 */ 9024 int doPostCopy(int uid) { 9025 return PackageManager.INSTALL_SUCCEEDED; 9026 } 9027 9028 protected boolean isFwdLocked() { 9029 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9030 } 9031 9032 UserHandle getUser() { 9033 return user; 9034 } 9035 } 9036 9037 class FileInstallArgs extends InstallArgs { 9038 File installDir; 9039 String codeFileName; 9040 String resourceFileName; 9041 String libraryPath; 9042 boolean created = false; 9043 9044 FileInstallArgs(InstallParams params) { 9045 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 9046 params.installerPackageName, params.getManifestDigest(), 9047 params.getUser(), params.packageInstructionSetOverride, 9048 params.packageAbiOverride); 9049 } 9050 9051 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9052 String instructionSet) { 9053 super(null, null, null, 0, null, null, null, instructionSet, null); 9054 File codeFile = new File(fullCodePath); 9055 installDir = codeFile.getParentFile(); 9056 codeFileName = fullCodePath; 9057 resourceFileName = fullResourcePath; 9058 libraryPath = nativeLibraryPath; 9059 } 9060 9061 FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) { 9062 super(packageURI, null, null, 0, null, null, null, instructionSet, null); 9063 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 9064 String apkName = getNextCodePath(null, pkgName, ".apk"); 9065 codeFileName = new File(installDir, apkName + ".apk").getPath(); 9066 resourceFileName = getResourcePathFromCodePath(); 9067 libraryPath = new File(mAppLibInstallDir, pkgName).getPath(); 9068 } 9069 9070 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9071 final long lowThreshold; 9072 9073 final DeviceStorageMonitorInternal 9074 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9075 if (dsm == null) { 9076 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9077 lowThreshold = 0L; 9078 } else { 9079 if (dsm.isMemoryLow()) { 9080 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9081 return false; 9082 } 9083 9084 lowThreshold = dsm.getMemoryLowThreshold(); 9085 } 9086 9087 try { 9088 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9089 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9090 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold); 9091 } finally { 9092 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9093 } 9094 } 9095 9096 void createCopyFile() { 9097 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 9098 codeFileName = createTempPackageFile(installDir).getPath(); 9099 resourceFileName = getResourcePathFromCodePath(); 9100 libraryPath = getLibraryPathFromCodePath(); 9101 created = true; 9102 } 9103 9104 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9105 if (temp) { 9106 // Generate temp file name 9107 createCopyFile(); 9108 } 9109 // Get a ParcelFileDescriptor to write to the output file 9110 File codeFile = new File(codeFileName); 9111 if (!created) { 9112 try { 9113 codeFile.createNewFile(); 9114 // Set permissions 9115 if (!setPermissions()) { 9116 // Failed setting permissions. 9117 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9118 } 9119 } catch (IOException e) { 9120 Slog.w(TAG, "Failed to create file " + codeFile); 9121 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9122 } 9123 } 9124 ParcelFileDescriptor out = null; 9125 try { 9126 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 9127 } catch (FileNotFoundException e) { 9128 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 9129 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9130 } 9131 // Copy the resource now 9132 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9133 try { 9134 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9135 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9136 ret = imcs.copyResource(packageURI, null, out); 9137 } finally { 9138 IoUtils.closeQuietly(out); 9139 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9140 } 9141 9142 if (isFwdLocked()) { 9143 final File destResourceFile = new File(getResourcePath()); 9144 9145 // Copy the public files 9146 try { 9147 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 9148 } catch (IOException e) { 9149 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 9150 + " forward-locked app."); 9151 destResourceFile.delete(); 9152 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9153 } 9154 } 9155 9156 final File nativeLibraryFile = new File(getNativeLibraryPath()); 9157 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath()); 9158 if (nativeLibraryFile.exists()) { 9159 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 9160 nativeLibraryFile.delete(); 9161 } 9162 9163 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(codeFile); 9164 String[] abiList = (abiOverride != null) ? 9165 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9166 try { 9167 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 9168 abiOverride == null && 9169 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9170 abiList = Build.SUPPORTED_32_BIT_ABIS; 9171 } 9172 9173 int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList); 9174 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9175 return copyRet; 9176 } 9177 } catch (IOException e) { 9178 Slog.e(TAG, "Copying native libraries failed", e); 9179 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9180 } finally { 9181 handle.close(); 9182 } 9183 9184 return ret; 9185 } 9186 9187 int doPreInstall(int status) { 9188 if (status != PackageManager.INSTALL_SUCCEEDED) { 9189 cleanUp(); 9190 } 9191 return status; 9192 } 9193 9194 boolean doRename(int status, final String pkgName, String oldCodePath) { 9195 if (status != PackageManager.INSTALL_SUCCEEDED) { 9196 cleanUp(); 9197 return false; 9198 } else { 9199 final File oldCodeFile = new File(getCodePath()); 9200 final File oldResourceFile = new File(getResourcePath()); 9201 final File oldLibraryFile = new File(getNativeLibraryPath()); 9202 9203 // Rename APK file based on packageName 9204 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 9205 final File newCodeFile = new File(installDir, apkName + ".apk"); 9206 if (!oldCodeFile.renameTo(newCodeFile)) { 9207 return false; 9208 } 9209 codeFileName = newCodeFile.getPath(); 9210 9211 // Rename public resource file if it's forward-locked. 9212 final File newResFile = new File(getResourcePathFromCodePath()); 9213 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 9214 return false; 9215 } 9216 resourceFileName = newResFile.getPath(); 9217 9218 // Rename library path 9219 final File newLibraryFile = new File(getLibraryPathFromCodePath()); 9220 if (newLibraryFile.exists()) { 9221 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile); 9222 newLibraryFile.delete(); 9223 } 9224 if (!oldLibraryFile.renameTo(newLibraryFile)) { 9225 Slog.e(TAG, "Cannot rename native library directory " 9226 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath()); 9227 return false; 9228 } 9229 libraryPath = newLibraryFile.getPath(); 9230 9231 // Attempt to set permissions 9232 if (!setPermissions()) { 9233 return false; 9234 } 9235 9236 if (!SELinux.restorecon(newCodeFile)) { 9237 return false; 9238 } 9239 9240 return true; 9241 } 9242 } 9243 9244 int doPostInstall(int status, int uid) { 9245 if (status != PackageManager.INSTALL_SUCCEEDED) { 9246 cleanUp(); 9247 } 9248 return status; 9249 } 9250 9251 private String getResourcePathFromCodePath() { 9252 final String codePath = getCodePath(); 9253 if (isFwdLocked()) { 9254 final StringBuilder sb = new StringBuilder(); 9255 9256 sb.append(mAppInstallDir.getPath()); 9257 sb.append('/'); 9258 sb.append(getApkName(codePath)); 9259 sb.append(".zip"); 9260 9261 /* 9262 * If our APK is a temporary file, mark the resource as a 9263 * temporary file as well so it can be cleaned up after 9264 * catastrophic failure. 9265 */ 9266 if (codePath.endsWith(".tmp")) { 9267 sb.append(".tmp"); 9268 } 9269 9270 return sb.toString(); 9271 } else { 9272 return codePath; 9273 } 9274 } 9275 9276 private String getLibraryPathFromCodePath() { 9277 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath(); 9278 } 9279 9280 @Override 9281 String getCodePath() { 9282 return codeFileName; 9283 } 9284 9285 @Override 9286 String getResourcePath() { 9287 return resourceFileName; 9288 } 9289 9290 @Override 9291 String getNativeLibraryPath() { 9292 if (libraryPath == null) { 9293 libraryPath = getLibraryPathFromCodePath(); 9294 } 9295 return libraryPath; 9296 } 9297 9298 private boolean cleanUp() { 9299 boolean ret = true; 9300 String sourceDir = getCodePath(); 9301 String publicSourceDir = getResourcePath(); 9302 if (sourceDir != null) { 9303 File sourceFile = new File(sourceDir); 9304 if (!sourceFile.exists()) { 9305 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 9306 ret = false; 9307 } 9308 // Delete application's code and resources 9309 sourceFile.delete(); 9310 } 9311 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 9312 final File publicSourceFile = new File(publicSourceDir); 9313 if (!publicSourceFile.exists()) { 9314 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 9315 } 9316 if (publicSourceFile.exists()) { 9317 publicSourceFile.delete(); 9318 } 9319 } 9320 9321 if (libraryPath != null) { 9322 File nativeLibraryFile = new File(libraryPath); 9323 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 9324 if (!nativeLibraryFile.delete()) { 9325 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath); 9326 } 9327 } 9328 9329 return ret; 9330 } 9331 9332 void cleanUpResourcesLI() { 9333 String sourceDir = getCodePath(); 9334 if (cleanUp()) { 9335 if (instructionSet == null) { 9336 throw new IllegalStateException("instructionSet == null"); 9337 } 9338 int retCode = mInstaller.rmdex(sourceDir, instructionSet); 9339 if (retCode < 0) { 9340 Slog.w(TAG, "Couldn't remove dex file for package: " 9341 + " at location " 9342 + sourceDir + ", retcode=" + retCode); 9343 // we don't consider this to be a failure of the core package deletion 9344 } 9345 } 9346 } 9347 9348 private boolean setPermissions() { 9349 // TODO Do this in a more elegant way later on. for now just a hack 9350 if (!isFwdLocked()) { 9351 final int filePermissions = 9352 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 9353 |FileUtils.S_IROTH; 9354 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 9355 if (retCode != 0) { 9356 Slog.e(TAG, "Couldn't set new package file permissions for " + 9357 getCodePath() 9358 + ". The return code was: " + retCode); 9359 // TODO Define new internal error 9360 return false; 9361 } 9362 return true; 9363 } 9364 return true; 9365 } 9366 9367 boolean doPostDeleteLI(boolean delete) { 9368 // XXX err, shouldn't we respect the delete flag? 9369 cleanUpResourcesLI(); 9370 return true; 9371 } 9372 } 9373 9374 private boolean isAsecExternal(String cid) { 9375 final String asecPath = PackageHelper.getSdFilesystem(cid); 9376 return !asecPath.startsWith(mAsecInternalPath); 9377 } 9378 9379 /** 9380 * Extract the MountService "container ID" from the full code path of an 9381 * .apk. 9382 */ 9383 static String cidFromCodePath(String fullCodePath) { 9384 int eidx = fullCodePath.lastIndexOf("/"); 9385 String subStr1 = fullCodePath.substring(0, eidx); 9386 int sidx = subStr1.lastIndexOf("/"); 9387 return subStr1.substring(sidx+1, eidx); 9388 } 9389 9390 class AsecInstallArgs extends InstallArgs { 9391 static final String RES_FILE_NAME = "pkg.apk"; 9392 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9393 9394 String cid; 9395 String packagePath; 9396 String resourcePath; 9397 String libraryPath; 9398 9399 AsecInstallArgs(InstallParams params) { 9400 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 9401 params.installerPackageName, params.getManifestDigest(), 9402 params.getUser(), params.packageInstructionSetOverride, 9403 params.packageAbiOverride); 9404 } 9405 9406 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9407 String instructionSet, boolean isExternal, boolean isForwardLocked) { 9408 super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9409 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9410 null, null, null, instructionSet, null); 9411 // Extract cid from fullCodePath 9412 int eidx = fullCodePath.lastIndexOf("/"); 9413 String subStr1 = fullCodePath.substring(0, eidx); 9414 int sidx = subStr1.lastIndexOf("/"); 9415 cid = subStr1.substring(sidx+1, eidx); 9416 setCachePath(subStr1); 9417 } 9418 9419 AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) { 9420 super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 9421 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9422 null, null, null, instructionSet, null); 9423 this.cid = cid; 9424 setCachePath(PackageHelper.getSdDir(cid)); 9425 } 9426 9427 AsecInstallArgs(Uri packageURI, String cid, String instructionSet, 9428 boolean isExternal, boolean isForwardLocked) { 9429 super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9430 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9431 null, null, null, instructionSet, null); 9432 this.cid = cid; 9433 } 9434 9435 void createCopyFile() { 9436 cid = getTempContainerId(); 9437 } 9438 9439 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9440 try { 9441 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9442 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9443 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked(), abiOverride); 9444 } finally { 9445 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9446 } 9447 } 9448 9449 private final boolean isExternal() { 9450 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9451 } 9452 9453 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9454 if (temp) { 9455 createCopyFile(); 9456 } else { 9457 /* 9458 * Pre-emptively destroy the container since it's destroyed if 9459 * copying fails due to it existing anyway. 9460 */ 9461 PackageHelper.destroySdDir(cid); 9462 } 9463 9464 final String newCachePath; 9465 try { 9466 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9467 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9468 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(), 9469 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked(), 9470 abiOverride); 9471 } finally { 9472 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9473 } 9474 9475 if (newCachePath != null) { 9476 setCachePath(newCachePath); 9477 return PackageManager.INSTALL_SUCCEEDED; 9478 } else { 9479 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9480 } 9481 } 9482 9483 @Override 9484 String getCodePath() { 9485 return packagePath; 9486 } 9487 9488 @Override 9489 String getResourcePath() { 9490 return resourcePath; 9491 } 9492 9493 @Override 9494 String getNativeLibraryPath() { 9495 return libraryPath; 9496 } 9497 9498 int doPreInstall(int status) { 9499 if (status != PackageManager.INSTALL_SUCCEEDED) { 9500 // Destroy container 9501 PackageHelper.destroySdDir(cid); 9502 } else { 9503 boolean mounted = PackageHelper.isContainerMounted(cid); 9504 if (!mounted) { 9505 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9506 Process.SYSTEM_UID); 9507 if (newCachePath != null) { 9508 setCachePath(newCachePath); 9509 } else { 9510 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9511 } 9512 } 9513 } 9514 return status; 9515 } 9516 9517 boolean doRename(int status, final String pkgName, 9518 String oldCodePath) { 9519 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 9520 String newCachePath = null; 9521 if (PackageHelper.isContainerMounted(cid)) { 9522 // Unmount the container 9523 if (!PackageHelper.unMountSdDir(cid)) { 9524 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9525 return false; 9526 } 9527 } 9528 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9529 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9530 " which might be stale. Will try to clean up."); 9531 // Clean up the stale container and proceed to recreate. 9532 if (!PackageHelper.destroySdDir(newCacheId)) { 9533 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9534 return false; 9535 } 9536 // Successfully cleaned up stale container. Try to rename again. 9537 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9538 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9539 + " inspite of cleaning it up."); 9540 return false; 9541 } 9542 } 9543 if (!PackageHelper.isContainerMounted(newCacheId)) { 9544 Slog.w(TAG, "Mounting container " + newCacheId); 9545 newCachePath = PackageHelper.mountSdDir(newCacheId, 9546 getEncryptKey(), Process.SYSTEM_UID); 9547 } else { 9548 newCachePath = PackageHelper.getSdDir(newCacheId); 9549 } 9550 if (newCachePath == null) { 9551 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9552 return false; 9553 } 9554 Log.i(TAG, "Succesfully renamed " + cid + 9555 " to " + newCacheId + 9556 " at new path: " + newCachePath); 9557 cid = newCacheId; 9558 setCachePath(newCachePath); 9559 return true; 9560 } 9561 9562 private void setCachePath(String newCachePath) { 9563 File cachePath = new File(newCachePath); 9564 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 9565 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9566 9567 if (isFwdLocked()) { 9568 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9569 } else { 9570 resourcePath = packagePath; 9571 } 9572 } 9573 9574 int doPostInstall(int status, int uid) { 9575 if (status != PackageManager.INSTALL_SUCCEEDED) { 9576 cleanUp(); 9577 } else { 9578 final int groupOwner; 9579 final String protectedFile; 9580 if (isFwdLocked()) { 9581 groupOwner = UserHandle.getSharedAppGid(uid); 9582 protectedFile = RES_FILE_NAME; 9583 } else { 9584 groupOwner = -1; 9585 protectedFile = null; 9586 } 9587 9588 if (uid < Process.FIRST_APPLICATION_UID 9589 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9590 Slog.e(TAG, "Failed to finalize " + cid); 9591 PackageHelper.destroySdDir(cid); 9592 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9593 } 9594 9595 boolean mounted = PackageHelper.isContainerMounted(cid); 9596 if (!mounted) { 9597 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9598 } 9599 } 9600 return status; 9601 } 9602 9603 private void cleanUp() { 9604 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9605 9606 // Destroy secure container 9607 PackageHelper.destroySdDir(cid); 9608 } 9609 9610 void cleanUpResourcesLI() { 9611 String sourceFile = getCodePath(); 9612 // Remove dex file 9613 if (instructionSet == null) { 9614 throw new IllegalStateException("instructionSet == null"); 9615 } 9616 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9617 if (retCode < 0) { 9618 Slog.w(TAG, "Couldn't remove dex file for package: " 9619 + " at location " 9620 + sourceFile.toString() + ", retcode=" + retCode); 9621 // we don't consider this to be a failure of the core package deletion 9622 } 9623 cleanUp(); 9624 } 9625 9626 boolean matchContainer(String app) { 9627 if (cid.startsWith(app)) { 9628 return true; 9629 } 9630 return false; 9631 } 9632 9633 String getPackageName() { 9634 return getAsecPackageName(cid); 9635 } 9636 9637 boolean doPostDeleteLI(boolean delete) { 9638 boolean ret = false; 9639 boolean mounted = PackageHelper.isContainerMounted(cid); 9640 if (mounted) { 9641 // Unmount first 9642 ret = PackageHelper.unMountSdDir(cid); 9643 } 9644 if (ret && delete) { 9645 cleanUpResourcesLI(); 9646 } 9647 return ret; 9648 } 9649 9650 @Override 9651 int doPreCopy() { 9652 if (isFwdLocked()) { 9653 if (!PackageHelper.fixSdPermissions(cid, 9654 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9655 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9656 } 9657 } 9658 9659 return PackageManager.INSTALL_SUCCEEDED; 9660 } 9661 9662 @Override 9663 int doPostCopy(int uid) { 9664 if (isFwdLocked()) { 9665 if (uid < Process.FIRST_APPLICATION_UID 9666 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9667 RES_FILE_NAME)) { 9668 Slog.e(TAG, "Failed to finalize " + cid); 9669 PackageHelper.destroySdDir(cid); 9670 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9671 } 9672 } 9673 9674 return PackageManager.INSTALL_SUCCEEDED; 9675 } 9676 } 9677 9678 static String getAsecPackageName(String packageCid) { 9679 int idx = packageCid.lastIndexOf("-"); 9680 if (idx == -1) { 9681 return packageCid; 9682 } 9683 return packageCid.substring(0, idx); 9684 } 9685 9686 // Utility method used to create code paths based on package name and available index. 9687 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9688 String idxStr = ""; 9689 int idx = 1; 9690 // Fall back to default value of idx=1 if prefix is not 9691 // part of oldCodePath 9692 if (oldCodePath != null) { 9693 String subStr = oldCodePath; 9694 // Drop the suffix right away 9695 if (subStr.endsWith(suffix)) { 9696 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9697 } 9698 // If oldCodePath already contains prefix find out the 9699 // ending index to either increment or decrement. 9700 int sidx = subStr.lastIndexOf(prefix); 9701 if (sidx != -1) { 9702 subStr = subStr.substring(sidx + prefix.length()); 9703 if (subStr != null) { 9704 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9705 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9706 } 9707 try { 9708 idx = Integer.parseInt(subStr); 9709 if (idx <= 1) { 9710 idx++; 9711 } else { 9712 idx--; 9713 } 9714 } catch(NumberFormatException e) { 9715 } 9716 } 9717 } 9718 } 9719 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9720 return prefix + idxStr; 9721 } 9722 9723 // Utility method used to ignore ADD/REMOVE events 9724 // by directory observer. 9725 private static boolean ignoreCodePath(String fullPathStr) { 9726 String apkName = getApkName(fullPathStr); 9727 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9728 if (idx != -1 && ((idx+1) < apkName.length())) { 9729 // Make sure the package ends with a numeral 9730 String version = apkName.substring(idx+1); 9731 try { 9732 Integer.parseInt(version); 9733 return true; 9734 } catch (NumberFormatException e) {} 9735 } 9736 return false; 9737 } 9738 9739 // Utility method that returns the relative package path with respect 9740 // to the installation directory. Like say for /data/data/com.test-1.apk 9741 // string com.test-1 is returned. 9742 static String getApkName(String codePath) { 9743 if (codePath == null) { 9744 return null; 9745 } 9746 int sidx = codePath.lastIndexOf("/"); 9747 int eidx = codePath.lastIndexOf("."); 9748 if (eidx == -1) { 9749 eidx = codePath.length(); 9750 } else if (eidx == 0) { 9751 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 9752 return null; 9753 } 9754 return codePath.substring(sidx+1, eidx); 9755 } 9756 9757 private static String[] deriveSplitResPaths(String[] splitCodePaths) { 9758 String[] splitResPaths = null; 9759 if (!ArrayUtils.isEmpty(splitCodePaths)) { 9760 splitResPaths = new String[splitCodePaths.length]; 9761 for (int i = 0; i < splitCodePaths.length; i++) { 9762 final String splitCodePath = splitCodePaths[i]; 9763 final String resName = getApkName(splitCodePath) + ".zip"; 9764 splitResPaths[i] = new File(new File(splitCodePath).getParentFile(), 9765 resName).getAbsolutePath(); 9766 } 9767 } 9768 return splitResPaths; 9769 } 9770 9771 class PackageInstalledInfo { 9772 String name; 9773 int uid; 9774 // The set of users that originally had this package installed. 9775 int[] origUsers; 9776 // The set of users that now have this package installed. 9777 int[] newUsers; 9778 PackageParser.Package pkg; 9779 int returnCode; 9780 PackageRemovedInfo removedInfo; 9781 9782 // In some error cases we want to convey more info back to the observer 9783 String origPackage; 9784 String origPermission; 9785 } 9786 9787 /* 9788 * Install a non-existing package. 9789 */ 9790 private void installNewPackageLI(PackageParser.Package pkg, 9791 int parseFlags, int scanMode, UserHandle user, 9792 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9793 // Remember this for later, in case we need to rollback this install 9794 String pkgName = pkg.packageName; 9795 9796 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9797 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9798 synchronized(mPackages) { 9799 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9800 // A package with the same name is already installed, though 9801 // it has been renamed to an older name. The package we 9802 // are trying to install should be installed as an update to 9803 // the existing one, but that has not been requested, so bail. 9804 Slog.w(TAG, "Attempt to re-install " + pkgName 9805 + " without first uninstalling package running as " 9806 + mSettings.mRenamedPackages.get(pkgName)); 9807 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9808 return; 9809 } 9810 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9811 // Don't allow installation over an existing package with the same name. 9812 Slog.w(TAG, "Attempt to re-install " + pkgName 9813 + " without first uninstalling."); 9814 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9815 return; 9816 } 9817 } 9818 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9819 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9820 System.currentTimeMillis(), user, abiOverride); 9821 if (newPackage == null) { 9822 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9823 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9824 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9825 } 9826 } else { 9827 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9828 // delete the partially installed application. the data directory will have to be 9829 // restored if it was already existing 9830 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9831 // remove package from internal structures. Note that we want deletePackageX to 9832 // delete the package data and cache directories that it created in 9833 // scanPackageLocked, unless those directories existed before we even tried to 9834 // install. 9835 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9836 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9837 res.removedInfo, true); 9838 } 9839 } 9840 } 9841 9842 private void replacePackageLI(PackageParser.Package pkg, 9843 int parseFlags, int scanMode, UserHandle user, 9844 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9845 9846 PackageParser.Package oldPackage; 9847 String pkgName = pkg.packageName; 9848 int[] allUsers; 9849 boolean[] perUserInstalled; 9850 9851 // First find the old package info and check signatures 9852 synchronized(mPackages) { 9853 oldPackage = mPackages.get(pkgName); 9854 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9855 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9856 != PackageManager.SIGNATURE_MATCH) { 9857 Slog.w(TAG, "New package has a different signature: " + pkgName); 9858 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9859 return; 9860 } 9861 9862 // In case of rollback, remember per-user/profile install state 9863 PackageSetting ps = mSettings.mPackages.get(pkgName); 9864 allUsers = sUserManager.getUserIds(); 9865 perUserInstalled = new boolean[allUsers.length]; 9866 for (int i = 0; i < allUsers.length; i++) { 9867 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9868 } 9869 } 9870 boolean sysPkg = (isSystemApp(oldPackage)); 9871 if (sysPkg) { 9872 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9873 user, allUsers, perUserInstalled, installerPackageName, res, 9874 abiOverride); 9875 } else { 9876 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9877 user, allUsers, perUserInstalled, installerPackageName, res, 9878 abiOverride); 9879 } 9880 } 9881 9882 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9883 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9884 int[] allUsers, boolean[] perUserInstalled, 9885 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9886 PackageParser.Package newPackage = null; 9887 String pkgName = deletedPackage.packageName; 9888 boolean deletedPkg = true; 9889 boolean updatedSettings = false; 9890 9891 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9892 + deletedPackage); 9893 long origUpdateTime; 9894 if (pkg.mExtras != null) { 9895 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9896 } else { 9897 origUpdateTime = 0; 9898 } 9899 9900 // First delete the existing package while retaining the data directory 9901 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9902 res.removedInfo, true)) { 9903 // If the existing package wasn't successfully deleted 9904 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9905 deletedPkg = false; 9906 } else { 9907 // Successfully deleted the old package. Now proceed with re-installation 9908 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9909 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9910 System.currentTimeMillis(), user, abiOverride); 9911 if (newPackage == null) { 9912 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9913 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9914 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9915 } 9916 } else { 9917 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9918 updatedSettings = true; 9919 } 9920 } 9921 9922 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9923 // remove package from internal structures. Note that we want deletePackageX to 9924 // delete the package data and cache directories that it created in 9925 // scanPackageLocked, unless those directories existed before we even tried to 9926 // install. 9927 if(updatedSettings) { 9928 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9929 deletePackageLI( 9930 pkgName, null, true, allUsers, perUserInstalled, 9931 PackageManager.DELETE_KEEP_DATA, 9932 res.removedInfo, true); 9933 } 9934 // Since we failed to install the new package we need to restore the old 9935 // package that we deleted. 9936 if (deletedPkg) { 9937 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9938 File restoreFile = new File(deletedPackage.codePath); 9939 // Parse old package 9940 boolean oldOnSd = isExternal(deletedPackage); 9941 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9942 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9943 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9944 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 9945 | SCAN_UPDATE_TIME; 9946 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 9947 origUpdateTime, null, null) == null) { 9948 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 9949 return; 9950 } 9951 // Restore of old package succeeded. Update permissions. 9952 // writer 9953 synchronized (mPackages) { 9954 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9955 UPDATE_PERMISSIONS_ALL); 9956 // can downgrade to reader 9957 mSettings.writeLPr(); 9958 } 9959 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9960 } 9961 } 9962 } 9963 9964 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9965 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9966 int[] allUsers, boolean[] perUserInstalled, 9967 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9968 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9969 + ", old=" + deletedPackage); 9970 PackageParser.Package newPackage = null; 9971 boolean updatedSettings = false; 9972 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 9973 PackageParser.PARSE_IS_SYSTEM; 9974 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9975 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9976 } 9977 String packageName = deletedPackage.packageName; 9978 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9979 if (packageName == null) { 9980 Slog.w(TAG, "Attempt to delete null packageName."); 9981 return; 9982 } 9983 PackageParser.Package oldPkg; 9984 PackageSetting oldPkgSetting; 9985 // reader 9986 synchronized (mPackages) { 9987 oldPkg = mPackages.get(packageName); 9988 oldPkgSetting = mSettings.mPackages.get(packageName); 9989 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 9990 (oldPkgSetting == null)) { 9991 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 9992 return; 9993 } 9994 } 9995 9996 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 9997 9998 res.removedInfo.uid = oldPkg.applicationInfo.uid; 9999 res.removedInfo.removedPackage = packageName; 10000 // Remove existing system package 10001 removePackageLI(oldPkgSetting, true); 10002 // writer 10003 synchronized (mPackages) { 10004 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10005 // We didn't need to disable the .apk as a current system package, 10006 // which means we are replacing another update that is already 10007 // installed. We need to make sure to delete the older one's .apk. 10008 res.removedInfo.args = createInstallArgs(0, 10009 deletedPackage.applicationInfo.sourceDir, 10010 deletedPackage.applicationInfo.publicSourceDir, 10011 deletedPackage.applicationInfo.nativeLibraryDir, 10012 getAppInstructionSet(deletedPackage.applicationInfo)); 10013 } else { 10014 res.removedInfo.args = null; 10015 } 10016 } 10017 10018 // Successfully disabled the old package. Now proceed with re-installation 10019 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 10020 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10021 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10022 if (newPackage == null) { 10023 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 10024 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 10025 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 10026 } 10027 } else { 10028 if (newPackage.mExtras != null) { 10029 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 10030 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10031 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10032 10033 // is the update attempting to change shared user? that isn't going to work... 10034 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10035 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 10036 + " to " + newPkgSetting.sharedUser); 10037 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 10038 updatedSettings = true; 10039 } 10040 } 10041 10042 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10043 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10044 updatedSettings = true; 10045 } 10046 } 10047 10048 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10049 // Re installation failed. Restore old information 10050 // Remove new pkg information 10051 if (newPackage != null) { 10052 removeInstalledPackageLI(newPackage, true); 10053 } 10054 // Add back the old system package 10055 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null); 10056 // Restore the old system information in Settings 10057 synchronized(mPackages) { 10058 if (updatedSettings) { 10059 mSettings.enableSystemPackageLPw(packageName); 10060 mSettings.setInstallerPackageName(packageName, 10061 oldPkgSetting.installerPackageName); 10062 } 10063 mSettings.writeLPr(); 10064 } 10065 } 10066 } 10067 10068 // Utility method used to move dex files during install. 10069 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10070 // TODO: extend to move split APK dex files 10071 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10072 final String instructionSet = getAppInstructionSet(newPackage.applicationInfo); 10073 int retCode = mInstaller.movedex(oldCodePath, newPackage.codePath, 10074 instructionSet); 10075 if (retCode != 0) { 10076 /* 10077 * Programs may be lazily run through dexopt, so the 10078 * source may not exist. However, something seems to 10079 * have gone wrong, so note that dexopt needs to be 10080 * run again and remove the source file. In addition, 10081 * remove the target to make sure there isn't a stale 10082 * file from a previous version of the package. 10083 */ 10084 newPackage.mDexOptNeeded = true; 10085 mInstaller.rmdex(oldCodePath, instructionSet); 10086 mInstaller.rmdex(newPackage.codePath, instructionSet); 10087 } 10088 } 10089 return PackageManager.INSTALL_SUCCEEDED; 10090 } 10091 10092 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10093 int[] allUsers, boolean[] perUserInstalled, 10094 PackageInstalledInfo res) { 10095 String pkgName = newPackage.packageName; 10096 synchronized (mPackages) { 10097 //write settings. the installStatus will be incomplete at this stage. 10098 //note that the new package setting would have already been 10099 //added to mPackages. It hasn't been persisted yet. 10100 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10101 mSettings.writeLPr(); 10102 } 10103 10104 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10105 10106 synchronized (mPackages) { 10107 updatePermissionsLPw(newPackage.packageName, newPackage, 10108 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10109 ? UPDATE_PERMISSIONS_ALL : 0)); 10110 // For system-bundled packages, we assume that installing an upgraded version 10111 // of the package implies that the user actually wants to run that new code, 10112 // so we enable the package. 10113 if (isSystemApp(newPackage)) { 10114 // NB: implicit assumption that system package upgrades apply to all users 10115 if (DEBUG_INSTALL) { 10116 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10117 } 10118 PackageSetting ps = mSettings.mPackages.get(pkgName); 10119 if (ps != null) { 10120 if (res.origUsers != null) { 10121 for (int userHandle : res.origUsers) { 10122 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10123 userHandle, installerPackageName); 10124 } 10125 } 10126 // Also convey the prior install/uninstall state 10127 if (allUsers != null && perUserInstalled != null) { 10128 for (int i = 0; i < allUsers.length; i++) { 10129 if (DEBUG_INSTALL) { 10130 Slog.d(TAG, " user " + allUsers[i] 10131 + " => " + perUserInstalled[i]); 10132 } 10133 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10134 } 10135 // these install state changes will be persisted in the 10136 // upcoming call to mSettings.writeLPr(). 10137 } 10138 } 10139 } 10140 res.name = pkgName; 10141 res.uid = newPackage.applicationInfo.uid; 10142 res.pkg = newPackage; 10143 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10144 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10145 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10146 //to update install status 10147 mSettings.writeLPr(); 10148 } 10149 } 10150 10151 private void installPackageLI(InstallArgs args, 10152 boolean newInstall, PackageInstalledInfo res) { 10153 int pFlags = args.flags; 10154 String installerPackageName = args.installerPackageName; 10155 File tmpPackageFile = new File(args.getCodePath()); 10156 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10157 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10158 boolean replace = false; 10159 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10160 | (newInstall ? SCAN_NEW_INSTALL : 0); 10161 // Result object to be returned 10162 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10163 10164 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10165 // Retrieve PackageSettings and parse package 10166 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10167 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10168 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10169 PackageParser pp = new PackageParser(); 10170 pp.setSeparateProcesses(mSeparateProcesses); 10171 pp.setDisplayMetrics(mMetrics); 10172 10173 final PackageParser.Package pkg; 10174 try { 10175 pkg = pp.parseMonolithicPackage(tmpPackageFile, parseFlags); 10176 } catch (PackageParserException e) { 10177 res.returnCode = e.error; 10178 return; 10179 } 10180 10181 String pkgName = res.name = pkg.packageName; 10182 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10183 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10184 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 10185 return; 10186 } 10187 } 10188 10189 try { 10190 pp.collectCertificates(pkg, parseFlags); 10191 pp.collectManifestDigest(pkg); 10192 } catch (PackageParserException e) { 10193 res.returnCode = e.error; 10194 return; 10195 } 10196 10197 /* If the installer passed in a manifest digest, compare it now. */ 10198 if (args.manifestDigest != null) { 10199 if (DEBUG_INSTALL) { 10200 final String parsedManifest = pkg.manifestDigest == null ? "null" 10201 : pkg.manifestDigest.toString(); 10202 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10203 + parsedManifest); 10204 } 10205 10206 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10207 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 10208 return; 10209 } 10210 } else if (DEBUG_INSTALL) { 10211 final String parsedManifest = pkg.manifestDigest == null 10212 ? "null" : pkg.manifestDigest.toString(); 10213 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10214 } 10215 10216 // Get rid of all references to package scan path via parser. 10217 pp = null; 10218 String oldCodePath = null; 10219 boolean systemApp = false; 10220 synchronized (mPackages) { 10221 // Check whether the newly-scanned package wants to define an already-defined perm 10222 int N = pkg.permissions.size(); 10223 for (int i = N-1; i >= 0; i--) { 10224 PackageParser.Permission perm = pkg.permissions.get(i); 10225 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10226 if (bp != null) { 10227 // If the defining package is signed with our cert, it's okay. This 10228 // also includes the "updating the same package" case, of course. 10229 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10230 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10231 // If the owning package is the system itself, we log but allow 10232 // install to proceed; we fail the install on all other permission 10233 // redefinitions. 10234 if (!bp.sourcePackage.equals("android")) { 10235 Slog.w(TAG, "Package " + pkg.packageName 10236 + " attempting to redeclare permission " + perm.info.name 10237 + " already owned by " + bp.sourcePackage); 10238 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 10239 res.origPermission = perm.info.name; 10240 res.origPackage = bp.sourcePackage; 10241 return; 10242 } else { 10243 Slog.w(TAG, "Package " + pkg.packageName 10244 + " attempting to redeclare system permission " 10245 + perm.info.name + "; ignoring new declaration"); 10246 pkg.permissions.remove(i); 10247 } 10248 } 10249 } 10250 } 10251 10252 // Check if installing already existing package 10253 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10254 String oldName = mSettings.mRenamedPackages.get(pkgName); 10255 if (pkg.mOriginalPackages != null 10256 && pkg.mOriginalPackages.contains(oldName) 10257 && mPackages.containsKey(oldName)) { 10258 // This package is derived from an original package, 10259 // and this device has been updating from that original 10260 // name. We must continue using the original name, so 10261 // rename the new package here. 10262 pkg.setPackageName(oldName); 10263 pkgName = pkg.packageName; 10264 replace = true; 10265 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10266 + oldName + " pkgName=" + pkgName); 10267 } else if (mPackages.containsKey(pkgName)) { 10268 // This package, under its official name, already exists 10269 // on the device; we should replace it. 10270 replace = true; 10271 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10272 } 10273 } 10274 PackageSetting ps = mSettings.mPackages.get(pkgName); 10275 if (ps != null) { 10276 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10277 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10278 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10279 systemApp = (ps.pkg.applicationInfo.flags & 10280 ApplicationInfo.FLAG_SYSTEM) != 0; 10281 } 10282 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10283 } 10284 } 10285 10286 if (systemApp && onSd) { 10287 // Disable updates to system apps on sdcard 10288 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 10289 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10290 return; 10291 } 10292 10293 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 10294 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10295 return; 10296 } 10297 // Set application objects path explicitly after the rename 10298 pkg.codePath = args.getCodePath(); 10299 pkg.applicationInfo.sourceDir = args.getCodePath(); 10300 pkg.applicationInfo.publicSourceDir = args.getResourcePath(); 10301 pkg.applicationInfo.splitSourceDirs = args.getSplitCodePaths(); 10302 pkg.applicationInfo.splitPublicSourceDirs = deriveSplitResPaths( 10303 pkg.applicationInfo.splitSourceDirs); 10304 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 10305 if (replace) { 10306 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10307 installerPackageName, res, args.abiOverride); 10308 } else { 10309 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10310 installerPackageName, res, args.abiOverride); 10311 } 10312 synchronized (mPackages) { 10313 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10314 if (ps != null) { 10315 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10316 } 10317 } 10318 } 10319 10320 private static boolean isForwardLocked(PackageParser.Package pkg) { 10321 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10322 } 10323 10324 10325 private boolean isForwardLocked(PackageSetting ps) { 10326 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10327 } 10328 10329 private static boolean isExternal(PackageParser.Package pkg) { 10330 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10331 } 10332 10333 private static boolean isExternal(PackageSetting ps) { 10334 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10335 } 10336 10337 private static boolean isSystemApp(PackageParser.Package pkg) { 10338 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10339 } 10340 10341 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10342 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10343 } 10344 10345 private static boolean isSystemApp(ApplicationInfo info) { 10346 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10347 } 10348 10349 private static boolean isSystemApp(PackageSetting ps) { 10350 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10351 } 10352 10353 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10354 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10355 } 10356 10357 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10358 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10359 } 10360 10361 private int packageFlagsToInstallFlags(PackageSetting ps) { 10362 int installFlags = 0; 10363 if (isExternal(ps)) { 10364 installFlags |= PackageManager.INSTALL_EXTERNAL; 10365 } 10366 if (isForwardLocked(ps)) { 10367 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10368 } 10369 return installFlags; 10370 } 10371 10372 private void deleteTempPackageFiles() { 10373 final FilenameFilter filter = new FilenameFilter() { 10374 public boolean accept(File dir, String name) { 10375 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10376 } 10377 }; 10378 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 10379 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 10380 } 10381 10382 private static final void deleteTempPackageFilesInDirectory(File directory, 10383 FilenameFilter filter) { 10384 final String[] tmpFilesList = directory.list(filter); 10385 if (tmpFilesList == null) { 10386 return; 10387 } 10388 for (int i = 0; i < tmpFilesList.length; i++) { 10389 final File tmpFile = new File(directory, tmpFilesList[i]); 10390 tmpFile.delete(); 10391 } 10392 } 10393 10394 private File createTempPackageFile(File installDir) { 10395 File tmpPackageFile; 10396 try { 10397 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 10398 } catch (IOException e) { 10399 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 10400 return null; 10401 } 10402 try { 10403 FileUtils.setPermissions( 10404 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 10405 -1, -1); 10406 if (!SELinux.restorecon(tmpPackageFile)) { 10407 return null; 10408 } 10409 } catch (IOException e) { 10410 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 10411 return null; 10412 } 10413 return tmpPackageFile; 10414 } 10415 10416 @Override 10417 public void deletePackageAsUser(final String packageName, 10418 final IPackageDeleteObserver observer, 10419 final int userId, final int flags) { 10420 mContext.enforceCallingOrSelfPermission( 10421 android.Manifest.permission.DELETE_PACKAGES, null); 10422 final int uid = Binder.getCallingUid(); 10423 if (UserHandle.getUserId(uid) != userId) { 10424 mContext.enforceCallingPermission( 10425 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10426 "deletePackage for user " + userId); 10427 } 10428 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10429 try { 10430 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10431 } catch (RemoteException re) { 10432 } 10433 return; 10434 } 10435 10436 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10437 // Queue up an async operation since the package deletion may take a little while. 10438 mHandler.post(new Runnable() { 10439 public void run() { 10440 mHandler.removeCallbacks(this); 10441 final int returnCode = deletePackageX(packageName, userId, flags); 10442 if (observer != null) { 10443 try { 10444 observer.packageDeleted(packageName, returnCode); 10445 } catch (RemoteException e) { 10446 Log.i(TAG, "Observer no longer exists."); 10447 } //end catch 10448 } //end if 10449 } //end run 10450 }); 10451 } 10452 10453 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10454 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10455 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10456 try { 10457 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10458 || dpm.isDeviceOwner(packageName))) { 10459 return true; 10460 } 10461 } catch (RemoteException e) { 10462 } 10463 return false; 10464 } 10465 10466 /** 10467 * This method is an internal method that could be get invoked either 10468 * to delete an installed package or to clean up a failed installation. 10469 * After deleting an installed package, a broadcast is sent to notify any 10470 * listeners that the package has been installed. For cleaning up a failed 10471 * installation, the broadcast is not necessary since the package's 10472 * installation wouldn't have sent the initial broadcast either 10473 * The key steps in deleting a package are 10474 * deleting the package information in internal structures like mPackages, 10475 * deleting the packages base directories through installd 10476 * updating mSettings to reflect current status 10477 * persisting settings for later use 10478 * sending a broadcast if necessary 10479 */ 10480 private int deletePackageX(String packageName, int userId, int flags) { 10481 final PackageRemovedInfo info = new PackageRemovedInfo(); 10482 final boolean res; 10483 10484 if (isPackageDeviceAdmin(packageName, userId)) { 10485 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10486 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10487 } 10488 10489 boolean removedForAllUsers = false; 10490 boolean systemUpdate = false; 10491 10492 // for the uninstall-updates case and restricted profiles, remember the per- 10493 // userhandle installed state 10494 int[] allUsers; 10495 boolean[] perUserInstalled; 10496 synchronized (mPackages) { 10497 PackageSetting ps = mSettings.mPackages.get(packageName); 10498 allUsers = sUserManager.getUserIds(); 10499 perUserInstalled = new boolean[allUsers.length]; 10500 for (int i = 0; i < allUsers.length; i++) { 10501 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10502 } 10503 } 10504 10505 synchronized (mInstallLock) { 10506 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10507 res = deletePackageLI(packageName, 10508 (flags & PackageManager.DELETE_ALL_USERS) != 0 10509 ? UserHandle.ALL : new UserHandle(userId), 10510 true, allUsers, perUserInstalled, 10511 flags | REMOVE_CHATTY, info, true); 10512 systemUpdate = info.isRemovedPackageSystemUpdate; 10513 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10514 removedForAllUsers = true; 10515 } 10516 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10517 + " removedForAllUsers=" + removedForAllUsers); 10518 } 10519 10520 if (res) { 10521 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10522 10523 // If the removed package was a system update, the old system package 10524 // was re-enabled; we need to broadcast this information 10525 if (systemUpdate) { 10526 Bundle extras = new Bundle(1); 10527 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10528 ? info.removedAppId : info.uid); 10529 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10530 10531 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10532 extras, null, null, null); 10533 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10534 extras, null, null, null); 10535 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10536 null, packageName, null, null); 10537 } 10538 } 10539 // Force a gc here. 10540 Runtime.getRuntime().gc(); 10541 // Delete the resources here after sending the broadcast to let 10542 // other processes clean up before deleting resources. 10543 if (info.args != null) { 10544 synchronized (mInstallLock) { 10545 info.args.doPostDeleteLI(true); 10546 } 10547 } 10548 10549 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10550 } 10551 10552 static class PackageRemovedInfo { 10553 String removedPackage; 10554 int uid = -1; 10555 int removedAppId = -1; 10556 int[] removedUsers = null; 10557 boolean isRemovedPackageSystemUpdate = false; 10558 // Clean up resources deleted packages. 10559 InstallArgs args = null; 10560 10561 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10562 Bundle extras = new Bundle(1); 10563 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10564 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10565 if (replacing) { 10566 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10567 } 10568 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10569 if (removedPackage != null) { 10570 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10571 extras, null, null, removedUsers); 10572 if (fullRemove && !replacing) { 10573 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10574 extras, null, null, removedUsers); 10575 } 10576 } 10577 if (removedAppId >= 0) { 10578 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10579 removedUsers); 10580 } 10581 } 10582 } 10583 10584 /* 10585 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10586 * flag is not set, the data directory is removed as well. 10587 * make sure this flag is set for partially installed apps. If not its meaningless to 10588 * delete a partially installed application. 10589 */ 10590 private void removePackageDataLI(PackageSetting ps, 10591 int[] allUserHandles, boolean[] perUserInstalled, 10592 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10593 String packageName = ps.name; 10594 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10595 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10596 // Retrieve object to delete permissions for shared user later on 10597 final PackageSetting deletedPs; 10598 // reader 10599 synchronized (mPackages) { 10600 deletedPs = mSettings.mPackages.get(packageName); 10601 if (outInfo != null) { 10602 outInfo.removedPackage = packageName; 10603 outInfo.removedUsers = deletedPs != null 10604 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10605 : null; 10606 } 10607 } 10608 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10609 removeDataDirsLI(packageName); 10610 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10611 } 10612 // writer 10613 synchronized (mPackages) { 10614 if (deletedPs != null) { 10615 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10616 if (outInfo != null) { 10617 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10618 } 10619 if (deletedPs != null) { 10620 updatePermissionsLPw(deletedPs.name, null, 0); 10621 if (deletedPs.sharedUser != null) { 10622 // remove permissions associated with package 10623 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10624 } 10625 } 10626 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10627 } 10628 // make sure to preserve per-user disabled state if this removal was just 10629 // a downgrade of a system app to the factory package 10630 if (allUserHandles != null && perUserInstalled != null) { 10631 if (DEBUG_REMOVE) { 10632 Slog.d(TAG, "Propagating install state across downgrade"); 10633 } 10634 for (int i = 0; i < allUserHandles.length; i++) { 10635 if (DEBUG_REMOVE) { 10636 Slog.d(TAG, " user " + allUserHandles[i] 10637 + " => " + perUserInstalled[i]); 10638 } 10639 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10640 } 10641 } 10642 } 10643 // can downgrade to reader 10644 if (writeSettings) { 10645 // Save settings now 10646 mSettings.writeLPr(); 10647 } 10648 } 10649 if (outInfo != null) { 10650 // A user ID was deleted here. Go through all users and remove it 10651 // from KeyStore. 10652 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10653 } 10654 } 10655 10656 static boolean locationIsPrivileged(File path) { 10657 try { 10658 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10659 .getCanonicalPath(); 10660 return path.getCanonicalPath().startsWith(privilegedAppDir); 10661 } catch (IOException e) { 10662 Slog.e(TAG, "Unable to access code path " + path); 10663 } 10664 return false; 10665 } 10666 10667 /* 10668 * Tries to delete system package. 10669 */ 10670 private boolean deleteSystemPackageLI(PackageSetting newPs, 10671 int[] allUserHandles, boolean[] perUserInstalled, 10672 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10673 final boolean applyUserRestrictions 10674 = (allUserHandles != null) && (perUserInstalled != null); 10675 PackageSetting disabledPs = null; 10676 // Confirm if the system package has been updated 10677 // An updated system app can be deleted. This will also have to restore 10678 // the system pkg from system partition 10679 // reader 10680 synchronized (mPackages) { 10681 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10682 } 10683 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10684 + " disabledPs=" + disabledPs); 10685 if (disabledPs == null) { 10686 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10687 return false; 10688 } else if (DEBUG_REMOVE) { 10689 Slog.d(TAG, "Deleting system pkg from data partition"); 10690 } 10691 if (DEBUG_REMOVE) { 10692 if (applyUserRestrictions) { 10693 Slog.d(TAG, "Remembering install states:"); 10694 for (int i = 0; i < allUserHandles.length; i++) { 10695 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10696 } 10697 } 10698 } 10699 // Delete the updated package 10700 outInfo.isRemovedPackageSystemUpdate = true; 10701 if (disabledPs.versionCode < newPs.versionCode) { 10702 // Delete data for downgrades 10703 flags &= ~PackageManager.DELETE_KEEP_DATA; 10704 } else { 10705 // Preserve data by setting flag 10706 flags |= PackageManager.DELETE_KEEP_DATA; 10707 } 10708 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10709 allUserHandles, perUserInstalled, outInfo, writeSettings); 10710 if (!ret) { 10711 return false; 10712 } 10713 // writer 10714 synchronized (mPackages) { 10715 // Reinstate the old system package 10716 mSettings.enableSystemPackageLPw(newPs.name); 10717 // Remove any native libraries from the upgraded package. 10718 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 10719 } 10720 // Install the system package 10721 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10722 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10723 if (locationIsPrivileged(disabledPs.codePath)) { 10724 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10725 } 10726 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10727 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null); 10728 10729 if (newPkg == null) { 10730 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10731 + " with error:" + mLastScanError); 10732 return false; 10733 } 10734 // writer 10735 synchronized (mPackages) { 10736 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10737 setInternalAppNativeLibraryPath(newPkg, ps); 10738 updatePermissionsLPw(newPkg.packageName, newPkg, 10739 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10740 if (applyUserRestrictions) { 10741 if (DEBUG_REMOVE) { 10742 Slog.d(TAG, "Propagating install state across reinstall"); 10743 } 10744 for (int i = 0; i < allUserHandles.length; i++) { 10745 if (DEBUG_REMOVE) { 10746 Slog.d(TAG, " user " + allUserHandles[i] 10747 + " => " + perUserInstalled[i]); 10748 } 10749 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10750 } 10751 // Regardless of writeSettings we need to ensure that this restriction 10752 // state propagation is persisted 10753 mSettings.writeAllUsersPackageRestrictionsLPr(); 10754 } 10755 // can downgrade to reader here 10756 if (writeSettings) { 10757 mSettings.writeLPr(); 10758 } 10759 } 10760 return true; 10761 } 10762 10763 private boolean deleteInstalledPackageLI(PackageSetting ps, 10764 boolean deleteCodeAndResources, int flags, 10765 int[] allUserHandles, boolean[] perUserInstalled, 10766 PackageRemovedInfo outInfo, boolean writeSettings) { 10767 if (outInfo != null) { 10768 outInfo.uid = ps.appId; 10769 } 10770 10771 // Delete package data from internal structures and also remove data if flag is set 10772 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10773 10774 // Delete application code and resources 10775 if (deleteCodeAndResources && (outInfo != null)) { 10776 outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString, 10777 ps.resourcePathString, ps.nativeLibraryPathString, 10778 getAppInstructionSetFromSettings(ps)); 10779 } 10780 return true; 10781 } 10782 10783 /* 10784 * This method handles package deletion in general 10785 */ 10786 private boolean deletePackageLI(String packageName, UserHandle user, 10787 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10788 int flags, PackageRemovedInfo outInfo, 10789 boolean writeSettings) { 10790 if (packageName == null) { 10791 Slog.w(TAG, "Attempt to delete null packageName."); 10792 return false; 10793 } 10794 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10795 PackageSetting ps; 10796 boolean dataOnly = false; 10797 int removeUser = -1; 10798 int appId = -1; 10799 synchronized (mPackages) { 10800 ps = mSettings.mPackages.get(packageName); 10801 if (ps == null) { 10802 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10803 return false; 10804 } 10805 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10806 && user.getIdentifier() != UserHandle.USER_ALL) { 10807 // The caller is asking that the package only be deleted for a single 10808 // user. To do this, we just mark its uninstalled state and delete 10809 // its data. If this is a system app, we only allow this to happen if 10810 // they have set the special DELETE_SYSTEM_APP which requests different 10811 // semantics than normal for uninstalling system apps. 10812 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10813 ps.setUserState(user.getIdentifier(), 10814 COMPONENT_ENABLED_STATE_DEFAULT, 10815 false, //installed 10816 true, //stopped 10817 true, //notLaunched 10818 false, //blocked 10819 null, null, null); 10820 if (!isSystemApp(ps)) { 10821 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10822 // Other user still have this package installed, so all 10823 // we need to do is clear this user's data and save that 10824 // it is uninstalled. 10825 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10826 removeUser = user.getIdentifier(); 10827 appId = ps.appId; 10828 mSettings.writePackageRestrictionsLPr(removeUser); 10829 } else { 10830 // We need to set it back to 'installed' so the uninstall 10831 // broadcasts will be sent correctly. 10832 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10833 ps.setInstalled(true, user.getIdentifier()); 10834 } 10835 } else { 10836 // This is a system app, so we assume that the 10837 // other users still have this package installed, so all 10838 // we need to do is clear this user's data and save that 10839 // it is uninstalled. 10840 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10841 removeUser = user.getIdentifier(); 10842 appId = ps.appId; 10843 mSettings.writePackageRestrictionsLPr(removeUser); 10844 } 10845 } 10846 } 10847 10848 if (removeUser >= 0) { 10849 // From above, we determined that we are deleting this only 10850 // for a single user. Continue the work here. 10851 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10852 if (outInfo != null) { 10853 outInfo.removedPackage = packageName; 10854 outInfo.removedAppId = appId; 10855 outInfo.removedUsers = new int[] {removeUser}; 10856 } 10857 mInstaller.clearUserData(packageName, removeUser); 10858 removeKeystoreDataIfNeeded(removeUser, appId); 10859 schedulePackageCleaning(packageName, removeUser, false); 10860 return true; 10861 } 10862 10863 if (dataOnly) { 10864 // Delete application data first 10865 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10866 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10867 return true; 10868 } 10869 10870 boolean ret = false; 10871 mSettings.mKeySetManager.removeAppKeySetData(packageName); 10872 if (isSystemApp(ps)) { 10873 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10874 // When an updated system application is deleted we delete the existing resources as well and 10875 // fall back to existing code in system partition 10876 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10877 flags, outInfo, writeSettings); 10878 } else { 10879 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10880 // Kill application pre-emptively especially for apps on sd. 10881 killApplication(packageName, ps.appId, "uninstall pkg"); 10882 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10883 allUserHandles, perUserInstalled, 10884 outInfo, writeSettings); 10885 } 10886 10887 return ret; 10888 } 10889 10890 private final class ClearStorageConnection implements ServiceConnection { 10891 IMediaContainerService mContainerService; 10892 10893 @Override 10894 public void onServiceConnected(ComponentName name, IBinder service) { 10895 synchronized (this) { 10896 mContainerService = IMediaContainerService.Stub.asInterface(service); 10897 notifyAll(); 10898 } 10899 } 10900 10901 @Override 10902 public void onServiceDisconnected(ComponentName name) { 10903 } 10904 } 10905 10906 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10907 final boolean mounted; 10908 if (Environment.isExternalStorageEmulated()) { 10909 mounted = true; 10910 } else { 10911 final String status = Environment.getExternalStorageState(); 10912 10913 mounted = status.equals(Environment.MEDIA_MOUNTED) 10914 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10915 } 10916 10917 if (!mounted) { 10918 return; 10919 } 10920 10921 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10922 int[] users; 10923 if (userId == UserHandle.USER_ALL) { 10924 users = sUserManager.getUserIds(); 10925 } else { 10926 users = new int[] { userId }; 10927 } 10928 final ClearStorageConnection conn = new ClearStorageConnection(); 10929 if (mContext.bindServiceAsUser( 10930 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10931 try { 10932 for (int curUser : users) { 10933 long timeout = SystemClock.uptimeMillis() + 5000; 10934 synchronized (conn) { 10935 long now = SystemClock.uptimeMillis(); 10936 while (conn.mContainerService == null && now < timeout) { 10937 try { 10938 conn.wait(timeout - now); 10939 } catch (InterruptedException e) { 10940 } 10941 } 10942 } 10943 if (conn.mContainerService == null) { 10944 return; 10945 } 10946 10947 final UserEnvironment userEnv = new UserEnvironment(curUser); 10948 clearDirectory(conn.mContainerService, 10949 userEnv.buildExternalStorageAppCacheDirs(packageName)); 10950 if (allData) { 10951 clearDirectory(conn.mContainerService, 10952 userEnv.buildExternalStorageAppDataDirs(packageName)); 10953 clearDirectory(conn.mContainerService, 10954 userEnv.buildExternalStorageAppMediaDirs(packageName)); 10955 } 10956 } 10957 } finally { 10958 mContext.unbindService(conn); 10959 } 10960 } 10961 } 10962 10963 @Override 10964 public void clearApplicationUserData(final String packageName, 10965 final IPackageDataObserver observer, final int userId) { 10966 mContext.enforceCallingOrSelfPermission( 10967 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 10968 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 10969 // Queue up an async operation since the package deletion may take a little while. 10970 mHandler.post(new Runnable() { 10971 public void run() { 10972 mHandler.removeCallbacks(this); 10973 final boolean succeeded; 10974 synchronized (mInstallLock) { 10975 succeeded = clearApplicationUserDataLI(packageName, userId); 10976 } 10977 clearExternalStorageDataSync(packageName, userId, true); 10978 if (succeeded) { 10979 // invoke DeviceStorageMonitor's update method to clear any notifications 10980 DeviceStorageMonitorInternal 10981 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 10982 if (dsm != null) { 10983 dsm.checkMemory(); 10984 } 10985 } 10986 if(observer != null) { 10987 try { 10988 observer.onRemoveCompleted(packageName, succeeded); 10989 } catch (RemoteException e) { 10990 Log.i(TAG, "Observer no longer exists."); 10991 } 10992 } //end if observer 10993 } //end run 10994 }); 10995 } 10996 10997 private boolean clearApplicationUserDataLI(String packageName, int userId) { 10998 if (packageName == null) { 10999 Slog.w(TAG, "Attempt to delete null packageName."); 11000 return false; 11001 } 11002 PackageParser.Package p; 11003 boolean dataOnly = false; 11004 final int appId; 11005 synchronized (mPackages) { 11006 p = mPackages.get(packageName); 11007 if (p == null) { 11008 dataOnly = true; 11009 PackageSetting ps = mSettings.mPackages.get(packageName); 11010 if ((ps == null) || (ps.pkg == null)) { 11011 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11012 return false; 11013 } 11014 p = ps.pkg; 11015 } 11016 if (!dataOnly) { 11017 // need to check this only for fully installed applications 11018 if (p == null) { 11019 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11020 return false; 11021 } 11022 final ApplicationInfo applicationInfo = p.applicationInfo; 11023 if (applicationInfo == null) { 11024 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11025 return false; 11026 } 11027 } 11028 if (p != null && p.applicationInfo != null) { 11029 appId = p.applicationInfo.uid; 11030 } else { 11031 appId = -1; 11032 } 11033 } 11034 int retCode = mInstaller.clearUserData(packageName, userId); 11035 if (retCode < 0) { 11036 Slog.w(TAG, "Couldn't remove cache files for package: " 11037 + packageName); 11038 return false; 11039 } 11040 removeKeystoreDataIfNeeded(userId, appId); 11041 return true; 11042 } 11043 11044 /** 11045 * Remove entries from the keystore daemon. Will only remove it if the 11046 * {@code appId} is valid. 11047 */ 11048 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11049 if (appId < 0) { 11050 return; 11051 } 11052 11053 final KeyStore keyStore = KeyStore.getInstance(); 11054 if (keyStore != null) { 11055 if (userId == UserHandle.USER_ALL) { 11056 for (final int individual : sUserManager.getUserIds()) { 11057 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11058 } 11059 } else { 11060 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11061 } 11062 } else { 11063 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11064 } 11065 } 11066 11067 @Override 11068 public void deleteApplicationCacheFiles(final String packageName, 11069 final IPackageDataObserver observer) { 11070 mContext.enforceCallingOrSelfPermission( 11071 android.Manifest.permission.DELETE_CACHE_FILES, null); 11072 // Queue up an async operation since the package deletion may take a little while. 11073 final int userId = UserHandle.getCallingUserId(); 11074 mHandler.post(new Runnable() { 11075 public void run() { 11076 mHandler.removeCallbacks(this); 11077 final boolean succeded; 11078 synchronized (mInstallLock) { 11079 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11080 } 11081 clearExternalStorageDataSync(packageName, userId, false); 11082 if(observer != null) { 11083 try { 11084 observer.onRemoveCompleted(packageName, succeded); 11085 } catch (RemoteException e) { 11086 Log.i(TAG, "Observer no longer exists."); 11087 } 11088 } //end if observer 11089 } //end run 11090 }); 11091 } 11092 11093 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11094 if (packageName == null) { 11095 Slog.w(TAG, "Attempt to delete null packageName."); 11096 return false; 11097 } 11098 PackageParser.Package p; 11099 synchronized (mPackages) { 11100 p = mPackages.get(packageName); 11101 } 11102 if (p == null) { 11103 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11104 return false; 11105 } 11106 final ApplicationInfo applicationInfo = p.applicationInfo; 11107 if (applicationInfo == null) { 11108 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11109 return false; 11110 } 11111 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11112 if (retCode < 0) { 11113 Slog.w(TAG, "Couldn't remove cache files for package: " 11114 + packageName + " u" + userId); 11115 return false; 11116 } 11117 return true; 11118 } 11119 11120 @Override 11121 public void getPackageSizeInfo(final String packageName, int userHandle, 11122 final IPackageStatsObserver observer) { 11123 mContext.enforceCallingOrSelfPermission( 11124 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11125 if (packageName == null) { 11126 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11127 } 11128 11129 PackageStats stats = new PackageStats(packageName, userHandle); 11130 11131 /* 11132 * Queue up an async operation since the package measurement may take a 11133 * little while. 11134 */ 11135 Message msg = mHandler.obtainMessage(INIT_COPY); 11136 msg.obj = new MeasureParams(stats, observer); 11137 mHandler.sendMessage(msg); 11138 } 11139 11140 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11141 PackageStats pStats) { 11142 if (packageName == null) { 11143 Slog.w(TAG, "Attempt to get size of null packageName."); 11144 return false; 11145 } 11146 PackageParser.Package p; 11147 boolean dataOnly = false; 11148 String libDirPath = null; 11149 String asecPath = null; 11150 PackageSetting ps = null; 11151 synchronized (mPackages) { 11152 p = mPackages.get(packageName); 11153 ps = mSettings.mPackages.get(packageName); 11154 if(p == null) { 11155 dataOnly = true; 11156 if((ps == null) || (ps.pkg == null)) { 11157 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11158 return false; 11159 } 11160 p = ps.pkg; 11161 } 11162 if (ps != null) { 11163 libDirPath = ps.nativeLibraryPathString; 11164 } 11165 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11166 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 11167 if (secureContainerId != null) { 11168 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11169 } 11170 } 11171 } 11172 String publicSrcDir = null; 11173 if(!dataOnly) { 11174 final ApplicationInfo applicationInfo = p.applicationInfo; 11175 if (applicationInfo == null) { 11176 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11177 return false; 11178 } 11179 if (isForwardLocked(p)) { 11180 publicSrcDir = applicationInfo.publicSourceDir; 11181 } 11182 } 11183 int res = mInstaller.getSizeInfo(packageName, userHandle, p.codePath, libDirPath, 11184 publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps), 11185 pStats); 11186 if (res < 0) { 11187 return false; 11188 } 11189 11190 // Fix-up for forward-locked applications in ASEC containers. 11191 if (!isExternal(p)) { 11192 pStats.codeSize += pStats.externalCodeSize; 11193 pStats.externalCodeSize = 0L; 11194 } 11195 11196 return true; 11197 } 11198 11199 11200 @Override 11201 public void addPackageToPreferred(String packageName) { 11202 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11203 } 11204 11205 @Override 11206 public void removePackageFromPreferred(String packageName) { 11207 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11208 } 11209 11210 @Override 11211 public List<PackageInfo> getPreferredPackages(int flags) { 11212 return new ArrayList<PackageInfo>(); 11213 } 11214 11215 private int getUidTargetSdkVersionLockedLPr(int uid) { 11216 Object obj = mSettings.getUserIdLPr(uid); 11217 if (obj instanceof SharedUserSetting) { 11218 final SharedUserSetting sus = (SharedUserSetting) obj; 11219 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11220 final Iterator<PackageSetting> it = sus.packages.iterator(); 11221 while (it.hasNext()) { 11222 final PackageSetting ps = it.next(); 11223 if (ps.pkg != null) { 11224 int v = ps.pkg.applicationInfo.targetSdkVersion; 11225 if (v < vers) vers = v; 11226 } 11227 } 11228 return vers; 11229 } else if (obj instanceof PackageSetting) { 11230 final PackageSetting ps = (PackageSetting) obj; 11231 if (ps.pkg != null) { 11232 return ps.pkg.applicationInfo.targetSdkVersion; 11233 } 11234 } 11235 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11236 } 11237 11238 @Override 11239 public void addPreferredActivity(IntentFilter filter, int match, 11240 ComponentName[] set, ComponentName activity, int userId) { 11241 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11242 } 11243 11244 private void addPreferredActivityInternal(IntentFilter filter, int match, 11245 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11246 // writer 11247 int callingUid = Binder.getCallingUid(); 11248 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11249 if (filter.countActions() == 0) { 11250 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11251 return; 11252 } 11253 synchronized (mPackages) { 11254 if (mContext.checkCallingOrSelfPermission( 11255 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11256 != PackageManager.PERMISSION_GRANTED) { 11257 if (getUidTargetSdkVersionLockedLPr(callingUid) 11258 < Build.VERSION_CODES.FROYO) { 11259 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11260 + callingUid); 11261 return; 11262 } 11263 mContext.enforceCallingOrSelfPermission( 11264 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11265 } 11266 11267 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11268 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11269 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11270 new PreferredActivity(filter, match, set, activity, always)); 11271 mSettings.writePackageRestrictionsLPr(userId); 11272 } 11273 } 11274 11275 @Override 11276 public void replacePreferredActivity(IntentFilter filter, int match, 11277 ComponentName[] set, ComponentName activity) { 11278 if (filter.countActions() != 1) { 11279 throw new IllegalArgumentException( 11280 "replacePreferredActivity expects filter to have only 1 action."); 11281 } 11282 if (filter.countDataAuthorities() != 0 11283 || filter.countDataPaths() != 0 11284 || filter.countDataSchemes() > 1 11285 || filter.countDataTypes() != 0) { 11286 throw new IllegalArgumentException( 11287 "replacePreferredActivity expects filter to have no data authorities, " + 11288 "paths, or types; and at most one scheme."); 11289 } 11290 synchronized (mPackages) { 11291 if (mContext.checkCallingOrSelfPermission( 11292 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11293 != PackageManager.PERMISSION_GRANTED) { 11294 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11295 < Build.VERSION_CODES.FROYO) { 11296 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11297 + Binder.getCallingUid()); 11298 return; 11299 } 11300 mContext.enforceCallingOrSelfPermission( 11301 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11302 } 11303 11304 final int callingUserId = UserHandle.getCallingUserId(); 11305 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11306 if (pir != null) { 11307 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11308 if (filter.countDataSchemes() == 1) { 11309 Uri.Builder builder = new Uri.Builder(); 11310 builder.scheme(filter.getDataScheme(0)); 11311 intent.setData(builder.build()); 11312 } 11313 List<PreferredActivity> matches = pir.queryIntent( 11314 intent, null, true, callingUserId); 11315 if (DEBUG_PREFERRED) { 11316 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11317 } 11318 for (int i = 0; i < matches.size(); i++) { 11319 PreferredActivity pa = matches.get(i); 11320 if (DEBUG_PREFERRED) { 11321 Slog.i(TAG, "Removing preferred activity " 11322 + pa.mPref.mComponent + ":"); 11323 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11324 } 11325 pir.removeFilter(pa); 11326 } 11327 } 11328 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11329 } 11330 } 11331 11332 @Override 11333 public void clearPackagePreferredActivities(String packageName) { 11334 final int uid = Binder.getCallingUid(); 11335 // writer 11336 synchronized (mPackages) { 11337 PackageParser.Package pkg = mPackages.get(packageName); 11338 if (pkg == null || pkg.applicationInfo.uid != uid) { 11339 if (mContext.checkCallingOrSelfPermission( 11340 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11341 != PackageManager.PERMISSION_GRANTED) { 11342 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11343 < Build.VERSION_CODES.FROYO) { 11344 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11345 + Binder.getCallingUid()); 11346 return; 11347 } 11348 mContext.enforceCallingOrSelfPermission( 11349 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11350 } 11351 } 11352 11353 int user = UserHandle.getCallingUserId(); 11354 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11355 mSettings.writePackageRestrictionsLPr(user); 11356 scheduleWriteSettingsLocked(); 11357 } 11358 } 11359 } 11360 11361 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11362 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11363 ArrayList<PreferredActivity> removed = null; 11364 boolean changed = false; 11365 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11366 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11367 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11368 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11369 continue; 11370 } 11371 Iterator<PreferredActivity> it = pir.filterIterator(); 11372 while (it.hasNext()) { 11373 PreferredActivity pa = it.next(); 11374 // Mark entry for removal only if it matches the package name 11375 // and the entry is of type "always". 11376 if (packageName == null || 11377 (pa.mPref.mComponent.getPackageName().equals(packageName) 11378 && pa.mPref.mAlways)) { 11379 if (removed == null) { 11380 removed = new ArrayList<PreferredActivity>(); 11381 } 11382 removed.add(pa); 11383 } 11384 } 11385 if (removed != null) { 11386 for (int j=0; j<removed.size(); j++) { 11387 PreferredActivity pa = removed.get(j); 11388 pir.removeFilter(pa); 11389 } 11390 changed = true; 11391 } 11392 } 11393 return changed; 11394 } 11395 11396 @Override 11397 public void resetPreferredActivities(int userId) { 11398 mContext.enforceCallingOrSelfPermission( 11399 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11400 // writer 11401 synchronized (mPackages) { 11402 int user = UserHandle.getCallingUserId(); 11403 clearPackagePreferredActivitiesLPw(null, user); 11404 mSettings.readDefaultPreferredAppsLPw(this, user); 11405 mSettings.writePackageRestrictionsLPr(user); 11406 scheduleWriteSettingsLocked(); 11407 } 11408 } 11409 11410 @Override 11411 public int getPreferredActivities(List<IntentFilter> outFilters, 11412 List<ComponentName> outActivities, String packageName) { 11413 11414 int num = 0; 11415 final int userId = UserHandle.getCallingUserId(); 11416 // reader 11417 synchronized (mPackages) { 11418 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11419 if (pir != null) { 11420 final Iterator<PreferredActivity> it = pir.filterIterator(); 11421 while (it.hasNext()) { 11422 final PreferredActivity pa = it.next(); 11423 if (packageName == null 11424 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11425 && pa.mPref.mAlways)) { 11426 if (outFilters != null) { 11427 outFilters.add(new IntentFilter(pa)); 11428 } 11429 if (outActivities != null) { 11430 outActivities.add(pa.mPref.mComponent); 11431 } 11432 } 11433 } 11434 } 11435 } 11436 11437 return num; 11438 } 11439 11440 @Override 11441 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11442 int userId) { 11443 int callingUid = Binder.getCallingUid(); 11444 if (callingUid != Process.SYSTEM_UID) { 11445 throw new SecurityException( 11446 "addPersistentPreferredActivity can only be run by the system"); 11447 } 11448 if (filter.countActions() == 0) { 11449 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11450 return; 11451 } 11452 synchronized (mPackages) { 11453 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11454 " :"); 11455 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11456 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11457 new PersistentPreferredActivity(filter, activity)); 11458 mSettings.writePackageRestrictionsLPr(userId); 11459 } 11460 } 11461 11462 @Override 11463 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11464 int callingUid = Binder.getCallingUid(); 11465 if (callingUid != Process.SYSTEM_UID) { 11466 throw new SecurityException( 11467 "clearPackagePersistentPreferredActivities can only be run by the system"); 11468 } 11469 ArrayList<PersistentPreferredActivity> removed = null; 11470 boolean changed = false; 11471 synchronized (mPackages) { 11472 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11473 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11474 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11475 .valueAt(i); 11476 if (userId != thisUserId) { 11477 continue; 11478 } 11479 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11480 while (it.hasNext()) { 11481 PersistentPreferredActivity ppa = it.next(); 11482 // Mark entry for removal only if it matches the package name. 11483 if (ppa.mComponent.getPackageName().equals(packageName)) { 11484 if (removed == null) { 11485 removed = new ArrayList<PersistentPreferredActivity>(); 11486 } 11487 removed.add(ppa); 11488 } 11489 } 11490 if (removed != null) { 11491 for (int j=0; j<removed.size(); j++) { 11492 PersistentPreferredActivity ppa = removed.get(j); 11493 ppir.removeFilter(ppa); 11494 } 11495 changed = true; 11496 } 11497 } 11498 11499 if (changed) { 11500 mSettings.writePackageRestrictionsLPr(userId); 11501 } 11502 } 11503 } 11504 11505 @Override 11506 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11507 int targetUserId, int flags) { 11508 mContext.enforceCallingOrSelfPermission( 11509 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11510 if (intentFilter.countActions() == 0) { 11511 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11512 return; 11513 } 11514 synchronized (mPackages) { 11515 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11516 targetUserId, flags); 11517 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11518 mSettings.writePackageRestrictionsLPr(sourceUserId); 11519 } 11520 } 11521 11522 public void addCrossProfileIntentsForPackage(String packageName, 11523 int sourceUserId, int targetUserId) { 11524 mContext.enforceCallingOrSelfPermission( 11525 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11526 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11527 mSettings.writePackageRestrictionsLPr(sourceUserId); 11528 } 11529 11530 public void removeCrossProfileIntentsForPackage(String packageName, 11531 int sourceUserId, int targetUserId) { 11532 mContext.enforceCallingOrSelfPermission( 11533 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11534 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11535 mSettings.writePackageRestrictionsLPr(sourceUserId); 11536 } 11537 11538 @Override 11539 public void clearCrossProfileIntentFilters(int sourceUserId) { 11540 mContext.enforceCallingOrSelfPermission( 11541 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11542 synchronized (mPackages) { 11543 CrossProfileIntentResolver resolver = 11544 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11545 HashSet<CrossProfileIntentFilter> set = 11546 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11547 for (CrossProfileIntentFilter filter : set) { 11548 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11549 resolver.removeFilter(filter); 11550 } 11551 } 11552 mSettings.writePackageRestrictionsLPr(sourceUserId); 11553 } 11554 } 11555 11556 @Override 11557 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11558 Intent intent = new Intent(Intent.ACTION_MAIN); 11559 intent.addCategory(Intent.CATEGORY_HOME); 11560 11561 final int callingUserId = UserHandle.getCallingUserId(); 11562 List<ResolveInfo> list = queryIntentActivities(intent, null, 11563 PackageManager.GET_META_DATA, callingUserId); 11564 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11565 true, false, false, callingUserId); 11566 11567 allHomeCandidates.clear(); 11568 if (list != null) { 11569 for (ResolveInfo ri : list) { 11570 allHomeCandidates.add(ri); 11571 } 11572 } 11573 return (preferred == null || preferred.activityInfo == null) 11574 ? null 11575 : new ComponentName(preferred.activityInfo.packageName, 11576 preferred.activityInfo.name); 11577 } 11578 11579 @Override 11580 public void setApplicationEnabledSetting(String appPackageName, 11581 int newState, int flags, int userId, String callingPackage) { 11582 if (!sUserManager.exists(userId)) return; 11583 if (callingPackage == null) { 11584 callingPackage = Integer.toString(Binder.getCallingUid()); 11585 } 11586 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11587 } 11588 11589 @Override 11590 public void setComponentEnabledSetting(ComponentName componentName, 11591 int newState, int flags, int userId) { 11592 if (!sUserManager.exists(userId)) return; 11593 setEnabledSetting(componentName.getPackageName(), 11594 componentName.getClassName(), newState, flags, userId, null); 11595 } 11596 11597 private void setEnabledSetting(final String packageName, String className, int newState, 11598 final int flags, int userId, String callingPackage) { 11599 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11600 || newState == COMPONENT_ENABLED_STATE_ENABLED 11601 || newState == COMPONENT_ENABLED_STATE_DISABLED 11602 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11603 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11604 throw new IllegalArgumentException("Invalid new component state: " 11605 + newState); 11606 } 11607 PackageSetting pkgSetting; 11608 final int uid = Binder.getCallingUid(); 11609 final int permission = mContext.checkCallingOrSelfPermission( 11610 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11611 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11612 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11613 boolean sendNow = false; 11614 boolean isApp = (className == null); 11615 String componentName = isApp ? packageName : className; 11616 int packageUid = -1; 11617 ArrayList<String> components; 11618 11619 // writer 11620 synchronized (mPackages) { 11621 pkgSetting = mSettings.mPackages.get(packageName); 11622 if (pkgSetting == null) { 11623 if (className == null) { 11624 throw new IllegalArgumentException( 11625 "Unknown package: " + packageName); 11626 } 11627 throw new IllegalArgumentException( 11628 "Unknown component: " + packageName 11629 + "/" + className); 11630 } 11631 // Allow root and verify that userId is not being specified by a different user 11632 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11633 throw new SecurityException( 11634 "Permission Denial: attempt to change component state from pid=" 11635 + Binder.getCallingPid() 11636 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11637 } 11638 if (className == null) { 11639 // We're dealing with an application/package level state change 11640 if (pkgSetting.getEnabled(userId) == newState) { 11641 // Nothing to do 11642 return; 11643 } 11644 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11645 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11646 // Don't care about who enables an app. 11647 callingPackage = null; 11648 } 11649 pkgSetting.setEnabled(newState, userId, callingPackage); 11650 // pkgSetting.pkg.mSetEnabled = newState; 11651 } else { 11652 // We're dealing with a component level state change 11653 // First, verify that this is a valid class name. 11654 PackageParser.Package pkg = pkgSetting.pkg; 11655 if (pkg == null || !pkg.hasComponentClassName(className)) { 11656 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11657 throw new IllegalArgumentException("Component class " + className 11658 + " does not exist in " + packageName); 11659 } else { 11660 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11661 + className + " does not exist in " + packageName); 11662 } 11663 } 11664 switch (newState) { 11665 case COMPONENT_ENABLED_STATE_ENABLED: 11666 if (!pkgSetting.enableComponentLPw(className, userId)) { 11667 return; 11668 } 11669 break; 11670 case COMPONENT_ENABLED_STATE_DISABLED: 11671 if (!pkgSetting.disableComponentLPw(className, userId)) { 11672 return; 11673 } 11674 break; 11675 case COMPONENT_ENABLED_STATE_DEFAULT: 11676 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11677 return; 11678 } 11679 break; 11680 default: 11681 Slog.e(TAG, "Invalid new component state: " + newState); 11682 return; 11683 } 11684 } 11685 mSettings.writePackageRestrictionsLPr(userId); 11686 components = mPendingBroadcasts.get(userId, packageName); 11687 final boolean newPackage = components == null; 11688 if (newPackage) { 11689 components = new ArrayList<String>(); 11690 } 11691 if (!components.contains(componentName)) { 11692 components.add(componentName); 11693 } 11694 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11695 sendNow = true; 11696 // Purge entry from pending broadcast list if another one exists already 11697 // since we are sending one right away. 11698 mPendingBroadcasts.remove(userId, packageName); 11699 } else { 11700 if (newPackage) { 11701 mPendingBroadcasts.put(userId, packageName, components); 11702 } 11703 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11704 // Schedule a message 11705 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11706 } 11707 } 11708 } 11709 11710 long callingId = Binder.clearCallingIdentity(); 11711 try { 11712 if (sendNow) { 11713 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11714 sendPackageChangedBroadcast(packageName, 11715 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11716 } 11717 } finally { 11718 Binder.restoreCallingIdentity(callingId); 11719 } 11720 } 11721 11722 private void sendPackageChangedBroadcast(String packageName, 11723 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11724 if (DEBUG_INSTALL) 11725 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11726 + componentNames); 11727 Bundle extras = new Bundle(4); 11728 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11729 String nameList[] = new String[componentNames.size()]; 11730 componentNames.toArray(nameList); 11731 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11732 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11733 extras.putInt(Intent.EXTRA_UID, packageUid); 11734 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11735 new int[] {UserHandle.getUserId(packageUid)}); 11736 } 11737 11738 @Override 11739 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11740 if (!sUserManager.exists(userId)) return; 11741 final int uid = Binder.getCallingUid(); 11742 final int permission = mContext.checkCallingOrSelfPermission( 11743 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11744 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11745 enforceCrossUserPermission(uid, userId, true, "stop package"); 11746 // writer 11747 synchronized (mPackages) { 11748 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11749 uid, userId)) { 11750 scheduleWritePackageRestrictionsLocked(userId); 11751 } 11752 } 11753 } 11754 11755 @Override 11756 public String getInstallerPackageName(String packageName) { 11757 // reader 11758 synchronized (mPackages) { 11759 return mSettings.getInstallerPackageNameLPr(packageName); 11760 } 11761 } 11762 11763 @Override 11764 public int getApplicationEnabledSetting(String packageName, int userId) { 11765 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11766 int uid = Binder.getCallingUid(); 11767 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11768 // reader 11769 synchronized (mPackages) { 11770 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11771 } 11772 } 11773 11774 @Override 11775 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11776 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11777 int uid = Binder.getCallingUid(); 11778 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11779 // reader 11780 synchronized (mPackages) { 11781 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11782 } 11783 } 11784 11785 @Override 11786 public void enterSafeMode() { 11787 enforceSystemOrRoot("Only the system can request entering safe mode"); 11788 11789 if (!mSystemReady) { 11790 mSafeMode = true; 11791 } 11792 } 11793 11794 @Override 11795 public void systemReady() { 11796 mSystemReady = true; 11797 11798 // Read the compatibilty setting when the system is ready. 11799 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11800 mContext.getContentResolver(), 11801 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11802 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11803 if (DEBUG_SETTINGS) { 11804 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11805 } 11806 11807 synchronized (mPackages) { 11808 // Verify that all of the preferred activity components actually 11809 // exist. It is possible for applications to be updated and at 11810 // that point remove a previously declared activity component that 11811 // had been set as a preferred activity. We try to clean this up 11812 // the next time we encounter that preferred activity, but it is 11813 // possible for the user flow to never be able to return to that 11814 // situation so here we do a sanity check to make sure we haven't 11815 // left any junk around. 11816 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11817 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11818 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11819 removed.clear(); 11820 for (PreferredActivity pa : pir.filterSet()) { 11821 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11822 removed.add(pa); 11823 } 11824 } 11825 if (removed.size() > 0) { 11826 for (int r=0; r<removed.size(); r++) { 11827 PreferredActivity pa = removed.get(r); 11828 Slog.w(TAG, "Removing dangling preferred activity: " 11829 + pa.mPref.mComponent); 11830 pir.removeFilter(pa); 11831 } 11832 mSettings.writePackageRestrictionsLPr( 11833 mSettings.mPreferredActivities.keyAt(i)); 11834 } 11835 } 11836 } 11837 sUserManager.systemReady(); 11838 } 11839 11840 @Override 11841 public boolean isSafeMode() { 11842 return mSafeMode; 11843 } 11844 11845 @Override 11846 public boolean hasSystemUidErrors() { 11847 return mHasSystemUidErrors; 11848 } 11849 11850 static String arrayToString(int[] array) { 11851 StringBuffer buf = new StringBuffer(128); 11852 buf.append('['); 11853 if (array != null) { 11854 for (int i=0; i<array.length; i++) { 11855 if (i > 0) buf.append(", "); 11856 buf.append(array[i]); 11857 } 11858 } 11859 buf.append(']'); 11860 return buf.toString(); 11861 } 11862 11863 static class DumpState { 11864 public static final int DUMP_LIBS = 1 << 0; 11865 11866 public static final int DUMP_FEATURES = 1 << 1; 11867 11868 public static final int DUMP_RESOLVERS = 1 << 2; 11869 11870 public static final int DUMP_PERMISSIONS = 1 << 3; 11871 11872 public static final int DUMP_PACKAGES = 1 << 4; 11873 11874 public static final int DUMP_SHARED_USERS = 1 << 5; 11875 11876 public static final int DUMP_MESSAGES = 1 << 6; 11877 11878 public static final int DUMP_PROVIDERS = 1 << 7; 11879 11880 public static final int DUMP_VERIFIERS = 1 << 8; 11881 11882 public static final int DUMP_PREFERRED = 1 << 9; 11883 11884 public static final int DUMP_PREFERRED_XML = 1 << 10; 11885 11886 public static final int DUMP_KEYSETS = 1 << 11; 11887 11888 public static final int DUMP_VERSION = 1 << 12; 11889 11890 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11891 11892 private int mTypes; 11893 11894 private int mOptions; 11895 11896 private boolean mTitlePrinted; 11897 11898 private SharedUserSetting mSharedUser; 11899 11900 public boolean isDumping(int type) { 11901 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11902 return true; 11903 } 11904 11905 return (mTypes & type) != 0; 11906 } 11907 11908 public void setDump(int type) { 11909 mTypes |= type; 11910 } 11911 11912 public boolean isOptionEnabled(int option) { 11913 return (mOptions & option) != 0; 11914 } 11915 11916 public void setOptionEnabled(int option) { 11917 mOptions |= option; 11918 } 11919 11920 public boolean onTitlePrinted() { 11921 final boolean printed = mTitlePrinted; 11922 mTitlePrinted = true; 11923 return printed; 11924 } 11925 11926 public boolean getTitlePrinted() { 11927 return mTitlePrinted; 11928 } 11929 11930 public void setTitlePrinted(boolean enabled) { 11931 mTitlePrinted = enabled; 11932 } 11933 11934 public SharedUserSetting getSharedUser() { 11935 return mSharedUser; 11936 } 11937 11938 public void setSharedUser(SharedUserSetting user) { 11939 mSharedUser = user; 11940 } 11941 } 11942 11943 @Override 11944 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 11945 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 11946 != PackageManager.PERMISSION_GRANTED) { 11947 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 11948 + Binder.getCallingPid() 11949 + ", uid=" + Binder.getCallingUid() 11950 + " without permission " 11951 + android.Manifest.permission.DUMP); 11952 return; 11953 } 11954 11955 DumpState dumpState = new DumpState(); 11956 boolean fullPreferred = false; 11957 boolean checkin = false; 11958 11959 String packageName = null; 11960 11961 int opti = 0; 11962 while (opti < args.length) { 11963 String opt = args[opti]; 11964 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 11965 break; 11966 } 11967 opti++; 11968 if ("-a".equals(opt)) { 11969 // Right now we only know how to print all. 11970 } else if ("-h".equals(opt)) { 11971 pw.println("Package manager dump options:"); 11972 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 11973 pw.println(" --checkin: dump for a checkin"); 11974 pw.println(" -f: print details of intent filters"); 11975 pw.println(" -h: print this help"); 11976 pw.println(" cmd may be one of:"); 11977 pw.println(" l[ibraries]: list known shared libraries"); 11978 pw.println(" f[ibraries]: list device features"); 11979 pw.println(" k[eysets]: print known keysets"); 11980 pw.println(" r[esolvers]: dump intent resolvers"); 11981 pw.println(" perm[issions]: dump permissions"); 11982 pw.println(" pref[erred]: print preferred package settings"); 11983 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 11984 pw.println(" prov[iders]: dump content providers"); 11985 pw.println(" p[ackages]: dump installed packages"); 11986 pw.println(" s[hared-users]: dump shared user IDs"); 11987 pw.println(" m[essages]: print collected runtime messages"); 11988 pw.println(" v[erifiers]: print package verifier info"); 11989 pw.println(" version: print database version info"); 11990 pw.println(" write: write current settings now"); 11991 pw.println(" <package.name>: info about given package"); 11992 return; 11993 } else if ("--checkin".equals(opt)) { 11994 checkin = true; 11995 } else if ("-f".equals(opt)) { 11996 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11997 } else { 11998 pw.println("Unknown argument: " + opt + "; use -h for help"); 11999 } 12000 } 12001 12002 // Is the caller requesting to dump a particular piece of data? 12003 if (opti < args.length) { 12004 String cmd = args[opti]; 12005 opti++; 12006 // Is this a package name? 12007 if ("android".equals(cmd) || cmd.contains(".")) { 12008 packageName = cmd; 12009 // When dumping a single package, we always dump all of its 12010 // filter information since the amount of data will be reasonable. 12011 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12012 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12013 dumpState.setDump(DumpState.DUMP_LIBS); 12014 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12015 dumpState.setDump(DumpState.DUMP_FEATURES); 12016 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12017 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12018 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12019 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12020 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12021 dumpState.setDump(DumpState.DUMP_PREFERRED); 12022 } else if ("preferred-xml".equals(cmd)) { 12023 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12024 if (opti < args.length && "--full".equals(args[opti])) { 12025 fullPreferred = true; 12026 opti++; 12027 } 12028 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12029 dumpState.setDump(DumpState.DUMP_PACKAGES); 12030 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12031 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12032 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12033 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12034 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12035 dumpState.setDump(DumpState.DUMP_MESSAGES); 12036 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12037 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12038 } else if ("version".equals(cmd)) { 12039 dumpState.setDump(DumpState.DUMP_VERSION); 12040 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12041 dumpState.setDump(DumpState.DUMP_KEYSETS); 12042 } else if ("write".equals(cmd)) { 12043 synchronized (mPackages) { 12044 mSettings.writeLPr(); 12045 pw.println("Settings written."); 12046 return; 12047 } 12048 } 12049 } 12050 12051 if (checkin) { 12052 pw.println("vers,1"); 12053 } 12054 12055 // reader 12056 synchronized (mPackages) { 12057 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12058 if (!checkin) { 12059 if (dumpState.onTitlePrinted()) 12060 pw.println(); 12061 pw.println("Database versions:"); 12062 pw.print(" SDK Version:"); 12063 pw.print(" internal="); 12064 pw.print(mSettings.mInternalSdkPlatform); 12065 pw.print(" external="); 12066 pw.println(mSettings.mExternalSdkPlatform); 12067 pw.print(" DB Version:"); 12068 pw.print(" internal="); 12069 pw.print(mSettings.mInternalDatabaseVersion); 12070 pw.print(" external="); 12071 pw.println(mSettings.mExternalDatabaseVersion); 12072 } 12073 } 12074 12075 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12076 if (!checkin) { 12077 if (dumpState.onTitlePrinted()) 12078 pw.println(); 12079 pw.println("Verifiers:"); 12080 pw.print(" Required: "); 12081 pw.print(mRequiredVerifierPackage); 12082 pw.print(" (uid="); 12083 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12084 pw.println(")"); 12085 } else if (mRequiredVerifierPackage != null) { 12086 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12087 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12088 } 12089 } 12090 12091 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12092 boolean printedHeader = false; 12093 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12094 while (it.hasNext()) { 12095 String name = it.next(); 12096 SharedLibraryEntry ent = mSharedLibraries.get(name); 12097 if (!checkin) { 12098 if (!printedHeader) { 12099 if (dumpState.onTitlePrinted()) 12100 pw.println(); 12101 pw.println("Libraries:"); 12102 printedHeader = true; 12103 } 12104 pw.print(" "); 12105 } else { 12106 pw.print("lib,"); 12107 } 12108 pw.print(name); 12109 if (!checkin) { 12110 pw.print(" -> "); 12111 } 12112 if (ent.path != null) { 12113 if (!checkin) { 12114 pw.print("(jar) "); 12115 pw.print(ent.path); 12116 } else { 12117 pw.print(",jar,"); 12118 pw.print(ent.path); 12119 } 12120 } else { 12121 if (!checkin) { 12122 pw.print("(apk) "); 12123 pw.print(ent.apk); 12124 } else { 12125 pw.print(",apk,"); 12126 pw.print(ent.apk); 12127 } 12128 } 12129 pw.println(); 12130 } 12131 } 12132 12133 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12134 if (dumpState.onTitlePrinted()) 12135 pw.println(); 12136 if (!checkin) { 12137 pw.println("Features:"); 12138 } 12139 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12140 while (it.hasNext()) { 12141 String name = it.next(); 12142 if (!checkin) { 12143 pw.print(" "); 12144 } else { 12145 pw.print("feat,"); 12146 } 12147 pw.println(name); 12148 } 12149 } 12150 12151 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12152 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12153 : "Activity Resolver Table:", " ", packageName, 12154 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12155 dumpState.setTitlePrinted(true); 12156 } 12157 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12158 : "Receiver Resolver Table:", " ", packageName, 12159 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12160 dumpState.setTitlePrinted(true); 12161 } 12162 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12163 : "Service Resolver Table:", " ", packageName, 12164 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12165 dumpState.setTitlePrinted(true); 12166 } 12167 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12168 : "Provider Resolver Table:", " ", packageName, 12169 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12170 dumpState.setTitlePrinted(true); 12171 } 12172 } 12173 12174 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12175 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12176 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12177 int user = mSettings.mPreferredActivities.keyAt(i); 12178 if (pir.dump(pw, 12179 dumpState.getTitlePrinted() 12180 ? "\nPreferred Activities User " + user + ":" 12181 : "Preferred Activities User " + user + ":", " ", 12182 packageName, true)) { 12183 dumpState.setTitlePrinted(true); 12184 } 12185 } 12186 } 12187 12188 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12189 pw.flush(); 12190 FileOutputStream fout = new FileOutputStream(fd); 12191 BufferedOutputStream str = new BufferedOutputStream(fout); 12192 XmlSerializer serializer = new FastXmlSerializer(); 12193 try { 12194 serializer.setOutput(str, "utf-8"); 12195 serializer.startDocument(null, true); 12196 serializer.setFeature( 12197 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12198 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12199 serializer.endDocument(); 12200 serializer.flush(); 12201 } catch (IllegalArgumentException e) { 12202 pw.println("Failed writing: " + e); 12203 } catch (IllegalStateException e) { 12204 pw.println("Failed writing: " + e); 12205 } catch (IOException e) { 12206 pw.println("Failed writing: " + e); 12207 } 12208 } 12209 12210 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12211 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12212 } 12213 12214 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12215 boolean printedSomething = false; 12216 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12217 if (packageName != null && !packageName.equals(p.info.packageName)) { 12218 continue; 12219 } 12220 if (!printedSomething) { 12221 if (dumpState.onTitlePrinted()) 12222 pw.println(); 12223 pw.println("Registered ContentProviders:"); 12224 printedSomething = true; 12225 } 12226 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12227 pw.print(" "); pw.println(p.toString()); 12228 } 12229 printedSomething = false; 12230 for (Map.Entry<String, PackageParser.Provider> entry : 12231 mProvidersByAuthority.entrySet()) { 12232 PackageParser.Provider p = entry.getValue(); 12233 if (packageName != null && !packageName.equals(p.info.packageName)) { 12234 continue; 12235 } 12236 if (!printedSomething) { 12237 if (dumpState.onTitlePrinted()) 12238 pw.println(); 12239 pw.println("ContentProvider Authorities:"); 12240 printedSomething = true; 12241 } 12242 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12243 pw.print(" "); pw.println(p.toString()); 12244 if (p.info != null && p.info.applicationInfo != null) { 12245 final String appInfo = p.info.applicationInfo.toString(); 12246 pw.print(" applicationInfo="); pw.println(appInfo); 12247 } 12248 } 12249 } 12250 12251 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12252 mSettings.mKeySetManager.dump(pw, packageName, dumpState); 12253 } 12254 12255 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12256 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12257 } 12258 12259 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12260 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12261 } 12262 12263 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12264 if (dumpState.onTitlePrinted()) 12265 pw.println(); 12266 mSettings.dumpReadMessagesLPr(pw, dumpState); 12267 12268 pw.println(); 12269 pw.println("Package warning messages:"); 12270 final File fname = getSettingsProblemFile(); 12271 FileInputStream in = null; 12272 try { 12273 in = new FileInputStream(fname); 12274 final int avail = in.available(); 12275 final byte[] data = new byte[avail]; 12276 in.read(data); 12277 pw.print(new String(data)); 12278 } catch (FileNotFoundException e) { 12279 } catch (IOException e) { 12280 } finally { 12281 if (in != null) { 12282 try { 12283 in.close(); 12284 } catch (IOException e) { 12285 } 12286 } 12287 } 12288 } 12289 } 12290 } 12291 12292 // ------- apps on sdcard specific code ------- 12293 static final boolean DEBUG_SD_INSTALL = false; 12294 12295 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12296 12297 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12298 12299 private boolean mMediaMounted = false; 12300 12301 private String getEncryptKey() { 12302 try { 12303 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12304 SD_ENCRYPTION_KEYSTORE_NAME); 12305 if (sdEncKey == null) { 12306 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12307 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12308 if (sdEncKey == null) { 12309 Slog.e(TAG, "Failed to create encryption keys"); 12310 return null; 12311 } 12312 } 12313 return sdEncKey; 12314 } catch (NoSuchAlgorithmException nsae) { 12315 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12316 return null; 12317 } catch (IOException ioe) { 12318 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12319 return null; 12320 } 12321 12322 } 12323 12324 /* package */static String getTempContainerId() { 12325 int tmpIdx = 1; 12326 String list[] = PackageHelper.getSecureContainerList(); 12327 if (list != null) { 12328 for (final String name : list) { 12329 // Ignore null and non-temporary container entries 12330 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12331 continue; 12332 } 12333 12334 String subStr = name.substring(mTempContainerPrefix.length()); 12335 try { 12336 int cid = Integer.parseInt(subStr); 12337 if (cid >= tmpIdx) { 12338 tmpIdx = cid + 1; 12339 } 12340 } catch (NumberFormatException e) { 12341 } 12342 } 12343 } 12344 return mTempContainerPrefix + tmpIdx; 12345 } 12346 12347 /* 12348 * Update media status on PackageManager. 12349 */ 12350 @Override 12351 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12352 int callingUid = Binder.getCallingUid(); 12353 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12354 throw new SecurityException("Media status can only be updated by the system"); 12355 } 12356 // reader; this apparently protects mMediaMounted, but should probably 12357 // be a different lock in that case. 12358 synchronized (mPackages) { 12359 Log.i(TAG, "Updating external media status from " 12360 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12361 + (mediaStatus ? "mounted" : "unmounted")); 12362 if (DEBUG_SD_INSTALL) 12363 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12364 + ", mMediaMounted=" + mMediaMounted); 12365 if (mediaStatus == mMediaMounted) { 12366 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12367 : 0, -1); 12368 mHandler.sendMessage(msg); 12369 return; 12370 } 12371 mMediaMounted = mediaStatus; 12372 } 12373 // Queue up an async operation since the package installation may take a 12374 // little while. 12375 mHandler.post(new Runnable() { 12376 public void run() { 12377 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12378 } 12379 }); 12380 } 12381 12382 /** 12383 * Called by MountService when the initial ASECs to scan are available. 12384 * Should block until all the ASEC containers are finished being scanned. 12385 */ 12386 public void scanAvailableAsecs() { 12387 updateExternalMediaStatusInner(true, false, false); 12388 if (mShouldRestoreconData) { 12389 SELinuxMMAC.setRestoreconDone(); 12390 mShouldRestoreconData = false; 12391 } 12392 } 12393 12394 /* 12395 * Collect information of applications on external media, map them against 12396 * existing containers and update information based on current mount status. 12397 * Please note that we always have to report status if reportStatus has been 12398 * set to true especially when unloading packages. 12399 */ 12400 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12401 boolean externalStorage) { 12402 // Collection of uids 12403 int uidArr[] = null; 12404 // Collection of stale containers 12405 HashSet<String> removeCids = new HashSet<String>(); 12406 // Collection of packages on external media with valid containers. 12407 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12408 // Get list of secure containers. 12409 final String list[] = PackageHelper.getSecureContainerList(); 12410 if (list == null || list.length == 0) { 12411 Log.i(TAG, "No secure containers on sdcard"); 12412 } else { 12413 // Process list of secure containers and categorize them 12414 // as active or stale based on their package internal state. 12415 int uidList[] = new int[list.length]; 12416 int num = 0; 12417 // reader 12418 synchronized (mPackages) { 12419 for (String cid : list) { 12420 if (DEBUG_SD_INSTALL) 12421 Log.i(TAG, "Processing container " + cid); 12422 String pkgName = getAsecPackageName(cid); 12423 if (pkgName == null) { 12424 if (DEBUG_SD_INSTALL) 12425 Log.i(TAG, "Container : " + cid + " stale"); 12426 removeCids.add(cid); 12427 continue; 12428 } 12429 if (DEBUG_SD_INSTALL) 12430 Log.i(TAG, "Looking for pkg : " + pkgName); 12431 12432 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12433 if (ps == null) { 12434 Log.i(TAG, "Deleting container with no matching settings " + cid); 12435 removeCids.add(cid); 12436 continue; 12437 } 12438 12439 /* 12440 * Skip packages that are not external if we're unmounting 12441 * external storage. 12442 */ 12443 if (externalStorage && !isMounted && !isExternal(ps)) { 12444 continue; 12445 } 12446 12447 final AsecInstallArgs args = new AsecInstallArgs(cid, 12448 getAppInstructionSetFromSettings(ps), 12449 isForwardLocked(ps)); 12450 // The package status is changed only if the code path 12451 // matches between settings and the container id. 12452 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12453 if (DEBUG_SD_INSTALL) { 12454 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12455 + " at code path: " + ps.codePathString); 12456 } 12457 12458 // We do have a valid package installed on sdcard 12459 processCids.put(args, ps.codePathString); 12460 final int uid = ps.appId; 12461 if (uid != -1) { 12462 uidList[num++] = uid; 12463 } 12464 } else { 12465 Log.i(TAG, "Deleting stale container for " + cid); 12466 removeCids.add(cid); 12467 } 12468 } 12469 } 12470 12471 if (num > 0) { 12472 // Sort uid list 12473 Arrays.sort(uidList, 0, num); 12474 // Throw away duplicates 12475 uidArr = new int[num]; 12476 uidArr[0] = uidList[0]; 12477 int di = 0; 12478 for (int i = 1; i < num; i++) { 12479 if (uidList[i - 1] != uidList[i]) { 12480 uidArr[di++] = uidList[i]; 12481 } 12482 } 12483 } 12484 } 12485 // Process packages with valid entries. 12486 if (isMounted) { 12487 if (DEBUG_SD_INSTALL) 12488 Log.i(TAG, "Loading packages"); 12489 loadMediaPackages(processCids, uidArr, removeCids); 12490 startCleaningPackages(); 12491 } else { 12492 if (DEBUG_SD_INSTALL) 12493 Log.i(TAG, "Unloading packages"); 12494 unloadMediaPackages(processCids, uidArr, reportStatus); 12495 } 12496 } 12497 12498 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12499 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12500 int size = pkgList.size(); 12501 if (size > 0) { 12502 // Send broadcasts here 12503 Bundle extras = new Bundle(); 12504 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12505 .toArray(new String[size])); 12506 if (uidArr != null) { 12507 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12508 } 12509 if (replacing) { 12510 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12511 } 12512 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12513 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12514 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12515 } 12516 } 12517 12518 /* 12519 * Look at potentially valid container ids from processCids If package 12520 * information doesn't match the one on record or package scanning fails, 12521 * the cid is added to list of removeCids. We currently don't delete stale 12522 * containers. 12523 */ 12524 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12525 HashSet<String> removeCids) { 12526 ArrayList<String> pkgList = new ArrayList<String>(); 12527 Set<AsecInstallArgs> keys = processCids.keySet(); 12528 boolean doGc = false; 12529 for (AsecInstallArgs args : keys) { 12530 String codePath = processCids.get(args); 12531 if (DEBUG_SD_INSTALL) 12532 Log.i(TAG, "Loading container : " + args.cid); 12533 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12534 try { 12535 // Make sure there are no container errors first. 12536 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12537 Slog.e(TAG, "Failed to mount cid : " + args.cid 12538 + " when installing from sdcard"); 12539 continue; 12540 } 12541 // Check code path here. 12542 if (codePath == null || !codePath.equals(args.getCodePath())) { 12543 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12544 + " does not match one in settings " + codePath); 12545 continue; 12546 } 12547 // Parse package 12548 int parseFlags = mDefParseFlags; 12549 if (args.isExternal()) { 12550 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12551 } 12552 if (args.isFwdLocked()) { 12553 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12554 } 12555 12556 doGc = true; 12557 synchronized (mInstallLock) { 12558 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 12559 0, 0, null, null); 12560 // Scan the package 12561 if (pkg != null) { 12562 /* 12563 * TODO why is the lock being held? doPostInstall is 12564 * called in other places without the lock. This needs 12565 * to be straightened out. 12566 */ 12567 // writer 12568 synchronized (mPackages) { 12569 retCode = PackageManager.INSTALL_SUCCEEDED; 12570 pkgList.add(pkg.packageName); 12571 // Post process args 12572 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12573 pkg.applicationInfo.uid); 12574 } 12575 } else { 12576 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12577 } 12578 } 12579 12580 } finally { 12581 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12582 // Don't destroy container here. Wait till gc clears things 12583 // up. 12584 removeCids.add(args.cid); 12585 } 12586 } 12587 } 12588 // writer 12589 synchronized (mPackages) { 12590 // If the platform SDK has changed since the last time we booted, 12591 // we need to re-grant app permission to catch any new ones that 12592 // appear. This is really a hack, and means that apps can in some 12593 // cases get permissions that the user didn't initially explicitly 12594 // allow... it would be nice to have some better way to handle 12595 // this situation. 12596 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12597 if (regrantPermissions) 12598 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12599 + mSdkVersion + "; regranting permissions for external storage"); 12600 mSettings.mExternalSdkPlatform = mSdkVersion; 12601 12602 // Make sure group IDs have been assigned, and any permission 12603 // changes in other apps are accounted for 12604 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12605 | (regrantPermissions 12606 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12607 : 0)); 12608 12609 mSettings.updateExternalDatabaseVersion(); 12610 12611 // can downgrade to reader 12612 // Persist settings 12613 mSettings.writeLPr(); 12614 } 12615 // Send a broadcast to let everyone know we are done processing 12616 if (pkgList.size() > 0) { 12617 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12618 } 12619 // Force gc to avoid any stale parser references that we might have. 12620 if (doGc) { 12621 Runtime.getRuntime().gc(); 12622 } 12623 // List stale containers and destroy stale temporary containers. 12624 if (removeCids != null) { 12625 for (String cid : removeCids) { 12626 if (cid.startsWith(mTempContainerPrefix)) { 12627 Log.i(TAG, "Destroying stale temporary container " + cid); 12628 PackageHelper.destroySdDir(cid); 12629 } else { 12630 Log.w(TAG, "Container " + cid + " is stale"); 12631 } 12632 } 12633 } 12634 } 12635 12636 /* 12637 * Utility method to unload a list of specified containers 12638 */ 12639 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12640 // Just unmount all valid containers. 12641 for (AsecInstallArgs arg : cidArgs) { 12642 synchronized (mInstallLock) { 12643 arg.doPostDeleteLI(false); 12644 } 12645 } 12646 } 12647 12648 /* 12649 * Unload packages mounted on external media. This involves deleting package 12650 * data from internal structures, sending broadcasts about diabled packages, 12651 * gc'ing to free up references, unmounting all secure containers 12652 * corresponding to packages on external media, and posting a 12653 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12654 * that we always have to post this message if status has been requested no 12655 * matter what. 12656 */ 12657 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12658 final boolean reportStatus) { 12659 if (DEBUG_SD_INSTALL) 12660 Log.i(TAG, "unloading media packages"); 12661 ArrayList<String> pkgList = new ArrayList<String>(); 12662 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12663 final Set<AsecInstallArgs> keys = processCids.keySet(); 12664 for (AsecInstallArgs args : keys) { 12665 String pkgName = args.getPackageName(); 12666 if (DEBUG_SD_INSTALL) 12667 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12668 // Delete package internally 12669 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12670 synchronized (mInstallLock) { 12671 boolean res = deletePackageLI(pkgName, null, false, null, null, 12672 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12673 if (res) { 12674 pkgList.add(pkgName); 12675 } else { 12676 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12677 failedList.add(args); 12678 } 12679 } 12680 } 12681 12682 // reader 12683 synchronized (mPackages) { 12684 // We didn't update the settings after removing each package; 12685 // write them now for all packages. 12686 mSettings.writeLPr(); 12687 } 12688 12689 // We have to absolutely send UPDATED_MEDIA_STATUS only 12690 // after confirming that all the receivers processed the ordered 12691 // broadcast when packages get disabled, force a gc to clean things up. 12692 // and unload all the containers. 12693 if (pkgList.size() > 0) { 12694 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12695 new IIntentReceiver.Stub() { 12696 public void performReceive(Intent intent, int resultCode, String data, 12697 Bundle extras, boolean ordered, boolean sticky, 12698 int sendingUser) throws RemoteException { 12699 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12700 reportStatus ? 1 : 0, 1, keys); 12701 mHandler.sendMessage(msg); 12702 } 12703 }); 12704 } else { 12705 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12706 keys); 12707 mHandler.sendMessage(msg); 12708 } 12709 } 12710 12711 /** Binder call */ 12712 @Override 12713 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12714 final int flags) { 12715 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12716 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12717 int returnCode = PackageManager.MOVE_SUCCEEDED; 12718 int currFlags = 0; 12719 int newFlags = 0; 12720 // reader 12721 synchronized (mPackages) { 12722 PackageParser.Package pkg = mPackages.get(packageName); 12723 if (pkg == null) { 12724 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12725 } else { 12726 // Disable moving fwd locked apps and system packages 12727 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12728 Slog.w(TAG, "Cannot move system application"); 12729 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12730 } else if (pkg.mOperationPending) { 12731 Slog.w(TAG, "Attempt to move package which has pending operations"); 12732 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12733 } else { 12734 // Find install location first 12735 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12736 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12737 Slog.w(TAG, "Ambigous flags specified for move location."); 12738 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12739 } else { 12740 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12741 : PackageManager.INSTALL_INTERNAL; 12742 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12743 : PackageManager.INSTALL_INTERNAL; 12744 12745 if (newFlags == currFlags) { 12746 Slog.w(TAG, "No move required. Trying to move to same location"); 12747 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12748 } else { 12749 if (isForwardLocked(pkg)) { 12750 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12751 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12752 } 12753 } 12754 } 12755 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12756 pkg.mOperationPending = true; 12757 } 12758 } 12759 } 12760 12761 /* 12762 * TODO this next block probably shouldn't be inside the lock. We 12763 * can't guarantee these won't change after this is fired off 12764 * anyway. 12765 */ 12766 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12767 processPendingMove(new MoveParams(null, observer, 0, packageName, null, 12768 null, -1, user), 12769 returnCode); 12770 } else { 12771 Message msg = mHandler.obtainMessage(INIT_COPY); 12772 final String instructionSet = getAppInstructionSet(pkg.applicationInfo); 12773 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir, 12774 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir, 12775 instructionSet); 12776 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12777 pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user); 12778 msg.obj = mp; 12779 mHandler.sendMessage(msg); 12780 } 12781 } 12782 } 12783 12784 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12785 // Queue up an async operation since the package deletion may take a 12786 // little while. 12787 mHandler.post(new Runnable() { 12788 public void run() { 12789 // TODO fix this; this does nothing. 12790 mHandler.removeCallbacks(this); 12791 int returnCode = currentStatus; 12792 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12793 int uidArr[] = null; 12794 ArrayList<String> pkgList = null; 12795 synchronized (mPackages) { 12796 PackageParser.Package pkg = mPackages.get(mp.packageName); 12797 if (pkg == null) { 12798 Slog.w(TAG, " Package " + mp.packageName 12799 + " doesn't exist. Aborting move"); 12800 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12801 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 12802 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12803 + mp.srcArgs.getCodePath() + " to " 12804 + pkg.applicationInfo.sourceDir 12805 + " Aborting move and returning error"); 12806 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12807 } else { 12808 uidArr = new int[] { 12809 pkg.applicationInfo.uid 12810 }; 12811 pkgList = new ArrayList<String>(); 12812 pkgList.add(mp.packageName); 12813 } 12814 } 12815 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12816 // Send resources unavailable broadcast 12817 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12818 // Update package code and resource paths 12819 synchronized (mInstallLock) { 12820 synchronized (mPackages) { 12821 PackageParser.Package pkg = mPackages.get(mp.packageName); 12822 // Recheck for package again. 12823 if (pkg == null) { 12824 Slog.w(TAG, " Package " + mp.packageName 12825 + " doesn't exist. Aborting move"); 12826 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12827 } else if (!mp.srcArgs.getCodePath().equals( 12828 pkg.applicationInfo.sourceDir)) { 12829 Slog.w(TAG, "Package " + mp.packageName 12830 + " code path changed from " + mp.srcArgs.getCodePath() 12831 + " to " + pkg.applicationInfo.sourceDir 12832 + " Aborting move and returning error"); 12833 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12834 } else { 12835 final String oldCodePath = pkg.codePath; 12836 final String newCodePath = mp.targetArgs.getCodePath(); 12837 final String newResPath = mp.targetArgs.getResourcePath(); 12838 final String newNativePath = mp.targetArgs 12839 .getNativeLibraryPath(); 12840 12841 final File newNativeDir = new File(newNativePath); 12842 12843 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12844 // NOTE: We do not report any errors from the APK scan and library 12845 // copy at this point. 12846 NativeLibraryHelper.ApkHandle handle = 12847 new NativeLibraryHelper.ApkHandle(newCodePath); 12848 final int abi = NativeLibraryHelper.findSupportedAbi( 12849 handle, Build.SUPPORTED_ABIS); 12850 if (abi >= 0) { 12851 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12852 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12853 } 12854 handle.close(); 12855 } 12856 final int[] users = sUserManager.getUserIds(); 12857 for (int user : users) { 12858 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 12859 newNativePath, user) < 0) { 12860 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12861 } 12862 } 12863 12864 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12865 pkg.codePath = newCodePath; 12866 // Move dex files around 12867 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 12868 // Moving of dex files failed. Set 12869 // error code and abort move. 12870 pkg.codePath = oldCodePath; 12871 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12872 } 12873 } 12874 12875 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12876 pkg.applicationInfo.sourceDir = newCodePath; 12877 pkg.applicationInfo.publicSourceDir = newResPath; 12878 pkg.applicationInfo.nativeLibraryDir = newNativePath; 12879 PackageSetting ps = (PackageSetting) pkg.mExtras; 12880 ps.codePath = new File(pkg.applicationInfo.sourceDir); 12881 ps.codePathString = ps.codePath.getPath(); 12882 ps.resourcePath = new File( 12883 pkg.applicationInfo.publicSourceDir); 12884 ps.resourcePathString = ps.resourcePath.getPath(); 12885 ps.nativeLibraryPathString = newNativePath; 12886 // Set the application info flag 12887 // correctly. 12888 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 12889 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12890 } else { 12891 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12892 } 12893 ps.setFlags(pkg.applicationInfo.flags); 12894 mAppDirs.remove(oldCodePath); 12895 mAppDirs.put(newCodePath, pkg); 12896 // Persist settings 12897 mSettings.writeLPr(); 12898 } 12899 } 12900 } 12901 } 12902 // Send resources available broadcast 12903 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12904 } 12905 } 12906 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12907 // Clean up failed installation 12908 if (mp.targetArgs != null) { 12909 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 12910 -1); 12911 } 12912 } else { 12913 // Force a gc to clear things up. 12914 Runtime.getRuntime().gc(); 12915 // Delete older code 12916 synchronized (mInstallLock) { 12917 mp.srcArgs.doPostDeleteLI(true); 12918 } 12919 } 12920 12921 // Allow more operations on this file if we didn't fail because 12922 // an operation was already pending for this package. 12923 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 12924 synchronized (mPackages) { 12925 PackageParser.Package pkg = mPackages.get(mp.packageName); 12926 if (pkg != null) { 12927 pkg.mOperationPending = false; 12928 } 12929 } 12930 } 12931 12932 IPackageMoveObserver observer = mp.observer; 12933 if (observer != null) { 12934 try { 12935 observer.packageMoved(mp.packageName, returnCode); 12936 } catch (RemoteException e) { 12937 Log.i(TAG, "Observer no longer exists."); 12938 } 12939 } 12940 } 12941 }); 12942 } 12943 12944 @Override 12945 public boolean setInstallLocation(int loc) { 12946 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12947 null); 12948 if (getInstallLocation() == loc) { 12949 return true; 12950 } 12951 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12952 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12953 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12954 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12955 return true; 12956 } 12957 return false; 12958 } 12959 12960 @Override 12961 public int getInstallLocation() { 12962 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12963 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12964 PackageHelper.APP_INSTALL_AUTO); 12965 } 12966 12967 /** Called by UserManagerService */ 12968 void cleanUpUserLILPw(int userHandle) { 12969 mDirtyUsers.remove(userHandle); 12970 mSettings.removeUserLPr(userHandle); 12971 mPendingBroadcasts.remove(userHandle); 12972 if (mInstaller != null) { 12973 // Technically, we shouldn't be doing this with the package lock 12974 // held. However, this is very rare, and there is already so much 12975 // other disk I/O going on, that we'll let it slide for now. 12976 mInstaller.removeUserDataDirs(userHandle); 12977 } 12978 } 12979 12980 /** Called by UserManagerService */ 12981 void createNewUserLILPw(int userHandle, File path) { 12982 if (mInstaller != null) { 12983 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 12984 } 12985 } 12986 12987 @Override 12988 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 12989 mContext.enforceCallingOrSelfPermission( 12990 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12991 "Only package verification agents can read the verifier device identity"); 12992 12993 synchronized (mPackages) { 12994 return mSettings.getVerifierDeviceIdentityLPw(); 12995 } 12996 } 12997 12998 @Override 12999 public void setPermissionEnforced(String permission, boolean enforced) { 13000 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13001 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13002 synchronized (mPackages) { 13003 if (mSettings.mReadExternalStorageEnforced == null 13004 || mSettings.mReadExternalStorageEnforced != enforced) { 13005 mSettings.mReadExternalStorageEnforced = enforced; 13006 mSettings.writeLPr(); 13007 } 13008 } 13009 // kill any non-foreground processes so we restart them and 13010 // grant/revoke the GID. 13011 final IActivityManager am = ActivityManagerNative.getDefault(); 13012 if (am != null) { 13013 final long token = Binder.clearCallingIdentity(); 13014 try { 13015 am.killProcessesBelowForeground("setPermissionEnforcement"); 13016 } catch (RemoteException e) { 13017 } finally { 13018 Binder.restoreCallingIdentity(token); 13019 } 13020 } 13021 } else { 13022 throw new IllegalArgumentException("No selective enforcement for " + permission); 13023 } 13024 } 13025 13026 @Override 13027 @Deprecated 13028 public boolean isPermissionEnforced(String permission) { 13029 return true; 13030 } 13031 13032 @Override 13033 public boolean isStorageLow() { 13034 final long token = Binder.clearCallingIdentity(); 13035 try { 13036 final DeviceStorageMonitorInternal 13037 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13038 if (dsm != null) { 13039 return dsm.isMemoryLow(); 13040 } else { 13041 return false; 13042 } 13043 } finally { 13044 Binder.restoreCallingIdentity(token); 13045 } 13046 } 13047 13048 @Override 13049 public IPackageInstaller getPackageInstaller() { 13050 return mInstallerService; 13051 } 13052} 13053