PackageManagerService.java revision c13053bf1c05b980421611487ce67677c08db299
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.content.pm.PackageParser.isPackageFilename; 28import static android.os.Process.PACKAGE_INFO_GID; 29import static android.os.Process.SYSTEM_UID; 30import static android.system.OsConstants.S_IRGRP; 31import static android.system.OsConstants.S_IROTH; 32import static android.system.OsConstants.S_IRWXU; 33import static android.system.OsConstants.S_IXGRP; 34import static android.system.OsConstants.S_IXOTH; 35import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 36import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 37import static com.android.internal.util.ArrayUtils.appendInt; 38import static com.android.internal.util.ArrayUtils.removeInt; 39 40import android.util.ArrayMap; 41import com.android.internal.R; 42import com.android.internal.app.IMediaContainerService; 43import com.android.internal.app.ResolverActivity; 44import com.android.internal.content.NativeLibraryHelper; 45import com.android.internal.content.NativeLibraryHelper.ApkHandle; 46import com.android.internal.content.PackageHelper; 47import com.android.internal.util.ArrayUtils; 48import com.android.internal.util.FastPrintWriter; 49import com.android.internal.util.FastXmlSerializer; 50import com.android.internal.util.Preconditions; 51import com.android.internal.util.XmlUtils; 52import com.android.server.EventLogTags; 53import com.android.server.IntentResolver; 54import com.android.server.LocalServices; 55import com.android.server.ServiceThread; 56import com.android.server.SystemConfig; 57import com.android.server.Watchdog; 58import com.android.server.pm.Settings.DatabaseVersion; 59import com.android.server.storage.DeviceStorageMonitorInternal; 60 61import org.xmlpull.v1.XmlPullParser; 62import org.xmlpull.v1.XmlPullParserException; 63import org.xmlpull.v1.XmlSerializer; 64 65import android.app.ActivityManager; 66import android.app.ActivityManagerNative; 67import android.app.IActivityManager; 68import android.app.PackageInstallObserver; 69import android.app.admin.IDevicePolicyManager; 70import android.app.backup.IBackupManager; 71import android.content.BroadcastReceiver; 72import android.content.ComponentName; 73import android.content.Context; 74import android.content.IIntentReceiver; 75import android.content.Intent; 76import android.content.IntentFilter; 77import android.content.IntentSender; 78import android.content.IntentSender.SendIntentException; 79import android.content.ServiceConnection; 80import android.content.pm.ActivityInfo; 81import android.content.pm.ApplicationInfo; 82import android.content.pm.ContainerEncryptionParams; 83import android.content.pm.FeatureInfo; 84import android.content.pm.IPackageDataObserver; 85import android.content.pm.IPackageDeleteObserver; 86import android.content.pm.IPackageInstallObserver; 87import android.content.pm.IPackageInstallObserver2; 88import android.content.pm.IPackageInstaller; 89import android.content.pm.IPackageManager; 90import android.content.pm.IPackageMoveObserver; 91import android.content.pm.IPackageStatsObserver; 92import android.content.pm.InstrumentationInfo; 93import android.content.pm.ManifestDigest; 94import android.content.pm.PackageCleanItem; 95import android.content.pm.PackageInfo; 96import android.content.pm.PackageInfoLite; 97import android.content.pm.PackageInstallerParams; 98import android.content.pm.PackageManager; 99import android.content.pm.PackageParser.ActivityIntentInfo; 100import android.content.pm.PackageParser.PackageParserException; 101import android.content.pm.PackageParser; 102import android.content.pm.PackageStats; 103import android.content.pm.PackageUserState; 104import android.content.pm.ParceledListSlice; 105import android.content.pm.PermissionGroupInfo; 106import android.content.pm.PermissionInfo; 107import android.content.pm.ProviderInfo; 108import android.content.pm.ResolveInfo; 109import android.content.pm.ServiceInfo; 110import android.content.pm.Signature; 111import android.content.pm.UserInfo; 112import android.content.pm.VerificationParams; 113import android.content.pm.VerifierDeviceIdentity; 114import android.content.pm.VerifierInfo; 115import android.content.res.Resources; 116import android.hardware.display.DisplayManager; 117import android.net.Uri; 118import android.os.Binder; 119import android.os.Build; 120import android.os.Bundle; 121import android.os.Environment; 122import android.os.Environment.UserEnvironment; 123import android.os.FileObserver; 124import android.os.FileUtils; 125import android.os.Handler; 126import android.os.IBinder; 127import android.os.Looper; 128import android.os.Message; 129import android.os.Parcel; 130import android.os.ParcelFileDescriptor; 131import android.os.Process; 132import android.os.RemoteException; 133import android.os.SELinux; 134import android.os.ServiceManager; 135import android.os.SystemClock; 136import android.os.SystemProperties; 137import android.os.UserHandle; 138import android.os.UserManager; 139import android.security.KeyStore; 140import android.security.SystemKeyStore; 141import android.system.ErrnoException; 142import android.system.Os; 143import android.system.StructStat; 144import android.text.TextUtils; 145import android.util.ArraySet; 146import android.util.AtomicFile; 147import android.util.DisplayMetrics; 148import android.util.EventLog; 149import android.util.Log; 150import android.util.LogPrinter; 151import android.util.PrintStreamPrinter; 152import android.util.Slog; 153import android.util.SparseArray; 154import android.util.SparseBooleanArray; 155import android.util.Xml; 156import android.view.Display; 157 158import java.io.BufferedInputStream; 159import java.io.BufferedOutputStream; 160import java.io.File; 161import java.io.FileDescriptor; 162import java.io.FileInputStream; 163import java.io.FileNotFoundException; 164import java.io.FileOutputStream; 165import java.io.FileReader; 166import java.io.FilenameFilter; 167import java.io.IOException; 168import java.io.InputStream; 169import java.io.PrintWriter; 170import java.nio.charset.StandardCharsets; 171import java.security.NoSuchAlgorithmException; 172import java.security.PublicKey; 173import java.security.cert.CertificateEncodingException; 174import java.security.cert.CertificateException; 175import java.text.SimpleDateFormat; 176import java.util.ArrayList; 177import java.util.Arrays; 178import java.util.Collection; 179import java.util.Collections; 180import java.util.Comparator; 181import java.util.Date; 182import java.util.HashMap; 183import java.util.HashSet; 184import java.util.Iterator; 185import java.util.List; 186import java.util.Map; 187import java.util.Set; 188import java.util.concurrent.atomic.AtomicBoolean; 189import java.util.concurrent.atomic.AtomicLong; 190 191import dalvik.system.DexFile; 192import dalvik.system.StaleDexCacheError; 193import dalvik.system.VMRuntime; 194 195import libcore.io.IoUtils; 196 197/** 198 * Keep track of all those .apks everywhere. 199 * 200 * This is very central to the platform's security; please run the unit 201 * tests whenever making modifications here: 202 * 203mmm frameworks/base/tests/AndroidTests 204adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 205adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 206 * 207 * {@hide} 208 */ 209public class PackageManagerService extends IPackageManager.Stub { 210 static final String TAG = "PackageManager"; 211 static final boolean DEBUG_SETTINGS = false; 212 static final boolean DEBUG_PREFERRED = false; 213 static final boolean DEBUG_UPGRADE = false; 214 private static final boolean DEBUG_INSTALL = false; 215 private static final boolean DEBUG_REMOVE = false; 216 private static final boolean DEBUG_BROADCASTS = false; 217 private static final boolean DEBUG_SHOW_INFO = false; 218 private static final boolean DEBUG_PACKAGE_INFO = false; 219 private static final boolean DEBUG_INTENT_MATCHING = false; 220 private static final boolean DEBUG_PACKAGE_SCANNING = false; 221 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 222 private static final boolean DEBUG_VERIFY = false; 223 private static final boolean DEBUG_DEXOPT = false; 224 225 private static final int RADIO_UID = Process.PHONE_UID; 226 private static final int LOG_UID = Process.LOG_UID; 227 private static final int NFC_UID = Process.NFC_UID; 228 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 229 private static final int SHELL_UID = Process.SHELL_UID; 230 231 // Cap the size of permission trees that 3rd party apps can define 232 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 233 234 private static final int REMOVE_EVENTS = 235 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 236 private static final int ADD_EVENTS = 237 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 238 239 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 240 // Suffix used during package installation when copying/moving 241 // package apks to install directory. 242 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 243 244 static final int SCAN_MONITOR = 1<<0; 245 static final int SCAN_NO_DEX = 1<<1; 246 static final int SCAN_FORCE_DEX = 1<<2; 247 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 248 static final int SCAN_NEW_INSTALL = 1<<4; 249 static final int SCAN_NO_PATHS = 1<<5; 250 static final int SCAN_UPDATE_TIME = 1<<6; 251 static final int SCAN_DEFER_DEX = 1<<7; 252 static final int SCAN_BOOTING = 1<<8; 253 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 254 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 255 256 static final int REMOVE_CHATTY = 1<<16; 257 258 /** 259 * Timeout (in milliseconds) after which the watchdog should declare that 260 * our handler thread is wedged. The usual default for such things is one 261 * minute but we sometimes do very lengthy I/O operations on this thread, 262 * such as installing multi-gigabyte applications, so ours needs to be longer. 263 */ 264 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 265 266 /** 267 * Whether verification is enabled by default. 268 */ 269 private static final boolean DEFAULT_VERIFY_ENABLE = true; 270 271 /** 272 * The default maximum time to wait for the verification agent to return in 273 * milliseconds. 274 */ 275 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 276 277 /** 278 * The default response for package verification timeout. 279 * 280 * This can be either PackageManager.VERIFICATION_ALLOW or 281 * PackageManager.VERIFICATION_REJECT. 282 */ 283 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 284 285 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 286 287 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 288 DEFAULT_CONTAINER_PACKAGE, 289 "com.android.defcontainer.DefaultContainerService"); 290 291 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 292 293 private static final String LIB_DIR_NAME = "lib"; 294 private static final String LIB64_DIR_NAME = "lib64"; 295 296 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 297 298 static final String mTempContainerPrefix = "smdl2tmp"; 299 300 private static String sPreferredInstructionSet; 301 302 final ServiceThread mHandlerThread; 303 304 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 305 private static final String IDMAP_SUFFIX = "@idmap"; 306 307 final PackageHandler mHandler; 308 309 final int mSdkVersion = Build.VERSION.SDK_INT; 310 311 final Context mContext; 312 final boolean mFactoryTest; 313 final boolean mOnlyCore; 314 final DisplayMetrics mMetrics; 315 final int mDefParseFlags; 316 final String[] mSeparateProcesses; 317 318 // This is where all application persistent data goes. 319 final File mAppDataDir; 320 321 // This is where all application persistent data goes for secondary users. 322 final File mUserAppDataDir; 323 324 /** The location for ASEC container files on internal storage. */ 325 final String mAsecInternalPath; 326 327 // This is the object monitoring the framework dir. 328 final FileObserver mFrameworkInstallObserver; 329 330 // This is the object monitoring the system app dir. 331 final FileObserver mSystemInstallObserver; 332 333 // This is the object monitoring the privileged system app dir. 334 final FileObserver mPrivilegedInstallObserver; 335 336 // This is the object monitoring the vendor app dir. 337 final FileObserver mVendorInstallObserver; 338 339 // This is the object monitoring the vendor overlay package dir. 340 final FileObserver mVendorOverlayInstallObserver; 341 342 // This is the object monitoring the OEM app dir. 343 final FileObserver mOemInstallObserver; 344 345 // This is the object monitoring mAppInstallDir. 346 final FileObserver mAppInstallObserver; 347 348 // This is the object monitoring mDrmAppPrivateInstallDir. 349 final FileObserver mDrmAppInstallObserver; 350 351 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 352 // LOCK HELD. Can be called with mInstallLock held. 353 final Installer mInstaller; 354 355 /** Directory where installed third-party apps stored */ 356 final File mAppInstallDir; 357 358 /** 359 * Directory to which applications installed internally have native 360 * libraries copied. 361 */ 362 private File mAppLibInstallDir; 363 364 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 365 // apps. 366 final File mDrmAppPrivateInstallDir; 367 368 /** Directory where third-party apps are staged before install */ 369 final File mAppStagingDir; 370 371 // ---------------------------------------------------------------- 372 373 // Lock for state used when installing and doing other long running 374 // operations. Methods that must be called with this lock held have 375 // the suffix "LI". 376 final Object mInstallLock = new Object(); 377 378 // These are the directories in the 3rd party applications installed dir 379 // that we have currently loaded packages from. Keys are the application's 380 // installed zip file (absolute codePath), and values are Package. 381 final HashMap<String, PackageParser.Package> mAppDirs = 382 new HashMap<String, PackageParser.Package>(); 383 384 // Information for the parser to write more useful error messages. 385 int mLastScanError; 386 387 // ---------------------------------------------------------------- 388 389 // Keys are String (package name), values are Package. This also serves 390 // as the lock for the global state. Methods that must be called with 391 // this lock held have the prefix "LP". 392 final HashMap<String, PackageParser.Package> mPackages = 393 new HashMap<String, PackageParser.Package>(); 394 395 // Tracks available target package names -> overlay package paths. 396 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 397 new HashMap<String, HashMap<String, PackageParser.Package>>(); 398 399 final Settings mSettings; 400 boolean mRestoredSettings; 401 402 // System configuration read by SystemConfig. 403 final int[] mGlobalGids; 404 final SparseArray<HashSet<String>> mSystemPermissions; 405 final HashMap<String, FeatureInfo> mAvailableFeatures; 406 407 // If mac_permissions.xml was found for seinfo labeling. 408 boolean mFoundPolicyFile; 409 410 // If a recursive restorecon of /data/data/<pkg> is needed. 411 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 412 413 public static final class SharedLibraryEntry { 414 public final String path; 415 public final String apk; 416 417 SharedLibraryEntry(String _path, String _apk) { 418 path = _path; 419 apk = _apk; 420 } 421 } 422 423 // Currently known shared libraries. 424 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 425 new HashMap<String, SharedLibraryEntry>(); 426 427 // All available activities, for your resolving pleasure. 428 final ActivityIntentResolver mActivities = 429 new ActivityIntentResolver(); 430 431 // All available receivers, for your resolving pleasure. 432 final ActivityIntentResolver mReceivers = 433 new ActivityIntentResolver(); 434 435 // All available services, for your resolving pleasure. 436 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 437 438 // All available providers, for your resolving pleasure. 439 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 440 441 // Mapping from provider base names (first directory in content URI codePath) 442 // to the provider information. 443 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 444 new HashMap<String, PackageParser.Provider>(); 445 446 // Mapping from instrumentation class names to info about them. 447 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 448 new HashMap<ComponentName, PackageParser.Instrumentation>(); 449 450 // Mapping from permission names to info about them. 451 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 452 new HashMap<String, PackageParser.PermissionGroup>(); 453 454 // Packages whose data we have transfered into another package, thus 455 // should no longer exist. 456 final HashSet<String> mTransferedPackages = new HashSet<String>(); 457 458 // Broadcast actions that are only available to the system. 459 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 460 461 /** List of packages waiting for verification. */ 462 final SparseArray<PackageVerificationState> mPendingVerification 463 = new SparseArray<PackageVerificationState>(); 464 465 final PackageInstallerService mInstallerService; 466 467 HashSet<PackageParser.Package> mDeferredDexOpt = null; 468 469 // Cache of users who need badging. 470 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 471 472 /** Token for keys in mPendingVerification. */ 473 private int mPendingVerificationToken = 0; 474 475 boolean mSystemReady; 476 boolean mSafeMode; 477 boolean mHasSystemUidErrors; 478 479 ApplicationInfo mAndroidApplication; 480 final ActivityInfo mResolveActivity = new ActivityInfo(); 481 final ResolveInfo mResolveInfo = new ResolveInfo(); 482 ComponentName mResolveComponentName; 483 PackageParser.Package mPlatformPackage; 484 ComponentName mCustomResolverComponentName; 485 486 boolean mResolverReplaced = false; 487 488 // Set of pending broadcasts for aggregating enable/disable of components. 489 static class PendingPackageBroadcasts { 490 // for each user id, a map of <package name -> components within that package> 491 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 492 493 public PendingPackageBroadcasts() { 494 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 495 } 496 497 public ArrayList<String> get(int userId, String packageName) { 498 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 499 return packages.get(packageName); 500 } 501 502 public void put(int userId, String packageName, ArrayList<String> components) { 503 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 504 packages.put(packageName, components); 505 } 506 507 public void remove(int userId, String packageName) { 508 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 509 if (packages != null) { 510 packages.remove(packageName); 511 } 512 } 513 514 public void remove(int userId) { 515 mUidMap.remove(userId); 516 } 517 518 public int userIdCount() { 519 return mUidMap.size(); 520 } 521 522 public int userIdAt(int n) { 523 return mUidMap.keyAt(n); 524 } 525 526 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 527 return mUidMap.get(userId); 528 } 529 530 public int size() { 531 // total number of pending broadcast entries across all userIds 532 int num = 0; 533 for (int i = 0; i< mUidMap.size(); i++) { 534 num += mUidMap.valueAt(i).size(); 535 } 536 return num; 537 } 538 539 public void clear() { 540 mUidMap.clear(); 541 } 542 543 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 544 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 545 if (map == null) { 546 map = new HashMap<String, ArrayList<String>>(); 547 mUidMap.put(userId, map); 548 } 549 return map; 550 } 551 } 552 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 553 554 // Service Connection to remote media container service to copy 555 // package uri's from external media onto secure containers 556 // or internal storage. 557 private IMediaContainerService mContainerService = null; 558 559 static final int SEND_PENDING_BROADCAST = 1; 560 static final int MCS_BOUND = 3; 561 static final int END_COPY = 4; 562 static final int INIT_COPY = 5; 563 static final int MCS_UNBIND = 6; 564 static final int START_CLEANING_PACKAGE = 7; 565 static final int FIND_INSTALL_LOC = 8; 566 static final int POST_INSTALL = 9; 567 static final int MCS_RECONNECT = 10; 568 static final int MCS_GIVE_UP = 11; 569 static final int UPDATED_MEDIA_STATUS = 12; 570 static final int WRITE_SETTINGS = 13; 571 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 572 static final int PACKAGE_VERIFIED = 15; 573 static final int CHECK_PENDING_VERIFICATION = 16; 574 575 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 576 577 // Delay time in millisecs 578 static final int BROADCAST_DELAY = 10 * 1000; 579 580 static UserManagerService sUserManager; 581 582 // Stores a list of users whose package restrictions file needs to be updated 583 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 584 585 final private DefaultContainerConnection mDefContainerConn = 586 new DefaultContainerConnection(); 587 class DefaultContainerConnection implements ServiceConnection { 588 public void onServiceConnected(ComponentName name, IBinder service) { 589 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 590 IMediaContainerService imcs = 591 IMediaContainerService.Stub.asInterface(service); 592 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 593 } 594 595 public void onServiceDisconnected(ComponentName name) { 596 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 597 } 598 }; 599 600 // Recordkeeping of restore-after-install operations that are currently in flight 601 // between the Package Manager and the Backup Manager 602 class PostInstallData { 603 public InstallArgs args; 604 public PackageInstalledInfo res; 605 606 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 607 args = _a; 608 res = _r; 609 } 610 }; 611 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 612 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 613 614 private final String mRequiredVerifierPackage; 615 616 private final PackageUsage mPackageUsage = new PackageUsage(); 617 618 private class PackageUsage { 619 private static final int WRITE_INTERVAL 620 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 621 622 private final Object mFileLock = new Object(); 623 private final AtomicLong mLastWritten = new AtomicLong(0); 624 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 625 626 private boolean mIsHistoricalPackageUsageAvailable = true; 627 628 boolean isHistoricalPackageUsageAvailable() { 629 return mIsHistoricalPackageUsageAvailable; 630 } 631 632 void write(boolean force) { 633 if (force) { 634 writeInternal(); 635 return; 636 } 637 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 638 && !DEBUG_DEXOPT) { 639 return; 640 } 641 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 642 new Thread("PackageUsage_DiskWriter") { 643 @Override 644 public void run() { 645 try { 646 writeInternal(); 647 } finally { 648 mBackgroundWriteRunning.set(false); 649 } 650 } 651 }.start(); 652 } 653 } 654 655 private void writeInternal() { 656 synchronized (mPackages) { 657 synchronized (mFileLock) { 658 AtomicFile file = getFile(); 659 FileOutputStream f = null; 660 try { 661 f = file.startWrite(); 662 BufferedOutputStream out = new BufferedOutputStream(f); 663 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 664 StringBuilder sb = new StringBuilder(); 665 for (PackageParser.Package pkg : mPackages.values()) { 666 if (pkg.mLastPackageUsageTimeInMills == 0) { 667 continue; 668 } 669 sb.setLength(0); 670 sb.append(pkg.packageName); 671 sb.append(' '); 672 sb.append((long)pkg.mLastPackageUsageTimeInMills); 673 sb.append('\n'); 674 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 675 } 676 out.flush(); 677 file.finishWrite(f); 678 } catch (IOException e) { 679 if (f != null) { 680 file.failWrite(f); 681 } 682 Log.e(TAG, "Failed to write package usage times", e); 683 } 684 } 685 } 686 mLastWritten.set(SystemClock.elapsedRealtime()); 687 } 688 689 void readLP() { 690 synchronized (mFileLock) { 691 AtomicFile file = getFile(); 692 BufferedInputStream in = null; 693 try { 694 in = new BufferedInputStream(file.openRead()); 695 StringBuffer sb = new StringBuffer(); 696 while (true) { 697 String packageName = readToken(in, sb, ' '); 698 if (packageName == null) { 699 break; 700 } 701 String timeInMillisString = readToken(in, sb, '\n'); 702 if (timeInMillisString == null) { 703 throw new IOException("Failed to find last usage time for package " 704 + packageName); 705 } 706 PackageParser.Package pkg = mPackages.get(packageName); 707 if (pkg == null) { 708 continue; 709 } 710 long timeInMillis; 711 try { 712 timeInMillis = Long.parseLong(timeInMillisString.toString()); 713 } catch (NumberFormatException e) { 714 throw new IOException("Failed to parse " + timeInMillisString 715 + " as a long.", e); 716 } 717 pkg.mLastPackageUsageTimeInMills = timeInMillis; 718 } 719 } catch (FileNotFoundException expected) { 720 mIsHistoricalPackageUsageAvailable = false; 721 } catch (IOException e) { 722 Log.w(TAG, "Failed to read package usage times", e); 723 } finally { 724 IoUtils.closeQuietly(in); 725 } 726 } 727 mLastWritten.set(SystemClock.elapsedRealtime()); 728 } 729 730 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 731 throws IOException { 732 sb.setLength(0); 733 while (true) { 734 int ch = in.read(); 735 if (ch == -1) { 736 if (sb.length() == 0) { 737 return null; 738 } 739 throw new IOException("Unexpected EOF"); 740 } 741 if (ch == endOfToken) { 742 return sb.toString(); 743 } 744 sb.append((char)ch); 745 } 746 } 747 748 private AtomicFile getFile() { 749 File dataDir = Environment.getDataDirectory(); 750 File systemDir = new File(dataDir, "system"); 751 File fname = new File(systemDir, "package-usage.list"); 752 return new AtomicFile(fname); 753 } 754 } 755 756 class PackageHandler extends Handler { 757 private boolean mBound = false; 758 final ArrayList<HandlerParams> mPendingInstalls = 759 new ArrayList<HandlerParams>(); 760 761 private boolean connectToService() { 762 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 763 " DefaultContainerService"); 764 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 765 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 766 if (mContext.bindServiceAsUser(service, mDefContainerConn, 767 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 768 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 769 mBound = true; 770 return true; 771 } 772 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 773 return false; 774 } 775 776 private void disconnectService() { 777 mContainerService = null; 778 mBound = false; 779 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 780 mContext.unbindService(mDefContainerConn); 781 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 782 } 783 784 PackageHandler(Looper looper) { 785 super(looper); 786 } 787 788 public void handleMessage(Message msg) { 789 try { 790 doHandleMessage(msg); 791 } finally { 792 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 793 } 794 } 795 796 void doHandleMessage(Message msg) { 797 switch (msg.what) { 798 case INIT_COPY: { 799 HandlerParams params = (HandlerParams) msg.obj; 800 int idx = mPendingInstalls.size(); 801 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 802 // If a bind was already initiated we dont really 803 // need to do anything. The pending install 804 // will be processed later on. 805 if (!mBound) { 806 // If this is the only one pending we might 807 // have to bind to the service again. 808 if (!connectToService()) { 809 Slog.e(TAG, "Failed to bind to media container service"); 810 params.serviceError(); 811 return; 812 } else { 813 // Once we bind to the service, the first 814 // pending request will be processed. 815 mPendingInstalls.add(idx, params); 816 } 817 } else { 818 mPendingInstalls.add(idx, params); 819 // Already bound to the service. Just make 820 // sure we trigger off processing the first request. 821 if (idx == 0) { 822 mHandler.sendEmptyMessage(MCS_BOUND); 823 } 824 } 825 break; 826 } 827 case MCS_BOUND: { 828 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 829 if (msg.obj != null) { 830 mContainerService = (IMediaContainerService) msg.obj; 831 } 832 if (mContainerService == null) { 833 // Something seriously wrong. Bail out 834 Slog.e(TAG, "Cannot bind to media container service"); 835 for (HandlerParams params : mPendingInstalls) { 836 // Indicate service bind error 837 params.serviceError(); 838 } 839 mPendingInstalls.clear(); 840 } else if (mPendingInstalls.size() > 0) { 841 HandlerParams params = mPendingInstalls.get(0); 842 if (params != null) { 843 if (params.startCopy()) { 844 // We are done... look for more work or to 845 // go idle. 846 if (DEBUG_SD_INSTALL) Log.i(TAG, 847 "Checking for more work or unbind..."); 848 // Delete pending install 849 if (mPendingInstalls.size() > 0) { 850 mPendingInstalls.remove(0); 851 } 852 if (mPendingInstalls.size() == 0) { 853 if (mBound) { 854 if (DEBUG_SD_INSTALL) Log.i(TAG, 855 "Posting delayed MCS_UNBIND"); 856 removeMessages(MCS_UNBIND); 857 Message ubmsg = obtainMessage(MCS_UNBIND); 858 // Unbind after a little delay, to avoid 859 // continual thrashing. 860 sendMessageDelayed(ubmsg, 10000); 861 } 862 } else { 863 // There are more pending requests in queue. 864 // Just post MCS_BOUND message to trigger processing 865 // of next pending install. 866 if (DEBUG_SD_INSTALL) Log.i(TAG, 867 "Posting MCS_BOUND for next work"); 868 mHandler.sendEmptyMessage(MCS_BOUND); 869 } 870 } 871 } 872 } else { 873 // Should never happen ideally. 874 Slog.w(TAG, "Empty queue"); 875 } 876 break; 877 } 878 case MCS_RECONNECT: { 879 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 880 if (mPendingInstalls.size() > 0) { 881 if (mBound) { 882 disconnectService(); 883 } 884 if (!connectToService()) { 885 Slog.e(TAG, "Failed to bind to media container service"); 886 for (HandlerParams params : mPendingInstalls) { 887 // Indicate service bind error 888 params.serviceError(); 889 } 890 mPendingInstalls.clear(); 891 } 892 } 893 break; 894 } 895 case MCS_UNBIND: { 896 // If there is no actual work left, then time to unbind. 897 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 898 899 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 900 if (mBound) { 901 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 902 903 disconnectService(); 904 } 905 } else if (mPendingInstalls.size() > 0) { 906 // There are more pending requests in queue. 907 // Just post MCS_BOUND message to trigger processing 908 // of next pending install. 909 mHandler.sendEmptyMessage(MCS_BOUND); 910 } 911 912 break; 913 } 914 case MCS_GIVE_UP: { 915 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 916 mPendingInstalls.remove(0); 917 break; 918 } 919 case SEND_PENDING_BROADCAST: { 920 String packages[]; 921 ArrayList<String> components[]; 922 int size = 0; 923 int uids[]; 924 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 925 synchronized (mPackages) { 926 if (mPendingBroadcasts == null) { 927 return; 928 } 929 size = mPendingBroadcasts.size(); 930 if (size <= 0) { 931 // Nothing to be done. Just return 932 return; 933 } 934 packages = new String[size]; 935 components = new ArrayList[size]; 936 uids = new int[size]; 937 int i = 0; // filling out the above arrays 938 939 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 940 int packageUserId = mPendingBroadcasts.userIdAt(n); 941 Iterator<Map.Entry<String, ArrayList<String>>> it 942 = mPendingBroadcasts.packagesForUserId(packageUserId) 943 .entrySet().iterator(); 944 while (it.hasNext() && i < size) { 945 Map.Entry<String, ArrayList<String>> ent = it.next(); 946 packages[i] = ent.getKey(); 947 components[i] = ent.getValue(); 948 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 949 uids[i] = (ps != null) 950 ? UserHandle.getUid(packageUserId, ps.appId) 951 : -1; 952 i++; 953 } 954 } 955 size = i; 956 mPendingBroadcasts.clear(); 957 } 958 // Send broadcasts 959 for (int i = 0; i < size; i++) { 960 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 961 } 962 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 963 break; 964 } 965 case START_CLEANING_PACKAGE: { 966 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 967 final String packageName = (String)msg.obj; 968 final int userId = msg.arg1; 969 final boolean andCode = msg.arg2 != 0; 970 synchronized (mPackages) { 971 if (userId == UserHandle.USER_ALL) { 972 int[] users = sUserManager.getUserIds(); 973 for (int user : users) { 974 mSettings.addPackageToCleanLPw( 975 new PackageCleanItem(user, packageName, andCode)); 976 } 977 } else { 978 mSettings.addPackageToCleanLPw( 979 new PackageCleanItem(userId, packageName, andCode)); 980 } 981 } 982 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 983 startCleaningPackages(); 984 } break; 985 case POST_INSTALL: { 986 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 987 PostInstallData data = mRunningInstalls.get(msg.arg1); 988 mRunningInstalls.delete(msg.arg1); 989 boolean deleteOld = false; 990 991 if (data != null) { 992 InstallArgs args = data.args; 993 PackageInstalledInfo res = data.res; 994 995 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 996 res.removedInfo.sendBroadcast(false, true, false); 997 Bundle extras = new Bundle(1); 998 extras.putInt(Intent.EXTRA_UID, res.uid); 999 // Determine the set of users who are adding this 1000 // package for the first time vs. those who are seeing 1001 // an update. 1002 int[] firstUsers; 1003 int[] updateUsers = new int[0]; 1004 if (res.origUsers == null || res.origUsers.length == 0) { 1005 firstUsers = res.newUsers; 1006 } else { 1007 firstUsers = new int[0]; 1008 for (int i=0; i<res.newUsers.length; i++) { 1009 int user = res.newUsers[i]; 1010 boolean isNew = true; 1011 for (int j=0; j<res.origUsers.length; j++) { 1012 if (res.origUsers[j] == user) { 1013 isNew = false; 1014 break; 1015 } 1016 } 1017 if (isNew) { 1018 int[] newFirst = new int[firstUsers.length+1]; 1019 System.arraycopy(firstUsers, 0, newFirst, 0, 1020 firstUsers.length); 1021 newFirst[firstUsers.length] = user; 1022 firstUsers = newFirst; 1023 } else { 1024 int[] newUpdate = new int[updateUsers.length+1]; 1025 System.arraycopy(updateUsers, 0, newUpdate, 0, 1026 updateUsers.length); 1027 newUpdate[updateUsers.length] = user; 1028 updateUsers = newUpdate; 1029 } 1030 } 1031 } 1032 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1033 res.pkg.applicationInfo.packageName, 1034 extras, null, null, firstUsers); 1035 final boolean update = res.removedInfo.removedPackage != null; 1036 if (update) { 1037 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1038 } 1039 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1040 res.pkg.applicationInfo.packageName, 1041 extras, null, null, updateUsers); 1042 if (update) { 1043 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1044 res.pkg.applicationInfo.packageName, 1045 extras, null, null, updateUsers); 1046 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1047 null, null, 1048 res.pkg.applicationInfo.packageName, null, updateUsers); 1049 1050 // treat asec-hosted packages like removable media on upgrade 1051 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1052 if (DEBUG_INSTALL) { 1053 Slog.i(TAG, "upgrading pkg " + res.pkg 1054 + " is ASEC-hosted -> AVAILABLE"); 1055 } 1056 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1057 ArrayList<String> pkgList = new ArrayList<String>(1); 1058 pkgList.add(res.pkg.applicationInfo.packageName); 1059 sendResourcesChangedBroadcast(true, true, 1060 pkgList,uidArray, null); 1061 } 1062 } 1063 if (res.removedInfo.args != null) { 1064 // Remove the replaced package's older resources safely now 1065 deleteOld = true; 1066 } 1067 1068 // Log current value of "unknown sources" setting 1069 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1070 getUnknownSourcesSettings()); 1071 } 1072 // Force a gc to clear up things 1073 Runtime.getRuntime().gc(); 1074 // We delete after a gc for applications on sdcard. 1075 if (deleteOld) { 1076 synchronized (mInstallLock) { 1077 res.removedInfo.args.doPostDeleteLI(true); 1078 } 1079 } 1080 if (args.observer != null) { 1081 try { 1082 args.observer.packageInstalled(res.name, res.returnCode); 1083 } catch (RemoteException e) { 1084 Slog.i(TAG, "Observer no longer exists."); 1085 } 1086 } 1087 if (args.observer2 != null) { 1088 try { 1089 Bundle extras = extrasForInstallResult(res); 1090 args.observer2.packageInstalled(res.name, extras, res.returnCode); 1091 } catch (RemoteException e) { 1092 Slog.i(TAG, "Observer no longer exists."); 1093 } 1094 } 1095 } else { 1096 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1097 } 1098 } break; 1099 case UPDATED_MEDIA_STATUS: { 1100 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1101 boolean reportStatus = msg.arg1 == 1; 1102 boolean doGc = msg.arg2 == 1; 1103 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1104 if (doGc) { 1105 // Force a gc to clear up stale containers. 1106 Runtime.getRuntime().gc(); 1107 } 1108 if (msg.obj != null) { 1109 @SuppressWarnings("unchecked") 1110 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1111 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1112 // Unload containers 1113 unloadAllContainers(args); 1114 } 1115 if (reportStatus) { 1116 try { 1117 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1118 PackageHelper.getMountService().finishMediaUpdate(); 1119 } catch (RemoteException e) { 1120 Log.e(TAG, "MountService not running?"); 1121 } 1122 } 1123 } break; 1124 case WRITE_SETTINGS: { 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1126 synchronized (mPackages) { 1127 removeMessages(WRITE_SETTINGS); 1128 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1129 mSettings.writeLPr(); 1130 mDirtyUsers.clear(); 1131 } 1132 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1133 } break; 1134 case WRITE_PACKAGE_RESTRICTIONS: { 1135 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1136 synchronized (mPackages) { 1137 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1138 for (int userId : mDirtyUsers) { 1139 mSettings.writePackageRestrictionsLPr(userId); 1140 } 1141 mDirtyUsers.clear(); 1142 } 1143 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1144 } break; 1145 case CHECK_PENDING_VERIFICATION: { 1146 final int verificationId = msg.arg1; 1147 final PackageVerificationState state = mPendingVerification.get(verificationId); 1148 1149 if ((state != null) && !state.timeoutExtended()) { 1150 final InstallArgs args = state.getInstallArgs(); 1151 final Uri fromUri = Uri.fromFile(args.fromFile); 1152 1153 Slog.i(TAG, "Verification timed out for " + fromUri); 1154 mPendingVerification.remove(verificationId); 1155 1156 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1157 1158 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1159 Slog.i(TAG, "Continuing with installation of " + fromUri); 1160 state.setVerifierResponse(Binder.getCallingUid(), 1161 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1162 broadcastPackageVerified(verificationId, fromUri, 1163 PackageManager.VERIFICATION_ALLOW, 1164 state.getInstallArgs().getUser()); 1165 try { 1166 ret = args.copyApk(mContainerService, true); 1167 } catch (RemoteException e) { 1168 Slog.e(TAG, "Could not contact the ContainerService"); 1169 } 1170 } else { 1171 broadcastPackageVerified(verificationId, fromUri, 1172 PackageManager.VERIFICATION_REJECT, 1173 state.getInstallArgs().getUser()); 1174 } 1175 1176 processPendingInstall(args, ret); 1177 mHandler.sendEmptyMessage(MCS_UNBIND); 1178 } 1179 break; 1180 } 1181 case PACKAGE_VERIFIED: { 1182 final int verificationId = msg.arg1; 1183 1184 final PackageVerificationState state = mPendingVerification.get(verificationId); 1185 if (state == null) { 1186 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1187 break; 1188 } 1189 1190 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1191 1192 state.setVerifierResponse(response.callerUid, response.code); 1193 1194 if (state.isVerificationComplete()) { 1195 mPendingVerification.remove(verificationId); 1196 1197 final InstallArgs args = state.getInstallArgs(); 1198 final Uri fromUri = Uri.fromFile(args.fromFile); 1199 1200 int ret; 1201 if (state.isInstallAllowed()) { 1202 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1203 broadcastPackageVerified(verificationId, fromUri, 1204 response.code, state.getInstallArgs().getUser()); 1205 try { 1206 ret = args.copyApk(mContainerService, true); 1207 } catch (RemoteException e) { 1208 Slog.e(TAG, "Could not contact the ContainerService"); 1209 } 1210 } else { 1211 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1212 } 1213 1214 processPendingInstall(args, ret); 1215 1216 mHandler.sendEmptyMessage(MCS_UNBIND); 1217 } 1218 1219 break; 1220 } 1221 } 1222 } 1223 } 1224 1225 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1226 Bundle extras = null; 1227 switch (res.returnCode) { 1228 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1229 extras = new Bundle(); 1230 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1231 res.origPermission); 1232 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1233 res.origPackage); 1234 break; 1235 } 1236 } 1237 return extras; 1238 } 1239 1240 void scheduleWriteSettingsLocked() { 1241 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1242 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1243 } 1244 } 1245 1246 void scheduleWritePackageRestrictionsLocked(int userId) { 1247 if (!sUserManager.exists(userId)) return; 1248 mDirtyUsers.add(userId); 1249 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1250 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1251 } 1252 } 1253 1254 public static final PackageManagerService main(Context context, Installer installer, 1255 boolean factoryTest, boolean onlyCore) { 1256 PackageManagerService m = new PackageManagerService(context, installer, 1257 factoryTest, onlyCore); 1258 ServiceManager.addService("package", m); 1259 return m; 1260 } 1261 1262 static String[] splitString(String str, char sep) { 1263 int count = 1; 1264 int i = 0; 1265 while ((i=str.indexOf(sep, i)) >= 0) { 1266 count++; 1267 i++; 1268 } 1269 1270 String[] res = new String[count]; 1271 i=0; 1272 count = 0; 1273 int lastI=0; 1274 while ((i=str.indexOf(sep, i)) >= 0) { 1275 res[count] = str.substring(lastI, i); 1276 count++; 1277 i++; 1278 lastI = i; 1279 } 1280 res[count] = str.substring(lastI, str.length()); 1281 return res; 1282 } 1283 1284 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1285 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1286 Context.DISPLAY_SERVICE); 1287 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1288 } 1289 1290 public PackageManagerService(Context context, Installer installer, 1291 boolean factoryTest, boolean onlyCore) { 1292 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1293 SystemClock.uptimeMillis()); 1294 1295 if (mSdkVersion <= 0) { 1296 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1297 } 1298 1299 mContext = context; 1300 mFactoryTest = factoryTest; 1301 mOnlyCore = onlyCore; 1302 mMetrics = new DisplayMetrics(); 1303 mSettings = new Settings(context); 1304 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1305 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1306 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1307 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1308 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1309 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1310 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1311 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1312 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1313 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1314 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1315 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1316 1317 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1318 if (separateProcesses != null && separateProcesses.length() > 0) { 1319 if ("*".equals(separateProcesses)) { 1320 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1321 mSeparateProcesses = null; 1322 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1323 } else { 1324 mDefParseFlags = 0; 1325 mSeparateProcesses = separateProcesses.split(","); 1326 Slog.w(TAG, "Running with debug.separate_processes: " 1327 + separateProcesses); 1328 } 1329 } else { 1330 mDefParseFlags = 0; 1331 mSeparateProcesses = null; 1332 } 1333 1334 mInstaller = installer; 1335 1336 getDefaultDisplayMetrics(context, mMetrics); 1337 1338 SystemConfig systemConfig = SystemConfig.getInstance(); 1339 mGlobalGids = systemConfig.getGlobalGids(); 1340 mSystemPermissions = systemConfig.getSystemPermissions(); 1341 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1342 1343 synchronized (mInstallLock) { 1344 // writer 1345 synchronized (mPackages) { 1346 mHandlerThread = new ServiceThread(TAG, 1347 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1348 mHandlerThread.start(); 1349 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1350 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1351 1352 File dataDir = Environment.getDataDirectory(); 1353 mAppDataDir = new File(dataDir, "data"); 1354 mAppInstallDir = new File(dataDir, "app"); 1355 mAppLibInstallDir = new File(dataDir, "app-lib"); 1356 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1357 mUserAppDataDir = new File(dataDir, "user"); 1358 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1359 mAppStagingDir = new File(dataDir, "app-staging"); 1360 1361 sUserManager = new UserManagerService(context, this, 1362 mInstallLock, mPackages); 1363 1364 // Propagate permission configuration in to package manager. 1365 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1366 = systemConfig.getPermissions(); 1367 for (int i=0; i<permConfig.size(); i++) { 1368 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1369 BasePermission bp = mSettings.mPermissions.get(perm.name); 1370 if (bp == null) { 1371 bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN); 1372 mSettings.mPermissions.put(perm.name, bp); 1373 } 1374 if (perm.gids != null) { 1375 bp.gids = appendInts(bp.gids, perm.gids); 1376 } 1377 } 1378 1379 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1380 for (int i=0; i<libConfig.size(); i++) { 1381 mSharedLibraries.put(libConfig.keyAt(i), 1382 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1383 } 1384 1385 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1386 1387 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1388 mSdkVersion, mOnlyCore); 1389 1390 String customResolverActivity = Resources.getSystem().getString( 1391 R.string.config_customResolverActivity); 1392 if (TextUtils.isEmpty(customResolverActivity)) { 1393 customResolverActivity = null; 1394 } else { 1395 mCustomResolverComponentName = ComponentName.unflattenFromString( 1396 customResolverActivity); 1397 } 1398 1399 long startTime = SystemClock.uptimeMillis(); 1400 1401 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1402 startTime); 1403 1404 // Set flag to monitor and not change apk file paths when 1405 // scanning install directories. 1406 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1407 1408 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1409 1410 /** 1411 * Add everything in the in the boot class path to the 1412 * list of process files because dexopt will have been run 1413 * if necessary during zygote startup. 1414 */ 1415 String bootClassPath = System.getProperty("java.boot.class.path"); 1416 if (bootClassPath != null) { 1417 String[] paths = splitString(bootClassPath, ':'); 1418 for (int i=0; i<paths.length; i++) { 1419 alreadyDexOpted.add(paths[i]); 1420 } 1421 } else { 1422 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1423 } 1424 1425 boolean didDexOptLibraryOrTool = false; 1426 1427 final List<String> instructionSets = getAllInstructionSets(); 1428 1429 /** 1430 * Ensure all external libraries have had dexopt run on them. 1431 */ 1432 if (mSharedLibraries.size() > 0) { 1433 // NOTE: For now, we're compiling these system "shared libraries" 1434 // (and framework jars) into all available architectures. It's possible 1435 // to compile them only when we come across an app that uses them (there's 1436 // already logic for that in scanPackageLI) but that adds some complexity. 1437 for (String instructionSet : instructionSets) { 1438 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1439 final String lib = libEntry.path; 1440 if (lib == null) { 1441 continue; 1442 } 1443 1444 try { 1445 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1446 alreadyDexOpted.add(lib); 1447 1448 // The list of "shared libraries" we have at this point is 1449 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1450 didDexOptLibraryOrTool = true; 1451 } 1452 } catch (FileNotFoundException e) { 1453 Slog.w(TAG, "Library not found: " + lib); 1454 } catch (IOException e) { 1455 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1456 + e.getMessage()); 1457 } 1458 } 1459 } 1460 } 1461 1462 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1463 1464 // Gross hack for now: we know this file doesn't contain any 1465 // code, so don't dexopt it to avoid the resulting log spew. 1466 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1467 1468 // Gross hack for now: we know this file is only part of 1469 // the boot class path for art, so don't dexopt it to 1470 // avoid the resulting log spew. 1471 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1472 1473 /** 1474 * And there are a number of commands implemented in Java, which 1475 * we currently need to do the dexopt on so that they can be 1476 * run from a non-root shell. 1477 */ 1478 String[] frameworkFiles = frameworkDir.list(); 1479 if (frameworkFiles != null) { 1480 // TODO: We could compile these only for the most preferred ABI. We should 1481 // first double check that the dex files for these commands are not referenced 1482 // by other system apps. 1483 for (String instructionSet : instructionSets) { 1484 for (int i=0; i<frameworkFiles.length; i++) { 1485 File libPath = new File(frameworkDir, frameworkFiles[i]); 1486 String path = libPath.getPath(); 1487 // Skip the file if we already did it. 1488 if (alreadyDexOpted.contains(path)) { 1489 continue; 1490 } 1491 // Skip the file if it is not a type we want to dexopt. 1492 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1493 continue; 1494 } 1495 try { 1496 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1497 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1498 didDexOptLibraryOrTool = true; 1499 } 1500 } catch (FileNotFoundException e) { 1501 Slog.w(TAG, "Jar not found: " + path); 1502 } catch (IOException e) { 1503 Slog.w(TAG, "Exception reading jar: " + path, e); 1504 } 1505 } 1506 } 1507 } 1508 1509 if (didDexOptLibraryOrTool) { 1510 // If we dexopted a library or tool, then something on the system has 1511 // changed. Consider this significant, and wipe away all other 1512 // existing dexopt files to ensure we don't leave any dangling around. 1513 // 1514 // TODO: This should be revisited because it isn't as good an indicator 1515 // as it used to be. It used to include the boot classpath but at some point 1516 // DexFile.isDexOptNeeded started returning false for the boot 1517 // class path files in all cases. It is very possible in a 1518 // small maintenance release update that the library and tool 1519 // jars may be unchanged but APK could be removed resulting in 1520 // unused dalvik-cache files. 1521 for (String instructionSet : instructionSets) { 1522 mInstaller.pruneDexCache(instructionSet); 1523 } 1524 1525 // Additionally, delete all dex files from the root directory 1526 // since there shouldn't be any there anyway, unless we're upgrading 1527 // from an older OS version or a build that contained the "old" style 1528 // flat scheme. 1529 mInstaller.pruneDexCache("."); 1530 } 1531 1532 // Collect vendor overlay packages. 1533 // (Do this before scanning any apps.) 1534 // For security and version matching reason, only consider 1535 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1536 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1537 mVendorOverlayInstallObserver = new AppDirObserver( 1538 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1539 mVendorOverlayInstallObserver.startWatching(); 1540 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1541 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1542 1543 // Find base frameworks (resource packages without code). 1544 mFrameworkInstallObserver = new AppDirObserver( 1545 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1546 mFrameworkInstallObserver.startWatching(); 1547 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1548 | PackageParser.PARSE_IS_SYSTEM_DIR 1549 | PackageParser.PARSE_IS_PRIVILEGED, 1550 scanMode | SCAN_NO_DEX, 0); 1551 1552 // Collected privileged system packages. 1553 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1554 mPrivilegedInstallObserver = new AppDirObserver( 1555 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1556 mPrivilegedInstallObserver.startWatching(); 1557 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1558 | PackageParser.PARSE_IS_SYSTEM_DIR 1559 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1560 1561 // Collect ordinary system packages. 1562 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1563 mSystemInstallObserver = new AppDirObserver( 1564 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1565 mSystemInstallObserver.startWatching(); 1566 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1567 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1568 1569 // Collect all vendor packages. 1570 File vendorAppDir = new File("/vendor/app"); 1571 try { 1572 vendorAppDir = vendorAppDir.getCanonicalFile(); 1573 } catch (IOException e) { 1574 // failed to look up canonical path, continue with original one 1575 } 1576 mVendorInstallObserver = new AppDirObserver( 1577 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1578 mVendorInstallObserver.startWatching(); 1579 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1580 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1581 1582 // Collect all OEM packages. 1583 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1584 mOemInstallObserver = new AppDirObserver( 1585 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1586 mOemInstallObserver.startWatching(); 1587 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1588 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1589 1590 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1591 mInstaller.moveFiles(); 1592 1593 // Prune any system packages that no longer exist. 1594 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1595 if (!mOnlyCore) { 1596 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1597 while (psit.hasNext()) { 1598 PackageSetting ps = psit.next(); 1599 1600 /* 1601 * If this is not a system app, it can't be a 1602 * disable system app. 1603 */ 1604 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1605 continue; 1606 } 1607 1608 /* 1609 * If the package is scanned, it's not erased. 1610 */ 1611 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1612 if (scannedPkg != null) { 1613 /* 1614 * If the system app is both scanned and in the 1615 * disabled packages list, then it must have been 1616 * added via OTA. Remove it from the currently 1617 * scanned package so the previously user-installed 1618 * application can be scanned. 1619 */ 1620 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1621 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1622 + "; removing system app"); 1623 removePackageLI(ps, true); 1624 } 1625 1626 continue; 1627 } 1628 1629 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1630 psit.remove(); 1631 String msg = "System package " + ps.name 1632 + " no longer exists; wiping its data"; 1633 reportSettingsProblem(Log.WARN, msg); 1634 removeDataDirsLI(ps.name); 1635 } else { 1636 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1637 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1638 possiblyDeletedUpdatedSystemApps.add(ps.name); 1639 } 1640 } 1641 } 1642 } 1643 1644 //look for any incomplete package installations 1645 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1646 //clean up list 1647 for(int i = 0; i < deletePkgsList.size(); i++) { 1648 //clean up here 1649 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1650 } 1651 //delete tmp files 1652 deleteTempPackageFiles(); 1653 1654 // Remove any shared userIDs that have no associated packages 1655 mSettings.pruneSharedUsersLPw(); 1656 1657 if (!mOnlyCore) { 1658 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1659 SystemClock.uptimeMillis()); 1660 mAppInstallObserver = new AppDirObserver( 1661 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1662 mAppInstallObserver.startWatching(); 1663 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1664 1665 mDrmAppInstallObserver = new AppDirObserver( 1666 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1667 mDrmAppInstallObserver.startWatching(); 1668 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1669 scanMode, 0); 1670 1671 /** 1672 * Remove disable package settings for any updated system 1673 * apps that were removed via an OTA. If they're not a 1674 * previously-updated app, remove them completely. 1675 * Otherwise, just revoke their system-level permissions. 1676 */ 1677 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1678 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1679 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1680 1681 String msg; 1682 if (deletedPkg == null) { 1683 msg = "Updated system package " + deletedAppName 1684 + " no longer exists; wiping its data"; 1685 removeDataDirsLI(deletedAppName); 1686 } else { 1687 msg = "Updated system app + " + deletedAppName 1688 + " no longer present; removing system privileges for " 1689 + deletedAppName; 1690 1691 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1692 1693 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1694 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1695 } 1696 reportSettingsProblem(Log.WARN, msg); 1697 } 1698 } else { 1699 mAppInstallObserver = null; 1700 mDrmAppInstallObserver = null; 1701 } 1702 1703 // Now that we know all of the shared libraries, update all clients to have 1704 // the correct library paths. 1705 updateAllSharedLibrariesLPw(); 1706 1707 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1708 // NOTE: We ignore potential failures here during a system scan (like 1709 // the rest of the commands above) because there's precious little we 1710 // can do about it. A settings error is reported, though. 1711 adjustCpuAbisForSharedUserLPw(setting.packages, null, 1712 false /* force dexopt */, false /* defer dexopt */); 1713 } 1714 1715 // Now that we know all the packages we are keeping, 1716 // read and update their last usage times. 1717 mPackageUsage.readLP(); 1718 1719 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1720 SystemClock.uptimeMillis()); 1721 Slog.i(TAG, "Time to scan packages: " 1722 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1723 + " seconds"); 1724 1725 // If the platform SDK has changed since the last time we booted, 1726 // we need to re-grant app permission to catch any new ones that 1727 // appear. This is really a hack, and means that apps can in some 1728 // cases get permissions that the user didn't initially explicitly 1729 // allow... it would be nice to have some better way to handle 1730 // this situation. 1731 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1732 != mSdkVersion; 1733 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1734 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1735 + "; regranting permissions for internal storage"); 1736 mSettings.mInternalSdkPlatform = mSdkVersion; 1737 1738 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1739 | (regrantPermissions 1740 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1741 : 0)); 1742 1743 // If this is the first boot, and it is a normal boot, then 1744 // we need to initialize the default preferred apps. 1745 if (!mRestoredSettings && !onlyCore) { 1746 mSettings.readDefaultPreferredAppsLPw(this, 0); 1747 } 1748 1749 // All the changes are done during package scanning. 1750 mSettings.updateInternalDatabaseVersion(); 1751 1752 // can downgrade to reader 1753 mSettings.writeLPr(); 1754 1755 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1756 SystemClock.uptimeMillis()); 1757 1758 1759 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1760 } // synchronized (mPackages) 1761 } // synchronized (mInstallLock) 1762 1763 mInstallerService = new PackageInstallerService(context, this, mAppStagingDir); 1764 1765 // Now after opening every single application zip, make sure they 1766 // are all flushed. Not really needed, but keeps things nice and 1767 // tidy. 1768 Runtime.getRuntime().gc(); 1769 } 1770 1771 @Override 1772 public boolean isFirstBoot() { 1773 return !mRestoredSettings; 1774 } 1775 1776 @Override 1777 public boolean isOnlyCoreApps() { 1778 return mOnlyCore; 1779 } 1780 1781 private String getRequiredVerifierLPr() { 1782 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1783 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1784 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1785 1786 String requiredVerifier = null; 1787 1788 final int N = receivers.size(); 1789 for (int i = 0; i < N; i++) { 1790 final ResolveInfo info = receivers.get(i); 1791 1792 if (info.activityInfo == null) { 1793 continue; 1794 } 1795 1796 final String packageName = info.activityInfo.packageName; 1797 1798 final PackageSetting ps = mSettings.mPackages.get(packageName); 1799 if (ps == null) { 1800 continue; 1801 } 1802 1803 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1804 if (!gp.grantedPermissions 1805 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1806 continue; 1807 } 1808 1809 if (requiredVerifier != null) { 1810 throw new RuntimeException("There can be only one required verifier"); 1811 } 1812 1813 requiredVerifier = packageName; 1814 } 1815 1816 return requiredVerifier; 1817 } 1818 1819 @Override 1820 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1821 throws RemoteException { 1822 try { 1823 return super.onTransact(code, data, reply, flags); 1824 } catch (RuntimeException e) { 1825 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1826 Slog.wtf(TAG, "Package Manager Crash", e); 1827 } 1828 throw e; 1829 } 1830 } 1831 1832 void cleanupInstallFailedPackage(PackageSetting ps) { 1833 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1834 removeDataDirsLI(ps.name); 1835 1836 // TODO: try cleaning up codePath directory contents first, since it 1837 // might be a cluster 1838 1839 if (ps.codePath != null) { 1840 if (!ps.codePath.delete()) { 1841 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1842 } 1843 } 1844 if (ps.resourcePath != null) { 1845 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1846 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1847 } 1848 } 1849 mSettings.removePackageLPw(ps.name); 1850 } 1851 1852 static int[] appendInts(int[] cur, int[] add) { 1853 if (add == null) return cur; 1854 if (cur == null) return add; 1855 final int N = add.length; 1856 for (int i=0; i<N; i++) { 1857 cur = appendInt(cur, add[i]); 1858 } 1859 return cur; 1860 } 1861 1862 static int[] removeInts(int[] cur, int[] rem) { 1863 if (rem == null) return cur; 1864 if (cur == null) return cur; 1865 final int N = rem.length; 1866 for (int i=0; i<N; i++) { 1867 cur = removeInt(cur, rem[i]); 1868 } 1869 return cur; 1870 } 1871 1872 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1873 if (!sUserManager.exists(userId)) return null; 1874 final PackageSetting ps = (PackageSetting) p.mExtras; 1875 if (ps == null) { 1876 return null; 1877 } 1878 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1879 final PackageUserState state = ps.readUserState(userId); 1880 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1881 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1882 state, userId); 1883 } 1884 1885 @Override 1886 public boolean isPackageAvailable(String packageName, int userId) { 1887 if (!sUserManager.exists(userId)) return false; 1888 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1889 synchronized (mPackages) { 1890 PackageParser.Package p = mPackages.get(packageName); 1891 if (p != null) { 1892 final PackageSetting ps = (PackageSetting) p.mExtras; 1893 if (ps != null) { 1894 final PackageUserState state = ps.readUserState(userId); 1895 if (state != null) { 1896 return PackageParser.isAvailable(state); 1897 } 1898 } 1899 } 1900 } 1901 return false; 1902 } 1903 1904 @Override 1905 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1906 if (!sUserManager.exists(userId)) return null; 1907 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1908 // reader 1909 synchronized (mPackages) { 1910 PackageParser.Package p = mPackages.get(packageName); 1911 if (DEBUG_PACKAGE_INFO) 1912 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1913 if (p != null) { 1914 return generatePackageInfo(p, flags, userId); 1915 } 1916 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1917 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1918 } 1919 } 1920 return null; 1921 } 1922 1923 @Override 1924 public String[] currentToCanonicalPackageNames(String[] names) { 1925 String[] out = new String[names.length]; 1926 // reader 1927 synchronized (mPackages) { 1928 for (int i=names.length-1; i>=0; i--) { 1929 PackageSetting ps = mSettings.mPackages.get(names[i]); 1930 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1931 } 1932 } 1933 return out; 1934 } 1935 1936 @Override 1937 public String[] canonicalToCurrentPackageNames(String[] names) { 1938 String[] out = new String[names.length]; 1939 // reader 1940 synchronized (mPackages) { 1941 for (int i=names.length-1; i>=0; i--) { 1942 String cur = mSettings.mRenamedPackages.get(names[i]); 1943 out[i] = cur != null ? cur : names[i]; 1944 } 1945 } 1946 return out; 1947 } 1948 1949 @Override 1950 public int getPackageUid(String packageName, int userId) { 1951 if (!sUserManager.exists(userId)) return -1; 1952 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1953 // reader 1954 synchronized (mPackages) { 1955 PackageParser.Package p = mPackages.get(packageName); 1956 if(p != null) { 1957 return UserHandle.getUid(userId, p.applicationInfo.uid); 1958 } 1959 PackageSetting ps = mSettings.mPackages.get(packageName); 1960 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1961 return -1; 1962 } 1963 p = ps.pkg; 1964 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1965 } 1966 } 1967 1968 @Override 1969 public int[] getPackageGids(String packageName) { 1970 // reader 1971 synchronized (mPackages) { 1972 PackageParser.Package p = mPackages.get(packageName); 1973 if (DEBUG_PACKAGE_INFO) 1974 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1975 if (p != null) { 1976 final PackageSetting ps = (PackageSetting)p.mExtras; 1977 return ps.getGids(); 1978 } 1979 } 1980 // stupid thing to indicate an error. 1981 return new int[0]; 1982 } 1983 1984 static final PermissionInfo generatePermissionInfo( 1985 BasePermission bp, int flags) { 1986 if (bp.perm != null) { 1987 return PackageParser.generatePermissionInfo(bp.perm, flags); 1988 } 1989 PermissionInfo pi = new PermissionInfo(); 1990 pi.name = bp.name; 1991 pi.packageName = bp.sourcePackage; 1992 pi.nonLocalizedLabel = bp.name; 1993 pi.protectionLevel = bp.protectionLevel; 1994 return pi; 1995 } 1996 1997 @Override 1998 public PermissionInfo getPermissionInfo(String name, int flags) { 1999 // reader 2000 synchronized (mPackages) { 2001 final BasePermission p = mSettings.mPermissions.get(name); 2002 if (p != null) { 2003 return generatePermissionInfo(p, flags); 2004 } 2005 return null; 2006 } 2007 } 2008 2009 @Override 2010 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2011 // reader 2012 synchronized (mPackages) { 2013 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2014 for (BasePermission p : mSettings.mPermissions.values()) { 2015 if (group == null) { 2016 if (p.perm == null || p.perm.info.group == null) { 2017 out.add(generatePermissionInfo(p, flags)); 2018 } 2019 } else { 2020 if (p.perm != null && group.equals(p.perm.info.group)) { 2021 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2022 } 2023 } 2024 } 2025 2026 if (out.size() > 0) { 2027 return out; 2028 } 2029 return mPermissionGroups.containsKey(group) ? out : null; 2030 } 2031 } 2032 2033 @Override 2034 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2035 // reader 2036 synchronized (mPackages) { 2037 return PackageParser.generatePermissionGroupInfo( 2038 mPermissionGroups.get(name), flags); 2039 } 2040 } 2041 2042 @Override 2043 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2044 // reader 2045 synchronized (mPackages) { 2046 final int N = mPermissionGroups.size(); 2047 ArrayList<PermissionGroupInfo> out 2048 = new ArrayList<PermissionGroupInfo>(N); 2049 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2050 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2051 } 2052 return out; 2053 } 2054 } 2055 2056 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2057 int userId) { 2058 if (!sUserManager.exists(userId)) return null; 2059 PackageSetting ps = mSettings.mPackages.get(packageName); 2060 if (ps != null) { 2061 if (ps.pkg == null) { 2062 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2063 flags, userId); 2064 if (pInfo != null) { 2065 return pInfo.applicationInfo; 2066 } 2067 return null; 2068 } 2069 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2070 ps.readUserState(userId), userId); 2071 } 2072 return null; 2073 } 2074 2075 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2076 int userId) { 2077 if (!sUserManager.exists(userId)) return null; 2078 PackageSetting ps = mSettings.mPackages.get(packageName); 2079 if (ps != null) { 2080 PackageParser.Package pkg = ps.pkg; 2081 if (pkg == null) { 2082 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2083 return null; 2084 } 2085 // Only data remains, so we aren't worried about code paths 2086 pkg = new PackageParser.Package(packageName); 2087 pkg.applicationInfo.packageName = packageName; 2088 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2089 pkg.applicationInfo.dataDir = 2090 getDataPathForPackage(packageName, 0).getPath(); 2091 pkg.applicationInfo.cpuAbi = ps.cpuAbiString; 2092 } 2093 return generatePackageInfo(pkg, flags, userId); 2094 } 2095 return null; 2096 } 2097 2098 @Override 2099 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2100 if (!sUserManager.exists(userId)) return null; 2101 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2102 // writer 2103 synchronized (mPackages) { 2104 PackageParser.Package p = mPackages.get(packageName); 2105 if (DEBUG_PACKAGE_INFO) Log.v( 2106 TAG, "getApplicationInfo " + packageName 2107 + ": " + p); 2108 if (p != null) { 2109 PackageSetting ps = mSettings.mPackages.get(packageName); 2110 if (ps == null) return null; 2111 // Note: isEnabledLP() does not apply here - always return info 2112 return PackageParser.generateApplicationInfo( 2113 p, flags, ps.readUserState(userId), userId); 2114 } 2115 if ("android".equals(packageName)||"system".equals(packageName)) { 2116 return mAndroidApplication; 2117 } 2118 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2119 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2120 } 2121 } 2122 return null; 2123 } 2124 2125 2126 @Override 2127 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2128 mContext.enforceCallingOrSelfPermission( 2129 android.Manifest.permission.CLEAR_APP_CACHE, null); 2130 // Queue up an async operation since clearing cache may take a little while. 2131 mHandler.post(new Runnable() { 2132 public void run() { 2133 mHandler.removeCallbacks(this); 2134 int retCode = -1; 2135 synchronized (mInstallLock) { 2136 retCode = mInstaller.freeCache(freeStorageSize); 2137 if (retCode < 0) { 2138 Slog.w(TAG, "Couldn't clear application caches"); 2139 } 2140 } 2141 if (observer != null) { 2142 try { 2143 observer.onRemoveCompleted(null, (retCode >= 0)); 2144 } catch (RemoteException e) { 2145 Slog.w(TAG, "RemoveException when invoking call back"); 2146 } 2147 } 2148 } 2149 }); 2150 } 2151 2152 @Override 2153 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2154 mContext.enforceCallingOrSelfPermission( 2155 android.Manifest.permission.CLEAR_APP_CACHE, null); 2156 // Queue up an async operation since clearing cache may take a little while. 2157 mHandler.post(new Runnable() { 2158 public void run() { 2159 mHandler.removeCallbacks(this); 2160 int retCode = -1; 2161 synchronized (mInstallLock) { 2162 retCode = mInstaller.freeCache(freeStorageSize); 2163 if (retCode < 0) { 2164 Slog.w(TAG, "Couldn't clear application caches"); 2165 } 2166 } 2167 if(pi != null) { 2168 try { 2169 // Callback via pending intent 2170 int code = (retCode >= 0) ? 1 : 0; 2171 pi.sendIntent(null, code, null, 2172 null, null); 2173 } catch (SendIntentException e1) { 2174 Slog.i(TAG, "Failed to send pending intent"); 2175 } 2176 } 2177 } 2178 }); 2179 } 2180 2181 void freeStorage(long freeStorageSize) throws IOException { 2182 synchronized (mInstallLock) { 2183 if (mInstaller.freeCache(freeStorageSize) < 0) { 2184 throw new IOException("Failed to free enough space"); 2185 } 2186 } 2187 } 2188 2189 @Override 2190 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2191 if (!sUserManager.exists(userId)) return null; 2192 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2193 synchronized (mPackages) { 2194 PackageParser.Activity a = mActivities.mActivities.get(component); 2195 2196 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2197 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2198 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2199 if (ps == null) return null; 2200 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2201 userId); 2202 } 2203 if (mResolveComponentName.equals(component)) { 2204 return mResolveActivity; 2205 } 2206 } 2207 return null; 2208 } 2209 2210 @Override 2211 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2212 String resolvedType) { 2213 synchronized (mPackages) { 2214 PackageParser.Activity a = mActivities.mActivities.get(component); 2215 if (a == null) { 2216 return false; 2217 } 2218 for (int i=0; i<a.intents.size(); i++) { 2219 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2220 intent.getData(), intent.getCategories(), TAG) >= 0) { 2221 return true; 2222 } 2223 } 2224 return false; 2225 } 2226 } 2227 2228 @Override 2229 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2230 if (!sUserManager.exists(userId)) return null; 2231 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2232 synchronized (mPackages) { 2233 PackageParser.Activity a = mReceivers.mActivities.get(component); 2234 if (DEBUG_PACKAGE_INFO) Log.v( 2235 TAG, "getReceiverInfo " + component + ": " + a); 2236 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2237 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2238 if (ps == null) return null; 2239 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2240 userId); 2241 } 2242 } 2243 return null; 2244 } 2245 2246 @Override 2247 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2248 if (!sUserManager.exists(userId)) return null; 2249 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2250 synchronized (mPackages) { 2251 PackageParser.Service s = mServices.mServices.get(component); 2252 if (DEBUG_PACKAGE_INFO) Log.v( 2253 TAG, "getServiceInfo " + component + ": " + s); 2254 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2255 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2256 if (ps == null) return null; 2257 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2258 userId); 2259 } 2260 } 2261 return null; 2262 } 2263 2264 @Override 2265 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2266 if (!sUserManager.exists(userId)) return null; 2267 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2268 synchronized (mPackages) { 2269 PackageParser.Provider p = mProviders.mProviders.get(component); 2270 if (DEBUG_PACKAGE_INFO) Log.v( 2271 TAG, "getProviderInfo " + component + ": " + p); 2272 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2273 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2274 if (ps == null) return null; 2275 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2276 userId); 2277 } 2278 } 2279 return null; 2280 } 2281 2282 @Override 2283 public String[] getSystemSharedLibraryNames() { 2284 Set<String> libSet; 2285 synchronized (mPackages) { 2286 libSet = mSharedLibraries.keySet(); 2287 int size = libSet.size(); 2288 if (size > 0) { 2289 String[] libs = new String[size]; 2290 libSet.toArray(libs); 2291 return libs; 2292 } 2293 } 2294 return null; 2295 } 2296 2297 @Override 2298 public FeatureInfo[] getSystemAvailableFeatures() { 2299 Collection<FeatureInfo> featSet; 2300 synchronized (mPackages) { 2301 featSet = mAvailableFeatures.values(); 2302 int size = featSet.size(); 2303 if (size > 0) { 2304 FeatureInfo[] features = new FeatureInfo[size+1]; 2305 featSet.toArray(features); 2306 FeatureInfo fi = new FeatureInfo(); 2307 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2308 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2309 features[size] = fi; 2310 return features; 2311 } 2312 } 2313 return null; 2314 } 2315 2316 @Override 2317 public boolean hasSystemFeature(String name) { 2318 synchronized (mPackages) { 2319 return mAvailableFeatures.containsKey(name); 2320 } 2321 } 2322 2323 private void checkValidCaller(int uid, int userId) { 2324 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2325 return; 2326 2327 throw new SecurityException("Caller uid=" + uid 2328 + " is not privileged to communicate with user=" + userId); 2329 } 2330 2331 @Override 2332 public int checkPermission(String permName, String pkgName) { 2333 synchronized (mPackages) { 2334 PackageParser.Package p = mPackages.get(pkgName); 2335 if (p != null && p.mExtras != null) { 2336 PackageSetting ps = (PackageSetting)p.mExtras; 2337 if (ps.sharedUser != null) { 2338 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2339 return PackageManager.PERMISSION_GRANTED; 2340 } 2341 } else if (ps.grantedPermissions.contains(permName)) { 2342 return PackageManager.PERMISSION_GRANTED; 2343 } 2344 } 2345 } 2346 return PackageManager.PERMISSION_DENIED; 2347 } 2348 2349 @Override 2350 public int checkUidPermission(String permName, int uid) { 2351 synchronized (mPackages) { 2352 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2353 if (obj != null) { 2354 GrantedPermissions gp = (GrantedPermissions)obj; 2355 if (gp.grantedPermissions.contains(permName)) { 2356 return PackageManager.PERMISSION_GRANTED; 2357 } 2358 } else { 2359 HashSet<String> perms = mSystemPermissions.get(uid); 2360 if (perms != null && perms.contains(permName)) { 2361 return PackageManager.PERMISSION_GRANTED; 2362 } 2363 } 2364 } 2365 return PackageManager.PERMISSION_DENIED; 2366 } 2367 2368 /** 2369 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2370 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2371 * @param message the message to log on security exception 2372 */ 2373 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2374 String message) { 2375 if (userId < 0) { 2376 throw new IllegalArgumentException("Invalid userId " + userId); 2377 } 2378 if (userId == UserHandle.getUserId(callingUid)) return; 2379 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2380 if (requireFullPermission) { 2381 mContext.enforceCallingOrSelfPermission( 2382 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2383 } else { 2384 try { 2385 mContext.enforceCallingOrSelfPermission( 2386 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2387 } catch (SecurityException se) { 2388 mContext.enforceCallingOrSelfPermission( 2389 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2390 } 2391 } 2392 } 2393 } 2394 2395 private BasePermission findPermissionTreeLP(String permName) { 2396 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2397 if (permName.startsWith(bp.name) && 2398 permName.length() > bp.name.length() && 2399 permName.charAt(bp.name.length()) == '.') { 2400 return bp; 2401 } 2402 } 2403 return null; 2404 } 2405 2406 private BasePermission checkPermissionTreeLP(String permName) { 2407 if (permName != null) { 2408 BasePermission bp = findPermissionTreeLP(permName); 2409 if (bp != null) { 2410 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2411 return bp; 2412 } 2413 throw new SecurityException("Calling uid " 2414 + Binder.getCallingUid() 2415 + " is not allowed to add to permission tree " 2416 + bp.name + " owned by uid " + bp.uid); 2417 } 2418 } 2419 throw new SecurityException("No permission tree found for " + permName); 2420 } 2421 2422 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2423 if (s1 == null) { 2424 return s2 == null; 2425 } 2426 if (s2 == null) { 2427 return false; 2428 } 2429 if (s1.getClass() != s2.getClass()) { 2430 return false; 2431 } 2432 return s1.equals(s2); 2433 } 2434 2435 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2436 if (pi1.icon != pi2.icon) return false; 2437 if (pi1.logo != pi2.logo) return false; 2438 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2439 if (!compareStrings(pi1.name, pi2.name)) return false; 2440 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2441 // We'll take care of setting this one. 2442 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2443 // These are not currently stored in settings. 2444 //if (!compareStrings(pi1.group, pi2.group)) return false; 2445 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2446 //if (pi1.labelRes != pi2.labelRes) return false; 2447 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2448 return true; 2449 } 2450 2451 int permissionInfoFootprint(PermissionInfo info) { 2452 int size = info.name.length(); 2453 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2454 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2455 return size; 2456 } 2457 2458 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2459 int size = 0; 2460 for (BasePermission perm : mSettings.mPermissions.values()) { 2461 if (perm.uid == tree.uid) { 2462 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2463 } 2464 } 2465 return size; 2466 } 2467 2468 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2469 // We calculate the max size of permissions defined by this uid and throw 2470 // if that plus the size of 'info' would exceed our stated maximum. 2471 if (tree.uid != Process.SYSTEM_UID) { 2472 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2473 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2474 throw new SecurityException("Permission tree size cap exceeded"); 2475 } 2476 } 2477 } 2478 2479 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2480 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2481 throw new SecurityException("Label must be specified in permission"); 2482 } 2483 BasePermission tree = checkPermissionTreeLP(info.name); 2484 BasePermission bp = mSettings.mPermissions.get(info.name); 2485 boolean added = bp == null; 2486 boolean changed = true; 2487 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2488 if (added) { 2489 enforcePermissionCapLocked(info, tree); 2490 bp = new BasePermission(info.name, tree.sourcePackage, 2491 BasePermission.TYPE_DYNAMIC); 2492 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2493 throw new SecurityException( 2494 "Not allowed to modify non-dynamic permission " 2495 + info.name); 2496 } else { 2497 if (bp.protectionLevel == fixedLevel 2498 && bp.perm.owner.equals(tree.perm.owner) 2499 && bp.uid == tree.uid 2500 && comparePermissionInfos(bp.perm.info, info)) { 2501 changed = false; 2502 } 2503 } 2504 bp.protectionLevel = fixedLevel; 2505 info = new PermissionInfo(info); 2506 info.protectionLevel = fixedLevel; 2507 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2508 bp.perm.info.packageName = tree.perm.info.packageName; 2509 bp.uid = tree.uid; 2510 if (added) { 2511 mSettings.mPermissions.put(info.name, bp); 2512 } 2513 if (changed) { 2514 if (!async) { 2515 mSettings.writeLPr(); 2516 } else { 2517 scheduleWriteSettingsLocked(); 2518 } 2519 } 2520 return added; 2521 } 2522 2523 @Override 2524 public boolean addPermission(PermissionInfo info) { 2525 synchronized (mPackages) { 2526 return addPermissionLocked(info, false); 2527 } 2528 } 2529 2530 @Override 2531 public boolean addPermissionAsync(PermissionInfo info) { 2532 synchronized (mPackages) { 2533 return addPermissionLocked(info, true); 2534 } 2535 } 2536 2537 @Override 2538 public void removePermission(String name) { 2539 synchronized (mPackages) { 2540 checkPermissionTreeLP(name); 2541 BasePermission bp = mSettings.mPermissions.get(name); 2542 if (bp != null) { 2543 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2544 throw new SecurityException( 2545 "Not allowed to modify non-dynamic permission " 2546 + name); 2547 } 2548 mSettings.mPermissions.remove(name); 2549 mSettings.writeLPr(); 2550 } 2551 } 2552 } 2553 2554 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2555 int index = pkg.requestedPermissions.indexOf(bp.name); 2556 if (index == -1) { 2557 throw new SecurityException("Package " + pkg.packageName 2558 + " has not requested permission " + bp.name); 2559 } 2560 boolean isNormal = 2561 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2562 == PermissionInfo.PROTECTION_NORMAL); 2563 boolean isDangerous = 2564 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2565 == PermissionInfo.PROTECTION_DANGEROUS); 2566 boolean isDevelopment = 2567 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2568 2569 if (!isNormal && !isDangerous && !isDevelopment) { 2570 throw new SecurityException("Permission " + bp.name 2571 + " is not a changeable permission type"); 2572 } 2573 2574 if (isNormal || isDangerous) { 2575 if (pkg.requestedPermissionsRequired.get(index)) { 2576 throw new SecurityException("Can't change " + bp.name 2577 + ". It is required by the application"); 2578 } 2579 } 2580 } 2581 2582 @Override 2583 public void grantPermission(String packageName, String permissionName) { 2584 mContext.enforceCallingOrSelfPermission( 2585 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2586 synchronized (mPackages) { 2587 final PackageParser.Package pkg = mPackages.get(packageName); 2588 if (pkg == null) { 2589 throw new IllegalArgumentException("Unknown package: " + packageName); 2590 } 2591 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2592 if (bp == null) { 2593 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2594 } 2595 2596 checkGrantRevokePermissions(pkg, bp); 2597 2598 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2599 if (ps == null) { 2600 return; 2601 } 2602 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2603 if (gp.grantedPermissions.add(permissionName)) { 2604 if (ps.haveGids) { 2605 gp.gids = appendInts(gp.gids, bp.gids); 2606 } 2607 mSettings.writeLPr(); 2608 } 2609 } 2610 } 2611 2612 @Override 2613 public void revokePermission(String packageName, String permissionName) { 2614 int changedAppId = -1; 2615 2616 synchronized (mPackages) { 2617 final PackageParser.Package pkg = mPackages.get(packageName); 2618 if (pkg == null) { 2619 throw new IllegalArgumentException("Unknown package: " + packageName); 2620 } 2621 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2622 mContext.enforceCallingOrSelfPermission( 2623 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2624 } 2625 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2626 if (bp == null) { 2627 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2628 } 2629 2630 checkGrantRevokePermissions(pkg, bp); 2631 2632 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2633 if (ps == null) { 2634 return; 2635 } 2636 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2637 if (gp.grantedPermissions.remove(permissionName)) { 2638 gp.grantedPermissions.remove(permissionName); 2639 if (ps.haveGids) { 2640 gp.gids = removeInts(gp.gids, bp.gids); 2641 } 2642 mSettings.writeLPr(); 2643 changedAppId = ps.appId; 2644 } 2645 } 2646 2647 if (changedAppId >= 0) { 2648 // We changed the perm on someone, kill its processes. 2649 IActivityManager am = ActivityManagerNative.getDefault(); 2650 if (am != null) { 2651 final int callingUserId = UserHandle.getCallingUserId(); 2652 final long ident = Binder.clearCallingIdentity(); 2653 try { 2654 //XXX we should only revoke for the calling user's app permissions, 2655 // but for now we impact all users. 2656 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2657 // "revoke " + permissionName); 2658 int[] users = sUserManager.getUserIds(); 2659 for (int user : users) { 2660 am.killUid(UserHandle.getUid(user, changedAppId), 2661 "revoke " + permissionName); 2662 } 2663 } catch (RemoteException e) { 2664 } finally { 2665 Binder.restoreCallingIdentity(ident); 2666 } 2667 } 2668 } 2669 } 2670 2671 @Override 2672 public boolean isProtectedBroadcast(String actionName) { 2673 synchronized (mPackages) { 2674 return mProtectedBroadcasts.contains(actionName); 2675 } 2676 } 2677 2678 @Override 2679 public int checkSignatures(String pkg1, String pkg2) { 2680 synchronized (mPackages) { 2681 final PackageParser.Package p1 = mPackages.get(pkg1); 2682 final PackageParser.Package p2 = mPackages.get(pkg2); 2683 if (p1 == null || p1.mExtras == null 2684 || p2 == null || p2.mExtras == null) { 2685 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2686 } 2687 return compareSignatures(p1.mSignatures, p2.mSignatures); 2688 } 2689 } 2690 2691 @Override 2692 public int checkUidSignatures(int uid1, int uid2) { 2693 // Map to base uids. 2694 uid1 = UserHandle.getAppId(uid1); 2695 uid2 = UserHandle.getAppId(uid2); 2696 // reader 2697 synchronized (mPackages) { 2698 Signature[] s1; 2699 Signature[] s2; 2700 Object obj = mSettings.getUserIdLPr(uid1); 2701 if (obj != null) { 2702 if (obj instanceof SharedUserSetting) { 2703 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2704 } else if (obj instanceof PackageSetting) { 2705 s1 = ((PackageSetting)obj).signatures.mSignatures; 2706 } else { 2707 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2708 } 2709 } else { 2710 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2711 } 2712 obj = mSettings.getUserIdLPr(uid2); 2713 if (obj != null) { 2714 if (obj instanceof SharedUserSetting) { 2715 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2716 } else if (obj instanceof PackageSetting) { 2717 s2 = ((PackageSetting)obj).signatures.mSignatures; 2718 } else { 2719 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2720 } 2721 } else { 2722 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2723 } 2724 return compareSignatures(s1, s2); 2725 } 2726 } 2727 2728 /** 2729 * Compares two sets of signatures. Returns: 2730 * <br /> 2731 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2732 * <br /> 2733 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2734 * <br /> 2735 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2736 * <br /> 2737 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2738 * <br /> 2739 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2740 */ 2741 static int compareSignatures(Signature[] s1, Signature[] s2) { 2742 if (s1 == null) { 2743 return s2 == null 2744 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2745 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2746 } 2747 2748 if (s2 == null) { 2749 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2750 } 2751 2752 if (s1.length != s2.length) { 2753 return PackageManager.SIGNATURE_NO_MATCH; 2754 } 2755 2756 // Since both signature sets are of size 1, we can compare without HashSets. 2757 if (s1.length == 1) { 2758 return s1[0].equals(s2[0]) ? 2759 PackageManager.SIGNATURE_MATCH : 2760 PackageManager.SIGNATURE_NO_MATCH; 2761 } 2762 2763 HashSet<Signature> set1 = new HashSet<Signature>(); 2764 for (Signature sig : s1) { 2765 set1.add(sig); 2766 } 2767 HashSet<Signature> set2 = new HashSet<Signature>(); 2768 for (Signature sig : s2) { 2769 set2.add(sig); 2770 } 2771 // Make sure s2 contains all signatures in s1. 2772 if (set1.equals(set2)) { 2773 return PackageManager.SIGNATURE_MATCH; 2774 } 2775 return PackageManager.SIGNATURE_NO_MATCH; 2776 } 2777 2778 /** 2779 * If the database version for this type of package (internal storage or 2780 * external storage) is less than the version where package signatures 2781 * were updated, return true. 2782 */ 2783 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2784 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2785 DatabaseVersion.SIGNATURE_END_ENTITY)) 2786 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2787 DatabaseVersion.SIGNATURE_END_ENTITY)); 2788 } 2789 2790 /** 2791 * Used for backward compatibility to make sure any packages with 2792 * certificate chains get upgraded to the new style. {@code existingSigs} 2793 * will be in the old format (since they were stored on disk from before the 2794 * system upgrade) and {@code scannedSigs} will be in the newer format. 2795 */ 2796 private int compareSignaturesCompat(PackageSignatures existingSigs, 2797 PackageParser.Package scannedPkg) { 2798 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2799 return PackageManager.SIGNATURE_NO_MATCH; 2800 } 2801 2802 HashSet<Signature> existingSet = new HashSet<Signature>(); 2803 for (Signature sig : existingSigs.mSignatures) { 2804 existingSet.add(sig); 2805 } 2806 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2807 for (Signature sig : scannedPkg.mSignatures) { 2808 try { 2809 Signature[] chainSignatures = sig.getChainSignatures(); 2810 for (Signature chainSig : chainSignatures) { 2811 scannedCompatSet.add(chainSig); 2812 } 2813 } catch (CertificateEncodingException e) { 2814 scannedCompatSet.add(sig); 2815 } 2816 } 2817 /* 2818 * Make sure the expanded scanned set contains all signatures in the 2819 * existing one. 2820 */ 2821 if (scannedCompatSet.equals(existingSet)) { 2822 // Migrate the old signatures to the new scheme. 2823 existingSigs.assignSignatures(scannedPkg.mSignatures); 2824 // The new KeySets will be re-added later in the scanning process. 2825 mSettings.mKeySetManagerService.removeAppKeySetData(scannedPkg.packageName); 2826 return PackageManager.SIGNATURE_MATCH; 2827 } 2828 return PackageManager.SIGNATURE_NO_MATCH; 2829 } 2830 2831 @Override 2832 public String[] getPackagesForUid(int uid) { 2833 uid = UserHandle.getAppId(uid); 2834 // reader 2835 synchronized (mPackages) { 2836 Object obj = mSettings.getUserIdLPr(uid); 2837 if (obj instanceof SharedUserSetting) { 2838 final SharedUserSetting sus = (SharedUserSetting) obj; 2839 final int N = sus.packages.size(); 2840 final String[] res = new String[N]; 2841 final Iterator<PackageSetting> it = sus.packages.iterator(); 2842 int i = 0; 2843 while (it.hasNext()) { 2844 res[i++] = it.next().name; 2845 } 2846 return res; 2847 } else if (obj instanceof PackageSetting) { 2848 final PackageSetting ps = (PackageSetting) obj; 2849 return new String[] { ps.name }; 2850 } 2851 } 2852 return null; 2853 } 2854 2855 @Override 2856 public String getNameForUid(int uid) { 2857 // reader 2858 synchronized (mPackages) { 2859 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2860 if (obj instanceof SharedUserSetting) { 2861 final SharedUserSetting sus = (SharedUserSetting) obj; 2862 return sus.name + ":" + sus.userId; 2863 } else if (obj instanceof PackageSetting) { 2864 final PackageSetting ps = (PackageSetting) obj; 2865 return ps.name; 2866 } 2867 } 2868 return null; 2869 } 2870 2871 @Override 2872 public int getUidForSharedUser(String sharedUserName) { 2873 if(sharedUserName == null) { 2874 return -1; 2875 } 2876 // reader 2877 synchronized (mPackages) { 2878 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2879 if (suid == null) { 2880 return -1; 2881 } 2882 return suid.userId; 2883 } 2884 } 2885 2886 @Override 2887 public int getFlagsForUid(int uid) { 2888 synchronized (mPackages) { 2889 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2890 if (obj instanceof SharedUserSetting) { 2891 final SharedUserSetting sus = (SharedUserSetting) obj; 2892 return sus.pkgFlags; 2893 } else if (obj instanceof PackageSetting) { 2894 final PackageSetting ps = (PackageSetting) obj; 2895 return ps.pkgFlags; 2896 } 2897 } 2898 return 0; 2899 } 2900 2901 @Override 2902 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2903 int flags, int userId) { 2904 if (!sUserManager.exists(userId)) return null; 2905 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2906 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2907 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2908 } 2909 2910 @Override 2911 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2912 IntentFilter filter, int match, ComponentName activity) { 2913 final int userId = UserHandle.getCallingUserId(); 2914 if (DEBUG_PREFERRED) { 2915 Log.v(TAG, "setLastChosenActivity intent=" + intent 2916 + " resolvedType=" + resolvedType 2917 + " flags=" + flags 2918 + " filter=" + filter 2919 + " match=" + match 2920 + " activity=" + activity); 2921 filter.dump(new PrintStreamPrinter(System.out), " "); 2922 } 2923 intent.setComponent(null); 2924 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2925 // Find any earlier preferred or last chosen entries and nuke them 2926 findPreferredActivity(intent, resolvedType, 2927 flags, query, 0, false, true, false, userId); 2928 // Add the new activity as the last chosen for this filter 2929 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2930 } 2931 2932 @Override 2933 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2934 final int userId = UserHandle.getCallingUserId(); 2935 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2936 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2937 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2938 false, false, false, userId); 2939 } 2940 2941 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2942 int flags, List<ResolveInfo> query, int userId) { 2943 if (query != null) { 2944 final int N = query.size(); 2945 if (N == 1) { 2946 return query.get(0); 2947 } else if (N > 1) { 2948 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2949 // If there is more than one activity with the same priority, 2950 // then let the user decide between them. 2951 ResolveInfo r0 = query.get(0); 2952 ResolveInfo r1 = query.get(1); 2953 if (DEBUG_INTENT_MATCHING || debug) { 2954 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2955 + r1.activityInfo.name + "=" + r1.priority); 2956 } 2957 // If the first activity has a higher priority, or a different 2958 // default, then it is always desireable to pick it. 2959 if (r0.priority != r1.priority 2960 || r0.preferredOrder != r1.preferredOrder 2961 || r0.isDefault != r1.isDefault) { 2962 return query.get(0); 2963 } 2964 // If we have saved a preference for a preferred activity for 2965 // this Intent, use that. 2966 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2967 flags, query, r0.priority, true, false, debug, userId); 2968 if (ri != null) { 2969 return ri; 2970 } 2971 if (userId != 0) { 2972 ri = new ResolveInfo(mResolveInfo); 2973 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2974 ri.activityInfo.applicationInfo = new ApplicationInfo( 2975 ri.activityInfo.applicationInfo); 2976 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2977 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2978 return ri; 2979 } 2980 return mResolveInfo; 2981 } 2982 } 2983 return null; 2984 } 2985 2986 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2987 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2988 final int N = query.size(); 2989 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2990 .get(userId); 2991 // Get the list of persistent preferred activities that handle the intent 2992 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2993 List<PersistentPreferredActivity> pprefs = ppir != null 2994 ? ppir.queryIntent(intent, resolvedType, 2995 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2996 : null; 2997 if (pprefs != null && pprefs.size() > 0) { 2998 final int M = pprefs.size(); 2999 for (int i=0; i<M; i++) { 3000 final PersistentPreferredActivity ppa = pprefs.get(i); 3001 if (DEBUG_PREFERRED || debug) { 3002 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3003 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3004 + "\n component=" + ppa.mComponent); 3005 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3006 } 3007 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3008 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3009 if (DEBUG_PREFERRED || debug) { 3010 Slog.v(TAG, "Found persistent preferred activity:"); 3011 if (ai != null) { 3012 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3013 } else { 3014 Slog.v(TAG, " null"); 3015 } 3016 } 3017 if (ai == null) { 3018 // This previously registered persistent preferred activity 3019 // component is no longer known. Ignore it and do NOT remove it. 3020 continue; 3021 } 3022 for (int j=0; j<N; j++) { 3023 final ResolveInfo ri = query.get(j); 3024 if (!ri.activityInfo.applicationInfo.packageName 3025 .equals(ai.applicationInfo.packageName)) { 3026 continue; 3027 } 3028 if (!ri.activityInfo.name.equals(ai.name)) { 3029 continue; 3030 } 3031 // Found a persistent preference that can handle the intent. 3032 if (DEBUG_PREFERRED || debug) { 3033 Slog.v(TAG, "Returning persistent preferred activity: " + 3034 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3035 } 3036 return ri; 3037 } 3038 } 3039 } 3040 return null; 3041 } 3042 3043 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3044 List<ResolveInfo> query, int priority, boolean always, 3045 boolean removeMatches, boolean debug, int userId) { 3046 if (!sUserManager.exists(userId)) return null; 3047 // writer 3048 synchronized (mPackages) { 3049 if (intent.getSelector() != null) { 3050 intent = intent.getSelector(); 3051 } 3052 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3053 3054 // Try to find a matching persistent preferred activity. 3055 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3056 debug, userId); 3057 3058 // If a persistent preferred activity matched, use it. 3059 if (pri != null) { 3060 return pri; 3061 } 3062 3063 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3064 // Get the list of preferred activities that handle the intent 3065 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3066 List<PreferredActivity> prefs = pir != null 3067 ? pir.queryIntent(intent, resolvedType, 3068 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3069 : null; 3070 if (prefs != null && prefs.size() > 0) { 3071 // First figure out how good the original match set is. 3072 // We will only allow preferred activities that came 3073 // from the same match quality. 3074 int match = 0; 3075 3076 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3077 3078 final int N = query.size(); 3079 for (int j=0; j<N; j++) { 3080 final ResolveInfo ri = query.get(j); 3081 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3082 + ": 0x" + Integer.toHexString(match)); 3083 if (ri.match > match) { 3084 match = ri.match; 3085 } 3086 } 3087 3088 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3089 + Integer.toHexString(match)); 3090 3091 match &= IntentFilter.MATCH_CATEGORY_MASK; 3092 final int M = prefs.size(); 3093 for (int i=0; i<M; i++) { 3094 final PreferredActivity pa = prefs.get(i); 3095 if (DEBUG_PREFERRED || debug) { 3096 Slog.v(TAG, "Checking PreferredActivity ds=" 3097 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3098 + "\n component=" + pa.mPref.mComponent); 3099 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3100 } 3101 if (pa.mPref.mMatch != match) { 3102 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3103 + Integer.toHexString(pa.mPref.mMatch)); 3104 continue; 3105 } 3106 // If it's not an "always" type preferred activity and that's what we're 3107 // looking for, skip it. 3108 if (always && !pa.mPref.mAlways) { 3109 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3110 continue; 3111 } 3112 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3113 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3114 if (DEBUG_PREFERRED || debug) { 3115 Slog.v(TAG, "Found preferred activity:"); 3116 if (ai != null) { 3117 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3118 } else { 3119 Slog.v(TAG, " null"); 3120 } 3121 } 3122 if (ai == null) { 3123 // This previously registered preferred activity 3124 // component is no longer known. Most likely an update 3125 // to the app was installed and in the new version this 3126 // component no longer exists. Clean it up by removing 3127 // it from the preferred activities list, and skip it. 3128 Slog.w(TAG, "Removing dangling preferred activity: " 3129 + pa.mPref.mComponent); 3130 pir.removeFilter(pa); 3131 continue; 3132 } 3133 for (int j=0; j<N; j++) { 3134 final ResolveInfo ri = query.get(j); 3135 if (!ri.activityInfo.applicationInfo.packageName 3136 .equals(ai.applicationInfo.packageName)) { 3137 continue; 3138 } 3139 if (!ri.activityInfo.name.equals(ai.name)) { 3140 continue; 3141 } 3142 3143 if (removeMatches) { 3144 pir.removeFilter(pa); 3145 if (DEBUG_PREFERRED) { 3146 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3147 } 3148 break; 3149 } 3150 3151 // Okay we found a previously set preferred or last chosen app. 3152 // If the result set is different from when this 3153 // was created, we need to clear it and re-ask the 3154 // user their preference, if we're looking for an "always" type entry. 3155 if (always && !pa.mPref.sameSet(query, priority)) { 3156 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3157 + intent + " type " + resolvedType); 3158 if (DEBUG_PREFERRED) { 3159 Slog.v(TAG, "Removing preferred activity since set changed " 3160 + pa.mPref.mComponent); 3161 } 3162 pir.removeFilter(pa); 3163 // Re-add the filter as a "last chosen" entry (!always) 3164 PreferredActivity lastChosen = new PreferredActivity( 3165 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3166 pir.addFilter(lastChosen); 3167 mSettings.writePackageRestrictionsLPr(userId); 3168 return null; 3169 } 3170 3171 // Yay! Either the set matched or we're looking for the last chosen 3172 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3173 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3174 mSettings.writePackageRestrictionsLPr(userId); 3175 return ri; 3176 } 3177 } 3178 } 3179 mSettings.writePackageRestrictionsLPr(userId); 3180 } 3181 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3182 return null; 3183 } 3184 3185 /* 3186 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3187 */ 3188 @Override 3189 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3190 int targetUserId) { 3191 mContext.enforceCallingOrSelfPermission( 3192 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3193 List<CrossProfileIntentFilter> matches = 3194 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3195 if (matches != null) { 3196 int size = matches.size(); 3197 for (int i = 0; i < size; i++) { 3198 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3199 } 3200 } 3201 3202 ArrayList<String> packageNames = null; 3203 SparseArray<ArrayList<String>> fromSource = 3204 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3205 if (fromSource != null) { 3206 packageNames = fromSource.get(targetUserId); 3207 } 3208 if (packageNames.contains(intent.getPackage())) { 3209 return true; 3210 } 3211 // We need the package name, so we try to resolve with the loosest flags possible 3212 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3213 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3214 int count = resolveInfos.size(); 3215 for (int i = 0; i < count; i++) { 3216 ResolveInfo resolveInfo = resolveInfos.get(i); 3217 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3218 return true; 3219 } 3220 } 3221 return false; 3222 } 3223 3224 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3225 String resolvedType, int userId) { 3226 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3227 if (resolver != null) { 3228 return resolver.queryIntent(intent, resolvedType, false, userId); 3229 } 3230 return null; 3231 } 3232 3233 @Override 3234 public List<ResolveInfo> queryIntentActivities(Intent intent, 3235 String resolvedType, int flags, int userId) { 3236 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3237 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3238 ComponentName comp = intent.getComponent(); 3239 if (comp == null) { 3240 if (intent.getSelector() != null) { 3241 intent = intent.getSelector(); 3242 comp = intent.getComponent(); 3243 } 3244 } 3245 3246 if (comp != null) { 3247 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3248 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3249 if (ai != null) { 3250 final ResolveInfo ri = new ResolveInfo(); 3251 ri.activityInfo = ai; 3252 list.add(ri); 3253 } 3254 return list; 3255 } 3256 3257 // reader 3258 synchronized (mPackages) { 3259 final String pkgName = intent.getPackage(); 3260 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3261 if (pkgName == null) { 3262 ResolveInfo resolveInfo = null; 3263 if (queryCrossProfile) { 3264 // Check if the intent needs to be forwarded to another user for this package 3265 ArrayList<ResolveInfo> crossProfileResult = 3266 queryIntentActivitiesCrossProfilePackage( 3267 intent, resolvedType, flags, userId); 3268 if (!crossProfileResult.isEmpty()) { 3269 // Skip the current profile 3270 return crossProfileResult; 3271 } 3272 List<CrossProfileIntentFilter> matchingFilters = 3273 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3274 // Check for results that need to skip the current profile. 3275 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3276 resolvedType, flags, userId); 3277 if (resolveInfo != null) { 3278 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3279 result.add(resolveInfo); 3280 return result; 3281 } 3282 // Check for cross profile results. 3283 resolveInfo = queryCrossProfileIntents( 3284 matchingFilters, intent, resolvedType, flags, userId); 3285 } 3286 // Check for results in the current profile. 3287 List<ResolveInfo> result = mActivities.queryIntent( 3288 intent, resolvedType, flags, userId); 3289 if (resolveInfo != null) { 3290 result.add(resolveInfo); 3291 } 3292 return result; 3293 } 3294 final PackageParser.Package pkg = mPackages.get(pkgName); 3295 if (pkg != null) { 3296 if (queryCrossProfile) { 3297 ArrayList<ResolveInfo> crossProfileResult = 3298 queryIntentActivitiesCrossProfilePackage( 3299 intent, resolvedType, flags, userId, pkg, pkgName); 3300 if (!crossProfileResult.isEmpty()) { 3301 // Skip the current profile 3302 return crossProfileResult; 3303 } 3304 } 3305 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3306 pkg.activities, userId); 3307 } 3308 return new ArrayList<ResolveInfo>(); 3309 } 3310 } 3311 3312 private ResolveInfo querySkipCurrentProfileIntents( 3313 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3314 int flags, int sourceUserId) { 3315 if (matchingFilters != null) { 3316 int size = matchingFilters.size(); 3317 for (int i = 0; i < size; i ++) { 3318 CrossProfileIntentFilter filter = matchingFilters.get(i); 3319 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3320 // Checking if there are activities in the target user that can handle the 3321 // intent. 3322 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3323 flags, sourceUserId); 3324 if (resolveInfo != null) { 3325 return resolveInfo; 3326 } 3327 } 3328 } 3329 } 3330 return null; 3331 } 3332 3333 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3334 Intent intent, String resolvedType, int flags, int userId) { 3335 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3336 SparseArray<ArrayList<String>> sourceForwardingInfo = 3337 mSettings.mCrossProfilePackageInfo.get(userId); 3338 if (sourceForwardingInfo != null) { 3339 int NI = sourceForwardingInfo.size(); 3340 for (int i = 0; i < NI; i++) { 3341 int targetUserId = sourceForwardingInfo.keyAt(i); 3342 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3343 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3344 intent, resolvedType, flags, targetUserId); 3345 int NJ = resolveInfos.size(); 3346 for (int j = 0; j < NJ; j++) { 3347 ResolveInfo resolveInfo = resolveInfos.get(j); 3348 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3349 matchingResolveInfos.add(createForwardingResolveInfo( 3350 resolveInfo.filter, userId, targetUserId)); 3351 } 3352 } 3353 } 3354 } 3355 return matchingResolveInfos; 3356 } 3357 3358 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3359 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3360 String packageName) { 3361 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3362 SparseArray<ArrayList<String>> sourceForwardingInfo = 3363 mSettings.mCrossProfilePackageInfo.get(userId); 3364 if (sourceForwardingInfo != null) { 3365 int NI = sourceForwardingInfo.size(); 3366 for (int i = 0; i < NI; i++) { 3367 int targetUserId = sourceForwardingInfo.keyAt(i); 3368 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3369 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3370 intent, resolvedType, flags, pkg.activities, targetUserId); 3371 int NJ = resolveInfos.size(); 3372 for (int j = 0; j < NJ; j++) { 3373 ResolveInfo resolveInfo = resolveInfos.get(j); 3374 matchingResolveInfos.add(createForwardingResolveInfo( 3375 resolveInfo.filter, userId, targetUserId)); 3376 } 3377 } 3378 } 3379 } 3380 return matchingResolveInfos; 3381 } 3382 3383 // Return matching ResolveInfo if any for skip current profile intent filters. 3384 private ResolveInfo queryCrossProfileIntents( 3385 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3386 int flags, int sourceUserId) { 3387 if (matchingFilters != null) { 3388 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3389 // match the same intent. For performance reasons, it is better not to 3390 // run queryIntent twice for the same userId 3391 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3392 int size = matchingFilters.size(); 3393 for (int i = 0; i < size; i++) { 3394 CrossProfileIntentFilter filter = matchingFilters.get(i); 3395 int targetUserId = filter.getTargetUserId(); 3396 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3397 && !alreadyTriedUserIds.get(targetUserId)) { 3398 // Checking if there are activities in the target user that can handle the 3399 // intent. 3400 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3401 flags, sourceUserId); 3402 if (resolveInfo != null) return resolveInfo; 3403 alreadyTriedUserIds.put(targetUserId, true); 3404 } 3405 } 3406 } 3407 return null; 3408 } 3409 3410 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3411 String resolvedType, int flags, int sourceUserId) { 3412 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3413 resolvedType, flags, filter.getTargetUserId()); 3414 if (resultTargetUser != null) { 3415 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3416 } 3417 return null; 3418 } 3419 3420 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3421 int sourceUserId, int targetUserId) { 3422 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3423 String className; 3424 if (targetUserId == UserHandle.USER_OWNER) { 3425 className = FORWARD_INTENT_TO_USER_OWNER; 3426 } else { 3427 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3428 } 3429 ComponentName forwardingActivityComponentName = new ComponentName( 3430 mAndroidApplication.packageName, className); 3431 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3432 sourceUserId); 3433 if (targetUserId == UserHandle.USER_OWNER) { 3434 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3435 forwardingResolveInfo.noResourceId = true; 3436 } 3437 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3438 forwardingResolveInfo.priority = 0; 3439 forwardingResolveInfo.preferredOrder = 0; 3440 forwardingResolveInfo.match = 0; 3441 forwardingResolveInfo.isDefault = true; 3442 forwardingResolveInfo.filter = filter; 3443 forwardingResolveInfo.targetUserId = targetUserId; 3444 return forwardingResolveInfo; 3445 } 3446 3447 @Override 3448 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3449 Intent[] specifics, String[] specificTypes, Intent intent, 3450 String resolvedType, int flags, int userId) { 3451 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3452 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3453 "query intent activity options"); 3454 final String resultsAction = intent.getAction(); 3455 3456 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3457 | PackageManager.GET_RESOLVED_FILTER, userId); 3458 3459 if (DEBUG_INTENT_MATCHING) { 3460 Log.v(TAG, "Query " + intent + ": " + results); 3461 } 3462 3463 int specificsPos = 0; 3464 int N; 3465 3466 // todo: note that the algorithm used here is O(N^2). This 3467 // isn't a problem in our current environment, but if we start running 3468 // into situations where we have more than 5 or 10 matches then this 3469 // should probably be changed to something smarter... 3470 3471 // First we go through and resolve each of the specific items 3472 // that were supplied, taking care of removing any corresponding 3473 // duplicate items in the generic resolve list. 3474 if (specifics != null) { 3475 for (int i=0; i<specifics.length; i++) { 3476 final Intent sintent = specifics[i]; 3477 if (sintent == null) { 3478 continue; 3479 } 3480 3481 if (DEBUG_INTENT_MATCHING) { 3482 Log.v(TAG, "Specific #" + i + ": " + sintent); 3483 } 3484 3485 String action = sintent.getAction(); 3486 if (resultsAction != null && resultsAction.equals(action)) { 3487 // If this action was explicitly requested, then don't 3488 // remove things that have it. 3489 action = null; 3490 } 3491 3492 ResolveInfo ri = null; 3493 ActivityInfo ai = null; 3494 3495 ComponentName comp = sintent.getComponent(); 3496 if (comp == null) { 3497 ri = resolveIntent( 3498 sintent, 3499 specificTypes != null ? specificTypes[i] : null, 3500 flags, userId); 3501 if (ri == null) { 3502 continue; 3503 } 3504 if (ri == mResolveInfo) { 3505 // ACK! Must do something better with this. 3506 } 3507 ai = ri.activityInfo; 3508 comp = new ComponentName(ai.applicationInfo.packageName, 3509 ai.name); 3510 } else { 3511 ai = getActivityInfo(comp, flags, userId); 3512 if (ai == null) { 3513 continue; 3514 } 3515 } 3516 3517 // Look for any generic query activities that are duplicates 3518 // of this specific one, and remove them from the results. 3519 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3520 N = results.size(); 3521 int j; 3522 for (j=specificsPos; j<N; j++) { 3523 ResolveInfo sri = results.get(j); 3524 if ((sri.activityInfo.name.equals(comp.getClassName()) 3525 && sri.activityInfo.applicationInfo.packageName.equals( 3526 comp.getPackageName())) 3527 || (action != null && sri.filter.matchAction(action))) { 3528 results.remove(j); 3529 if (DEBUG_INTENT_MATCHING) Log.v( 3530 TAG, "Removing duplicate item from " + j 3531 + " due to specific " + specificsPos); 3532 if (ri == null) { 3533 ri = sri; 3534 } 3535 j--; 3536 N--; 3537 } 3538 } 3539 3540 // Add this specific item to its proper place. 3541 if (ri == null) { 3542 ri = new ResolveInfo(); 3543 ri.activityInfo = ai; 3544 } 3545 results.add(specificsPos, ri); 3546 ri.specificIndex = i; 3547 specificsPos++; 3548 } 3549 } 3550 3551 // Now we go through the remaining generic results and remove any 3552 // duplicate actions that are found here. 3553 N = results.size(); 3554 for (int i=specificsPos; i<N-1; i++) { 3555 final ResolveInfo rii = results.get(i); 3556 if (rii.filter == null) { 3557 continue; 3558 } 3559 3560 // Iterate over all of the actions of this result's intent 3561 // filter... typically this should be just one. 3562 final Iterator<String> it = rii.filter.actionsIterator(); 3563 if (it == null) { 3564 continue; 3565 } 3566 while (it.hasNext()) { 3567 final String action = it.next(); 3568 if (resultsAction != null && resultsAction.equals(action)) { 3569 // If this action was explicitly requested, then don't 3570 // remove things that have it. 3571 continue; 3572 } 3573 for (int j=i+1; j<N; j++) { 3574 final ResolveInfo rij = results.get(j); 3575 if (rij.filter != null && rij.filter.hasAction(action)) { 3576 results.remove(j); 3577 if (DEBUG_INTENT_MATCHING) Log.v( 3578 TAG, "Removing duplicate item from " + j 3579 + " due to action " + action + " at " + i); 3580 j--; 3581 N--; 3582 } 3583 } 3584 } 3585 3586 // If the caller didn't request filter information, drop it now 3587 // so we don't have to marshall/unmarshall it. 3588 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3589 rii.filter = null; 3590 } 3591 } 3592 3593 // Filter out the caller activity if so requested. 3594 if (caller != null) { 3595 N = results.size(); 3596 for (int i=0; i<N; i++) { 3597 ActivityInfo ainfo = results.get(i).activityInfo; 3598 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3599 && caller.getClassName().equals(ainfo.name)) { 3600 results.remove(i); 3601 break; 3602 } 3603 } 3604 } 3605 3606 // If the caller didn't request filter information, 3607 // drop them now so we don't have to 3608 // marshall/unmarshall it. 3609 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3610 N = results.size(); 3611 for (int i=0; i<N; i++) { 3612 results.get(i).filter = null; 3613 } 3614 } 3615 3616 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3617 return results; 3618 } 3619 3620 @Override 3621 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3622 int userId) { 3623 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3624 ComponentName comp = intent.getComponent(); 3625 if (comp == null) { 3626 if (intent.getSelector() != null) { 3627 intent = intent.getSelector(); 3628 comp = intent.getComponent(); 3629 } 3630 } 3631 if (comp != null) { 3632 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3633 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3634 if (ai != null) { 3635 ResolveInfo ri = new ResolveInfo(); 3636 ri.activityInfo = ai; 3637 list.add(ri); 3638 } 3639 return list; 3640 } 3641 3642 // reader 3643 synchronized (mPackages) { 3644 String pkgName = intent.getPackage(); 3645 if (pkgName == null) { 3646 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3647 } 3648 final PackageParser.Package pkg = mPackages.get(pkgName); 3649 if (pkg != null) { 3650 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3651 userId); 3652 } 3653 return null; 3654 } 3655 } 3656 3657 @Override 3658 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3659 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3660 if (!sUserManager.exists(userId)) return null; 3661 if (query != null) { 3662 if (query.size() >= 1) { 3663 // If there is more than one service with the same priority, 3664 // just arbitrarily pick the first one. 3665 return query.get(0); 3666 } 3667 } 3668 return null; 3669 } 3670 3671 @Override 3672 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3673 int userId) { 3674 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3675 ComponentName comp = intent.getComponent(); 3676 if (comp == null) { 3677 if (intent.getSelector() != null) { 3678 intent = intent.getSelector(); 3679 comp = intent.getComponent(); 3680 } 3681 } 3682 if (comp != null) { 3683 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3684 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3685 if (si != null) { 3686 final ResolveInfo ri = new ResolveInfo(); 3687 ri.serviceInfo = si; 3688 list.add(ri); 3689 } 3690 return list; 3691 } 3692 3693 // reader 3694 synchronized (mPackages) { 3695 String pkgName = intent.getPackage(); 3696 if (pkgName == null) { 3697 return mServices.queryIntent(intent, resolvedType, flags, userId); 3698 } 3699 final PackageParser.Package pkg = mPackages.get(pkgName); 3700 if (pkg != null) { 3701 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3702 userId); 3703 } 3704 return null; 3705 } 3706 } 3707 3708 @Override 3709 public List<ResolveInfo> queryIntentContentProviders( 3710 Intent intent, String resolvedType, int flags, int userId) { 3711 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3712 ComponentName comp = intent.getComponent(); 3713 if (comp == null) { 3714 if (intent.getSelector() != null) { 3715 intent = intent.getSelector(); 3716 comp = intent.getComponent(); 3717 } 3718 } 3719 if (comp != null) { 3720 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3721 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3722 if (pi != null) { 3723 final ResolveInfo ri = new ResolveInfo(); 3724 ri.providerInfo = pi; 3725 list.add(ri); 3726 } 3727 return list; 3728 } 3729 3730 // reader 3731 synchronized (mPackages) { 3732 String pkgName = intent.getPackage(); 3733 if (pkgName == null) { 3734 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3735 } 3736 final PackageParser.Package pkg = mPackages.get(pkgName); 3737 if (pkg != null) { 3738 return mProviders.queryIntentForPackage( 3739 intent, resolvedType, flags, pkg.providers, userId); 3740 } 3741 return null; 3742 } 3743 } 3744 3745 @Override 3746 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3747 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3748 3749 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3750 3751 // writer 3752 synchronized (mPackages) { 3753 ArrayList<PackageInfo> list; 3754 if (listUninstalled) { 3755 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3756 for (PackageSetting ps : mSettings.mPackages.values()) { 3757 PackageInfo pi; 3758 if (ps.pkg != null) { 3759 pi = generatePackageInfo(ps.pkg, flags, userId); 3760 } else { 3761 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3762 } 3763 if (pi != null) { 3764 list.add(pi); 3765 } 3766 } 3767 } else { 3768 list = new ArrayList<PackageInfo>(mPackages.size()); 3769 for (PackageParser.Package p : mPackages.values()) { 3770 PackageInfo pi = generatePackageInfo(p, flags, userId); 3771 if (pi != null) { 3772 list.add(pi); 3773 } 3774 } 3775 } 3776 3777 return new ParceledListSlice<PackageInfo>(list); 3778 } 3779 } 3780 3781 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3782 String[] permissions, boolean[] tmp, int flags, int userId) { 3783 int numMatch = 0; 3784 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3785 for (int i=0; i<permissions.length; i++) { 3786 if (gp.grantedPermissions.contains(permissions[i])) { 3787 tmp[i] = true; 3788 numMatch++; 3789 } else { 3790 tmp[i] = false; 3791 } 3792 } 3793 if (numMatch == 0) { 3794 return; 3795 } 3796 PackageInfo pi; 3797 if (ps.pkg != null) { 3798 pi = generatePackageInfo(ps.pkg, flags, userId); 3799 } else { 3800 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3801 } 3802 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3803 if (numMatch == permissions.length) { 3804 pi.requestedPermissions = permissions; 3805 } else { 3806 pi.requestedPermissions = new String[numMatch]; 3807 numMatch = 0; 3808 for (int i=0; i<permissions.length; i++) { 3809 if (tmp[i]) { 3810 pi.requestedPermissions[numMatch] = permissions[i]; 3811 numMatch++; 3812 } 3813 } 3814 } 3815 } 3816 list.add(pi); 3817 } 3818 3819 @Override 3820 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3821 String[] permissions, int flags, int userId) { 3822 if (!sUserManager.exists(userId)) return null; 3823 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3824 3825 // writer 3826 synchronized (mPackages) { 3827 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3828 boolean[] tmpBools = new boolean[permissions.length]; 3829 if (listUninstalled) { 3830 for (PackageSetting ps : mSettings.mPackages.values()) { 3831 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3832 } 3833 } else { 3834 for (PackageParser.Package pkg : mPackages.values()) { 3835 PackageSetting ps = (PackageSetting)pkg.mExtras; 3836 if (ps != null) { 3837 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3838 userId); 3839 } 3840 } 3841 } 3842 3843 return new ParceledListSlice<PackageInfo>(list); 3844 } 3845 } 3846 3847 @Override 3848 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3849 if (!sUserManager.exists(userId)) return null; 3850 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3851 3852 // writer 3853 synchronized (mPackages) { 3854 ArrayList<ApplicationInfo> list; 3855 if (listUninstalled) { 3856 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3857 for (PackageSetting ps : mSettings.mPackages.values()) { 3858 ApplicationInfo ai; 3859 if (ps.pkg != null) { 3860 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3861 ps.readUserState(userId), userId); 3862 } else { 3863 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3864 } 3865 if (ai != null) { 3866 list.add(ai); 3867 } 3868 } 3869 } else { 3870 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3871 for (PackageParser.Package p : mPackages.values()) { 3872 if (p.mExtras != null) { 3873 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3874 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3875 if (ai != null) { 3876 list.add(ai); 3877 } 3878 } 3879 } 3880 } 3881 3882 return new ParceledListSlice<ApplicationInfo>(list); 3883 } 3884 } 3885 3886 public List<ApplicationInfo> getPersistentApplications(int flags) { 3887 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3888 3889 // reader 3890 synchronized (mPackages) { 3891 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3892 final int userId = UserHandle.getCallingUserId(); 3893 while (i.hasNext()) { 3894 final PackageParser.Package p = i.next(); 3895 if (p.applicationInfo != null 3896 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3897 && (!mSafeMode || isSystemApp(p))) { 3898 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3899 if (ps != null) { 3900 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3901 ps.readUserState(userId), userId); 3902 if (ai != null) { 3903 finalList.add(ai); 3904 } 3905 } 3906 } 3907 } 3908 } 3909 3910 return finalList; 3911 } 3912 3913 @Override 3914 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3915 if (!sUserManager.exists(userId)) return null; 3916 // reader 3917 synchronized (mPackages) { 3918 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3919 PackageSetting ps = provider != null 3920 ? mSettings.mPackages.get(provider.owner.packageName) 3921 : null; 3922 return ps != null 3923 && mSettings.isEnabledLPr(provider.info, flags, userId) 3924 && (!mSafeMode || (provider.info.applicationInfo.flags 3925 &ApplicationInfo.FLAG_SYSTEM) != 0) 3926 ? PackageParser.generateProviderInfo(provider, flags, 3927 ps.readUserState(userId), userId) 3928 : null; 3929 } 3930 } 3931 3932 /** 3933 * @deprecated 3934 */ 3935 @Deprecated 3936 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3937 // reader 3938 synchronized (mPackages) { 3939 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3940 .entrySet().iterator(); 3941 final int userId = UserHandle.getCallingUserId(); 3942 while (i.hasNext()) { 3943 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3944 PackageParser.Provider p = entry.getValue(); 3945 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3946 3947 if (ps != null && p.syncable 3948 && (!mSafeMode || (p.info.applicationInfo.flags 3949 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3950 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3951 ps.readUserState(userId), userId); 3952 if (info != null) { 3953 outNames.add(entry.getKey()); 3954 outInfo.add(info); 3955 } 3956 } 3957 } 3958 } 3959 } 3960 3961 @Override 3962 public List<ProviderInfo> queryContentProviders(String processName, 3963 int uid, int flags) { 3964 ArrayList<ProviderInfo> finalList = null; 3965 // reader 3966 synchronized (mPackages) { 3967 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3968 final int userId = processName != null ? 3969 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3970 while (i.hasNext()) { 3971 final PackageParser.Provider p = i.next(); 3972 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3973 if (ps != null && p.info.authority != null 3974 && (processName == null 3975 || (p.info.processName.equals(processName) 3976 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3977 && mSettings.isEnabledLPr(p.info, flags, userId) 3978 && (!mSafeMode 3979 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3980 if (finalList == null) { 3981 finalList = new ArrayList<ProviderInfo>(3); 3982 } 3983 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3984 ps.readUserState(userId), userId); 3985 if (info != null) { 3986 finalList.add(info); 3987 } 3988 } 3989 } 3990 } 3991 3992 if (finalList != null) { 3993 Collections.sort(finalList, mProviderInitOrderSorter); 3994 } 3995 3996 return finalList; 3997 } 3998 3999 @Override 4000 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4001 int flags) { 4002 // reader 4003 synchronized (mPackages) { 4004 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4005 return PackageParser.generateInstrumentationInfo(i, flags); 4006 } 4007 } 4008 4009 @Override 4010 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4011 int flags) { 4012 ArrayList<InstrumentationInfo> finalList = 4013 new ArrayList<InstrumentationInfo>(); 4014 4015 // reader 4016 synchronized (mPackages) { 4017 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4018 while (i.hasNext()) { 4019 final PackageParser.Instrumentation p = i.next(); 4020 if (targetPackage == null 4021 || targetPackage.equals(p.info.targetPackage)) { 4022 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4023 flags); 4024 if (ii != null) { 4025 finalList.add(ii); 4026 } 4027 } 4028 } 4029 } 4030 4031 return finalList; 4032 } 4033 4034 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4035 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4036 if (overlays == null) { 4037 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4038 return; 4039 } 4040 for (PackageParser.Package opkg : overlays.values()) { 4041 // Not much to do if idmap fails: we already logged the error 4042 // and we certainly don't want to abort installation of pkg simply 4043 // because an overlay didn't fit properly. For these reasons, 4044 // ignore the return value of createIdmapForPackagePairLI. 4045 createIdmapForPackagePairLI(pkg, opkg); 4046 } 4047 } 4048 4049 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4050 PackageParser.Package opkg) { 4051 if (!opkg.mTrustedOverlay) { 4052 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4053 opkg.baseCodePath + ": overlay not trusted"); 4054 return false; 4055 } 4056 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4057 if (overlaySet == null) { 4058 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4059 opkg.baseCodePath + " but target package has no known overlays"); 4060 return false; 4061 } 4062 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4063 // TODO: generate idmap for split APKs 4064 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4065 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4066 + opkg.baseCodePath); 4067 return false; 4068 } 4069 PackageParser.Package[] overlayArray = 4070 overlaySet.values().toArray(new PackageParser.Package[0]); 4071 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4072 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4073 return p1.mOverlayPriority - p2.mOverlayPriority; 4074 } 4075 }; 4076 Arrays.sort(overlayArray, cmp); 4077 4078 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4079 int i = 0; 4080 for (PackageParser.Package p : overlayArray) { 4081 pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir; 4082 } 4083 return true; 4084 } 4085 4086 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4087 final File[] files = dir.listFiles(); 4088 if (ArrayUtils.isEmpty(files)) { 4089 Log.d(TAG, "No files in app dir " + dir); 4090 return; 4091 } 4092 4093 if (DEBUG_PACKAGE_SCANNING) { 4094 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4095 + " flags=0x" + Integer.toHexString(flags)); 4096 } 4097 4098 for (File file : files) { 4099 if (!isPackageFilename(file)) { 4100 // Ignore entries which are not apk's 4101 continue; 4102 } 4103 PackageParser.Package pkg = scanPackageLI(file, 4104 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null); 4105 // Don't mess around with apps in system partition. 4106 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4107 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 4108 // Delete the apk 4109 Slog.w(TAG, "Cleaning up failed install of " + file); 4110 file.delete(); 4111 } 4112 } 4113 } 4114 4115 private static File getSettingsProblemFile() { 4116 File dataDir = Environment.getDataDirectory(); 4117 File systemDir = new File(dataDir, "system"); 4118 File fname = new File(systemDir, "uiderrors.txt"); 4119 return fname; 4120 } 4121 4122 static void reportSettingsProblem(int priority, String msg) { 4123 try { 4124 File fname = getSettingsProblemFile(); 4125 FileOutputStream out = new FileOutputStream(fname, true); 4126 PrintWriter pw = new FastPrintWriter(out); 4127 SimpleDateFormat formatter = new SimpleDateFormat(); 4128 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4129 pw.println(dateString + ": " + msg); 4130 pw.close(); 4131 FileUtils.setPermissions( 4132 fname.toString(), 4133 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4134 -1, -1); 4135 } catch (java.io.IOException e) { 4136 } 4137 Slog.println(priority, TAG, msg); 4138 } 4139 4140 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 4141 PackageParser.Package pkg, File srcFile, int parseFlags) { 4142 if (ps != null 4143 && ps.codePath.equals(srcFile) 4144 && ps.timeStamp == srcFile.lastModified() 4145 && !isCompatSignatureUpdateNeeded(pkg)) { 4146 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4147 if (ps.signatures.mSignatures != null 4148 && ps.signatures.mSignatures.length != 0 4149 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4150 // Optimization: reuse the existing cached certificates 4151 // if the package appears to be unchanged. 4152 pkg.mSignatures = ps.signatures.mSignatures; 4153 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4154 pkg.mSigningKeys = ksms.getPublicKeysFromKeySet(mSigningKeySetId); 4155 return true; 4156 } 4157 4158 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 4159 } else { 4160 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4161 } 4162 4163 try { 4164 pp.collectCertificates(pkg, parseFlags); 4165 pp.collectManifestDigest(pkg); 4166 } catch (PackageParserException e) { 4167 mLastScanError = e.error; 4168 return false; 4169 } 4170 return true; 4171 } 4172 4173 /* 4174 * Scan a package and return the newly parsed package. 4175 * Returns null in case of errors and the error code is stored in mLastScanError 4176 */ 4177 private PackageParser.Package scanPackageLI(File scanFile, 4178 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4179 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 4180 String scanPath = scanFile.getPath(); 4181 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath); 4182 parseFlags |= mDefParseFlags; 4183 PackageParser pp = new PackageParser(); 4184 pp.setSeparateProcesses(mSeparateProcesses); 4185 pp.setOnlyCoreApps(mOnlyCore); 4186 pp.setDisplayMetrics(mMetrics); 4187 4188 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4189 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4190 } 4191 4192 final PackageParser.Package pkg; 4193 try { 4194 pkg = pp.parseMonolithicPackage(scanFile, parseFlags); 4195 } catch (PackageParserException e) { 4196 mLastScanError = e.error; 4197 return null; 4198 } 4199 4200 PackageSetting ps = null; 4201 PackageSetting updatedPkg; 4202 // reader 4203 synchronized (mPackages) { 4204 // Look to see if we already know about this package. 4205 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4206 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4207 // This package has been renamed to its original name. Let's 4208 // use that. 4209 ps = mSettings.peekPackageLPr(oldName); 4210 } 4211 // If there was no original package, see one for the real package name. 4212 if (ps == null) { 4213 ps = mSettings.peekPackageLPr(pkg.packageName); 4214 } 4215 // Check to see if this package could be hiding/updating a system 4216 // package. Must look for it either under the original or real 4217 // package name depending on our state. 4218 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4219 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4220 } 4221 boolean updatedPkgBetter = false; 4222 // First check if this is a system package that may involve an update 4223 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4224 if (ps != null && !ps.codePath.equals(scanFile)) { 4225 // The path has changed from what was last scanned... check the 4226 // version of the new path against what we have stored to determine 4227 // what to do. 4228 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4229 if (pkg.mVersionCode < ps.versionCode) { 4230 // The system package has been updated and the code path does not match 4231 // Ignore entry. Skip it. 4232 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4233 + " ignored: updated version " + ps.versionCode 4234 + " better than this " + pkg.mVersionCode); 4235 if (!updatedPkg.codePath.equals(scanFile)) { 4236 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4237 + ps.name + " changing from " + updatedPkg.codePathString 4238 + " to " + scanFile); 4239 updatedPkg.codePath = scanFile; 4240 updatedPkg.codePathString = scanFile.toString(); 4241 // This is the point at which we know that the system-disk APK 4242 // for this package has moved during a reboot (e.g. due to an OTA), 4243 // so we need to reevaluate it for privilege policy. 4244 if (locationIsPrivileged(scanFile)) { 4245 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4246 } 4247 } 4248 updatedPkg.pkg = pkg; 4249 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4250 return null; 4251 } else { 4252 // The current app on the system partition is better than 4253 // what we have updated to on the data partition; switch 4254 // back to the system partition version. 4255 // At this point, its safely assumed that package installation for 4256 // apps in system partition will go through. If not there won't be a working 4257 // version of the app 4258 // writer 4259 synchronized (mPackages) { 4260 // Just remove the loaded entries from package lists. 4261 mPackages.remove(ps.name); 4262 } 4263 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4264 + "reverting from " + ps.codePathString 4265 + ": new version " + pkg.mVersionCode 4266 + " better than installed " + ps.versionCode); 4267 4268 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4269 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4270 getAppInstructionSetFromSettings(ps)); 4271 synchronized (mInstallLock) { 4272 args.cleanUpResourcesLI(); 4273 } 4274 synchronized (mPackages) { 4275 mSettings.enableSystemPackageLPw(ps.name); 4276 } 4277 updatedPkgBetter = true; 4278 } 4279 } 4280 } 4281 4282 if (updatedPkg != null) { 4283 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4284 // initially 4285 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4286 4287 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4288 // flag set initially 4289 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4290 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4291 } 4292 } 4293 // Verify certificates against what was last scanned 4294 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 4295 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 4296 return null; 4297 } 4298 4299 /* 4300 * A new system app appeared, but we already had a non-system one of the 4301 * same name installed earlier. 4302 */ 4303 boolean shouldHideSystemApp = false; 4304 if (updatedPkg == null && ps != null 4305 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4306 /* 4307 * Check to make sure the signatures match first. If they don't, 4308 * wipe the installed application and its data. 4309 */ 4310 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4311 != PackageManager.SIGNATURE_MATCH) { 4312 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4313 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4314 ps = null; 4315 } else { 4316 /* 4317 * If the newly-added system app is an older version than the 4318 * already installed version, hide it. It will be scanned later 4319 * and re-added like an update. 4320 */ 4321 if (pkg.mVersionCode < ps.versionCode) { 4322 shouldHideSystemApp = true; 4323 } else { 4324 /* 4325 * The newly found system app is a newer version that the 4326 * one previously installed. Simply remove the 4327 * already-installed application and replace it with our own 4328 * while keeping the application data. 4329 */ 4330 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4331 + ps.codePathString + ": new version " + pkg.mVersionCode 4332 + " better than installed " + ps.versionCode); 4333 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4334 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4335 getAppInstructionSetFromSettings(ps)); 4336 synchronized (mInstallLock) { 4337 args.cleanUpResourcesLI(); 4338 } 4339 } 4340 } 4341 } 4342 4343 // The apk is forward locked (not public) if its code and resources 4344 // are kept in different files. (except for app in either system or 4345 // vendor path). 4346 // TODO grab this value from PackageSettings 4347 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4348 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4349 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4350 } 4351 } 4352 4353 final String baseCodePath = pkg.baseCodePath; 4354 final String[] splitCodePaths = pkg.splitCodePaths; 4355 4356 // TODO: extend to support forward-locked splits 4357 String baseResPath = null; 4358 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4359 if (ps != null && ps.resourcePathString != null) { 4360 baseResPath = ps.resourcePathString; 4361 } else { 4362 // Should not happen at all. Just log an error. 4363 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4364 } 4365 } else { 4366 baseResPath = pkg.baseCodePath; 4367 } 4368 4369 // Set application objects path explicitly. 4370 pkg.applicationInfo.sourceDir = baseCodePath; 4371 pkg.applicationInfo.publicSourceDir = baseResPath; 4372 pkg.applicationInfo.splitSourceDirs = splitCodePaths; 4373 pkg.applicationInfo.splitPublicSourceDirs = splitCodePaths; 4374 4375 // Note that we invoke the following method only if we are about to unpack an application 4376 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4377 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4378 4379 /* 4380 * If the system app should be overridden by a previously installed 4381 * data, hide the system app now and let the /data/app scan pick it up 4382 * again. 4383 */ 4384 if (shouldHideSystemApp) { 4385 synchronized (mPackages) { 4386 /* 4387 * We have to grant systems permissions before we hide, because 4388 * grantPermissions will assume the package update is trying to 4389 * expand its permissions. 4390 */ 4391 grantPermissionsLPw(pkg, true); 4392 mSettings.disableSystemPackageLPw(pkg.packageName); 4393 } 4394 } 4395 4396 return scannedPkg; 4397 } 4398 4399 private static String fixProcessName(String defProcessName, 4400 String processName, int uid) { 4401 if (processName == null) { 4402 return defProcessName; 4403 } 4404 return processName; 4405 } 4406 4407 private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) { 4408 if (pkgSetting.signatures.mSignatures != null) { 4409 // Already existing package. Make sure signatures match 4410 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4411 == PackageManager.SIGNATURE_MATCH; 4412 if (!match) { 4413 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4414 == PackageManager.SIGNATURE_MATCH; 4415 } 4416 if (!match) { 4417 Slog.e(TAG, "Package " + pkg.packageName 4418 + " signatures do not match the previously installed version; ignoring!"); 4419 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4420 return false; 4421 } 4422 } 4423 4424 // Check for shared user signatures 4425 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4426 // Already existing package. Make sure signatures match 4427 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4428 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4429 if (!match) { 4430 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4431 == PackageManager.SIGNATURE_MATCH; 4432 } 4433 if (!match) { 4434 Slog.e(TAG, "Package " + pkg.packageName 4435 + " has no signatures that match those in shared user " 4436 + pkgSetting.sharedUser.name + "; ignoring!"); 4437 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4438 return false; 4439 } 4440 } 4441 return true; 4442 } 4443 4444 /** 4445 * Enforces that only the system UID or root's UID can call a method exposed 4446 * via Binder. 4447 * 4448 * @param message used as message if SecurityException is thrown 4449 * @throws SecurityException if the caller is not system or root 4450 */ 4451 private static final void enforceSystemOrRoot(String message) { 4452 final int uid = Binder.getCallingUid(); 4453 if (uid != Process.SYSTEM_UID && uid != 0) { 4454 throw new SecurityException(message); 4455 } 4456 } 4457 4458 @Override 4459 public void performBootDexOpt() { 4460 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4461 4462 final HashSet<PackageParser.Package> pkgs; 4463 synchronized (mPackages) { 4464 pkgs = mDeferredDexOpt; 4465 mDeferredDexOpt = null; 4466 } 4467 4468 if (pkgs != null) { 4469 // Filter out packages that aren't recently used. 4470 // 4471 // The exception is first boot of a non-eng device, which 4472 // should do a full dexopt. 4473 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4474 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4475 // TODO: add a property to control this? 4476 long dexOptLRUThresholdInMinutes; 4477 if (eng) { 4478 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4479 } else { 4480 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4481 } 4482 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4483 4484 int total = pkgs.size(); 4485 int skipped = 0; 4486 long now = System.currentTimeMillis(); 4487 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4488 PackageParser.Package pkg = i.next(); 4489 long then = pkg.mLastPackageUsageTimeInMills; 4490 if (then + dexOptLRUThresholdInMills < now) { 4491 if (DEBUG_DEXOPT) { 4492 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4493 ((then == 0) ? "never" : new Date(then))); 4494 } 4495 i.remove(); 4496 skipped++; 4497 } 4498 } 4499 if (DEBUG_DEXOPT) { 4500 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4501 } 4502 } 4503 4504 int i = 0; 4505 for (PackageParser.Package pkg : pkgs) { 4506 i++; 4507 if (DEBUG_DEXOPT) { 4508 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4509 + ": " + pkg.packageName); 4510 } 4511 if (!isFirstBoot()) { 4512 try { 4513 ActivityManagerNative.getDefault().showBootMessage( 4514 mContext.getResources().getString( 4515 R.string.android_upgrading_apk, 4516 i, pkgs.size()), true); 4517 } catch (RemoteException e) { 4518 } 4519 } 4520 PackageParser.Package p = pkg; 4521 synchronized (mInstallLock) { 4522 if (p.mDexOptNeeded) { 4523 performDexOptLI(p, false /* force dex */, false /* defer */, 4524 true /* include dependencies */); 4525 } 4526 } 4527 } 4528 } 4529 } 4530 4531 @Override 4532 public boolean performDexOpt(String packageName) { 4533 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4534 return performDexOpt(packageName, true); 4535 } 4536 4537 public boolean performDexOpt(String packageName, boolean updateUsage) { 4538 4539 PackageParser.Package p; 4540 synchronized (mPackages) { 4541 p = mPackages.get(packageName); 4542 if (p == null) { 4543 return false; 4544 } 4545 if (updateUsage) { 4546 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4547 } 4548 mPackageUsage.write(false); 4549 if (!p.mDexOptNeeded) { 4550 return false; 4551 } 4552 } 4553 4554 synchronized (mInstallLock) { 4555 return performDexOptLI(p, false /* force dex */, false /* defer */, 4556 true /* include dependencies */) == DEX_OPT_PERFORMED; 4557 } 4558 } 4559 4560 public HashSet<String> getPackagesThatNeedDexOpt() { 4561 HashSet<String> pkgs = null; 4562 synchronized (mPackages) { 4563 for (PackageParser.Package p : mPackages.values()) { 4564 if (DEBUG_DEXOPT) { 4565 Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded); 4566 } 4567 if (!p.mDexOptNeeded) { 4568 continue; 4569 } 4570 if (pkgs == null) { 4571 pkgs = new HashSet<String>(); 4572 } 4573 pkgs.add(p.packageName); 4574 } 4575 } 4576 return pkgs; 4577 } 4578 4579 public void shutdown() { 4580 mPackageUsage.write(true); 4581 } 4582 4583 private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, 4584 boolean forceDex, boolean defer, HashSet<String> done) { 4585 for (int i=0; i<libs.size(); i++) { 4586 PackageParser.Package libPkg; 4587 String libName; 4588 synchronized (mPackages) { 4589 libName = libs.get(i); 4590 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4591 if (lib != null && lib.apk != null) { 4592 libPkg = mPackages.get(lib.apk); 4593 } else { 4594 libPkg = null; 4595 } 4596 } 4597 if (libPkg != null && !done.contains(libName)) { 4598 performDexOptLI(libPkg, instructionSet, forceDex, defer, done); 4599 } 4600 } 4601 } 4602 4603 static final int DEX_OPT_SKIPPED = 0; 4604 static final int DEX_OPT_PERFORMED = 1; 4605 static final int DEX_OPT_DEFERRED = 2; 4606 static final int DEX_OPT_FAILED = -1; 4607 4608 private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride, 4609 boolean forceDex, boolean defer, HashSet<String> done) { 4610 final String instructionSet = instructionSetOverride != null ? 4611 instructionSetOverride : getAppInstructionSet(pkg.applicationInfo); 4612 4613 if (done != null) { 4614 done.add(pkg.packageName); 4615 if (pkg.usesLibraries != null) { 4616 performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done); 4617 } 4618 if (pkg.usesOptionalLibraries != null) { 4619 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done); 4620 } 4621 } 4622 4623 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) { 4624 final Collection<String> paths = pkg.getAllCodePaths(); 4625 for (String path : paths) { 4626 try { 4627 boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path, 4628 pkg.packageName, instructionSet, defer); 4629 // There are three basic cases here: 4630 // 1.) we need to dexopt, either because we are forced or it is needed 4631 // 2.) we are defering a needed dexopt 4632 // 3.) we are skipping an unneeded dexopt 4633 if (forceDex || (!defer && isDexOptNeededInternal)) { 4634 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName); 4635 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4636 int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4637 pkg.packageName, instructionSet); 4638 // Note that we ran dexopt, since rerunning will 4639 // probably just result in an error again. 4640 pkg.mDexOptNeeded = false; 4641 if (ret < 0) { 4642 return DEX_OPT_FAILED; 4643 } 4644 return DEX_OPT_PERFORMED; 4645 } 4646 if (defer && isDexOptNeededInternal) { 4647 if (mDeferredDexOpt == null) { 4648 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4649 } 4650 mDeferredDexOpt.add(pkg); 4651 return DEX_OPT_DEFERRED; 4652 } 4653 pkg.mDexOptNeeded = false; 4654 return DEX_OPT_SKIPPED; 4655 } catch (FileNotFoundException e) { 4656 Slog.w(TAG, "Apk not found for dexopt: " + path); 4657 return DEX_OPT_FAILED; 4658 } catch (IOException e) { 4659 Slog.w(TAG, "IOException reading apk: " + path, e); 4660 return DEX_OPT_FAILED; 4661 } catch (StaleDexCacheError e) { 4662 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4663 return DEX_OPT_FAILED; 4664 } catch (Exception e) { 4665 Slog.w(TAG, "Exception when doing dexopt : ", e); 4666 return DEX_OPT_FAILED; 4667 } 4668 } 4669 } 4670 return DEX_OPT_SKIPPED; 4671 } 4672 4673 private String getAppInstructionSet(ApplicationInfo info) { 4674 String instructionSet = getPreferredInstructionSet(); 4675 4676 if (info.cpuAbi != null) { 4677 instructionSet = VMRuntime.getInstructionSet(info.cpuAbi); 4678 } 4679 4680 return instructionSet; 4681 } 4682 4683 private String getAppInstructionSetFromSettings(PackageSetting ps) { 4684 String instructionSet = getPreferredInstructionSet(); 4685 4686 if (ps.cpuAbiString != null) { 4687 instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 4688 } 4689 4690 return instructionSet; 4691 } 4692 4693 private static String getPreferredInstructionSet() { 4694 if (sPreferredInstructionSet == null) { 4695 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4696 } 4697 4698 return sPreferredInstructionSet; 4699 } 4700 4701 private static List<String> getAllInstructionSets() { 4702 final String[] allAbis = Build.SUPPORTED_ABIS; 4703 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4704 4705 for (String abi : allAbis) { 4706 final String instructionSet = VMRuntime.getInstructionSet(abi); 4707 if (!allInstructionSets.contains(instructionSet)) { 4708 allInstructionSets.add(instructionSet); 4709 } 4710 } 4711 4712 return allInstructionSets; 4713 } 4714 4715 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4716 boolean inclDependencies) { 4717 HashSet<String> done; 4718 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4719 done = new HashSet<String>(); 4720 done.add(pkg.packageName); 4721 } else { 4722 done = null; 4723 } 4724 return performDexOptLI(pkg, null /* instruction set override */, forceDex, defer, done); 4725 } 4726 4727 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4728 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4729 Slog.w(TAG, "Unable to update from " + oldPkg.name 4730 + " to " + newPkg.packageName 4731 + ": old package not in system partition"); 4732 return false; 4733 } else if (mPackages.get(oldPkg.name) != null) { 4734 Slog.w(TAG, "Unable to update from " + oldPkg.name 4735 + " to " + newPkg.packageName 4736 + ": old package still exists"); 4737 return false; 4738 } 4739 return true; 4740 } 4741 4742 File getDataPathForUser(int userId) { 4743 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4744 } 4745 4746 private File getDataPathForPackage(String packageName, int userId) { 4747 /* 4748 * Until we fully support multiple users, return the directory we 4749 * previously would have. The PackageManagerTests will need to be 4750 * revised when this is changed back.. 4751 */ 4752 if (userId == 0) { 4753 return new File(mAppDataDir, packageName); 4754 } else { 4755 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4756 + File.separator + packageName); 4757 } 4758 } 4759 4760 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4761 int[] users = sUserManager.getUserIds(); 4762 int res = mInstaller.install(packageName, uid, uid, seinfo); 4763 if (res < 0) { 4764 return res; 4765 } 4766 for (int user : users) { 4767 if (user != 0) { 4768 res = mInstaller.createUserData(packageName, 4769 UserHandle.getUid(user, uid), user, seinfo); 4770 if (res < 0) { 4771 return res; 4772 } 4773 } 4774 } 4775 return res; 4776 } 4777 4778 private int removeDataDirsLI(String packageName) { 4779 int[] users = sUserManager.getUserIds(); 4780 int res = 0; 4781 for (int user : users) { 4782 int resInner = mInstaller.remove(packageName, user); 4783 if (resInner < 0) { 4784 res = resInner; 4785 } 4786 } 4787 4788 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4789 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4790 if (!nativeLibraryFile.delete()) { 4791 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4792 } 4793 4794 return res; 4795 } 4796 4797 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4798 PackageParser.Package changingLib) { 4799 if (file.path != null) { 4800 usesLibraryFiles.add(file.path); 4801 return; 4802 } 4803 PackageParser.Package p = mPackages.get(file.apk); 4804 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4805 // If we are doing this while in the middle of updating a library apk, 4806 // then we need to make sure to use that new apk for determining the 4807 // dependencies here. (We haven't yet finished committing the new apk 4808 // to the package manager state.) 4809 if (p == null || p.packageName.equals(changingLib.packageName)) { 4810 p = changingLib; 4811 } 4812 } 4813 if (p != null) { 4814 usesLibraryFiles.addAll(p.getAllCodePaths()); 4815 } 4816 } 4817 4818 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4819 PackageParser.Package changingLib) { 4820 // We might be upgrading from a version of the platform that did not 4821 // provide per-package native library directories for system apps. 4822 // Fix that up here. 4823 if (isSystemApp(pkg)) { 4824 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4825 setInternalAppNativeLibraryPath(pkg, ps); 4826 } 4827 4828 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4829 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4830 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4831 for (int i=0; i<N; i++) { 4832 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4833 if (file == null) { 4834 Slog.e(TAG, "Package " + pkg.packageName 4835 + " requires unavailable shared library " 4836 + pkg.usesLibraries.get(i) + "; failing!"); 4837 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4838 return false; 4839 } 4840 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4841 } 4842 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4843 for (int i=0; i<N; i++) { 4844 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4845 if (file == null) { 4846 Slog.w(TAG, "Package " + pkg.packageName 4847 + " desires unavailable shared library " 4848 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4849 } else { 4850 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4851 } 4852 } 4853 N = usesLibraryFiles.size(); 4854 if (N > 0) { 4855 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4856 } else { 4857 pkg.usesLibraryFiles = null; 4858 } 4859 } 4860 return true; 4861 } 4862 4863 private static boolean hasString(List<String> list, List<String> which) { 4864 if (list == null) { 4865 return false; 4866 } 4867 for (int i=list.size()-1; i>=0; i--) { 4868 for (int j=which.size()-1; j>=0; j--) { 4869 if (which.get(j).equals(list.get(i))) { 4870 return true; 4871 } 4872 } 4873 } 4874 return false; 4875 } 4876 4877 private void updateAllSharedLibrariesLPw() { 4878 for (PackageParser.Package pkg : mPackages.values()) { 4879 updateSharedLibrariesLPw(pkg, null); 4880 } 4881 } 4882 4883 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4884 PackageParser.Package changingPkg) { 4885 ArrayList<PackageParser.Package> res = null; 4886 for (PackageParser.Package pkg : mPackages.values()) { 4887 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4888 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4889 if (res == null) { 4890 res = new ArrayList<PackageParser.Package>(); 4891 } 4892 res.add(pkg); 4893 updateSharedLibrariesLPw(pkg, changingPkg); 4894 } 4895 } 4896 return res; 4897 } 4898 4899 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4900 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4901 final File scanFile = new File(pkg.codePath); 4902 if (pkg.applicationInfo.sourceDir == null || 4903 pkg.applicationInfo.publicSourceDir == null) { 4904 // Bail out. The resource and code paths haven't been set. 4905 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4906 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4907 return null; 4908 } 4909 4910 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4911 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4912 } 4913 4914 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4915 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4916 } 4917 4918 if (mCustomResolverComponentName != null && 4919 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4920 setUpCustomResolverActivity(pkg); 4921 } 4922 4923 if (pkg.packageName.equals("android")) { 4924 synchronized (mPackages) { 4925 if (mAndroidApplication != null) { 4926 Slog.w(TAG, "*************************************************"); 4927 Slog.w(TAG, "Core android package being redefined. Skipping."); 4928 Slog.w(TAG, " file=" + scanFile); 4929 Slog.w(TAG, "*************************************************"); 4930 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4931 return null; 4932 } 4933 4934 // Set up information for our fall-back user intent resolution activity. 4935 mPlatformPackage = pkg; 4936 pkg.mVersionCode = mSdkVersion; 4937 mAndroidApplication = pkg.applicationInfo; 4938 4939 if (!mResolverReplaced) { 4940 mResolveActivity.applicationInfo = mAndroidApplication; 4941 mResolveActivity.name = ResolverActivity.class.getName(); 4942 mResolveActivity.packageName = mAndroidApplication.packageName; 4943 mResolveActivity.processName = "system:ui"; 4944 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4945 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 4946 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4947 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 4948 mResolveActivity.exported = true; 4949 mResolveActivity.enabled = true; 4950 mResolveInfo.activityInfo = mResolveActivity; 4951 mResolveInfo.priority = 0; 4952 mResolveInfo.preferredOrder = 0; 4953 mResolveInfo.match = 0; 4954 mResolveComponentName = new ComponentName( 4955 mAndroidApplication.packageName, mResolveActivity.name); 4956 } 4957 } 4958 } 4959 4960 if (DEBUG_PACKAGE_SCANNING) { 4961 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4962 Log.d(TAG, "Scanning package " + pkg.packageName); 4963 } 4964 4965 if (mPackages.containsKey(pkg.packageName) 4966 || mSharedLibraries.containsKey(pkg.packageName)) { 4967 Slog.w(TAG, "Application package " + pkg.packageName 4968 + " already installed. Skipping duplicate."); 4969 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4970 return null; 4971 } 4972 4973 // Initialize package source and resource directories 4974 File destCodeFile = new File(pkg.applicationInfo.sourceDir); 4975 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir); 4976 4977 SharedUserSetting suid = null; 4978 PackageSetting pkgSetting = null; 4979 4980 if (!isSystemApp(pkg)) { 4981 // Only system apps can use these features. 4982 pkg.mOriginalPackages = null; 4983 pkg.mRealPackage = null; 4984 pkg.mAdoptPermissions = null; 4985 } 4986 4987 // writer 4988 synchronized (mPackages) { 4989 if (pkg.mSharedUserId != null) { 4990 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 4991 if (suid == null) { 4992 Slog.w(TAG, "Creating application package " + pkg.packageName 4993 + " for shared user failed"); 4994 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4995 return null; 4996 } 4997 if (DEBUG_PACKAGE_SCANNING) { 4998 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4999 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5000 + "): packages=" + suid.packages); 5001 } 5002 } 5003 5004 // Check if we are renaming from an original package name. 5005 PackageSetting origPackage = null; 5006 String realName = null; 5007 if (pkg.mOriginalPackages != null) { 5008 // This package may need to be renamed to a previously 5009 // installed name. Let's check on that... 5010 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5011 if (pkg.mOriginalPackages.contains(renamed)) { 5012 // This package had originally been installed as the 5013 // original name, and we have already taken care of 5014 // transitioning to the new one. Just update the new 5015 // one to continue using the old name. 5016 realName = pkg.mRealPackage; 5017 if (!pkg.packageName.equals(renamed)) { 5018 // Callers into this function may have already taken 5019 // care of renaming the package; only do it here if 5020 // it is not already done. 5021 pkg.setPackageName(renamed); 5022 } 5023 5024 } else { 5025 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5026 if ((origPackage = mSettings.peekPackageLPr( 5027 pkg.mOriginalPackages.get(i))) != null) { 5028 // We do have the package already installed under its 5029 // original name... should we use it? 5030 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5031 // New package is not compatible with original. 5032 origPackage = null; 5033 continue; 5034 } else if (origPackage.sharedUser != null) { 5035 // Make sure uid is compatible between packages. 5036 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5037 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5038 + " to " + pkg.packageName + ": old uid " 5039 + origPackage.sharedUser.name 5040 + " differs from " + pkg.mSharedUserId); 5041 origPackage = null; 5042 continue; 5043 } 5044 } else { 5045 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5046 + pkg.packageName + " to old name " + origPackage.name); 5047 } 5048 break; 5049 } 5050 } 5051 } 5052 } 5053 5054 if (mTransferedPackages.contains(pkg.packageName)) { 5055 Slog.w(TAG, "Package " + pkg.packageName 5056 + " was transferred to another, but its .apk remains"); 5057 } 5058 5059 // Just create the setting, don't add it yet. For already existing packages 5060 // the PkgSetting exists already and doesn't have to be created. 5061 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5062 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 5063 pkg.applicationInfo.cpuAbi, 5064 pkg.applicationInfo.flags, user, false); 5065 if (pkgSetting == null) { 5066 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 5067 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5068 return null; 5069 } 5070 5071 if (pkgSetting.origPackage != null) { 5072 // If we are first transitioning from an original package, 5073 // fix up the new package's name now. We need to do this after 5074 // looking up the package under its new name, so getPackageLP 5075 // can take care of fiddling things correctly. 5076 pkg.setPackageName(origPackage.name); 5077 5078 // File a report about this. 5079 String msg = "New package " + pkgSetting.realName 5080 + " renamed to replace old package " + pkgSetting.name; 5081 reportSettingsProblem(Log.WARN, msg); 5082 5083 // Make a note of it. 5084 mTransferedPackages.add(origPackage.name); 5085 5086 // No longer need to retain this. 5087 pkgSetting.origPackage = null; 5088 } 5089 5090 if (realName != null) { 5091 // Make a note of it. 5092 mTransferedPackages.add(pkg.packageName); 5093 } 5094 5095 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5096 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5097 } 5098 5099 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5100 // Check all shared libraries and map to their actual file path. 5101 // We only do this here for apps not on a system dir, because those 5102 // are the only ones that can fail an install due to this. We 5103 // will take care of the system apps by updating all of their 5104 // library paths after the scan is done. 5105 if (!updateSharedLibrariesLPw(pkg, null)) { 5106 return null; 5107 } 5108 } 5109 5110 if (mFoundPolicyFile) { 5111 SELinuxMMAC.assignSeinfoValue(pkg); 5112 } 5113 5114 pkg.applicationInfo.uid = pkgSetting.appId; 5115 pkg.mExtras = pkgSetting; 5116 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5117 if (!verifySignaturesLP(pkgSetting, pkg)) { 5118 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5119 return null; 5120 } 5121 // The signature has changed, but this package is in the system 5122 // image... let's recover! 5123 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5124 // However... if this package is part of a shared user, but it 5125 // doesn't match the signature of the shared user, let's fail. 5126 // What this means is that you can't change the signatures 5127 // associated with an overall shared user, which doesn't seem all 5128 // that unreasonable. 5129 if (pkgSetting.sharedUser != null) { 5130 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5131 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5132 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 5133 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 5134 return null; 5135 } 5136 } 5137 // File a report about this. 5138 String msg = "System package " + pkg.packageName 5139 + " signature changed; retaining data."; 5140 reportSettingsProblem(Log.WARN, msg); 5141 } 5142 } else { 5143 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5144 Slog.e(TAG, "Package " + pkg.packageName 5145 + " upgrade keys do not match the previously installed version; "); 5146 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5147 return null; 5148 } else { 5149 // signatures may have changed as result of upgrade 5150 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5151 } 5152 } 5153 // Verify that this new package doesn't have any content providers 5154 // that conflict with existing packages. Only do this if the 5155 // package isn't already installed, since we don't want to break 5156 // things that are installed. 5157 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5158 final int N = pkg.providers.size(); 5159 int i; 5160 for (i=0; i<N; i++) { 5161 PackageParser.Provider p = pkg.providers.get(i); 5162 if (p.info.authority != null) { 5163 String names[] = p.info.authority.split(";"); 5164 for (int j = 0; j < names.length; j++) { 5165 if (mProvidersByAuthority.containsKey(names[j])) { 5166 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5167 Slog.w(TAG, "Can't install because provider name " + names[j] + 5168 " (in package " + pkg.applicationInfo.packageName + 5169 ") is already used by " 5170 + ((other != null && other.getComponentName() != null) 5171 ? other.getComponentName().getPackageName() : "?")); 5172 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 5173 return null; 5174 } 5175 } 5176 } 5177 } 5178 } 5179 5180 if (pkg.mAdoptPermissions != null) { 5181 // This package wants to adopt ownership of permissions from 5182 // another package. 5183 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5184 final String origName = pkg.mAdoptPermissions.get(i); 5185 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5186 if (orig != null) { 5187 if (verifyPackageUpdateLPr(orig, pkg)) { 5188 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5189 + pkg.packageName); 5190 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5191 } 5192 } 5193 } 5194 } 5195 } 5196 5197 final String pkgName = pkg.packageName; 5198 5199 final long scanFileTime = scanFile.lastModified(); 5200 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5201 pkg.applicationInfo.processName = fixProcessName( 5202 pkg.applicationInfo.packageName, 5203 pkg.applicationInfo.processName, 5204 pkg.applicationInfo.uid); 5205 5206 File dataPath; 5207 if (mPlatformPackage == pkg) { 5208 // The system package is special. 5209 dataPath = new File (Environment.getDataDirectory(), "system"); 5210 pkg.applicationInfo.dataDir = dataPath.getPath(); 5211 } else { 5212 // This is a normal package, need to make its data directory. 5213 dataPath = getDataPathForPackage(pkg.packageName, 0); 5214 5215 boolean uidError = false; 5216 5217 if (dataPath.exists()) { 5218 int currentUid = 0; 5219 try { 5220 StructStat stat = Os.stat(dataPath.getPath()); 5221 currentUid = stat.st_uid; 5222 } catch (ErrnoException e) { 5223 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5224 } 5225 5226 // If we have mismatched owners for the data path, we have a problem. 5227 if (currentUid != pkg.applicationInfo.uid) { 5228 boolean recovered = false; 5229 if (currentUid == 0) { 5230 // The directory somehow became owned by root. Wow. 5231 // This is probably because the system was stopped while 5232 // installd was in the middle of messing with its libs 5233 // directory. Ask installd to fix that. 5234 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5235 pkg.applicationInfo.uid); 5236 if (ret >= 0) { 5237 recovered = true; 5238 String msg = "Package " + pkg.packageName 5239 + " unexpectedly changed to uid 0; recovered to " + 5240 + pkg.applicationInfo.uid; 5241 reportSettingsProblem(Log.WARN, msg); 5242 } 5243 } 5244 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5245 || (scanMode&SCAN_BOOTING) != 0)) { 5246 // If this is a system app, we can at least delete its 5247 // current data so the application will still work. 5248 int ret = removeDataDirsLI(pkgName); 5249 if (ret >= 0) { 5250 // TODO: Kill the processes first 5251 // Old data gone! 5252 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5253 ? "System package " : "Third party package "; 5254 String msg = prefix + pkg.packageName 5255 + " has changed from uid: " 5256 + currentUid + " to " 5257 + pkg.applicationInfo.uid + "; old data erased"; 5258 reportSettingsProblem(Log.WARN, msg); 5259 recovered = true; 5260 5261 // And now re-install the app. 5262 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5263 pkg.applicationInfo.seinfo); 5264 if (ret == -1) { 5265 // Ack should not happen! 5266 msg = prefix + pkg.packageName 5267 + " could not have data directory re-created after delete."; 5268 reportSettingsProblem(Log.WARN, msg); 5269 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5270 return null; 5271 } 5272 } 5273 if (!recovered) { 5274 mHasSystemUidErrors = true; 5275 } 5276 } else if (!recovered) { 5277 // If we allow this install to proceed, we will be broken. 5278 // Abort, abort! 5279 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 5280 return null; 5281 } 5282 if (!recovered) { 5283 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5284 + pkg.applicationInfo.uid + "/fs_" 5285 + currentUid; 5286 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5287 String msg = "Package " + pkg.packageName 5288 + " has mismatched uid: " 5289 + currentUid + " on disk, " 5290 + pkg.applicationInfo.uid + " in settings"; 5291 // writer 5292 synchronized (mPackages) { 5293 mSettings.mReadMessages.append(msg); 5294 mSettings.mReadMessages.append('\n'); 5295 uidError = true; 5296 if (!pkgSetting.uidError) { 5297 reportSettingsProblem(Log.ERROR, msg); 5298 } 5299 } 5300 } 5301 } 5302 pkg.applicationInfo.dataDir = dataPath.getPath(); 5303 if (mShouldRestoreconData) { 5304 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5305 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5306 pkg.applicationInfo.uid); 5307 } 5308 } else { 5309 if (DEBUG_PACKAGE_SCANNING) { 5310 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5311 Log.v(TAG, "Want this data dir: " + dataPath); 5312 } 5313 //invoke installer to do the actual installation 5314 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5315 pkg.applicationInfo.seinfo); 5316 if (ret < 0) { 5317 // Error from installer 5318 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5319 return null; 5320 } 5321 5322 if (dataPath.exists()) { 5323 pkg.applicationInfo.dataDir = dataPath.getPath(); 5324 } else { 5325 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5326 pkg.applicationInfo.dataDir = null; 5327 } 5328 } 5329 5330 /* 5331 * Set the data dir to the default "/data/data/<package name>/lib" 5332 * if we got here without anyone telling us different (e.g., apps 5333 * stored on SD card have their native libraries stored in the ASEC 5334 * container with the APK). 5335 * 5336 * This happens during an upgrade from a package settings file that 5337 * doesn't have a native library path attribute at all. 5338 */ 5339 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 5340 if (pkgSetting.nativeLibraryPathString == null) { 5341 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5342 } else { 5343 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 5344 } 5345 } 5346 pkgSetting.uidError = uidError; 5347 } 5348 5349 final String path = scanFile.getPath(); 5350 /* Note: We don't want to unpack the native binaries for 5351 * system applications, unless they have been updated 5352 * (the binaries are already under /system/lib). 5353 * Also, don't unpack libs for apps on the external card 5354 * since they should have their libraries in the ASEC 5355 * container already. 5356 * 5357 * In other words, we're going to unpack the binaries 5358 * only for non-system apps and system app upgrades. 5359 */ 5360 if (pkg.applicationInfo.nativeLibraryDir != null) { 5361 // TODO: extend to extract native code from split APKs 5362 ApkHandle handle = null; 5363 try { 5364 handle = ApkHandle.create(scanFile.getPath()); 5365 // Enable gross and lame hacks for apps that are built with old 5366 // SDK tools. We must scan their APKs for renderscript bitcode and 5367 // not launch them if it's present. Don't bother checking on devices 5368 // that don't have 64 bit support. 5369 String[] abiList = Build.SUPPORTED_ABIS; 5370 boolean hasLegacyRenderscriptBitcode = false; 5371 if (abiOverride != null) { 5372 abiList = new String[] { abiOverride }; 5373 } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 5374 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5375 abiList = Build.SUPPORTED_32_BIT_ABIS; 5376 hasLegacyRenderscriptBitcode = true; 5377 } 5378 5379 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5380 final String dataPathString = dataPath.getCanonicalPath(); 5381 5382 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5383 /* 5384 * Upgrading from a previous version of the OS sometimes 5385 * leaves native libraries in the /data/data/<app>/lib 5386 * directory for system apps even when they shouldn't be. 5387 * Recent changes in the JNI library search path 5388 * necessitates we remove those to match previous behavior. 5389 */ 5390 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 5391 Log.i(TAG, "removed obsolete native libraries for system package " 5392 + path); 5393 } 5394 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5395 pkg.applicationInfo.cpuAbi = abiList[0]; 5396 pkgSetting.cpuAbiString = abiList[0]; 5397 } else { 5398 setInternalAppAbi(pkg, pkgSetting); 5399 } 5400 } else { 5401 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 5402 /* 5403 * Update native library dir if it starts with 5404 * /data/data 5405 */ 5406 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 5407 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5408 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5409 } 5410 5411 try { 5412 int copyRet = copyNativeLibrariesForInternalApp(handle, 5413 nativeLibraryDir, abiList); 5414 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5415 Slog.e(TAG, "Unable to copy native libraries"); 5416 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5417 return null; 5418 } 5419 5420 // We've successfully copied native libraries across, so we make a 5421 // note of what ABI we're using 5422 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5423 pkg.applicationInfo.cpuAbi = abiList[copyRet]; 5424 } else if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5425 pkg.applicationInfo.cpuAbi = abiList[0]; 5426 } else { 5427 pkg.applicationInfo.cpuAbi = null; 5428 } 5429 } catch (IOException e) { 5430 Slog.e(TAG, "Unable to copy native libraries", e); 5431 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5432 return null; 5433 } 5434 } else { 5435 // We don't have to copy the shared libraries if we're in the ASEC container 5436 // but we still need to scan the file to figure out what ABI the app needs. 5437 // 5438 // TODO: This duplicates work done in the default container service. It's possible 5439 // to clean this up but we'll need to change the interface between this service 5440 // and IMediaContainerService (but doing so will spread this logic out, rather 5441 // than centralizing it). 5442 final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5443 if (abi >= 0) { 5444 pkg.applicationInfo.cpuAbi = abiList[abi]; 5445 } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) { 5446 // Note that (non upgraded) system apps will not have any native 5447 // libraries bundled in their APK, but we're guaranteed not to be 5448 // such an app at this point. 5449 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5450 pkg.applicationInfo.cpuAbi = abiList[0]; 5451 } else { 5452 pkg.applicationInfo.cpuAbi = null; 5453 } 5454 } else { 5455 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5456 return null; 5457 } 5458 } 5459 5460 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5461 final int[] userIds = sUserManager.getUserIds(); 5462 synchronized (mInstallLock) { 5463 for (int userId : userIds) { 5464 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 5465 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 5466 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5467 + ")"); 5468 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5469 return null; 5470 } 5471 } 5472 } 5473 } 5474 5475 pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi; 5476 } catch (IOException ioe) { 5477 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5478 } finally { 5479 IoUtils.closeQuietly(handle); 5480 } 5481 } 5482 5483 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5484 // We don't do this here during boot because we can do it all 5485 // at once after scanning all existing packages. 5486 // 5487 // We also do this *before* we perform dexopt on this package, so that 5488 // we can avoid redundant dexopts, and also to make sure we've got the 5489 // code and package path correct. 5490 if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5491 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) { 5492 mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE; 5493 return null; 5494 } 5495 } 5496 5497 if ((scanMode&SCAN_NO_DEX) == 0) { 5498 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5499 == DEX_OPT_FAILED) { 5500 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5501 removeDataDirsLI(pkg.packageName); 5502 } 5503 5504 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5505 return null; 5506 } 5507 } 5508 5509 if (mFactoryTest && pkg.requestedPermissions.contains( 5510 android.Manifest.permission.FACTORY_TEST)) { 5511 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5512 } 5513 5514 ArrayList<PackageParser.Package> clientLibPkgs = null; 5515 5516 // writer 5517 synchronized (mPackages) { 5518 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5519 // Only system apps can add new shared libraries. 5520 if (pkg.libraryNames != null) { 5521 for (int i=0; i<pkg.libraryNames.size(); i++) { 5522 String name = pkg.libraryNames.get(i); 5523 boolean allowed = false; 5524 if (isUpdatedSystemApp(pkg)) { 5525 // New library entries can only be added through the 5526 // system image. This is important to get rid of a lot 5527 // of nasty edge cases: for example if we allowed a non- 5528 // system update of the app to add a library, then uninstalling 5529 // the update would make the library go away, and assumptions 5530 // we made such as through app install filtering would now 5531 // have allowed apps on the device which aren't compatible 5532 // with it. Better to just have the restriction here, be 5533 // conservative, and create many fewer cases that can negatively 5534 // impact the user experience. 5535 final PackageSetting sysPs = mSettings 5536 .getDisabledSystemPkgLPr(pkg.packageName); 5537 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5538 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5539 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5540 allowed = true; 5541 allowed = true; 5542 break; 5543 } 5544 } 5545 } 5546 } else { 5547 allowed = true; 5548 } 5549 if (allowed) { 5550 if (!mSharedLibraries.containsKey(name)) { 5551 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5552 } else if (!name.equals(pkg.packageName)) { 5553 Slog.w(TAG, "Package " + pkg.packageName + " library " 5554 + name + " already exists; skipping"); 5555 } 5556 } else { 5557 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5558 + name + " that is not declared on system image; skipping"); 5559 } 5560 } 5561 if ((scanMode&SCAN_BOOTING) == 0) { 5562 // If we are not booting, we need to update any applications 5563 // that are clients of our shared library. If we are booting, 5564 // this will all be done once the scan is complete. 5565 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5566 } 5567 } 5568 } 5569 } 5570 5571 // We also need to dexopt any apps that are dependent on this library. Note that 5572 // if these fail, we should abort the install since installing the library will 5573 // result in some apps being broken. 5574 if (clientLibPkgs != null) { 5575 if ((scanMode&SCAN_NO_DEX) == 0) { 5576 for (int i=0; i<clientLibPkgs.size(); i++) { 5577 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5578 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5579 == DEX_OPT_FAILED) { 5580 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5581 removeDataDirsLI(pkg.packageName); 5582 } 5583 5584 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5585 return null; 5586 } 5587 } 5588 } 5589 } 5590 5591 // Request the ActivityManager to kill the process(only for existing packages) 5592 // so that we do not end up in a confused state while the user is still using the older 5593 // version of the application while the new one gets installed. 5594 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5595 // If the package lives in an asec, tell everyone that the container is going 5596 // away so they can clean up any references to its resources (which would prevent 5597 // vold from being able to unmount the asec) 5598 if (isForwardLocked(pkg) || isExternal(pkg)) { 5599 if (DEBUG_INSTALL) { 5600 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5601 } 5602 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5603 final ArrayList<String> pkgList = new ArrayList<String>(1); 5604 pkgList.add(pkg.applicationInfo.packageName); 5605 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5606 } 5607 5608 // Post the request that it be killed now that the going-away broadcast is en route 5609 killApplication(pkg.applicationInfo.packageName, 5610 pkg.applicationInfo.uid, "update pkg"); 5611 } 5612 5613 // Also need to kill any apps that are dependent on the library. 5614 if (clientLibPkgs != null) { 5615 for (int i=0; i<clientLibPkgs.size(); i++) { 5616 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5617 killApplication(clientPkg.applicationInfo.packageName, 5618 clientPkg.applicationInfo.uid, "update lib"); 5619 } 5620 } 5621 5622 // writer 5623 synchronized (mPackages) { 5624 // We don't expect installation to fail beyond this point, 5625 if ((scanMode&SCAN_MONITOR) != 0) { 5626 mAppDirs.put(pkg.codePath, pkg); 5627 } 5628 // Add the new setting to mSettings 5629 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5630 // Add the new setting to mPackages 5631 mPackages.put(pkg.applicationInfo.packageName, pkg); 5632 // Make sure we don't accidentally delete its data. 5633 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5634 while (iter.hasNext()) { 5635 PackageCleanItem item = iter.next(); 5636 if (pkgName.equals(item.packageName)) { 5637 iter.remove(); 5638 } 5639 } 5640 5641 // Take care of first install / last update times. 5642 if (currentTime != 0) { 5643 if (pkgSetting.firstInstallTime == 0) { 5644 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5645 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5646 pkgSetting.lastUpdateTime = currentTime; 5647 } 5648 } else if (pkgSetting.firstInstallTime == 0) { 5649 // We need *something*. Take time time stamp of the file. 5650 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5651 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5652 if (scanFileTime != pkgSetting.timeStamp) { 5653 // A package on the system image has changed; consider this 5654 // to be an update. 5655 pkgSetting.lastUpdateTime = scanFileTime; 5656 } 5657 } 5658 5659 // Add the package's KeySets to the global KeySetManagerService 5660 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5661 try { 5662 // Old KeySetData no longer valid. 5663 ksms.removeAppKeySetData(pkg.packageName); 5664 ksms.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5665 if (pkg.mKeySetMapping != null) { 5666 for (Map.Entry<String, Set<PublicKey>> entry : 5667 pkg.mKeySetMapping.entrySet()) { 5668 if (entry.getValue() != null) { 5669 ksms.addDefinedKeySetToPackage(pkg.packageName, 5670 entry.getValue(), entry.getKey()); 5671 } 5672 } 5673 if (pkg.mUpgradeKeySets != null 5674 && pkg.mKeySetMapping.keySet().containsAll(pkg.mUpgradeKeySets)) { 5675 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5676 ksms.addUpgradeKeySetToPackage(pkg.packageName, upgradeAlias); 5677 } 5678 } 5679 } 5680 } catch (NullPointerException e) { 5681 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5682 } catch (IllegalArgumentException e) { 5683 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5684 } 5685 5686 int N = pkg.providers.size(); 5687 StringBuilder r = null; 5688 int i; 5689 for (i=0; i<N; i++) { 5690 PackageParser.Provider p = pkg.providers.get(i); 5691 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5692 p.info.processName, pkg.applicationInfo.uid); 5693 mProviders.addProvider(p); 5694 p.syncable = p.info.isSyncable; 5695 if (p.info.authority != null) { 5696 String names[] = p.info.authority.split(";"); 5697 p.info.authority = null; 5698 for (int j = 0; j < names.length; j++) { 5699 if (j == 1 && p.syncable) { 5700 // We only want the first authority for a provider to possibly be 5701 // syncable, so if we already added this provider using a different 5702 // authority clear the syncable flag. We copy the provider before 5703 // changing it because the mProviders object contains a reference 5704 // to a provider that we don't want to change. 5705 // Only do this for the second authority since the resulting provider 5706 // object can be the same for all future authorities for this provider. 5707 p = new PackageParser.Provider(p); 5708 p.syncable = false; 5709 } 5710 if (!mProvidersByAuthority.containsKey(names[j])) { 5711 mProvidersByAuthority.put(names[j], p); 5712 if (p.info.authority == null) { 5713 p.info.authority = names[j]; 5714 } else { 5715 p.info.authority = p.info.authority + ";" + names[j]; 5716 } 5717 if (DEBUG_PACKAGE_SCANNING) { 5718 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5719 Log.d(TAG, "Registered content provider: " + names[j] 5720 + ", className = " + p.info.name + ", isSyncable = " 5721 + p.info.isSyncable); 5722 } 5723 } else { 5724 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5725 Slog.w(TAG, "Skipping provider name " + names[j] + 5726 " (in package " + pkg.applicationInfo.packageName + 5727 "): name already used by " 5728 + ((other != null && other.getComponentName() != null) 5729 ? other.getComponentName().getPackageName() : "?")); 5730 } 5731 } 5732 } 5733 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5734 if (r == null) { 5735 r = new StringBuilder(256); 5736 } else { 5737 r.append(' '); 5738 } 5739 r.append(p.info.name); 5740 } 5741 } 5742 if (r != null) { 5743 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5744 } 5745 5746 N = pkg.services.size(); 5747 r = null; 5748 for (i=0; i<N; i++) { 5749 PackageParser.Service s = pkg.services.get(i); 5750 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5751 s.info.processName, pkg.applicationInfo.uid); 5752 mServices.addService(s); 5753 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5754 if (r == null) { 5755 r = new StringBuilder(256); 5756 } else { 5757 r.append(' '); 5758 } 5759 r.append(s.info.name); 5760 } 5761 } 5762 if (r != null) { 5763 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5764 } 5765 5766 N = pkg.receivers.size(); 5767 r = null; 5768 for (i=0; i<N; i++) { 5769 PackageParser.Activity a = pkg.receivers.get(i); 5770 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5771 a.info.processName, pkg.applicationInfo.uid); 5772 mReceivers.addActivity(a, "receiver"); 5773 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5774 if (r == null) { 5775 r = new StringBuilder(256); 5776 } else { 5777 r.append(' '); 5778 } 5779 r.append(a.info.name); 5780 } 5781 } 5782 if (r != null) { 5783 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5784 } 5785 5786 N = pkg.activities.size(); 5787 r = null; 5788 for (i=0; i<N; i++) { 5789 PackageParser.Activity a = pkg.activities.get(i); 5790 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5791 a.info.processName, pkg.applicationInfo.uid); 5792 mActivities.addActivity(a, "activity"); 5793 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5794 if (r == null) { 5795 r = new StringBuilder(256); 5796 } else { 5797 r.append(' '); 5798 } 5799 r.append(a.info.name); 5800 } 5801 } 5802 if (r != null) { 5803 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5804 } 5805 5806 N = pkg.permissionGroups.size(); 5807 r = null; 5808 for (i=0; i<N; i++) { 5809 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5810 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5811 if (cur == null) { 5812 mPermissionGroups.put(pg.info.name, pg); 5813 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5814 if (r == null) { 5815 r = new StringBuilder(256); 5816 } else { 5817 r.append(' '); 5818 } 5819 r.append(pg.info.name); 5820 } 5821 } else { 5822 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5823 + pg.info.packageName + " ignored: original from " 5824 + cur.info.packageName); 5825 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5826 if (r == null) { 5827 r = new StringBuilder(256); 5828 } else { 5829 r.append(' '); 5830 } 5831 r.append("DUP:"); 5832 r.append(pg.info.name); 5833 } 5834 } 5835 } 5836 if (r != null) { 5837 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5838 } 5839 5840 N = pkg.permissions.size(); 5841 r = null; 5842 for (i=0; i<N; i++) { 5843 PackageParser.Permission p = pkg.permissions.get(i); 5844 HashMap<String, BasePermission> permissionMap = 5845 p.tree ? mSettings.mPermissionTrees 5846 : mSettings.mPermissions; 5847 p.group = mPermissionGroups.get(p.info.group); 5848 if (p.info.group == null || p.group != null) { 5849 BasePermission bp = permissionMap.get(p.info.name); 5850 if (bp == null) { 5851 bp = new BasePermission(p.info.name, p.info.packageName, 5852 BasePermission.TYPE_NORMAL); 5853 permissionMap.put(p.info.name, bp); 5854 } 5855 if (bp.perm == null) { 5856 if (bp.sourcePackage != null 5857 && !bp.sourcePackage.equals(p.info.packageName)) { 5858 // If this is a permission that was formerly defined by a non-system 5859 // app, but is now defined by a system app (following an upgrade), 5860 // discard the previous declaration and consider the system's to be 5861 // canonical. 5862 if (isSystemApp(p.owner)) { 5863 String msg = "New decl " + p.owner + " of permission " 5864 + p.info.name + " is system"; 5865 reportSettingsProblem(Log.WARN, msg); 5866 bp.sourcePackage = null; 5867 } 5868 } 5869 if (bp.sourcePackage == null 5870 || bp.sourcePackage.equals(p.info.packageName)) { 5871 BasePermission tree = findPermissionTreeLP(p.info.name); 5872 if (tree == null 5873 || tree.sourcePackage.equals(p.info.packageName)) { 5874 bp.packageSetting = pkgSetting; 5875 bp.perm = p; 5876 bp.uid = pkg.applicationInfo.uid; 5877 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5878 if (r == null) { 5879 r = new StringBuilder(256); 5880 } else { 5881 r.append(' '); 5882 } 5883 r.append(p.info.name); 5884 } 5885 } else { 5886 Slog.w(TAG, "Permission " + p.info.name + " from package " 5887 + p.info.packageName + " ignored: base tree " 5888 + tree.name + " is from package " 5889 + tree.sourcePackage); 5890 } 5891 } else { 5892 Slog.w(TAG, "Permission " + p.info.name + " from package " 5893 + p.info.packageName + " ignored: original from " 5894 + bp.sourcePackage); 5895 } 5896 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5897 if (r == null) { 5898 r = new StringBuilder(256); 5899 } else { 5900 r.append(' '); 5901 } 5902 r.append("DUP:"); 5903 r.append(p.info.name); 5904 } 5905 if (bp.perm == p) { 5906 bp.protectionLevel = p.info.protectionLevel; 5907 } 5908 } else { 5909 Slog.w(TAG, "Permission " + p.info.name + " from package " 5910 + p.info.packageName + " ignored: no group " 5911 + p.group); 5912 } 5913 } 5914 if (r != null) { 5915 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5916 } 5917 5918 N = pkg.instrumentation.size(); 5919 r = null; 5920 for (i=0; i<N; i++) { 5921 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5922 a.info.packageName = pkg.applicationInfo.packageName; 5923 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5924 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5925 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 5926 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 5927 a.info.dataDir = pkg.applicationInfo.dataDir; 5928 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5929 mInstrumentation.put(a.getComponentName(), a); 5930 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5931 if (r == null) { 5932 r = new StringBuilder(256); 5933 } else { 5934 r.append(' '); 5935 } 5936 r.append(a.info.name); 5937 } 5938 } 5939 if (r != null) { 5940 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5941 } 5942 5943 if (pkg.protectedBroadcasts != null) { 5944 N = pkg.protectedBroadcasts.size(); 5945 for (i=0; i<N; i++) { 5946 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5947 } 5948 } 5949 5950 pkgSetting.setTimeStamp(scanFileTime); 5951 5952 // Create idmap files for pairs of (packages, overlay packages). 5953 // Note: "android", ie framework-res.apk, is handled by native layers. 5954 if (pkg.mOverlayTarget != null) { 5955 // This is an overlay package. 5956 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 5957 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 5958 mOverlays.put(pkg.mOverlayTarget, 5959 new HashMap<String, PackageParser.Package>()); 5960 } 5961 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 5962 map.put(pkg.packageName, pkg); 5963 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 5964 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 5965 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5966 return null; 5967 } 5968 } 5969 } else if (mOverlays.containsKey(pkg.packageName) && 5970 !pkg.packageName.equals("android")) { 5971 // This is a regular package, with one or more known overlay packages. 5972 createIdmapsForPackageLI(pkg); 5973 } 5974 } 5975 5976 return pkg; 5977 } 5978 5979 /** 5980 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 5981 * i.e, so that all packages can be run inside a single process if required. 5982 * 5983 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 5984 * this function will either try and make the ABI for all packages in {@code packagesForUser} 5985 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 5986 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 5987 * updating a package that belongs to a shared user. 5988 */ 5989 private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 5990 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 5991 String requiredInstructionSet = null; 5992 if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) { 5993 requiredInstructionSet = VMRuntime.getInstructionSet( 5994 scannedPackage.applicationInfo.cpuAbi); 5995 } 5996 5997 PackageSetting requirer = null; 5998 for (PackageSetting ps : packagesForUser) { 5999 // If packagesForUser contains scannedPackage, we skip it. This will happen 6000 // when scannedPackage is an update of an existing package. Without this check, 6001 // we will never be able to change the ABI of any package belonging to a shared 6002 // user, even if it's compatible with other packages. 6003 if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) { 6004 if (ps.cpuAbiString == null) { 6005 continue; 6006 } 6007 6008 final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 6009 if (requiredInstructionSet != null) { 6010 if (!instructionSet.equals(requiredInstructionSet)) { 6011 // We have a mismatch between instruction sets (say arm vs arm64). 6012 // bail out. 6013 String errorMessage = "Instruction set mismatch, " 6014 + ((requirer == null) ? "[caller]" : requirer) 6015 + " requires " + requiredInstructionSet + " whereas " + ps 6016 + " requires " + instructionSet; 6017 Slog.e(TAG, errorMessage); 6018 6019 reportSettingsProblem(Log.WARN, errorMessage); 6020 // Give up, don't bother making any other changes to the package settings. 6021 return false; 6022 } 6023 } else { 6024 requiredInstructionSet = instructionSet; 6025 requirer = ps; 6026 } 6027 } 6028 } 6029 6030 if (requiredInstructionSet != null) { 6031 String adjustedAbi; 6032 if (requirer != null) { 6033 // requirer != null implies that either scannedPackage was null or that scannedPackage 6034 // did not require an ABI, in which case we have to adjust scannedPackage to match 6035 // the ABI of the set (which is the same as requirer's ABI) 6036 adjustedAbi = requirer.cpuAbiString; 6037 if (scannedPackage != null) { 6038 scannedPackage.applicationInfo.cpuAbi = adjustedAbi; 6039 } 6040 } else { 6041 // requirer == null implies that we're updating all ABIs in the set to 6042 // match scannedPackage. 6043 adjustedAbi = scannedPackage.applicationInfo.cpuAbi; 6044 } 6045 6046 for (PackageSetting ps : packagesForUser) { 6047 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6048 if (ps.cpuAbiString != null) { 6049 continue; 6050 } 6051 6052 ps.cpuAbiString = adjustedAbi; 6053 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6054 ps.pkg.applicationInfo.cpuAbi = adjustedAbi; 6055 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6056 6057 if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) { 6058 ps.cpuAbiString = null; 6059 ps.pkg.applicationInfo.cpuAbi = null; 6060 return false; 6061 } else { 6062 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6063 } 6064 } 6065 } 6066 } 6067 } 6068 6069 return true; 6070 } 6071 6072 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6073 synchronized (mPackages) { 6074 mResolverReplaced = true; 6075 // Set up information for custom user intent resolution activity. 6076 mResolveActivity.applicationInfo = pkg.applicationInfo; 6077 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6078 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6079 mResolveActivity.processName = null; 6080 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6081 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6082 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6083 mResolveActivity.theme = 0; 6084 mResolveActivity.exported = true; 6085 mResolveActivity.enabled = true; 6086 mResolveInfo.activityInfo = mResolveActivity; 6087 mResolveInfo.priority = 0; 6088 mResolveInfo.preferredOrder = 0; 6089 mResolveInfo.match = 0; 6090 mResolveComponentName = mCustomResolverComponentName; 6091 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6092 mResolveComponentName); 6093 } 6094 } 6095 6096 private String calculateApkRoot(final String codePathString) { 6097 final File codePath = new File(codePathString); 6098 final File codeRoot; 6099 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6100 codeRoot = Environment.getRootDirectory(); 6101 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6102 codeRoot = Environment.getOemDirectory(); 6103 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6104 codeRoot = Environment.getVendorDirectory(); 6105 } else { 6106 // Unrecognized code path; take its top real segment as the apk root: 6107 // e.g. /something/app/blah.apk => /something 6108 try { 6109 File f = codePath.getCanonicalFile(); 6110 File parent = f.getParentFile(); // non-null because codePath is a file 6111 File tmp; 6112 while ((tmp = parent.getParentFile()) != null) { 6113 f = parent; 6114 parent = tmp; 6115 } 6116 codeRoot = f; 6117 Slog.w(TAG, "Unrecognized code path " 6118 + codePath + " - using " + codeRoot); 6119 } catch (IOException e) { 6120 // Can't canonicalize the lib path -- shenanigans? 6121 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6122 return Environment.getRootDirectory().getPath(); 6123 } 6124 } 6125 return codeRoot.getPath(); 6126 } 6127 6128 // This is the initial scan-time determination of how to handle a given 6129 // package for purposes of native library location. 6130 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 6131 PackageSetting pkgSetting) { 6132 // "bundled" here means system-installed with no overriding update 6133 final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg); 6134 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 6135 final File libDir; 6136 if (bundledApk) { 6137 // If "/system/lib64/apkname" exists, assume that is the per-package 6138 // native library directory to use; otherwise use "/system/lib/apkname". 6139 String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6140 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 6141 File packLib64 = new File(lib64, apkName); 6142 libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 6143 } else { 6144 libDir = mAppLibInstallDir; 6145 } 6146 final String nativeLibraryPath = (new File(libDir, apkName)).getPath(); 6147 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 6148 // pkgSetting might be null during rescan following uninstall of updates 6149 // to a bundled app, so accommodate that possibility. The settings in 6150 // that case will be established later from the parsed package. 6151 if (pkgSetting != null) { 6152 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 6153 } 6154 } 6155 6156 // Deduces the required ABI of an upgraded system app. 6157 private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) { 6158 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6159 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 6160 6161 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 6162 // or similar. 6163 final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath()); 6164 final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath()); 6165 6166 // Assume that the bundled native libraries always correspond to the 6167 // most preferred 32 or 64 bit ABI. 6168 if (lib64.exists()) { 6169 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6170 pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0]; 6171 } else if (lib.exists()) { 6172 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6173 pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0]; 6174 } else { 6175 // This is the case where the app has no native code. 6176 pkg.applicationInfo.cpuAbi = null; 6177 pkgSetting.cpuAbiString = null; 6178 } 6179 } 6180 6181 private static int copyNativeLibrariesForInternalApp(ApkHandle handle, 6182 final File nativeLibraryDir, String[] abiList) throws IOException { 6183 if (!nativeLibraryDir.isDirectory()) { 6184 nativeLibraryDir.delete(); 6185 6186 if (!nativeLibraryDir.mkdir()) { 6187 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 6188 } 6189 6190 try { 6191 Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6192 } catch (ErrnoException e) { 6193 throw new IOException("Cannot chmod native library directory " 6194 + nativeLibraryDir.getPath(), e); 6195 } 6196 } else if (!SELinux.restorecon(nativeLibraryDir)) { 6197 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 6198 } 6199 6200 /* 6201 * If this is an internal application or our nativeLibraryPath points to 6202 * the app-lib directory, unpack the libraries if necessary. 6203 */ 6204 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6205 if (abi >= 0) { 6206 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 6207 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 6208 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6209 return copyRet; 6210 } 6211 } 6212 6213 return abi; 6214 } 6215 6216 private void killApplication(String pkgName, int appId, String reason) { 6217 // Request the ActivityManager to kill the process(only for existing packages) 6218 // so that we do not end up in a confused state while the user is still using the older 6219 // version of the application while the new one gets installed. 6220 IActivityManager am = ActivityManagerNative.getDefault(); 6221 if (am != null) { 6222 try { 6223 am.killApplicationWithAppId(pkgName, appId, reason); 6224 } catch (RemoteException e) { 6225 } 6226 } 6227 } 6228 6229 void removePackageLI(PackageSetting ps, boolean chatty) { 6230 if (DEBUG_INSTALL) { 6231 if (chatty) 6232 Log.d(TAG, "Removing package " + ps.name); 6233 } 6234 6235 // writer 6236 synchronized (mPackages) { 6237 mPackages.remove(ps.name); 6238 if (ps.codePathString != null) { 6239 mAppDirs.remove(ps.codePathString); 6240 } 6241 6242 final PackageParser.Package pkg = ps.pkg; 6243 if (pkg != null) { 6244 cleanPackageDataStructuresLILPw(pkg, chatty); 6245 } 6246 } 6247 } 6248 6249 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6250 if (DEBUG_INSTALL) { 6251 if (chatty) 6252 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6253 } 6254 6255 // writer 6256 synchronized (mPackages) { 6257 mPackages.remove(pkg.applicationInfo.packageName); 6258 if (pkg.codePath != null) { 6259 mAppDirs.remove(pkg.codePath); 6260 } 6261 cleanPackageDataStructuresLILPw(pkg, chatty); 6262 } 6263 } 6264 6265 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6266 int N = pkg.providers.size(); 6267 StringBuilder r = null; 6268 int i; 6269 for (i=0; i<N; i++) { 6270 PackageParser.Provider p = pkg.providers.get(i); 6271 mProviders.removeProvider(p); 6272 if (p.info.authority == null) { 6273 6274 /* There was another ContentProvider with this authority when 6275 * this app was installed so this authority is null, 6276 * Ignore it as we don't have to unregister the provider. 6277 */ 6278 continue; 6279 } 6280 String names[] = p.info.authority.split(";"); 6281 for (int j = 0; j < names.length; j++) { 6282 if (mProvidersByAuthority.get(names[j]) == p) { 6283 mProvidersByAuthority.remove(names[j]); 6284 if (DEBUG_REMOVE) { 6285 if (chatty) 6286 Log.d(TAG, "Unregistered content provider: " + names[j] 6287 + ", className = " + p.info.name + ", isSyncable = " 6288 + p.info.isSyncable); 6289 } 6290 } 6291 } 6292 if (DEBUG_REMOVE && chatty) { 6293 if (r == null) { 6294 r = new StringBuilder(256); 6295 } else { 6296 r.append(' '); 6297 } 6298 r.append(p.info.name); 6299 } 6300 } 6301 if (r != null) { 6302 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6303 } 6304 6305 N = pkg.services.size(); 6306 r = null; 6307 for (i=0; i<N; i++) { 6308 PackageParser.Service s = pkg.services.get(i); 6309 mServices.removeService(s); 6310 if (chatty) { 6311 if (r == null) { 6312 r = new StringBuilder(256); 6313 } else { 6314 r.append(' '); 6315 } 6316 r.append(s.info.name); 6317 } 6318 } 6319 if (r != null) { 6320 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6321 } 6322 6323 N = pkg.receivers.size(); 6324 r = null; 6325 for (i=0; i<N; i++) { 6326 PackageParser.Activity a = pkg.receivers.get(i); 6327 mReceivers.removeActivity(a, "receiver"); 6328 if (DEBUG_REMOVE && chatty) { 6329 if (r == null) { 6330 r = new StringBuilder(256); 6331 } else { 6332 r.append(' '); 6333 } 6334 r.append(a.info.name); 6335 } 6336 } 6337 if (r != null) { 6338 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6339 } 6340 6341 N = pkg.activities.size(); 6342 r = null; 6343 for (i=0; i<N; i++) { 6344 PackageParser.Activity a = pkg.activities.get(i); 6345 mActivities.removeActivity(a, "activity"); 6346 if (DEBUG_REMOVE && chatty) { 6347 if (r == null) { 6348 r = new StringBuilder(256); 6349 } else { 6350 r.append(' '); 6351 } 6352 r.append(a.info.name); 6353 } 6354 } 6355 if (r != null) { 6356 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6357 } 6358 6359 N = pkg.permissions.size(); 6360 r = null; 6361 for (i=0; i<N; i++) { 6362 PackageParser.Permission p = pkg.permissions.get(i); 6363 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6364 if (bp == null) { 6365 bp = mSettings.mPermissionTrees.get(p.info.name); 6366 } 6367 if (bp != null && bp.perm == p) { 6368 bp.perm = null; 6369 if (DEBUG_REMOVE && chatty) { 6370 if (r == null) { 6371 r = new StringBuilder(256); 6372 } else { 6373 r.append(' '); 6374 } 6375 r.append(p.info.name); 6376 } 6377 } 6378 } 6379 if (r != null) { 6380 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6381 } 6382 6383 N = pkg.instrumentation.size(); 6384 r = null; 6385 for (i=0; i<N; i++) { 6386 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6387 mInstrumentation.remove(a.getComponentName()); 6388 if (DEBUG_REMOVE && chatty) { 6389 if (r == null) { 6390 r = new StringBuilder(256); 6391 } else { 6392 r.append(' '); 6393 } 6394 r.append(a.info.name); 6395 } 6396 } 6397 if (r != null) { 6398 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6399 } 6400 6401 r = null; 6402 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6403 // Only system apps can hold shared libraries. 6404 if (pkg.libraryNames != null) { 6405 for (i=0; i<pkg.libraryNames.size(); i++) { 6406 String name = pkg.libraryNames.get(i); 6407 SharedLibraryEntry cur = mSharedLibraries.get(name); 6408 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6409 mSharedLibraries.remove(name); 6410 if (DEBUG_REMOVE && chatty) { 6411 if (r == null) { 6412 r = new StringBuilder(256); 6413 } else { 6414 r.append(' '); 6415 } 6416 r.append(name); 6417 } 6418 } 6419 } 6420 } 6421 } 6422 if (r != null) { 6423 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6424 } 6425 } 6426 6427 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6428 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6429 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6430 return true; 6431 } 6432 } 6433 return false; 6434 } 6435 6436 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6437 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6438 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6439 6440 private void updatePermissionsLPw(String changingPkg, 6441 PackageParser.Package pkgInfo, int flags) { 6442 // Make sure there are no dangling permission trees. 6443 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6444 while (it.hasNext()) { 6445 final BasePermission bp = it.next(); 6446 if (bp.packageSetting == null) { 6447 // We may not yet have parsed the package, so just see if 6448 // we still know about its settings. 6449 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6450 } 6451 if (bp.packageSetting == null) { 6452 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6453 + " from package " + bp.sourcePackage); 6454 it.remove(); 6455 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6456 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6457 Slog.i(TAG, "Removing old permission tree: " + bp.name 6458 + " from package " + bp.sourcePackage); 6459 flags |= UPDATE_PERMISSIONS_ALL; 6460 it.remove(); 6461 } 6462 } 6463 } 6464 6465 // Make sure all dynamic permissions have been assigned to a package, 6466 // and make sure there are no dangling permissions. 6467 it = mSettings.mPermissions.values().iterator(); 6468 while (it.hasNext()) { 6469 final BasePermission bp = it.next(); 6470 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6471 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6472 + bp.name + " pkg=" + bp.sourcePackage 6473 + " info=" + bp.pendingInfo); 6474 if (bp.packageSetting == null && bp.pendingInfo != null) { 6475 final BasePermission tree = findPermissionTreeLP(bp.name); 6476 if (tree != null && tree.perm != null) { 6477 bp.packageSetting = tree.packageSetting; 6478 bp.perm = new PackageParser.Permission(tree.perm.owner, 6479 new PermissionInfo(bp.pendingInfo)); 6480 bp.perm.info.packageName = tree.perm.info.packageName; 6481 bp.perm.info.name = bp.name; 6482 bp.uid = tree.uid; 6483 } 6484 } 6485 } 6486 if (bp.packageSetting == null) { 6487 // We may not yet have parsed the package, so just see if 6488 // we still know about its settings. 6489 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6490 } 6491 if (bp.packageSetting == null) { 6492 Slog.w(TAG, "Removing dangling permission: " + bp.name 6493 + " from package " + bp.sourcePackage); 6494 it.remove(); 6495 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6496 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6497 Slog.i(TAG, "Removing old permission: " + bp.name 6498 + " from package " + bp.sourcePackage); 6499 flags |= UPDATE_PERMISSIONS_ALL; 6500 it.remove(); 6501 } 6502 } 6503 } 6504 6505 // Now update the permissions for all packages, in particular 6506 // replace the granted permissions of the system packages. 6507 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6508 for (PackageParser.Package pkg : mPackages.values()) { 6509 if (pkg != pkgInfo) { 6510 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6511 } 6512 } 6513 } 6514 6515 if (pkgInfo != null) { 6516 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6517 } 6518 } 6519 6520 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6521 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6522 if (ps == null) { 6523 return; 6524 } 6525 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6526 HashSet<String> origPermissions = gp.grantedPermissions; 6527 boolean changedPermission = false; 6528 6529 if (replace) { 6530 ps.permissionsFixed = false; 6531 if (gp == ps) { 6532 origPermissions = new HashSet<String>(gp.grantedPermissions); 6533 gp.grantedPermissions.clear(); 6534 gp.gids = mGlobalGids; 6535 } 6536 } 6537 6538 if (gp.gids == null) { 6539 gp.gids = mGlobalGids; 6540 } 6541 6542 final int N = pkg.requestedPermissions.size(); 6543 for (int i=0; i<N; i++) { 6544 final String name = pkg.requestedPermissions.get(i); 6545 final boolean required = pkg.requestedPermissionsRequired.get(i); 6546 final BasePermission bp = mSettings.mPermissions.get(name); 6547 if (DEBUG_INSTALL) { 6548 if (gp != ps) { 6549 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6550 } 6551 } 6552 6553 if (bp == null || bp.packageSetting == null) { 6554 Slog.w(TAG, "Unknown permission " + name 6555 + " in package " + pkg.packageName); 6556 continue; 6557 } 6558 6559 final String perm = bp.name; 6560 boolean allowed; 6561 boolean allowedSig = false; 6562 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6563 if (level == PermissionInfo.PROTECTION_NORMAL 6564 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6565 // We grant a normal or dangerous permission if any of the following 6566 // are true: 6567 // 1) The permission is required 6568 // 2) The permission is optional, but was granted in the past 6569 // 3) The permission is optional, but was requested by an 6570 // app in /system (not /data) 6571 // 6572 // Otherwise, reject the permission. 6573 allowed = (required || origPermissions.contains(perm) 6574 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6575 } else if (bp.packageSetting == null) { 6576 // This permission is invalid; skip it. 6577 allowed = false; 6578 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6579 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6580 if (allowed) { 6581 allowedSig = true; 6582 } 6583 } else { 6584 allowed = false; 6585 } 6586 if (DEBUG_INSTALL) { 6587 if (gp != ps) { 6588 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6589 } 6590 } 6591 if (allowed) { 6592 if (!isSystemApp(ps) && ps.permissionsFixed) { 6593 // If this is an existing, non-system package, then 6594 // we can't add any new permissions to it. 6595 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6596 // Except... if this is a permission that was added 6597 // to the platform (note: need to only do this when 6598 // updating the platform). 6599 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6600 } 6601 } 6602 if (allowed) { 6603 if (!gp.grantedPermissions.contains(perm)) { 6604 changedPermission = true; 6605 gp.grantedPermissions.add(perm); 6606 gp.gids = appendInts(gp.gids, bp.gids); 6607 } else if (!ps.haveGids) { 6608 gp.gids = appendInts(gp.gids, bp.gids); 6609 } 6610 } else { 6611 Slog.w(TAG, "Not granting permission " + perm 6612 + " to package " + pkg.packageName 6613 + " because it was previously installed without"); 6614 } 6615 } else { 6616 if (gp.grantedPermissions.remove(perm)) { 6617 changedPermission = true; 6618 gp.gids = removeInts(gp.gids, bp.gids); 6619 Slog.i(TAG, "Un-granting permission " + perm 6620 + " from package " + pkg.packageName 6621 + " (protectionLevel=" + bp.protectionLevel 6622 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6623 + ")"); 6624 } else { 6625 Slog.w(TAG, "Not granting permission " + perm 6626 + " to package " + pkg.packageName 6627 + " (protectionLevel=" + bp.protectionLevel 6628 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6629 + ")"); 6630 } 6631 } 6632 } 6633 6634 if ((changedPermission || replace) && !ps.permissionsFixed && 6635 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6636 // This is the first that we have heard about this package, so the 6637 // permissions we have now selected are fixed until explicitly 6638 // changed. 6639 ps.permissionsFixed = true; 6640 } 6641 ps.haveGids = true; 6642 } 6643 6644 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6645 boolean allowed = false; 6646 final int NP = PackageParser.NEW_PERMISSIONS.length; 6647 for (int ip=0; ip<NP; ip++) { 6648 final PackageParser.NewPermissionInfo npi 6649 = PackageParser.NEW_PERMISSIONS[ip]; 6650 if (npi.name.equals(perm) 6651 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6652 allowed = true; 6653 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6654 + pkg.packageName); 6655 break; 6656 } 6657 } 6658 return allowed; 6659 } 6660 6661 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6662 BasePermission bp, HashSet<String> origPermissions) { 6663 boolean allowed; 6664 allowed = (compareSignatures( 6665 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6666 == PackageManager.SIGNATURE_MATCH) 6667 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6668 == PackageManager.SIGNATURE_MATCH); 6669 if (!allowed && (bp.protectionLevel 6670 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6671 if (isSystemApp(pkg)) { 6672 // For updated system applications, a system permission 6673 // is granted only if it had been defined by the original application. 6674 if (isUpdatedSystemApp(pkg)) { 6675 final PackageSetting sysPs = mSettings 6676 .getDisabledSystemPkgLPr(pkg.packageName); 6677 final GrantedPermissions origGp = sysPs.sharedUser != null 6678 ? sysPs.sharedUser : sysPs; 6679 6680 if (origGp.grantedPermissions.contains(perm)) { 6681 // If the original was granted this permission, we take 6682 // that grant decision as read and propagate it to the 6683 // update. 6684 allowed = true; 6685 } else { 6686 // The system apk may have been updated with an older 6687 // version of the one on the data partition, but which 6688 // granted a new system permission that it didn't have 6689 // before. In this case we do want to allow the app to 6690 // now get the new permission if the ancestral apk is 6691 // privileged to get it. 6692 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6693 for (int j=0; 6694 j<sysPs.pkg.requestedPermissions.size(); j++) { 6695 if (perm.equals( 6696 sysPs.pkg.requestedPermissions.get(j))) { 6697 allowed = true; 6698 break; 6699 } 6700 } 6701 } 6702 } 6703 } else { 6704 allowed = isPrivilegedApp(pkg); 6705 } 6706 } 6707 } 6708 if (!allowed && (bp.protectionLevel 6709 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6710 // For development permissions, a development permission 6711 // is granted only if it was already granted. 6712 allowed = origPermissions.contains(perm); 6713 } 6714 return allowed; 6715 } 6716 6717 final class ActivityIntentResolver 6718 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6719 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6720 boolean defaultOnly, int userId) { 6721 if (!sUserManager.exists(userId)) return null; 6722 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6723 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6724 } 6725 6726 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6727 int userId) { 6728 if (!sUserManager.exists(userId)) return null; 6729 mFlags = flags; 6730 return super.queryIntent(intent, resolvedType, 6731 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6732 } 6733 6734 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6735 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6736 if (!sUserManager.exists(userId)) return null; 6737 if (packageActivities == null) { 6738 return null; 6739 } 6740 mFlags = flags; 6741 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6742 final int N = packageActivities.size(); 6743 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6744 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6745 6746 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6747 for (int i = 0; i < N; ++i) { 6748 intentFilters = packageActivities.get(i).intents; 6749 if (intentFilters != null && intentFilters.size() > 0) { 6750 PackageParser.ActivityIntentInfo[] array = 6751 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6752 intentFilters.toArray(array); 6753 listCut.add(array); 6754 } 6755 } 6756 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6757 } 6758 6759 public final void addActivity(PackageParser.Activity a, String type) { 6760 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6761 mActivities.put(a.getComponentName(), a); 6762 if (DEBUG_SHOW_INFO) 6763 Log.v( 6764 TAG, " " + type + " " + 6765 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6766 if (DEBUG_SHOW_INFO) 6767 Log.v(TAG, " Class=" + a.info.name); 6768 final int NI = a.intents.size(); 6769 for (int j=0; j<NI; j++) { 6770 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6771 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6772 intent.setPriority(0); 6773 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6774 + a.className + " with priority > 0, forcing to 0"); 6775 } 6776 if (DEBUG_SHOW_INFO) { 6777 Log.v(TAG, " IntentFilter:"); 6778 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6779 } 6780 if (!intent.debugCheck()) { 6781 Log.w(TAG, "==> For Activity " + a.info.name); 6782 } 6783 addFilter(intent); 6784 } 6785 } 6786 6787 public final void removeActivity(PackageParser.Activity a, String type) { 6788 mActivities.remove(a.getComponentName()); 6789 if (DEBUG_SHOW_INFO) { 6790 Log.v(TAG, " " + type + " " 6791 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6792 : a.info.name) + ":"); 6793 Log.v(TAG, " Class=" + a.info.name); 6794 } 6795 final int NI = a.intents.size(); 6796 for (int j=0; j<NI; j++) { 6797 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6798 if (DEBUG_SHOW_INFO) { 6799 Log.v(TAG, " IntentFilter:"); 6800 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6801 } 6802 removeFilter(intent); 6803 } 6804 } 6805 6806 @Override 6807 protected boolean allowFilterResult( 6808 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6809 ActivityInfo filterAi = filter.activity.info; 6810 for (int i=dest.size()-1; i>=0; i--) { 6811 ActivityInfo destAi = dest.get(i).activityInfo; 6812 if (destAi.name == filterAi.name 6813 && destAi.packageName == filterAi.packageName) { 6814 return false; 6815 } 6816 } 6817 return true; 6818 } 6819 6820 @Override 6821 protected ActivityIntentInfo[] newArray(int size) { 6822 return new ActivityIntentInfo[size]; 6823 } 6824 6825 @Override 6826 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6827 if (!sUserManager.exists(userId)) return true; 6828 PackageParser.Package p = filter.activity.owner; 6829 if (p != null) { 6830 PackageSetting ps = (PackageSetting)p.mExtras; 6831 if (ps != null) { 6832 // System apps are never considered stopped for purposes of 6833 // filtering, because there may be no way for the user to 6834 // actually re-launch them. 6835 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6836 && ps.getStopped(userId); 6837 } 6838 } 6839 return false; 6840 } 6841 6842 @Override 6843 protected boolean isPackageForFilter(String packageName, 6844 PackageParser.ActivityIntentInfo info) { 6845 return packageName.equals(info.activity.owner.packageName); 6846 } 6847 6848 @Override 6849 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6850 int match, int userId) { 6851 if (!sUserManager.exists(userId)) return null; 6852 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6853 return null; 6854 } 6855 final PackageParser.Activity activity = info.activity; 6856 if (mSafeMode && (activity.info.applicationInfo.flags 6857 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6858 return null; 6859 } 6860 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6861 if (ps == null) { 6862 return null; 6863 } 6864 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6865 ps.readUserState(userId), userId); 6866 if (ai == null) { 6867 return null; 6868 } 6869 final ResolveInfo res = new ResolveInfo(); 6870 res.activityInfo = ai; 6871 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6872 res.filter = info; 6873 } 6874 res.priority = info.getPriority(); 6875 res.preferredOrder = activity.owner.mPreferredOrder; 6876 //System.out.println("Result: " + res.activityInfo.className + 6877 // " = " + res.priority); 6878 res.match = match; 6879 res.isDefault = info.hasDefault; 6880 res.labelRes = info.labelRes; 6881 res.nonLocalizedLabel = info.nonLocalizedLabel; 6882 if (userNeedsBadging(userId)) { 6883 res.noResourceId = true; 6884 } else { 6885 res.icon = info.icon; 6886 } 6887 res.system = isSystemApp(res.activityInfo.applicationInfo); 6888 return res; 6889 } 6890 6891 @Override 6892 protected void sortResults(List<ResolveInfo> results) { 6893 Collections.sort(results, mResolvePrioritySorter); 6894 } 6895 6896 @Override 6897 protected void dumpFilter(PrintWriter out, String prefix, 6898 PackageParser.ActivityIntentInfo filter) { 6899 out.print(prefix); out.print( 6900 Integer.toHexString(System.identityHashCode(filter.activity))); 6901 out.print(' '); 6902 filter.activity.printComponentShortName(out); 6903 out.print(" filter "); 6904 out.println(Integer.toHexString(System.identityHashCode(filter))); 6905 } 6906 6907// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6908// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6909// final List<ResolveInfo> retList = Lists.newArrayList(); 6910// while (i.hasNext()) { 6911// final ResolveInfo resolveInfo = i.next(); 6912// if (isEnabledLP(resolveInfo.activityInfo)) { 6913// retList.add(resolveInfo); 6914// } 6915// } 6916// return retList; 6917// } 6918 6919 // Keys are String (activity class name), values are Activity. 6920 private final HashMap<ComponentName, PackageParser.Activity> mActivities 6921 = new HashMap<ComponentName, PackageParser.Activity>(); 6922 private int mFlags; 6923 } 6924 6925 private final class ServiceIntentResolver 6926 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 6927 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6928 boolean defaultOnly, int userId) { 6929 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6930 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6931 } 6932 6933 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6934 int userId) { 6935 if (!sUserManager.exists(userId)) return null; 6936 mFlags = flags; 6937 return super.queryIntent(intent, resolvedType, 6938 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6939 } 6940 6941 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6942 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 6943 if (!sUserManager.exists(userId)) return null; 6944 if (packageServices == null) { 6945 return null; 6946 } 6947 mFlags = flags; 6948 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6949 final int N = packageServices.size(); 6950 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 6951 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 6952 6953 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 6954 for (int i = 0; i < N; ++i) { 6955 intentFilters = packageServices.get(i).intents; 6956 if (intentFilters != null && intentFilters.size() > 0) { 6957 PackageParser.ServiceIntentInfo[] array = 6958 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 6959 intentFilters.toArray(array); 6960 listCut.add(array); 6961 } 6962 } 6963 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6964 } 6965 6966 public final void addService(PackageParser.Service s) { 6967 mServices.put(s.getComponentName(), s); 6968 if (DEBUG_SHOW_INFO) { 6969 Log.v(TAG, " " 6970 + (s.info.nonLocalizedLabel != null 6971 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6972 Log.v(TAG, " Class=" + s.info.name); 6973 } 6974 final int NI = s.intents.size(); 6975 int j; 6976 for (j=0; j<NI; j++) { 6977 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6978 if (DEBUG_SHOW_INFO) { 6979 Log.v(TAG, " IntentFilter:"); 6980 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6981 } 6982 if (!intent.debugCheck()) { 6983 Log.w(TAG, "==> For Service " + s.info.name); 6984 } 6985 addFilter(intent); 6986 } 6987 } 6988 6989 public final void removeService(PackageParser.Service s) { 6990 mServices.remove(s.getComponentName()); 6991 if (DEBUG_SHOW_INFO) { 6992 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 6993 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6994 Log.v(TAG, " Class=" + s.info.name); 6995 } 6996 final int NI = s.intents.size(); 6997 int j; 6998 for (j=0; j<NI; j++) { 6999 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7000 if (DEBUG_SHOW_INFO) { 7001 Log.v(TAG, " IntentFilter:"); 7002 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7003 } 7004 removeFilter(intent); 7005 } 7006 } 7007 7008 @Override 7009 protected boolean allowFilterResult( 7010 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7011 ServiceInfo filterSi = filter.service.info; 7012 for (int i=dest.size()-1; i>=0; i--) { 7013 ServiceInfo destAi = dest.get(i).serviceInfo; 7014 if (destAi.name == filterSi.name 7015 && destAi.packageName == filterSi.packageName) { 7016 return false; 7017 } 7018 } 7019 return true; 7020 } 7021 7022 @Override 7023 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7024 return new PackageParser.ServiceIntentInfo[size]; 7025 } 7026 7027 @Override 7028 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7029 if (!sUserManager.exists(userId)) return true; 7030 PackageParser.Package p = filter.service.owner; 7031 if (p != null) { 7032 PackageSetting ps = (PackageSetting)p.mExtras; 7033 if (ps != null) { 7034 // System apps are never considered stopped for purposes of 7035 // filtering, because there may be no way for the user to 7036 // actually re-launch them. 7037 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7038 && ps.getStopped(userId); 7039 } 7040 } 7041 return false; 7042 } 7043 7044 @Override 7045 protected boolean isPackageForFilter(String packageName, 7046 PackageParser.ServiceIntentInfo info) { 7047 return packageName.equals(info.service.owner.packageName); 7048 } 7049 7050 @Override 7051 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7052 int match, int userId) { 7053 if (!sUserManager.exists(userId)) return null; 7054 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7055 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7056 return null; 7057 } 7058 final PackageParser.Service service = info.service; 7059 if (mSafeMode && (service.info.applicationInfo.flags 7060 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7061 return null; 7062 } 7063 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7064 if (ps == null) { 7065 return null; 7066 } 7067 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7068 ps.readUserState(userId), userId); 7069 if (si == null) { 7070 return null; 7071 } 7072 final ResolveInfo res = new ResolveInfo(); 7073 res.serviceInfo = si; 7074 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7075 res.filter = filter; 7076 } 7077 res.priority = info.getPriority(); 7078 res.preferredOrder = service.owner.mPreferredOrder; 7079 //System.out.println("Result: " + res.activityInfo.className + 7080 // " = " + res.priority); 7081 res.match = match; 7082 res.isDefault = info.hasDefault; 7083 res.labelRes = info.labelRes; 7084 res.nonLocalizedLabel = info.nonLocalizedLabel; 7085 res.icon = info.icon; 7086 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7087 return res; 7088 } 7089 7090 @Override 7091 protected void sortResults(List<ResolveInfo> results) { 7092 Collections.sort(results, mResolvePrioritySorter); 7093 } 7094 7095 @Override 7096 protected void dumpFilter(PrintWriter out, String prefix, 7097 PackageParser.ServiceIntentInfo filter) { 7098 out.print(prefix); out.print( 7099 Integer.toHexString(System.identityHashCode(filter.service))); 7100 out.print(' '); 7101 filter.service.printComponentShortName(out); 7102 out.print(" filter "); 7103 out.println(Integer.toHexString(System.identityHashCode(filter))); 7104 } 7105 7106// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7107// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7108// final List<ResolveInfo> retList = Lists.newArrayList(); 7109// while (i.hasNext()) { 7110// final ResolveInfo resolveInfo = (ResolveInfo) i; 7111// if (isEnabledLP(resolveInfo.serviceInfo)) { 7112// retList.add(resolveInfo); 7113// } 7114// } 7115// return retList; 7116// } 7117 7118 // Keys are String (activity class name), values are Activity. 7119 private final HashMap<ComponentName, PackageParser.Service> mServices 7120 = new HashMap<ComponentName, PackageParser.Service>(); 7121 private int mFlags; 7122 }; 7123 7124 private final class ProviderIntentResolver 7125 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7126 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7127 boolean defaultOnly, int userId) { 7128 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7129 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7130 } 7131 7132 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7133 int userId) { 7134 if (!sUserManager.exists(userId)) 7135 return null; 7136 mFlags = flags; 7137 return super.queryIntent(intent, resolvedType, 7138 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7139 } 7140 7141 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7142 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7143 if (!sUserManager.exists(userId)) 7144 return null; 7145 if (packageProviders == null) { 7146 return null; 7147 } 7148 mFlags = flags; 7149 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7150 final int N = packageProviders.size(); 7151 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7152 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7153 7154 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7155 for (int i = 0; i < N; ++i) { 7156 intentFilters = packageProviders.get(i).intents; 7157 if (intentFilters != null && intentFilters.size() > 0) { 7158 PackageParser.ProviderIntentInfo[] array = 7159 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7160 intentFilters.toArray(array); 7161 listCut.add(array); 7162 } 7163 } 7164 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7165 } 7166 7167 public final void addProvider(PackageParser.Provider p) { 7168 if (mProviders.containsKey(p.getComponentName())) { 7169 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7170 return; 7171 } 7172 7173 mProviders.put(p.getComponentName(), p); 7174 if (DEBUG_SHOW_INFO) { 7175 Log.v(TAG, " " 7176 + (p.info.nonLocalizedLabel != null 7177 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7178 Log.v(TAG, " Class=" + p.info.name); 7179 } 7180 final int NI = p.intents.size(); 7181 int j; 7182 for (j = 0; j < NI; j++) { 7183 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7184 if (DEBUG_SHOW_INFO) { 7185 Log.v(TAG, " IntentFilter:"); 7186 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7187 } 7188 if (!intent.debugCheck()) { 7189 Log.w(TAG, "==> For Provider " + p.info.name); 7190 } 7191 addFilter(intent); 7192 } 7193 } 7194 7195 public final void removeProvider(PackageParser.Provider p) { 7196 mProviders.remove(p.getComponentName()); 7197 if (DEBUG_SHOW_INFO) { 7198 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7199 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7200 Log.v(TAG, " Class=" + p.info.name); 7201 } 7202 final int NI = p.intents.size(); 7203 int j; 7204 for (j = 0; j < NI; j++) { 7205 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7206 if (DEBUG_SHOW_INFO) { 7207 Log.v(TAG, " IntentFilter:"); 7208 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7209 } 7210 removeFilter(intent); 7211 } 7212 } 7213 7214 @Override 7215 protected boolean allowFilterResult( 7216 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7217 ProviderInfo filterPi = filter.provider.info; 7218 for (int i = dest.size() - 1; i >= 0; i--) { 7219 ProviderInfo destPi = dest.get(i).providerInfo; 7220 if (destPi.name == filterPi.name 7221 && destPi.packageName == filterPi.packageName) { 7222 return false; 7223 } 7224 } 7225 return true; 7226 } 7227 7228 @Override 7229 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7230 return new PackageParser.ProviderIntentInfo[size]; 7231 } 7232 7233 @Override 7234 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7235 if (!sUserManager.exists(userId)) 7236 return true; 7237 PackageParser.Package p = filter.provider.owner; 7238 if (p != null) { 7239 PackageSetting ps = (PackageSetting) p.mExtras; 7240 if (ps != null) { 7241 // System apps are never considered stopped for purposes of 7242 // filtering, because there may be no way for the user to 7243 // actually re-launch them. 7244 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7245 && ps.getStopped(userId); 7246 } 7247 } 7248 return false; 7249 } 7250 7251 @Override 7252 protected boolean isPackageForFilter(String packageName, 7253 PackageParser.ProviderIntentInfo info) { 7254 return packageName.equals(info.provider.owner.packageName); 7255 } 7256 7257 @Override 7258 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7259 int match, int userId) { 7260 if (!sUserManager.exists(userId)) 7261 return null; 7262 final PackageParser.ProviderIntentInfo info = filter; 7263 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7264 return null; 7265 } 7266 final PackageParser.Provider provider = info.provider; 7267 if (mSafeMode && (provider.info.applicationInfo.flags 7268 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7269 return null; 7270 } 7271 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7272 if (ps == null) { 7273 return null; 7274 } 7275 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7276 ps.readUserState(userId), userId); 7277 if (pi == null) { 7278 return null; 7279 } 7280 final ResolveInfo res = new ResolveInfo(); 7281 res.providerInfo = pi; 7282 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7283 res.filter = filter; 7284 } 7285 res.priority = info.getPriority(); 7286 res.preferredOrder = provider.owner.mPreferredOrder; 7287 res.match = match; 7288 res.isDefault = info.hasDefault; 7289 res.labelRes = info.labelRes; 7290 res.nonLocalizedLabel = info.nonLocalizedLabel; 7291 res.icon = info.icon; 7292 res.system = isSystemApp(res.providerInfo.applicationInfo); 7293 return res; 7294 } 7295 7296 @Override 7297 protected void sortResults(List<ResolveInfo> results) { 7298 Collections.sort(results, mResolvePrioritySorter); 7299 } 7300 7301 @Override 7302 protected void dumpFilter(PrintWriter out, String prefix, 7303 PackageParser.ProviderIntentInfo filter) { 7304 out.print(prefix); 7305 out.print( 7306 Integer.toHexString(System.identityHashCode(filter.provider))); 7307 out.print(' '); 7308 filter.provider.printComponentShortName(out); 7309 out.print(" filter "); 7310 out.println(Integer.toHexString(System.identityHashCode(filter))); 7311 } 7312 7313 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7314 = new HashMap<ComponentName, PackageParser.Provider>(); 7315 private int mFlags; 7316 }; 7317 7318 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7319 new Comparator<ResolveInfo>() { 7320 public int compare(ResolveInfo r1, ResolveInfo r2) { 7321 int v1 = r1.priority; 7322 int v2 = r2.priority; 7323 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7324 if (v1 != v2) { 7325 return (v1 > v2) ? -1 : 1; 7326 } 7327 v1 = r1.preferredOrder; 7328 v2 = r2.preferredOrder; 7329 if (v1 != v2) { 7330 return (v1 > v2) ? -1 : 1; 7331 } 7332 if (r1.isDefault != r2.isDefault) { 7333 return r1.isDefault ? -1 : 1; 7334 } 7335 v1 = r1.match; 7336 v2 = r2.match; 7337 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7338 if (v1 != v2) { 7339 return (v1 > v2) ? -1 : 1; 7340 } 7341 if (r1.system != r2.system) { 7342 return r1.system ? -1 : 1; 7343 } 7344 return 0; 7345 } 7346 }; 7347 7348 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7349 new Comparator<ProviderInfo>() { 7350 public int compare(ProviderInfo p1, ProviderInfo p2) { 7351 final int v1 = p1.initOrder; 7352 final int v2 = p2.initOrder; 7353 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7354 } 7355 }; 7356 7357 static final void sendPackageBroadcast(String action, String pkg, 7358 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7359 int[] userIds) { 7360 IActivityManager am = ActivityManagerNative.getDefault(); 7361 if (am != null) { 7362 try { 7363 if (userIds == null) { 7364 userIds = am.getRunningUserIds(); 7365 } 7366 for (int id : userIds) { 7367 final Intent intent = new Intent(action, 7368 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7369 if (extras != null) { 7370 intent.putExtras(extras); 7371 } 7372 if (targetPkg != null) { 7373 intent.setPackage(targetPkg); 7374 } 7375 // Modify the UID when posting to other users 7376 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7377 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7378 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7379 intent.putExtra(Intent.EXTRA_UID, uid); 7380 } 7381 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7382 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7383 if (DEBUG_BROADCASTS) { 7384 RuntimeException here = new RuntimeException("here"); 7385 here.fillInStackTrace(); 7386 Slog.d(TAG, "Sending to user " + id + ": " 7387 + intent.toShortString(false, true, false, false) 7388 + " " + intent.getExtras(), here); 7389 } 7390 am.broadcastIntent(null, intent, null, finishedReceiver, 7391 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7392 finishedReceiver != null, false, id); 7393 } 7394 } catch (RemoteException ex) { 7395 } 7396 } 7397 } 7398 7399 /** 7400 * Check if the external storage media is available. This is true if there 7401 * is a mounted external storage medium or if the external storage is 7402 * emulated. 7403 */ 7404 private boolean isExternalMediaAvailable() { 7405 return mMediaMounted || Environment.isExternalStorageEmulated(); 7406 } 7407 7408 @Override 7409 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7410 // writer 7411 synchronized (mPackages) { 7412 if (!isExternalMediaAvailable()) { 7413 // If the external storage is no longer mounted at this point, 7414 // the caller may not have been able to delete all of this 7415 // packages files and can not delete any more. Bail. 7416 return null; 7417 } 7418 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7419 if (lastPackage != null) { 7420 pkgs.remove(lastPackage); 7421 } 7422 if (pkgs.size() > 0) { 7423 return pkgs.get(0); 7424 } 7425 } 7426 return null; 7427 } 7428 7429 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7430 if (false) { 7431 RuntimeException here = new RuntimeException("here"); 7432 here.fillInStackTrace(); 7433 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7434 + " andCode=" + andCode, here); 7435 } 7436 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7437 userId, andCode ? 1 : 0, packageName)); 7438 } 7439 7440 void startCleaningPackages() { 7441 // reader 7442 synchronized (mPackages) { 7443 if (!isExternalMediaAvailable()) { 7444 return; 7445 } 7446 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7447 return; 7448 } 7449 } 7450 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7451 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7452 IActivityManager am = ActivityManagerNative.getDefault(); 7453 if (am != null) { 7454 try { 7455 am.startService(null, intent, null, UserHandle.USER_OWNER); 7456 } catch (RemoteException e) { 7457 } 7458 } 7459 } 7460 7461 private final class AppDirObserver extends FileObserver { 7462 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7463 super(path, mask); 7464 mRootDir = path; 7465 mIsRom = isrom; 7466 mIsPrivileged = isPrivileged; 7467 } 7468 7469 public void onEvent(int event, String path) { 7470 String removedPackage = null; 7471 int removedAppId = -1; 7472 int[] removedUsers = null; 7473 String addedPackage = null; 7474 int addedAppId = -1; 7475 int[] addedUsers = null; 7476 7477 // TODO post a message to the handler to obtain serial ordering 7478 synchronized (mInstallLock) { 7479 String fullPathStr = null; 7480 File fullPath = null; 7481 if (path != null) { 7482 fullPath = new File(mRootDir, path); 7483 fullPathStr = fullPath.getPath(); 7484 } 7485 7486 if (DEBUG_APP_DIR_OBSERVER) 7487 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7488 7489 if (!isPackageFilename(path)) { 7490 if (DEBUG_APP_DIR_OBSERVER) 7491 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7492 return; 7493 } 7494 7495 // Ignore packages that are being installed or 7496 // have just been installed. 7497 if (ignoreCodePath(fullPathStr)) { 7498 return; 7499 } 7500 PackageParser.Package p = null; 7501 PackageSetting ps = null; 7502 // reader 7503 synchronized (mPackages) { 7504 p = mAppDirs.get(fullPathStr); 7505 if (p != null) { 7506 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7507 if (ps != null) { 7508 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7509 } else { 7510 removedUsers = sUserManager.getUserIds(); 7511 } 7512 } 7513 addedUsers = sUserManager.getUserIds(); 7514 } 7515 if ((event&REMOVE_EVENTS) != 0) { 7516 if (ps != null) { 7517 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7518 removePackageLI(ps, true); 7519 removedPackage = ps.name; 7520 removedAppId = ps.appId; 7521 } 7522 } 7523 7524 if ((event&ADD_EVENTS) != 0) { 7525 if (p == null) { 7526 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7527 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7528 if (mIsRom) { 7529 flags |= PackageParser.PARSE_IS_SYSTEM 7530 | PackageParser.PARSE_IS_SYSTEM_DIR; 7531 if (mIsPrivileged) { 7532 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7533 } 7534 } 7535 p = scanPackageLI(fullPath, flags, 7536 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7537 System.currentTimeMillis(), UserHandle.ALL, null); 7538 if (p != null) { 7539 /* 7540 * TODO this seems dangerous as the package may have 7541 * changed since we last acquired the mPackages 7542 * lock. 7543 */ 7544 // writer 7545 synchronized (mPackages) { 7546 updatePermissionsLPw(p.packageName, p, 7547 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7548 } 7549 addedPackage = p.applicationInfo.packageName; 7550 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7551 } 7552 } 7553 } 7554 7555 // reader 7556 synchronized (mPackages) { 7557 mSettings.writeLPr(); 7558 } 7559 } 7560 7561 if (removedPackage != null) { 7562 Bundle extras = new Bundle(1); 7563 extras.putInt(Intent.EXTRA_UID, removedAppId); 7564 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7565 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7566 extras, null, null, removedUsers); 7567 } 7568 if (addedPackage != null) { 7569 Bundle extras = new Bundle(1); 7570 extras.putInt(Intent.EXTRA_UID, addedAppId); 7571 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7572 extras, null, null, addedUsers); 7573 } 7574 } 7575 7576 private final String mRootDir; 7577 private final boolean mIsRom; 7578 private final boolean mIsPrivileged; 7579 } 7580 7581 /* 7582 * The old-style observer methods all just trampoline to the newer signature with 7583 * expanded install observer API. The older API continues to work but does not 7584 * supply the additional details of the Observer2 API. 7585 */ 7586 7587 /* Called when a downloaded package installation has been confirmed by the user */ 7588 public void installPackage( 7589 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 7590 installPackageEtc(packageURI, observer, null, flags, null); 7591 } 7592 7593 /* Called when a downloaded package installation has been confirmed by the user */ 7594 @Override 7595 public void installPackage( 7596 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 7597 final String installerPackageName) { 7598 installPackageWithVerificationEtc(packageURI, observer, null, flags, 7599 installerPackageName, null, null, null); 7600 } 7601 7602 @Override 7603 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 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, null, flags, 7609 installerPackageName, verificationParams, encryptionParams); 7610 } 7611 7612 @Override 7613 public void installPackageWithVerificationAndEncryption(Uri packageURI, 7614 IPackageInstallObserver observer, int flags, String installerPackageName, 7615 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7616 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7617 installerPackageName, verificationParams, encryptionParams); 7618 } 7619 7620 /* 7621 * And here are the "live" versions that take both observer arguments 7622 */ 7623 public void installPackageEtc( 7624 final Uri packageURI, final IPackageInstallObserver observer, 7625 IPackageInstallObserver2 observer2, final int flags) { 7626 installPackageEtc(packageURI, observer, observer2, flags, null); 7627 } 7628 7629 public void installPackageEtc( 7630 final Uri packageURI, final IPackageInstallObserver observer, 7631 final IPackageInstallObserver2 observer2, final int flags, 7632 final String installerPackageName) { 7633 installPackageWithVerificationEtc(packageURI, observer, observer2, flags, 7634 installerPackageName, null, null, null); 7635 } 7636 7637 @Override 7638 public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer, 7639 IPackageInstallObserver2 observer2, 7640 int flags, String installerPackageName, Uri verificationURI, 7641 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7642 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7643 VerificationParams.NO_UID, manifestDigest); 7644 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags, 7645 installerPackageName, verificationParams, encryptionParams); 7646 } 7647 7648 /* 7649 * All of the installPackage...*() methods redirect to this one for the master implementation 7650 */ 7651 public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI, 7652 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7653 int flags, String installerPackageName, 7654 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7655 if (observer == null && observer2 == null) { 7656 throw new IllegalArgumentException("No install observer supplied"); 7657 } 7658 installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2, 7659 flags, installerPackageName, verificationParams, encryptionParams, null); 7660 } 7661 7662 @Override 7663 public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI, 7664 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7665 int flags, String installerPackageName, 7666 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams, 7667 String packageAbiOverride) { 7668 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7669 null); 7670 7671 final int uid = Binder.getCallingUid(); 7672 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7673 try { 7674 if (observer != null) { 7675 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7676 } 7677 if (observer2 != null) { 7678 observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7679 } 7680 } catch (RemoteException re) { 7681 } 7682 return; 7683 } 7684 7685 UserHandle user; 7686 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7687 user = UserHandle.ALL; 7688 } else { 7689 user = new UserHandle(UserHandle.getUserId(uid)); 7690 } 7691 7692 final int filteredFlags; 7693 7694 if (uid == Process.SHELL_UID || uid == 0) { 7695 if (DEBUG_INSTALL) { 7696 Slog.v(TAG, "Install from ADB"); 7697 } 7698 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7699 } else { 7700 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7701 } 7702 7703 verificationParams.setInstallerUid(uid); 7704 7705 if (!"file".equals(packageURI.getScheme())) { 7706 throw new UnsupportedOperationException("Only file:// URIs are supported"); 7707 } 7708 final File fromFile = new File(packageURI.getPath()); 7709 7710 final Message msg = mHandler.obtainMessage(INIT_COPY); 7711 msg.obj = new InstallParams(fromFile, observer, observer2, filteredFlags, 7712 installerPackageName, verificationParams, encryptionParams, user, 7713 packageAbiOverride); 7714 mHandler.sendMessage(msg); 7715 } 7716 7717 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7718 Bundle extras = new Bundle(1); 7719 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7720 7721 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7722 packageName, extras, null, null, new int[] {userId}); 7723 try { 7724 IActivityManager am = ActivityManagerNative.getDefault(); 7725 final boolean isSystem = 7726 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7727 if (isSystem && am.isUserRunning(userId, false)) { 7728 // The just-installed/enabled app is bundled on the system, so presumed 7729 // to be able to run automatically without needing an explicit launch. 7730 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7731 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7732 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7733 .setPackage(packageName); 7734 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7735 android.app.AppOpsManager.OP_NONE, false, false, userId); 7736 } 7737 } catch (RemoteException e) { 7738 // shouldn't happen 7739 Slog.w(TAG, "Unable to bootstrap installed package", e); 7740 } 7741 } 7742 7743 @Override 7744 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7745 int userId) { 7746 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7747 PackageSetting pkgSetting; 7748 final int uid = Binder.getCallingUid(); 7749 if (UserHandle.getUserId(uid) != userId) { 7750 mContext.enforceCallingOrSelfPermission( 7751 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7752 "setApplicationBlockedSetting for user " + userId); 7753 } 7754 7755 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7756 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7757 return false; 7758 } 7759 7760 long callingId = Binder.clearCallingIdentity(); 7761 try { 7762 boolean sendAdded = false; 7763 boolean sendRemoved = false; 7764 // writer 7765 synchronized (mPackages) { 7766 pkgSetting = mSettings.mPackages.get(packageName); 7767 if (pkgSetting == null) { 7768 return false; 7769 } 7770 if (pkgSetting.getBlocked(userId) != blocked) { 7771 pkgSetting.setBlocked(blocked, userId); 7772 mSettings.writePackageRestrictionsLPr(userId); 7773 if (blocked) { 7774 sendRemoved = true; 7775 } else { 7776 sendAdded = true; 7777 } 7778 } 7779 } 7780 if (sendAdded) { 7781 sendPackageAddedForUser(packageName, pkgSetting, userId); 7782 return true; 7783 } 7784 if (sendRemoved) { 7785 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7786 "blocking pkg"); 7787 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7788 } 7789 } finally { 7790 Binder.restoreCallingIdentity(callingId); 7791 } 7792 return false; 7793 } 7794 7795 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7796 int userId) { 7797 final PackageRemovedInfo info = new PackageRemovedInfo(); 7798 info.removedPackage = packageName; 7799 info.removedUsers = new int[] {userId}; 7800 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7801 info.sendBroadcast(false, false, false); 7802 } 7803 7804 /** 7805 * Returns true if application is not found or there was an error. Otherwise it returns 7806 * the blocked state of the package for the given user. 7807 */ 7808 @Override 7809 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7810 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7811 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7812 "getApplicationBlocked for user " + userId); 7813 PackageSetting pkgSetting; 7814 long callingId = Binder.clearCallingIdentity(); 7815 try { 7816 // writer 7817 synchronized (mPackages) { 7818 pkgSetting = mSettings.mPackages.get(packageName); 7819 if (pkgSetting == null) { 7820 return true; 7821 } 7822 return pkgSetting.getBlocked(userId); 7823 } 7824 } finally { 7825 Binder.restoreCallingIdentity(callingId); 7826 } 7827 } 7828 7829 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer2, 7830 PackageInstallerParams params, String installerPackageName, int installerUid, 7831 UserHandle user) { 7832 Slog.e(TAG, "TODO: install stage!"); 7833 try { 7834 observer2.packageInstalled(packageName, null, 7835 PackageManager.INSTALL_FAILED_INTERNAL_ERROR); 7836 } catch (RemoteException ignored) { 7837 } 7838 } 7839 7840 /** 7841 * @hide 7842 */ 7843 @Override 7844 public int installExistingPackageAsUser(String packageName, int userId) { 7845 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7846 null); 7847 PackageSetting pkgSetting; 7848 final int uid = Binder.getCallingUid(); 7849 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7850 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7851 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7852 } 7853 7854 long callingId = Binder.clearCallingIdentity(); 7855 try { 7856 boolean sendAdded = false; 7857 Bundle extras = new Bundle(1); 7858 7859 // writer 7860 synchronized (mPackages) { 7861 pkgSetting = mSettings.mPackages.get(packageName); 7862 if (pkgSetting == null) { 7863 return PackageManager.INSTALL_FAILED_INVALID_URI; 7864 } 7865 if (!pkgSetting.getInstalled(userId)) { 7866 pkgSetting.setInstalled(true, userId); 7867 pkgSetting.setBlocked(false, userId); 7868 mSettings.writePackageRestrictionsLPr(userId); 7869 sendAdded = true; 7870 } 7871 } 7872 7873 if (sendAdded) { 7874 sendPackageAddedForUser(packageName, pkgSetting, userId); 7875 } 7876 } finally { 7877 Binder.restoreCallingIdentity(callingId); 7878 } 7879 7880 return PackageManager.INSTALL_SUCCEEDED; 7881 } 7882 7883 boolean isUserRestricted(int userId, String restrictionKey) { 7884 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7885 if (restrictions.getBoolean(restrictionKey, false)) { 7886 Log.w(TAG, "User is restricted: " + restrictionKey); 7887 return true; 7888 } 7889 return false; 7890 } 7891 7892 @Override 7893 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7894 mContext.enforceCallingOrSelfPermission( 7895 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7896 "Only package verification agents can verify applications"); 7897 7898 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7899 final PackageVerificationResponse response = new PackageVerificationResponse( 7900 verificationCode, Binder.getCallingUid()); 7901 msg.arg1 = id; 7902 msg.obj = response; 7903 mHandler.sendMessage(msg); 7904 } 7905 7906 @Override 7907 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7908 long millisecondsToDelay) { 7909 mContext.enforceCallingOrSelfPermission( 7910 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7911 "Only package verification agents can extend verification timeouts"); 7912 7913 final PackageVerificationState state = mPendingVerification.get(id); 7914 final PackageVerificationResponse response = new PackageVerificationResponse( 7915 verificationCodeAtTimeout, Binder.getCallingUid()); 7916 7917 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7918 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7919 } 7920 if (millisecondsToDelay < 0) { 7921 millisecondsToDelay = 0; 7922 } 7923 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7924 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7925 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7926 } 7927 7928 if ((state != null) && !state.timeoutExtended()) { 7929 state.extendTimeout(); 7930 7931 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7932 msg.arg1 = id; 7933 msg.obj = response; 7934 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7935 } 7936 } 7937 7938 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7939 int verificationCode, UserHandle user) { 7940 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7941 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7942 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7943 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7944 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7945 7946 mContext.sendBroadcastAsUser(intent, user, 7947 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7948 } 7949 7950 private ComponentName matchComponentForVerifier(String packageName, 7951 List<ResolveInfo> receivers) { 7952 ActivityInfo targetReceiver = null; 7953 7954 final int NR = receivers.size(); 7955 for (int i = 0; i < NR; i++) { 7956 final ResolveInfo info = receivers.get(i); 7957 if (info.activityInfo == null) { 7958 continue; 7959 } 7960 7961 if (packageName.equals(info.activityInfo.packageName)) { 7962 targetReceiver = info.activityInfo; 7963 break; 7964 } 7965 } 7966 7967 if (targetReceiver == null) { 7968 return null; 7969 } 7970 7971 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 7972 } 7973 7974 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 7975 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 7976 if (pkgInfo.verifiers.length == 0) { 7977 return null; 7978 } 7979 7980 final int N = pkgInfo.verifiers.length; 7981 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 7982 for (int i = 0; i < N; i++) { 7983 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 7984 7985 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 7986 receivers); 7987 if (comp == null) { 7988 continue; 7989 } 7990 7991 final int verifierUid = getUidForVerifier(verifierInfo); 7992 if (verifierUid == -1) { 7993 continue; 7994 } 7995 7996 if (DEBUG_VERIFY) { 7997 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 7998 + " with the correct signature"); 7999 } 8000 sufficientVerifiers.add(comp); 8001 verificationState.addSufficientVerifier(verifierUid); 8002 } 8003 8004 return sufficientVerifiers; 8005 } 8006 8007 private int getUidForVerifier(VerifierInfo verifierInfo) { 8008 synchronized (mPackages) { 8009 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8010 if (pkg == null) { 8011 return -1; 8012 } else if (pkg.mSignatures.length != 1) { 8013 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8014 + " has more than one signature; ignoring"); 8015 return -1; 8016 } 8017 8018 /* 8019 * If the public key of the package's signature does not match 8020 * our expected public key, then this is a different package and 8021 * we should skip. 8022 */ 8023 8024 final byte[] expectedPublicKey; 8025 try { 8026 final Signature verifierSig = pkg.mSignatures[0]; 8027 final PublicKey publicKey = verifierSig.getPublicKey(); 8028 expectedPublicKey = publicKey.getEncoded(); 8029 } catch (CertificateException e) { 8030 return -1; 8031 } 8032 8033 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8034 8035 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8036 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8037 + " does not have the expected public key; ignoring"); 8038 return -1; 8039 } 8040 8041 return pkg.applicationInfo.uid; 8042 } 8043 } 8044 8045 @Override 8046 public void finishPackageInstall(int token) { 8047 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8048 8049 if (DEBUG_INSTALL) { 8050 Slog.v(TAG, "BM finishing package install for " + token); 8051 } 8052 8053 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8054 mHandler.sendMessage(msg); 8055 } 8056 8057 /** 8058 * Get the verification agent timeout. 8059 * 8060 * @return verification timeout in milliseconds 8061 */ 8062 private long getVerificationTimeout() { 8063 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8064 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8065 DEFAULT_VERIFICATION_TIMEOUT); 8066 } 8067 8068 /** 8069 * Get the default verification agent response code. 8070 * 8071 * @return default verification response code 8072 */ 8073 private int getDefaultVerificationResponse() { 8074 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8075 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8076 DEFAULT_VERIFICATION_RESPONSE); 8077 } 8078 8079 /** 8080 * Check whether or not package verification has been enabled. 8081 * 8082 * @return true if verification should be performed 8083 */ 8084 private boolean isVerificationEnabled(int userId, int flags) { 8085 if (!DEFAULT_VERIFY_ENABLE) { 8086 return false; 8087 } 8088 8089 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8090 8091 // Check if installing from ADB 8092 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8093 // Do not run verification in a test harness environment 8094 if (ActivityManager.isRunningInTestHarness()) { 8095 return false; 8096 } 8097 if (ensureVerifyAppsEnabled) { 8098 return true; 8099 } 8100 // Check if the developer does not want package verification for ADB installs 8101 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8102 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8103 return false; 8104 } 8105 } 8106 8107 if (ensureVerifyAppsEnabled) { 8108 return true; 8109 } 8110 8111 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8112 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8113 } 8114 8115 /** 8116 * Get the "allow unknown sources" setting. 8117 * 8118 * @return the current "allow unknown sources" setting 8119 */ 8120 private int getUnknownSourcesSettings() { 8121 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8122 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8123 -1); 8124 } 8125 8126 @Override 8127 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8128 final int uid = Binder.getCallingUid(); 8129 // writer 8130 synchronized (mPackages) { 8131 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8132 if (targetPackageSetting == null) { 8133 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8134 } 8135 8136 PackageSetting installerPackageSetting; 8137 if (installerPackageName != null) { 8138 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8139 if (installerPackageSetting == null) { 8140 throw new IllegalArgumentException("Unknown installer package: " 8141 + installerPackageName); 8142 } 8143 } else { 8144 installerPackageSetting = null; 8145 } 8146 8147 Signature[] callerSignature; 8148 Object obj = mSettings.getUserIdLPr(uid); 8149 if (obj != null) { 8150 if (obj instanceof SharedUserSetting) { 8151 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8152 } else if (obj instanceof PackageSetting) { 8153 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8154 } else { 8155 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8156 } 8157 } else { 8158 throw new SecurityException("Unknown calling uid " + uid); 8159 } 8160 8161 // Verify: can't set installerPackageName to a package that is 8162 // not signed with the same cert as the caller. 8163 if (installerPackageSetting != null) { 8164 if (compareSignatures(callerSignature, 8165 installerPackageSetting.signatures.mSignatures) 8166 != PackageManager.SIGNATURE_MATCH) { 8167 throw new SecurityException( 8168 "Caller does not have same cert as new installer package " 8169 + installerPackageName); 8170 } 8171 } 8172 8173 // Verify: if target already has an installer package, it must 8174 // be signed with the same cert as the caller. 8175 if (targetPackageSetting.installerPackageName != null) { 8176 PackageSetting setting = mSettings.mPackages.get( 8177 targetPackageSetting.installerPackageName); 8178 // If the currently set package isn't valid, then it's always 8179 // okay to change it. 8180 if (setting != null) { 8181 if (compareSignatures(callerSignature, 8182 setting.signatures.mSignatures) 8183 != PackageManager.SIGNATURE_MATCH) { 8184 throw new SecurityException( 8185 "Caller does not have same cert as old installer package " 8186 + targetPackageSetting.installerPackageName); 8187 } 8188 } 8189 } 8190 8191 // Okay! 8192 targetPackageSetting.installerPackageName = installerPackageName; 8193 scheduleWriteSettingsLocked(); 8194 } 8195 } 8196 8197 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8198 // Queue up an async operation since the package installation may take a little while. 8199 mHandler.post(new Runnable() { 8200 public void run() { 8201 mHandler.removeCallbacks(this); 8202 // Result object to be returned 8203 PackageInstalledInfo res = new PackageInstalledInfo(); 8204 res.returnCode = currentStatus; 8205 res.uid = -1; 8206 res.pkg = null; 8207 res.removedInfo = new PackageRemovedInfo(); 8208 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8209 args.doPreInstall(res.returnCode); 8210 synchronized (mInstallLock) { 8211 installPackageLI(args, true, res); 8212 } 8213 args.doPostInstall(res.returnCode, res.uid); 8214 } 8215 8216 // A restore should be performed at this point if (a) the install 8217 // succeeded, (b) the operation is not an update, and (c) the new 8218 // package has a backupAgent defined. 8219 final boolean update = res.removedInfo.removedPackage != null; 8220 boolean doRestore = (!update 8221 && res.pkg != null 8222 && res.pkg.applicationInfo.backupAgentName != null); 8223 8224 // Set up the post-install work request bookkeeping. This will be used 8225 // and cleaned up by the post-install event handling regardless of whether 8226 // there's a restore pass performed. Token values are >= 1. 8227 int token; 8228 if (mNextInstallToken < 0) mNextInstallToken = 1; 8229 token = mNextInstallToken++; 8230 8231 PostInstallData data = new PostInstallData(args, res); 8232 mRunningInstalls.put(token, data); 8233 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8234 8235 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8236 // Pass responsibility to the Backup Manager. It will perform a 8237 // restore if appropriate, then pass responsibility back to the 8238 // Package Manager to run the post-install observer callbacks 8239 // and broadcasts. 8240 IBackupManager bm = IBackupManager.Stub.asInterface( 8241 ServiceManager.getService(Context.BACKUP_SERVICE)); 8242 if (bm != null) { 8243 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8244 + " to BM for possible restore"); 8245 try { 8246 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8247 } catch (RemoteException e) { 8248 // can't happen; the backup manager is local 8249 } catch (Exception e) { 8250 Slog.e(TAG, "Exception trying to enqueue restore", e); 8251 doRestore = false; 8252 } 8253 } else { 8254 Slog.e(TAG, "Backup Manager not found!"); 8255 doRestore = false; 8256 } 8257 } 8258 8259 if (!doRestore) { 8260 // No restore possible, or the Backup Manager was mysteriously not 8261 // available -- just fire the post-install work request directly. 8262 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8263 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8264 mHandler.sendMessage(msg); 8265 } 8266 } 8267 }); 8268 } 8269 8270 private abstract class HandlerParams { 8271 private static final int MAX_RETRIES = 4; 8272 8273 /** 8274 * Number of times startCopy() has been attempted and had a non-fatal 8275 * error. 8276 */ 8277 private int mRetries = 0; 8278 8279 /** User handle for the user requesting the information or installation. */ 8280 private final UserHandle mUser; 8281 8282 HandlerParams(UserHandle user) { 8283 mUser = user; 8284 } 8285 8286 UserHandle getUser() { 8287 return mUser; 8288 } 8289 8290 final boolean startCopy() { 8291 boolean res; 8292 try { 8293 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8294 8295 if (++mRetries > MAX_RETRIES) { 8296 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8297 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8298 handleServiceError(); 8299 return false; 8300 } else { 8301 handleStartCopy(); 8302 res = true; 8303 } 8304 } catch (RemoteException e) { 8305 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8306 mHandler.sendEmptyMessage(MCS_RECONNECT); 8307 res = false; 8308 } 8309 handleReturnCode(); 8310 return res; 8311 } 8312 8313 final void serviceError() { 8314 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8315 handleServiceError(); 8316 handleReturnCode(); 8317 } 8318 8319 abstract void handleStartCopy() throws RemoteException; 8320 abstract void handleServiceError(); 8321 abstract void handleReturnCode(); 8322 } 8323 8324 class MeasureParams extends HandlerParams { 8325 private final PackageStats mStats; 8326 private boolean mSuccess; 8327 8328 private final IPackageStatsObserver mObserver; 8329 8330 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8331 super(new UserHandle(stats.userHandle)); 8332 mObserver = observer; 8333 mStats = stats; 8334 } 8335 8336 @Override 8337 public String toString() { 8338 return "MeasureParams{" 8339 + Integer.toHexString(System.identityHashCode(this)) 8340 + " " + mStats.packageName + "}"; 8341 } 8342 8343 @Override 8344 void handleStartCopy() throws RemoteException { 8345 synchronized (mInstallLock) { 8346 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8347 } 8348 8349 if (mSuccess) { 8350 final boolean mounted; 8351 if (Environment.isExternalStorageEmulated()) { 8352 mounted = true; 8353 } else { 8354 final String status = Environment.getExternalStorageState(); 8355 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8356 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8357 } 8358 8359 if (mounted) { 8360 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8361 8362 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8363 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8364 8365 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8366 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8367 8368 // Always subtract cache size, since it's a subdirectory 8369 mStats.externalDataSize -= mStats.externalCacheSize; 8370 8371 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8372 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8373 8374 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8375 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8376 } 8377 } 8378 } 8379 8380 @Override 8381 void handleReturnCode() { 8382 if (mObserver != null) { 8383 try { 8384 mObserver.onGetStatsCompleted(mStats, mSuccess); 8385 } catch (RemoteException e) { 8386 Slog.i(TAG, "Observer no longer exists."); 8387 } 8388 } 8389 } 8390 8391 @Override 8392 void handleServiceError() { 8393 Slog.e(TAG, "Could not measure application " + mStats.packageName 8394 + " external storage"); 8395 } 8396 } 8397 8398 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8399 throws RemoteException { 8400 long result = 0; 8401 for (File path : paths) { 8402 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8403 } 8404 return result; 8405 } 8406 8407 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8408 for (File path : paths) { 8409 try { 8410 mcs.clearDirectory(path.getAbsolutePath()); 8411 } catch (RemoteException e) { 8412 } 8413 } 8414 } 8415 8416 class InstallParams extends HandlerParams { 8417 /** 8418 * Location where install is coming from, before it has been 8419 * copied/renamed into place. This could be a single monolithic APK 8420 * file, or a cluster directory. This location may be untrusted. 8421 */ 8422 private final File mFromFile; 8423 8424 /** 8425 * Local copy of {@link #mFromFile}, if generated. 8426 */ 8427 private File mLocalFromFile; 8428 8429 final IPackageInstallObserver observer; 8430 final IPackageInstallObserver2 observer2; 8431 int flags; 8432 final String installerPackageName; 8433 final VerificationParams verificationParams; 8434 private InstallArgs mArgs; 8435 private int mRet; 8436 final ContainerEncryptionParams encryptionParams; 8437 final String packageAbiOverride; 8438 final String packageInstructionSetOverride; 8439 8440 InstallParams(File fromFile, IPackageInstallObserver observer, 8441 IPackageInstallObserver2 observer2, int flags, String installerPackageName, 8442 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams, 8443 UserHandle user, String packageAbiOverride) { 8444 super(user); 8445 mFromFile = Preconditions.checkNotNull(fromFile); 8446 this.observer = observer; 8447 this.observer2 = observer2; 8448 this.flags = flags; 8449 this.installerPackageName = installerPackageName; 8450 this.verificationParams = verificationParams; 8451 this.encryptionParams = encryptionParams; 8452 this.packageAbiOverride = packageAbiOverride; 8453 this.packageInstructionSetOverride = (packageAbiOverride == null) ? 8454 packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride); 8455 } 8456 8457 @Override 8458 public String toString() { 8459 return "InstallParams{" 8460 + Integer.toHexString(System.identityHashCode(this)) 8461 + " " + mFromFile + "}"; 8462 } 8463 8464 public ManifestDigest getManifestDigest() { 8465 if (verificationParams == null) { 8466 return null; 8467 } 8468 return verificationParams.getManifestDigest(); 8469 } 8470 8471 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8472 String packageName = pkgLite.packageName; 8473 int installLocation = pkgLite.installLocation; 8474 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8475 // reader 8476 synchronized (mPackages) { 8477 PackageParser.Package pkg = mPackages.get(packageName); 8478 if (pkg != null) { 8479 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8480 // Check for downgrading. 8481 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8482 if (pkgLite.versionCode < pkg.mVersionCode) { 8483 Slog.w(TAG, "Can't install update of " + packageName 8484 + " update version " + pkgLite.versionCode 8485 + " is older than installed version " 8486 + pkg.mVersionCode); 8487 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8488 } 8489 } 8490 // Check for updated system application. 8491 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8492 if (onSd) { 8493 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8494 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8495 } 8496 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8497 } else { 8498 if (onSd) { 8499 // Install flag overrides everything. 8500 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8501 } 8502 // If current upgrade specifies particular preference 8503 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8504 // Application explicitly specified internal. 8505 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8506 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8507 // App explictly prefers external. Let policy decide 8508 } else { 8509 // Prefer previous location 8510 if (isExternal(pkg)) { 8511 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8512 } 8513 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8514 } 8515 } 8516 } else { 8517 // Invalid install. Return error code 8518 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8519 } 8520 } 8521 } 8522 // All the special cases have been taken care of. 8523 // Return result based on recommended install location. 8524 if (onSd) { 8525 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8526 } 8527 return pkgLite.recommendedInstallLocation; 8528 } 8529 8530 private long getMemoryLowThreshold() { 8531 final DeviceStorageMonitorInternal 8532 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8533 if (dsm == null) { 8534 return 0L; 8535 } 8536 return dsm.getMemoryLowThreshold(); 8537 } 8538 8539 /* 8540 * Invoke remote method to get package information and install 8541 * location values. Override install location based on default 8542 * policy if needed and then create install arguments based 8543 * on the install location. 8544 */ 8545 public void handleStartCopy() throws RemoteException { 8546 int ret = PackageManager.INSTALL_SUCCEEDED; 8547 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8548 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8549 PackageInfoLite pkgLite = null; 8550 8551 if (onInt && onSd) { 8552 // Check if both bits are set. 8553 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8554 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8555 } else { 8556 final long lowThreshold = getMemoryLowThreshold(); 8557 if (lowThreshold == 0L) { 8558 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8559 } 8560 8561 if (encryptionParams != null) { 8562 // Make a temporary file for decryption. 8563 mLocalFromFile = createTempPackageFile(mDrmAppPrivateInstallDir); 8564 if (mLocalFromFile != null) { 8565 ParcelFileDescriptor out = null; 8566 try { 8567 out = ParcelFileDescriptor.open(mLocalFromFile, 8568 ParcelFileDescriptor.MODE_READ_WRITE); 8569 ret = mContainerService.copyResource(mFromFile.getAbsolutePath(), 8570 encryptionParams, out); 8571 } catch (FileNotFoundException e) { 8572 Slog.e(TAG, "Failed to create temporary file for: " + mFromFile); 8573 } finally { 8574 IoUtils.closeQuietly(out); 8575 } 8576 8577 FileUtils.setPermissions(mLocalFromFile, 0644, -1, -1); 8578 } 8579 } 8580 8581 // Remote call to find out default install location 8582 final String fromPath = getFromFile().getAbsolutePath(); 8583 pkgLite = mContainerService.getMinimalPackageInfo(fromPath, flags, lowThreshold, 8584 packageAbiOverride); 8585 8586 /* 8587 * If we have too little free space, try to free cache 8588 * before giving up. 8589 */ 8590 if (pkgLite.recommendedInstallLocation 8591 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8592 final long size = mContainerService.calculateInstalledSize( 8593 fromPath, isForwardLocked(), packageAbiOverride); 8594 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8595 pkgLite = mContainerService.getMinimalPackageInfo(fromPath, 8596 flags, lowThreshold, packageAbiOverride); 8597 } 8598 /* 8599 * The cache free must have deleted the file we 8600 * downloaded to install. 8601 * 8602 * TODO: fix the "freeCache" call to not delete 8603 * the file we care about. 8604 */ 8605 if (pkgLite.recommendedInstallLocation 8606 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8607 pkgLite.recommendedInstallLocation 8608 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8609 } 8610 } 8611 } 8612 8613 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8614 int loc = pkgLite.recommendedInstallLocation; 8615 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8616 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8617 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8618 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8619 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8620 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8621 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8622 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8623 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8624 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8625 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8626 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8627 } else { 8628 // Override with defaults if needed. 8629 loc = installLocationPolicy(pkgLite, flags); 8630 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8631 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8632 } else if (!onSd && !onInt) { 8633 // Override install location with flags 8634 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8635 // Set the flag to install on external media. 8636 flags |= PackageManager.INSTALL_EXTERNAL; 8637 flags &= ~PackageManager.INSTALL_INTERNAL; 8638 } else { 8639 // Make sure the flag for installing on external 8640 // media is unset 8641 flags |= PackageManager.INSTALL_INTERNAL; 8642 flags &= ~PackageManager.INSTALL_EXTERNAL; 8643 } 8644 } 8645 } 8646 } 8647 8648 final InstallArgs args = createInstallArgs(this); 8649 mArgs = args; 8650 8651 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8652 /* 8653 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8654 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8655 */ 8656 int userIdentifier = getUser().getIdentifier(); 8657 if (userIdentifier == UserHandle.USER_ALL 8658 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8659 userIdentifier = UserHandle.USER_OWNER; 8660 } 8661 8662 /* 8663 * Determine if we have any installed package verifiers. If we 8664 * do, then we'll defer to them to verify the packages. 8665 */ 8666 final int requiredUid = mRequiredVerifierPackage == null ? -1 8667 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8668 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8669 // TODO: send verifier the install session instead of uri 8670 final Intent verification = new Intent( 8671 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8672 verification.setDataAndType(Uri.fromFile(getFromFile()), PACKAGE_MIME_TYPE); 8673 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8674 8675 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8676 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8677 0 /* TODO: Which userId? */); 8678 8679 if (DEBUG_VERIFY) { 8680 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8681 + verification.toString() + " with " + pkgLite.verifiers.length 8682 + " optional verifiers"); 8683 } 8684 8685 final int verificationId = mPendingVerificationToken++; 8686 8687 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8688 8689 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8690 installerPackageName); 8691 8692 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8693 8694 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8695 pkgLite.packageName); 8696 8697 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8698 pkgLite.versionCode); 8699 8700 if (verificationParams != null) { 8701 if (verificationParams.getVerificationURI() != null) { 8702 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8703 verificationParams.getVerificationURI()); 8704 } 8705 if (verificationParams.getOriginatingURI() != null) { 8706 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8707 verificationParams.getOriginatingURI()); 8708 } 8709 if (verificationParams.getReferrer() != null) { 8710 verification.putExtra(Intent.EXTRA_REFERRER, 8711 verificationParams.getReferrer()); 8712 } 8713 if (verificationParams.getOriginatingUid() >= 0) { 8714 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8715 verificationParams.getOriginatingUid()); 8716 } 8717 if (verificationParams.getInstallerUid() >= 0) { 8718 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8719 verificationParams.getInstallerUid()); 8720 } 8721 } 8722 8723 final PackageVerificationState verificationState = new PackageVerificationState( 8724 requiredUid, args); 8725 8726 mPendingVerification.append(verificationId, verificationState); 8727 8728 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8729 receivers, verificationState); 8730 8731 /* 8732 * If any sufficient verifiers were listed in the package 8733 * manifest, attempt to ask them. 8734 */ 8735 if (sufficientVerifiers != null) { 8736 final int N = sufficientVerifiers.size(); 8737 if (N == 0) { 8738 Slog.i(TAG, "Additional verifiers required, but none installed."); 8739 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8740 } else { 8741 for (int i = 0; i < N; i++) { 8742 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8743 8744 final Intent sufficientIntent = new Intent(verification); 8745 sufficientIntent.setComponent(verifierComponent); 8746 8747 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8748 } 8749 } 8750 } 8751 8752 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8753 mRequiredVerifierPackage, receivers); 8754 if (ret == PackageManager.INSTALL_SUCCEEDED 8755 && mRequiredVerifierPackage != null) { 8756 /* 8757 * Send the intent to the required verification agent, 8758 * but only start the verification timeout after the 8759 * target BroadcastReceivers have run. 8760 */ 8761 verification.setComponent(requiredVerifierComponent); 8762 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8763 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8764 new BroadcastReceiver() { 8765 @Override 8766 public void onReceive(Context context, Intent intent) { 8767 final Message msg = mHandler 8768 .obtainMessage(CHECK_PENDING_VERIFICATION); 8769 msg.arg1 = verificationId; 8770 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8771 } 8772 }, null, 0, null, null); 8773 8774 /* 8775 * We don't want the copy to proceed until verification 8776 * succeeds, so null out this field. 8777 */ 8778 mArgs = null; 8779 } 8780 } else { 8781 /* 8782 * No package verification is enabled, so immediately start 8783 * the remote call to initiate copy using temporary file. 8784 */ 8785 ret = args.copyApk(mContainerService, true); 8786 } 8787 } 8788 8789 mRet = ret; 8790 } 8791 8792 @Override 8793 void handleReturnCode() { 8794 // If mArgs is null, then MCS couldn't be reached. When it 8795 // reconnects, it will try again to install. At that point, this 8796 // will succeed. 8797 if (mArgs != null) { 8798 processPendingInstall(mArgs, mRet); 8799 8800 if (mLocalFromFile != null) { 8801 if (!mLocalFromFile.delete()) { 8802 Slog.w(TAG, "Couldn't delete temporary file: " + mLocalFromFile); 8803 } 8804 } 8805 } 8806 } 8807 8808 @Override 8809 void handleServiceError() { 8810 mArgs = createInstallArgs(this); 8811 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8812 } 8813 8814 public boolean isForwardLocked() { 8815 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8816 } 8817 8818 public File getFromFile() { 8819 if (mLocalFromFile != null) { 8820 return mLocalFromFile; 8821 } else { 8822 return mFromFile; 8823 } 8824 } 8825 } 8826 8827 /* 8828 * Utility class used in movePackage api. 8829 * srcArgs and targetArgs are not set for invalid flags and make 8830 * sure to do null checks when invoking methods on them. 8831 * We probably want to return ErrorPrams for both failed installs 8832 * and moves. 8833 */ 8834 class MoveParams extends HandlerParams { 8835 final IPackageMoveObserver observer; 8836 final int flags; 8837 final String packageName; 8838 final InstallArgs srcArgs; 8839 final InstallArgs targetArgs; 8840 int uid; 8841 int mRet; 8842 8843 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8844 String packageName, String dataDir, String instructionSet, 8845 int uid, UserHandle user) { 8846 super(user); 8847 this.srcArgs = srcArgs; 8848 this.observer = observer; 8849 this.flags = flags; 8850 this.packageName = packageName; 8851 this.uid = uid; 8852 if (srcArgs != null) { 8853 final String codePath = srcArgs.getCodePath(); 8854 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, dataDir, 8855 instructionSet); 8856 } else { 8857 targetArgs = null; 8858 } 8859 } 8860 8861 @Override 8862 public String toString() { 8863 return "MoveParams{" 8864 + Integer.toHexString(System.identityHashCode(this)) 8865 + " " + packageName + "}"; 8866 } 8867 8868 public void handleStartCopy() throws RemoteException { 8869 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8870 // Check for storage space on target medium 8871 if (!targetArgs.checkFreeStorage(mContainerService)) { 8872 Log.w(TAG, "Insufficient storage to install"); 8873 return; 8874 } 8875 8876 mRet = srcArgs.doPreCopy(); 8877 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8878 return; 8879 } 8880 8881 mRet = targetArgs.copyApk(mContainerService, false); 8882 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8883 srcArgs.doPostCopy(uid); 8884 return; 8885 } 8886 8887 mRet = srcArgs.doPostCopy(uid); 8888 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8889 return; 8890 } 8891 8892 mRet = targetArgs.doPreInstall(mRet); 8893 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8894 return; 8895 } 8896 8897 if (DEBUG_SD_INSTALL) { 8898 StringBuilder builder = new StringBuilder(); 8899 if (srcArgs != null) { 8900 builder.append("src: "); 8901 builder.append(srcArgs.getCodePath()); 8902 } 8903 if (targetArgs != null) { 8904 builder.append(" target : "); 8905 builder.append(targetArgs.getCodePath()); 8906 } 8907 Log.i(TAG, builder.toString()); 8908 } 8909 } 8910 8911 @Override 8912 void handleReturnCode() { 8913 targetArgs.doPostInstall(mRet, uid); 8914 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8915 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8916 currentStatus = PackageManager.MOVE_SUCCEEDED; 8917 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8918 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8919 } 8920 processPendingMove(this, currentStatus); 8921 } 8922 8923 @Override 8924 void handleServiceError() { 8925 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8926 } 8927 } 8928 8929 /** 8930 * Used during creation of InstallArgs 8931 * 8932 * @param flags package installation flags 8933 * @return true if should be installed on external storage 8934 */ 8935 private static boolean installOnSd(int flags) { 8936 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8937 return false; 8938 } 8939 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8940 return true; 8941 } 8942 return false; 8943 } 8944 8945 /** 8946 * Used during creation of InstallArgs 8947 * 8948 * @param flags package installation flags 8949 * @return true if should be installed as forward locked 8950 */ 8951 private static boolean installForwardLocked(int flags) { 8952 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8953 } 8954 8955 private InstallArgs createInstallArgs(InstallParams params) { 8956 // TODO: extend to support incoming zero-copy locations 8957 8958 if (installOnSd(params.flags) || params.isForwardLocked()) { 8959 return new AsecInstallArgs(params); 8960 } else { 8961 return new FileInstallArgs(params); 8962 } 8963 } 8964 8965 /** 8966 * Create args that describe an existing installed package. Typically used 8967 * when cleaning up old installs, or used as a move source. 8968 */ 8969 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 8970 String resourcePath, String nativeLibraryPath, String instructionSet) { 8971 final boolean isInAsec; 8972 if (installOnSd(flags)) { 8973 /* Apps on SD card are always in ASEC containers. */ 8974 isInAsec = true; 8975 } else if (installForwardLocked(flags) 8976 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8977 /* 8978 * Forward-locked apps are only in ASEC containers if they're the 8979 * new style 8980 */ 8981 isInAsec = true; 8982 } else { 8983 isInAsec = false; 8984 } 8985 8986 if (isInAsec) { 8987 return new AsecInstallArgs(codePath, resourcePath, nativeLibraryPath, 8988 instructionSet, installOnSd(flags), installForwardLocked(flags)); 8989 } else { 8990 return new FileInstallArgs(codePath, resourcePath, nativeLibraryPath, instructionSet); 8991 } 8992 } 8993 8994 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 8995 String dataDir, String instructionSet) { 8996 final File codeFile = new File(codePath); 8997 if (installOnSd(flags) || installForwardLocked(flags)) { 8998 String cid = getNextCodePath(codePath, pkgName, "/" 8999 + AsecInstallArgs.RES_FILE_NAME); 9000 return new AsecInstallArgs(codeFile, cid, instructionSet, installOnSd(flags), 9001 installForwardLocked(flags)); 9002 } else { 9003 return new FileInstallArgs(codeFile, pkgName, dataDir, instructionSet); 9004 } 9005 } 9006 9007 static abstract class InstallArgs { 9008 /** 9009 * Location where install is coming from, before it has been 9010 * copied/renamed into place. This could be a single monolithic APK 9011 * file, or a cluster directory. This location is typically untrusted. 9012 */ 9013 final File fromFile; 9014 9015 final IPackageInstallObserver observer; 9016 final IPackageInstallObserver2 observer2; 9017 // Always refers to PackageManager flags only 9018 final int flags; 9019 final String installerPackageName; 9020 final ManifestDigest manifestDigest; 9021 final UserHandle user; 9022 final String instructionSet; 9023 final String abiOverride; 9024 9025 InstallArgs(File fromFile, IPackageInstallObserver observer, 9026 IPackageInstallObserver2 observer2, int flags, String installerPackageName, 9027 ManifestDigest manifestDigest, UserHandle user, String instructionSet, 9028 String abiOverride) { 9029 this.fromFile = fromFile; 9030 this.flags = flags; 9031 this.observer = observer; 9032 this.observer2 = observer2; 9033 this.installerPackageName = installerPackageName; 9034 this.manifestDigest = manifestDigest; 9035 this.user = user; 9036 this.instructionSet = instructionSet; 9037 this.abiOverride = abiOverride; 9038 } 9039 9040 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9041 abstract int doPreInstall(int status); 9042 abstract boolean doRename(int status, String pkgName, String oldCodePath); 9043 abstract int doPostInstall(int status, int uid); 9044 9045 /** @see PackageSettingBase#codePathString */ 9046 abstract String getCodePath(); 9047 /** @see PackageSettingBase#resourcePathString */ 9048 abstract String getResourcePath(); 9049 /** @see PackageSettingBase#nativeLibraryPathString */ 9050 abstract String getNativeLibraryPath(); 9051 9052 // Need installer lock especially for dex file removal. 9053 abstract void cleanUpResourcesLI(); 9054 abstract boolean doPostDeleteLI(boolean delete); 9055 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9056 9057 /** 9058 * Called before the source arguments are copied. This is used mostly 9059 * for MoveParams when it needs to read the source file to put it in the 9060 * destination. 9061 */ 9062 int doPreCopy() { 9063 return PackageManager.INSTALL_SUCCEEDED; 9064 } 9065 9066 /** 9067 * Called after the source arguments are copied. This is used mostly for 9068 * MoveParams when it needs to read the source file to put it in the 9069 * destination. 9070 * 9071 * @return 9072 */ 9073 int doPostCopy(int uid) { 9074 return PackageManager.INSTALL_SUCCEEDED; 9075 } 9076 9077 protected boolean isFwdLocked() { 9078 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9079 } 9080 9081 UserHandle getUser() { 9082 return user; 9083 } 9084 } 9085 9086 /** 9087 * Logic to handle installation of non-ASEC applications, including copying 9088 * and renaming logic. 9089 */ 9090 class FileInstallArgs extends InstallArgs { 9091 // TODO: teach about handling cluster directories 9092 9093 File installDir; 9094 String codeFileName; 9095 String resourceFileName; 9096 String libraryPath; 9097 boolean created = false; 9098 9099 /** New install */ 9100 FileInstallArgs(InstallParams params) { 9101 super(params.getFromFile(), params.observer, params.observer2, params.flags, 9102 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9103 params.packageInstructionSetOverride, params.packageAbiOverride); 9104 } 9105 9106 /** Existing install */ 9107 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9108 String instructionSet) { 9109 super(null, null, null, 0, null, null, null, instructionSet, null); 9110 File codeFile = new File(fullCodePath); 9111 installDir = codeFile.getParentFile(); 9112 codeFileName = fullCodePath; 9113 resourceFileName = fullResourcePath; 9114 libraryPath = nativeLibraryPath; 9115 } 9116 9117 /** New install from existing */ 9118 FileInstallArgs(File fromFile, String pkgName, String dataDir, String instructionSet) { 9119 super(fromFile, null, null, 0, null, null, null, instructionSet, null); 9120 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 9121 String apkName = getNextCodePath(null, pkgName, ".apk"); 9122 codeFileName = new File(installDir, apkName + ".apk").getPath(); 9123 resourceFileName = getResourcePathFromCodePath(); 9124 libraryPath = new File(mAppLibInstallDir, pkgName).getPath(); 9125 } 9126 9127 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9128 final long lowThreshold; 9129 9130 final DeviceStorageMonitorInternal 9131 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9132 if (dsm == null) { 9133 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9134 lowThreshold = 0L; 9135 } else { 9136 if (dsm.isMemoryLow()) { 9137 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9138 return false; 9139 } 9140 9141 lowThreshold = dsm.getMemoryLowThreshold(); 9142 } 9143 9144 return imcs.checkInternalFreeStorage(fromFile.getAbsolutePath(), isFwdLocked(), 9145 lowThreshold); 9146 } 9147 9148 void createCopyFile() { 9149 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 9150 codeFileName = createTempPackageFile(installDir).getPath(); 9151 resourceFileName = getResourcePathFromCodePath(); 9152 libraryPath = getLibraryPathFromCodePath(); 9153 created = true; 9154 } 9155 9156 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9157 if (temp) { 9158 // Generate temp file name 9159 createCopyFile(); 9160 } 9161 // Get a ParcelFileDescriptor to write to the output file 9162 File codeFile = new File(codeFileName); 9163 if (!created) { 9164 try { 9165 codeFile.createNewFile(); 9166 // Set permissions 9167 if (!setPermissions()) { 9168 // Failed setting permissions. 9169 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9170 } 9171 } catch (IOException e) { 9172 Slog.w(TAG, "Failed to create file " + codeFile); 9173 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9174 } 9175 } 9176 ParcelFileDescriptor out = null; 9177 try { 9178 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 9179 } catch (FileNotFoundException e) { 9180 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 9181 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9182 } 9183 // Copy the resource now 9184 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9185 try { 9186 ret = imcs.copyResource(fromFile.getAbsolutePath(), null, out); 9187 } finally { 9188 IoUtils.closeQuietly(out); 9189 } 9190 9191 if (isFwdLocked()) { 9192 final File destResourceFile = new File(getResourcePath()); 9193 9194 // Copy the public files 9195 try { 9196 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 9197 } catch (IOException e) { 9198 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 9199 + " forward-locked app."); 9200 destResourceFile.delete(); 9201 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9202 } 9203 } 9204 9205 final File nativeLibraryFile = new File(getNativeLibraryPath()); 9206 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath()); 9207 if (nativeLibraryFile.exists()) { 9208 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 9209 nativeLibraryFile.delete(); 9210 } 9211 9212 String[] abiList = (abiOverride != null) ? 9213 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9214 ApkHandle handle = null; 9215 try { 9216 handle = ApkHandle.create(codeFile); 9217 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 9218 abiOverride == null && 9219 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9220 abiList = Build.SUPPORTED_32_BIT_ABIS; 9221 } 9222 9223 int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList); 9224 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9225 return copyRet; 9226 } 9227 } catch (IOException e) { 9228 Slog.e(TAG, "Copying native libraries failed", e); 9229 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9230 } finally { 9231 IoUtils.closeQuietly(handle); 9232 } 9233 9234 return ret; 9235 } 9236 9237 int doPreInstall(int status) { 9238 if (status != PackageManager.INSTALL_SUCCEEDED) { 9239 cleanUp(); 9240 } 9241 return status; 9242 } 9243 9244 boolean doRename(int status, final String pkgName, String oldCodePath) { 9245 if (status != PackageManager.INSTALL_SUCCEEDED) { 9246 cleanUp(); 9247 return false; 9248 } else { 9249 final File oldCodeFile = new File(getCodePath()); 9250 final File oldResourceFile = new File(getResourcePath()); 9251 final File oldLibraryFile = new File(getNativeLibraryPath()); 9252 9253 // Rename APK file based on packageName 9254 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 9255 final File newCodeFile = new File(installDir, apkName + ".apk"); 9256 if (!oldCodeFile.renameTo(newCodeFile)) { 9257 return false; 9258 } 9259 codeFileName = newCodeFile.getPath(); 9260 9261 // Rename public resource file if it's forward-locked. 9262 final File newResFile = new File(getResourcePathFromCodePath()); 9263 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 9264 return false; 9265 } 9266 resourceFileName = newResFile.getPath(); 9267 9268 // Rename library path 9269 final File newLibraryFile = new File(getLibraryPathFromCodePath()); 9270 if (newLibraryFile.exists()) { 9271 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile); 9272 newLibraryFile.delete(); 9273 } 9274 if (!oldLibraryFile.renameTo(newLibraryFile)) { 9275 Slog.e(TAG, "Cannot rename native library directory " 9276 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath()); 9277 return false; 9278 } 9279 libraryPath = newLibraryFile.getPath(); 9280 9281 // Attempt to set permissions 9282 if (!setPermissions()) { 9283 return false; 9284 } 9285 9286 if (!SELinux.restorecon(newCodeFile)) { 9287 return false; 9288 } 9289 9290 return true; 9291 } 9292 } 9293 9294 int doPostInstall(int status, int uid) { 9295 if (status != PackageManager.INSTALL_SUCCEEDED) { 9296 cleanUp(); 9297 } 9298 return status; 9299 } 9300 9301 private String getResourcePathFromCodePath() { 9302 final String codePath = getCodePath(); 9303 if (isFwdLocked()) { 9304 final StringBuilder sb = new StringBuilder(); 9305 9306 sb.append(mAppInstallDir.getPath()); 9307 sb.append('/'); 9308 sb.append(getApkName(codePath)); 9309 sb.append(".zip"); 9310 9311 /* 9312 * If our APK is a temporary file, mark the resource as a 9313 * temporary file as well so it can be cleaned up after 9314 * catastrophic failure. 9315 */ 9316 if (codePath.endsWith(".tmp")) { 9317 sb.append(".tmp"); 9318 } 9319 9320 return sb.toString(); 9321 } else { 9322 return codePath; 9323 } 9324 } 9325 9326 private String getLibraryPathFromCodePath() { 9327 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath(); 9328 } 9329 9330 @Override 9331 String getCodePath() { 9332 return codeFileName; 9333 } 9334 9335 @Override 9336 String getResourcePath() { 9337 return resourceFileName; 9338 } 9339 9340 @Override 9341 String getNativeLibraryPath() { 9342 if (libraryPath == null) { 9343 libraryPath = getLibraryPathFromCodePath(); 9344 } 9345 return libraryPath; 9346 } 9347 9348 private boolean cleanUp() { 9349 boolean ret = true; 9350 String sourceDir = getCodePath(); 9351 String publicSourceDir = getResourcePath(); 9352 if (sourceDir != null) { 9353 File sourceFile = new File(sourceDir); 9354 if (!sourceFile.exists()) { 9355 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 9356 ret = false; 9357 } 9358 // Delete application's code and resources 9359 sourceFile.delete(); 9360 } 9361 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 9362 final File publicSourceFile = new File(publicSourceDir); 9363 if (!publicSourceFile.exists()) { 9364 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 9365 } 9366 if (publicSourceFile.exists()) { 9367 publicSourceFile.delete(); 9368 } 9369 } 9370 9371 if (libraryPath != null) { 9372 File nativeLibraryFile = new File(libraryPath); 9373 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 9374 if (!nativeLibraryFile.delete()) { 9375 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath); 9376 } 9377 } 9378 9379 return ret; 9380 } 9381 9382 void cleanUpResourcesLI() { 9383 String sourceDir = getCodePath(); 9384 if (cleanUp()) { 9385 if (instructionSet == null) { 9386 throw new IllegalStateException("instructionSet == null"); 9387 } 9388 int retCode = mInstaller.rmdex(sourceDir, instructionSet); 9389 if (retCode < 0) { 9390 Slog.w(TAG, "Couldn't remove dex file for package: " 9391 + " at location " 9392 + sourceDir + ", retcode=" + retCode); 9393 // we don't consider this to be a failure of the core package deletion 9394 } 9395 } 9396 } 9397 9398 private boolean setPermissions() { 9399 // TODO Do this in a more elegant way later on. for now just a hack 9400 if (!isFwdLocked()) { 9401 final int filePermissions = 9402 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 9403 |FileUtils.S_IROTH; 9404 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 9405 if (retCode != 0) { 9406 Slog.e(TAG, "Couldn't set new package file permissions for " + 9407 getCodePath() 9408 + ". The return code was: " + retCode); 9409 // TODO Define new internal error 9410 return false; 9411 } 9412 return true; 9413 } 9414 return true; 9415 } 9416 9417 boolean doPostDeleteLI(boolean delete) { 9418 // XXX err, shouldn't we respect the delete flag? 9419 cleanUpResourcesLI(); 9420 return true; 9421 } 9422 } 9423 9424 private boolean isAsecExternal(String cid) { 9425 final String asecPath = PackageHelper.getSdFilesystem(cid); 9426 return !asecPath.startsWith(mAsecInternalPath); 9427 } 9428 9429 /** 9430 * Extract the MountService "container ID" from the full code path of an 9431 * .apk. 9432 */ 9433 static String cidFromCodePath(String fullCodePath) { 9434 int eidx = fullCodePath.lastIndexOf("/"); 9435 String subStr1 = fullCodePath.substring(0, eidx); 9436 int sidx = subStr1.lastIndexOf("/"); 9437 return subStr1.substring(sidx+1, eidx); 9438 } 9439 9440 /** 9441 * Logic to handle installation of ASEC applications, including copying and 9442 * renaming logic. 9443 */ 9444 class AsecInstallArgs extends InstallArgs { 9445 // TODO: teach about handling cluster directories 9446 9447 static final String RES_FILE_NAME = "pkg.apk"; 9448 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9449 9450 String cid; 9451 String packagePath; 9452 String resourcePath; 9453 String libraryPath; 9454 9455 /** New install */ 9456 AsecInstallArgs(InstallParams params) { 9457 super(params.getFromFile(), params.observer, params.observer2, params.flags, 9458 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9459 params.packageInstructionSetOverride, params.packageAbiOverride); 9460 } 9461 9462 /** Existing install */ 9463 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9464 String instructionSet, boolean isExternal, boolean isForwardLocked) { 9465 super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9466 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9467 null, null, null, instructionSet, null); 9468 // Extract cid from fullCodePath 9469 int eidx = fullCodePath.lastIndexOf("/"); 9470 String subStr1 = fullCodePath.substring(0, eidx); 9471 int sidx = subStr1.lastIndexOf("/"); 9472 cid = subStr1.substring(sidx+1, eidx); 9473 setCachePath(subStr1); 9474 } 9475 9476 AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) { 9477 super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 9478 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9479 null, null, null, instructionSet, null); 9480 this.cid = cid; 9481 setCachePath(PackageHelper.getSdDir(cid)); 9482 } 9483 9484 /** New install from existing */ 9485 AsecInstallArgs(File fromFile, String cid, String instructionSet, 9486 boolean isExternal, boolean isForwardLocked) { 9487 super(fromFile, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9488 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9489 null, null, null, instructionSet, null); 9490 this.cid = cid; 9491 } 9492 9493 void createCopyFile() { 9494 cid = getTempContainerId(); 9495 } 9496 9497 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9498 return imcs.checkExternalFreeStorage(fromFile.getAbsolutePath(), isFwdLocked(), 9499 abiOverride); 9500 } 9501 9502 private final boolean isExternal() { 9503 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9504 } 9505 9506 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9507 if (temp) { 9508 createCopyFile(); 9509 } else { 9510 /* 9511 * Pre-emptively destroy the container since it's destroyed if 9512 * copying fails due to it existing anyway. 9513 */ 9514 PackageHelper.destroySdDir(cid); 9515 } 9516 9517 final String newCachePath = imcs.copyResourceToContainer(fromFile.getAbsolutePath(), 9518 cid, getEncryptKey(), RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), 9519 isFwdLocked(), abiOverride); 9520 9521 if (newCachePath != null) { 9522 setCachePath(newCachePath); 9523 return PackageManager.INSTALL_SUCCEEDED; 9524 } else { 9525 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9526 } 9527 } 9528 9529 @Override 9530 String getCodePath() { 9531 return packagePath; 9532 } 9533 9534 @Override 9535 String getResourcePath() { 9536 return resourcePath; 9537 } 9538 9539 @Override 9540 String getNativeLibraryPath() { 9541 return libraryPath; 9542 } 9543 9544 int doPreInstall(int status) { 9545 if (status != PackageManager.INSTALL_SUCCEEDED) { 9546 // Destroy container 9547 PackageHelper.destroySdDir(cid); 9548 } else { 9549 boolean mounted = PackageHelper.isContainerMounted(cid); 9550 if (!mounted) { 9551 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9552 Process.SYSTEM_UID); 9553 if (newCachePath != null) { 9554 setCachePath(newCachePath); 9555 } else { 9556 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9557 } 9558 } 9559 } 9560 return status; 9561 } 9562 9563 boolean doRename(int status, final String pkgName, 9564 String oldCodePath) { 9565 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 9566 String newCachePath = null; 9567 if (PackageHelper.isContainerMounted(cid)) { 9568 // Unmount the container 9569 if (!PackageHelper.unMountSdDir(cid)) { 9570 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9571 return false; 9572 } 9573 } 9574 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9575 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9576 " which might be stale. Will try to clean up."); 9577 // Clean up the stale container and proceed to recreate. 9578 if (!PackageHelper.destroySdDir(newCacheId)) { 9579 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9580 return false; 9581 } 9582 // Successfully cleaned up stale container. Try to rename again. 9583 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9584 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9585 + " inspite of cleaning it up."); 9586 return false; 9587 } 9588 } 9589 if (!PackageHelper.isContainerMounted(newCacheId)) { 9590 Slog.w(TAG, "Mounting container " + newCacheId); 9591 newCachePath = PackageHelper.mountSdDir(newCacheId, 9592 getEncryptKey(), Process.SYSTEM_UID); 9593 } else { 9594 newCachePath = PackageHelper.getSdDir(newCacheId); 9595 } 9596 if (newCachePath == null) { 9597 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9598 return false; 9599 } 9600 Log.i(TAG, "Succesfully renamed " + cid + 9601 " to " + newCacheId + 9602 " at new path: " + newCachePath); 9603 cid = newCacheId; 9604 setCachePath(newCachePath); 9605 return true; 9606 } 9607 9608 private void setCachePath(String newCachePath) { 9609 File cachePath = new File(newCachePath); 9610 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 9611 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9612 9613 if (isFwdLocked()) { 9614 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9615 } else { 9616 resourcePath = packagePath; 9617 } 9618 } 9619 9620 int doPostInstall(int status, int uid) { 9621 if (status != PackageManager.INSTALL_SUCCEEDED) { 9622 cleanUp(); 9623 } else { 9624 final int groupOwner; 9625 final String protectedFile; 9626 if (isFwdLocked()) { 9627 groupOwner = UserHandle.getSharedAppGid(uid); 9628 protectedFile = RES_FILE_NAME; 9629 } else { 9630 groupOwner = -1; 9631 protectedFile = null; 9632 } 9633 9634 if (uid < Process.FIRST_APPLICATION_UID 9635 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9636 Slog.e(TAG, "Failed to finalize " + cid); 9637 PackageHelper.destroySdDir(cid); 9638 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9639 } 9640 9641 boolean mounted = PackageHelper.isContainerMounted(cid); 9642 if (!mounted) { 9643 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9644 } 9645 } 9646 return status; 9647 } 9648 9649 private void cleanUp() { 9650 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9651 9652 // Destroy secure container 9653 PackageHelper.destroySdDir(cid); 9654 } 9655 9656 void cleanUpResourcesLI() { 9657 String sourceFile = getCodePath(); 9658 // Remove dex file 9659 if (instructionSet == null) { 9660 throw new IllegalStateException("instructionSet == null"); 9661 } 9662 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9663 if (retCode < 0) { 9664 Slog.w(TAG, "Couldn't remove dex file for package: " 9665 + " at location " 9666 + sourceFile.toString() + ", retcode=" + retCode); 9667 // we don't consider this to be a failure of the core package deletion 9668 } 9669 cleanUp(); 9670 } 9671 9672 boolean matchContainer(String app) { 9673 if (cid.startsWith(app)) { 9674 return true; 9675 } 9676 return false; 9677 } 9678 9679 String getPackageName() { 9680 return getAsecPackageName(cid); 9681 } 9682 9683 boolean doPostDeleteLI(boolean delete) { 9684 boolean ret = false; 9685 boolean mounted = PackageHelper.isContainerMounted(cid); 9686 if (mounted) { 9687 // Unmount first 9688 ret = PackageHelper.unMountSdDir(cid); 9689 } 9690 if (ret && delete) { 9691 cleanUpResourcesLI(); 9692 } 9693 return ret; 9694 } 9695 9696 @Override 9697 int doPreCopy() { 9698 if (isFwdLocked()) { 9699 if (!PackageHelper.fixSdPermissions(cid, 9700 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9701 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9702 } 9703 } 9704 9705 return PackageManager.INSTALL_SUCCEEDED; 9706 } 9707 9708 @Override 9709 int doPostCopy(int uid) { 9710 if (isFwdLocked()) { 9711 if (uid < Process.FIRST_APPLICATION_UID 9712 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9713 RES_FILE_NAME)) { 9714 Slog.e(TAG, "Failed to finalize " + cid); 9715 PackageHelper.destroySdDir(cid); 9716 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9717 } 9718 } 9719 9720 return PackageManager.INSTALL_SUCCEEDED; 9721 } 9722 } 9723 9724 static String getAsecPackageName(String packageCid) { 9725 int idx = packageCid.lastIndexOf("-"); 9726 if (idx == -1) { 9727 return packageCid; 9728 } 9729 return packageCid.substring(0, idx); 9730 } 9731 9732 // Utility method used to create code paths based on package name and available index. 9733 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9734 String idxStr = ""; 9735 int idx = 1; 9736 // Fall back to default value of idx=1 if prefix is not 9737 // part of oldCodePath 9738 if (oldCodePath != null) { 9739 String subStr = oldCodePath; 9740 // Drop the suffix right away 9741 if (subStr.endsWith(suffix)) { 9742 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9743 } 9744 // If oldCodePath already contains prefix find out the 9745 // ending index to either increment or decrement. 9746 int sidx = subStr.lastIndexOf(prefix); 9747 if (sidx != -1) { 9748 subStr = subStr.substring(sidx + prefix.length()); 9749 if (subStr != null) { 9750 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9751 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9752 } 9753 try { 9754 idx = Integer.parseInt(subStr); 9755 if (idx <= 1) { 9756 idx++; 9757 } else { 9758 idx--; 9759 } 9760 } catch(NumberFormatException e) { 9761 } 9762 } 9763 } 9764 } 9765 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9766 return prefix + idxStr; 9767 } 9768 9769 // Utility method used to ignore ADD/REMOVE events 9770 // by directory observer. 9771 private static boolean ignoreCodePath(String fullPathStr) { 9772 String apkName = getApkName(fullPathStr); 9773 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9774 if (idx != -1 && ((idx+1) < apkName.length())) { 9775 // Make sure the package ends with a numeral 9776 String version = apkName.substring(idx+1); 9777 try { 9778 Integer.parseInt(version); 9779 return true; 9780 } catch (NumberFormatException e) {} 9781 } 9782 return false; 9783 } 9784 9785 // Utility method that returns the relative package path with respect 9786 // to the installation directory. Like say for /data/data/com.test-1.apk 9787 // string com.test-1 is returned. 9788 static String getApkName(String codePath) { 9789 if (codePath == null) { 9790 return null; 9791 } 9792 int sidx = codePath.lastIndexOf("/"); 9793 int eidx = codePath.lastIndexOf("."); 9794 if (eidx == -1) { 9795 eidx = codePath.length(); 9796 } else if (eidx == 0) { 9797 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 9798 return null; 9799 } 9800 return codePath.substring(sidx+1, eidx); 9801 } 9802 9803 private static String[] deriveSplitResPaths(String[] splitCodePaths) { 9804 String[] splitResPaths = null; 9805 if (!ArrayUtils.isEmpty(splitCodePaths)) { 9806 splitResPaths = new String[splitCodePaths.length]; 9807 for (int i = 0; i < splitCodePaths.length; i++) { 9808 final String splitCodePath = splitCodePaths[i]; 9809 final String resName = getApkName(splitCodePath) + ".zip"; 9810 splitResPaths[i] = new File(new File(splitCodePath).getParentFile(), 9811 resName).getAbsolutePath(); 9812 } 9813 } 9814 return splitResPaths; 9815 } 9816 9817 class PackageInstalledInfo { 9818 String name; 9819 int uid; 9820 // The set of users that originally had this package installed. 9821 int[] origUsers; 9822 // The set of users that now have this package installed. 9823 int[] newUsers; 9824 PackageParser.Package pkg; 9825 int returnCode; 9826 PackageRemovedInfo removedInfo; 9827 9828 // In some error cases we want to convey more info back to the observer 9829 String origPackage; 9830 String origPermission; 9831 } 9832 9833 /* 9834 * Install a non-existing package. 9835 */ 9836 private void installNewPackageLI(PackageParser.Package pkg, 9837 int parseFlags, int scanMode, UserHandle user, 9838 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9839 // Remember this for later, in case we need to rollback this install 9840 String pkgName = pkg.packageName; 9841 9842 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9843 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9844 synchronized(mPackages) { 9845 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9846 // A package with the same name is already installed, though 9847 // it has been renamed to an older name. The package we 9848 // are trying to install should be installed as an update to 9849 // the existing one, but that has not been requested, so bail. 9850 Slog.w(TAG, "Attempt to re-install " + pkgName 9851 + " without first uninstalling package running as " 9852 + mSettings.mRenamedPackages.get(pkgName)); 9853 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9854 return; 9855 } 9856 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9857 // Don't allow installation over an existing package with the same name. 9858 Slog.w(TAG, "Attempt to re-install " + pkgName 9859 + " without first uninstalling."); 9860 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9861 return; 9862 } 9863 } 9864 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9865 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9866 System.currentTimeMillis(), user, abiOverride); 9867 if (newPackage == null) { 9868 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9869 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9870 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9871 } 9872 } else { 9873 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9874 // delete the partially installed application. the data directory will have to be 9875 // restored if it was already existing 9876 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9877 // remove package from internal structures. Note that we want deletePackageX to 9878 // delete the package data and cache directories that it created in 9879 // scanPackageLocked, unless those directories existed before we even tried to 9880 // install. 9881 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9882 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9883 res.removedInfo, true); 9884 } 9885 } 9886 } 9887 9888 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9889 // Upgrade keysets are being used. Determine if new package has a superset of the 9890 // required keys. 9891 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9892 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9893 Set<Long> newSigningKeyIds = new ArraySet<Long>(); 9894 for (PublicKey pk : newPkg.mSigningKeys) { 9895 newSigningKeyIds.add(ksms.getIdForPublicKey(pk)); 9896 } 9897 //remove PUBLIC_KEY_NOT_FOUND, although not necessary 9898 newSigningKeyIds.remove(ksms.PUBLIC_KEY_NOT_FOUND); 9899 for (int i = 0; i < upgradeKeySets.length; i++) { 9900 if (newSigningKeyIds.containsAll(ksms.mKeySetMapping.get(upgradeKeySets[i]))) { 9901 return true; 9902 } 9903 } 9904 return false; 9905 } 9906 9907 private void replacePackageLI(PackageParser.Package pkg, 9908 int parseFlags, int scanMode, UserHandle user, 9909 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9910 PackageParser.Package oldPackage; 9911 String pkgName = pkg.packageName; 9912 int[] allUsers; 9913 boolean[] perUserInstalled; 9914 9915 // First find the old package info and check signatures 9916 synchronized(mPackages) { 9917 oldPackage = mPackages.get(pkgName); 9918 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9919 PackageSetting ps = mSettings.mPackages.get(pkgName); 9920 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9921 // default to original signature matching 9922 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9923 != PackageManager.SIGNATURE_MATCH) { 9924 Slog.w(TAG, "New package has a different signature: " + pkgName); 9925 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9926 return; 9927 } 9928 } else { 9929 if(!checkUpgradeKeySetLP(ps, pkg)) { 9930 Slog.w(TAG, "New package not signed by keys specified by upgrade-keysets: " 9931 + pkgName); 9932 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9933 return; 9934 } 9935 } 9936 9937 // In case of rollback, remember per-user/profile install state 9938 allUsers = sUserManager.getUserIds(); 9939 perUserInstalled = new boolean[allUsers.length]; 9940 for (int i = 0; i < allUsers.length; i++) { 9941 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9942 } 9943 } 9944 boolean sysPkg = (isSystemApp(oldPackage)); 9945 if (sysPkg) { 9946 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9947 user, allUsers, perUserInstalled, installerPackageName, res, 9948 abiOverride); 9949 } else { 9950 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9951 user, allUsers, perUserInstalled, installerPackageName, res, 9952 abiOverride); 9953 } 9954 } 9955 9956 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9957 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9958 int[] allUsers, boolean[] perUserInstalled, 9959 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9960 PackageParser.Package newPackage = null; 9961 String pkgName = deletedPackage.packageName; 9962 boolean deletedPkg = true; 9963 boolean updatedSettings = false; 9964 9965 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9966 + deletedPackage); 9967 long origUpdateTime; 9968 if (pkg.mExtras != null) { 9969 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9970 } else { 9971 origUpdateTime = 0; 9972 } 9973 9974 // First delete the existing package while retaining the data directory 9975 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9976 res.removedInfo, true)) { 9977 // If the existing package wasn't successfully deleted 9978 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9979 deletedPkg = false; 9980 } else { 9981 // Successfully deleted the old package. Now proceed with re-installation 9982 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9983 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9984 System.currentTimeMillis(), user, abiOverride); 9985 if (newPackage == null) { 9986 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9987 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9988 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9989 } 9990 } else { 9991 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9992 updatedSettings = true; 9993 } 9994 } 9995 9996 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9997 // remove package from internal structures. Note that we want deletePackageX to 9998 // delete the package data and cache directories that it created in 9999 // scanPackageLocked, unless those directories existed before we even tried to 10000 // install. 10001 if(updatedSettings) { 10002 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10003 deletePackageLI( 10004 pkgName, null, true, allUsers, perUserInstalled, 10005 PackageManager.DELETE_KEEP_DATA, 10006 res.removedInfo, true); 10007 } 10008 // Since we failed to install the new package we need to restore the old 10009 // package that we deleted. 10010 if (deletedPkg) { 10011 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10012 File restoreFile = new File(deletedPackage.codePath); 10013 // Parse old package 10014 boolean oldOnSd = isExternal(deletedPackage); 10015 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10016 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10017 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10018 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10019 | SCAN_UPDATE_TIME; 10020 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 10021 origUpdateTime, null, null) == null) { 10022 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 10023 return; 10024 } 10025 // Restore of old package succeeded. Update permissions. 10026 // writer 10027 synchronized (mPackages) { 10028 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10029 UPDATE_PERMISSIONS_ALL); 10030 // can downgrade to reader 10031 mSettings.writeLPr(); 10032 } 10033 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10034 } 10035 } 10036 } 10037 10038 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10039 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10040 int[] allUsers, boolean[] perUserInstalled, 10041 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10042 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10043 + ", old=" + deletedPackage); 10044 PackageParser.Package newPackage = null; 10045 boolean updatedSettings = false; 10046 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10047 PackageParser.PARSE_IS_SYSTEM; 10048 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10049 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10050 } 10051 String packageName = deletedPackage.packageName; 10052 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 10053 if (packageName == null) { 10054 Slog.w(TAG, "Attempt to delete null packageName."); 10055 return; 10056 } 10057 PackageParser.Package oldPkg; 10058 PackageSetting oldPkgSetting; 10059 // reader 10060 synchronized (mPackages) { 10061 oldPkg = mPackages.get(packageName); 10062 oldPkgSetting = mSettings.mPackages.get(packageName); 10063 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10064 (oldPkgSetting == null)) { 10065 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 10066 return; 10067 } 10068 } 10069 10070 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10071 10072 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10073 res.removedInfo.removedPackage = packageName; 10074 // Remove existing system package 10075 removePackageLI(oldPkgSetting, true); 10076 // writer 10077 synchronized (mPackages) { 10078 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10079 // We didn't need to disable the .apk as a current system package, 10080 // which means we are replacing another update that is already 10081 // installed. We need to make sure to delete the older one's .apk. 10082 res.removedInfo.args = createInstallArgsForExisting(0, 10083 deletedPackage.applicationInfo.sourceDir, 10084 deletedPackage.applicationInfo.publicSourceDir, 10085 deletedPackage.applicationInfo.nativeLibraryDir, 10086 getAppInstructionSet(deletedPackage.applicationInfo)); 10087 } else { 10088 res.removedInfo.args = null; 10089 } 10090 } 10091 10092 // Successfully disabled the old package. Now proceed with re-installation 10093 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 10094 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10095 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10096 if (newPackage == null) { 10097 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 10098 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 10099 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 10100 } 10101 } else { 10102 if (newPackage.mExtras != null) { 10103 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 10104 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10105 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10106 10107 // is the update attempting to change shared user? that isn't going to work... 10108 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10109 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 10110 + " to " + newPkgSetting.sharedUser); 10111 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 10112 updatedSettings = true; 10113 } 10114 } 10115 10116 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10117 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10118 updatedSettings = true; 10119 } 10120 } 10121 10122 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10123 // Re installation failed. Restore old information 10124 // Remove new pkg information 10125 if (newPackage != null) { 10126 removeInstalledPackageLI(newPackage, true); 10127 } 10128 // Add back the old system package 10129 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null); 10130 // Restore the old system information in Settings 10131 synchronized(mPackages) { 10132 if (updatedSettings) { 10133 mSettings.enableSystemPackageLPw(packageName); 10134 mSettings.setInstallerPackageName(packageName, 10135 oldPkgSetting.installerPackageName); 10136 } 10137 mSettings.writeLPr(); 10138 } 10139 } 10140 } 10141 10142 // Utility method used to move dex files during install. 10143 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10144 // TODO: extend to move split APK dex files 10145 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10146 final String instructionSet = getAppInstructionSet(newPackage.applicationInfo); 10147 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10148 instructionSet); 10149 if (retCode != 0) { 10150 /* 10151 * Programs may be lazily run through dexopt, so the 10152 * source may not exist. However, something seems to 10153 * have gone wrong, so note that dexopt needs to be 10154 * run again and remove the source file. In addition, 10155 * remove the target to make sure there isn't a stale 10156 * file from a previous version of the package. 10157 */ 10158 newPackage.mDexOptNeeded = true; 10159 mInstaller.rmdex(oldCodePath, instructionSet); 10160 mInstaller.rmdex(newPackage.baseCodePath, instructionSet); 10161 } 10162 } 10163 return PackageManager.INSTALL_SUCCEEDED; 10164 } 10165 10166 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10167 int[] allUsers, boolean[] perUserInstalled, 10168 PackageInstalledInfo res) { 10169 String pkgName = newPackage.packageName; 10170 synchronized (mPackages) { 10171 //write settings. the installStatus will be incomplete at this stage. 10172 //note that the new package setting would have already been 10173 //added to mPackages. It hasn't been persisted yet. 10174 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10175 mSettings.writeLPr(); 10176 } 10177 10178 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10179 10180 synchronized (mPackages) { 10181 updatePermissionsLPw(newPackage.packageName, newPackage, 10182 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10183 ? UPDATE_PERMISSIONS_ALL : 0)); 10184 // For system-bundled packages, we assume that installing an upgraded version 10185 // of the package implies that the user actually wants to run that new code, 10186 // so we enable the package. 10187 if (isSystemApp(newPackage)) { 10188 // NB: implicit assumption that system package upgrades apply to all users 10189 if (DEBUG_INSTALL) { 10190 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10191 } 10192 PackageSetting ps = mSettings.mPackages.get(pkgName); 10193 if (ps != null) { 10194 if (res.origUsers != null) { 10195 for (int userHandle : res.origUsers) { 10196 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10197 userHandle, installerPackageName); 10198 } 10199 } 10200 // Also convey the prior install/uninstall state 10201 if (allUsers != null && perUserInstalled != null) { 10202 for (int i = 0; i < allUsers.length; i++) { 10203 if (DEBUG_INSTALL) { 10204 Slog.d(TAG, " user " + allUsers[i] 10205 + " => " + perUserInstalled[i]); 10206 } 10207 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10208 } 10209 // these install state changes will be persisted in the 10210 // upcoming call to mSettings.writeLPr(). 10211 } 10212 } 10213 } 10214 res.name = pkgName; 10215 res.uid = newPackage.applicationInfo.uid; 10216 res.pkg = newPackage; 10217 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10218 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10219 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10220 //to update install status 10221 mSettings.writeLPr(); 10222 } 10223 } 10224 10225 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10226 int pFlags = args.flags; 10227 String installerPackageName = args.installerPackageName; 10228 File tmpPackageFile = new File(args.getCodePath()); 10229 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10230 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10231 boolean replace = false; 10232 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10233 | (newInstall ? SCAN_NEW_INSTALL : 0); 10234 // Result object to be returned 10235 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10236 10237 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10238 // Retrieve PackageSettings and parse package 10239 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10240 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10241 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10242 PackageParser pp = new PackageParser(); 10243 pp.setSeparateProcesses(mSeparateProcesses); 10244 pp.setDisplayMetrics(mMetrics); 10245 10246 final PackageParser.Package pkg; 10247 try { 10248 pkg = pp.parseMonolithicPackage(tmpPackageFile, parseFlags); 10249 } catch (PackageParserException e) { 10250 res.returnCode = e.error; 10251 return; 10252 } 10253 10254 String pkgName = res.name = pkg.packageName; 10255 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10256 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10257 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 10258 return; 10259 } 10260 } 10261 10262 try { 10263 pp.collectCertificates(pkg, parseFlags); 10264 pp.collectManifestDigest(pkg); 10265 } catch (PackageParserException e) { 10266 res.returnCode = e.error; 10267 return; 10268 } 10269 10270 /* If the installer passed in a manifest digest, compare it now. */ 10271 if (args.manifestDigest != null) { 10272 if (DEBUG_INSTALL) { 10273 final String parsedManifest = pkg.manifestDigest == null ? "null" 10274 : pkg.manifestDigest.toString(); 10275 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10276 + parsedManifest); 10277 } 10278 10279 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10280 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 10281 return; 10282 } 10283 } else if (DEBUG_INSTALL) { 10284 final String parsedManifest = pkg.manifestDigest == null 10285 ? "null" : pkg.manifestDigest.toString(); 10286 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10287 } 10288 10289 // Get rid of all references to package scan path via parser. 10290 pp = null; 10291 String oldCodePath = null; 10292 boolean systemApp = false; 10293 synchronized (mPackages) { 10294 // Check whether the newly-scanned package wants to define an already-defined perm 10295 int N = pkg.permissions.size(); 10296 for (int i = N-1; i >= 0; i--) { 10297 PackageParser.Permission perm = pkg.permissions.get(i); 10298 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10299 if (bp != null) { 10300 // If the defining package is signed with our cert, it's okay. This 10301 // also includes the "updating the same package" case, of course. 10302 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10303 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10304 // If the owning package is the system itself, we log but allow 10305 // install to proceed; we fail the install on all other permission 10306 // redefinitions. 10307 if (!bp.sourcePackage.equals("android")) { 10308 Slog.w(TAG, "Package " + pkg.packageName 10309 + " attempting to redeclare permission " + perm.info.name 10310 + " already owned by " + bp.sourcePackage); 10311 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 10312 res.origPermission = perm.info.name; 10313 res.origPackage = bp.sourcePackage; 10314 return; 10315 } else { 10316 Slog.w(TAG, "Package " + pkg.packageName 10317 + " attempting to redeclare system permission " 10318 + perm.info.name + "; ignoring new declaration"); 10319 pkg.permissions.remove(i); 10320 } 10321 } 10322 } 10323 } 10324 10325 // Check if installing already existing package 10326 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10327 String oldName = mSettings.mRenamedPackages.get(pkgName); 10328 if (pkg.mOriginalPackages != null 10329 && pkg.mOriginalPackages.contains(oldName) 10330 && mPackages.containsKey(oldName)) { 10331 // This package is derived from an original package, 10332 // and this device has been updating from that original 10333 // name. We must continue using the original name, so 10334 // rename the new package here. 10335 pkg.setPackageName(oldName); 10336 pkgName = pkg.packageName; 10337 replace = true; 10338 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10339 + oldName + " pkgName=" + pkgName); 10340 } else if (mPackages.containsKey(pkgName)) { 10341 // This package, under its official name, already exists 10342 // on the device; we should replace it. 10343 replace = true; 10344 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10345 } 10346 } 10347 PackageSetting ps = mSettings.mPackages.get(pkgName); 10348 if (ps != null) { 10349 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10350 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10351 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10352 systemApp = (ps.pkg.applicationInfo.flags & 10353 ApplicationInfo.FLAG_SYSTEM) != 0; 10354 } 10355 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10356 } 10357 } 10358 10359 if (systemApp && onSd) { 10360 // Disable updates to system apps on sdcard 10361 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 10362 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10363 return; 10364 } 10365 10366 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 10367 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10368 return; 10369 } 10370 10371 // Set application objects path explicitly after the rename 10372 // TODO: derive split paths from original scan after rename 10373 pkg.codePath = args.getCodePath(); 10374 pkg.baseCodePath = args.getCodePath(); 10375 pkg.splitCodePaths = null; 10376 pkg.applicationInfo.sourceDir = args.getCodePath(); 10377 pkg.applicationInfo.publicSourceDir = args.getResourcePath(); 10378 pkg.applicationInfo.splitSourceDirs = null; 10379 pkg.applicationInfo.splitPublicSourceDirs = null; 10380 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 10381 10382 if (replace) { 10383 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10384 installerPackageName, res, args.abiOverride); 10385 } else { 10386 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10387 installerPackageName, res, args.abiOverride); 10388 } 10389 synchronized (mPackages) { 10390 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10391 if (ps != null) { 10392 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10393 } 10394 } 10395 } 10396 10397 private static boolean isForwardLocked(PackageParser.Package pkg) { 10398 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10399 } 10400 10401 10402 private boolean isForwardLocked(PackageSetting ps) { 10403 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10404 } 10405 10406 private static boolean isExternal(PackageParser.Package pkg) { 10407 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10408 } 10409 10410 private static boolean isExternal(PackageSetting ps) { 10411 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10412 } 10413 10414 private static boolean isSystemApp(PackageParser.Package pkg) { 10415 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10416 } 10417 10418 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10419 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10420 } 10421 10422 private static boolean isSystemApp(ApplicationInfo info) { 10423 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10424 } 10425 10426 private static boolean isSystemApp(PackageSetting ps) { 10427 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10428 } 10429 10430 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10431 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10432 } 10433 10434 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10435 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10436 } 10437 10438 private int packageFlagsToInstallFlags(PackageSetting ps) { 10439 int installFlags = 0; 10440 if (isExternal(ps)) { 10441 installFlags |= PackageManager.INSTALL_EXTERNAL; 10442 } 10443 if (isForwardLocked(ps)) { 10444 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10445 } 10446 return installFlags; 10447 } 10448 10449 private void deleteTempPackageFiles() { 10450 final FilenameFilter filter = new FilenameFilter() { 10451 public boolean accept(File dir, String name) { 10452 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10453 } 10454 }; 10455 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 10456 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 10457 } 10458 10459 private static final void deleteTempPackageFilesInDirectory(File directory, 10460 FilenameFilter filter) { 10461 final String[] tmpFilesList = directory.list(filter); 10462 if (tmpFilesList == null) { 10463 return; 10464 } 10465 for (int i = 0; i < tmpFilesList.length; i++) { 10466 final File tmpFile = new File(directory, tmpFilesList[i]); 10467 tmpFile.delete(); 10468 } 10469 } 10470 10471 private File createTempPackageFile(File installDir) { 10472 File tmpPackageFile; 10473 try { 10474 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 10475 } catch (IOException e) { 10476 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 10477 return null; 10478 } 10479 try { 10480 FileUtils.setPermissions( 10481 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 10482 -1, -1); 10483 if (!SELinux.restorecon(tmpPackageFile)) { 10484 return null; 10485 } 10486 } catch (IOException e) { 10487 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 10488 return null; 10489 } 10490 return tmpPackageFile; 10491 } 10492 10493 @Override 10494 public void deletePackageAsUser(final String packageName, 10495 final IPackageDeleteObserver observer, 10496 final int userId, final int flags) { 10497 mContext.enforceCallingOrSelfPermission( 10498 android.Manifest.permission.DELETE_PACKAGES, null); 10499 final int uid = Binder.getCallingUid(); 10500 if (UserHandle.getUserId(uid) != userId) { 10501 mContext.enforceCallingPermission( 10502 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10503 "deletePackage for user " + userId); 10504 } 10505 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10506 try { 10507 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10508 } catch (RemoteException re) { 10509 } 10510 return; 10511 } 10512 10513 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10514 // Queue up an async operation since the package deletion may take a little while. 10515 mHandler.post(new Runnable() { 10516 public void run() { 10517 mHandler.removeCallbacks(this); 10518 final int returnCode = deletePackageX(packageName, userId, flags); 10519 if (observer != null) { 10520 try { 10521 observer.packageDeleted(packageName, returnCode); 10522 } catch (RemoteException e) { 10523 Log.i(TAG, "Observer no longer exists."); 10524 } //end catch 10525 } //end if 10526 } //end run 10527 }); 10528 } 10529 10530 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10531 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10532 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10533 try { 10534 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10535 || dpm.isDeviceOwner(packageName))) { 10536 return true; 10537 } 10538 } catch (RemoteException e) { 10539 } 10540 return false; 10541 } 10542 10543 /** 10544 * This method is an internal method that could be get invoked either 10545 * to delete an installed package or to clean up a failed installation. 10546 * After deleting an installed package, a broadcast is sent to notify any 10547 * listeners that the package has been installed. For cleaning up a failed 10548 * installation, the broadcast is not necessary since the package's 10549 * installation wouldn't have sent the initial broadcast either 10550 * The key steps in deleting a package are 10551 * deleting the package information in internal structures like mPackages, 10552 * deleting the packages base directories through installd 10553 * updating mSettings to reflect current status 10554 * persisting settings for later use 10555 * sending a broadcast if necessary 10556 */ 10557 private int deletePackageX(String packageName, int userId, int flags) { 10558 final PackageRemovedInfo info = new PackageRemovedInfo(); 10559 final boolean res; 10560 10561 if (isPackageDeviceAdmin(packageName, userId)) { 10562 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10563 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10564 } 10565 10566 boolean removedForAllUsers = false; 10567 boolean systemUpdate = false; 10568 10569 // for the uninstall-updates case and restricted profiles, remember the per- 10570 // userhandle installed state 10571 int[] allUsers; 10572 boolean[] perUserInstalled; 10573 synchronized (mPackages) { 10574 PackageSetting ps = mSettings.mPackages.get(packageName); 10575 allUsers = sUserManager.getUserIds(); 10576 perUserInstalled = new boolean[allUsers.length]; 10577 for (int i = 0; i < allUsers.length; i++) { 10578 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10579 } 10580 } 10581 10582 synchronized (mInstallLock) { 10583 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10584 res = deletePackageLI(packageName, 10585 (flags & PackageManager.DELETE_ALL_USERS) != 0 10586 ? UserHandle.ALL : new UserHandle(userId), 10587 true, allUsers, perUserInstalled, 10588 flags | REMOVE_CHATTY, info, true); 10589 systemUpdate = info.isRemovedPackageSystemUpdate; 10590 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10591 removedForAllUsers = true; 10592 } 10593 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10594 + " removedForAllUsers=" + removedForAllUsers); 10595 } 10596 10597 if (res) { 10598 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10599 10600 // If the removed package was a system update, the old system package 10601 // was re-enabled; we need to broadcast this information 10602 if (systemUpdate) { 10603 Bundle extras = new Bundle(1); 10604 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10605 ? info.removedAppId : info.uid); 10606 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10607 10608 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10609 extras, null, null, null); 10610 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10611 extras, null, null, null); 10612 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10613 null, packageName, null, null); 10614 } 10615 } 10616 // Force a gc here. 10617 Runtime.getRuntime().gc(); 10618 // Delete the resources here after sending the broadcast to let 10619 // other processes clean up before deleting resources. 10620 if (info.args != null) { 10621 synchronized (mInstallLock) { 10622 info.args.doPostDeleteLI(true); 10623 } 10624 } 10625 10626 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10627 } 10628 10629 static class PackageRemovedInfo { 10630 String removedPackage; 10631 int uid = -1; 10632 int removedAppId = -1; 10633 int[] removedUsers = null; 10634 boolean isRemovedPackageSystemUpdate = false; 10635 // Clean up resources deleted packages. 10636 InstallArgs args = null; 10637 10638 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10639 Bundle extras = new Bundle(1); 10640 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10641 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10642 if (replacing) { 10643 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10644 } 10645 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10646 if (removedPackage != null) { 10647 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10648 extras, null, null, removedUsers); 10649 if (fullRemove && !replacing) { 10650 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10651 extras, null, null, removedUsers); 10652 } 10653 } 10654 if (removedAppId >= 0) { 10655 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10656 removedUsers); 10657 } 10658 } 10659 } 10660 10661 /* 10662 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10663 * flag is not set, the data directory is removed as well. 10664 * make sure this flag is set for partially installed apps. If not its meaningless to 10665 * delete a partially installed application. 10666 */ 10667 private void removePackageDataLI(PackageSetting ps, 10668 int[] allUserHandles, boolean[] perUserInstalled, 10669 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10670 String packageName = ps.name; 10671 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10672 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10673 // Retrieve object to delete permissions for shared user later on 10674 final PackageSetting deletedPs; 10675 // reader 10676 synchronized (mPackages) { 10677 deletedPs = mSettings.mPackages.get(packageName); 10678 if (outInfo != null) { 10679 outInfo.removedPackage = packageName; 10680 outInfo.removedUsers = deletedPs != null 10681 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10682 : null; 10683 } 10684 } 10685 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10686 removeDataDirsLI(packageName); 10687 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10688 } 10689 // writer 10690 synchronized (mPackages) { 10691 if (deletedPs != null) { 10692 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10693 if (outInfo != null) { 10694 mSettings.mKeySetManagerService.removeAppKeySetData(packageName); 10695 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10696 } 10697 if (deletedPs != null) { 10698 updatePermissionsLPw(deletedPs.name, null, 0); 10699 if (deletedPs.sharedUser != null) { 10700 // remove permissions associated with package 10701 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10702 } 10703 } 10704 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10705 } 10706 // make sure to preserve per-user disabled state if this removal was just 10707 // a downgrade of a system app to the factory package 10708 if (allUserHandles != null && perUserInstalled != null) { 10709 if (DEBUG_REMOVE) { 10710 Slog.d(TAG, "Propagating install state across downgrade"); 10711 } 10712 for (int i = 0; i < allUserHandles.length; i++) { 10713 if (DEBUG_REMOVE) { 10714 Slog.d(TAG, " user " + allUserHandles[i] 10715 + " => " + perUserInstalled[i]); 10716 } 10717 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10718 } 10719 } 10720 } 10721 // can downgrade to reader 10722 if (writeSettings) { 10723 // Save settings now 10724 mSettings.writeLPr(); 10725 } 10726 } 10727 if (outInfo != null) { 10728 // A user ID was deleted here. Go through all users and remove it 10729 // from KeyStore. 10730 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10731 } 10732 } 10733 10734 static boolean locationIsPrivileged(File path) { 10735 try { 10736 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10737 .getCanonicalPath(); 10738 return path.getCanonicalPath().startsWith(privilegedAppDir); 10739 } catch (IOException e) { 10740 Slog.e(TAG, "Unable to access code path " + path); 10741 } 10742 return false; 10743 } 10744 10745 /* 10746 * Tries to delete system package. 10747 */ 10748 private boolean deleteSystemPackageLI(PackageSetting newPs, 10749 int[] allUserHandles, boolean[] perUserInstalled, 10750 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10751 final boolean applyUserRestrictions 10752 = (allUserHandles != null) && (perUserInstalled != null); 10753 PackageSetting disabledPs = null; 10754 // Confirm if the system package has been updated 10755 // An updated system app can be deleted. This will also have to restore 10756 // the system pkg from system partition 10757 // reader 10758 synchronized (mPackages) { 10759 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10760 } 10761 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10762 + " disabledPs=" + disabledPs); 10763 if (disabledPs == null) { 10764 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10765 return false; 10766 } else if (DEBUG_REMOVE) { 10767 Slog.d(TAG, "Deleting system pkg from data partition"); 10768 } 10769 if (DEBUG_REMOVE) { 10770 if (applyUserRestrictions) { 10771 Slog.d(TAG, "Remembering install states:"); 10772 for (int i = 0; i < allUserHandles.length; i++) { 10773 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10774 } 10775 } 10776 } 10777 // Delete the updated package 10778 outInfo.isRemovedPackageSystemUpdate = true; 10779 if (disabledPs.versionCode < newPs.versionCode) { 10780 // Delete data for downgrades 10781 flags &= ~PackageManager.DELETE_KEEP_DATA; 10782 } else { 10783 // Preserve data by setting flag 10784 flags |= PackageManager.DELETE_KEEP_DATA; 10785 } 10786 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10787 allUserHandles, perUserInstalled, outInfo, writeSettings); 10788 if (!ret) { 10789 return false; 10790 } 10791 // writer 10792 synchronized (mPackages) { 10793 // Reinstate the old system package 10794 mSettings.enableSystemPackageLPw(newPs.name); 10795 // Remove any native libraries from the upgraded package. 10796 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 10797 } 10798 // Install the system package 10799 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10800 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10801 if (locationIsPrivileged(disabledPs.codePath)) { 10802 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10803 } 10804 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10805 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null); 10806 10807 if (newPkg == null) { 10808 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10809 + " with error:" + mLastScanError); 10810 return false; 10811 } 10812 // writer 10813 synchronized (mPackages) { 10814 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10815 setInternalAppNativeLibraryPath(newPkg, ps); 10816 updatePermissionsLPw(newPkg.packageName, newPkg, 10817 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10818 if (applyUserRestrictions) { 10819 if (DEBUG_REMOVE) { 10820 Slog.d(TAG, "Propagating install state across reinstall"); 10821 } 10822 for (int i = 0; i < allUserHandles.length; i++) { 10823 if (DEBUG_REMOVE) { 10824 Slog.d(TAG, " user " + allUserHandles[i] 10825 + " => " + perUserInstalled[i]); 10826 } 10827 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10828 } 10829 // Regardless of writeSettings we need to ensure that this restriction 10830 // state propagation is persisted 10831 mSettings.writeAllUsersPackageRestrictionsLPr(); 10832 } 10833 // can downgrade to reader here 10834 if (writeSettings) { 10835 mSettings.writeLPr(); 10836 } 10837 } 10838 return true; 10839 } 10840 10841 private boolean deleteInstalledPackageLI(PackageSetting ps, 10842 boolean deleteCodeAndResources, int flags, 10843 int[] allUserHandles, boolean[] perUserInstalled, 10844 PackageRemovedInfo outInfo, boolean writeSettings) { 10845 if (outInfo != null) { 10846 outInfo.uid = ps.appId; 10847 } 10848 10849 // Delete package data from internal structures and also remove data if flag is set 10850 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10851 10852 // Delete application code and resources 10853 if (deleteCodeAndResources && (outInfo != null)) { 10854 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10855 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 10856 getAppInstructionSetFromSettings(ps)); 10857 } 10858 return true; 10859 } 10860 10861 @Override 10862 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10863 int userId) { 10864 mContext.enforceCallingOrSelfPermission( 10865 android.Manifest.permission.DELETE_PACKAGES, null); 10866 synchronized (mPackages) { 10867 PackageSetting ps = mSettings.mPackages.get(packageName); 10868 if (ps == null) { 10869 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10870 return false; 10871 } 10872 if (!ps.getInstalled(userId)) { 10873 // Can't block uninstall for an app that is not installed or enabled. 10874 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10875 return false; 10876 } 10877 ps.setBlockUninstall(blockUninstall, userId); 10878 mSettings.writePackageRestrictionsLPr(userId); 10879 } 10880 return true; 10881 } 10882 10883 @Override 10884 public boolean getBlockUninstallForUser(String packageName, int userId) { 10885 synchronized (mPackages) { 10886 PackageSetting ps = mSettings.mPackages.get(packageName); 10887 if (ps == null) { 10888 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10889 return false; 10890 } 10891 return ps.getBlockUninstall(userId); 10892 } 10893 } 10894 10895 /* 10896 * This method handles package deletion in general 10897 */ 10898 private boolean deletePackageLI(String packageName, UserHandle user, 10899 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10900 int flags, PackageRemovedInfo outInfo, 10901 boolean writeSettings) { 10902 if (packageName == null) { 10903 Slog.w(TAG, "Attempt to delete null packageName."); 10904 return false; 10905 } 10906 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10907 PackageSetting ps; 10908 boolean dataOnly = false; 10909 int removeUser = -1; 10910 int appId = -1; 10911 synchronized (mPackages) { 10912 ps = mSettings.mPackages.get(packageName); 10913 if (ps == null) { 10914 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10915 return false; 10916 } 10917 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10918 && user.getIdentifier() != UserHandle.USER_ALL) { 10919 // The caller is asking that the package only be deleted for a single 10920 // user. To do this, we just mark its uninstalled state and delete 10921 // its data. If this is a system app, we only allow this to happen if 10922 // they have set the special DELETE_SYSTEM_APP which requests different 10923 // semantics than normal for uninstalling system apps. 10924 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10925 ps.setUserState(user.getIdentifier(), 10926 COMPONENT_ENABLED_STATE_DEFAULT, 10927 false, //installed 10928 true, //stopped 10929 true, //notLaunched 10930 false, //blocked 10931 null, null, null, 10932 false // blockUninstall 10933 ); 10934 if (!isSystemApp(ps)) { 10935 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10936 // Other user still have this package installed, so all 10937 // we need to do is clear this user's data and save that 10938 // it is uninstalled. 10939 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10940 removeUser = user.getIdentifier(); 10941 appId = ps.appId; 10942 mSettings.writePackageRestrictionsLPr(removeUser); 10943 } else { 10944 // We need to set it back to 'installed' so the uninstall 10945 // broadcasts will be sent correctly. 10946 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10947 ps.setInstalled(true, user.getIdentifier()); 10948 } 10949 } else { 10950 // This is a system app, so we assume that the 10951 // other users still have this package installed, so all 10952 // we need to do is clear this user's data and save that 10953 // it is uninstalled. 10954 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10955 removeUser = user.getIdentifier(); 10956 appId = ps.appId; 10957 mSettings.writePackageRestrictionsLPr(removeUser); 10958 } 10959 } 10960 } 10961 10962 if (removeUser >= 0) { 10963 // From above, we determined that we are deleting this only 10964 // for a single user. Continue the work here. 10965 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10966 if (outInfo != null) { 10967 outInfo.removedPackage = packageName; 10968 outInfo.removedAppId = appId; 10969 outInfo.removedUsers = new int[] {removeUser}; 10970 } 10971 mInstaller.clearUserData(packageName, removeUser); 10972 removeKeystoreDataIfNeeded(removeUser, appId); 10973 schedulePackageCleaning(packageName, removeUser, false); 10974 return true; 10975 } 10976 10977 if (dataOnly) { 10978 // Delete application data first 10979 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10980 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10981 return true; 10982 } 10983 10984 boolean ret = false; 10985 if (isSystemApp(ps)) { 10986 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10987 // When an updated system application is deleted we delete the existing resources as well and 10988 // fall back to existing code in system partition 10989 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10990 flags, outInfo, writeSettings); 10991 } else { 10992 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10993 // Kill application pre-emptively especially for apps on sd. 10994 killApplication(packageName, ps.appId, "uninstall pkg"); 10995 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10996 allUserHandles, perUserInstalled, 10997 outInfo, writeSettings); 10998 } 10999 11000 return ret; 11001 } 11002 11003 private final class ClearStorageConnection implements ServiceConnection { 11004 IMediaContainerService mContainerService; 11005 11006 @Override 11007 public void onServiceConnected(ComponentName name, IBinder service) { 11008 synchronized (this) { 11009 mContainerService = IMediaContainerService.Stub.asInterface(service); 11010 notifyAll(); 11011 } 11012 } 11013 11014 @Override 11015 public void onServiceDisconnected(ComponentName name) { 11016 } 11017 } 11018 11019 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11020 final boolean mounted; 11021 if (Environment.isExternalStorageEmulated()) { 11022 mounted = true; 11023 } else { 11024 final String status = Environment.getExternalStorageState(); 11025 11026 mounted = status.equals(Environment.MEDIA_MOUNTED) 11027 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11028 } 11029 11030 if (!mounted) { 11031 return; 11032 } 11033 11034 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11035 int[] users; 11036 if (userId == UserHandle.USER_ALL) { 11037 users = sUserManager.getUserIds(); 11038 } else { 11039 users = new int[] { userId }; 11040 } 11041 final ClearStorageConnection conn = new ClearStorageConnection(); 11042 if (mContext.bindServiceAsUser( 11043 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11044 try { 11045 for (int curUser : users) { 11046 long timeout = SystemClock.uptimeMillis() + 5000; 11047 synchronized (conn) { 11048 long now = SystemClock.uptimeMillis(); 11049 while (conn.mContainerService == null && now < timeout) { 11050 try { 11051 conn.wait(timeout - now); 11052 } catch (InterruptedException e) { 11053 } 11054 } 11055 } 11056 if (conn.mContainerService == null) { 11057 return; 11058 } 11059 11060 final UserEnvironment userEnv = new UserEnvironment(curUser); 11061 clearDirectory(conn.mContainerService, 11062 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11063 if (allData) { 11064 clearDirectory(conn.mContainerService, 11065 userEnv.buildExternalStorageAppDataDirs(packageName)); 11066 clearDirectory(conn.mContainerService, 11067 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11068 } 11069 } 11070 } finally { 11071 mContext.unbindService(conn); 11072 } 11073 } 11074 } 11075 11076 @Override 11077 public void clearApplicationUserData(final String packageName, 11078 final IPackageDataObserver observer, final int userId) { 11079 mContext.enforceCallingOrSelfPermission( 11080 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11081 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11082 // Queue up an async operation since the package deletion may take a little while. 11083 mHandler.post(new Runnable() { 11084 public void run() { 11085 mHandler.removeCallbacks(this); 11086 final boolean succeeded; 11087 synchronized (mInstallLock) { 11088 succeeded = clearApplicationUserDataLI(packageName, userId); 11089 } 11090 clearExternalStorageDataSync(packageName, userId, true); 11091 if (succeeded) { 11092 // invoke DeviceStorageMonitor's update method to clear any notifications 11093 DeviceStorageMonitorInternal 11094 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11095 if (dsm != null) { 11096 dsm.checkMemory(); 11097 } 11098 } 11099 if(observer != null) { 11100 try { 11101 observer.onRemoveCompleted(packageName, succeeded); 11102 } catch (RemoteException e) { 11103 Log.i(TAG, "Observer no longer exists."); 11104 } 11105 } //end if observer 11106 } //end run 11107 }); 11108 } 11109 11110 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11111 if (packageName == null) { 11112 Slog.w(TAG, "Attempt to delete null packageName."); 11113 return false; 11114 } 11115 PackageParser.Package p; 11116 boolean dataOnly = false; 11117 final int appId; 11118 synchronized (mPackages) { 11119 p = mPackages.get(packageName); 11120 if (p == null) { 11121 dataOnly = true; 11122 PackageSetting ps = mSettings.mPackages.get(packageName); 11123 if ((ps == null) || (ps.pkg == null)) { 11124 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11125 return false; 11126 } 11127 p = ps.pkg; 11128 } 11129 if (!dataOnly) { 11130 // need to check this only for fully installed applications 11131 if (p == null) { 11132 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11133 return false; 11134 } 11135 final ApplicationInfo applicationInfo = p.applicationInfo; 11136 if (applicationInfo == null) { 11137 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11138 return false; 11139 } 11140 } 11141 if (p != null && p.applicationInfo != null) { 11142 appId = p.applicationInfo.uid; 11143 } else { 11144 appId = -1; 11145 } 11146 } 11147 int retCode = mInstaller.clearUserData(packageName, userId); 11148 if (retCode < 0) { 11149 Slog.w(TAG, "Couldn't remove cache files for package: " 11150 + packageName); 11151 return false; 11152 } 11153 removeKeystoreDataIfNeeded(userId, appId); 11154 return true; 11155 } 11156 11157 /** 11158 * Remove entries from the keystore daemon. Will only remove it if the 11159 * {@code appId} is valid. 11160 */ 11161 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11162 if (appId < 0) { 11163 return; 11164 } 11165 11166 final KeyStore keyStore = KeyStore.getInstance(); 11167 if (keyStore != null) { 11168 if (userId == UserHandle.USER_ALL) { 11169 for (final int individual : sUserManager.getUserIds()) { 11170 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11171 } 11172 } else { 11173 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11174 } 11175 } else { 11176 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11177 } 11178 } 11179 11180 @Override 11181 public void deleteApplicationCacheFiles(final String packageName, 11182 final IPackageDataObserver observer) { 11183 mContext.enforceCallingOrSelfPermission( 11184 android.Manifest.permission.DELETE_CACHE_FILES, null); 11185 // Queue up an async operation since the package deletion may take a little while. 11186 final int userId = UserHandle.getCallingUserId(); 11187 mHandler.post(new Runnable() { 11188 public void run() { 11189 mHandler.removeCallbacks(this); 11190 final boolean succeded; 11191 synchronized (mInstallLock) { 11192 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11193 } 11194 clearExternalStorageDataSync(packageName, userId, false); 11195 if(observer != null) { 11196 try { 11197 observer.onRemoveCompleted(packageName, succeded); 11198 } catch (RemoteException e) { 11199 Log.i(TAG, "Observer no longer exists."); 11200 } 11201 } //end if observer 11202 } //end run 11203 }); 11204 } 11205 11206 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11207 if (packageName == null) { 11208 Slog.w(TAG, "Attempt to delete null packageName."); 11209 return false; 11210 } 11211 PackageParser.Package p; 11212 synchronized (mPackages) { 11213 p = mPackages.get(packageName); 11214 } 11215 if (p == null) { 11216 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11217 return false; 11218 } 11219 final ApplicationInfo applicationInfo = p.applicationInfo; 11220 if (applicationInfo == null) { 11221 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11222 return false; 11223 } 11224 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11225 if (retCode < 0) { 11226 Slog.w(TAG, "Couldn't remove cache files for package: " 11227 + packageName + " u" + userId); 11228 return false; 11229 } 11230 return true; 11231 } 11232 11233 @Override 11234 public void getPackageSizeInfo(final String packageName, int userHandle, 11235 final IPackageStatsObserver observer) { 11236 mContext.enforceCallingOrSelfPermission( 11237 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11238 if (packageName == null) { 11239 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11240 } 11241 11242 PackageStats stats = new PackageStats(packageName, userHandle); 11243 11244 /* 11245 * Queue up an async operation since the package measurement may take a 11246 * little while. 11247 */ 11248 Message msg = mHandler.obtainMessage(INIT_COPY); 11249 msg.obj = new MeasureParams(stats, observer); 11250 mHandler.sendMessage(msg); 11251 } 11252 11253 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11254 PackageStats pStats) { 11255 if (packageName == null) { 11256 Slog.w(TAG, "Attempt to get size of null packageName."); 11257 return false; 11258 } 11259 PackageParser.Package p; 11260 boolean dataOnly = false; 11261 String libDirPath = null; 11262 String asecPath = null; 11263 PackageSetting ps = null; 11264 synchronized (mPackages) { 11265 p = mPackages.get(packageName); 11266 ps = mSettings.mPackages.get(packageName); 11267 if(p == null) { 11268 dataOnly = true; 11269 if((ps == null) || (ps.pkg == null)) { 11270 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11271 return false; 11272 } 11273 p = ps.pkg; 11274 } 11275 if (ps != null) { 11276 libDirPath = ps.nativeLibraryPathString; 11277 } 11278 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11279 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 11280 if (secureContainerId != null) { 11281 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11282 } 11283 } 11284 } 11285 String publicSrcDir = null; 11286 if(!dataOnly) { 11287 final ApplicationInfo applicationInfo = p.applicationInfo; 11288 if (applicationInfo == null) { 11289 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11290 return false; 11291 } 11292 if (isForwardLocked(p)) { 11293 publicSrcDir = applicationInfo.publicSourceDir; 11294 } 11295 } 11296 // TODO: extend to measure size of split APKs 11297 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirPath, 11298 publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps), 11299 pStats); 11300 if (res < 0) { 11301 return false; 11302 } 11303 11304 // Fix-up for forward-locked applications in ASEC containers. 11305 if (!isExternal(p)) { 11306 pStats.codeSize += pStats.externalCodeSize; 11307 pStats.externalCodeSize = 0L; 11308 } 11309 11310 return true; 11311 } 11312 11313 11314 @Override 11315 public void addPackageToPreferred(String packageName) { 11316 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11317 } 11318 11319 @Override 11320 public void removePackageFromPreferred(String packageName) { 11321 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11322 } 11323 11324 @Override 11325 public List<PackageInfo> getPreferredPackages(int flags) { 11326 return new ArrayList<PackageInfo>(); 11327 } 11328 11329 private int getUidTargetSdkVersionLockedLPr(int uid) { 11330 Object obj = mSettings.getUserIdLPr(uid); 11331 if (obj instanceof SharedUserSetting) { 11332 final SharedUserSetting sus = (SharedUserSetting) obj; 11333 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11334 final Iterator<PackageSetting> it = sus.packages.iterator(); 11335 while (it.hasNext()) { 11336 final PackageSetting ps = it.next(); 11337 if (ps.pkg != null) { 11338 int v = ps.pkg.applicationInfo.targetSdkVersion; 11339 if (v < vers) vers = v; 11340 } 11341 } 11342 return vers; 11343 } else if (obj instanceof PackageSetting) { 11344 final PackageSetting ps = (PackageSetting) obj; 11345 if (ps.pkg != null) { 11346 return ps.pkg.applicationInfo.targetSdkVersion; 11347 } 11348 } 11349 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11350 } 11351 11352 @Override 11353 public void addPreferredActivity(IntentFilter filter, int match, 11354 ComponentName[] set, ComponentName activity, int userId) { 11355 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11356 } 11357 11358 private void addPreferredActivityInternal(IntentFilter filter, int match, 11359 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11360 // writer 11361 int callingUid = Binder.getCallingUid(); 11362 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11363 if (filter.countActions() == 0) { 11364 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11365 return; 11366 } 11367 synchronized (mPackages) { 11368 if (mContext.checkCallingOrSelfPermission( 11369 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11370 != PackageManager.PERMISSION_GRANTED) { 11371 if (getUidTargetSdkVersionLockedLPr(callingUid) 11372 < Build.VERSION_CODES.FROYO) { 11373 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11374 + callingUid); 11375 return; 11376 } 11377 mContext.enforceCallingOrSelfPermission( 11378 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11379 } 11380 11381 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11382 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11383 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11384 new PreferredActivity(filter, match, set, activity, always)); 11385 mSettings.writePackageRestrictionsLPr(userId); 11386 } 11387 } 11388 11389 @Override 11390 public void replacePreferredActivity(IntentFilter filter, int match, 11391 ComponentName[] set, ComponentName activity) { 11392 if (filter.countActions() != 1) { 11393 throw new IllegalArgumentException( 11394 "replacePreferredActivity expects filter to have only 1 action."); 11395 } 11396 if (filter.countDataAuthorities() != 0 11397 || filter.countDataPaths() != 0 11398 || filter.countDataSchemes() > 1 11399 || filter.countDataTypes() != 0) { 11400 throw new IllegalArgumentException( 11401 "replacePreferredActivity expects filter to have no data authorities, " + 11402 "paths, or types; and at most one scheme."); 11403 } 11404 synchronized (mPackages) { 11405 if (mContext.checkCallingOrSelfPermission( 11406 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11407 != PackageManager.PERMISSION_GRANTED) { 11408 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11409 < Build.VERSION_CODES.FROYO) { 11410 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11411 + Binder.getCallingUid()); 11412 return; 11413 } 11414 mContext.enforceCallingOrSelfPermission( 11415 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11416 } 11417 11418 final int callingUserId = UserHandle.getCallingUserId(); 11419 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11420 if (pir != null) { 11421 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11422 if (filter.countDataSchemes() == 1) { 11423 Uri.Builder builder = new Uri.Builder(); 11424 builder.scheme(filter.getDataScheme(0)); 11425 intent.setData(builder.build()); 11426 } 11427 List<PreferredActivity> matches = pir.queryIntent( 11428 intent, null, true, callingUserId); 11429 if (DEBUG_PREFERRED) { 11430 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11431 } 11432 for (int i = 0; i < matches.size(); i++) { 11433 PreferredActivity pa = matches.get(i); 11434 if (DEBUG_PREFERRED) { 11435 Slog.i(TAG, "Removing preferred activity " 11436 + pa.mPref.mComponent + ":"); 11437 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11438 } 11439 pir.removeFilter(pa); 11440 } 11441 } 11442 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11443 } 11444 } 11445 11446 @Override 11447 public void clearPackagePreferredActivities(String packageName) { 11448 final int uid = Binder.getCallingUid(); 11449 // writer 11450 synchronized (mPackages) { 11451 PackageParser.Package pkg = mPackages.get(packageName); 11452 if (pkg == null || pkg.applicationInfo.uid != uid) { 11453 if (mContext.checkCallingOrSelfPermission( 11454 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11455 != PackageManager.PERMISSION_GRANTED) { 11456 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11457 < Build.VERSION_CODES.FROYO) { 11458 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11459 + Binder.getCallingUid()); 11460 return; 11461 } 11462 mContext.enforceCallingOrSelfPermission( 11463 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11464 } 11465 } 11466 11467 int user = UserHandle.getCallingUserId(); 11468 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11469 mSettings.writePackageRestrictionsLPr(user); 11470 scheduleWriteSettingsLocked(); 11471 } 11472 } 11473 } 11474 11475 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11476 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11477 ArrayList<PreferredActivity> removed = null; 11478 boolean changed = false; 11479 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11480 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11481 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11482 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11483 continue; 11484 } 11485 Iterator<PreferredActivity> it = pir.filterIterator(); 11486 while (it.hasNext()) { 11487 PreferredActivity pa = it.next(); 11488 // Mark entry for removal only if it matches the package name 11489 // and the entry is of type "always". 11490 if (packageName == null || 11491 (pa.mPref.mComponent.getPackageName().equals(packageName) 11492 && pa.mPref.mAlways)) { 11493 if (removed == null) { 11494 removed = new ArrayList<PreferredActivity>(); 11495 } 11496 removed.add(pa); 11497 } 11498 } 11499 if (removed != null) { 11500 for (int j=0; j<removed.size(); j++) { 11501 PreferredActivity pa = removed.get(j); 11502 pir.removeFilter(pa); 11503 } 11504 changed = true; 11505 } 11506 } 11507 return changed; 11508 } 11509 11510 @Override 11511 public void resetPreferredActivities(int userId) { 11512 mContext.enforceCallingOrSelfPermission( 11513 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11514 // writer 11515 synchronized (mPackages) { 11516 int user = UserHandle.getCallingUserId(); 11517 clearPackagePreferredActivitiesLPw(null, user); 11518 mSettings.readDefaultPreferredAppsLPw(this, user); 11519 mSettings.writePackageRestrictionsLPr(user); 11520 scheduleWriteSettingsLocked(); 11521 } 11522 } 11523 11524 @Override 11525 public int getPreferredActivities(List<IntentFilter> outFilters, 11526 List<ComponentName> outActivities, String packageName) { 11527 11528 int num = 0; 11529 final int userId = UserHandle.getCallingUserId(); 11530 // reader 11531 synchronized (mPackages) { 11532 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11533 if (pir != null) { 11534 final Iterator<PreferredActivity> it = pir.filterIterator(); 11535 while (it.hasNext()) { 11536 final PreferredActivity pa = it.next(); 11537 if (packageName == null 11538 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11539 && pa.mPref.mAlways)) { 11540 if (outFilters != null) { 11541 outFilters.add(new IntentFilter(pa)); 11542 } 11543 if (outActivities != null) { 11544 outActivities.add(pa.mPref.mComponent); 11545 } 11546 } 11547 } 11548 } 11549 } 11550 11551 return num; 11552 } 11553 11554 @Override 11555 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11556 int userId) { 11557 int callingUid = Binder.getCallingUid(); 11558 if (callingUid != Process.SYSTEM_UID) { 11559 throw new SecurityException( 11560 "addPersistentPreferredActivity can only be run by the system"); 11561 } 11562 if (filter.countActions() == 0) { 11563 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11564 return; 11565 } 11566 synchronized (mPackages) { 11567 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11568 " :"); 11569 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11570 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11571 new PersistentPreferredActivity(filter, activity)); 11572 mSettings.writePackageRestrictionsLPr(userId); 11573 } 11574 } 11575 11576 @Override 11577 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11578 int callingUid = Binder.getCallingUid(); 11579 if (callingUid != Process.SYSTEM_UID) { 11580 throw new SecurityException( 11581 "clearPackagePersistentPreferredActivities can only be run by the system"); 11582 } 11583 ArrayList<PersistentPreferredActivity> removed = null; 11584 boolean changed = false; 11585 synchronized (mPackages) { 11586 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11587 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11588 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11589 .valueAt(i); 11590 if (userId != thisUserId) { 11591 continue; 11592 } 11593 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11594 while (it.hasNext()) { 11595 PersistentPreferredActivity ppa = it.next(); 11596 // Mark entry for removal only if it matches the package name. 11597 if (ppa.mComponent.getPackageName().equals(packageName)) { 11598 if (removed == null) { 11599 removed = new ArrayList<PersistentPreferredActivity>(); 11600 } 11601 removed.add(ppa); 11602 } 11603 } 11604 if (removed != null) { 11605 for (int j=0; j<removed.size(); j++) { 11606 PersistentPreferredActivity ppa = removed.get(j); 11607 ppir.removeFilter(ppa); 11608 } 11609 changed = true; 11610 } 11611 } 11612 11613 if (changed) { 11614 mSettings.writePackageRestrictionsLPr(userId); 11615 } 11616 } 11617 } 11618 11619 @Override 11620 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11621 int targetUserId, int flags) { 11622 mContext.enforceCallingOrSelfPermission( 11623 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11624 if (intentFilter.countActions() == 0) { 11625 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11626 return; 11627 } 11628 synchronized (mPackages) { 11629 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11630 targetUserId, flags); 11631 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11632 mSettings.writePackageRestrictionsLPr(sourceUserId); 11633 } 11634 } 11635 11636 public void addCrossProfileIntentsForPackage(String packageName, 11637 int sourceUserId, int targetUserId) { 11638 mContext.enforceCallingOrSelfPermission( 11639 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11640 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11641 mSettings.writePackageRestrictionsLPr(sourceUserId); 11642 } 11643 11644 public void removeCrossProfileIntentsForPackage(String packageName, 11645 int sourceUserId, int targetUserId) { 11646 mContext.enforceCallingOrSelfPermission( 11647 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11648 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11649 mSettings.writePackageRestrictionsLPr(sourceUserId); 11650 } 11651 11652 @Override 11653 public void clearCrossProfileIntentFilters(int sourceUserId) { 11654 mContext.enforceCallingOrSelfPermission( 11655 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11656 synchronized (mPackages) { 11657 CrossProfileIntentResolver resolver = 11658 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11659 HashSet<CrossProfileIntentFilter> set = 11660 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11661 for (CrossProfileIntentFilter filter : set) { 11662 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11663 resolver.removeFilter(filter); 11664 } 11665 } 11666 mSettings.writePackageRestrictionsLPr(sourceUserId); 11667 } 11668 } 11669 11670 @Override 11671 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11672 Intent intent = new Intent(Intent.ACTION_MAIN); 11673 intent.addCategory(Intent.CATEGORY_HOME); 11674 11675 final int callingUserId = UserHandle.getCallingUserId(); 11676 List<ResolveInfo> list = queryIntentActivities(intent, null, 11677 PackageManager.GET_META_DATA, callingUserId); 11678 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11679 true, false, false, callingUserId); 11680 11681 allHomeCandidates.clear(); 11682 if (list != null) { 11683 for (ResolveInfo ri : list) { 11684 allHomeCandidates.add(ri); 11685 } 11686 } 11687 return (preferred == null || preferred.activityInfo == null) 11688 ? null 11689 : new ComponentName(preferred.activityInfo.packageName, 11690 preferred.activityInfo.name); 11691 } 11692 11693 @Override 11694 public void setApplicationEnabledSetting(String appPackageName, 11695 int newState, int flags, int userId, String callingPackage) { 11696 if (!sUserManager.exists(userId)) return; 11697 if (callingPackage == null) { 11698 callingPackage = Integer.toString(Binder.getCallingUid()); 11699 } 11700 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11701 } 11702 11703 @Override 11704 public void setComponentEnabledSetting(ComponentName componentName, 11705 int newState, int flags, int userId) { 11706 if (!sUserManager.exists(userId)) return; 11707 setEnabledSetting(componentName.getPackageName(), 11708 componentName.getClassName(), newState, flags, userId, null); 11709 } 11710 11711 private void setEnabledSetting(final String packageName, String className, int newState, 11712 final int flags, int userId, String callingPackage) { 11713 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11714 || newState == COMPONENT_ENABLED_STATE_ENABLED 11715 || newState == COMPONENT_ENABLED_STATE_DISABLED 11716 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11717 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11718 throw new IllegalArgumentException("Invalid new component state: " 11719 + newState); 11720 } 11721 PackageSetting pkgSetting; 11722 final int uid = Binder.getCallingUid(); 11723 final int permission = mContext.checkCallingOrSelfPermission( 11724 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11725 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11726 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11727 boolean sendNow = false; 11728 boolean isApp = (className == null); 11729 String componentName = isApp ? packageName : className; 11730 int packageUid = -1; 11731 ArrayList<String> components; 11732 11733 // writer 11734 synchronized (mPackages) { 11735 pkgSetting = mSettings.mPackages.get(packageName); 11736 if (pkgSetting == null) { 11737 if (className == null) { 11738 throw new IllegalArgumentException( 11739 "Unknown package: " + packageName); 11740 } 11741 throw new IllegalArgumentException( 11742 "Unknown component: " + packageName 11743 + "/" + className); 11744 } 11745 // Allow root and verify that userId is not being specified by a different user 11746 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11747 throw new SecurityException( 11748 "Permission Denial: attempt to change component state from pid=" 11749 + Binder.getCallingPid() 11750 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11751 } 11752 if (className == null) { 11753 // We're dealing with an application/package level state change 11754 if (pkgSetting.getEnabled(userId) == newState) { 11755 // Nothing to do 11756 return; 11757 } 11758 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11759 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11760 // Don't care about who enables an app. 11761 callingPackage = null; 11762 } 11763 pkgSetting.setEnabled(newState, userId, callingPackage); 11764 // pkgSetting.pkg.mSetEnabled = newState; 11765 } else { 11766 // We're dealing with a component level state change 11767 // First, verify that this is a valid class name. 11768 PackageParser.Package pkg = pkgSetting.pkg; 11769 if (pkg == null || !pkg.hasComponentClassName(className)) { 11770 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11771 throw new IllegalArgumentException("Component class " + className 11772 + " does not exist in " + packageName); 11773 } else { 11774 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11775 + className + " does not exist in " + packageName); 11776 } 11777 } 11778 switch (newState) { 11779 case COMPONENT_ENABLED_STATE_ENABLED: 11780 if (!pkgSetting.enableComponentLPw(className, userId)) { 11781 return; 11782 } 11783 break; 11784 case COMPONENT_ENABLED_STATE_DISABLED: 11785 if (!pkgSetting.disableComponentLPw(className, userId)) { 11786 return; 11787 } 11788 break; 11789 case COMPONENT_ENABLED_STATE_DEFAULT: 11790 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11791 return; 11792 } 11793 break; 11794 default: 11795 Slog.e(TAG, "Invalid new component state: " + newState); 11796 return; 11797 } 11798 } 11799 mSettings.writePackageRestrictionsLPr(userId); 11800 components = mPendingBroadcasts.get(userId, packageName); 11801 final boolean newPackage = components == null; 11802 if (newPackage) { 11803 components = new ArrayList<String>(); 11804 } 11805 if (!components.contains(componentName)) { 11806 components.add(componentName); 11807 } 11808 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11809 sendNow = true; 11810 // Purge entry from pending broadcast list if another one exists already 11811 // since we are sending one right away. 11812 mPendingBroadcasts.remove(userId, packageName); 11813 } else { 11814 if (newPackage) { 11815 mPendingBroadcasts.put(userId, packageName, components); 11816 } 11817 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11818 // Schedule a message 11819 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11820 } 11821 } 11822 } 11823 11824 long callingId = Binder.clearCallingIdentity(); 11825 try { 11826 if (sendNow) { 11827 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11828 sendPackageChangedBroadcast(packageName, 11829 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11830 } 11831 } finally { 11832 Binder.restoreCallingIdentity(callingId); 11833 } 11834 } 11835 11836 private void sendPackageChangedBroadcast(String packageName, 11837 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11838 if (DEBUG_INSTALL) 11839 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11840 + componentNames); 11841 Bundle extras = new Bundle(4); 11842 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11843 String nameList[] = new String[componentNames.size()]; 11844 componentNames.toArray(nameList); 11845 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11846 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11847 extras.putInt(Intent.EXTRA_UID, packageUid); 11848 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11849 new int[] {UserHandle.getUserId(packageUid)}); 11850 } 11851 11852 @Override 11853 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11854 if (!sUserManager.exists(userId)) return; 11855 final int uid = Binder.getCallingUid(); 11856 final int permission = mContext.checkCallingOrSelfPermission( 11857 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11858 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11859 enforceCrossUserPermission(uid, userId, true, "stop package"); 11860 // writer 11861 synchronized (mPackages) { 11862 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11863 uid, userId)) { 11864 scheduleWritePackageRestrictionsLocked(userId); 11865 } 11866 } 11867 } 11868 11869 @Override 11870 public String getInstallerPackageName(String packageName) { 11871 // reader 11872 synchronized (mPackages) { 11873 return mSettings.getInstallerPackageNameLPr(packageName); 11874 } 11875 } 11876 11877 @Override 11878 public int getApplicationEnabledSetting(String packageName, int userId) { 11879 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11880 int uid = Binder.getCallingUid(); 11881 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11882 // reader 11883 synchronized (mPackages) { 11884 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11885 } 11886 } 11887 11888 @Override 11889 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11890 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11891 int uid = Binder.getCallingUid(); 11892 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11893 // reader 11894 synchronized (mPackages) { 11895 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11896 } 11897 } 11898 11899 @Override 11900 public void enterSafeMode() { 11901 enforceSystemOrRoot("Only the system can request entering safe mode"); 11902 11903 if (!mSystemReady) { 11904 mSafeMode = true; 11905 } 11906 } 11907 11908 @Override 11909 public void systemReady() { 11910 mSystemReady = true; 11911 11912 // Read the compatibilty setting when the system is ready. 11913 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11914 mContext.getContentResolver(), 11915 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11916 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11917 if (DEBUG_SETTINGS) { 11918 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11919 } 11920 11921 synchronized (mPackages) { 11922 // Verify that all of the preferred activity components actually 11923 // exist. It is possible for applications to be updated and at 11924 // that point remove a previously declared activity component that 11925 // had been set as a preferred activity. We try to clean this up 11926 // the next time we encounter that preferred activity, but it is 11927 // possible for the user flow to never be able to return to that 11928 // situation so here we do a sanity check to make sure we haven't 11929 // left any junk around. 11930 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11931 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11932 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11933 removed.clear(); 11934 for (PreferredActivity pa : pir.filterSet()) { 11935 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11936 removed.add(pa); 11937 } 11938 } 11939 if (removed.size() > 0) { 11940 for (int r=0; r<removed.size(); r++) { 11941 PreferredActivity pa = removed.get(r); 11942 Slog.w(TAG, "Removing dangling preferred activity: " 11943 + pa.mPref.mComponent); 11944 pir.removeFilter(pa); 11945 } 11946 mSettings.writePackageRestrictionsLPr( 11947 mSettings.mPreferredActivities.keyAt(i)); 11948 } 11949 } 11950 } 11951 sUserManager.systemReady(); 11952 } 11953 11954 @Override 11955 public boolean isSafeMode() { 11956 return mSafeMode; 11957 } 11958 11959 @Override 11960 public boolean hasSystemUidErrors() { 11961 return mHasSystemUidErrors; 11962 } 11963 11964 static String arrayToString(int[] array) { 11965 StringBuffer buf = new StringBuffer(128); 11966 buf.append('['); 11967 if (array != null) { 11968 for (int i=0; i<array.length; i++) { 11969 if (i > 0) buf.append(", "); 11970 buf.append(array[i]); 11971 } 11972 } 11973 buf.append(']'); 11974 return buf.toString(); 11975 } 11976 11977 static class DumpState { 11978 public static final int DUMP_LIBS = 1 << 0; 11979 11980 public static final int DUMP_FEATURES = 1 << 1; 11981 11982 public static final int DUMP_RESOLVERS = 1 << 2; 11983 11984 public static final int DUMP_PERMISSIONS = 1 << 3; 11985 11986 public static final int DUMP_PACKAGES = 1 << 4; 11987 11988 public static final int DUMP_SHARED_USERS = 1 << 5; 11989 11990 public static final int DUMP_MESSAGES = 1 << 6; 11991 11992 public static final int DUMP_PROVIDERS = 1 << 7; 11993 11994 public static final int DUMP_VERIFIERS = 1 << 8; 11995 11996 public static final int DUMP_PREFERRED = 1 << 9; 11997 11998 public static final int DUMP_PREFERRED_XML = 1 << 10; 11999 12000 public static final int DUMP_KEYSETS = 1 << 11; 12001 12002 public static final int DUMP_VERSION = 1 << 12; 12003 12004 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12005 12006 private int mTypes; 12007 12008 private int mOptions; 12009 12010 private boolean mTitlePrinted; 12011 12012 private SharedUserSetting mSharedUser; 12013 12014 public boolean isDumping(int type) { 12015 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12016 return true; 12017 } 12018 12019 return (mTypes & type) != 0; 12020 } 12021 12022 public void setDump(int type) { 12023 mTypes |= type; 12024 } 12025 12026 public boolean isOptionEnabled(int option) { 12027 return (mOptions & option) != 0; 12028 } 12029 12030 public void setOptionEnabled(int option) { 12031 mOptions |= option; 12032 } 12033 12034 public boolean onTitlePrinted() { 12035 final boolean printed = mTitlePrinted; 12036 mTitlePrinted = true; 12037 return printed; 12038 } 12039 12040 public boolean getTitlePrinted() { 12041 return mTitlePrinted; 12042 } 12043 12044 public void setTitlePrinted(boolean enabled) { 12045 mTitlePrinted = enabled; 12046 } 12047 12048 public SharedUserSetting getSharedUser() { 12049 return mSharedUser; 12050 } 12051 12052 public void setSharedUser(SharedUserSetting user) { 12053 mSharedUser = user; 12054 } 12055 } 12056 12057 @Override 12058 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12059 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12060 != PackageManager.PERMISSION_GRANTED) { 12061 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12062 + Binder.getCallingPid() 12063 + ", uid=" + Binder.getCallingUid() 12064 + " without permission " 12065 + android.Manifest.permission.DUMP); 12066 return; 12067 } 12068 12069 DumpState dumpState = new DumpState(); 12070 boolean fullPreferred = false; 12071 boolean checkin = false; 12072 12073 String packageName = null; 12074 12075 int opti = 0; 12076 while (opti < args.length) { 12077 String opt = args[opti]; 12078 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12079 break; 12080 } 12081 opti++; 12082 if ("-a".equals(opt)) { 12083 // Right now we only know how to print all. 12084 } else if ("-h".equals(opt)) { 12085 pw.println("Package manager dump options:"); 12086 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12087 pw.println(" --checkin: dump for a checkin"); 12088 pw.println(" -f: print details of intent filters"); 12089 pw.println(" -h: print this help"); 12090 pw.println(" cmd may be one of:"); 12091 pw.println(" l[ibraries]: list known shared libraries"); 12092 pw.println(" f[ibraries]: list device features"); 12093 pw.println(" k[eysets]: print known keysets"); 12094 pw.println(" r[esolvers]: dump intent resolvers"); 12095 pw.println(" perm[issions]: dump permissions"); 12096 pw.println(" pref[erred]: print preferred package settings"); 12097 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12098 pw.println(" prov[iders]: dump content providers"); 12099 pw.println(" p[ackages]: dump installed packages"); 12100 pw.println(" s[hared-users]: dump shared user IDs"); 12101 pw.println(" m[essages]: print collected runtime messages"); 12102 pw.println(" v[erifiers]: print package verifier info"); 12103 pw.println(" version: print database version info"); 12104 pw.println(" write: write current settings now"); 12105 pw.println(" <package.name>: info about given package"); 12106 return; 12107 } else if ("--checkin".equals(opt)) { 12108 checkin = true; 12109 } else if ("-f".equals(opt)) { 12110 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12111 } else { 12112 pw.println("Unknown argument: " + opt + "; use -h for help"); 12113 } 12114 } 12115 12116 // Is the caller requesting to dump a particular piece of data? 12117 if (opti < args.length) { 12118 String cmd = args[opti]; 12119 opti++; 12120 // Is this a package name? 12121 if ("android".equals(cmd) || cmd.contains(".")) { 12122 packageName = cmd; 12123 // When dumping a single package, we always dump all of its 12124 // filter information since the amount of data will be reasonable. 12125 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12126 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12127 dumpState.setDump(DumpState.DUMP_LIBS); 12128 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12129 dumpState.setDump(DumpState.DUMP_FEATURES); 12130 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12131 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12132 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12133 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12134 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12135 dumpState.setDump(DumpState.DUMP_PREFERRED); 12136 } else if ("preferred-xml".equals(cmd)) { 12137 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12138 if (opti < args.length && "--full".equals(args[opti])) { 12139 fullPreferred = true; 12140 opti++; 12141 } 12142 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12143 dumpState.setDump(DumpState.DUMP_PACKAGES); 12144 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12145 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12146 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12147 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12148 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12149 dumpState.setDump(DumpState.DUMP_MESSAGES); 12150 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12151 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12152 } else if ("version".equals(cmd)) { 12153 dumpState.setDump(DumpState.DUMP_VERSION); 12154 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12155 dumpState.setDump(DumpState.DUMP_KEYSETS); 12156 } else if ("write".equals(cmd)) { 12157 synchronized (mPackages) { 12158 mSettings.writeLPr(); 12159 pw.println("Settings written."); 12160 return; 12161 } 12162 } 12163 } 12164 12165 if (checkin) { 12166 pw.println("vers,1"); 12167 } 12168 12169 // reader 12170 synchronized (mPackages) { 12171 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12172 if (!checkin) { 12173 if (dumpState.onTitlePrinted()) 12174 pw.println(); 12175 pw.println("Database versions:"); 12176 pw.print(" SDK Version:"); 12177 pw.print(" internal="); 12178 pw.print(mSettings.mInternalSdkPlatform); 12179 pw.print(" external="); 12180 pw.println(mSettings.mExternalSdkPlatform); 12181 pw.print(" DB Version:"); 12182 pw.print(" internal="); 12183 pw.print(mSettings.mInternalDatabaseVersion); 12184 pw.print(" external="); 12185 pw.println(mSettings.mExternalDatabaseVersion); 12186 } 12187 } 12188 12189 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12190 if (!checkin) { 12191 if (dumpState.onTitlePrinted()) 12192 pw.println(); 12193 pw.println("Verifiers:"); 12194 pw.print(" Required: "); 12195 pw.print(mRequiredVerifierPackage); 12196 pw.print(" (uid="); 12197 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12198 pw.println(")"); 12199 } else if (mRequiredVerifierPackage != null) { 12200 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12201 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12202 } 12203 } 12204 12205 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12206 boolean printedHeader = false; 12207 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12208 while (it.hasNext()) { 12209 String name = it.next(); 12210 SharedLibraryEntry ent = mSharedLibraries.get(name); 12211 if (!checkin) { 12212 if (!printedHeader) { 12213 if (dumpState.onTitlePrinted()) 12214 pw.println(); 12215 pw.println("Libraries:"); 12216 printedHeader = true; 12217 } 12218 pw.print(" "); 12219 } else { 12220 pw.print("lib,"); 12221 } 12222 pw.print(name); 12223 if (!checkin) { 12224 pw.print(" -> "); 12225 } 12226 if (ent.path != null) { 12227 if (!checkin) { 12228 pw.print("(jar) "); 12229 pw.print(ent.path); 12230 } else { 12231 pw.print(",jar,"); 12232 pw.print(ent.path); 12233 } 12234 } else { 12235 if (!checkin) { 12236 pw.print("(apk) "); 12237 pw.print(ent.apk); 12238 } else { 12239 pw.print(",apk,"); 12240 pw.print(ent.apk); 12241 } 12242 } 12243 pw.println(); 12244 } 12245 } 12246 12247 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12248 if (dumpState.onTitlePrinted()) 12249 pw.println(); 12250 if (!checkin) { 12251 pw.println("Features:"); 12252 } 12253 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12254 while (it.hasNext()) { 12255 String name = it.next(); 12256 if (!checkin) { 12257 pw.print(" "); 12258 } else { 12259 pw.print("feat,"); 12260 } 12261 pw.println(name); 12262 } 12263 } 12264 12265 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12266 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12267 : "Activity Resolver Table:", " ", packageName, 12268 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12269 dumpState.setTitlePrinted(true); 12270 } 12271 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12272 : "Receiver Resolver Table:", " ", packageName, 12273 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12274 dumpState.setTitlePrinted(true); 12275 } 12276 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12277 : "Service Resolver Table:", " ", packageName, 12278 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12279 dumpState.setTitlePrinted(true); 12280 } 12281 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12282 : "Provider Resolver Table:", " ", packageName, 12283 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12284 dumpState.setTitlePrinted(true); 12285 } 12286 } 12287 12288 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12289 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12290 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12291 int user = mSettings.mPreferredActivities.keyAt(i); 12292 if (pir.dump(pw, 12293 dumpState.getTitlePrinted() 12294 ? "\nPreferred Activities User " + user + ":" 12295 : "Preferred Activities User " + user + ":", " ", 12296 packageName, true)) { 12297 dumpState.setTitlePrinted(true); 12298 } 12299 } 12300 } 12301 12302 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12303 pw.flush(); 12304 FileOutputStream fout = new FileOutputStream(fd); 12305 BufferedOutputStream str = new BufferedOutputStream(fout); 12306 XmlSerializer serializer = new FastXmlSerializer(); 12307 try { 12308 serializer.setOutput(str, "utf-8"); 12309 serializer.startDocument(null, true); 12310 serializer.setFeature( 12311 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12312 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12313 serializer.endDocument(); 12314 serializer.flush(); 12315 } catch (IllegalArgumentException e) { 12316 pw.println("Failed writing: " + e); 12317 } catch (IllegalStateException e) { 12318 pw.println("Failed writing: " + e); 12319 } catch (IOException e) { 12320 pw.println("Failed writing: " + e); 12321 } 12322 } 12323 12324 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12325 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12326 } 12327 12328 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12329 boolean printedSomething = false; 12330 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12331 if (packageName != null && !packageName.equals(p.info.packageName)) { 12332 continue; 12333 } 12334 if (!printedSomething) { 12335 if (dumpState.onTitlePrinted()) 12336 pw.println(); 12337 pw.println("Registered ContentProviders:"); 12338 printedSomething = true; 12339 } 12340 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12341 pw.print(" "); pw.println(p.toString()); 12342 } 12343 printedSomething = false; 12344 for (Map.Entry<String, PackageParser.Provider> entry : 12345 mProvidersByAuthority.entrySet()) { 12346 PackageParser.Provider p = entry.getValue(); 12347 if (packageName != null && !packageName.equals(p.info.packageName)) { 12348 continue; 12349 } 12350 if (!printedSomething) { 12351 if (dumpState.onTitlePrinted()) 12352 pw.println(); 12353 pw.println("ContentProvider Authorities:"); 12354 printedSomething = true; 12355 } 12356 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12357 pw.print(" "); pw.println(p.toString()); 12358 if (p.info != null && p.info.applicationInfo != null) { 12359 final String appInfo = p.info.applicationInfo.toString(); 12360 pw.print(" applicationInfo="); pw.println(appInfo); 12361 } 12362 } 12363 } 12364 12365 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12366 mSettings.mKeySetManagerService.dump(pw, packageName, dumpState); 12367 } 12368 12369 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12370 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12371 } 12372 12373 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12374 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12375 } 12376 12377 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12378 if (dumpState.onTitlePrinted()) 12379 pw.println(); 12380 mSettings.dumpReadMessagesLPr(pw, dumpState); 12381 12382 pw.println(); 12383 pw.println("Package warning messages:"); 12384 final File fname = getSettingsProblemFile(); 12385 FileInputStream in = null; 12386 try { 12387 in = new FileInputStream(fname); 12388 final int avail = in.available(); 12389 final byte[] data = new byte[avail]; 12390 in.read(data); 12391 pw.print(new String(data)); 12392 } catch (FileNotFoundException e) { 12393 } catch (IOException e) { 12394 } finally { 12395 if (in != null) { 12396 try { 12397 in.close(); 12398 } catch (IOException e) { 12399 } 12400 } 12401 } 12402 } 12403 } 12404 } 12405 12406 // ------- apps on sdcard specific code ------- 12407 static final boolean DEBUG_SD_INSTALL = false; 12408 12409 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12410 12411 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12412 12413 private boolean mMediaMounted = false; 12414 12415 private String getEncryptKey() { 12416 try { 12417 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12418 SD_ENCRYPTION_KEYSTORE_NAME); 12419 if (sdEncKey == null) { 12420 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12421 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12422 if (sdEncKey == null) { 12423 Slog.e(TAG, "Failed to create encryption keys"); 12424 return null; 12425 } 12426 } 12427 return sdEncKey; 12428 } catch (NoSuchAlgorithmException nsae) { 12429 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12430 return null; 12431 } catch (IOException ioe) { 12432 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12433 return null; 12434 } 12435 12436 } 12437 12438 /* package */static String getTempContainerId() { 12439 int tmpIdx = 1; 12440 String list[] = PackageHelper.getSecureContainerList(); 12441 if (list != null) { 12442 for (final String name : list) { 12443 // Ignore null and non-temporary container entries 12444 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12445 continue; 12446 } 12447 12448 String subStr = name.substring(mTempContainerPrefix.length()); 12449 try { 12450 int cid = Integer.parseInt(subStr); 12451 if (cid >= tmpIdx) { 12452 tmpIdx = cid + 1; 12453 } 12454 } catch (NumberFormatException e) { 12455 } 12456 } 12457 } 12458 return mTempContainerPrefix + tmpIdx; 12459 } 12460 12461 /* 12462 * Update media status on PackageManager. 12463 */ 12464 @Override 12465 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12466 int callingUid = Binder.getCallingUid(); 12467 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12468 throw new SecurityException("Media status can only be updated by the system"); 12469 } 12470 // reader; this apparently protects mMediaMounted, but should probably 12471 // be a different lock in that case. 12472 synchronized (mPackages) { 12473 Log.i(TAG, "Updating external media status from " 12474 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12475 + (mediaStatus ? "mounted" : "unmounted")); 12476 if (DEBUG_SD_INSTALL) 12477 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12478 + ", mMediaMounted=" + mMediaMounted); 12479 if (mediaStatus == mMediaMounted) { 12480 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12481 : 0, -1); 12482 mHandler.sendMessage(msg); 12483 return; 12484 } 12485 mMediaMounted = mediaStatus; 12486 } 12487 // Queue up an async operation since the package installation may take a 12488 // little while. 12489 mHandler.post(new Runnable() { 12490 public void run() { 12491 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12492 } 12493 }); 12494 } 12495 12496 /** 12497 * Called by MountService when the initial ASECs to scan are available. 12498 * Should block until all the ASEC containers are finished being scanned. 12499 */ 12500 public void scanAvailableAsecs() { 12501 updateExternalMediaStatusInner(true, false, false); 12502 if (mShouldRestoreconData) { 12503 SELinuxMMAC.setRestoreconDone(); 12504 mShouldRestoreconData = false; 12505 } 12506 } 12507 12508 /* 12509 * Collect information of applications on external media, map them against 12510 * existing containers and update information based on current mount status. 12511 * Please note that we always have to report status if reportStatus has been 12512 * set to true especially when unloading packages. 12513 */ 12514 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12515 boolean externalStorage) { 12516 // Collection of uids 12517 int uidArr[] = null; 12518 // Collection of stale containers 12519 HashSet<String> removeCids = new HashSet<String>(); 12520 // Collection of packages on external media with valid containers. 12521 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12522 // Get list of secure containers. 12523 final String list[] = PackageHelper.getSecureContainerList(); 12524 if (list == null || list.length == 0) { 12525 Log.i(TAG, "No secure containers on sdcard"); 12526 } else { 12527 // Process list of secure containers and categorize them 12528 // as active or stale based on their package internal state. 12529 int uidList[] = new int[list.length]; 12530 int num = 0; 12531 // reader 12532 synchronized (mPackages) { 12533 for (String cid : list) { 12534 if (DEBUG_SD_INSTALL) 12535 Log.i(TAG, "Processing container " + cid); 12536 String pkgName = getAsecPackageName(cid); 12537 if (pkgName == null) { 12538 if (DEBUG_SD_INSTALL) 12539 Log.i(TAG, "Container : " + cid + " stale"); 12540 removeCids.add(cid); 12541 continue; 12542 } 12543 if (DEBUG_SD_INSTALL) 12544 Log.i(TAG, "Looking for pkg : " + pkgName); 12545 12546 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12547 if (ps == null) { 12548 Log.i(TAG, "Deleting container with no matching settings " + cid); 12549 removeCids.add(cid); 12550 continue; 12551 } 12552 12553 /* 12554 * Skip packages that are not external if we're unmounting 12555 * external storage. 12556 */ 12557 if (externalStorage && !isMounted && !isExternal(ps)) { 12558 continue; 12559 } 12560 12561 final AsecInstallArgs args = new AsecInstallArgs(cid, 12562 getAppInstructionSetFromSettings(ps), 12563 isForwardLocked(ps)); 12564 // The package status is changed only if the code path 12565 // matches between settings and the container id. 12566 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12567 if (DEBUG_SD_INSTALL) { 12568 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12569 + " at code path: " + ps.codePathString); 12570 } 12571 12572 // We do have a valid package installed on sdcard 12573 processCids.put(args, ps.codePathString); 12574 final int uid = ps.appId; 12575 if (uid != -1) { 12576 uidList[num++] = uid; 12577 } 12578 } else { 12579 Log.i(TAG, "Deleting stale container for " + cid); 12580 removeCids.add(cid); 12581 } 12582 } 12583 } 12584 12585 if (num > 0) { 12586 // Sort uid list 12587 Arrays.sort(uidList, 0, num); 12588 // Throw away duplicates 12589 uidArr = new int[num]; 12590 uidArr[0] = uidList[0]; 12591 int di = 0; 12592 for (int i = 1; i < num; i++) { 12593 if (uidList[i - 1] != uidList[i]) { 12594 uidArr[di++] = uidList[i]; 12595 } 12596 } 12597 } 12598 } 12599 // Process packages with valid entries. 12600 if (isMounted) { 12601 if (DEBUG_SD_INSTALL) 12602 Log.i(TAG, "Loading packages"); 12603 loadMediaPackages(processCids, uidArr, removeCids); 12604 startCleaningPackages(); 12605 } else { 12606 if (DEBUG_SD_INSTALL) 12607 Log.i(TAG, "Unloading packages"); 12608 unloadMediaPackages(processCids, uidArr, reportStatus); 12609 } 12610 } 12611 12612 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12613 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12614 int size = pkgList.size(); 12615 if (size > 0) { 12616 // Send broadcasts here 12617 Bundle extras = new Bundle(); 12618 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12619 .toArray(new String[size])); 12620 if (uidArr != null) { 12621 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12622 } 12623 if (replacing) { 12624 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12625 } 12626 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12627 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12628 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12629 } 12630 } 12631 12632 /* 12633 * Look at potentially valid container ids from processCids If package 12634 * information doesn't match the one on record or package scanning fails, 12635 * the cid is added to list of removeCids. We currently don't delete stale 12636 * containers. 12637 */ 12638 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12639 HashSet<String> removeCids) { 12640 ArrayList<String> pkgList = new ArrayList<String>(); 12641 Set<AsecInstallArgs> keys = processCids.keySet(); 12642 boolean doGc = false; 12643 for (AsecInstallArgs args : keys) { 12644 String codePath = processCids.get(args); 12645 if (DEBUG_SD_INSTALL) 12646 Log.i(TAG, "Loading container : " + args.cid); 12647 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12648 try { 12649 // Make sure there are no container errors first. 12650 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12651 Slog.e(TAG, "Failed to mount cid : " + args.cid 12652 + " when installing from sdcard"); 12653 continue; 12654 } 12655 // Check code path here. 12656 if (codePath == null || !codePath.equals(args.getCodePath())) { 12657 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12658 + " does not match one in settings " + codePath); 12659 continue; 12660 } 12661 // Parse package 12662 int parseFlags = mDefParseFlags; 12663 if (args.isExternal()) { 12664 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12665 } 12666 if (args.isFwdLocked()) { 12667 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12668 } 12669 12670 doGc = true; 12671 synchronized (mInstallLock) { 12672 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 12673 0, 0, null, null); 12674 // Scan the package 12675 if (pkg != null) { 12676 /* 12677 * TODO why is the lock being held? doPostInstall is 12678 * called in other places without the lock. This needs 12679 * to be straightened out. 12680 */ 12681 // writer 12682 synchronized (mPackages) { 12683 retCode = PackageManager.INSTALL_SUCCEEDED; 12684 pkgList.add(pkg.packageName); 12685 // Post process args 12686 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12687 pkg.applicationInfo.uid); 12688 } 12689 } else { 12690 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12691 } 12692 } 12693 12694 } finally { 12695 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12696 // Don't destroy container here. Wait till gc clears things 12697 // up. 12698 removeCids.add(args.cid); 12699 } 12700 } 12701 } 12702 // writer 12703 synchronized (mPackages) { 12704 // If the platform SDK has changed since the last time we booted, 12705 // we need to re-grant app permission to catch any new ones that 12706 // appear. This is really a hack, and means that apps can in some 12707 // cases get permissions that the user didn't initially explicitly 12708 // allow... it would be nice to have some better way to handle 12709 // this situation. 12710 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12711 if (regrantPermissions) 12712 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12713 + mSdkVersion + "; regranting permissions for external storage"); 12714 mSettings.mExternalSdkPlatform = mSdkVersion; 12715 12716 // Make sure group IDs have been assigned, and any permission 12717 // changes in other apps are accounted for 12718 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12719 | (regrantPermissions 12720 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12721 : 0)); 12722 12723 mSettings.updateExternalDatabaseVersion(); 12724 12725 // can downgrade to reader 12726 // Persist settings 12727 mSettings.writeLPr(); 12728 } 12729 // Send a broadcast to let everyone know we are done processing 12730 if (pkgList.size() > 0) { 12731 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12732 } 12733 // Force gc to avoid any stale parser references that we might have. 12734 if (doGc) { 12735 Runtime.getRuntime().gc(); 12736 } 12737 // List stale containers and destroy stale temporary containers. 12738 if (removeCids != null) { 12739 for (String cid : removeCids) { 12740 if (cid.startsWith(mTempContainerPrefix)) { 12741 Log.i(TAG, "Destroying stale temporary container " + cid); 12742 PackageHelper.destroySdDir(cid); 12743 } else { 12744 Log.w(TAG, "Container " + cid + " is stale"); 12745 } 12746 } 12747 } 12748 } 12749 12750 /* 12751 * Utility method to unload a list of specified containers 12752 */ 12753 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12754 // Just unmount all valid containers. 12755 for (AsecInstallArgs arg : cidArgs) { 12756 synchronized (mInstallLock) { 12757 arg.doPostDeleteLI(false); 12758 } 12759 } 12760 } 12761 12762 /* 12763 * Unload packages mounted on external media. This involves deleting package 12764 * data from internal structures, sending broadcasts about diabled packages, 12765 * gc'ing to free up references, unmounting all secure containers 12766 * corresponding to packages on external media, and posting a 12767 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12768 * that we always have to post this message if status has been requested no 12769 * matter what. 12770 */ 12771 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12772 final boolean reportStatus) { 12773 if (DEBUG_SD_INSTALL) 12774 Log.i(TAG, "unloading media packages"); 12775 ArrayList<String> pkgList = new ArrayList<String>(); 12776 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12777 final Set<AsecInstallArgs> keys = processCids.keySet(); 12778 for (AsecInstallArgs args : keys) { 12779 String pkgName = args.getPackageName(); 12780 if (DEBUG_SD_INSTALL) 12781 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12782 // Delete package internally 12783 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12784 synchronized (mInstallLock) { 12785 boolean res = deletePackageLI(pkgName, null, false, null, null, 12786 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12787 if (res) { 12788 pkgList.add(pkgName); 12789 } else { 12790 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12791 failedList.add(args); 12792 } 12793 } 12794 } 12795 12796 // reader 12797 synchronized (mPackages) { 12798 // We didn't update the settings after removing each package; 12799 // write them now for all packages. 12800 mSettings.writeLPr(); 12801 } 12802 12803 // We have to absolutely send UPDATED_MEDIA_STATUS only 12804 // after confirming that all the receivers processed the ordered 12805 // broadcast when packages get disabled, force a gc to clean things up. 12806 // and unload all the containers. 12807 if (pkgList.size() > 0) { 12808 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12809 new IIntentReceiver.Stub() { 12810 public void performReceive(Intent intent, int resultCode, String data, 12811 Bundle extras, boolean ordered, boolean sticky, 12812 int sendingUser) throws RemoteException { 12813 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12814 reportStatus ? 1 : 0, 1, keys); 12815 mHandler.sendMessage(msg); 12816 } 12817 }); 12818 } else { 12819 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12820 keys); 12821 mHandler.sendMessage(msg); 12822 } 12823 } 12824 12825 /** Binder call */ 12826 @Override 12827 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12828 final int flags) { 12829 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12830 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12831 int returnCode = PackageManager.MOVE_SUCCEEDED; 12832 int currFlags = 0; 12833 int newFlags = 0; 12834 // reader 12835 synchronized (mPackages) { 12836 PackageParser.Package pkg = mPackages.get(packageName); 12837 if (pkg == null) { 12838 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12839 } else { 12840 // Disable moving fwd locked apps and system packages 12841 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12842 Slog.w(TAG, "Cannot move system application"); 12843 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12844 } else if (pkg.mOperationPending) { 12845 Slog.w(TAG, "Attempt to move package which has pending operations"); 12846 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12847 } else { 12848 // Find install location first 12849 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12850 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12851 Slog.w(TAG, "Ambigous flags specified for move location."); 12852 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12853 } else { 12854 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12855 : PackageManager.INSTALL_INTERNAL; 12856 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12857 : PackageManager.INSTALL_INTERNAL; 12858 12859 if (newFlags == currFlags) { 12860 Slog.w(TAG, "No move required. Trying to move to same location"); 12861 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12862 } else { 12863 if (isForwardLocked(pkg)) { 12864 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12865 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12866 } 12867 } 12868 } 12869 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12870 pkg.mOperationPending = true; 12871 } 12872 } 12873 } 12874 12875 /* 12876 * TODO this next block probably shouldn't be inside the lock. We 12877 * can't guarantee these won't change after this is fired off 12878 * anyway. 12879 */ 12880 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12881 processPendingMove(new MoveParams(null, observer, 0, packageName, null, 12882 null, -1, user), 12883 returnCode); 12884 } else { 12885 Message msg = mHandler.obtainMessage(INIT_COPY); 12886 final String instructionSet = getAppInstructionSet(pkg.applicationInfo); 12887 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 12888 pkg.applicationInfo.sourceDir, pkg.applicationInfo.publicSourceDir, 12889 pkg.applicationInfo.nativeLibraryDir, instructionSet); 12890 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12891 pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user); 12892 msg.obj = mp; 12893 mHandler.sendMessage(msg); 12894 } 12895 } 12896 } 12897 12898 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12899 // Queue up an async operation since the package deletion may take a 12900 // little while. 12901 mHandler.post(new Runnable() { 12902 public void run() { 12903 // TODO fix this; this does nothing. 12904 mHandler.removeCallbacks(this); 12905 int returnCode = currentStatus; 12906 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12907 int uidArr[] = null; 12908 ArrayList<String> pkgList = null; 12909 synchronized (mPackages) { 12910 PackageParser.Package pkg = mPackages.get(mp.packageName); 12911 if (pkg == null) { 12912 Slog.w(TAG, " Package " + mp.packageName 12913 + " doesn't exist. Aborting move"); 12914 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12915 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 12916 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12917 + mp.srcArgs.getCodePath() + " to " 12918 + pkg.applicationInfo.sourceDir 12919 + " Aborting move and returning error"); 12920 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12921 } else { 12922 uidArr = new int[] { 12923 pkg.applicationInfo.uid 12924 }; 12925 pkgList = new ArrayList<String>(); 12926 pkgList.add(mp.packageName); 12927 } 12928 } 12929 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12930 // Send resources unavailable broadcast 12931 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12932 // Update package code and resource paths 12933 synchronized (mInstallLock) { 12934 synchronized (mPackages) { 12935 PackageParser.Package pkg = mPackages.get(mp.packageName); 12936 // Recheck for package again. 12937 if (pkg == null) { 12938 Slog.w(TAG, " Package " + mp.packageName 12939 + " doesn't exist. Aborting move"); 12940 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12941 } else if (!mp.srcArgs.getCodePath().equals( 12942 pkg.applicationInfo.sourceDir)) { 12943 Slog.w(TAG, "Package " + mp.packageName 12944 + " code path changed from " + mp.srcArgs.getCodePath() 12945 + " to " + pkg.applicationInfo.sourceDir 12946 + " Aborting move and returning error"); 12947 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12948 } else { 12949 final String oldCodePath = pkg.codePath; 12950 final String newCodePath = mp.targetArgs.getCodePath(); 12951 final String newResPath = mp.targetArgs.getResourcePath(); 12952 final String newNativePath = mp.targetArgs 12953 .getNativeLibraryPath(); 12954 12955 final File newNativeDir = new File(newNativePath); 12956 12957 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12958 ApkHandle handle = null; 12959 try { 12960 handle = ApkHandle.create(newCodePath); 12961 final int abi = NativeLibraryHelper.findSupportedAbi( 12962 handle, Build.SUPPORTED_ABIS); 12963 if (abi >= 0) { 12964 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12965 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12966 } 12967 } catch (IOException ioe) { 12968 Slog.w(TAG, "Unable to extract native libs for package :" 12969 + mp.packageName, ioe); 12970 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12971 } finally { 12972 IoUtils.closeQuietly(handle); 12973 } 12974 } 12975 final int[] users = sUserManager.getUserIds(); 12976 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12977 for (int user : users) { 12978 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 12979 newNativePath, user) < 0) { 12980 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12981 } 12982 } 12983 } 12984 12985 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12986 pkg.codePath = newCodePath; 12987 pkg.baseCodePath = newCodePath; 12988 // Move dex files around 12989 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 12990 // Moving of dex files failed. Set 12991 // error code and abort move. 12992 pkg.codePath = oldCodePath; 12993 pkg.baseCodePath = oldCodePath; 12994 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12995 } 12996 } 12997 12998 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12999 pkg.applicationInfo.sourceDir = newCodePath; 13000 pkg.applicationInfo.publicSourceDir = newResPath; 13001 pkg.applicationInfo.nativeLibraryDir = newNativePath; 13002 PackageSetting ps = (PackageSetting) pkg.mExtras; 13003 ps.codePath = new File(pkg.applicationInfo.sourceDir); 13004 ps.codePathString = ps.codePath.getPath(); 13005 ps.resourcePath = new File( 13006 pkg.applicationInfo.publicSourceDir); 13007 ps.resourcePathString = ps.resourcePath.getPath(); 13008 ps.nativeLibraryPathString = newNativePath; 13009 // Set the application info flag 13010 // correctly. 13011 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13012 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13013 } else { 13014 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13015 } 13016 ps.setFlags(pkg.applicationInfo.flags); 13017 mAppDirs.remove(oldCodePath); 13018 mAppDirs.put(newCodePath, pkg); 13019 // Persist settings 13020 mSettings.writeLPr(); 13021 } 13022 } 13023 } 13024 } 13025 // Send resources available broadcast 13026 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13027 } 13028 } 13029 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13030 // Clean up failed installation 13031 if (mp.targetArgs != null) { 13032 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13033 -1); 13034 } 13035 } else { 13036 // Force a gc to clear things up. 13037 Runtime.getRuntime().gc(); 13038 // Delete older code 13039 synchronized (mInstallLock) { 13040 mp.srcArgs.doPostDeleteLI(true); 13041 } 13042 } 13043 13044 // Allow more operations on this file if we didn't fail because 13045 // an operation was already pending for this package. 13046 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13047 synchronized (mPackages) { 13048 PackageParser.Package pkg = mPackages.get(mp.packageName); 13049 if (pkg != null) { 13050 pkg.mOperationPending = false; 13051 } 13052 } 13053 } 13054 13055 IPackageMoveObserver observer = mp.observer; 13056 if (observer != null) { 13057 try { 13058 observer.packageMoved(mp.packageName, returnCode); 13059 } catch (RemoteException e) { 13060 Log.i(TAG, "Observer no longer exists."); 13061 } 13062 } 13063 } 13064 }); 13065 } 13066 13067 @Override 13068 public boolean setInstallLocation(int loc) { 13069 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13070 null); 13071 if (getInstallLocation() == loc) { 13072 return true; 13073 } 13074 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13075 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13076 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13077 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13078 return true; 13079 } 13080 return false; 13081 } 13082 13083 @Override 13084 public int getInstallLocation() { 13085 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13086 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13087 PackageHelper.APP_INSTALL_AUTO); 13088 } 13089 13090 /** Called by UserManagerService */ 13091 void cleanUpUserLILPw(int userHandle) { 13092 mDirtyUsers.remove(userHandle); 13093 mSettings.removeUserLPr(userHandle); 13094 mPendingBroadcasts.remove(userHandle); 13095 if (mInstaller != null) { 13096 // Technically, we shouldn't be doing this with the package lock 13097 // held. However, this is very rare, and there is already so much 13098 // other disk I/O going on, that we'll let it slide for now. 13099 mInstaller.removeUserDataDirs(userHandle); 13100 } 13101 mUserNeedsBadging.delete(userHandle); 13102 } 13103 13104 /** Called by UserManagerService */ 13105 void createNewUserLILPw(int userHandle, File path) { 13106 if (mInstaller != null) { 13107 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13108 } 13109 } 13110 13111 @Override 13112 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13113 mContext.enforceCallingOrSelfPermission( 13114 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13115 "Only package verification agents can read the verifier device identity"); 13116 13117 synchronized (mPackages) { 13118 return mSettings.getVerifierDeviceIdentityLPw(); 13119 } 13120 } 13121 13122 @Override 13123 public void setPermissionEnforced(String permission, boolean enforced) { 13124 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13125 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13126 synchronized (mPackages) { 13127 if (mSettings.mReadExternalStorageEnforced == null 13128 || mSettings.mReadExternalStorageEnforced != enforced) { 13129 mSettings.mReadExternalStorageEnforced = enforced; 13130 mSettings.writeLPr(); 13131 } 13132 } 13133 // kill any non-foreground processes so we restart them and 13134 // grant/revoke the GID. 13135 final IActivityManager am = ActivityManagerNative.getDefault(); 13136 if (am != null) { 13137 final long token = Binder.clearCallingIdentity(); 13138 try { 13139 am.killProcessesBelowForeground("setPermissionEnforcement"); 13140 } catch (RemoteException e) { 13141 } finally { 13142 Binder.restoreCallingIdentity(token); 13143 } 13144 } 13145 } else { 13146 throw new IllegalArgumentException("No selective enforcement for " + permission); 13147 } 13148 } 13149 13150 @Override 13151 @Deprecated 13152 public boolean isPermissionEnforced(String permission) { 13153 return true; 13154 } 13155 13156 @Override 13157 public boolean isStorageLow() { 13158 final long token = Binder.clearCallingIdentity(); 13159 try { 13160 final DeviceStorageMonitorInternal 13161 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13162 if (dsm != null) { 13163 return dsm.isMemoryLow(); 13164 } else { 13165 return false; 13166 } 13167 } finally { 13168 Binder.restoreCallingIdentity(token); 13169 } 13170 } 13171 13172 @Override 13173 public IPackageInstaller getPackageInstaller() { 13174 return mInstallerService; 13175 } 13176 13177 private boolean userNeedsBadging(int userId) { 13178 int index = mUserNeedsBadging.indexOfKey(userId); 13179 if (index < 0) { 13180 final UserInfo userInfo; 13181 final long token = Binder.clearCallingIdentity(); 13182 try { 13183 userInfo = sUserManager.getUserInfo(userId); 13184 } finally { 13185 Binder.restoreCallingIdentity(token); 13186 } 13187 final boolean b; 13188 if (userInfo != null && userInfo.isManagedProfile()) { 13189 b = true; 13190 } else { 13191 b = false; 13192 } 13193 mUserNeedsBadging.put(userId, b); 13194 return b; 13195 } 13196 return mUserNeedsBadging.valueAt(index); 13197 } 13198} 13199