PackageManagerService.java revision 73767b9d607d99b3a027619b5c6b7f1a09b7673d
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.isApkFile; 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.PackageHelper; 46import com.android.internal.util.ArrayUtils; 47import com.android.internal.util.FastPrintWriter; 48import com.android.internal.util.FastXmlSerializer; 49import com.android.internal.util.Preconditions; 50import com.android.internal.util.XmlUtils; 51import com.android.server.EventLogTags; 52import com.android.server.IntentResolver; 53import com.android.server.LocalServices; 54import com.android.server.ServiceThread; 55import com.android.server.SystemConfig; 56import com.android.server.Watchdog; 57import com.android.server.pm.Settings.DatabaseVersion; 58import com.android.server.storage.DeviceStorageMonitorInternal; 59 60import org.xmlpull.v1.XmlPullParser; 61import org.xmlpull.v1.XmlPullParserException; 62import org.xmlpull.v1.XmlSerializer; 63 64import android.app.ActivityManager; 65import android.app.ActivityManagerNative; 66import android.app.IActivityManager; 67import android.app.PackageInstallObserver; 68import android.app.admin.IDevicePolicyManager; 69import android.app.backup.IBackupManager; 70import android.content.BroadcastReceiver; 71import android.content.ComponentName; 72import android.content.Context; 73import android.content.IIntentReceiver; 74import android.content.Intent; 75import android.content.IntentFilter; 76import android.content.IntentSender; 77import android.content.IntentSender.SendIntentException; 78import android.content.ServiceConnection; 79import android.content.pm.ActivityInfo; 80import android.content.pm.ApplicationInfo; 81import android.content.pm.ContainerEncryptionParams; 82import android.content.pm.FeatureInfo; 83import android.content.pm.IPackageDataObserver; 84import android.content.pm.IPackageDeleteObserver; 85import android.content.pm.IPackageInstallObserver; 86import android.content.pm.IPackageInstallObserver2; 87import android.content.pm.IPackageInstaller; 88import android.content.pm.IPackageManager; 89import android.content.pm.IPackageMoveObserver; 90import android.content.pm.IPackageStatsObserver; 91import android.content.pm.InstrumentationInfo; 92import android.content.pm.ManifestDigest; 93import android.content.pm.PackageCleanItem; 94import android.content.pm.PackageInfo; 95import android.content.pm.PackageInfoLite; 96import android.content.pm.PackageInstallerParams; 97import android.content.pm.PackageManager; 98import android.content.pm.PackageParser.ActivityIntentInfo; 99import android.content.pm.PackageParser.PackageParserException; 100import android.content.pm.PackageParser; 101import android.content.pm.PackageStats; 102import android.content.pm.PackageUserState; 103import android.content.pm.ParceledListSlice; 104import android.content.pm.PermissionGroupInfo; 105import android.content.pm.PermissionInfo; 106import android.content.pm.ProviderInfo; 107import android.content.pm.ResolveInfo; 108import android.content.pm.ServiceInfo; 109import android.content.pm.Signature; 110import android.content.pm.UserInfo; 111import android.content.pm.VerificationParams; 112import android.content.pm.VerifierDeviceIdentity; 113import android.content.pm.VerifierInfo; 114import android.content.res.Resources; 115import android.hardware.display.DisplayManager; 116import android.net.Uri; 117import android.os.Binder; 118import android.os.Build; 119import android.os.Bundle; 120import android.os.Environment; 121import android.os.Environment.UserEnvironment; 122import android.os.FileObserver; 123import android.os.FileUtils; 124import android.os.Handler; 125import android.os.IBinder; 126import android.os.Looper; 127import android.os.Message; 128import android.os.Parcel; 129import android.os.ParcelFileDescriptor; 130import android.os.Process; 131import android.os.RemoteException; 132import android.os.SELinux; 133import android.os.ServiceManager; 134import android.os.SystemClock; 135import android.os.SystemProperties; 136import android.os.UserHandle; 137import android.os.UserManager; 138import android.security.KeyStore; 139import android.security.SystemKeyStore; 140import android.system.ErrnoException; 141import android.system.Os; 142import android.system.StructStat; 143import android.text.TextUtils; 144import android.util.ArraySet; 145import android.util.AtomicFile; 146import android.util.DisplayMetrics; 147import android.util.EventLog; 148import android.util.Log; 149import android.util.LogPrinter; 150import android.util.PrintStreamPrinter; 151import android.util.Slog; 152import android.util.SparseArray; 153import android.util.SparseBooleanArray; 154import android.util.Xml; 155import android.view.Display; 156 157import java.io.BufferedInputStream; 158import java.io.BufferedOutputStream; 159import java.io.File; 160import java.io.FileDescriptor; 161import java.io.FileInputStream; 162import java.io.FileNotFoundException; 163import java.io.FileOutputStream; 164import java.io.FileReader; 165import java.io.FilenameFilter; 166import java.io.IOException; 167import java.io.InputStream; 168import java.io.PrintWriter; 169import java.nio.charset.StandardCharsets; 170import java.security.NoSuchAlgorithmException; 171import java.security.PublicKey; 172import java.security.cert.CertificateEncodingException; 173import java.security.cert.CertificateException; 174import java.text.SimpleDateFormat; 175import java.util.ArrayList; 176import java.util.Arrays; 177import java.util.Collection; 178import java.util.Collections; 179import java.util.Comparator; 180import java.util.Date; 181import java.util.HashMap; 182import java.util.HashSet; 183import java.util.Iterator; 184import java.util.List; 185import java.util.Map; 186import java.util.Set; 187import java.util.concurrent.atomic.AtomicBoolean; 188import java.util.concurrent.atomic.AtomicLong; 189 190import dalvik.system.DexFile; 191import dalvik.system.StaleDexCacheError; 192import dalvik.system.VMRuntime; 193 194import libcore.io.IoUtils; 195 196/** 197 * Keep track of all those .apks everywhere. 198 * 199 * This is very central to the platform's security; please run the unit 200 * tests whenever making modifications here: 201 * 202mmm frameworks/base/tests/AndroidTests 203adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 204adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 205 * 206 * {@hide} 207 */ 208public class PackageManagerService extends IPackageManager.Stub { 209 static final String TAG = "PackageManager"; 210 static final boolean DEBUG_SETTINGS = false; 211 static final boolean DEBUG_PREFERRED = false; 212 static final boolean DEBUG_UPGRADE = false; 213 private static final boolean DEBUG_INSTALL = false; 214 private static final boolean DEBUG_REMOVE = false; 215 private static final boolean DEBUG_BROADCASTS = false; 216 private static final boolean DEBUG_SHOW_INFO = false; 217 private static final boolean DEBUG_PACKAGE_INFO = false; 218 private static final boolean DEBUG_INTENT_MATCHING = false; 219 private static final boolean DEBUG_PACKAGE_SCANNING = false; 220 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 221 private static final boolean DEBUG_VERIFY = false; 222 private static final boolean DEBUG_DEXOPT = false; 223 224 private static final int RADIO_UID = Process.PHONE_UID; 225 private static final int LOG_UID = Process.LOG_UID; 226 private static final int NFC_UID = Process.NFC_UID; 227 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 228 private static final int SHELL_UID = Process.SHELL_UID; 229 230 // Cap the size of permission trees that 3rd party apps can define 231 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 232 233 private static final int REMOVE_EVENTS = 234 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 235 private static final int ADD_EVENTS = 236 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 237 238 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 239 // Suffix used during package installation when copying/moving 240 // package apks to install directory. 241 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 242 243 static final int SCAN_MONITOR = 1<<0; 244 static final int SCAN_NO_DEX = 1<<1; 245 static final int SCAN_FORCE_DEX = 1<<2; 246 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 247 static final int SCAN_NEW_INSTALL = 1<<4; 248 static final int SCAN_NO_PATHS = 1<<5; 249 static final int SCAN_UPDATE_TIME = 1<<6; 250 static final int SCAN_DEFER_DEX = 1<<7; 251 static final int SCAN_BOOTING = 1<<8; 252 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 253 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 254 255 static final int REMOVE_CHATTY = 1<<16; 256 257 /** 258 * Timeout (in milliseconds) after which the watchdog should declare that 259 * our handler thread is wedged. The usual default for such things is one 260 * minute but we sometimes do very lengthy I/O operations on this thread, 261 * such as installing multi-gigabyte applications, so ours needs to be longer. 262 */ 263 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 264 265 /** 266 * Whether verification is enabled by default. 267 */ 268 private static final boolean DEFAULT_VERIFY_ENABLE = true; 269 270 /** 271 * The default maximum time to wait for the verification agent to return in 272 * milliseconds. 273 */ 274 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 275 276 /** 277 * The default response for package verification timeout. 278 * 279 * This can be either PackageManager.VERIFICATION_ALLOW or 280 * PackageManager.VERIFICATION_REJECT. 281 */ 282 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 283 284 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 285 286 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 287 DEFAULT_CONTAINER_PACKAGE, 288 "com.android.defcontainer.DefaultContainerService"); 289 290 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 291 292 private static final String LIB_DIR_NAME = "lib"; 293 private static final String LIB64_DIR_NAME = "lib64"; 294 295 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 296 297 static final String mTempContainerPrefix = "smdl2tmp"; 298 299 private static String sPreferredInstructionSet; 300 301 final ServiceThread mHandlerThread; 302 303 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 304 private static final String IDMAP_SUFFIX = "@idmap"; 305 306 final PackageHandler mHandler; 307 308 final int mSdkVersion = Build.VERSION.SDK_INT; 309 310 final Context mContext; 311 final boolean mFactoryTest; 312 final boolean mOnlyCore; 313 final DisplayMetrics mMetrics; 314 final int mDefParseFlags; 315 final String[] mSeparateProcesses; 316 317 // This is where all application persistent data goes. 318 final File mAppDataDir; 319 320 // This is where all application persistent data goes for secondary users. 321 final File mUserAppDataDir; 322 323 /** The location for ASEC container files on internal storage. */ 324 final String mAsecInternalPath; 325 326 // This is the object monitoring the framework dir. 327 final FileObserver mFrameworkInstallObserver; 328 329 // This is the object monitoring the system app dir. 330 final FileObserver mSystemInstallObserver; 331 332 // This is the object monitoring the privileged system app dir. 333 final FileObserver mPrivilegedInstallObserver; 334 335 // This is the object monitoring the vendor app dir. 336 final FileObserver mVendorInstallObserver; 337 338 // This is the object monitoring the vendor overlay package dir. 339 final FileObserver mVendorOverlayInstallObserver; 340 341 // This is the object monitoring the OEM app dir. 342 final FileObserver mOemInstallObserver; 343 344 // This is the object monitoring mAppInstallDir. 345 final FileObserver mAppInstallObserver; 346 347 // This is the object monitoring mDrmAppPrivateInstallDir. 348 final FileObserver mDrmAppInstallObserver; 349 350 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 351 // LOCK HELD. Can be called with mInstallLock held. 352 final Installer mInstaller; 353 354 /** Directory where installed third-party apps stored */ 355 final File mAppInstallDir; 356 357 /** 358 * Directory to which applications installed internally have native 359 * libraries copied. 360 */ 361 private File mAppLibInstallDir; 362 363 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 364 // apps. 365 final File mDrmAppPrivateInstallDir; 366 367 /** Directory where third-party apps are staged before install */ 368 final File mAppStagingDir; 369 370 // ---------------------------------------------------------------- 371 372 // Lock for state used when installing and doing other long running 373 // operations. Methods that must be called with this lock held have 374 // the suffix "LI". 375 final Object mInstallLock = new Object(); 376 377 // These are the directories in the 3rd party applications installed dir 378 // that we have currently loaded packages from. Keys are the application's 379 // installed zip file (absolute codePath), and values are Package. 380 final HashMap<String, PackageParser.Package> mAppDirs = 381 new HashMap<String, PackageParser.Package>(); 382 383 // Information for the parser to write more useful error messages. 384 int mLastScanError; 385 386 // ---------------------------------------------------------------- 387 388 // Keys are String (package name), values are Package. This also serves 389 // as the lock for the global state. Methods that must be called with 390 // this lock held have the prefix "LP". 391 final HashMap<String, PackageParser.Package> mPackages = 392 new HashMap<String, PackageParser.Package>(); 393 394 // Tracks available target package names -> overlay package paths. 395 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 396 new HashMap<String, HashMap<String, PackageParser.Package>>(); 397 398 final Settings mSettings; 399 boolean mRestoredSettings; 400 401 // System configuration read by SystemConfig. 402 final int[] mGlobalGids; 403 final SparseArray<HashSet<String>> mSystemPermissions; 404 final HashMap<String, FeatureInfo> mAvailableFeatures; 405 406 // If mac_permissions.xml was found for seinfo labeling. 407 boolean mFoundPolicyFile; 408 409 // If a recursive restorecon of /data/data/<pkg> is needed. 410 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 411 412 public static final class SharedLibraryEntry { 413 public final String path; 414 public final String apk; 415 416 SharedLibraryEntry(String _path, String _apk) { 417 path = _path; 418 apk = _apk; 419 } 420 } 421 422 // Currently known shared libraries. 423 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 424 new HashMap<String, SharedLibraryEntry>(); 425 426 // All available activities, for your resolving pleasure. 427 final ActivityIntentResolver mActivities = 428 new ActivityIntentResolver(); 429 430 // All available receivers, for your resolving pleasure. 431 final ActivityIntentResolver mReceivers = 432 new ActivityIntentResolver(); 433 434 // All available services, for your resolving pleasure. 435 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 436 437 // All available providers, for your resolving pleasure. 438 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 439 440 // Mapping from provider base names (first directory in content URI codePath) 441 // to the provider information. 442 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 443 new HashMap<String, PackageParser.Provider>(); 444 445 // Mapping from instrumentation class names to info about them. 446 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 447 new HashMap<ComponentName, PackageParser.Instrumentation>(); 448 449 // Mapping from permission names to info about them. 450 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 451 new HashMap<String, PackageParser.PermissionGroup>(); 452 453 // Packages whose data we have transfered into another package, thus 454 // should no longer exist. 455 final HashSet<String> mTransferedPackages = new HashSet<String>(); 456 457 // Broadcast actions that are only available to the system. 458 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 459 460 /** List of packages waiting for verification. */ 461 final SparseArray<PackageVerificationState> mPendingVerification 462 = new SparseArray<PackageVerificationState>(); 463 464 final PackageInstallerService mInstallerService; 465 466 HashSet<PackageParser.Package> mDeferredDexOpt = null; 467 468 // Cache of users who need badging. 469 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 470 471 /** Token for keys in mPendingVerification. */ 472 private int mPendingVerificationToken = 0; 473 474 boolean mSystemReady; 475 boolean mSafeMode; 476 boolean mHasSystemUidErrors; 477 478 ApplicationInfo mAndroidApplication; 479 final ActivityInfo mResolveActivity = new ActivityInfo(); 480 final ResolveInfo mResolveInfo = new ResolveInfo(); 481 ComponentName mResolveComponentName; 482 PackageParser.Package mPlatformPackage; 483 ComponentName mCustomResolverComponentName; 484 485 boolean mResolverReplaced = false; 486 487 // Set of pending broadcasts for aggregating enable/disable of components. 488 static class PendingPackageBroadcasts { 489 // for each user id, a map of <package name -> components within that package> 490 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 491 492 public PendingPackageBroadcasts() { 493 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 494 } 495 496 public ArrayList<String> get(int userId, String packageName) { 497 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 498 return packages.get(packageName); 499 } 500 501 public void put(int userId, String packageName, ArrayList<String> components) { 502 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 503 packages.put(packageName, components); 504 } 505 506 public void remove(int userId, String packageName) { 507 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 508 if (packages != null) { 509 packages.remove(packageName); 510 } 511 } 512 513 public void remove(int userId) { 514 mUidMap.remove(userId); 515 } 516 517 public int userIdCount() { 518 return mUidMap.size(); 519 } 520 521 public int userIdAt(int n) { 522 return mUidMap.keyAt(n); 523 } 524 525 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 526 return mUidMap.get(userId); 527 } 528 529 public int size() { 530 // total number of pending broadcast entries across all userIds 531 int num = 0; 532 for (int i = 0; i< mUidMap.size(); i++) { 533 num += mUidMap.valueAt(i).size(); 534 } 535 return num; 536 } 537 538 public void clear() { 539 mUidMap.clear(); 540 } 541 542 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 543 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 544 if (map == null) { 545 map = new HashMap<String, ArrayList<String>>(); 546 mUidMap.put(userId, map); 547 } 548 return map; 549 } 550 } 551 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 552 553 // Service Connection to remote media container service to copy 554 // package uri's from external media onto secure containers 555 // or internal storage. 556 private IMediaContainerService mContainerService = null; 557 558 static final int SEND_PENDING_BROADCAST = 1; 559 static final int MCS_BOUND = 3; 560 static final int END_COPY = 4; 561 static final int INIT_COPY = 5; 562 static final int MCS_UNBIND = 6; 563 static final int START_CLEANING_PACKAGE = 7; 564 static final int FIND_INSTALL_LOC = 8; 565 static final int POST_INSTALL = 9; 566 static final int MCS_RECONNECT = 10; 567 static final int MCS_GIVE_UP = 11; 568 static final int UPDATED_MEDIA_STATUS = 12; 569 static final int WRITE_SETTINGS = 13; 570 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 571 static final int PACKAGE_VERIFIED = 15; 572 static final int CHECK_PENDING_VERIFICATION = 16; 573 574 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 575 576 // Delay time in millisecs 577 static final int BROADCAST_DELAY = 10 * 1000; 578 579 static UserManagerService sUserManager; 580 581 // Stores a list of users whose package restrictions file needs to be updated 582 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 583 584 final private DefaultContainerConnection mDefContainerConn = 585 new DefaultContainerConnection(); 586 class DefaultContainerConnection implements ServiceConnection { 587 public void onServiceConnected(ComponentName name, IBinder service) { 588 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 589 IMediaContainerService imcs = 590 IMediaContainerService.Stub.asInterface(service); 591 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 592 } 593 594 public void onServiceDisconnected(ComponentName name) { 595 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 596 } 597 }; 598 599 // Recordkeeping of restore-after-install operations that are currently in flight 600 // between the Package Manager and the Backup Manager 601 class PostInstallData { 602 public InstallArgs args; 603 public PackageInstalledInfo res; 604 605 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 606 args = _a; 607 res = _r; 608 } 609 }; 610 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 611 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 612 613 private final String mRequiredVerifierPackage; 614 615 private final PackageUsage mPackageUsage = new PackageUsage(); 616 617 private class PackageUsage { 618 private static final int WRITE_INTERVAL 619 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 620 621 private final Object mFileLock = new Object(); 622 private final AtomicLong mLastWritten = new AtomicLong(0); 623 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 624 625 private boolean mIsHistoricalPackageUsageAvailable = true; 626 627 boolean isHistoricalPackageUsageAvailable() { 628 return mIsHistoricalPackageUsageAvailable; 629 } 630 631 void write(boolean force) { 632 if (force) { 633 writeInternal(); 634 return; 635 } 636 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 637 && !DEBUG_DEXOPT) { 638 return; 639 } 640 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 641 new Thread("PackageUsage_DiskWriter") { 642 @Override 643 public void run() { 644 try { 645 writeInternal(); 646 } finally { 647 mBackgroundWriteRunning.set(false); 648 } 649 } 650 }.start(); 651 } 652 } 653 654 private void writeInternal() { 655 synchronized (mPackages) { 656 synchronized (mFileLock) { 657 AtomicFile file = getFile(); 658 FileOutputStream f = null; 659 try { 660 f = file.startWrite(); 661 BufferedOutputStream out = new BufferedOutputStream(f); 662 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 663 StringBuilder sb = new StringBuilder(); 664 for (PackageParser.Package pkg : mPackages.values()) { 665 if (pkg.mLastPackageUsageTimeInMills == 0) { 666 continue; 667 } 668 sb.setLength(0); 669 sb.append(pkg.packageName); 670 sb.append(' '); 671 sb.append((long)pkg.mLastPackageUsageTimeInMills); 672 sb.append('\n'); 673 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 674 } 675 out.flush(); 676 file.finishWrite(f); 677 } catch (IOException e) { 678 if (f != null) { 679 file.failWrite(f); 680 } 681 Log.e(TAG, "Failed to write package usage times", e); 682 } 683 } 684 } 685 mLastWritten.set(SystemClock.elapsedRealtime()); 686 } 687 688 void readLP() { 689 synchronized (mFileLock) { 690 AtomicFile file = getFile(); 691 BufferedInputStream in = null; 692 try { 693 in = new BufferedInputStream(file.openRead()); 694 StringBuffer sb = new StringBuffer(); 695 while (true) { 696 String packageName = readToken(in, sb, ' '); 697 if (packageName == null) { 698 break; 699 } 700 String timeInMillisString = readToken(in, sb, '\n'); 701 if (timeInMillisString == null) { 702 throw new IOException("Failed to find last usage time for package " 703 + packageName); 704 } 705 PackageParser.Package pkg = mPackages.get(packageName); 706 if (pkg == null) { 707 continue; 708 } 709 long timeInMillis; 710 try { 711 timeInMillis = Long.parseLong(timeInMillisString.toString()); 712 } catch (NumberFormatException e) { 713 throw new IOException("Failed to parse " + timeInMillisString 714 + " as a long.", e); 715 } 716 pkg.mLastPackageUsageTimeInMills = timeInMillis; 717 } 718 } catch (FileNotFoundException expected) { 719 mIsHistoricalPackageUsageAvailable = false; 720 } catch (IOException e) { 721 Log.w(TAG, "Failed to read package usage times", e); 722 } finally { 723 IoUtils.closeQuietly(in); 724 } 725 } 726 mLastWritten.set(SystemClock.elapsedRealtime()); 727 } 728 729 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 730 throws IOException { 731 sb.setLength(0); 732 while (true) { 733 int ch = in.read(); 734 if (ch == -1) { 735 if (sb.length() == 0) { 736 return null; 737 } 738 throw new IOException("Unexpected EOF"); 739 } 740 if (ch == endOfToken) { 741 return sb.toString(); 742 } 743 sb.append((char)ch); 744 } 745 } 746 747 private AtomicFile getFile() { 748 File dataDir = Environment.getDataDirectory(); 749 File systemDir = new File(dataDir, "system"); 750 File fname = new File(systemDir, "package-usage.list"); 751 return new AtomicFile(fname); 752 } 753 } 754 755 class PackageHandler extends Handler { 756 private boolean mBound = false; 757 final ArrayList<HandlerParams> mPendingInstalls = 758 new ArrayList<HandlerParams>(); 759 760 private boolean connectToService() { 761 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 762 " DefaultContainerService"); 763 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 764 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 765 if (mContext.bindServiceAsUser(service, mDefContainerConn, 766 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 767 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 768 mBound = true; 769 return true; 770 } 771 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 772 return false; 773 } 774 775 private void disconnectService() { 776 mContainerService = null; 777 mBound = false; 778 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 779 mContext.unbindService(mDefContainerConn); 780 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 781 } 782 783 PackageHandler(Looper looper) { 784 super(looper); 785 } 786 787 public void handleMessage(Message msg) { 788 try { 789 doHandleMessage(msg); 790 } finally { 791 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 792 } 793 } 794 795 void doHandleMessage(Message msg) { 796 switch (msg.what) { 797 case INIT_COPY: { 798 HandlerParams params = (HandlerParams) msg.obj; 799 int idx = mPendingInstalls.size(); 800 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 801 // If a bind was already initiated we dont really 802 // need to do anything. The pending install 803 // will be processed later on. 804 if (!mBound) { 805 // If this is the only one pending we might 806 // have to bind to the service again. 807 if (!connectToService()) { 808 Slog.e(TAG, "Failed to bind to media container service"); 809 params.serviceError(); 810 return; 811 } else { 812 // Once we bind to the service, the first 813 // pending request will be processed. 814 mPendingInstalls.add(idx, params); 815 } 816 } else { 817 mPendingInstalls.add(idx, params); 818 // Already bound to the service. Just make 819 // sure we trigger off processing the first request. 820 if (idx == 0) { 821 mHandler.sendEmptyMessage(MCS_BOUND); 822 } 823 } 824 break; 825 } 826 case MCS_BOUND: { 827 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 828 if (msg.obj != null) { 829 mContainerService = (IMediaContainerService) msg.obj; 830 } 831 if (mContainerService == null) { 832 // Something seriously wrong. Bail out 833 Slog.e(TAG, "Cannot bind to media container service"); 834 for (HandlerParams params : mPendingInstalls) { 835 // Indicate service bind error 836 params.serviceError(); 837 } 838 mPendingInstalls.clear(); 839 } else if (mPendingInstalls.size() > 0) { 840 HandlerParams params = mPendingInstalls.get(0); 841 if (params != null) { 842 if (params.startCopy()) { 843 // We are done... look for more work or to 844 // go idle. 845 if (DEBUG_SD_INSTALL) Log.i(TAG, 846 "Checking for more work or unbind..."); 847 // Delete pending install 848 if (mPendingInstalls.size() > 0) { 849 mPendingInstalls.remove(0); 850 } 851 if (mPendingInstalls.size() == 0) { 852 if (mBound) { 853 if (DEBUG_SD_INSTALL) Log.i(TAG, 854 "Posting delayed MCS_UNBIND"); 855 removeMessages(MCS_UNBIND); 856 Message ubmsg = obtainMessage(MCS_UNBIND); 857 // Unbind after a little delay, to avoid 858 // continual thrashing. 859 sendMessageDelayed(ubmsg, 10000); 860 } 861 } else { 862 // There are more pending requests in queue. 863 // Just post MCS_BOUND message to trigger processing 864 // of next pending install. 865 if (DEBUG_SD_INSTALL) Log.i(TAG, 866 "Posting MCS_BOUND for next work"); 867 mHandler.sendEmptyMessage(MCS_BOUND); 868 } 869 } 870 } 871 } else { 872 // Should never happen ideally. 873 Slog.w(TAG, "Empty queue"); 874 } 875 break; 876 } 877 case MCS_RECONNECT: { 878 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 879 if (mPendingInstalls.size() > 0) { 880 if (mBound) { 881 disconnectService(); 882 } 883 if (!connectToService()) { 884 Slog.e(TAG, "Failed to bind to media container service"); 885 for (HandlerParams params : mPendingInstalls) { 886 // Indicate service bind error 887 params.serviceError(); 888 } 889 mPendingInstalls.clear(); 890 } 891 } 892 break; 893 } 894 case MCS_UNBIND: { 895 // If there is no actual work left, then time to unbind. 896 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 897 898 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 899 if (mBound) { 900 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 901 902 disconnectService(); 903 } 904 } else if (mPendingInstalls.size() > 0) { 905 // There are more pending requests in queue. 906 // Just post MCS_BOUND message to trigger processing 907 // of next pending install. 908 mHandler.sendEmptyMessage(MCS_BOUND); 909 } 910 911 break; 912 } 913 case MCS_GIVE_UP: { 914 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 915 mPendingInstalls.remove(0); 916 break; 917 } 918 case SEND_PENDING_BROADCAST: { 919 String packages[]; 920 ArrayList<String> components[]; 921 int size = 0; 922 int uids[]; 923 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 924 synchronized (mPackages) { 925 if (mPendingBroadcasts == null) { 926 return; 927 } 928 size = mPendingBroadcasts.size(); 929 if (size <= 0) { 930 // Nothing to be done. Just return 931 return; 932 } 933 packages = new String[size]; 934 components = new ArrayList[size]; 935 uids = new int[size]; 936 int i = 0; // filling out the above arrays 937 938 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 939 int packageUserId = mPendingBroadcasts.userIdAt(n); 940 Iterator<Map.Entry<String, ArrayList<String>>> it 941 = mPendingBroadcasts.packagesForUserId(packageUserId) 942 .entrySet().iterator(); 943 while (it.hasNext() && i < size) { 944 Map.Entry<String, ArrayList<String>> ent = it.next(); 945 packages[i] = ent.getKey(); 946 components[i] = ent.getValue(); 947 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 948 uids[i] = (ps != null) 949 ? UserHandle.getUid(packageUserId, ps.appId) 950 : -1; 951 i++; 952 } 953 } 954 size = i; 955 mPendingBroadcasts.clear(); 956 } 957 // Send broadcasts 958 for (int i = 0; i < size; i++) { 959 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 960 } 961 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 962 break; 963 } 964 case START_CLEANING_PACKAGE: { 965 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 966 final String packageName = (String)msg.obj; 967 final int userId = msg.arg1; 968 final boolean andCode = msg.arg2 != 0; 969 synchronized (mPackages) { 970 if (userId == UserHandle.USER_ALL) { 971 int[] users = sUserManager.getUserIds(); 972 for (int user : users) { 973 mSettings.addPackageToCleanLPw( 974 new PackageCleanItem(user, packageName, andCode)); 975 } 976 } else { 977 mSettings.addPackageToCleanLPw( 978 new PackageCleanItem(userId, packageName, andCode)); 979 } 980 } 981 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 982 startCleaningPackages(); 983 } break; 984 case POST_INSTALL: { 985 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 986 PostInstallData data = mRunningInstalls.get(msg.arg1); 987 mRunningInstalls.delete(msg.arg1); 988 boolean deleteOld = false; 989 990 if (data != null) { 991 InstallArgs args = data.args; 992 PackageInstalledInfo res = data.res; 993 994 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 995 res.removedInfo.sendBroadcast(false, true, false); 996 Bundle extras = new Bundle(1); 997 extras.putInt(Intent.EXTRA_UID, res.uid); 998 // Determine the set of users who are adding this 999 // package for the first time vs. those who are seeing 1000 // an update. 1001 int[] firstUsers; 1002 int[] updateUsers = new int[0]; 1003 if (res.origUsers == null || res.origUsers.length == 0) { 1004 firstUsers = res.newUsers; 1005 } else { 1006 firstUsers = new int[0]; 1007 for (int i=0; i<res.newUsers.length; i++) { 1008 int user = res.newUsers[i]; 1009 boolean isNew = true; 1010 for (int j=0; j<res.origUsers.length; j++) { 1011 if (res.origUsers[j] == user) { 1012 isNew = false; 1013 break; 1014 } 1015 } 1016 if (isNew) { 1017 int[] newFirst = new int[firstUsers.length+1]; 1018 System.arraycopy(firstUsers, 0, newFirst, 0, 1019 firstUsers.length); 1020 newFirst[firstUsers.length] = user; 1021 firstUsers = newFirst; 1022 } else { 1023 int[] newUpdate = new int[updateUsers.length+1]; 1024 System.arraycopy(updateUsers, 0, newUpdate, 0, 1025 updateUsers.length); 1026 newUpdate[updateUsers.length] = user; 1027 updateUsers = newUpdate; 1028 } 1029 } 1030 } 1031 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1032 res.pkg.applicationInfo.packageName, 1033 extras, null, null, firstUsers); 1034 final boolean update = res.removedInfo.removedPackage != null; 1035 if (update) { 1036 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1037 } 1038 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1039 res.pkg.applicationInfo.packageName, 1040 extras, null, null, updateUsers); 1041 if (update) { 1042 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1043 res.pkg.applicationInfo.packageName, 1044 extras, null, null, updateUsers); 1045 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1046 null, null, 1047 res.pkg.applicationInfo.packageName, null, updateUsers); 1048 1049 // treat asec-hosted packages like removable media on upgrade 1050 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1051 if (DEBUG_INSTALL) { 1052 Slog.i(TAG, "upgrading pkg " + res.pkg 1053 + " is ASEC-hosted -> AVAILABLE"); 1054 } 1055 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1056 ArrayList<String> pkgList = new ArrayList<String>(1); 1057 pkgList.add(res.pkg.applicationInfo.packageName); 1058 sendResourcesChangedBroadcast(true, true, 1059 pkgList,uidArray, null); 1060 } 1061 } 1062 if (res.removedInfo.args != null) { 1063 // Remove the replaced package's older resources safely now 1064 deleteOld = true; 1065 } 1066 1067 // Log current value of "unknown sources" setting 1068 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1069 getUnknownSourcesSettings()); 1070 } 1071 // Force a gc to clear up things 1072 Runtime.getRuntime().gc(); 1073 // We delete after a gc for applications on sdcard. 1074 if (deleteOld) { 1075 synchronized (mInstallLock) { 1076 res.removedInfo.args.doPostDeleteLI(true); 1077 } 1078 } 1079 if (args.observer != null) { 1080 try { 1081 args.observer.packageInstalled(res.name, res.returnCode); 1082 } catch (RemoteException e) { 1083 Slog.i(TAG, "Observer no longer exists."); 1084 } 1085 } 1086 if (args.observer2 != null) { 1087 try { 1088 Bundle extras = extrasForInstallResult(res); 1089 args.observer2.packageInstalled(res.name, extras, res.returnCode); 1090 } catch (RemoteException e) { 1091 Slog.i(TAG, "Observer no longer exists."); 1092 } 1093 } 1094 } else { 1095 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1096 } 1097 } break; 1098 case UPDATED_MEDIA_STATUS: { 1099 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1100 boolean reportStatus = msg.arg1 == 1; 1101 boolean doGc = msg.arg2 == 1; 1102 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1103 if (doGc) { 1104 // Force a gc to clear up stale containers. 1105 Runtime.getRuntime().gc(); 1106 } 1107 if (msg.obj != null) { 1108 @SuppressWarnings("unchecked") 1109 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1110 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1111 // Unload containers 1112 unloadAllContainers(args); 1113 } 1114 if (reportStatus) { 1115 try { 1116 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1117 PackageHelper.getMountService().finishMediaUpdate(); 1118 } catch (RemoteException e) { 1119 Log.e(TAG, "MountService not running?"); 1120 } 1121 } 1122 } break; 1123 case WRITE_SETTINGS: { 1124 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1125 synchronized (mPackages) { 1126 removeMessages(WRITE_SETTINGS); 1127 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1128 mSettings.writeLPr(); 1129 mDirtyUsers.clear(); 1130 } 1131 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1132 } break; 1133 case WRITE_PACKAGE_RESTRICTIONS: { 1134 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1135 synchronized (mPackages) { 1136 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1137 for (int userId : mDirtyUsers) { 1138 mSettings.writePackageRestrictionsLPr(userId); 1139 } 1140 mDirtyUsers.clear(); 1141 } 1142 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1143 } break; 1144 case CHECK_PENDING_VERIFICATION: { 1145 final int verificationId = msg.arg1; 1146 final PackageVerificationState state = mPendingVerification.get(verificationId); 1147 1148 if ((state != null) && !state.timeoutExtended()) { 1149 final InstallArgs args = state.getInstallArgs(); 1150 final Uri fromUri = Uri.fromFile(args.fromFile); 1151 1152 Slog.i(TAG, "Verification timed out for " + fromUri); 1153 mPendingVerification.remove(verificationId); 1154 1155 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1156 1157 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1158 Slog.i(TAG, "Continuing with installation of " + fromUri); 1159 state.setVerifierResponse(Binder.getCallingUid(), 1160 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1161 broadcastPackageVerified(verificationId, fromUri, 1162 PackageManager.VERIFICATION_ALLOW, 1163 state.getInstallArgs().getUser()); 1164 try { 1165 ret = args.copyApk(mContainerService, true); 1166 } catch (RemoteException e) { 1167 Slog.e(TAG, "Could not contact the ContainerService"); 1168 } 1169 } else { 1170 broadcastPackageVerified(verificationId, fromUri, 1171 PackageManager.VERIFICATION_REJECT, 1172 state.getInstallArgs().getUser()); 1173 } 1174 1175 processPendingInstall(args, ret); 1176 mHandler.sendEmptyMessage(MCS_UNBIND); 1177 } 1178 break; 1179 } 1180 case PACKAGE_VERIFIED: { 1181 final int verificationId = msg.arg1; 1182 1183 final PackageVerificationState state = mPendingVerification.get(verificationId); 1184 if (state == null) { 1185 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1186 break; 1187 } 1188 1189 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1190 1191 state.setVerifierResponse(response.callerUid, response.code); 1192 1193 if (state.isVerificationComplete()) { 1194 mPendingVerification.remove(verificationId); 1195 1196 final InstallArgs args = state.getInstallArgs(); 1197 final Uri fromUri = Uri.fromFile(args.fromFile); 1198 1199 int ret; 1200 if (state.isInstallAllowed()) { 1201 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1202 broadcastPackageVerified(verificationId, fromUri, 1203 response.code, state.getInstallArgs().getUser()); 1204 try { 1205 ret = args.copyApk(mContainerService, true); 1206 } catch (RemoteException e) { 1207 Slog.e(TAG, "Could not contact the ContainerService"); 1208 } 1209 } else { 1210 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1211 } 1212 1213 processPendingInstall(args, ret); 1214 1215 mHandler.sendEmptyMessage(MCS_UNBIND); 1216 } 1217 1218 break; 1219 } 1220 } 1221 } 1222 } 1223 1224 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1225 Bundle extras = null; 1226 switch (res.returnCode) { 1227 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1228 extras = new Bundle(); 1229 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1230 res.origPermission); 1231 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1232 res.origPackage); 1233 break; 1234 } 1235 } 1236 return extras; 1237 } 1238 1239 void scheduleWriteSettingsLocked() { 1240 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1241 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1242 } 1243 } 1244 1245 void scheduleWritePackageRestrictionsLocked(int userId) { 1246 if (!sUserManager.exists(userId)) return; 1247 mDirtyUsers.add(userId); 1248 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1249 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1250 } 1251 } 1252 1253 public static final PackageManagerService main(Context context, Installer installer, 1254 boolean factoryTest, boolean onlyCore) { 1255 PackageManagerService m = new PackageManagerService(context, installer, 1256 factoryTest, onlyCore); 1257 ServiceManager.addService("package", m); 1258 return m; 1259 } 1260 1261 static String[] splitString(String str, char sep) { 1262 int count = 1; 1263 int i = 0; 1264 while ((i=str.indexOf(sep, i)) >= 0) { 1265 count++; 1266 i++; 1267 } 1268 1269 String[] res = new String[count]; 1270 i=0; 1271 count = 0; 1272 int lastI=0; 1273 while ((i=str.indexOf(sep, i)) >= 0) { 1274 res[count] = str.substring(lastI, i); 1275 count++; 1276 i++; 1277 lastI = i; 1278 } 1279 res[count] = str.substring(lastI, str.length()); 1280 return res; 1281 } 1282 1283 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1284 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1285 Context.DISPLAY_SERVICE); 1286 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1287 } 1288 1289 public PackageManagerService(Context context, Installer installer, 1290 boolean factoryTest, boolean onlyCore) { 1291 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1292 SystemClock.uptimeMillis()); 1293 1294 if (mSdkVersion <= 0) { 1295 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1296 } 1297 1298 mContext = context; 1299 mFactoryTest = factoryTest; 1300 mOnlyCore = onlyCore; 1301 mMetrics = new DisplayMetrics(); 1302 mSettings = new Settings(context); 1303 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1304 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1305 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1306 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1307 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1308 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1309 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1310 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1311 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1312 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1313 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1314 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1315 1316 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1317 if (separateProcesses != null && separateProcesses.length() > 0) { 1318 if ("*".equals(separateProcesses)) { 1319 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1320 mSeparateProcesses = null; 1321 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1322 } else { 1323 mDefParseFlags = 0; 1324 mSeparateProcesses = separateProcesses.split(","); 1325 Slog.w(TAG, "Running with debug.separate_processes: " 1326 + separateProcesses); 1327 } 1328 } else { 1329 mDefParseFlags = 0; 1330 mSeparateProcesses = null; 1331 } 1332 1333 mInstaller = installer; 1334 1335 getDefaultDisplayMetrics(context, mMetrics); 1336 1337 SystemConfig systemConfig = SystemConfig.getInstance(); 1338 mGlobalGids = systemConfig.getGlobalGids(); 1339 mSystemPermissions = systemConfig.getSystemPermissions(); 1340 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1341 1342 synchronized (mInstallLock) { 1343 // writer 1344 synchronized (mPackages) { 1345 mHandlerThread = new ServiceThread(TAG, 1346 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1347 mHandlerThread.start(); 1348 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1349 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1350 1351 File dataDir = Environment.getDataDirectory(); 1352 mAppDataDir = new File(dataDir, "data"); 1353 mAppInstallDir = new File(dataDir, "app"); 1354 mAppLibInstallDir = new File(dataDir, "app-lib"); 1355 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1356 mUserAppDataDir = new File(dataDir, "user"); 1357 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1358 mAppStagingDir = new File(dataDir, "app-staging"); 1359 1360 sUserManager = new UserManagerService(context, this, 1361 mInstallLock, mPackages); 1362 1363 // Propagate permission configuration in to package manager. 1364 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1365 = systemConfig.getPermissions(); 1366 for (int i=0; i<permConfig.size(); i++) { 1367 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1368 BasePermission bp = mSettings.mPermissions.get(perm.name); 1369 if (bp == null) { 1370 bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN); 1371 mSettings.mPermissions.put(perm.name, bp); 1372 } 1373 if (perm.gids != null) { 1374 bp.gids = appendInts(bp.gids, perm.gids); 1375 } 1376 } 1377 1378 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1379 for (int i=0; i<libConfig.size(); i++) { 1380 mSharedLibraries.put(libConfig.keyAt(i), 1381 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1382 } 1383 1384 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1385 1386 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1387 mSdkVersion, mOnlyCore); 1388 1389 String customResolverActivity = Resources.getSystem().getString( 1390 R.string.config_customResolverActivity); 1391 if (TextUtils.isEmpty(customResolverActivity)) { 1392 customResolverActivity = null; 1393 } else { 1394 mCustomResolverComponentName = ComponentName.unflattenFromString( 1395 customResolverActivity); 1396 } 1397 1398 long startTime = SystemClock.uptimeMillis(); 1399 1400 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1401 startTime); 1402 1403 // Set flag to monitor and not change apk file paths when 1404 // scanning install directories. 1405 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1406 1407 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1408 1409 /** 1410 * Add everything in the in the boot class path to the 1411 * list of process files because dexopt will have been run 1412 * if necessary during zygote startup. 1413 */ 1414 String bootClassPath = System.getProperty("java.boot.class.path"); 1415 if (bootClassPath != null) { 1416 String[] paths = splitString(bootClassPath, ':'); 1417 for (int i=0; i<paths.length; i++) { 1418 alreadyDexOpted.add(paths[i]); 1419 } 1420 } else { 1421 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1422 } 1423 1424 boolean didDexOptLibraryOrTool = false; 1425 1426 final List<String> instructionSets = getAllInstructionSets(); 1427 1428 /** 1429 * Ensure all external libraries have had dexopt run on them. 1430 */ 1431 if (mSharedLibraries.size() > 0) { 1432 // NOTE: For now, we're compiling these system "shared libraries" 1433 // (and framework jars) into all available architectures. It's possible 1434 // to compile them only when we come across an app that uses them (there's 1435 // already logic for that in scanPackageLI) but that adds some complexity. 1436 for (String instructionSet : instructionSets) { 1437 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1438 final String lib = libEntry.path; 1439 if (lib == null) { 1440 continue; 1441 } 1442 1443 try { 1444 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1445 alreadyDexOpted.add(lib); 1446 1447 // The list of "shared libraries" we have at this point is 1448 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1449 didDexOptLibraryOrTool = true; 1450 } 1451 } catch (FileNotFoundException e) { 1452 Slog.w(TAG, "Library not found: " + lib); 1453 } catch (IOException e) { 1454 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1455 + e.getMessage()); 1456 } 1457 } 1458 } 1459 } 1460 1461 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1462 1463 // Gross hack for now: we know this file doesn't contain any 1464 // code, so don't dexopt it to avoid the resulting log spew. 1465 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1466 1467 // Gross hack for now: we know this file is only part of 1468 // the boot class path for art, so don't dexopt it to 1469 // avoid the resulting log spew. 1470 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1471 1472 /** 1473 * And there are a number of commands implemented in Java, which 1474 * we currently need to do the dexopt on so that they can be 1475 * run from a non-root shell. 1476 */ 1477 String[] frameworkFiles = frameworkDir.list(); 1478 if (frameworkFiles != null) { 1479 // TODO: We could compile these only for the most preferred ABI. We should 1480 // first double check that the dex files for these commands are not referenced 1481 // by other system apps. 1482 for (String instructionSet : instructionSets) { 1483 for (int i=0; i<frameworkFiles.length; i++) { 1484 File libPath = new File(frameworkDir, frameworkFiles[i]); 1485 String path = libPath.getPath(); 1486 // Skip the file if we already did it. 1487 if (alreadyDexOpted.contains(path)) { 1488 continue; 1489 } 1490 // Skip the file if it is not a type we want to dexopt. 1491 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1492 continue; 1493 } 1494 try { 1495 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1496 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1497 didDexOptLibraryOrTool = true; 1498 } 1499 } catch (FileNotFoundException e) { 1500 Slog.w(TAG, "Jar not found: " + path); 1501 } catch (IOException e) { 1502 Slog.w(TAG, "Exception reading jar: " + path, e); 1503 } 1504 } 1505 } 1506 } 1507 1508 if (didDexOptLibraryOrTool) { 1509 // If we dexopted a library or tool, then something on the system has 1510 // changed. Consider this significant, and wipe away all other 1511 // existing dexopt files to ensure we don't leave any dangling around. 1512 // 1513 // TODO: This should be revisited because it isn't as good an indicator 1514 // as it used to be. It used to include the boot classpath but at some point 1515 // DexFile.isDexOptNeeded started returning false for the boot 1516 // class path files in all cases. It is very possible in a 1517 // small maintenance release update that the library and tool 1518 // jars may be unchanged but APK could be removed resulting in 1519 // unused dalvik-cache files. 1520 for (String instructionSet : instructionSets) { 1521 mInstaller.pruneDexCache(instructionSet); 1522 } 1523 1524 // Additionally, delete all dex files from the root directory 1525 // since there shouldn't be any there anyway, unless we're upgrading 1526 // from an older OS version or a build that contained the "old" style 1527 // flat scheme. 1528 mInstaller.pruneDexCache("."); 1529 } 1530 1531 // Collect vendor overlay packages. 1532 // (Do this before scanning any apps.) 1533 // For security and version matching reason, only consider 1534 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1535 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1536 mVendorOverlayInstallObserver = new AppDirObserver( 1537 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1538 mVendorOverlayInstallObserver.startWatching(); 1539 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1540 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1541 1542 // Find base frameworks (resource packages without code). 1543 mFrameworkInstallObserver = new AppDirObserver( 1544 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1545 mFrameworkInstallObserver.startWatching(); 1546 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1547 | PackageParser.PARSE_IS_SYSTEM_DIR 1548 | PackageParser.PARSE_IS_PRIVILEGED, 1549 scanMode | SCAN_NO_DEX, 0); 1550 1551 // Collected privileged system packages. 1552 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1553 mPrivilegedInstallObserver = new AppDirObserver( 1554 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1555 mPrivilegedInstallObserver.startWatching(); 1556 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1557 | PackageParser.PARSE_IS_SYSTEM_DIR 1558 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1559 1560 // Collect ordinary system packages. 1561 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1562 mSystemInstallObserver = new AppDirObserver( 1563 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1564 mSystemInstallObserver.startWatching(); 1565 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1566 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1567 1568 // Collect all vendor packages. 1569 File vendorAppDir = new File("/vendor/app"); 1570 try { 1571 vendorAppDir = vendorAppDir.getCanonicalFile(); 1572 } catch (IOException e) { 1573 // failed to look up canonical path, continue with original one 1574 } 1575 mVendorInstallObserver = new AppDirObserver( 1576 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1577 mVendorInstallObserver.startWatching(); 1578 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1579 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1580 1581 // Collect all OEM packages. 1582 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1583 mOemInstallObserver = new AppDirObserver( 1584 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1585 mOemInstallObserver.startWatching(); 1586 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1587 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1588 1589 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1590 mInstaller.moveFiles(); 1591 1592 // Prune any system packages that no longer exist. 1593 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1594 if (!mOnlyCore) { 1595 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1596 while (psit.hasNext()) { 1597 PackageSetting ps = psit.next(); 1598 1599 /* 1600 * If this is not a system app, it can't be a 1601 * disable system app. 1602 */ 1603 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1604 continue; 1605 } 1606 1607 /* 1608 * If the package is scanned, it's not erased. 1609 */ 1610 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1611 if (scannedPkg != null) { 1612 /* 1613 * If the system app is both scanned and in the 1614 * disabled packages list, then it must have been 1615 * added via OTA. Remove it from the currently 1616 * scanned package so the previously user-installed 1617 * application can be scanned. 1618 */ 1619 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1620 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1621 + "; removing system app"); 1622 removePackageLI(ps, true); 1623 } 1624 1625 continue; 1626 } 1627 1628 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1629 psit.remove(); 1630 String msg = "System package " + ps.name 1631 + " no longer exists; wiping its data"; 1632 reportSettingsProblem(Log.WARN, msg); 1633 removeDataDirsLI(ps.name); 1634 } else { 1635 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1636 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1637 possiblyDeletedUpdatedSystemApps.add(ps.name); 1638 } 1639 } 1640 } 1641 } 1642 1643 //look for any incomplete package installations 1644 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1645 //clean up list 1646 for(int i = 0; i < deletePkgsList.size(); i++) { 1647 //clean up here 1648 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1649 } 1650 //delete tmp files 1651 deleteTempPackageFiles(); 1652 1653 // Remove any shared userIDs that have no associated packages 1654 mSettings.pruneSharedUsersLPw(); 1655 1656 if (!mOnlyCore) { 1657 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1658 SystemClock.uptimeMillis()); 1659 mAppInstallObserver = new AppDirObserver( 1660 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1661 mAppInstallObserver.startWatching(); 1662 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1663 1664 mDrmAppInstallObserver = new AppDirObserver( 1665 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1666 mDrmAppInstallObserver.startWatching(); 1667 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1668 scanMode, 0); 1669 1670 /** 1671 * Remove disable package settings for any updated system 1672 * apps that were removed via an OTA. If they're not a 1673 * previously-updated app, remove them completely. 1674 * Otherwise, just revoke their system-level permissions. 1675 */ 1676 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1677 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1678 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1679 1680 String msg; 1681 if (deletedPkg == null) { 1682 msg = "Updated system package " + deletedAppName 1683 + " no longer exists; wiping its data"; 1684 removeDataDirsLI(deletedAppName); 1685 } else { 1686 msg = "Updated system app + " + deletedAppName 1687 + " no longer present; removing system privileges for " 1688 + deletedAppName; 1689 1690 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1691 1692 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1693 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1694 } 1695 reportSettingsProblem(Log.WARN, msg); 1696 } 1697 } else { 1698 mAppInstallObserver = null; 1699 mDrmAppInstallObserver = null; 1700 } 1701 1702 // Now that we know all of the shared libraries, update all clients to have 1703 // the correct library paths. 1704 updateAllSharedLibrariesLPw(); 1705 1706 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1707 // NOTE: We ignore potential failures here during a system scan (like 1708 // the rest of the commands above) because there's precious little we 1709 // can do about it. A settings error is reported, though. 1710 adjustCpuAbisForSharedUserLPw(setting.packages, null, 1711 false /* force dexopt */, false /* defer dexopt */); 1712 } 1713 1714 // Now that we know all the packages we are keeping, 1715 // read and update their last usage times. 1716 mPackageUsage.readLP(); 1717 1718 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1719 SystemClock.uptimeMillis()); 1720 Slog.i(TAG, "Time to scan packages: " 1721 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1722 + " seconds"); 1723 1724 // If the platform SDK has changed since the last time we booted, 1725 // we need to re-grant app permission to catch any new ones that 1726 // appear. This is really a hack, and means that apps can in some 1727 // cases get permissions that the user didn't initially explicitly 1728 // allow... it would be nice to have some better way to handle 1729 // this situation. 1730 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1731 != mSdkVersion; 1732 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1733 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1734 + "; regranting permissions for internal storage"); 1735 mSettings.mInternalSdkPlatform = mSdkVersion; 1736 1737 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1738 | (regrantPermissions 1739 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1740 : 0)); 1741 1742 // If this is the first boot, and it is a normal boot, then 1743 // we need to initialize the default preferred apps. 1744 if (!mRestoredSettings && !onlyCore) { 1745 mSettings.readDefaultPreferredAppsLPw(this, 0); 1746 } 1747 1748 // All the changes are done during package scanning. 1749 mSettings.updateInternalDatabaseVersion(); 1750 1751 // can downgrade to reader 1752 mSettings.writeLPr(); 1753 1754 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1755 SystemClock.uptimeMillis()); 1756 1757 1758 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1759 } // synchronized (mPackages) 1760 } // synchronized (mInstallLock) 1761 1762 mInstallerService = new PackageInstallerService(context, this, mAppStagingDir); 1763 1764 // Now after opening every single application zip, make sure they 1765 // are all flushed. Not really needed, but keeps things nice and 1766 // tidy. 1767 Runtime.getRuntime().gc(); 1768 } 1769 1770 @Override 1771 public boolean isFirstBoot() { 1772 return !mRestoredSettings; 1773 } 1774 1775 @Override 1776 public boolean isOnlyCoreApps() { 1777 return mOnlyCore; 1778 } 1779 1780 private String getRequiredVerifierLPr() { 1781 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1782 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1783 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1784 1785 String requiredVerifier = null; 1786 1787 final int N = receivers.size(); 1788 for (int i = 0; i < N; i++) { 1789 final ResolveInfo info = receivers.get(i); 1790 1791 if (info.activityInfo == null) { 1792 continue; 1793 } 1794 1795 final String packageName = info.activityInfo.packageName; 1796 1797 final PackageSetting ps = mSettings.mPackages.get(packageName); 1798 if (ps == null) { 1799 continue; 1800 } 1801 1802 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1803 if (!gp.grantedPermissions 1804 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1805 continue; 1806 } 1807 1808 if (requiredVerifier != null) { 1809 throw new RuntimeException("There can be only one required verifier"); 1810 } 1811 1812 requiredVerifier = packageName; 1813 } 1814 1815 return requiredVerifier; 1816 } 1817 1818 @Override 1819 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1820 throws RemoteException { 1821 try { 1822 return super.onTransact(code, data, reply, flags); 1823 } catch (RuntimeException e) { 1824 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1825 Slog.wtf(TAG, "Package Manager Crash", e); 1826 } 1827 throw e; 1828 } 1829 } 1830 1831 void cleanupInstallFailedPackage(PackageSetting ps) { 1832 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1833 removeDataDirsLI(ps.name); 1834 1835 // TODO: try cleaning up codePath directory contents first, since it 1836 // might be a cluster 1837 1838 if (ps.codePath != null) { 1839 if (!ps.codePath.delete()) { 1840 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1841 } 1842 } 1843 if (ps.resourcePath != null) { 1844 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1845 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1846 } 1847 } 1848 mSettings.removePackageLPw(ps.name); 1849 } 1850 1851 static int[] appendInts(int[] cur, int[] add) { 1852 if (add == null) return cur; 1853 if (cur == null) return add; 1854 final int N = add.length; 1855 for (int i=0; i<N; i++) { 1856 cur = appendInt(cur, add[i]); 1857 } 1858 return cur; 1859 } 1860 1861 static int[] removeInts(int[] cur, int[] rem) { 1862 if (rem == null) return cur; 1863 if (cur == null) return cur; 1864 final int N = rem.length; 1865 for (int i=0; i<N; i++) { 1866 cur = removeInt(cur, rem[i]); 1867 } 1868 return cur; 1869 } 1870 1871 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1872 if (!sUserManager.exists(userId)) return null; 1873 final PackageSetting ps = (PackageSetting) p.mExtras; 1874 if (ps == null) { 1875 return null; 1876 } 1877 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1878 final PackageUserState state = ps.readUserState(userId); 1879 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1880 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1881 state, userId); 1882 } 1883 1884 @Override 1885 public boolean isPackageAvailable(String packageName, int userId) { 1886 if (!sUserManager.exists(userId)) return false; 1887 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1888 synchronized (mPackages) { 1889 PackageParser.Package p = mPackages.get(packageName); 1890 if (p != null) { 1891 final PackageSetting ps = (PackageSetting) p.mExtras; 1892 if (ps != null) { 1893 final PackageUserState state = ps.readUserState(userId); 1894 if (state != null) { 1895 return PackageParser.isAvailable(state); 1896 } 1897 } 1898 } 1899 } 1900 return false; 1901 } 1902 1903 @Override 1904 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1905 if (!sUserManager.exists(userId)) return null; 1906 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1907 // reader 1908 synchronized (mPackages) { 1909 PackageParser.Package p = mPackages.get(packageName); 1910 if (DEBUG_PACKAGE_INFO) 1911 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1912 if (p != null) { 1913 return generatePackageInfo(p, flags, userId); 1914 } 1915 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1916 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1917 } 1918 } 1919 return null; 1920 } 1921 1922 @Override 1923 public String[] currentToCanonicalPackageNames(String[] names) { 1924 String[] out = new String[names.length]; 1925 // reader 1926 synchronized (mPackages) { 1927 for (int i=names.length-1; i>=0; i--) { 1928 PackageSetting ps = mSettings.mPackages.get(names[i]); 1929 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1930 } 1931 } 1932 return out; 1933 } 1934 1935 @Override 1936 public String[] canonicalToCurrentPackageNames(String[] names) { 1937 String[] out = new String[names.length]; 1938 // reader 1939 synchronized (mPackages) { 1940 for (int i=names.length-1; i>=0; i--) { 1941 String cur = mSettings.mRenamedPackages.get(names[i]); 1942 out[i] = cur != null ? cur : names[i]; 1943 } 1944 } 1945 return out; 1946 } 1947 1948 @Override 1949 public int getPackageUid(String packageName, int userId) { 1950 if (!sUserManager.exists(userId)) return -1; 1951 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1952 // reader 1953 synchronized (mPackages) { 1954 PackageParser.Package p = mPackages.get(packageName); 1955 if(p != null) { 1956 return UserHandle.getUid(userId, p.applicationInfo.uid); 1957 } 1958 PackageSetting ps = mSettings.mPackages.get(packageName); 1959 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1960 return -1; 1961 } 1962 p = ps.pkg; 1963 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1964 } 1965 } 1966 1967 @Override 1968 public int[] getPackageGids(String packageName) { 1969 // reader 1970 synchronized (mPackages) { 1971 PackageParser.Package p = mPackages.get(packageName); 1972 if (DEBUG_PACKAGE_INFO) 1973 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1974 if (p != null) { 1975 final PackageSetting ps = (PackageSetting)p.mExtras; 1976 return ps.getGids(); 1977 } 1978 } 1979 // stupid thing to indicate an error. 1980 return new int[0]; 1981 } 1982 1983 static final PermissionInfo generatePermissionInfo( 1984 BasePermission bp, int flags) { 1985 if (bp.perm != null) { 1986 return PackageParser.generatePermissionInfo(bp.perm, flags); 1987 } 1988 PermissionInfo pi = new PermissionInfo(); 1989 pi.name = bp.name; 1990 pi.packageName = bp.sourcePackage; 1991 pi.nonLocalizedLabel = bp.name; 1992 pi.protectionLevel = bp.protectionLevel; 1993 return pi; 1994 } 1995 1996 @Override 1997 public PermissionInfo getPermissionInfo(String name, int flags) { 1998 // reader 1999 synchronized (mPackages) { 2000 final BasePermission p = mSettings.mPermissions.get(name); 2001 if (p != null) { 2002 return generatePermissionInfo(p, flags); 2003 } 2004 return null; 2005 } 2006 } 2007 2008 @Override 2009 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2010 // reader 2011 synchronized (mPackages) { 2012 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2013 for (BasePermission p : mSettings.mPermissions.values()) { 2014 if (group == null) { 2015 if (p.perm == null || p.perm.info.group == null) { 2016 out.add(generatePermissionInfo(p, flags)); 2017 } 2018 } else { 2019 if (p.perm != null && group.equals(p.perm.info.group)) { 2020 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2021 } 2022 } 2023 } 2024 2025 if (out.size() > 0) { 2026 return out; 2027 } 2028 return mPermissionGroups.containsKey(group) ? out : null; 2029 } 2030 } 2031 2032 @Override 2033 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2034 // reader 2035 synchronized (mPackages) { 2036 return PackageParser.generatePermissionGroupInfo( 2037 mPermissionGroups.get(name), flags); 2038 } 2039 } 2040 2041 @Override 2042 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2043 // reader 2044 synchronized (mPackages) { 2045 final int N = mPermissionGroups.size(); 2046 ArrayList<PermissionGroupInfo> out 2047 = new ArrayList<PermissionGroupInfo>(N); 2048 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2049 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2050 } 2051 return out; 2052 } 2053 } 2054 2055 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2056 int userId) { 2057 if (!sUserManager.exists(userId)) return null; 2058 PackageSetting ps = mSettings.mPackages.get(packageName); 2059 if (ps != null) { 2060 if (ps.pkg == null) { 2061 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2062 flags, userId); 2063 if (pInfo != null) { 2064 return pInfo.applicationInfo; 2065 } 2066 return null; 2067 } 2068 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2069 ps.readUserState(userId), userId); 2070 } 2071 return null; 2072 } 2073 2074 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2075 int userId) { 2076 if (!sUserManager.exists(userId)) return null; 2077 PackageSetting ps = mSettings.mPackages.get(packageName); 2078 if (ps != null) { 2079 PackageParser.Package pkg = ps.pkg; 2080 if (pkg == null) { 2081 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2082 return null; 2083 } 2084 // Only data remains, so we aren't worried about code paths 2085 pkg = new PackageParser.Package(packageName); 2086 pkg.applicationInfo.packageName = packageName; 2087 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2088 pkg.applicationInfo.dataDir = 2089 getDataPathForPackage(packageName, 0).getPath(); 2090 pkg.applicationInfo.cpuAbi = ps.cpuAbiString; 2091 } 2092 return generatePackageInfo(pkg, flags, userId); 2093 } 2094 return null; 2095 } 2096 2097 @Override 2098 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2099 if (!sUserManager.exists(userId)) return null; 2100 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2101 // writer 2102 synchronized (mPackages) { 2103 PackageParser.Package p = mPackages.get(packageName); 2104 if (DEBUG_PACKAGE_INFO) Log.v( 2105 TAG, "getApplicationInfo " + packageName 2106 + ": " + p); 2107 if (p != null) { 2108 PackageSetting ps = mSettings.mPackages.get(packageName); 2109 if (ps == null) return null; 2110 // Note: isEnabledLP() does not apply here - always return info 2111 return PackageParser.generateApplicationInfo( 2112 p, flags, ps.readUserState(userId), userId); 2113 } 2114 if ("android".equals(packageName)||"system".equals(packageName)) { 2115 return mAndroidApplication; 2116 } 2117 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2118 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2119 } 2120 } 2121 return null; 2122 } 2123 2124 2125 @Override 2126 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2127 mContext.enforceCallingOrSelfPermission( 2128 android.Manifest.permission.CLEAR_APP_CACHE, null); 2129 // Queue up an async operation since clearing cache may take a little while. 2130 mHandler.post(new Runnable() { 2131 public void run() { 2132 mHandler.removeCallbacks(this); 2133 int retCode = -1; 2134 synchronized (mInstallLock) { 2135 retCode = mInstaller.freeCache(freeStorageSize); 2136 if (retCode < 0) { 2137 Slog.w(TAG, "Couldn't clear application caches"); 2138 } 2139 } 2140 if (observer != null) { 2141 try { 2142 observer.onRemoveCompleted(null, (retCode >= 0)); 2143 } catch (RemoteException e) { 2144 Slog.w(TAG, "RemoveException when invoking call back"); 2145 } 2146 } 2147 } 2148 }); 2149 } 2150 2151 @Override 2152 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2153 mContext.enforceCallingOrSelfPermission( 2154 android.Manifest.permission.CLEAR_APP_CACHE, null); 2155 // Queue up an async operation since clearing cache may take a little while. 2156 mHandler.post(new Runnable() { 2157 public void run() { 2158 mHandler.removeCallbacks(this); 2159 int retCode = -1; 2160 synchronized (mInstallLock) { 2161 retCode = mInstaller.freeCache(freeStorageSize); 2162 if (retCode < 0) { 2163 Slog.w(TAG, "Couldn't clear application caches"); 2164 } 2165 } 2166 if(pi != null) { 2167 try { 2168 // Callback via pending intent 2169 int code = (retCode >= 0) ? 1 : 0; 2170 pi.sendIntent(null, code, null, 2171 null, null); 2172 } catch (SendIntentException e1) { 2173 Slog.i(TAG, "Failed to send pending intent"); 2174 } 2175 } 2176 } 2177 }); 2178 } 2179 2180 void freeStorage(long freeStorageSize) throws IOException { 2181 synchronized (mInstallLock) { 2182 if (mInstaller.freeCache(freeStorageSize) < 0) { 2183 throw new IOException("Failed to free enough space"); 2184 } 2185 } 2186 } 2187 2188 @Override 2189 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2190 if (!sUserManager.exists(userId)) return null; 2191 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2192 synchronized (mPackages) { 2193 PackageParser.Activity a = mActivities.mActivities.get(component); 2194 2195 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2196 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2197 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2198 if (ps == null) return null; 2199 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2200 userId); 2201 } 2202 if (mResolveComponentName.equals(component)) { 2203 return mResolveActivity; 2204 } 2205 } 2206 return null; 2207 } 2208 2209 @Override 2210 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2211 String resolvedType) { 2212 synchronized (mPackages) { 2213 PackageParser.Activity a = mActivities.mActivities.get(component); 2214 if (a == null) { 2215 return false; 2216 } 2217 for (int i=0; i<a.intents.size(); i++) { 2218 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2219 intent.getData(), intent.getCategories(), TAG) >= 0) { 2220 return true; 2221 } 2222 } 2223 return false; 2224 } 2225 } 2226 2227 @Override 2228 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2229 if (!sUserManager.exists(userId)) return null; 2230 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2231 synchronized (mPackages) { 2232 PackageParser.Activity a = mReceivers.mActivities.get(component); 2233 if (DEBUG_PACKAGE_INFO) Log.v( 2234 TAG, "getReceiverInfo " + component + ": " + a); 2235 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2236 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2237 if (ps == null) return null; 2238 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2239 userId); 2240 } 2241 } 2242 return null; 2243 } 2244 2245 @Override 2246 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2247 if (!sUserManager.exists(userId)) return null; 2248 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2249 synchronized (mPackages) { 2250 PackageParser.Service s = mServices.mServices.get(component); 2251 if (DEBUG_PACKAGE_INFO) Log.v( 2252 TAG, "getServiceInfo " + component + ": " + s); 2253 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2254 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2255 if (ps == null) return null; 2256 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2257 userId); 2258 } 2259 } 2260 return null; 2261 } 2262 2263 @Override 2264 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2265 if (!sUserManager.exists(userId)) return null; 2266 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2267 synchronized (mPackages) { 2268 PackageParser.Provider p = mProviders.mProviders.get(component); 2269 if (DEBUG_PACKAGE_INFO) Log.v( 2270 TAG, "getProviderInfo " + component + ": " + p); 2271 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2272 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2273 if (ps == null) return null; 2274 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2275 userId); 2276 } 2277 } 2278 return null; 2279 } 2280 2281 @Override 2282 public String[] getSystemSharedLibraryNames() { 2283 Set<String> libSet; 2284 synchronized (mPackages) { 2285 libSet = mSharedLibraries.keySet(); 2286 int size = libSet.size(); 2287 if (size > 0) { 2288 String[] libs = new String[size]; 2289 libSet.toArray(libs); 2290 return libs; 2291 } 2292 } 2293 return null; 2294 } 2295 2296 @Override 2297 public FeatureInfo[] getSystemAvailableFeatures() { 2298 Collection<FeatureInfo> featSet; 2299 synchronized (mPackages) { 2300 featSet = mAvailableFeatures.values(); 2301 int size = featSet.size(); 2302 if (size > 0) { 2303 FeatureInfo[] features = new FeatureInfo[size+1]; 2304 featSet.toArray(features); 2305 FeatureInfo fi = new FeatureInfo(); 2306 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2307 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2308 features[size] = fi; 2309 return features; 2310 } 2311 } 2312 return null; 2313 } 2314 2315 @Override 2316 public boolean hasSystemFeature(String name) { 2317 synchronized (mPackages) { 2318 return mAvailableFeatures.containsKey(name); 2319 } 2320 } 2321 2322 private void checkValidCaller(int uid, int userId) { 2323 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2324 return; 2325 2326 throw new SecurityException("Caller uid=" + uid 2327 + " is not privileged to communicate with user=" + userId); 2328 } 2329 2330 @Override 2331 public int checkPermission(String permName, String pkgName) { 2332 synchronized (mPackages) { 2333 PackageParser.Package p = mPackages.get(pkgName); 2334 if (p != null && p.mExtras != null) { 2335 PackageSetting ps = (PackageSetting)p.mExtras; 2336 if (ps.sharedUser != null) { 2337 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2338 return PackageManager.PERMISSION_GRANTED; 2339 } 2340 } else if (ps.grantedPermissions.contains(permName)) { 2341 return PackageManager.PERMISSION_GRANTED; 2342 } 2343 } 2344 } 2345 return PackageManager.PERMISSION_DENIED; 2346 } 2347 2348 @Override 2349 public int checkUidPermission(String permName, int uid) { 2350 synchronized (mPackages) { 2351 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2352 if (obj != null) { 2353 GrantedPermissions gp = (GrantedPermissions)obj; 2354 if (gp.grantedPermissions.contains(permName)) { 2355 return PackageManager.PERMISSION_GRANTED; 2356 } 2357 } else { 2358 HashSet<String> perms = mSystemPermissions.get(uid); 2359 if (perms != null && perms.contains(permName)) { 2360 return PackageManager.PERMISSION_GRANTED; 2361 } 2362 } 2363 } 2364 return PackageManager.PERMISSION_DENIED; 2365 } 2366 2367 /** 2368 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2369 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2370 * @param message the message to log on security exception 2371 */ 2372 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2373 String message) { 2374 if (userId < 0) { 2375 throw new IllegalArgumentException("Invalid userId " + userId); 2376 } 2377 if (userId == UserHandle.getUserId(callingUid)) return; 2378 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2379 if (requireFullPermission) { 2380 mContext.enforceCallingOrSelfPermission( 2381 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2382 } else { 2383 try { 2384 mContext.enforceCallingOrSelfPermission( 2385 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2386 } catch (SecurityException se) { 2387 mContext.enforceCallingOrSelfPermission( 2388 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2389 } 2390 } 2391 } 2392 } 2393 2394 private BasePermission findPermissionTreeLP(String permName) { 2395 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2396 if (permName.startsWith(bp.name) && 2397 permName.length() > bp.name.length() && 2398 permName.charAt(bp.name.length()) == '.') { 2399 return bp; 2400 } 2401 } 2402 return null; 2403 } 2404 2405 private BasePermission checkPermissionTreeLP(String permName) { 2406 if (permName != null) { 2407 BasePermission bp = findPermissionTreeLP(permName); 2408 if (bp != null) { 2409 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2410 return bp; 2411 } 2412 throw new SecurityException("Calling uid " 2413 + Binder.getCallingUid() 2414 + " is not allowed to add to permission tree " 2415 + bp.name + " owned by uid " + bp.uid); 2416 } 2417 } 2418 throw new SecurityException("No permission tree found for " + permName); 2419 } 2420 2421 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2422 if (s1 == null) { 2423 return s2 == null; 2424 } 2425 if (s2 == null) { 2426 return false; 2427 } 2428 if (s1.getClass() != s2.getClass()) { 2429 return false; 2430 } 2431 return s1.equals(s2); 2432 } 2433 2434 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2435 if (pi1.icon != pi2.icon) return false; 2436 if (pi1.logo != pi2.logo) return false; 2437 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2438 if (!compareStrings(pi1.name, pi2.name)) return false; 2439 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2440 // We'll take care of setting this one. 2441 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2442 // These are not currently stored in settings. 2443 //if (!compareStrings(pi1.group, pi2.group)) return false; 2444 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2445 //if (pi1.labelRes != pi2.labelRes) return false; 2446 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2447 return true; 2448 } 2449 2450 int permissionInfoFootprint(PermissionInfo info) { 2451 int size = info.name.length(); 2452 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2453 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2454 return size; 2455 } 2456 2457 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2458 int size = 0; 2459 for (BasePermission perm : mSettings.mPermissions.values()) { 2460 if (perm.uid == tree.uid) { 2461 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2462 } 2463 } 2464 return size; 2465 } 2466 2467 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2468 // We calculate the max size of permissions defined by this uid and throw 2469 // if that plus the size of 'info' would exceed our stated maximum. 2470 if (tree.uid != Process.SYSTEM_UID) { 2471 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2472 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2473 throw new SecurityException("Permission tree size cap exceeded"); 2474 } 2475 } 2476 } 2477 2478 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2479 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2480 throw new SecurityException("Label must be specified in permission"); 2481 } 2482 BasePermission tree = checkPermissionTreeLP(info.name); 2483 BasePermission bp = mSettings.mPermissions.get(info.name); 2484 boolean added = bp == null; 2485 boolean changed = true; 2486 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2487 if (added) { 2488 enforcePermissionCapLocked(info, tree); 2489 bp = new BasePermission(info.name, tree.sourcePackage, 2490 BasePermission.TYPE_DYNAMIC); 2491 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2492 throw new SecurityException( 2493 "Not allowed to modify non-dynamic permission " 2494 + info.name); 2495 } else { 2496 if (bp.protectionLevel == fixedLevel 2497 && bp.perm.owner.equals(tree.perm.owner) 2498 && bp.uid == tree.uid 2499 && comparePermissionInfos(bp.perm.info, info)) { 2500 changed = false; 2501 } 2502 } 2503 bp.protectionLevel = fixedLevel; 2504 info = new PermissionInfo(info); 2505 info.protectionLevel = fixedLevel; 2506 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2507 bp.perm.info.packageName = tree.perm.info.packageName; 2508 bp.uid = tree.uid; 2509 if (added) { 2510 mSettings.mPermissions.put(info.name, bp); 2511 } 2512 if (changed) { 2513 if (!async) { 2514 mSettings.writeLPr(); 2515 } else { 2516 scheduleWriteSettingsLocked(); 2517 } 2518 } 2519 return added; 2520 } 2521 2522 @Override 2523 public boolean addPermission(PermissionInfo info) { 2524 synchronized (mPackages) { 2525 return addPermissionLocked(info, false); 2526 } 2527 } 2528 2529 @Override 2530 public boolean addPermissionAsync(PermissionInfo info) { 2531 synchronized (mPackages) { 2532 return addPermissionLocked(info, true); 2533 } 2534 } 2535 2536 @Override 2537 public void removePermission(String name) { 2538 synchronized (mPackages) { 2539 checkPermissionTreeLP(name); 2540 BasePermission bp = mSettings.mPermissions.get(name); 2541 if (bp != null) { 2542 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2543 throw new SecurityException( 2544 "Not allowed to modify non-dynamic permission " 2545 + name); 2546 } 2547 mSettings.mPermissions.remove(name); 2548 mSettings.writeLPr(); 2549 } 2550 } 2551 } 2552 2553 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2554 int index = pkg.requestedPermissions.indexOf(bp.name); 2555 if (index == -1) { 2556 throw new SecurityException("Package " + pkg.packageName 2557 + " has not requested permission " + bp.name); 2558 } 2559 boolean isNormal = 2560 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2561 == PermissionInfo.PROTECTION_NORMAL); 2562 boolean isDangerous = 2563 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2564 == PermissionInfo.PROTECTION_DANGEROUS); 2565 boolean isDevelopment = 2566 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2567 2568 if (!isNormal && !isDangerous && !isDevelopment) { 2569 throw new SecurityException("Permission " + bp.name 2570 + " is not a changeable permission type"); 2571 } 2572 2573 if (isNormal || isDangerous) { 2574 if (pkg.requestedPermissionsRequired.get(index)) { 2575 throw new SecurityException("Can't change " + bp.name 2576 + ". It is required by the application"); 2577 } 2578 } 2579 } 2580 2581 @Override 2582 public void grantPermission(String packageName, String permissionName) { 2583 mContext.enforceCallingOrSelfPermission( 2584 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2585 synchronized (mPackages) { 2586 final PackageParser.Package pkg = mPackages.get(packageName); 2587 if (pkg == null) { 2588 throw new IllegalArgumentException("Unknown package: " + packageName); 2589 } 2590 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2591 if (bp == null) { 2592 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2593 } 2594 2595 checkGrantRevokePermissions(pkg, bp); 2596 2597 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2598 if (ps == null) { 2599 return; 2600 } 2601 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2602 if (gp.grantedPermissions.add(permissionName)) { 2603 if (ps.haveGids) { 2604 gp.gids = appendInts(gp.gids, bp.gids); 2605 } 2606 mSettings.writeLPr(); 2607 } 2608 } 2609 } 2610 2611 @Override 2612 public void revokePermission(String packageName, String permissionName) { 2613 int changedAppId = -1; 2614 2615 synchronized (mPackages) { 2616 final PackageParser.Package pkg = mPackages.get(packageName); 2617 if (pkg == null) { 2618 throw new IllegalArgumentException("Unknown package: " + packageName); 2619 } 2620 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2621 mContext.enforceCallingOrSelfPermission( 2622 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2623 } 2624 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2625 if (bp == null) { 2626 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2627 } 2628 2629 checkGrantRevokePermissions(pkg, bp); 2630 2631 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2632 if (ps == null) { 2633 return; 2634 } 2635 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2636 if (gp.grantedPermissions.remove(permissionName)) { 2637 gp.grantedPermissions.remove(permissionName); 2638 if (ps.haveGids) { 2639 gp.gids = removeInts(gp.gids, bp.gids); 2640 } 2641 mSettings.writeLPr(); 2642 changedAppId = ps.appId; 2643 } 2644 } 2645 2646 if (changedAppId >= 0) { 2647 // We changed the perm on someone, kill its processes. 2648 IActivityManager am = ActivityManagerNative.getDefault(); 2649 if (am != null) { 2650 final int callingUserId = UserHandle.getCallingUserId(); 2651 final long ident = Binder.clearCallingIdentity(); 2652 try { 2653 //XXX we should only revoke for the calling user's app permissions, 2654 // but for now we impact all users. 2655 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2656 // "revoke " + permissionName); 2657 int[] users = sUserManager.getUserIds(); 2658 for (int user : users) { 2659 am.killUid(UserHandle.getUid(user, changedAppId), 2660 "revoke " + permissionName); 2661 } 2662 } catch (RemoteException e) { 2663 } finally { 2664 Binder.restoreCallingIdentity(ident); 2665 } 2666 } 2667 } 2668 } 2669 2670 @Override 2671 public boolean isProtectedBroadcast(String actionName) { 2672 synchronized (mPackages) { 2673 return mProtectedBroadcasts.contains(actionName); 2674 } 2675 } 2676 2677 @Override 2678 public int checkSignatures(String pkg1, String pkg2) { 2679 synchronized (mPackages) { 2680 final PackageParser.Package p1 = mPackages.get(pkg1); 2681 final PackageParser.Package p2 = mPackages.get(pkg2); 2682 if (p1 == null || p1.mExtras == null 2683 || p2 == null || p2.mExtras == null) { 2684 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2685 } 2686 return compareSignatures(p1.mSignatures, p2.mSignatures); 2687 } 2688 } 2689 2690 @Override 2691 public int checkUidSignatures(int uid1, int uid2) { 2692 // Map to base uids. 2693 uid1 = UserHandle.getAppId(uid1); 2694 uid2 = UserHandle.getAppId(uid2); 2695 // reader 2696 synchronized (mPackages) { 2697 Signature[] s1; 2698 Signature[] s2; 2699 Object obj = mSettings.getUserIdLPr(uid1); 2700 if (obj != null) { 2701 if (obj instanceof SharedUserSetting) { 2702 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2703 } else if (obj instanceof PackageSetting) { 2704 s1 = ((PackageSetting)obj).signatures.mSignatures; 2705 } else { 2706 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2707 } 2708 } else { 2709 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2710 } 2711 obj = mSettings.getUserIdLPr(uid2); 2712 if (obj != null) { 2713 if (obj instanceof SharedUserSetting) { 2714 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2715 } else if (obj instanceof PackageSetting) { 2716 s2 = ((PackageSetting)obj).signatures.mSignatures; 2717 } else { 2718 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2719 } 2720 } else { 2721 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2722 } 2723 return compareSignatures(s1, s2); 2724 } 2725 } 2726 2727 /** 2728 * Compares two sets of signatures. Returns: 2729 * <br /> 2730 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2731 * <br /> 2732 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2733 * <br /> 2734 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2735 * <br /> 2736 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2737 * <br /> 2738 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2739 */ 2740 static int compareSignatures(Signature[] s1, Signature[] s2) { 2741 if (s1 == null) { 2742 return s2 == null 2743 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2744 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2745 } 2746 2747 if (s2 == null) { 2748 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2749 } 2750 2751 if (s1.length != s2.length) { 2752 return PackageManager.SIGNATURE_NO_MATCH; 2753 } 2754 2755 // Since both signature sets are of size 1, we can compare without HashSets. 2756 if (s1.length == 1) { 2757 return s1[0].equals(s2[0]) ? 2758 PackageManager.SIGNATURE_MATCH : 2759 PackageManager.SIGNATURE_NO_MATCH; 2760 } 2761 2762 HashSet<Signature> set1 = new HashSet<Signature>(); 2763 for (Signature sig : s1) { 2764 set1.add(sig); 2765 } 2766 HashSet<Signature> set2 = new HashSet<Signature>(); 2767 for (Signature sig : s2) { 2768 set2.add(sig); 2769 } 2770 // Make sure s2 contains all signatures in s1. 2771 if (set1.equals(set2)) { 2772 return PackageManager.SIGNATURE_MATCH; 2773 } 2774 return PackageManager.SIGNATURE_NO_MATCH; 2775 } 2776 2777 /** 2778 * If the database version for this type of package (internal storage or 2779 * external storage) is less than the version where package signatures 2780 * were updated, return true. 2781 */ 2782 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2783 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2784 DatabaseVersion.SIGNATURE_END_ENTITY)) 2785 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2786 DatabaseVersion.SIGNATURE_END_ENTITY)); 2787 } 2788 2789 /** 2790 * Used for backward compatibility to make sure any packages with 2791 * certificate chains get upgraded to the new style. {@code existingSigs} 2792 * will be in the old format (since they were stored on disk from before the 2793 * system upgrade) and {@code scannedSigs} will be in the newer format. 2794 */ 2795 private int compareSignaturesCompat(PackageSignatures existingSigs, 2796 PackageParser.Package scannedPkg) { 2797 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2798 return PackageManager.SIGNATURE_NO_MATCH; 2799 } 2800 2801 HashSet<Signature> existingSet = new HashSet<Signature>(); 2802 for (Signature sig : existingSigs.mSignatures) { 2803 existingSet.add(sig); 2804 } 2805 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2806 for (Signature sig : scannedPkg.mSignatures) { 2807 try { 2808 Signature[] chainSignatures = sig.getChainSignatures(); 2809 for (Signature chainSig : chainSignatures) { 2810 scannedCompatSet.add(chainSig); 2811 } 2812 } catch (CertificateEncodingException e) { 2813 scannedCompatSet.add(sig); 2814 } 2815 } 2816 /* 2817 * Make sure the expanded scanned set contains all signatures in the 2818 * existing one. 2819 */ 2820 if (scannedCompatSet.equals(existingSet)) { 2821 // Migrate the old signatures to the new scheme. 2822 existingSigs.assignSignatures(scannedPkg.mSignatures); 2823 // The new KeySets will be re-added later in the scanning process. 2824 mSettings.mKeySetManagerService.removeAppKeySetData(scannedPkg.packageName); 2825 return PackageManager.SIGNATURE_MATCH; 2826 } 2827 return PackageManager.SIGNATURE_NO_MATCH; 2828 } 2829 2830 @Override 2831 public String[] getPackagesForUid(int uid) { 2832 uid = UserHandle.getAppId(uid); 2833 // reader 2834 synchronized (mPackages) { 2835 Object obj = mSettings.getUserIdLPr(uid); 2836 if (obj instanceof SharedUserSetting) { 2837 final SharedUserSetting sus = (SharedUserSetting) obj; 2838 final int N = sus.packages.size(); 2839 final String[] res = new String[N]; 2840 final Iterator<PackageSetting> it = sus.packages.iterator(); 2841 int i = 0; 2842 while (it.hasNext()) { 2843 res[i++] = it.next().name; 2844 } 2845 return res; 2846 } else if (obj instanceof PackageSetting) { 2847 final PackageSetting ps = (PackageSetting) obj; 2848 return new String[] { ps.name }; 2849 } 2850 } 2851 return null; 2852 } 2853 2854 @Override 2855 public String getNameForUid(int uid) { 2856 // reader 2857 synchronized (mPackages) { 2858 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2859 if (obj instanceof SharedUserSetting) { 2860 final SharedUserSetting sus = (SharedUserSetting) obj; 2861 return sus.name + ":" + sus.userId; 2862 } else if (obj instanceof PackageSetting) { 2863 final PackageSetting ps = (PackageSetting) obj; 2864 return ps.name; 2865 } 2866 } 2867 return null; 2868 } 2869 2870 @Override 2871 public int getUidForSharedUser(String sharedUserName) { 2872 if(sharedUserName == null) { 2873 return -1; 2874 } 2875 // reader 2876 synchronized (mPackages) { 2877 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2878 if (suid == null) { 2879 return -1; 2880 } 2881 return suid.userId; 2882 } 2883 } 2884 2885 @Override 2886 public int getFlagsForUid(int uid) { 2887 synchronized (mPackages) { 2888 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2889 if (obj instanceof SharedUserSetting) { 2890 final SharedUserSetting sus = (SharedUserSetting) obj; 2891 return sus.pkgFlags; 2892 } else if (obj instanceof PackageSetting) { 2893 final PackageSetting ps = (PackageSetting) obj; 2894 return ps.pkgFlags; 2895 } 2896 } 2897 return 0; 2898 } 2899 2900 @Override 2901 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2902 int flags, int userId) { 2903 if (!sUserManager.exists(userId)) return null; 2904 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2905 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2906 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2907 } 2908 2909 @Override 2910 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2911 IntentFilter filter, int match, ComponentName activity) { 2912 final int userId = UserHandle.getCallingUserId(); 2913 if (DEBUG_PREFERRED) { 2914 Log.v(TAG, "setLastChosenActivity intent=" + intent 2915 + " resolvedType=" + resolvedType 2916 + " flags=" + flags 2917 + " filter=" + filter 2918 + " match=" + match 2919 + " activity=" + activity); 2920 filter.dump(new PrintStreamPrinter(System.out), " "); 2921 } 2922 intent.setComponent(null); 2923 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2924 // Find any earlier preferred or last chosen entries and nuke them 2925 findPreferredActivity(intent, resolvedType, 2926 flags, query, 0, false, true, false, userId); 2927 // Add the new activity as the last chosen for this filter 2928 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2929 } 2930 2931 @Override 2932 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2933 final int userId = UserHandle.getCallingUserId(); 2934 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2935 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2936 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2937 false, false, false, userId); 2938 } 2939 2940 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2941 int flags, List<ResolveInfo> query, int userId) { 2942 if (query != null) { 2943 final int N = query.size(); 2944 if (N == 1) { 2945 return query.get(0); 2946 } else if (N > 1) { 2947 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2948 // If there is more than one activity with the same priority, 2949 // then let the user decide between them. 2950 ResolveInfo r0 = query.get(0); 2951 ResolveInfo r1 = query.get(1); 2952 if (DEBUG_INTENT_MATCHING || debug) { 2953 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2954 + r1.activityInfo.name + "=" + r1.priority); 2955 } 2956 // If the first activity has a higher priority, or a different 2957 // default, then it is always desireable to pick it. 2958 if (r0.priority != r1.priority 2959 || r0.preferredOrder != r1.preferredOrder 2960 || r0.isDefault != r1.isDefault) { 2961 return query.get(0); 2962 } 2963 // If we have saved a preference for a preferred activity for 2964 // this Intent, use that. 2965 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2966 flags, query, r0.priority, true, false, debug, userId); 2967 if (ri != null) { 2968 return ri; 2969 } 2970 if (userId != 0) { 2971 ri = new ResolveInfo(mResolveInfo); 2972 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2973 ri.activityInfo.applicationInfo = new ApplicationInfo( 2974 ri.activityInfo.applicationInfo); 2975 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2976 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2977 return ri; 2978 } 2979 return mResolveInfo; 2980 } 2981 } 2982 return null; 2983 } 2984 2985 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2986 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2987 final int N = query.size(); 2988 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2989 .get(userId); 2990 // Get the list of persistent preferred activities that handle the intent 2991 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2992 List<PersistentPreferredActivity> pprefs = ppir != null 2993 ? ppir.queryIntent(intent, resolvedType, 2994 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2995 : null; 2996 if (pprefs != null && pprefs.size() > 0) { 2997 final int M = pprefs.size(); 2998 for (int i=0; i<M; i++) { 2999 final PersistentPreferredActivity ppa = pprefs.get(i); 3000 if (DEBUG_PREFERRED || debug) { 3001 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3002 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3003 + "\n component=" + ppa.mComponent); 3004 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3005 } 3006 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3007 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3008 if (DEBUG_PREFERRED || debug) { 3009 Slog.v(TAG, "Found persistent preferred activity:"); 3010 if (ai != null) { 3011 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3012 } else { 3013 Slog.v(TAG, " null"); 3014 } 3015 } 3016 if (ai == null) { 3017 // This previously registered persistent preferred activity 3018 // component is no longer known. Ignore it and do NOT remove it. 3019 continue; 3020 } 3021 for (int j=0; j<N; j++) { 3022 final ResolveInfo ri = query.get(j); 3023 if (!ri.activityInfo.applicationInfo.packageName 3024 .equals(ai.applicationInfo.packageName)) { 3025 continue; 3026 } 3027 if (!ri.activityInfo.name.equals(ai.name)) { 3028 continue; 3029 } 3030 // Found a persistent preference that can handle the intent. 3031 if (DEBUG_PREFERRED || debug) { 3032 Slog.v(TAG, "Returning persistent preferred activity: " + 3033 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3034 } 3035 return ri; 3036 } 3037 } 3038 } 3039 return null; 3040 } 3041 3042 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3043 List<ResolveInfo> query, int priority, boolean always, 3044 boolean removeMatches, boolean debug, int userId) { 3045 if (!sUserManager.exists(userId)) return null; 3046 // writer 3047 synchronized (mPackages) { 3048 if (intent.getSelector() != null) { 3049 intent = intent.getSelector(); 3050 } 3051 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3052 3053 // Try to find a matching persistent preferred activity. 3054 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3055 debug, userId); 3056 3057 // If a persistent preferred activity matched, use it. 3058 if (pri != null) { 3059 return pri; 3060 } 3061 3062 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3063 // Get the list of preferred activities that handle the intent 3064 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3065 List<PreferredActivity> prefs = pir != null 3066 ? pir.queryIntent(intent, resolvedType, 3067 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3068 : null; 3069 if (prefs != null && prefs.size() > 0) { 3070 // First figure out how good the original match set is. 3071 // We will only allow preferred activities that came 3072 // from the same match quality. 3073 int match = 0; 3074 3075 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3076 3077 final int N = query.size(); 3078 for (int j=0; j<N; j++) { 3079 final ResolveInfo ri = query.get(j); 3080 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3081 + ": 0x" + Integer.toHexString(match)); 3082 if (ri.match > match) { 3083 match = ri.match; 3084 } 3085 } 3086 3087 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3088 + Integer.toHexString(match)); 3089 3090 match &= IntentFilter.MATCH_CATEGORY_MASK; 3091 final int M = prefs.size(); 3092 for (int i=0; i<M; i++) { 3093 final PreferredActivity pa = prefs.get(i); 3094 if (DEBUG_PREFERRED || debug) { 3095 Slog.v(TAG, "Checking PreferredActivity ds=" 3096 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3097 + "\n component=" + pa.mPref.mComponent); 3098 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3099 } 3100 if (pa.mPref.mMatch != match) { 3101 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3102 + Integer.toHexString(pa.mPref.mMatch)); 3103 continue; 3104 } 3105 // If it's not an "always" type preferred activity and that's what we're 3106 // looking for, skip it. 3107 if (always && !pa.mPref.mAlways) { 3108 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3109 continue; 3110 } 3111 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3112 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3113 if (DEBUG_PREFERRED || debug) { 3114 Slog.v(TAG, "Found preferred activity:"); 3115 if (ai != null) { 3116 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3117 } else { 3118 Slog.v(TAG, " null"); 3119 } 3120 } 3121 if (ai == null) { 3122 // This previously registered preferred activity 3123 // component is no longer known. Most likely an update 3124 // to the app was installed and in the new version this 3125 // component no longer exists. Clean it up by removing 3126 // it from the preferred activities list, and skip it. 3127 Slog.w(TAG, "Removing dangling preferred activity: " 3128 + pa.mPref.mComponent); 3129 pir.removeFilter(pa); 3130 continue; 3131 } 3132 for (int j=0; j<N; j++) { 3133 final ResolveInfo ri = query.get(j); 3134 if (!ri.activityInfo.applicationInfo.packageName 3135 .equals(ai.applicationInfo.packageName)) { 3136 continue; 3137 } 3138 if (!ri.activityInfo.name.equals(ai.name)) { 3139 continue; 3140 } 3141 3142 if (removeMatches) { 3143 pir.removeFilter(pa); 3144 if (DEBUG_PREFERRED) { 3145 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3146 } 3147 break; 3148 } 3149 3150 // Okay we found a previously set preferred or last chosen app. 3151 // If the result set is different from when this 3152 // was created, we need to clear it and re-ask the 3153 // user their preference, if we're looking for an "always" type entry. 3154 if (always && !pa.mPref.sameSet(query, priority)) { 3155 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3156 + intent + " type " + resolvedType); 3157 if (DEBUG_PREFERRED) { 3158 Slog.v(TAG, "Removing preferred activity since set changed " 3159 + pa.mPref.mComponent); 3160 } 3161 pir.removeFilter(pa); 3162 // Re-add the filter as a "last chosen" entry (!always) 3163 PreferredActivity lastChosen = new PreferredActivity( 3164 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3165 pir.addFilter(lastChosen); 3166 mSettings.writePackageRestrictionsLPr(userId); 3167 return null; 3168 } 3169 3170 // Yay! Either the set matched or we're looking for the last chosen 3171 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3172 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3173 mSettings.writePackageRestrictionsLPr(userId); 3174 return ri; 3175 } 3176 } 3177 } 3178 mSettings.writePackageRestrictionsLPr(userId); 3179 } 3180 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3181 return null; 3182 } 3183 3184 /* 3185 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3186 */ 3187 @Override 3188 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3189 int targetUserId) { 3190 mContext.enforceCallingOrSelfPermission( 3191 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3192 List<CrossProfileIntentFilter> matches = 3193 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3194 if (matches != null) { 3195 int size = matches.size(); 3196 for (int i = 0; i < size; i++) { 3197 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3198 } 3199 } 3200 3201 ArrayList<String> packageNames = null; 3202 SparseArray<ArrayList<String>> fromSource = 3203 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3204 if (fromSource != null) { 3205 packageNames = fromSource.get(targetUserId); 3206 } 3207 if (packageNames.contains(intent.getPackage())) { 3208 return true; 3209 } 3210 // We need the package name, so we try to resolve with the loosest flags possible 3211 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3212 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3213 int count = resolveInfos.size(); 3214 for (int i = 0; i < count; i++) { 3215 ResolveInfo resolveInfo = resolveInfos.get(i); 3216 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3217 return true; 3218 } 3219 } 3220 return false; 3221 } 3222 3223 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3224 String resolvedType, int userId) { 3225 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3226 if (resolver != null) { 3227 return resolver.queryIntent(intent, resolvedType, false, userId); 3228 } 3229 return null; 3230 } 3231 3232 @Override 3233 public List<ResolveInfo> queryIntentActivities(Intent intent, 3234 String resolvedType, int flags, int userId) { 3235 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3236 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3237 ComponentName comp = intent.getComponent(); 3238 if (comp == null) { 3239 if (intent.getSelector() != null) { 3240 intent = intent.getSelector(); 3241 comp = intent.getComponent(); 3242 } 3243 } 3244 3245 if (comp != null) { 3246 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3247 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3248 if (ai != null) { 3249 final ResolveInfo ri = new ResolveInfo(); 3250 ri.activityInfo = ai; 3251 list.add(ri); 3252 } 3253 return list; 3254 } 3255 3256 // reader 3257 synchronized (mPackages) { 3258 final String pkgName = intent.getPackage(); 3259 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3260 if (pkgName == null) { 3261 ResolveInfo resolveInfo = null; 3262 if (queryCrossProfile) { 3263 // Check if the intent needs to be forwarded to another user for this package 3264 ArrayList<ResolveInfo> crossProfileResult = 3265 queryIntentActivitiesCrossProfilePackage( 3266 intent, resolvedType, flags, userId); 3267 if (!crossProfileResult.isEmpty()) { 3268 // Skip the current profile 3269 return crossProfileResult; 3270 } 3271 List<CrossProfileIntentFilter> matchingFilters = 3272 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3273 // Check for results that need to skip the current profile. 3274 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3275 resolvedType, flags, userId); 3276 if (resolveInfo != null) { 3277 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3278 result.add(resolveInfo); 3279 return result; 3280 } 3281 // Check for cross profile results. 3282 resolveInfo = queryCrossProfileIntents( 3283 matchingFilters, intent, resolvedType, flags, userId); 3284 } 3285 // Check for results in the current profile. 3286 List<ResolveInfo> result = mActivities.queryIntent( 3287 intent, resolvedType, flags, userId); 3288 if (resolveInfo != null) { 3289 result.add(resolveInfo); 3290 } 3291 return result; 3292 } 3293 final PackageParser.Package pkg = mPackages.get(pkgName); 3294 if (pkg != null) { 3295 if (queryCrossProfile) { 3296 ArrayList<ResolveInfo> crossProfileResult = 3297 queryIntentActivitiesCrossProfilePackage( 3298 intent, resolvedType, flags, userId, pkg, pkgName); 3299 if (!crossProfileResult.isEmpty()) { 3300 // Skip the current profile 3301 return crossProfileResult; 3302 } 3303 } 3304 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3305 pkg.activities, userId); 3306 } 3307 return new ArrayList<ResolveInfo>(); 3308 } 3309 } 3310 3311 private ResolveInfo querySkipCurrentProfileIntents( 3312 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3313 int flags, int sourceUserId) { 3314 if (matchingFilters != null) { 3315 int size = matchingFilters.size(); 3316 for (int i = 0; i < size; i ++) { 3317 CrossProfileIntentFilter filter = matchingFilters.get(i); 3318 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3319 // Checking if there are activities in the target user that can handle the 3320 // intent. 3321 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3322 flags, sourceUserId); 3323 if (resolveInfo != null) { 3324 return resolveInfo; 3325 } 3326 } 3327 } 3328 } 3329 return null; 3330 } 3331 3332 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3333 Intent intent, String resolvedType, int flags, int userId) { 3334 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3335 SparseArray<ArrayList<String>> sourceForwardingInfo = 3336 mSettings.mCrossProfilePackageInfo.get(userId); 3337 if (sourceForwardingInfo != null) { 3338 int NI = sourceForwardingInfo.size(); 3339 for (int i = 0; i < NI; i++) { 3340 int targetUserId = sourceForwardingInfo.keyAt(i); 3341 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3342 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3343 intent, resolvedType, flags, targetUserId); 3344 int NJ = resolveInfos.size(); 3345 for (int j = 0; j < NJ; j++) { 3346 ResolveInfo resolveInfo = resolveInfos.get(j); 3347 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3348 matchingResolveInfos.add(createForwardingResolveInfo( 3349 resolveInfo.filter, userId, targetUserId)); 3350 } 3351 } 3352 } 3353 } 3354 return matchingResolveInfos; 3355 } 3356 3357 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3358 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3359 String packageName) { 3360 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3361 SparseArray<ArrayList<String>> sourceForwardingInfo = 3362 mSettings.mCrossProfilePackageInfo.get(userId); 3363 if (sourceForwardingInfo != null) { 3364 int NI = sourceForwardingInfo.size(); 3365 for (int i = 0; i < NI; i++) { 3366 int targetUserId = sourceForwardingInfo.keyAt(i); 3367 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3368 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3369 intent, resolvedType, flags, pkg.activities, targetUserId); 3370 int NJ = resolveInfos.size(); 3371 for (int j = 0; j < NJ; j++) { 3372 ResolveInfo resolveInfo = resolveInfos.get(j); 3373 matchingResolveInfos.add(createForwardingResolveInfo( 3374 resolveInfo.filter, userId, targetUserId)); 3375 } 3376 } 3377 } 3378 } 3379 return matchingResolveInfos; 3380 } 3381 3382 // Return matching ResolveInfo if any for skip current profile intent filters. 3383 private ResolveInfo queryCrossProfileIntents( 3384 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3385 int flags, int sourceUserId) { 3386 if (matchingFilters != null) { 3387 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3388 // match the same intent. For performance reasons, it is better not to 3389 // run queryIntent twice for the same userId 3390 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3391 int size = matchingFilters.size(); 3392 for (int i = 0; i < size; i++) { 3393 CrossProfileIntentFilter filter = matchingFilters.get(i); 3394 int targetUserId = filter.getTargetUserId(); 3395 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3396 && !alreadyTriedUserIds.get(targetUserId)) { 3397 // Checking if there are activities in the target user that can handle the 3398 // intent. 3399 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3400 flags, sourceUserId); 3401 if (resolveInfo != null) return resolveInfo; 3402 alreadyTriedUserIds.put(targetUserId, true); 3403 } 3404 } 3405 } 3406 return null; 3407 } 3408 3409 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3410 String resolvedType, int flags, int sourceUserId) { 3411 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3412 resolvedType, flags, filter.getTargetUserId()); 3413 if (resultTargetUser != null) { 3414 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3415 } 3416 return null; 3417 } 3418 3419 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3420 int sourceUserId, int targetUserId) { 3421 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3422 String className; 3423 if (targetUserId == UserHandle.USER_OWNER) { 3424 className = FORWARD_INTENT_TO_USER_OWNER; 3425 } else { 3426 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3427 } 3428 ComponentName forwardingActivityComponentName = new ComponentName( 3429 mAndroidApplication.packageName, className); 3430 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3431 sourceUserId); 3432 if (targetUserId == UserHandle.USER_OWNER) { 3433 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3434 forwardingResolveInfo.noResourceId = true; 3435 } 3436 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3437 forwardingResolveInfo.priority = 0; 3438 forwardingResolveInfo.preferredOrder = 0; 3439 forwardingResolveInfo.match = 0; 3440 forwardingResolveInfo.isDefault = true; 3441 forwardingResolveInfo.filter = filter; 3442 forwardingResolveInfo.targetUserId = targetUserId; 3443 return forwardingResolveInfo; 3444 } 3445 3446 @Override 3447 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3448 Intent[] specifics, String[] specificTypes, Intent intent, 3449 String resolvedType, int flags, int userId) { 3450 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3451 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3452 "query intent activity options"); 3453 final String resultsAction = intent.getAction(); 3454 3455 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3456 | PackageManager.GET_RESOLVED_FILTER, userId); 3457 3458 if (DEBUG_INTENT_MATCHING) { 3459 Log.v(TAG, "Query " + intent + ": " + results); 3460 } 3461 3462 int specificsPos = 0; 3463 int N; 3464 3465 // todo: note that the algorithm used here is O(N^2). This 3466 // isn't a problem in our current environment, but if we start running 3467 // into situations where we have more than 5 or 10 matches then this 3468 // should probably be changed to something smarter... 3469 3470 // First we go through and resolve each of the specific items 3471 // that were supplied, taking care of removing any corresponding 3472 // duplicate items in the generic resolve list. 3473 if (specifics != null) { 3474 for (int i=0; i<specifics.length; i++) { 3475 final Intent sintent = specifics[i]; 3476 if (sintent == null) { 3477 continue; 3478 } 3479 3480 if (DEBUG_INTENT_MATCHING) { 3481 Log.v(TAG, "Specific #" + i + ": " + sintent); 3482 } 3483 3484 String action = sintent.getAction(); 3485 if (resultsAction != null && resultsAction.equals(action)) { 3486 // If this action was explicitly requested, then don't 3487 // remove things that have it. 3488 action = null; 3489 } 3490 3491 ResolveInfo ri = null; 3492 ActivityInfo ai = null; 3493 3494 ComponentName comp = sintent.getComponent(); 3495 if (comp == null) { 3496 ri = resolveIntent( 3497 sintent, 3498 specificTypes != null ? specificTypes[i] : null, 3499 flags, userId); 3500 if (ri == null) { 3501 continue; 3502 } 3503 if (ri == mResolveInfo) { 3504 // ACK! Must do something better with this. 3505 } 3506 ai = ri.activityInfo; 3507 comp = new ComponentName(ai.applicationInfo.packageName, 3508 ai.name); 3509 } else { 3510 ai = getActivityInfo(comp, flags, userId); 3511 if (ai == null) { 3512 continue; 3513 } 3514 } 3515 3516 // Look for any generic query activities that are duplicates 3517 // of this specific one, and remove them from the results. 3518 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3519 N = results.size(); 3520 int j; 3521 for (j=specificsPos; j<N; j++) { 3522 ResolveInfo sri = results.get(j); 3523 if ((sri.activityInfo.name.equals(comp.getClassName()) 3524 && sri.activityInfo.applicationInfo.packageName.equals( 3525 comp.getPackageName())) 3526 || (action != null && sri.filter.matchAction(action))) { 3527 results.remove(j); 3528 if (DEBUG_INTENT_MATCHING) Log.v( 3529 TAG, "Removing duplicate item from " + j 3530 + " due to specific " + specificsPos); 3531 if (ri == null) { 3532 ri = sri; 3533 } 3534 j--; 3535 N--; 3536 } 3537 } 3538 3539 // Add this specific item to its proper place. 3540 if (ri == null) { 3541 ri = new ResolveInfo(); 3542 ri.activityInfo = ai; 3543 } 3544 results.add(specificsPos, ri); 3545 ri.specificIndex = i; 3546 specificsPos++; 3547 } 3548 } 3549 3550 // Now we go through the remaining generic results and remove any 3551 // duplicate actions that are found here. 3552 N = results.size(); 3553 for (int i=specificsPos; i<N-1; i++) { 3554 final ResolveInfo rii = results.get(i); 3555 if (rii.filter == null) { 3556 continue; 3557 } 3558 3559 // Iterate over all of the actions of this result's intent 3560 // filter... typically this should be just one. 3561 final Iterator<String> it = rii.filter.actionsIterator(); 3562 if (it == null) { 3563 continue; 3564 } 3565 while (it.hasNext()) { 3566 final String action = it.next(); 3567 if (resultsAction != null && resultsAction.equals(action)) { 3568 // If this action was explicitly requested, then don't 3569 // remove things that have it. 3570 continue; 3571 } 3572 for (int j=i+1; j<N; j++) { 3573 final ResolveInfo rij = results.get(j); 3574 if (rij.filter != null && rij.filter.hasAction(action)) { 3575 results.remove(j); 3576 if (DEBUG_INTENT_MATCHING) Log.v( 3577 TAG, "Removing duplicate item from " + j 3578 + " due to action " + action + " at " + i); 3579 j--; 3580 N--; 3581 } 3582 } 3583 } 3584 3585 // If the caller didn't request filter information, drop it now 3586 // so we don't have to marshall/unmarshall it. 3587 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3588 rii.filter = null; 3589 } 3590 } 3591 3592 // Filter out the caller activity if so requested. 3593 if (caller != null) { 3594 N = results.size(); 3595 for (int i=0; i<N; i++) { 3596 ActivityInfo ainfo = results.get(i).activityInfo; 3597 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3598 && caller.getClassName().equals(ainfo.name)) { 3599 results.remove(i); 3600 break; 3601 } 3602 } 3603 } 3604 3605 // If the caller didn't request filter information, 3606 // drop them now so we don't have to 3607 // marshall/unmarshall it. 3608 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3609 N = results.size(); 3610 for (int i=0; i<N; i++) { 3611 results.get(i).filter = null; 3612 } 3613 } 3614 3615 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3616 return results; 3617 } 3618 3619 @Override 3620 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3621 int userId) { 3622 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3623 ComponentName comp = intent.getComponent(); 3624 if (comp == null) { 3625 if (intent.getSelector() != null) { 3626 intent = intent.getSelector(); 3627 comp = intent.getComponent(); 3628 } 3629 } 3630 if (comp != null) { 3631 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3632 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3633 if (ai != null) { 3634 ResolveInfo ri = new ResolveInfo(); 3635 ri.activityInfo = ai; 3636 list.add(ri); 3637 } 3638 return list; 3639 } 3640 3641 // reader 3642 synchronized (mPackages) { 3643 String pkgName = intent.getPackage(); 3644 if (pkgName == null) { 3645 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3646 } 3647 final PackageParser.Package pkg = mPackages.get(pkgName); 3648 if (pkg != null) { 3649 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3650 userId); 3651 } 3652 return null; 3653 } 3654 } 3655 3656 @Override 3657 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3658 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3659 if (!sUserManager.exists(userId)) return null; 3660 if (query != null) { 3661 if (query.size() >= 1) { 3662 // If there is more than one service with the same priority, 3663 // just arbitrarily pick the first one. 3664 return query.get(0); 3665 } 3666 } 3667 return null; 3668 } 3669 3670 @Override 3671 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3672 int userId) { 3673 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3674 ComponentName comp = intent.getComponent(); 3675 if (comp == null) { 3676 if (intent.getSelector() != null) { 3677 intent = intent.getSelector(); 3678 comp = intent.getComponent(); 3679 } 3680 } 3681 if (comp != null) { 3682 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3683 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3684 if (si != null) { 3685 final ResolveInfo ri = new ResolveInfo(); 3686 ri.serviceInfo = si; 3687 list.add(ri); 3688 } 3689 return list; 3690 } 3691 3692 // reader 3693 synchronized (mPackages) { 3694 String pkgName = intent.getPackage(); 3695 if (pkgName == null) { 3696 return mServices.queryIntent(intent, resolvedType, flags, userId); 3697 } 3698 final PackageParser.Package pkg = mPackages.get(pkgName); 3699 if (pkg != null) { 3700 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3701 userId); 3702 } 3703 return null; 3704 } 3705 } 3706 3707 @Override 3708 public List<ResolveInfo> queryIntentContentProviders( 3709 Intent intent, String resolvedType, int flags, int userId) { 3710 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3711 ComponentName comp = intent.getComponent(); 3712 if (comp == null) { 3713 if (intent.getSelector() != null) { 3714 intent = intent.getSelector(); 3715 comp = intent.getComponent(); 3716 } 3717 } 3718 if (comp != null) { 3719 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3720 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3721 if (pi != null) { 3722 final ResolveInfo ri = new ResolveInfo(); 3723 ri.providerInfo = pi; 3724 list.add(ri); 3725 } 3726 return list; 3727 } 3728 3729 // reader 3730 synchronized (mPackages) { 3731 String pkgName = intent.getPackage(); 3732 if (pkgName == null) { 3733 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3734 } 3735 final PackageParser.Package pkg = mPackages.get(pkgName); 3736 if (pkg != null) { 3737 return mProviders.queryIntentForPackage( 3738 intent, resolvedType, flags, pkg.providers, userId); 3739 } 3740 return null; 3741 } 3742 } 3743 3744 @Override 3745 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3746 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3747 3748 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3749 3750 // writer 3751 synchronized (mPackages) { 3752 ArrayList<PackageInfo> list; 3753 if (listUninstalled) { 3754 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3755 for (PackageSetting ps : mSettings.mPackages.values()) { 3756 PackageInfo pi; 3757 if (ps.pkg != null) { 3758 pi = generatePackageInfo(ps.pkg, flags, userId); 3759 } else { 3760 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3761 } 3762 if (pi != null) { 3763 list.add(pi); 3764 } 3765 } 3766 } else { 3767 list = new ArrayList<PackageInfo>(mPackages.size()); 3768 for (PackageParser.Package p : mPackages.values()) { 3769 PackageInfo pi = generatePackageInfo(p, flags, userId); 3770 if (pi != null) { 3771 list.add(pi); 3772 } 3773 } 3774 } 3775 3776 return new ParceledListSlice<PackageInfo>(list); 3777 } 3778 } 3779 3780 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3781 String[] permissions, boolean[] tmp, int flags, int userId) { 3782 int numMatch = 0; 3783 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3784 for (int i=0; i<permissions.length; i++) { 3785 if (gp.grantedPermissions.contains(permissions[i])) { 3786 tmp[i] = true; 3787 numMatch++; 3788 } else { 3789 tmp[i] = false; 3790 } 3791 } 3792 if (numMatch == 0) { 3793 return; 3794 } 3795 PackageInfo pi; 3796 if (ps.pkg != null) { 3797 pi = generatePackageInfo(ps.pkg, flags, userId); 3798 } else { 3799 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3800 } 3801 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3802 if (numMatch == permissions.length) { 3803 pi.requestedPermissions = permissions; 3804 } else { 3805 pi.requestedPermissions = new String[numMatch]; 3806 numMatch = 0; 3807 for (int i=0; i<permissions.length; i++) { 3808 if (tmp[i]) { 3809 pi.requestedPermissions[numMatch] = permissions[i]; 3810 numMatch++; 3811 } 3812 } 3813 } 3814 } 3815 list.add(pi); 3816 } 3817 3818 @Override 3819 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3820 String[] permissions, int flags, int userId) { 3821 if (!sUserManager.exists(userId)) return null; 3822 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3823 3824 // writer 3825 synchronized (mPackages) { 3826 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3827 boolean[] tmpBools = new boolean[permissions.length]; 3828 if (listUninstalled) { 3829 for (PackageSetting ps : mSettings.mPackages.values()) { 3830 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3831 } 3832 } else { 3833 for (PackageParser.Package pkg : mPackages.values()) { 3834 PackageSetting ps = (PackageSetting)pkg.mExtras; 3835 if (ps != null) { 3836 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3837 userId); 3838 } 3839 } 3840 } 3841 3842 return new ParceledListSlice<PackageInfo>(list); 3843 } 3844 } 3845 3846 @Override 3847 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3848 if (!sUserManager.exists(userId)) return null; 3849 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3850 3851 // writer 3852 synchronized (mPackages) { 3853 ArrayList<ApplicationInfo> list; 3854 if (listUninstalled) { 3855 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3856 for (PackageSetting ps : mSettings.mPackages.values()) { 3857 ApplicationInfo ai; 3858 if (ps.pkg != null) { 3859 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3860 ps.readUserState(userId), userId); 3861 } else { 3862 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3863 } 3864 if (ai != null) { 3865 list.add(ai); 3866 } 3867 } 3868 } else { 3869 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3870 for (PackageParser.Package p : mPackages.values()) { 3871 if (p.mExtras != null) { 3872 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3873 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3874 if (ai != null) { 3875 list.add(ai); 3876 } 3877 } 3878 } 3879 } 3880 3881 return new ParceledListSlice<ApplicationInfo>(list); 3882 } 3883 } 3884 3885 public List<ApplicationInfo> getPersistentApplications(int flags) { 3886 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3887 3888 // reader 3889 synchronized (mPackages) { 3890 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3891 final int userId = UserHandle.getCallingUserId(); 3892 while (i.hasNext()) { 3893 final PackageParser.Package p = i.next(); 3894 if (p.applicationInfo != null 3895 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3896 && (!mSafeMode || isSystemApp(p))) { 3897 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3898 if (ps != null) { 3899 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3900 ps.readUserState(userId), userId); 3901 if (ai != null) { 3902 finalList.add(ai); 3903 } 3904 } 3905 } 3906 } 3907 } 3908 3909 return finalList; 3910 } 3911 3912 @Override 3913 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3914 if (!sUserManager.exists(userId)) return null; 3915 // reader 3916 synchronized (mPackages) { 3917 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3918 PackageSetting ps = provider != null 3919 ? mSettings.mPackages.get(provider.owner.packageName) 3920 : null; 3921 return ps != null 3922 && mSettings.isEnabledLPr(provider.info, flags, userId) 3923 && (!mSafeMode || (provider.info.applicationInfo.flags 3924 &ApplicationInfo.FLAG_SYSTEM) != 0) 3925 ? PackageParser.generateProviderInfo(provider, flags, 3926 ps.readUserState(userId), userId) 3927 : null; 3928 } 3929 } 3930 3931 /** 3932 * @deprecated 3933 */ 3934 @Deprecated 3935 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3936 // reader 3937 synchronized (mPackages) { 3938 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3939 .entrySet().iterator(); 3940 final int userId = UserHandle.getCallingUserId(); 3941 while (i.hasNext()) { 3942 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3943 PackageParser.Provider p = entry.getValue(); 3944 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3945 3946 if (ps != null && p.syncable 3947 && (!mSafeMode || (p.info.applicationInfo.flags 3948 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3949 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3950 ps.readUserState(userId), userId); 3951 if (info != null) { 3952 outNames.add(entry.getKey()); 3953 outInfo.add(info); 3954 } 3955 } 3956 } 3957 } 3958 } 3959 3960 @Override 3961 public List<ProviderInfo> queryContentProviders(String processName, 3962 int uid, int flags) { 3963 ArrayList<ProviderInfo> finalList = null; 3964 // reader 3965 synchronized (mPackages) { 3966 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3967 final int userId = processName != null ? 3968 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3969 while (i.hasNext()) { 3970 final PackageParser.Provider p = i.next(); 3971 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3972 if (ps != null && p.info.authority != null 3973 && (processName == null 3974 || (p.info.processName.equals(processName) 3975 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3976 && mSettings.isEnabledLPr(p.info, flags, userId) 3977 && (!mSafeMode 3978 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3979 if (finalList == null) { 3980 finalList = new ArrayList<ProviderInfo>(3); 3981 } 3982 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3983 ps.readUserState(userId), userId); 3984 if (info != null) { 3985 finalList.add(info); 3986 } 3987 } 3988 } 3989 } 3990 3991 if (finalList != null) { 3992 Collections.sort(finalList, mProviderInitOrderSorter); 3993 } 3994 3995 return finalList; 3996 } 3997 3998 @Override 3999 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4000 int flags) { 4001 // reader 4002 synchronized (mPackages) { 4003 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4004 return PackageParser.generateInstrumentationInfo(i, flags); 4005 } 4006 } 4007 4008 @Override 4009 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4010 int flags) { 4011 ArrayList<InstrumentationInfo> finalList = 4012 new ArrayList<InstrumentationInfo>(); 4013 4014 // reader 4015 synchronized (mPackages) { 4016 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4017 while (i.hasNext()) { 4018 final PackageParser.Instrumentation p = i.next(); 4019 if (targetPackage == null 4020 || targetPackage.equals(p.info.targetPackage)) { 4021 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4022 flags); 4023 if (ii != null) { 4024 finalList.add(ii); 4025 } 4026 } 4027 } 4028 } 4029 4030 return finalList; 4031 } 4032 4033 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4034 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4035 if (overlays == null) { 4036 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4037 return; 4038 } 4039 for (PackageParser.Package opkg : overlays.values()) { 4040 // Not much to do if idmap fails: we already logged the error 4041 // and we certainly don't want to abort installation of pkg simply 4042 // because an overlay didn't fit properly. For these reasons, 4043 // ignore the return value of createIdmapForPackagePairLI. 4044 createIdmapForPackagePairLI(pkg, opkg); 4045 } 4046 } 4047 4048 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4049 PackageParser.Package opkg) { 4050 if (!opkg.mTrustedOverlay) { 4051 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4052 opkg.baseCodePath + ": overlay not trusted"); 4053 return false; 4054 } 4055 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4056 if (overlaySet == null) { 4057 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4058 opkg.baseCodePath + " but target package has no known overlays"); 4059 return false; 4060 } 4061 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4062 // TODO: generate idmap for split APKs 4063 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4064 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4065 + opkg.baseCodePath); 4066 return false; 4067 } 4068 PackageParser.Package[] overlayArray = 4069 overlaySet.values().toArray(new PackageParser.Package[0]); 4070 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4071 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4072 return p1.mOverlayPriority - p2.mOverlayPriority; 4073 } 4074 }; 4075 Arrays.sort(overlayArray, cmp); 4076 4077 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4078 int i = 0; 4079 for (PackageParser.Package p : overlayArray) { 4080 pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir; 4081 } 4082 return true; 4083 } 4084 4085 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4086 final File[] files = dir.listFiles(); 4087 if (ArrayUtils.isEmpty(files)) { 4088 Log.d(TAG, "No files in app dir " + dir); 4089 return; 4090 } 4091 4092 if (DEBUG_PACKAGE_SCANNING) { 4093 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4094 + " flags=0x" + Integer.toHexString(flags)); 4095 } 4096 4097 for (File file : files) { 4098 if (!isApkFile(file)) { 4099 // Ignore entries which are not apk's 4100 continue; 4101 } 4102 PackageParser.Package pkg = scanPackageLI(file, 4103 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null); 4104 // Don't mess around with apps in system partition. 4105 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4106 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 4107 // Delete the apk 4108 Slog.w(TAG, "Cleaning up failed install of " + file); 4109 file.delete(); 4110 } 4111 } 4112 } 4113 4114 private static File getSettingsProblemFile() { 4115 File dataDir = Environment.getDataDirectory(); 4116 File systemDir = new File(dataDir, "system"); 4117 File fname = new File(systemDir, "uiderrors.txt"); 4118 return fname; 4119 } 4120 4121 static void reportSettingsProblem(int priority, String msg) { 4122 try { 4123 File fname = getSettingsProblemFile(); 4124 FileOutputStream out = new FileOutputStream(fname, true); 4125 PrintWriter pw = new FastPrintWriter(out); 4126 SimpleDateFormat formatter = new SimpleDateFormat(); 4127 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4128 pw.println(dateString + ": " + msg); 4129 pw.close(); 4130 FileUtils.setPermissions( 4131 fname.toString(), 4132 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4133 -1, -1); 4134 } catch (java.io.IOException e) { 4135 } 4136 Slog.println(priority, TAG, msg); 4137 } 4138 4139 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 4140 PackageParser.Package pkg, File srcFile, int parseFlags) { 4141 if (ps != null 4142 && ps.codePath.equals(srcFile) 4143 && ps.timeStamp == srcFile.lastModified() 4144 && !isCompatSignatureUpdateNeeded(pkg)) { 4145 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4146 if (ps.signatures.mSignatures != null 4147 && ps.signatures.mSignatures.length != 0 4148 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4149 // Optimization: reuse the existing cached certificates 4150 // if the package appears to be unchanged. 4151 pkg.mSignatures = ps.signatures.mSignatures; 4152 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4153 pkg.mSigningKeys = ksms.getPublicKeysFromKeySet(mSigningKeySetId); 4154 return true; 4155 } 4156 4157 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 4158 } else { 4159 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4160 } 4161 4162 try { 4163 pp.collectCertificates(pkg, parseFlags); 4164 pp.collectManifestDigest(pkg); 4165 } catch (PackageParserException e) { 4166 mLastScanError = e.error; 4167 return false; 4168 } 4169 return true; 4170 } 4171 4172 /* 4173 * Scan a package and return the newly parsed package. 4174 * Returns null in case of errors and the error code is stored in mLastScanError 4175 */ 4176 private PackageParser.Package scanPackageLI(File scanFile, 4177 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4178 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 4179 String scanPath = scanFile.getPath(); 4180 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath); 4181 parseFlags |= mDefParseFlags; 4182 PackageParser pp = new PackageParser(); 4183 pp.setSeparateProcesses(mSeparateProcesses); 4184 pp.setOnlyCoreApps(mOnlyCore); 4185 pp.setDisplayMetrics(mMetrics); 4186 4187 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4188 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4189 } 4190 4191 final PackageParser.Package pkg; 4192 try { 4193 pkg = pp.parseMonolithicPackage(scanFile, parseFlags); 4194 } catch (PackageParserException e) { 4195 mLastScanError = e.error; 4196 return null; 4197 } 4198 4199 PackageSetting ps = null; 4200 PackageSetting updatedPkg; 4201 // reader 4202 synchronized (mPackages) { 4203 // Look to see if we already know about this package. 4204 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4205 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4206 // This package has been renamed to its original name. Let's 4207 // use that. 4208 ps = mSettings.peekPackageLPr(oldName); 4209 } 4210 // If there was no original package, see one for the real package name. 4211 if (ps == null) { 4212 ps = mSettings.peekPackageLPr(pkg.packageName); 4213 } 4214 // Check to see if this package could be hiding/updating a system 4215 // package. Must look for it either under the original or real 4216 // package name depending on our state. 4217 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4218 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4219 } 4220 boolean updatedPkgBetter = false; 4221 // First check if this is a system package that may involve an update 4222 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4223 if (ps != null && !ps.codePath.equals(scanFile)) { 4224 // The path has changed from what was last scanned... check the 4225 // version of the new path against what we have stored to determine 4226 // what to do. 4227 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4228 if (pkg.mVersionCode < ps.versionCode) { 4229 // The system package has been updated and the code path does not match 4230 // Ignore entry. Skip it. 4231 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4232 + " ignored: updated version " + ps.versionCode 4233 + " better than this " + pkg.mVersionCode); 4234 if (!updatedPkg.codePath.equals(scanFile)) { 4235 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4236 + ps.name + " changing from " + updatedPkg.codePathString 4237 + " to " + scanFile); 4238 updatedPkg.codePath = scanFile; 4239 updatedPkg.codePathString = scanFile.toString(); 4240 // This is the point at which we know that the system-disk APK 4241 // for this package has moved during a reboot (e.g. due to an OTA), 4242 // so we need to reevaluate it for privilege policy. 4243 if (locationIsPrivileged(scanFile)) { 4244 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4245 } 4246 } 4247 updatedPkg.pkg = pkg; 4248 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4249 return null; 4250 } else { 4251 // The current app on the system partition is better than 4252 // what we have updated to on the data partition; switch 4253 // back to the system partition version. 4254 // At this point, its safely assumed that package installation for 4255 // apps in system partition will go through. If not there won't be a working 4256 // version of the app 4257 // writer 4258 synchronized (mPackages) { 4259 // Just remove the loaded entries from package lists. 4260 mPackages.remove(ps.name); 4261 } 4262 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4263 + "reverting from " + ps.codePathString 4264 + ": new version " + pkg.mVersionCode 4265 + " better than installed " + ps.versionCode); 4266 4267 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4268 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4269 getAppInstructionSetFromSettings(ps)); 4270 synchronized (mInstallLock) { 4271 args.cleanUpResourcesLI(); 4272 } 4273 synchronized (mPackages) { 4274 mSettings.enableSystemPackageLPw(ps.name); 4275 } 4276 updatedPkgBetter = true; 4277 } 4278 } 4279 } 4280 4281 if (updatedPkg != null) { 4282 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4283 // initially 4284 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4285 4286 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4287 // flag set initially 4288 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4289 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4290 } 4291 } 4292 // Verify certificates against what was last scanned 4293 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 4294 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 4295 return null; 4296 } 4297 4298 /* 4299 * A new system app appeared, but we already had a non-system one of the 4300 * same name installed earlier. 4301 */ 4302 boolean shouldHideSystemApp = false; 4303 if (updatedPkg == null && ps != null 4304 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4305 /* 4306 * Check to make sure the signatures match first. If they don't, 4307 * wipe the installed application and its data. 4308 */ 4309 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4310 != PackageManager.SIGNATURE_MATCH) { 4311 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4312 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4313 ps = null; 4314 } else { 4315 /* 4316 * If the newly-added system app is an older version than the 4317 * already installed version, hide it. It will be scanned later 4318 * and re-added like an update. 4319 */ 4320 if (pkg.mVersionCode < ps.versionCode) { 4321 shouldHideSystemApp = true; 4322 } else { 4323 /* 4324 * The newly found system app is a newer version that the 4325 * one previously installed. Simply remove the 4326 * already-installed application and replace it with our own 4327 * while keeping the application data. 4328 */ 4329 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4330 + ps.codePathString + ": new version " + pkg.mVersionCode 4331 + " better than installed " + ps.versionCode); 4332 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4333 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4334 getAppInstructionSetFromSettings(ps)); 4335 synchronized (mInstallLock) { 4336 args.cleanUpResourcesLI(); 4337 } 4338 } 4339 } 4340 } 4341 4342 // The apk is forward locked (not public) if its code and resources 4343 // are kept in different files. (except for app in either system or 4344 // vendor path). 4345 // TODO grab this value from PackageSettings 4346 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4347 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4348 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4349 } 4350 } 4351 4352 final String baseCodePath = pkg.baseCodePath; 4353 final String[] splitCodePaths = pkg.splitCodePaths; 4354 4355 // TODO: extend to support forward-locked splits 4356 String baseResPath = null; 4357 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4358 if (ps != null && ps.resourcePathString != null) { 4359 baseResPath = ps.resourcePathString; 4360 } else { 4361 // Should not happen at all. Just log an error. 4362 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4363 } 4364 } else { 4365 baseResPath = pkg.baseCodePath; 4366 } 4367 4368 // Set application objects path explicitly. 4369 pkg.applicationInfo.sourceDir = baseCodePath; 4370 pkg.applicationInfo.publicSourceDir = baseResPath; 4371 pkg.applicationInfo.splitSourceDirs = splitCodePaths; 4372 pkg.applicationInfo.splitPublicSourceDirs = splitCodePaths; 4373 4374 // Note that we invoke the following method only if we are about to unpack an application 4375 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4376 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4377 4378 /* 4379 * If the system app should be overridden by a previously installed 4380 * data, hide the system app now and let the /data/app scan pick it up 4381 * again. 4382 */ 4383 if (shouldHideSystemApp) { 4384 synchronized (mPackages) { 4385 /* 4386 * We have to grant systems permissions before we hide, because 4387 * grantPermissions will assume the package update is trying to 4388 * expand its permissions. 4389 */ 4390 grantPermissionsLPw(pkg, true); 4391 mSettings.disableSystemPackageLPw(pkg.packageName); 4392 } 4393 } 4394 4395 return scannedPkg; 4396 } 4397 4398 private static String fixProcessName(String defProcessName, 4399 String processName, int uid) { 4400 if (processName == null) { 4401 return defProcessName; 4402 } 4403 return processName; 4404 } 4405 4406 private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) { 4407 if (pkgSetting.signatures.mSignatures != null) { 4408 // Already existing package. Make sure signatures match 4409 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4410 == PackageManager.SIGNATURE_MATCH; 4411 if (!match) { 4412 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4413 == PackageManager.SIGNATURE_MATCH; 4414 } 4415 if (!match) { 4416 Slog.e(TAG, "Package " + pkg.packageName 4417 + " signatures do not match the previously installed version; ignoring!"); 4418 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4419 return false; 4420 } 4421 } 4422 4423 // Check for shared user signatures 4424 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4425 // Already existing package. Make sure signatures match 4426 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4427 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4428 if (!match) { 4429 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4430 == PackageManager.SIGNATURE_MATCH; 4431 } 4432 if (!match) { 4433 Slog.e(TAG, "Package " + pkg.packageName 4434 + " has no signatures that match those in shared user " 4435 + pkgSetting.sharedUser.name + "; ignoring!"); 4436 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4437 return false; 4438 } 4439 } 4440 return true; 4441 } 4442 4443 /** 4444 * Enforces that only the system UID or root's UID can call a method exposed 4445 * via Binder. 4446 * 4447 * @param message used as message if SecurityException is thrown 4448 * @throws SecurityException if the caller is not system or root 4449 */ 4450 private static final void enforceSystemOrRoot(String message) { 4451 final int uid = Binder.getCallingUid(); 4452 if (uid != Process.SYSTEM_UID && uid != 0) { 4453 throw new SecurityException(message); 4454 } 4455 } 4456 4457 @Override 4458 public void performBootDexOpt() { 4459 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4460 4461 final HashSet<PackageParser.Package> pkgs; 4462 synchronized (mPackages) { 4463 pkgs = mDeferredDexOpt; 4464 mDeferredDexOpt = null; 4465 } 4466 4467 if (pkgs != null) { 4468 // Filter out packages that aren't recently used. 4469 // 4470 // The exception is first boot of a non-eng device, which 4471 // should do a full dexopt. 4472 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4473 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4474 // TODO: add a property to control this? 4475 long dexOptLRUThresholdInMinutes; 4476 if (eng) { 4477 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4478 } else { 4479 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4480 } 4481 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4482 4483 int total = pkgs.size(); 4484 int skipped = 0; 4485 long now = System.currentTimeMillis(); 4486 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4487 PackageParser.Package pkg = i.next(); 4488 long then = pkg.mLastPackageUsageTimeInMills; 4489 if (then + dexOptLRUThresholdInMills < now) { 4490 if (DEBUG_DEXOPT) { 4491 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4492 ((then == 0) ? "never" : new Date(then))); 4493 } 4494 i.remove(); 4495 skipped++; 4496 } 4497 } 4498 if (DEBUG_DEXOPT) { 4499 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4500 } 4501 } 4502 4503 int i = 0; 4504 for (PackageParser.Package pkg : pkgs) { 4505 i++; 4506 if (DEBUG_DEXOPT) { 4507 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4508 + ": " + pkg.packageName); 4509 } 4510 if (!isFirstBoot()) { 4511 try { 4512 ActivityManagerNative.getDefault().showBootMessage( 4513 mContext.getResources().getString( 4514 R.string.android_upgrading_apk, 4515 i, pkgs.size()), true); 4516 } catch (RemoteException e) { 4517 } 4518 } 4519 PackageParser.Package p = pkg; 4520 synchronized (mInstallLock) { 4521 if (p.mDexOptNeeded) { 4522 performDexOptLI(p, false /* force dex */, false /* defer */, 4523 true /* include dependencies */); 4524 } 4525 } 4526 } 4527 } 4528 } 4529 4530 @Override 4531 public boolean performDexOpt(String packageName) { 4532 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4533 return performDexOpt(packageName, true); 4534 } 4535 4536 public boolean performDexOpt(String packageName, boolean updateUsage) { 4537 4538 PackageParser.Package p; 4539 synchronized (mPackages) { 4540 p = mPackages.get(packageName); 4541 if (p == null) { 4542 return false; 4543 } 4544 if (updateUsage) { 4545 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4546 } 4547 mPackageUsage.write(false); 4548 if (!p.mDexOptNeeded) { 4549 return false; 4550 } 4551 } 4552 4553 synchronized (mInstallLock) { 4554 return performDexOptLI(p, false /* force dex */, false /* defer */, 4555 true /* include dependencies */) == DEX_OPT_PERFORMED; 4556 } 4557 } 4558 4559 public HashSet<String> getPackagesThatNeedDexOpt() { 4560 HashSet<String> pkgs = null; 4561 synchronized (mPackages) { 4562 for (PackageParser.Package p : mPackages.values()) { 4563 if (DEBUG_DEXOPT) { 4564 Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded); 4565 } 4566 if (!p.mDexOptNeeded) { 4567 continue; 4568 } 4569 if (pkgs == null) { 4570 pkgs = new HashSet<String>(); 4571 } 4572 pkgs.add(p.packageName); 4573 } 4574 } 4575 return pkgs; 4576 } 4577 4578 public void shutdown() { 4579 mPackageUsage.write(true); 4580 } 4581 4582 private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, 4583 boolean forceDex, boolean defer, HashSet<String> done) { 4584 for (int i=0; i<libs.size(); i++) { 4585 PackageParser.Package libPkg; 4586 String libName; 4587 synchronized (mPackages) { 4588 libName = libs.get(i); 4589 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4590 if (lib != null && lib.apk != null) { 4591 libPkg = mPackages.get(lib.apk); 4592 } else { 4593 libPkg = null; 4594 } 4595 } 4596 if (libPkg != null && !done.contains(libName)) { 4597 performDexOptLI(libPkg, instructionSet, forceDex, defer, done); 4598 } 4599 } 4600 } 4601 4602 static final int DEX_OPT_SKIPPED = 0; 4603 static final int DEX_OPT_PERFORMED = 1; 4604 static final int DEX_OPT_DEFERRED = 2; 4605 static final int DEX_OPT_FAILED = -1; 4606 4607 private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride, 4608 boolean forceDex, boolean defer, HashSet<String> done) { 4609 final String instructionSet = instructionSetOverride != null ? 4610 instructionSetOverride : getAppInstructionSet(pkg.applicationInfo); 4611 4612 if (done != null) { 4613 done.add(pkg.packageName); 4614 if (pkg.usesLibraries != null) { 4615 performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done); 4616 } 4617 if (pkg.usesOptionalLibraries != null) { 4618 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done); 4619 } 4620 } 4621 4622 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) { 4623 final Collection<String> paths = pkg.getAllCodePaths(); 4624 for (String path : paths) { 4625 try { 4626 boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path, 4627 pkg.packageName, instructionSet, defer); 4628 // There are three basic cases here: 4629 // 1.) we need to dexopt, either because we are forced or it is needed 4630 // 2.) we are defering a needed dexopt 4631 // 3.) we are skipping an unneeded dexopt 4632 if (forceDex || (!defer && isDexOptNeededInternal)) { 4633 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName); 4634 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4635 int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4636 pkg.packageName, instructionSet); 4637 // Note that we ran dexopt, since rerunning will 4638 // probably just result in an error again. 4639 pkg.mDexOptNeeded = false; 4640 if (ret < 0) { 4641 return DEX_OPT_FAILED; 4642 } 4643 return DEX_OPT_PERFORMED; 4644 } 4645 if (defer && isDexOptNeededInternal) { 4646 if (mDeferredDexOpt == null) { 4647 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4648 } 4649 mDeferredDexOpt.add(pkg); 4650 return DEX_OPT_DEFERRED; 4651 } 4652 pkg.mDexOptNeeded = false; 4653 return DEX_OPT_SKIPPED; 4654 } catch (FileNotFoundException e) { 4655 Slog.w(TAG, "Apk not found for dexopt: " + path); 4656 return DEX_OPT_FAILED; 4657 } catch (IOException e) { 4658 Slog.w(TAG, "IOException reading apk: " + path, e); 4659 return DEX_OPT_FAILED; 4660 } catch (StaleDexCacheError e) { 4661 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4662 return DEX_OPT_FAILED; 4663 } catch (Exception e) { 4664 Slog.w(TAG, "Exception when doing dexopt : ", e); 4665 return DEX_OPT_FAILED; 4666 } 4667 } 4668 } 4669 return DEX_OPT_SKIPPED; 4670 } 4671 4672 private String getAppInstructionSet(ApplicationInfo info) { 4673 String instructionSet = getPreferredInstructionSet(); 4674 4675 if (info.cpuAbi != null) { 4676 instructionSet = VMRuntime.getInstructionSet(info.cpuAbi); 4677 } 4678 4679 return instructionSet; 4680 } 4681 4682 private String getAppInstructionSetFromSettings(PackageSetting ps) { 4683 String instructionSet = getPreferredInstructionSet(); 4684 4685 if (ps.cpuAbiString != null) { 4686 instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 4687 } 4688 4689 return instructionSet; 4690 } 4691 4692 private static String getPreferredInstructionSet() { 4693 if (sPreferredInstructionSet == null) { 4694 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4695 } 4696 4697 return sPreferredInstructionSet; 4698 } 4699 4700 private static List<String> getAllInstructionSets() { 4701 final String[] allAbis = Build.SUPPORTED_ABIS; 4702 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4703 4704 for (String abi : allAbis) { 4705 final String instructionSet = VMRuntime.getInstructionSet(abi); 4706 if (!allInstructionSets.contains(instructionSet)) { 4707 allInstructionSets.add(instructionSet); 4708 } 4709 } 4710 4711 return allInstructionSets; 4712 } 4713 4714 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4715 boolean inclDependencies) { 4716 HashSet<String> done; 4717 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4718 done = new HashSet<String>(); 4719 done.add(pkg.packageName); 4720 } else { 4721 done = null; 4722 } 4723 return performDexOptLI(pkg, null /* instruction set override */, forceDex, defer, done); 4724 } 4725 4726 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4727 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4728 Slog.w(TAG, "Unable to update from " + oldPkg.name 4729 + " to " + newPkg.packageName 4730 + ": old package not in system partition"); 4731 return false; 4732 } else if (mPackages.get(oldPkg.name) != null) { 4733 Slog.w(TAG, "Unable to update from " + oldPkg.name 4734 + " to " + newPkg.packageName 4735 + ": old package still exists"); 4736 return false; 4737 } 4738 return true; 4739 } 4740 4741 File getDataPathForUser(int userId) { 4742 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4743 } 4744 4745 private File getDataPathForPackage(String packageName, int userId) { 4746 /* 4747 * Until we fully support multiple users, return the directory we 4748 * previously would have. The PackageManagerTests will need to be 4749 * revised when this is changed back.. 4750 */ 4751 if (userId == 0) { 4752 return new File(mAppDataDir, packageName); 4753 } else { 4754 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4755 + File.separator + packageName); 4756 } 4757 } 4758 4759 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4760 int[] users = sUserManager.getUserIds(); 4761 int res = mInstaller.install(packageName, uid, uid, seinfo); 4762 if (res < 0) { 4763 return res; 4764 } 4765 for (int user : users) { 4766 if (user != 0) { 4767 res = mInstaller.createUserData(packageName, 4768 UserHandle.getUid(user, uid), user, seinfo); 4769 if (res < 0) { 4770 return res; 4771 } 4772 } 4773 } 4774 return res; 4775 } 4776 4777 private int removeDataDirsLI(String packageName) { 4778 int[] users = sUserManager.getUserIds(); 4779 int res = 0; 4780 for (int user : users) { 4781 int resInner = mInstaller.remove(packageName, user); 4782 if (resInner < 0) { 4783 res = resInner; 4784 } 4785 } 4786 4787 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4788 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4789 if (!nativeLibraryFile.delete()) { 4790 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4791 } 4792 4793 return res; 4794 } 4795 4796 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4797 PackageParser.Package changingLib) { 4798 if (file.path != null) { 4799 usesLibraryFiles.add(file.path); 4800 return; 4801 } 4802 PackageParser.Package p = mPackages.get(file.apk); 4803 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4804 // If we are doing this while in the middle of updating a library apk, 4805 // then we need to make sure to use that new apk for determining the 4806 // dependencies here. (We haven't yet finished committing the new apk 4807 // to the package manager state.) 4808 if (p == null || p.packageName.equals(changingLib.packageName)) { 4809 p = changingLib; 4810 } 4811 } 4812 if (p != null) { 4813 usesLibraryFiles.addAll(p.getAllCodePaths()); 4814 } 4815 } 4816 4817 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4818 PackageParser.Package changingLib) { 4819 // We might be upgrading from a version of the platform that did not 4820 // provide per-package native library directories for system apps. 4821 // Fix that up here. 4822 if (isSystemApp(pkg)) { 4823 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4824 setInternalAppNativeLibraryPath(pkg, ps); 4825 } 4826 4827 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4828 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4829 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4830 for (int i=0; i<N; i++) { 4831 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4832 if (file == null) { 4833 Slog.e(TAG, "Package " + pkg.packageName 4834 + " requires unavailable shared library " 4835 + pkg.usesLibraries.get(i) + "; failing!"); 4836 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4837 return false; 4838 } 4839 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4840 } 4841 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4842 for (int i=0; i<N; i++) { 4843 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4844 if (file == null) { 4845 Slog.w(TAG, "Package " + pkg.packageName 4846 + " desires unavailable shared library " 4847 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4848 } else { 4849 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4850 } 4851 } 4852 N = usesLibraryFiles.size(); 4853 if (N > 0) { 4854 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4855 } else { 4856 pkg.usesLibraryFiles = null; 4857 } 4858 } 4859 return true; 4860 } 4861 4862 private static boolean hasString(List<String> list, List<String> which) { 4863 if (list == null) { 4864 return false; 4865 } 4866 for (int i=list.size()-1; i>=0; i--) { 4867 for (int j=which.size()-1; j>=0; j--) { 4868 if (which.get(j).equals(list.get(i))) { 4869 return true; 4870 } 4871 } 4872 } 4873 return false; 4874 } 4875 4876 private void updateAllSharedLibrariesLPw() { 4877 for (PackageParser.Package pkg : mPackages.values()) { 4878 updateSharedLibrariesLPw(pkg, null); 4879 } 4880 } 4881 4882 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4883 PackageParser.Package changingPkg) { 4884 ArrayList<PackageParser.Package> res = null; 4885 for (PackageParser.Package pkg : mPackages.values()) { 4886 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4887 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4888 if (res == null) { 4889 res = new ArrayList<PackageParser.Package>(); 4890 } 4891 res.add(pkg); 4892 updateSharedLibrariesLPw(pkg, changingPkg); 4893 } 4894 } 4895 return res; 4896 } 4897 4898 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4899 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4900 final File scanFile = new File(pkg.codePath); 4901 if (pkg.applicationInfo.sourceDir == null || 4902 pkg.applicationInfo.publicSourceDir == null) { 4903 // Bail out. The resource and code paths haven't been set. 4904 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4905 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4906 return null; 4907 } 4908 4909 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4910 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4911 } 4912 4913 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4914 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4915 } 4916 4917 if (mCustomResolverComponentName != null && 4918 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4919 setUpCustomResolverActivity(pkg); 4920 } 4921 4922 if (pkg.packageName.equals("android")) { 4923 synchronized (mPackages) { 4924 if (mAndroidApplication != null) { 4925 Slog.w(TAG, "*************************************************"); 4926 Slog.w(TAG, "Core android package being redefined. Skipping."); 4927 Slog.w(TAG, " file=" + scanFile); 4928 Slog.w(TAG, "*************************************************"); 4929 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4930 return null; 4931 } 4932 4933 // Set up information for our fall-back user intent resolution activity. 4934 mPlatformPackage = pkg; 4935 pkg.mVersionCode = mSdkVersion; 4936 mAndroidApplication = pkg.applicationInfo; 4937 4938 if (!mResolverReplaced) { 4939 mResolveActivity.applicationInfo = mAndroidApplication; 4940 mResolveActivity.name = ResolverActivity.class.getName(); 4941 mResolveActivity.packageName = mAndroidApplication.packageName; 4942 mResolveActivity.processName = "system:ui"; 4943 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4944 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 4945 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4946 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 4947 mResolveActivity.exported = true; 4948 mResolveActivity.enabled = true; 4949 mResolveInfo.activityInfo = mResolveActivity; 4950 mResolveInfo.priority = 0; 4951 mResolveInfo.preferredOrder = 0; 4952 mResolveInfo.match = 0; 4953 mResolveComponentName = new ComponentName( 4954 mAndroidApplication.packageName, mResolveActivity.name); 4955 } 4956 } 4957 } 4958 4959 if (DEBUG_PACKAGE_SCANNING) { 4960 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4961 Log.d(TAG, "Scanning package " + pkg.packageName); 4962 } 4963 4964 if (mPackages.containsKey(pkg.packageName) 4965 || mSharedLibraries.containsKey(pkg.packageName)) { 4966 Slog.w(TAG, "Application package " + pkg.packageName 4967 + " already installed. Skipping duplicate."); 4968 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4969 return null; 4970 } 4971 4972 // Initialize package source and resource directories 4973 File destCodeFile = new File(pkg.applicationInfo.sourceDir); 4974 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir); 4975 4976 SharedUserSetting suid = null; 4977 PackageSetting pkgSetting = null; 4978 4979 if (!isSystemApp(pkg)) { 4980 // Only system apps can use these features. 4981 pkg.mOriginalPackages = null; 4982 pkg.mRealPackage = null; 4983 pkg.mAdoptPermissions = null; 4984 } 4985 4986 // writer 4987 synchronized (mPackages) { 4988 if (pkg.mSharedUserId != null) { 4989 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 4990 if (suid == null) { 4991 Slog.w(TAG, "Creating application package " + pkg.packageName 4992 + " for shared user failed"); 4993 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4994 return null; 4995 } 4996 if (DEBUG_PACKAGE_SCANNING) { 4997 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4998 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 4999 + "): packages=" + suid.packages); 5000 } 5001 } 5002 5003 // Check if we are renaming from an original package name. 5004 PackageSetting origPackage = null; 5005 String realName = null; 5006 if (pkg.mOriginalPackages != null) { 5007 // This package may need to be renamed to a previously 5008 // installed name. Let's check on that... 5009 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5010 if (pkg.mOriginalPackages.contains(renamed)) { 5011 // This package had originally been installed as the 5012 // original name, and we have already taken care of 5013 // transitioning to the new one. Just update the new 5014 // one to continue using the old name. 5015 realName = pkg.mRealPackage; 5016 if (!pkg.packageName.equals(renamed)) { 5017 // Callers into this function may have already taken 5018 // care of renaming the package; only do it here if 5019 // it is not already done. 5020 pkg.setPackageName(renamed); 5021 } 5022 5023 } else { 5024 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5025 if ((origPackage = mSettings.peekPackageLPr( 5026 pkg.mOriginalPackages.get(i))) != null) { 5027 // We do have the package already installed under its 5028 // original name... should we use it? 5029 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5030 // New package is not compatible with original. 5031 origPackage = null; 5032 continue; 5033 } else if (origPackage.sharedUser != null) { 5034 // Make sure uid is compatible between packages. 5035 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5036 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5037 + " to " + pkg.packageName + ": old uid " 5038 + origPackage.sharedUser.name 5039 + " differs from " + pkg.mSharedUserId); 5040 origPackage = null; 5041 continue; 5042 } 5043 } else { 5044 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5045 + pkg.packageName + " to old name " + origPackage.name); 5046 } 5047 break; 5048 } 5049 } 5050 } 5051 } 5052 5053 if (mTransferedPackages.contains(pkg.packageName)) { 5054 Slog.w(TAG, "Package " + pkg.packageName 5055 + " was transferred to another, but its .apk remains"); 5056 } 5057 5058 // Just create the setting, don't add it yet. For already existing packages 5059 // the PkgSetting exists already and doesn't have to be created. 5060 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5061 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 5062 pkg.applicationInfo.cpuAbi, 5063 pkg.applicationInfo.flags, user, false); 5064 if (pkgSetting == null) { 5065 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 5066 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5067 return null; 5068 } 5069 5070 if (pkgSetting.origPackage != null) { 5071 // If we are first transitioning from an original package, 5072 // fix up the new package's name now. We need to do this after 5073 // looking up the package under its new name, so getPackageLP 5074 // can take care of fiddling things correctly. 5075 pkg.setPackageName(origPackage.name); 5076 5077 // File a report about this. 5078 String msg = "New package " + pkgSetting.realName 5079 + " renamed to replace old package " + pkgSetting.name; 5080 reportSettingsProblem(Log.WARN, msg); 5081 5082 // Make a note of it. 5083 mTransferedPackages.add(origPackage.name); 5084 5085 // No longer need to retain this. 5086 pkgSetting.origPackage = null; 5087 } 5088 5089 if (realName != null) { 5090 // Make a note of it. 5091 mTransferedPackages.add(pkg.packageName); 5092 } 5093 5094 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5095 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5096 } 5097 5098 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5099 // Check all shared libraries and map to their actual file path. 5100 // We only do this here for apps not on a system dir, because those 5101 // are the only ones that can fail an install due to this. We 5102 // will take care of the system apps by updating all of their 5103 // library paths after the scan is done. 5104 if (!updateSharedLibrariesLPw(pkg, null)) { 5105 return null; 5106 } 5107 } 5108 5109 if (mFoundPolicyFile) { 5110 SELinuxMMAC.assignSeinfoValue(pkg); 5111 } 5112 5113 pkg.applicationInfo.uid = pkgSetting.appId; 5114 pkg.mExtras = pkgSetting; 5115 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5116 if (!verifySignaturesLP(pkgSetting, pkg)) { 5117 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5118 return null; 5119 } 5120 // The signature has changed, but this package is in the system 5121 // image... let's recover! 5122 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5123 // However... if this package is part of a shared user, but it 5124 // doesn't match the signature of the shared user, let's fail. 5125 // What this means is that you can't change the signatures 5126 // associated with an overall shared user, which doesn't seem all 5127 // that unreasonable. 5128 if (pkgSetting.sharedUser != null) { 5129 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5130 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5131 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 5132 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 5133 return null; 5134 } 5135 } 5136 // File a report about this. 5137 String msg = "System package " + pkg.packageName 5138 + " signature changed; retaining data."; 5139 reportSettingsProblem(Log.WARN, msg); 5140 } 5141 } else { 5142 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5143 Slog.e(TAG, "Package " + pkg.packageName 5144 + " upgrade keys do not match the previously installed version; "); 5145 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5146 return null; 5147 } else { 5148 // signatures may have changed as result of upgrade 5149 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5150 } 5151 } 5152 // Verify that this new package doesn't have any content providers 5153 // that conflict with existing packages. Only do this if the 5154 // package isn't already installed, since we don't want to break 5155 // things that are installed. 5156 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5157 final int N = pkg.providers.size(); 5158 int i; 5159 for (i=0; i<N; i++) { 5160 PackageParser.Provider p = pkg.providers.get(i); 5161 if (p.info.authority != null) { 5162 String names[] = p.info.authority.split(";"); 5163 for (int j = 0; j < names.length; j++) { 5164 if (mProvidersByAuthority.containsKey(names[j])) { 5165 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5166 Slog.w(TAG, "Can't install because provider name " + names[j] + 5167 " (in package " + pkg.applicationInfo.packageName + 5168 ") is already used by " 5169 + ((other != null && other.getComponentName() != null) 5170 ? other.getComponentName().getPackageName() : "?")); 5171 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 5172 return null; 5173 } 5174 } 5175 } 5176 } 5177 } 5178 5179 if (pkg.mAdoptPermissions != null) { 5180 // This package wants to adopt ownership of permissions from 5181 // another package. 5182 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5183 final String origName = pkg.mAdoptPermissions.get(i); 5184 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5185 if (orig != null) { 5186 if (verifyPackageUpdateLPr(orig, pkg)) { 5187 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5188 + pkg.packageName); 5189 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5190 } 5191 } 5192 } 5193 } 5194 } 5195 5196 final String pkgName = pkg.packageName; 5197 5198 final long scanFileTime = scanFile.lastModified(); 5199 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5200 pkg.applicationInfo.processName = fixProcessName( 5201 pkg.applicationInfo.packageName, 5202 pkg.applicationInfo.processName, 5203 pkg.applicationInfo.uid); 5204 5205 File dataPath; 5206 if (mPlatformPackage == pkg) { 5207 // The system package is special. 5208 dataPath = new File (Environment.getDataDirectory(), "system"); 5209 pkg.applicationInfo.dataDir = dataPath.getPath(); 5210 } else { 5211 // This is a normal package, need to make its data directory. 5212 dataPath = getDataPathForPackage(pkg.packageName, 0); 5213 5214 boolean uidError = false; 5215 5216 if (dataPath.exists()) { 5217 int currentUid = 0; 5218 try { 5219 StructStat stat = Os.stat(dataPath.getPath()); 5220 currentUid = stat.st_uid; 5221 } catch (ErrnoException e) { 5222 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5223 } 5224 5225 // If we have mismatched owners for the data path, we have a problem. 5226 if (currentUid != pkg.applicationInfo.uid) { 5227 boolean recovered = false; 5228 if (currentUid == 0) { 5229 // The directory somehow became owned by root. Wow. 5230 // This is probably because the system was stopped while 5231 // installd was in the middle of messing with its libs 5232 // directory. Ask installd to fix that. 5233 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5234 pkg.applicationInfo.uid); 5235 if (ret >= 0) { 5236 recovered = true; 5237 String msg = "Package " + pkg.packageName 5238 + " unexpectedly changed to uid 0; recovered to " + 5239 + pkg.applicationInfo.uid; 5240 reportSettingsProblem(Log.WARN, msg); 5241 } 5242 } 5243 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5244 || (scanMode&SCAN_BOOTING) != 0)) { 5245 // If this is a system app, we can at least delete its 5246 // current data so the application will still work. 5247 int ret = removeDataDirsLI(pkgName); 5248 if (ret >= 0) { 5249 // TODO: Kill the processes first 5250 // Old data gone! 5251 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5252 ? "System package " : "Third party package "; 5253 String msg = prefix + pkg.packageName 5254 + " has changed from uid: " 5255 + currentUid + " to " 5256 + pkg.applicationInfo.uid + "; old data erased"; 5257 reportSettingsProblem(Log.WARN, msg); 5258 recovered = true; 5259 5260 // And now re-install the app. 5261 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5262 pkg.applicationInfo.seinfo); 5263 if (ret == -1) { 5264 // Ack should not happen! 5265 msg = prefix + pkg.packageName 5266 + " could not have data directory re-created after delete."; 5267 reportSettingsProblem(Log.WARN, msg); 5268 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5269 return null; 5270 } 5271 } 5272 if (!recovered) { 5273 mHasSystemUidErrors = true; 5274 } 5275 } else if (!recovered) { 5276 // If we allow this install to proceed, we will be broken. 5277 // Abort, abort! 5278 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 5279 return null; 5280 } 5281 if (!recovered) { 5282 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5283 + pkg.applicationInfo.uid + "/fs_" 5284 + currentUid; 5285 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5286 String msg = "Package " + pkg.packageName 5287 + " has mismatched uid: " 5288 + currentUid + " on disk, " 5289 + pkg.applicationInfo.uid + " in settings"; 5290 // writer 5291 synchronized (mPackages) { 5292 mSettings.mReadMessages.append(msg); 5293 mSettings.mReadMessages.append('\n'); 5294 uidError = true; 5295 if (!pkgSetting.uidError) { 5296 reportSettingsProblem(Log.ERROR, msg); 5297 } 5298 } 5299 } 5300 } 5301 pkg.applicationInfo.dataDir = dataPath.getPath(); 5302 if (mShouldRestoreconData) { 5303 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5304 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5305 pkg.applicationInfo.uid); 5306 } 5307 } else { 5308 if (DEBUG_PACKAGE_SCANNING) { 5309 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5310 Log.v(TAG, "Want this data dir: " + dataPath); 5311 } 5312 //invoke installer to do the actual installation 5313 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5314 pkg.applicationInfo.seinfo); 5315 if (ret < 0) { 5316 // Error from installer 5317 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5318 return null; 5319 } 5320 5321 if (dataPath.exists()) { 5322 pkg.applicationInfo.dataDir = dataPath.getPath(); 5323 } else { 5324 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5325 pkg.applicationInfo.dataDir = null; 5326 } 5327 } 5328 5329 /* 5330 * Set the data dir to the default "/data/data/<package name>/lib" 5331 * if we got here without anyone telling us different (e.g., apps 5332 * stored on SD card have their native libraries stored in the ASEC 5333 * container with the APK). 5334 * 5335 * This happens during an upgrade from a package settings file that 5336 * doesn't have a native library path attribute at all. 5337 */ 5338 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 5339 if (pkgSetting.nativeLibraryPathString == null) { 5340 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5341 } else { 5342 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 5343 } 5344 } 5345 pkgSetting.uidError = uidError; 5346 } 5347 5348 final String path = scanFile.getPath(); 5349 /* Note: We don't want to unpack the native binaries for 5350 * system applications, unless they have been updated 5351 * (the binaries are already under /system/lib). 5352 * Also, don't unpack libs for apps on the external card 5353 * since they should have their libraries in the ASEC 5354 * container already. 5355 * 5356 * In other words, we're going to unpack the binaries 5357 * only for non-system apps and system app upgrades. 5358 */ 5359 if (pkg.applicationInfo.nativeLibraryDir != null) { 5360 NativeLibraryHelper.Handle handle = null; 5361 try { 5362 handle = NativeLibraryHelper.Handle.create(scanFile); 5363 // Enable gross and lame hacks for apps that are built with old 5364 // SDK tools. We must scan their APKs for renderscript bitcode and 5365 // not launch them if it's present. Don't bother checking on devices 5366 // that don't have 64 bit support. 5367 String[] abiList = Build.SUPPORTED_ABIS; 5368 boolean hasLegacyRenderscriptBitcode = false; 5369 if (abiOverride != null) { 5370 abiList = new String[] { abiOverride }; 5371 } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 5372 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5373 abiList = Build.SUPPORTED_32_BIT_ABIS; 5374 hasLegacyRenderscriptBitcode = true; 5375 } 5376 5377 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5378 final String dataPathString = dataPath.getCanonicalPath(); 5379 5380 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5381 /* 5382 * Upgrading from a previous version of the OS sometimes 5383 * leaves native libraries in the /data/data/<app>/lib 5384 * directory for system apps even when they shouldn't be. 5385 * Recent changes in the JNI library search path 5386 * necessitates we remove those to match previous behavior. 5387 */ 5388 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 5389 Log.i(TAG, "removed obsolete native libraries for system package " 5390 + path); 5391 } 5392 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5393 pkg.applicationInfo.cpuAbi = abiList[0]; 5394 pkgSetting.cpuAbiString = abiList[0]; 5395 } else { 5396 setInternalAppAbi(pkg, pkgSetting); 5397 } 5398 } else { 5399 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 5400 /* 5401 * Update native library dir if it starts with 5402 * /data/data 5403 */ 5404 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 5405 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5406 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5407 } 5408 5409 try { 5410 int copyRet = copyNativeLibrariesForInternalApp(handle, 5411 nativeLibraryDir, abiList); 5412 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5413 Slog.e(TAG, "Unable to copy native libraries"); 5414 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5415 return null; 5416 } 5417 5418 // We've successfully copied native libraries across, so we make a 5419 // note of what ABI we're using 5420 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5421 pkg.applicationInfo.cpuAbi = abiList[copyRet]; 5422 } else if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5423 pkg.applicationInfo.cpuAbi = abiList[0]; 5424 } else { 5425 pkg.applicationInfo.cpuAbi = null; 5426 } 5427 } catch (IOException e) { 5428 Slog.e(TAG, "Unable to copy native libraries", e); 5429 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5430 return null; 5431 } 5432 } else { 5433 // We don't have to copy the shared libraries if we're in the ASEC container 5434 // but we still need to scan the file to figure out what ABI the app needs. 5435 // 5436 // TODO: This duplicates work done in the default container service. It's possible 5437 // to clean this up but we'll need to change the interface between this service 5438 // and IMediaContainerService (but doing so will spread this logic out, rather 5439 // than centralizing it). 5440 final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5441 if (abi >= 0) { 5442 pkg.applicationInfo.cpuAbi = abiList[abi]; 5443 } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) { 5444 // Note that (non upgraded) system apps will not have any native 5445 // libraries bundled in their APK, but we're guaranteed not to be 5446 // such an app at this point. 5447 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5448 pkg.applicationInfo.cpuAbi = abiList[0]; 5449 } else { 5450 pkg.applicationInfo.cpuAbi = null; 5451 } 5452 } else { 5453 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5454 return null; 5455 } 5456 } 5457 5458 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5459 final int[] userIds = sUserManager.getUserIds(); 5460 synchronized (mInstallLock) { 5461 for (int userId : userIds) { 5462 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 5463 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 5464 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5465 + ")"); 5466 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5467 return null; 5468 } 5469 } 5470 } 5471 } 5472 5473 pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi; 5474 } catch (IOException ioe) { 5475 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5476 } finally { 5477 IoUtils.closeQuietly(handle); 5478 } 5479 } 5480 5481 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5482 // We don't do this here during boot because we can do it all 5483 // at once after scanning all existing packages. 5484 // 5485 // We also do this *before* we perform dexopt on this package, so that 5486 // we can avoid redundant dexopts, and also to make sure we've got the 5487 // code and package path correct. 5488 if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5489 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) { 5490 mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE; 5491 return null; 5492 } 5493 } 5494 5495 if ((scanMode&SCAN_NO_DEX) == 0) { 5496 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5497 == DEX_OPT_FAILED) { 5498 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5499 removeDataDirsLI(pkg.packageName); 5500 } 5501 5502 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5503 return null; 5504 } 5505 } 5506 5507 if (mFactoryTest && pkg.requestedPermissions.contains( 5508 android.Manifest.permission.FACTORY_TEST)) { 5509 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5510 } 5511 5512 ArrayList<PackageParser.Package> clientLibPkgs = null; 5513 5514 // writer 5515 synchronized (mPackages) { 5516 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5517 // Only system apps can add new shared libraries. 5518 if (pkg.libraryNames != null) { 5519 for (int i=0; i<pkg.libraryNames.size(); i++) { 5520 String name = pkg.libraryNames.get(i); 5521 boolean allowed = false; 5522 if (isUpdatedSystemApp(pkg)) { 5523 // New library entries can only be added through the 5524 // system image. This is important to get rid of a lot 5525 // of nasty edge cases: for example if we allowed a non- 5526 // system update of the app to add a library, then uninstalling 5527 // the update would make the library go away, and assumptions 5528 // we made such as through app install filtering would now 5529 // have allowed apps on the device which aren't compatible 5530 // with it. Better to just have the restriction here, be 5531 // conservative, and create many fewer cases that can negatively 5532 // impact the user experience. 5533 final PackageSetting sysPs = mSettings 5534 .getDisabledSystemPkgLPr(pkg.packageName); 5535 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5536 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5537 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5538 allowed = true; 5539 allowed = true; 5540 break; 5541 } 5542 } 5543 } 5544 } else { 5545 allowed = true; 5546 } 5547 if (allowed) { 5548 if (!mSharedLibraries.containsKey(name)) { 5549 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5550 } else if (!name.equals(pkg.packageName)) { 5551 Slog.w(TAG, "Package " + pkg.packageName + " library " 5552 + name + " already exists; skipping"); 5553 } 5554 } else { 5555 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5556 + name + " that is not declared on system image; skipping"); 5557 } 5558 } 5559 if ((scanMode&SCAN_BOOTING) == 0) { 5560 // If we are not booting, we need to update any applications 5561 // that are clients of our shared library. If we are booting, 5562 // this will all be done once the scan is complete. 5563 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5564 } 5565 } 5566 } 5567 } 5568 5569 // We also need to dexopt any apps that are dependent on this library. Note that 5570 // if these fail, we should abort the install since installing the library will 5571 // result in some apps being broken. 5572 if (clientLibPkgs != null) { 5573 if ((scanMode&SCAN_NO_DEX) == 0) { 5574 for (int i=0; i<clientLibPkgs.size(); i++) { 5575 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5576 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5577 == DEX_OPT_FAILED) { 5578 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5579 removeDataDirsLI(pkg.packageName); 5580 } 5581 5582 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5583 return null; 5584 } 5585 } 5586 } 5587 } 5588 5589 // Request the ActivityManager to kill the process(only for existing packages) 5590 // so that we do not end up in a confused state while the user is still using the older 5591 // version of the application while the new one gets installed. 5592 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5593 // If the package lives in an asec, tell everyone that the container is going 5594 // away so they can clean up any references to its resources (which would prevent 5595 // vold from being able to unmount the asec) 5596 if (isForwardLocked(pkg) || isExternal(pkg)) { 5597 if (DEBUG_INSTALL) { 5598 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5599 } 5600 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5601 final ArrayList<String> pkgList = new ArrayList<String>(1); 5602 pkgList.add(pkg.applicationInfo.packageName); 5603 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5604 } 5605 5606 // Post the request that it be killed now that the going-away broadcast is en route 5607 killApplication(pkg.applicationInfo.packageName, 5608 pkg.applicationInfo.uid, "update pkg"); 5609 } 5610 5611 // Also need to kill any apps that are dependent on the library. 5612 if (clientLibPkgs != null) { 5613 for (int i=0; i<clientLibPkgs.size(); i++) { 5614 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5615 killApplication(clientPkg.applicationInfo.packageName, 5616 clientPkg.applicationInfo.uid, "update lib"); 5617 } 5618 } 5619 5620 // writer 5621 synchronized (mPackages) { 5622 // We don't expect installation to fail beyond this point, 5623 if ((scanMode&SCAN_MONITOR) != 0) { 5624 mAppDirs.put(pkg.codePath, pkg); 5625 } 5626 // Add the new setting to mSettings 5627 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5628 // Add the new setting to mPackages 5629 mPackages.put(pkg.applicationInfo.packageName, pkg); 5630 // Make sure we don't accidentally delete its data. 5631 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5632 while (iter.hasNext()) { 5633 PackageCleanItem item = iter.next(); 5634 if (pkgName.equals(item.packageName)) { 5635 iter.remove(); 5636 } 5637 } 5638 5639 // Take care of first install / last update times. 5640 if (currentTime != 0) { 5641 if (pkgSetting.firstInstallTime == 0) { 5642 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5643 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5644 pkgSetting.lastUpdateTime = currentTime; 5645 } 5646 } else if (pkgSetting.firstInstallTime == 0) { 5647 // We need *something*. Take time time stamp of the file. 5648 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5649 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5650 if (scanFileTime != pkgSetting.timeStamp) { 5651 // A package on the system image has changed; consider this 5652 // to be an update. 5653 pkgSetting.lastUpdateTime = scanFileTime; 5654 } 5655 } 5656 5657 // Add the package's KeySets to the global KeySetManagerService 5658 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5659 try { 5660 // Old KeySetData no longer valid. 5661 ksms.removeAppKeySetData(pkg.packageName); 5662 ksms.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5663 if (pkg.mKeySetMapping != null) { 5664 for (Map.Entry<String, Set<PublicKey>> entry : 5665 pkg.mKeySetMapping.entrySet()) { 5666 if (entry.getValue() != null) { 5667 ksms.addDefinedKeySetToPackage(pkg.packageName, 5668 entry.getValue(), entry.getKey()); 5669 } 5670 } 5671 if (pkg.mUpgradeKeySets != null 5672 && pkg.mKeySetMapping.keySet().containsAll(pkg.mUpgradeKeySets)) { 5673 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5674 ksms.addUpgradeKeySetToPackage(pkg.packageName, upgradeAlias); 5675 } 5676 } 5677 } 5678 } catch (NullPointerException e) { 5679 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5680 } catch (IllegalArgumentException e) { 5681 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5682 } 5683 5684 int N = pkg.providers.size(); 5685 StringBuilder r = null; 5686 int i; 5687 for (i=0; i<N; i++) { 5688 PackageParser.Provider p = pkg.providers.get(i); 5689 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5690 p.info.processName, pkg.applicationInfo.uid); 5691 mProviders.addProvider(p); 5692 p.syncable = p.info.isSyncable; 5693 if (p.info.authority != null) { 5694 String names[] = p.info.authority.split(";"); 5695 p.info.authority = null; 5696 for (int j = 0; j < names.length; j++) { 5697 if (j == 1 && p.syncable) { 5698 // We only want the first authority for a provider to possibly be 5699 // syncable, so if we already added this provider using a different 5700 // authority clear the syncable flag. We copy the provider before 5701 // changing it because the mProviders object contains a reference 5702 // to a provider that we don't want to change. 5703 // Only do this for the second authority since the resulting provider 5704 // object can be the same for all future authorities for this provider. 5705 p = new PackageParser.Provider(p); 5706 p.syncable = false; 5707 } 5708 if (!mProvidersByAuthority.containsKey(names[j])) { 5709 mProvidersByAuthority.put(names[j], p); 5710 if (p.info.authority == null) { 5711 p.info.authority = names[j]; 5712 } else { 5713 p.info.authority = p.info.authority + ";" + names[j]; 5714 } 5715 if (DEBUG_PACKAGE_SCANNING) { 5716 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5717 Log.d(TAG, "Registered content provider: " + names[j] 5718 + ", className = " + p.info.name + ", isSyncable = " 5719 + p.info.isSyncable); 5720 } 5721 } else { 5722 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5723 Slog.w(TAG, "Skipping provider name " + names[j] + 5724 " (in package " + pkg.applicationInfo.packageName + 5725 "): name already used by " 5726 + ((other != null && other.getComponentName() != null) 5727 ? other.getComponentName().getPackageName() : "?")); 5728 } 5729 } 5730 } 5731 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5732 if (r == null) { 5733 r = new StringBuilder(256); 5734 } else { 5735 r.append(' '); 5736 } 5737 r.append(p.info.name); 5738 } 5739 } 5740 if (r != null) { 5741 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5742 } 5743 5744 N = pkg.services.size(); 5745 r = null; 5746 for (i=0; i<N; i++) { 5747 PackageParser.Service s = pkg.services.get(i); 5748 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5749 s.info.processName, pkg.applicationInfo.uid); 5750 mServices.addService(s); 5751 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5752 if (r == null) { 5753 r = new StringBuilder(256); 5754 } else { 5755 r.append(' '); 5756 } 5757 r.append(s.info.name); 5758 } 5759 } 5760 if (r != null) { 5761 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5762 } 5763 5764 N = pkg.receivers.size(); 5765 r = null; 5766 for (i=0; i<N; i++) { 5767 PackageParser.Activity a = pkg.receivers.get(i); 5768 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5769 a.info.processName, pkg.applicationInfo.uid); 5770 mReceivers.addActivity(a, "receiver"); 5771 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5772 if (r == null) { 5773 r = new StringBuilder(256); 5774 } else { 5775 r.append(' '); 5776 } 5777 r.append(a.info.name); 5778 } 5779 } 5780 if (r != null) { 5781 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5782 } 5783 5784 N = pkg.activities.size(); 5785 r = null; 5786 for (i=0; i<N; i++) { 5787 PackageParser.Activity a = pkg.activities.get(i); 5788 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5789 a.info.processName, pkg.applicationInfo.uid); 5790 mActivities.addActivity(a, "activity"); 5791 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5792 if (r == null) { 5793 r = new StringBuilder(256); 5794 } else { 5795 r.append(' '); 5796 } 5797 r.append(a.info.name); 5798 } 5799 } 5800 if (r != null) { 5801 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5802 } 5803 5804 N = pkg.permissionGroups.size(); 5805 r = null; 5806 for (i=0; i<N; i++) { 5807 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5808 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5809 if (cur == null) { 5810 mPermissionGroups.put(pg.info.name, pg); 5811 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5812 if (r == null) { 5813 r = new StringBuilder(256); 5814 } else { 5815 r.append(' '); 5816 } 5817 r.append(pg.info.name); 5818 } 5819 } else { 5820 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5821 + pg.info.packageName + " ignored: original from " 5822 + cur.info.packageName); 5823 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5824 if (r == null) { 5825 r = new StringBuilder(256); 5826 } else { 5827 r.append(' '); 5828 } 5829 r.append("DUP:"); 5830 r.append(pg.info.name); 5831 } 5832 } 5833 } 5834 if (r != null) { 5835 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5836 } 5837 5838 N = pkg.permissions.size(); 5839 r = null; 5840 for (i=0; i<N; i++) { 5841 PackageParser.Permission p = pkg.permissions.get(i); 5842 HashMap<String, BasePermission> permissionMap = 5843 p.tree ? mSettings.mPermissionTrees 5844 : mSettings.mPermissions; 5845 p.group = mPermissionGroups.get(p.info.group); 5846 if (p.info.group == null || p.group != null) { 5847 BasePermission bp = permissionMap.get(p.info.name); 5848 if (bp == null) { 5849 bp = new BasePermission(p.info.name, p.info.packageName, 5850 BasePermission.TYPE_NORMAL); 5851 permissionMap.put(p.info.name, bp); 5852 } 5853 if (bp.perm == null) { 5854 if (bp.sourcePackage != null 5855 && !bp.sourcePackage.equals(p.info.packageName)) { 5856 // If this is a permission that was formerly defined by a non-system 5857 // app, but is now defined by a system app (following an upgrade), 5858 // discard the previous declaration and consider the system's to be 5859 // canonical. 5860 if (isSystemApp(p.owner)) { 5861 String msg = "New decl " + p.owner + " of permission " 5862 + p.info.name + " is system"; 5863 reportSettingsProblem(Log.WARN, msg); 5864 bp.sourcePackage = null; 5865 } 5866 } 5867 if (bp.sourcePackage == null 5868 || bp.sourcePackage.equals(p.info.packageName)) { 5869 BasePermission tree = findPermissionTreeLP(p.info.name); 5870 if (tree == null 5871 || tree.sourcePackage.equals(p.info.packageName)) { 5872 bp.packageSetting = pkgSetting; 5873 bp.perm = p; 5874 bp.uid = pkg.applicationInfo.uid; 5875 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5876 if (r == null) { 5877 r = new StringBuilder(256); 5878 } else { 5879 r.append(' '); 5880 } 5881 r.append(p.info.name); 5882 } 5883 } else { 5884 Slog.w(TAG, "Permission " + p.info.name + " from package " 5885 + p.info.packageName + " ignored: base tree " 5886 + tree.name + " is from package " 5887 + tree.sourcePackage); 5888 } 5889 } else { 5890 Slog.w(TAG, "Permission " + p.info.name + " from package " 5891 + p.info.packageName + " ignored: original from " 5892 + bp.sourcePackage); 5893 } 5894 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5895 if (r == null) { 5896 r = new StringBuilder(256); 5897 } else { 5898 r.append(' '); 5899 } 5900 r.append("DUP:"); 5901 r.append(p.info.name); 5902 } 5903 if (bp.perm == p) { 5904 bp.protectionLevel = p.info.protectionLevel; 5905 } 5906 } else { 5907 Slog.w(TAG, "Permission " + p.info.name + " from package " 5908 + p.info.packageName + " ignored: no group " 5909 + p.group); 5910 } 5911 } 5912 if (r != null) { 5913 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5914 } 5915 5916 N = pkg.instrumentation.size(); 5917 r = null; 5918 for (i=0; i<N; i++) { 5919 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5920 a.info.packageName = pkg.applicationInfo.packageName; 5921 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5922 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5923 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 5924 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 5925 a.info.dataDir = pkg.applicationInfo.dataDir; 5926 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5927 mInstrumentation.put(a.getComponentName(), a); 5928 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5929 if (r == null) { 5930 r = new StringBuilder(256); 5931 } else { 5932 r.append(' '); 5933 } 5934 r.append(a.info.name); 5935 } 5936 } 5937 if (r != null) { 5938 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5939 } 5940 5941 if (pkg.protectedBroadcasts != null) { 5942 N = pkg.protectedBroadcasts.size(); 5943 for (i=0; i<N; i++) { 5944 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5945 } 5946 } 5947 5948 pkgSetting.setTimeStamp(scanFileTime); 5949 5950 // Create idmap files for pairs of (packages, overlay packages). 5951 // Note: "android", ie framework-res.apk, is handled by native layers. 5952 if (pkg.mOverlayTarget != null) { 5953 // This is an overlay package. 5954 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 5955 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 5956 mOverlays.put(pkg.mOverlayTarget, 5957 new HashMap<String, PackageParser.Package>()); 5958 } 5959 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 5960 map.put(pkg.packageName, pkg); 5961 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 5962 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 5963 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5964 return null; 5965 } 5966 } 5967 } else if (mOverlays.containsKey(pkg.packageName) && 5968 !pkg.packageName.equals("android")) { 5969 // This is a regular package, with one or more known overlay packages. 5970 createIdmapsForPackageLI(pkg); 5971 } 5972 } 5973 5974 return pkg; 5975 } 5976 5977 /** 5978 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 5979 * i.e, so that all packages can be run inside a single process if required. 5980 * 5981 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 5982 * this function will either try and make the ABI for all packages in {@code packagesForUser} 5983 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 5984 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 5985 * updating a package that belongs to a shared user. 5986 */ 5987 private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 5988 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 5989 String requiredInstructionSet = null; 5990 if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) { 5991 requiredInstructionSet = VMRuntime.getInstructionSet( 5992 scannedPackage.applicationInfo.cpuAbi); 5993 } 5994 5995 PackageSetting requirer = null; 5996 for (PackageSetting ps : packagesForUser) { 5997 // If packagesForUser contains scannedPackage, we skip it. This will happen 5998 // when scannedPackage is an update of an existing package. Without this check, 5999 // we will never be able to change the ABI of any package belonging to a shared 6000 // user, even if it's compatible with other packages. 6001 if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) { 6002 if (ps.cpuAbiString == null) { 6003 continue; 6004 } 6005 6006 final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 6007 if (requiredInstructionSet != null) { 6008 if (!instructionSet.equals(requiredInstructionSet)) { 6009 // We have a mismatch between instruction sets (say arm vs arm64). 6010 // bail out. 6011 String errorMessage = "Instruction set mismatch, " 6012 + ((requirer == null) ? "[caller]" : requirer) 6013 + " requires " + requiredInstructionSet + " whereas " + ps 6014 + " requires " + instructionSet; 6015 Slog.e(TAG, errorMessage); 6016 6017 reportSettingsProblem(Log.WARN, errorMessage); 6018 // Give up, don't bother making any other changes to the package settings. 6019 return false; 6020 } 6021 } else { 6022 requiredInstructionSet = instructionSet; 6023 requirer = ps; 6024 } 6025 } 6026 } 6027 6028 if (requiredInstructionSet != null) { 6029 String adjustedAbi; 6030 if (requirer != null) { 6031 // requirer != null implies that either scannedPackage was null or that scannedPackage 6032 // did not require an ABI, in which case we have to adjust scannedPackage to match 6033 // the ABI of the set (which is the same as requirer's ABI) 6034 adjustedAbi = requirer.cpuAbiString; 6035 if (scannedPackage != null) { 6036 scannedPackage.applicationInfo.cpuAbi = adjustedAbi; 6037 } 6038 } else { 6039 // requirer == null implies that we're updating all ABIs in the set to 6040 // match scannedPackage. 6041 adjustedAbi = scannedPackage.applicationInfo.cpuAbi; 6042 } 6043 6044 for (PackageSetting ps : packagesForUser) { 6045 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6046 if (ps.cpuAbiString != null) { 6047 continue; 6048 } 6049 6050 ps.cpuAbiString = adjustedAbi; 6051 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6052 ps.pkg.applicationInfo.cpuAbi = adjustedAbi; 6053 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6054 6055 if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) { 6056 ps.cpuAbiString = null; 6057 ps.pkg.applicationInfo.cpuAbi = null; 6058 return false; 6059 } else { 6060 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6061 } 6062 } 6063 } 6064 } 6065 } 6066 6067 return true; 6068 } 6069 6070 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6071 synchronized (mPackages) { 6072 mResolverReplaced = true; 6073 // Set up information for custom user intent resolution activity. 6074 mResolveActivity.applicationInfo = pkg.applicationInfo; 6075 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6076 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6077 mResolveActivity.processName = null; 6078 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6079 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6080 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6081 mResolveActivity.theme = 0; 6082 mResolveActivity.exported = true; 6083 mResolveActivity.enabled = true; 6084 mResolveInfo.activityInfo = mResolveActivity; 6085 mResolveInfo.priority = 0; 6086 mResolveInfo.preferredOrder = 0; 6087 mResolveInfo.match = 0; 6088 mResolveComponentName = mCustomResolverComponentName; 6089 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6090 mResolveComponentName); 6091 } 6092 } 6093 6094 private String calculateApkRoot(final String codePathString) { 6095 final File codePath = new File(codePathString); 6096 final File codeRoot; 6097 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6098 codeRoot = Environment.getRootDirectory(); 6099 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6100 codeRoot = Environment.getOemDirectory(); 6101 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6102 codeRoot = Environment.getVendorDirectory(); 6103 } else { 6104 // Unrecognized code path; take its top real segment as the apk root: 6105 // e.g. /something/app/blah.apk => /something 6106 try { 6107 File f = codePath.getCanonicalFile(); 6108 File parent = f.getParentFile(); // non-null because codePath is a file 6109 File tmp; 6110 while ((tmp = parent.getParentFile()) != null) { 6111 f = parent; 6112 parent = tmp; 6113 } 6114 codeRoot = f; 6115 Slog.w(TAG, "Unrecognized code path " 6116 + codePath + " - using " + codeRoot); 6117 } catch (IOException e) { 6118 // Can't canonicalize the lib path -- shenanigans? 6119 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6120 return Environment.getRootDirectory().getPath(); 6121 } 6122 } 6123 return codeRoot.getPath(); 6124 } 6125 6126 // This is the initial scan-time determination of how to handle a given 6127 // package for purposes of native library location. 6128 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 6129 PackageSetting pkgSetting) { 6130 // "bundled" here means system-installed with no overriding update 6131 final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg); 6132 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 6133 final File libDir; 6134 if (bundledApk) { 6135 // If "/system/lib64/apkname" exists, assume that is the per-package 6136 // native library directory to use; otherwise use "/system/lib/apkname". 6137 String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6138 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 6139 File packLib64 = new File(lib64, apkName); 6140 libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 6141 } else { 6142 libDir = mAppLibInstallDir; 6143 } 6144 final String nativeLibraryPath = (new File(libDir, apkName)).getPath(); 6145 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 6146 // pkgSetting might be null during rescan following uninstall of updates 6147 // to a bundled app, so accommodate that possibility. The settings in 6148 // that case will be established later from the parsed package. 6149 if (pkgSetting != null) { 6150 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 6151 } 6152 } 6153 6154 // Deduces the required ABI of an upgraded system app. 6155 private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) { 6156 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6157 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 6158 6159 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 6160 // or similar. 6161 final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath()); 6162 final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath()); 6163 6164 // Assume that the bundled native libraries always correspond to the 6165 // most preferred 32 or 64 bit ABI. 6166 if (lib64.exists()) { 6167 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6168 pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0]; 6169 } else if (lib.exists()) { 6170 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6171 pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0]; 6172 } else { 6173 // This is the case where the app has no native code. 6174 pkg.applicationInfo.cpuAbi = null; 6175 pkgSetting.cpuAbiString = null; 6176 } 6177 } 6178 6179 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6180 final File nativeLibraryDir, String[] abiList) throws IOException { 6181 if (!nativeLibraryDir.isDirectory()) { 6182 nativeLibraryDir.delete(); 6183 6184 if (!nativeLibraryDir.mkdir()) { 6185 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 6186 } 6187 6188 try { 6189 Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6190 } catch (ErrnoException e) { 6191 throw new IOException("Cannot chmod native library directory " 6192 + nativeLibraryDir.getPath(), e); 6193 } 6194 } else if (!SELinux.restorecon(nativeLibraryDir)) { 6195 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 6196 } 6197 6198 /* 6199 * If this is an internal application or our nativeLibraryPath points to 6200 * the app-lib directory, unpack the libraries if necessary. 6201 */ 6202 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6203 if (abi >= 0) { 6204 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 6205 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 6206 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6207 return copyRet; 6208 } 6209 } 6210 6211 return abi; 6212 } 6213 6214 private void killApplication(String pkgName, int appId, String reason) { 6215 // Request the ActivityManager to kill the process(only for existing packages) 6216 // so that we do not end up in a confused state while the user is still using the older 6217 // version of the application while the new one gets installed. 6218 IActivityManager am = ActivityManagerNative.getDefault(); 6219 if (am != null) { 6220 try { 6221 am.killApplicationWithAppId(pkgName, appId, reason); 6222 } catch (RemoteException e) { 6223 } 6224 } 6225 } 6226 6227 void removePackageLI(PackageSetting ps, boolean chatty) { 6228 if (DEBUG_INSTALL) { 6229 if (chatty) 6230 Log.d(TAG, "Removing package " + ps.name); 6231 } 6232 6233 // writer 6234 synchronized (mPackages) { 6235 mPackages.remove(ps.name); 6236 if (ps.codePathString != null) { 6237 mAppDirs.remove(ps.codePathString); 6238 } 6239 6240 final PackageParser.Package pkg = ps.pkg; 6241 if (pkg != null) { 6242 cleanPackageDataStructuresLILPw(pkg, chatty); 6243 } 6244 } 6245 } 6246 6247 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6248 if (DEBUG_INSTALL) { 6249 if (chatty) 6250 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6251 } 6252 6253 // writer 6254 synchronized (mPackages) { 6255 mPackages.remove(pkg.applicationInfo.packageName); 6256 if (pkg.codePath != null) { 6257 mAppDirs.remove(pkg.codePath); 6258 } 6259 cleanPackageDataStructuresLILPw(pkg, chatty); 6260 } 6261 } 6262 6263 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6264 int N = pkg.providers.size(); 6265 StringBuilder r = null; 6266 int i; 6267 for (i=0; i<N; i++) { 6268 PackageParser.Provider p = pkg.providers.get(i); 6269 mProviders.removeProvider(p); 6270 if (p.info.authority == null) { 6271 6272 /* There was another ContentProvider with this authority when 6273 * this app was installed so this authority is null, 6274 * Ignore it as we don't have to unregister the provider. 6275 */ 6276 continue; 6277 } 6278 String names[] = p.info.authority.split(";"); 6279 for (int j = 0; j < names.length; j++) { 6280 if (mProvidersByAuthority.get(names[j]) == p) { 6281 mProvidersByAuthority.remove(names[j]); 6282 if (DEBUG_REMOVE) { 6283 if (chatty) 6284 Log.d(TAG, "Unregistered content provider: " + names[j] 6285 + ", className = " + p.info.name + ", isSyncable = " 6286 + p.info.isSyncable); 6287 } 6288 } 6289 } 6290 if (DEBUG_REMOVE && chatty) { 6291 if (r == null) { 6292 r = new StringBuilder(256); 6293 } else { 6294 r.append(' '); 6295 } 6296 r.append(p.info.name); 6297 } 6298 } 6299 if (r != null) { 6300 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6301 } 6302 6303 N = pkg.services.size(); 6304 r = null; 6305 for (i=0; i<N; i++) { 6306 PackageParser.Service s = pkg.services.get(i); 6307 mServices.removeService(s); 6308 if (chatty) { 6309 if (r == null) { 6310 r = new StringBuilder(256); 6311 } else { 6312 r.append(' '); 6313 } 6314 r.append(s.info.name); 6315 } 6316 } 6317 if (r != null) { 6318 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6319 } 6320 6321 N = pkg.receivers.size(); 6322 r = null; 6323 for (i=0; i<N; i++) { 6324 PackageParser.Activity a = pkg.receivers.get(i); 6325 mReceivers.removeActivity(a, "receiver"); 6326 if (DEBUG_REMOVE && chatty) { 6327 if (r == null) { 6328 r = new StringBuilder(256); 6329 } else { 6330 r.append(' '); 6331 } 6332 r.append(a.info.name); 6333 } 6334 } 6335 if (r != null) { 6336 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6337 } 6338 6339 N = pkg.activities.size(); 6340 r = null; 6341 for (i=0; i<N; i++) { 6342 PackageParser.Activity a = pkg.activities.get(i); 6343 mActivities.removeActivity(a, "activity"); 6344 if (DEBUG_REMOVE && chatty) { 6345 if (r == null) { 6346 r = new StringBuilder(256); 6347 } else { 6348 r.append(' '); 6349 } 6350 r.append(a.info.name); 6351 } 6352 } 6353 if (r != null) { 6354 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6355 } 6356 6357 N = pkg.permissions.size(); 6358 r = null; 6359 for (i=0; i<N; i++) { 6360 PackageParser.Permission p = pkg.permissions.get(i); 6361 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6362 if (bp == null) { 6363 bp = mSettings.mPermissionTrees.get(p.info.name); 6364 } 6365 if (bp != null && bp.perm == p) { 6366 bp.perm = null; 6367 if (DEBUG_REMOVE && chatty) { 6368 if (r == null) { 6369 r = new StringBuilder(256); 6370 } else { 6371 r.append(' '); 6372 } 6373 r.append(p.info.name); 6374 } 6375 } 6376 } 6377 if (r != null) { 6378 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6379 } 6380 6381 N = pkg.instrumentation.size(); 6382 r = null; 6383 for (i=0; i<N; i++) { 6384 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6385 mInstrumentation.remove(a.getComponentName()); 6386 if (DEBUG_REMOVE && chatty) { 6387 if (r == null) { 6388 r = new StringBuilder(256); 6389 } else { 6390 r.append(' '); 6391 } 6392 r.append(a.info.name); 6393 } 6394 } 6395 if (r != null) { 6396 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6397 } 6398 6399 r = null; 6400 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6401 // Only system apps can hold shared libraries. 6402 if (pkg.libraryNames != null) { 6403 for (i=0; i<pkg.libraryNames.size(); i++) { 6404 String name = pkg.libraryNames.get(i); 6405 SharedLibraryEntry cur = mSharedLibraries.get(name); 6406 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6407 mSharedLibraries.remove(name); 6408 if (DEBUG_REMOVE && chatty) { 6409 if (r == null) { 6410 r = new StringBuilder(256); 6411 } else { 6412 r.append(' '); 6413 } 6414 r.append(name); 6415 } 6416 } 6417 } 6418 } 6419 } 6420 if (r != null) { 6421 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6422 } 6423 } 6424 6425 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6426 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6427 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6428 return true; 6429 } 6430 } 6431 return false; 6432 } 6433 6434 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6435 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6436 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6437 6438 private void updatePermissionsLPw(String changingPkg, 6439 PackageParser.Package pkgInfo, int flags) { 6440 // Make sure there are no dangling permission trees. 6441 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6442 while (it.hasNext()) { 6443 final BasePermission bp = it.next(); 6444 if (bp.packageSetting == null) { 6445 // We may not yet have parsed the package, so just see if 6446 // we still know about its settings. 6447 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6448 } 6449 if (bp.packageSetting == null) { 6450 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6451 + " from package " + bp.sourcePackage); 6452 it.remove(); 6453 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6454 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6455 Slog.i(TAG, "Removing old permission tree: " + bp.name 6456 + " from package " + bp.sourcePackage); 6457 flags |= UPDATE_PERMISSIONS_ALL; 6458 it.remove(); 6459 } 6460 } 6461 } 6462 6463 // Make sure all dynamic permissions have been assigned to a package, 6464 // and make sure there are no dangling permissions. 6465 it = mSettings.mPermissions.values().iterator(); 6466 while (it.hasNext()) { 6467 final BasePermission bp = it.next(); 6468 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6469 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6470 + bp.name + " pkg=" + bp.sourcePackage 6471 + " info=" + bp.pendingInfo); 6472 if (bp.packageSetting == null && bp.pendingInfo != null) { 6473 final BasePermission tree = findPermissionTreeLP(bp.name); 6474 if (tree != null && tree.perm != null) { 6475 bp.packageSetting = tree.packageSetting; 6476 bp.perm = new PackageParser.Permission(tree.perm.owner, 6477 new PermissionInfo(bp.pendingInfo)); 6478 bp.perm.info.packageName = tree.perm.info.packageName; 6479 bp.perm.info.name = bp.name; 6480 bp.uid = tree.uid; 6481 } 6482 } 6483 } 6484 if (bp.packageSetting == null) { 6485 // We may not yet have parsed the package, so just see if 6486 // we still know about its settings. 6487 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6488 } 6489 if (bp.packageSetting == null) { 6490 Slog.w(TAG, "Removing dangling permission: " + bp.name 6491 + " from package " + bp.sourcePackage); 6492 it.remove(); 6493 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6494 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6495 Slog.i(TAG, "Removing old permission: " + bp.name 6496 + " from package " + bp.sourcePackage); 6497 flags |= UPDATE_PERMISSIONS_ALL; 6498 it.remove(); 6499 } 6500 } 6501 } 6502 6503 // Now update the permissions for all packages, in particular 6504 // replace the granted permissions of the system packages. 6505 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6506 for (PackageParser.Package pkg : mPackages.values()) { 6507 if (pkg != pkgInfo) { 6508 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6509 } 6510 } 6511 } 6512 6513 if (pkgInfo != null) { 6514 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6515 } 6516 } 6517 6518 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6519 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6520 if (ps == null) { 6521 return; 6522 } 6523 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6524 HashSet<String> origPermissions = gp.grantedPermissions; 6525 boolean changedPermission = false; 6526 6527 if (replace) { 6528 ps.permissionsFixed = false; 6529 if (gp == ps) { 6530 origPermissions = new HashSet<String>(gp.grantedPermissions); 6531 gp.grantedPermissions.clear(); 6532 gp.gids = mGlobalGids; 6533 } 6534 } 6535 6536 if (gp.gids == null) { 6537 gp.gids = mGlobalGids; 6538 } 6539 6540 final int N = pkg.requestedPermissions.size(); 6541 for (int i=0; i<N; i++) { 6542 final String name = pkg.requestedPermissions.get(i); 6543 final boolean required = pkg.requestedPermissionsRequired.get(i); 6544 final BasePermission bp = mSettings.mPermissions.get(name); 6545 if (DEBUG_INSTALL) { 6546 if (gp != ps) { 6547 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6548 } 6549 } 6550 6551 if (bp == null || bp.packageSetting == null) { 6552 Slog.w(TAG, "Unknown permission " + name 6553 + " in package " + pkg.packageName); 6554 continue; 6555 } 6556 6557 final String perm = bp.name; 6558 boolean allowed; 6559 boolean allowedSig = false; 6560 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6561 if (level == PermissionInfo.PROTECTION_NORMAL 6562 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6563 // We grant a normal or dangerous permission if any of the following 6564 // are true: 6565 // 1) The permission is required 6566 // 2) The permission is optional, but was granted in the past 6567 // 3) The permission is optional, but was requested by an 6568 // app in /system (not /data) 6569 // 6570 // Otherwise, reject the permission. 6571 allowed = (required || origPermissions.contains(perm) 6572 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6573 } else if (bp.packageSetting == null) { 6574 // This permission is invalid; skip it. 6575 allowed = false; 6576 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6577 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6578 if (allowed) { 6579 allowedSig = true; 6580 } 6581 } else { 6582 allowed = false; 6583 } 6584 if (DEBUG_INSTALL) { 6585 if (gp != ps) { 6586 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6587 } 6588 } 6589 if (allowed) { 6590 if (!isSystemApp(ps) && ps.permissionsFixed) { 6591 // If this is an existing, non-system package, then 6592 // we can't add any new permissions to it. 6593 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6594 // Except... if this is a permission that was added 6595 // to the platform (note: need to only do this when 6596 // updating the platform). 6597 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6598 } 6599 } 6600 if (allowed) { 6601 if (!gp.grantedPermissions.contains(perm)) { 6602 changedPermission = true; 6603 gp.grantedPermissions.add(perm); 6604 gp.gids = appendInts(gp.gids, bp.gids); 6605 } else if (!ps.haveGids) { 6606 gp.gids = appendInts(gp.gids, bp.gids); 6607 } 6608 } else { 6609 Slog.w(TAG, "Not granting permission " + perm 6610 + " to package " + pkg.packageName 6611 + " because it was previously installed without"); 6612 } 6613 } else { 6614 if (gp.grantedPermissions.remove(perm)) { 6615 changedPermission = true; 6616 gp.gids = removeInts(gp.gids, bp.gids); 6617 Slog.i(TAG, "Un-granting permission " + perm 6618 + " from package " + pkg.packageName 6619 + " (protectionLevel=" + bp.protectionLevel 6620 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6621 + ")"); 6622 } else { 6623 Slog.w(TAG, "Not granting permission " + perm 6624 + " to package " + pkg.packageName 6625 + " (protectionLevel=" + bp.protectionLevel 6626 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6627 + ")"); 6628 } 6629 } 6630 } 6631 6632 if ((changedPermission || replace) && !ps.permissionsFixed && 6633 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6634 // This is the first that we have heard about this package, so the 6635 // permissions we have now selected are fixed until explicitly 6636 // changed. 6637 ps.permissionsFixed = true; 6638 } 6639 ps.haveGids = true; 6640 } 6641 6642 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6643 boolean allowed = false; 6644 final int NP = PackageParser.NEW_PERMISSIONS.length; 6645 for (int ip=0; ip<NP; ip++) { 6646 final PackageParser.NewPermissionInfo npi 6647 = PackageParser.NEW_PERMISSIONS[ip]; 6648 if (npi.name.equals(perm) 6649 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6650 allowed = true; 6651 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6652 + pkg.packageName); 6653 break; 6654 } 6655 } 6656 return allowed; 6657 } 6658 6659 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6660 BasePermission bp, HashSet<String> origPermissions) { 6661 boolean allowed; 6662 allowed = (compareSignatures( 6663 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6664 == PackageManager.SIGNATURE_MATCH) 6665 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6666 == PackageManager.SIGNATURE_MATCH); 6667 if (!allowed && (bp.protectionLevel 6668 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6669 if (isSystemApp(pkg)) { 6670 // For updated system applications, a system permission 6671 // is granted only if it had been defined by the original application. 6672 if (isUpdatedSystemApp(pkg)) { 6673 final PackageSetting sysPs = mSettings 6674 .getDisabledSystemPkgLPr(pkg.packageName); 6675 final GrantedPermissions origGp = sysPs.sharedUser != null 6676 ? sysPs.sharedUser : sysPs; 6677 6678 if (origGp.grantedPermissions.contains(perm)) { 6679 // If the original was granted this permission, we take 6680 // that grant decision as read and propagate it to the 6681 // update. 6682 allowed = true; 6683 } else { 6684 // The system apk may have been updated with an older 6685 // version of the one on the data partition, but which 6686 // granted a new system permission that it didn't have 6687 // before. In this case we do want to allow the app to 6688 // now get the new permission if the ancestral apk is 6689 // privileged to get it. 6690 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6691 for (int j=0; 6692 j<sysPs.pkg.requestedPermissions.size(); j++) { 6693 if (perm.equals( 6694 sysPs.pkg.requestedPermissions.get(j))) { 6695 allowed = true; 6696 break; 6697 } 6698 } 6699 } 6700 } 6701 } else { 6702 allowed = isPrivilegedApp(pkg); 6703 } 6704 } 6705 } 6706 if (!allowed && (bp.protectionLevel 6707 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6708 // For development permissions, a development permission 6709 // is granted only if it was already granted. 6710 allowed = origPermissions.contains(perm); 6711 } 6712 return allowed; 6713 } 6714 6715 final class ActivityIntentResolver 6716 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6717 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6718 boolean defaultOnly, int userId) { 6719 if (!sUserManager.exists(userId)) return null; 6720 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6721 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6722 } 6723 6724 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6725 int userId) { 6726 if (!sUserManager.exists(userId)) return null; 6727 mFlags = flags; 6728 return super.queryIntent(intent, resolvedType, 6729 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6730 } 6731 6732 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6733 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6734 if (!sUserManager.exists(userId)) return null; 6735 if (packageActivities == null) { 6736 return null; 6737 } 6738 mFlags = flags; 6739 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6740 final int N = packageActivities.size(); 6741 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6742 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6743 6744 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6745 for (int i = 0; i < N; ++i) { 6746 intentFilters = packageActivities.get(i).intents; 6747 if (intentFilters != null && intentFilters.size() > 0) { 6748 PackageParser.ActivityIntentInfo[] array = 6749 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6750 intentFilters.toArray(array); 6751 listCut.add(array); 6752 } 6753 } 6754 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6755 } 6756 6757 public final void addActivity(PackageParser.Activity a, String type) { 6758 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6759 mActivities.put(a.getComponentName(), a); 6760 if (DEBUG_SHOW_INFO) 6761 Log.v( 6762 TAG, " " + type + " " + 6763 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6764 if (DEBUG_SHOW_INFO) 6765 Log.v(TAG, " Class=" + a.info.name); 6766 final int NI = a.intents.size(); 6767 for (int j=0; j<NI; j++) { 6768 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6769 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6770 intent.setPriority(0); 6771 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6772 + a.className + " with priority > 0, forcing to 0"); 6773 } 6774 if (DEBUG_SHOW_INFO) { 6775 Log.v(TAG, " IntentFilter:"); 6776 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6777 } 6778 if (!intent.debugCheck()) { 6779 Log.w(TAG, "==> For Activity " + a.info.name); 6780 } 6781 addFilter(intent); 6782 } 6783 } 6784 6785 public final void removeActivity(PackageParser.Activity a, String type) { 6786 mActivities.remove(a.getComponentName()); 6787 if (DEBUG_SHOW_INFO) { 6788 Log.v(TAG, " " + type + " " 6789 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6790 : a.info.name) + ":"); 6791 Log.v(TAG, " Class=" + a.info.name); 6792 } 6793 final int NI = a.intents.size(); 6794 for (int j=0; j<NI; j++) { 6795 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6796 if (DEBUG_SHOW_INFO) { 6797 Log.v(TAG, " IntentFilter:"); 6798 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6799 } 6800 removeFilter(intent); 6801 } 6802 } 6803 6804 @Override 6805 protected boolean allowFilterResult( 6806 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6807 ActivityInfo filterAi = filter.activity.info; 6808 for (int i=dest.size()-1; i>=0; i--) { 6809 ActivityInfo destAi = dest.get(i).activityInfo; 6810 if (destAi.name == filterAi.name 6811 && destAi.packageName == filterAi.packageName) { 6812 return false; 6813 } 6814 } 6815 return true; 6816 } 6817 6818 @Override 6819 protected ActivityIntentInfo[] newArray(int size) { 6820 return new ActivityIntentInfo[size]; 6821 } 6822 6823 @Override 6824 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6825 if (!sUserManager.exists(userId)) return true; 6826 PackageParser.Package p = filter.activity.owner; 6827 if (p != null) { 6828 PackageSetting ps = (PackageSetting)p.mExtras; 6829 if (ps != null) { 6830 // System apps are never considered stopped for purposes of 6831 // filtering, because there may be no way for the user to 6832 // actually re-launch them. 6833 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6834 && ps.getStopped(userId); 6835 } 6836 } 6837 return false; 6838 } 6839 6840 @Override 6841 protected boolean isPackageForFilter(String packageName, 6842 PackageParser.ActivityIntentInfo info) { 6843 return packageName.equals(info.activity.owner.packageName); 6844 } 6845 6846 @Override 6847 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6848 int match, int userId) { 6849 if (!sUserManager.exists(userId)) return null; 6850 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6851 return null; 6852 } 6853 final PackageParser.Activity activity = info.activity; 6854 if (mSafeMode && (activity.info.applicationInfo.flags 6855 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6856 return null; 6857 } 6858 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6859 if (ps == null) { 6860 return null; 6861 } 6862 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6863 ps.readUserState(userId), userId); 6864 if (ai == null) { 6865 return null; 6866 } 6867 final ResolveInfo res = new ResolveInfo(); 6868 res.activityInfo = ai; 6869 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6870 res.filter = info; 6871 } 6872 res.priority = info.getPriority(); 6873 res.preferredOrder = activity.owner.mPreferredOrder; 6874 //System.out.println("Result: " + res.activityInfo.className + 6875 // " = " + res.priority); 6876 res.match = match; 6877 res.isDefault = info.hasDefault; 6878 res.labelRes = info.labelRes; 6879 res.nonLocalizedLabel = info.nonLocalizedLabel; 6880 if (userNeedsBadging(userId)) { 6881 res.noResourceId = true; 6882 } else { 6883 res.icon = info.icon; 6884 } 6885 res.system = isSystemApp(res.activityInfo.applicationInfo); 6886 return res; 6887 } 6888 6889 @Override 6890 protected void sortResults(List<ResolveInfo> results) { 6891 Collections.sort(results, mResolvePrioritySorter); 6892 } 6893 6894 @Override 6895 protected void dumpFilter(PrintWriter out, String prefix, 6896 PackageParser.ActivityIntentInfo filter) { 6897 out.print(prefix); out.print( 6898 Integer.toHexString(System.identityHashCode(filter.activity))); 6899 out.print(' '); 6900 filter.activity.printComponentShortName(out); 6901 out.print(" filter "); 6902 out.println(Integer.toHexString(System.identityHashCode(filter))); 6903 } 6904 6905// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6906// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6907// final List<ResolveInfo> retList = Lists.newArrayList(); 6908// while (i.hasNext()) { 6909// final ResolveInfo resolveInfo = i.next(); 6910// if (isEnabledLP(resolveInfo.activityInfo)) { 6911// retList.add(resolveInfo); 6912// } 6913// } 6914// return retList; 6915// } 6916 6917 // Keys are String (activity class name), values are Activity. 6918 private final HashMap<ComponentName, PackageParser.Activity> mActivities 6919 = new HashMap<ComponentName, PackageParser.Activity>(); 6920 private int mFlags; 6921 } 6922 6923 private final class ServiceIntentResolver 6924 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 6925 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6926 boolean defaultOnly, int userId) { 6927 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6928 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6929 } 6930 6931 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6932 int userId) { 6933 if (!sUserManager.exists(userId)) return null; 6934 mFlags = flags; 6935 return super.queryIntent(intent, resolvedType, 6936 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6937 } 6938 6939 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6940 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 6941 if (!sUserManager.exists(userId)) return null; 6942 if (packageServices == null) { 6943 return null; 6944 } 6945 mFlags = flags; 6946 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6947 final int N = packageServices.size(); 6948 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 6949 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 6950 6951 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 6952 for (int i = 0; i < N; ++i) { 6953 intentFilters = packageServices.get(i).intents; 6954 if (intentFilters != null && intentFilters.size() > 0) { 6955 PackageParser.ServiceIntentInfo[] array = 6956 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 6957 intentFilters.toArray(array); 6958 listCut.add(array); 6959 } 6960 } 6961 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6962 } 6963 6964 public final void addService(PackageParser.Service s) { 6965 mServices.put(s.getComponentName(), s); 6966 if (DEBUG_SHOW_INFO) { 6967 Log.v(TAG, " " 6968 + (s.info.nonLocalizedLabel != null 6969 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6970 Log.v(TAG, " Class=" + s.info.name); 6971 } 6972 final int NI = s.intents.size(); 6973 int j; 6974 for (j=0; j<NI; j++) { 6975 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6976 if (DEBUG_SHOW_INFO) { 6977 Log.v(TAG, " IntentFilter:"); 6978 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6979 } 6980 if (!intent.debugCheck()) { 6981 Log.w(TAG, "==> For Service " + s.info.name); 6982 } 6983 addFilter(intent); 6984 } 6985 } 6986 6987 public final void removeService(PackageParser.Service s) { 6988 mServices.remove(s.getComponentName()); 6989 if (DEBUG_SHOW_INFO) { 6990 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 6991 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6992 Log.v(TAG, " Class=" + s.info.name); 6993 } 6994 final int NI = s.intents.size(); 6995 int j; 6996 for (j=0; j<NI; j++) { 6997 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6998 if (DEBUG_SHOW_INFO) { 6999 Log.v(TAG, " IntentFilter:"); 7000 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7001 } 7002 removeFilter(intent); 7003 } 7004 } 7005 7006 @Override 7007 protected boolean allowFilterResult( 7008 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7009 ServiceInfo filterSi = filter.service.info; 7010 for (int i=dest.size()-1; i>=0; i--) { 7011 ServiceInfo destAi = dest.get(i).serviceInfo; 7012 if (destAi.name == filterSi.name 7013 && destAi.packageName == filterSi.packageName) { 7014 return false; 7015 } 7016 } 7017 return true; 7018 } 7019 7020 @Override 7021 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7022 return new PackageParser.ServiceIntentInfo[size]; 7023 } 7024 7025 @Override 7026 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7027 if (!sUserManager.exists(userId)) return true; 7028 PackageParser.Package p = filter.service.owner; 7029 if (p != null) { 7030 PackageSetting ps = (PackageSetting)p.mExtras; 7031 if (ps != null) { 7032 // System apps are never considered stopped for purposes of 7033 // filtering, because there may be no way for the user to 7034 // actually re-launch them. 7035 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7036 && ps.getStopped(userId); 7037 } 7038 } 7039 return false; 7040 } 7041 7042 @Override 7043 protected boolean isPackageForFilter(String packageName, 7044 PackageParser.ServiceIntentInfo info) { 7045 return packageName.equals(info.service.owner.packageName); 7046 } 7047 7048 @Override 7049 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7050 int match, int userId) { 7051 if (!sUserManager.exists(userId)) return null; 7052 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7053 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7054 return null; 7055 } 7056 final PackageParser.Service service = info.service; 7057 if (mSafeMode && (service.info.applicationInfo.flags 7058 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7059 return null; 7060 } 7061 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7062 if (ps == null) { 7063 return null; 7064 } 7065 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7066 ps.readUserState(userId), userId); 7067 if (si == null) { 7068 return null; 7069 } 7070 final ResolveInfo res = new ResolveInfo(); 7071 res.serviceInfo = si; 7072 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7073 res.filter = filter; 7074 } 7075 res.priority = info.getPriority(); 7076 res.preferredOrder = service.owner.mPreferredOrder; 7077 //System.out.println("Result: " + res.activityInfo.className + 7078 // " = " + res.priority); 7079 res.match = match; 7080 res.isDefault = info.hasDefault; 7081 res.labelRes = info.labelRes; 7082 res.nonLocalizedLabel = info.nonLocalizedLabel; 7083 res.icon = info.icon; 7084 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7085 return res; 7086 } 7087 7088 @Override 7089 protected void sortResults(List<ResolveInfo> results) { 7090 Collections.sort(results, mResolvePrioritySorter); 7091 } 7092 7093 @Override 7094 protected void dumpFilter(PrintWriter out, String prefix, 7095 PackageParser.ServiceIntentInfo filter) { 7096 out.print(prefix); out.print( 7097 Integer.toHexString(System.identityHashCode(filter.service))); 7098 out.print(' '); 7099 filter.service.printComponentShortName(out); 7100 out.print(" filter "); 7101 out.println(Integer.toHexString(System.identityHashCode(filter))); 7102 } 7103 7104// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7105// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7106// final List<ResolveInfo> retList = Lists.newArrayList(); 7107// while (i.hasNext()) { 7108// final ResolveInfo resolveInfo = (ResolveInfo) i; 7109// if (isEnabledLP(resolveInfo.serviceInfo)) { 7110// retList.add(resolveInfo); 7111// } 7112// } 7113// return retList; 7114// } 7115 7116 // Keys are String (activity class name), values are Activity. 7117 private final HashMap<ComponentName, PackageParser.Service> mServices 7118 = new HashMap<ComponentName, PackageParser.Service>(); 7119 private int mFlags; 7120 }; 7121 7122 private final class ProviderIntentResolver 7123 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7124 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7125 boolean defaultOnly, int userId) { 7126 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7127 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7128 } 7129 7130 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7131 int userId) { 7132 if (!sUserManager.exists(userId)) 7133 return null; 7134 mFlags = flags; 7135 return super.queryIntent(intent, resolvedType, 7136 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7137 } 7138 7139 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7140 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7141 if (!sUserManager.exists(userId)) 7142 return null; 7143 if (packageProviders == null) { 7144 return null; 7145 } 7146 mFlags = flags; 7147 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7148 final int N = packageProviders.size(); 7149 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7150 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7151 7152 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7153 for (int i = 0; i < N; ++i) { 7154 intentFilters = packageProviders.get(i).intents; 7155 if (intentFilters != null && intentFilters.size() > 0) { 7156 PackageParser.ProviderIntentInfo[] array = 7157 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7158 intentFilters.toArray(array); 7159 listCut.add(array); 7160 } 7161 } 7162 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7163 } 7164 7165 public final void addProvider(PackageParser.Provider p) { 7166 if (mProviders.containsKey(p.getComponentName())) { 7167 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7168 return; 7169 } 7170 7171 mProviders.put(p.getComponentName(), p); 7172 if (DEBUG_SHOW_INFO) { 7173 Log.v(TAG, " " 7174 + (p.info.nonLocalizedLabel != null 7175 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7176 Log.v(TAG, " Class=" + p.info.name); 7177 } 7178 final int NI = p.intents.size(); 7179 int j; 7180 for (j = 0; j < NI; j++) { 7181 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7182 if (DEBUG_SHOW_INFO) { 7183 Log.v(TAG, " IntentFilter:"); 7184 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7185 } 7186 if (!intent.debugCheck()) { 7187 Log.w(TAG, "==> For Provider " + p.info.name); 7188 } 7189 addFilter(intent); 7190 } 7191 } 7192 7193 public final void removeProvider(PackageParser.Provider p) { 7194 mProviders.remove(p.getComponentName()); 7195 if (DEBUG_SHOW_INFO) { 7196 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7197 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7198 Log.v(TAG, " Class=" + p.info.name); 7199 } 7200 final int NI = p.intents.size(); 7201 int j; 7202 for (j = 0; j < NI; j++) { 7203 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7204 if (DEBUG_SHOW_INFO) { 7205 Log.v(TAG, " IntentFilter:"); 7206 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7207 } 7208 removeFilter(intent); 7209 } 7210 } 7211 7212 @Override 7213 protected boolean allowFilterResult( 7214 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7215 ProviderInfo filterPi = filter.provider.info; 7216 for (int i = dest.size() - 1; i >= 0; i--) { 7217 ProviderInfo destPi = dest.get(i).providerInfo; 7218 if (destPi.name == filterPi.name 7219 && destPi.packageName == filterPi.packageName) { 7220 return false; 7221 } 7222 } 7223 return true; 7224 } 7225 7226 @Override 7227 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7228 return new PackageParser.ProviderIntentInfo[size]; 7229 } 7230 7231 @Override 7232 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7233 if (!sUserManager.exists(userId)) 7234 return true; 7235 PackageParser.Package p = filter.provider.owner; 7236 if (p != null) { 7237 PackageSetting ps = (PackageSetting) p.mExtras; 7238 if (ps != null) { 7239 // System apps are never considered stopped for purposes of 7240 // filtering, because there may be no way for the user to 7241 // actually re-launch them. 7242 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7243 && ps.getStopped(userId); 7244 } 7245 } 7246 return false; 7247 } 7248 7249 @Override 7250 protected boolean isPackageForFilter(String packageName, 7251 PackageParser.ProviderIntentInfo info) { 7252 return packageName.equals(info.provider.owner.packageName); 7253 } 7254 7255 @Override 7256 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7257 int match, int userId) { 7258 if (!sUserManager.exists(userId)) 7259 return null; 7260 final PackageParser.ProviderIntentInfo info = filter; 7261 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7262 return null; 7263 } 7264 final PackageParser.Provider provider = info.provider; 7265 if (mSafeMode && (provider.info.applicationInfo.flags 7266 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7267 return null; 7268 } 7269 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7270 if (ps == null) { 7271 return null; 7272 } 7273 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7274 ps.readUserState(userId), userId); 7275 if (pi == null) { 7276 return null; 7277 } 7278 final ResolveInfo res = new ResolveInfo(); 7279 res.providerInfo = pi; 7280 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7281 res.filter = filter; 7282 } 7283 res.priority = info.getPriority(); 7284 res.preferredOrder = provider.owner.mPreferredOrder; 7285 res.match = match; 7286 res.isDefault = info.hasDefault; 7287 res.labelRes = info.labelRes; 7288 res.nonLocalizedLabel = info.nonLocalizedLabel; 7289 res.icon = info.icon; 7290 res.system = isSystemApp(res.providerInfo.applicationInfo); 7291 return res; 7292 } 7293 7294 @Override 7295 protected void sortResults(List<ResolveInfo> results) { 7296 Collections.sort(results, mResolvePrioritySorter); 7297 } 7298 7299 @Override 7300 protected void dumpFilter(PrintWriter out, String prefix, 7301 PackageParser.ProviderIntentInfo filter) { 7302 out.print(prefix); 7303 out.print( 7304 Integer.toHexString(System.identityHashCode(filter.provider))); 7305 out.print(' '); 7306 filter.provider.printComponentShortName(out); 7307 out.print(" filter "); 7308 out.println(Integer.toHexString(System.identityHashCode(filter))); 7309 } 7310 7311 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7312 = new HashMap<ComponentName, PackageParser.Provider>(); 7313 private int mFlags; 7314 }; 7315 7316 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7317 new Comparator<ResolveInfo>() { 7318 public int compare(ResolveInfo r1, ResolveInfo r2) { 7319 int v1 = r1.priority; 7320 int v2 = r2.priority; 7321 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7322 if (v1 != v2) { 7323 return (v1 > v2) ? -1 : 1; 7324 } 7325 v1 = r1.preferredOrder; 7326 v2 = r2.preferredOrder; 7327 if (v1 != v2) { 7328 return (v1 > v2) ? -1 : 1; 7329 } 7330 if (r1.isDefault != r2.isDefault) { 7331 return r1.isDefault ? -1 : 1; 7332 } 7333 v1 = r1.match; 7334 v2 = r2.match; 7335 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7336 if (v1 != v2) { 7337 return (v1 > v2) ? -1 : 1; 7338 } 7339 if (r1.system != r2.system) { 7340 return r1.system ? -1 : 1; 7341 } 7342 return 0; 7343 } 7344 }; 7345 7346 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7347 new Comparator<ProviderInfo>() { 7348 public int compare(ProviderInfo p1, ProviderInfo p2) { 7349 final int v1 = p1.initOrder; 7350 final int v2 = p2.initOrder; 7351 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7352 } 7353 }; 7354 7355 static final void sendPackageBroadcast(String action, String pkg, 7356 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7357 int[] userIds) { 7358 IActivityManager am = ActivityManagerNative.getDefault(); 7359 if (am != null) { 7360 try { 7361 if (userIds == null) { 7362 userIds = am.getRunningUserIds(); 7363 } 7364 for (int id : userIds) { 7365 final Intent intent = new Intent(action, 7366 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7367 if (extras != null) { 7368 intent.putExtras(extras); 7369 } 7370 if (targetPkg != null) { 7371 intent.setPackage(targetPkg); 7372 } 7373 // Modify the UID when posting to other users 7374 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7375 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7376 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7377 intent.putExtra(Intent.EXTRA_UID, uid); 7378 } 7379 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7380 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7381 if (DEBUG_BROADCASTS) { 7382 RuntimeException here = new RuntimeException("here"); 7383 here.fillInStackTrace(); 7384 Slog.d(TAG, "Sending to user " + id + ": " 7385 + intent.toShortString(false, true, false, false) 7386 + " " + intent.getExtras(), here); 7387 } 7388 am.broadcastIntent(null, intent, null, finishedReceiver, 7389 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7390 finishedReceiver != null, false, id); 7391 } 7392 } catch (RemoteException ex) { 7393 } 7394 } 7395 } 7396 7397 /** 7398 * Check if the external storage media is available. This is true if there 7399 * is a mounted external storage medium or if the external storage is 7400 * emulated. 7401 */ 7402 private boolean isExternalMediaAvailable() { 7403 return mMediaMounted || Environment.isExternalStorageEmulated(); 7404 } 7405 7406 @Override 7407 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7408 // writer 7409 synchronized (mPackages) { 7410 if (!isExternalMediaAvailable()) { 7411 // If the external storage is no longer mounted at this point, 7412 // the caller may not have been able to delete all of this 7413 // packages files and can not delete any more. Bail. 7414 return null; 7415 } 7416 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7417 if (lastPackage != null) { 7418 pkgs.remove(lastPackage); 7419 } 7420 if (pkgs.size() > 0) { 7421 return pkgs.get(0); 7422 } 7423 } 7424 return null; 7425 } 7426 7427 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7428 if (false) { 7429 RuntimeException here = new RuntimeException("here"); 7430 here.fillInStackTrace(); 7431 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7432 + " andCode=" + andCode, here); 7433 } 7434 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7435 userId, andCode ? 1 : 0, packageName)); 7436 } 7437 7438 void startCleaningPackages() { 7439 // reader 7440 synchronized (mPackages) { 7441 if (!isExternalMediaAvailable()) { 7442 return; 7443 } 7444 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7445 return; 7446 } 7447 } 7448 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7449 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7450 IActivityManager am = ActivityManagerNative.getDefault(); 7451 if (am != null) { 7452 try { 7453 am.startService(null, intent, null, UserHandle.USER_OWNER); 7454 } catch (RemoteException e) { 7455 } 7456 } 7457 } 7458 7459 private final class AppDirObserver extends FileObserver { 7460 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7461 super(path, mask); 7462 mRootDir = path; 7463 mIsRom = isrom; 7464 mIsPrivileged = isPrivileged; 7465 } 7466 7467 public void onEvent(int event, String path) { 7468 String removedPackage = null; 7469 int removedAppId = -1; 7470 int[] removedUsers = null; 7471 String addedPackage = null; 7472 int addedAppId = -1; 7473 int[] addedUsers = null; 7474 7475 // TODO post a message to the handler to obtain serial ordering 7476 synchronized (mInstallLock) { 7477 String fullPathStr = null; 7478 File fullPath = null; 7479 if (path != null) { 7480 fullPath = new File(mRootDir, path); 7481 fullPathStr = fullPath.getPath(); 7482 } 7483 7484 if (DEBUG_APP_DIR_OBSERVER) 7485 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7486 7487 if (!isApkFile(fullPath)) { 7488 if (DEBUG_APP_DIR_OBSERVER) 7489 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7490 return; 7491 } 7492 7493 // Ignore packages that are being installed or 7494 // have just been installed. 7495 if (ignoreCodePath(fullPathStr)) { 7496 return; 7497 } 7498 PackageParser.Package p = null; 7499 PackageSetting ps = null; 7500 // reader 7501 synchronized (mPackages) { 7502 p = mAppDirs.get(fullPathStr); 7503 if (p != null) { 7504 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7505 if (ps != null) { 7506 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7507 } else { 7508 removedUsers = sUserManager.getUserIds(); 7509 } 7510 } 7511 addedUsers = sUserManager.getUserIds(); 7512 } 7513 if ((event&REMOVE_EVENTS) != 0) { 7514 if (ps != null) { 7515 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7516 removePackageLI(ps, true); 7517 removedPackage = ps.name; 7518 removedAppId = ps.appId; 7519 } 7520 } 7521 7522 if ((event&ADD_EVENTS) != 0) { 7523 if (p == null) { 7524 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7525 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7526 if (mIsRom) { 7527 flags |= PackageParser.PARSE_IS_SYSTEM 7528 | PackageParser.PARSE_IS_SYSTEM_DIR; 7529 if (mIsPrivileged) { 7530 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7531 } 7532 } 7533 p = scanPackageLI(fullPath, flags, 7534 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7535 System.currentTimeMillis(), UserHandle.ALL, null); 7536 if (p != null) { 7537 /* 7538 * TODO this seems dangerous as the package may have 7539 * changed since we last acquired the mPackages 7540 * lock. 7541 */ 7542 // writer 7543 synchronized (mPackages) { 7544 updatePermissionsLPw(p.packageName, p, 7545 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7546 } 7547 addedPackage = p.applicationInfo.packageName; 7548 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7549 } 7550 } 7551 } 7552 7553 // reader 7554 synchronized (mPackages) { 7555 mSettings.writeLPr(); 7556 } 7557 } 7558 7559 if (removedPackage != null) { 7560 Bundle extras = new Bundle(1); 7561 extras.putInt(Intent.EXTRA_UID, removedAppId); 7562 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7563 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7564 extras, null, null, removedUsers); 7565 } 7566 if (addedPackage != null) { 7567 Bundle extras = new Bundle(1); 7568 extras.putInt(Intent.EXTRA_UID, addedAppId); 7569 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7570 extras, null, null, addedUsers); 7571 } 7572 } 7573 7574 private final String mRootDir; 7575 private final boolean mIsRom; 7576 private final boolean mIsPrivileged; 7577 } 7578 7579 /* 7580 * The old-style observer methods all just trampoline to the newer signature with 7581 * expanded install observer API. The older API continues to work but does not 7582 * supply the additional details of the Observer2 API. 7583 */ 7584 7585 /* Called when a downloaded package installation has been confirmed by the user */ 7586 public void installPackage( 7587 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 7588 installPackageEtc(packageURI, observer, null, flags, null); 7589 } 7590 7591 /* Called when a downloaded package installation has been confirmed by the user */ 7592 @Override 7593 public void installPackage( 7594 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 7595 final String installerPackageName) { 7596 installPackageWithVerificationEtc(packageURI, observer, null, flags, 7597 installerPackageName, null, null, null); 7598 } 7599 7600 @Override 7601 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 7602 int flags, String installerPackageName, Uri verificationURI, 7603 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7604 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7605 VerificationParams.NO_UID, manifestDigest); 7606 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7607 installerPackageName, verificationParams, encryptionParams); 7608 } 7609 7610 @Override 7611 public void installPackageWithVerificationAndEncryption(Uri packageURI, 7612 IPackageInstallObserver observer, int flags, String installerPackageName, 7613 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7614 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7615 installerPackageName, verificationParams, encryptionParams); 7616 } 7617 7618 /* 7619 * And here are the "live" versions that take both observer arguments 7620 */ 7621 public void installPackageEtc( 7622 final Uri packageURI, final IPackageInstallObserver observer, 7623 IPackageInstallObserver2 observer2, final int flags) { 7624 installPackageEtc(packageURI, observer, observer2, flags, null); 7625 } 7626 7627 public void installPackageEtc( 7628 final Uri packageURI, final IPackageInstallObserver observer, 7629 final IPackageInstallObserver2 observer2, final int flags, 7630 final String installerPackageName) { 7631 installPackageWithVerificationEtc(packageURI, observer, observer2, flags, 7632 installerPackageName, null, null, null); 7633 } 7634 7635 @Override 7636 public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer, 7637 IPackageInstallObserver2 observer2, 7638 int flags, String installerPackageName, Uri verificationURI, 7639 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7640 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7641 VerificationParams.NO_UID, manifestDigest); 7642 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags, 7643 installerPackageName, verificationParams, encryptionParams); 7644 } 7645 7646 /* 7647 * All of the installPackage...*() methods redirect to this one for the master implementation 7648 */ 7649 public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI, 7650 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7651 int flags, String installerPackageName, 7652 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7653 if (observer == null && observer2 == null) { 7654 throw new IllegalArgumentException("No install observer supplied"); 7655 } 7656 installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2, 7657 flags, installerPackageName, verificationParams, encryptionParams, null); 7658 } 7659 7660 @Override 7661 public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI, 7662 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7663 int flags, String installerPackageName, 7664 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams, 7665 String packageAbiOverride) { 7666 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7667 null); 7668 7669 final int uid = Binder.getCallingUid(); 7670 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7671 try { 7672 if (observer != null) { 7673 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7674 } 7675 if (observer2 != null) { 7676 observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7677 } 7678 } catch (RemoteException re) { 7679 } 7680 return; 7681 } 7682 7683 UserHandle user; 7684 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7685 user = UserHandle.ALL; 7686 } else { 7687 user = new UserHandle(UserHandle.getUserId(uid)); 7688 } 7689 7690 final int filteredFlags; 7691 7692 if (uid == Process.SHELL_UID || uid == 0) { 7693 if (DEBUG_INSTALL) { 7694 Slog.v(TAG, "Install from ADB"); 7695 } 7696 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7697 } else { 7698 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7699 } 7700 7701 verificationParams.setInstallerUid(uid); 7702 7703 if (!"file".equals(packageURI.getScheme())) { 7704 throw new UnsupportedOperationException("Only file:// URIs are supported"); 7705 } 7706 final File fromFile = new File(packageURI.getPath()); 7707 7708 final Message msg = mHandler.obtainMessage(INIT_COPY); 7709 msg.obj = new InstallParams(fromFile, observer, observer2, filteredFlags, 7710 installerPackageName, verificationParams, encryptionParams, user, 7711 packageAbiOverride); 7712 mHandler.sendMessage(msg); 7713 } 7714 7715 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7716 Bundle extras = new Bundle(1); 7717 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7718 7719 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7720 packageName, extras, null, null, new int[] {userId}); 7721 try { 7722 IActivityManager am = ActivityManagerNative.getDefault(); 7723 final boolean isSystem = 7724 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7725 if (isSystem && am.isUserRunning(userId, false)) { 7726 // The just-installed/enabled app is bundled on the system, so presumed 7727 // to be able to run automatically without needing an explicit launch. 7728 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7729 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7730 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7731 .setPackage(packageName); 7732 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7733 android.app.AppOpsManager.OP_NONE, false, false, userId); 7734 } 7735 } catch (RemoteException e) { 7736 // shouldn't happen 7737 Slog.w(TAG, "Unable to bootstrap installed package", e); 7738 } 7739 } 7740 7741 @Override 7742 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7743 int userId) { 7744 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7745 PackageSetting pkgSetting; 7746 final int uid = Binder.getCallingUid(); 7747 if (UserHandle.getUserId(uid) != userId) { 7748 mContext.enforceCallingOrSelfPermission( 7749 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7750 "setApplicationBlockedSetting for user " + userId); 7751 } 7752 7753 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7754 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7755 return false; 7756 } 7757 7758 long callingId = Binder.clearCallingIdentity(); 7759 try { 7760 boolean sendAdded = false; 7761 boolean sendRemoved = false; 7762 // writer 7763 synchronized (mPackages) { 7764 pkgSetting = mSettings.mPackages.get(packageName); 7765 if (pkgSetting == null) { 7766 return false; 7767 } 7768 if (pkgSetting.getBlocked(userId) != blocked) { 7769 pkgSetting.setBlocked(blocked, userId); 7770 mSettings.writePackageRestrictionsLPr(userId); 7771 if (blocked) { 7772 sendRemoved = true; 7773 } else { 7774 sendAdded = true; 7775 } 7776 } 7777 } 7778 if (sendAdded) { 7779 sendPackageAddedForUser(packageName, pkgSetting, userId); 7780 return true; 7781 } 7782 if (sendRemoved) { 7783 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7784 "blocking pkg"); 7785 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7786 } 7787 } finally { 7788 Binder.restoreCallingIdentity(callingId); 7789 } 7790 return false; 7791 } 7792 7793 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7794 int userId) { 7795 final PackageRemovedInfo info = new PackageRemovedInfo(); 7796 info.removedPackage = packageName; 7797 info.removedUsers = new int[] {userId}; 7798 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7799 info.sendBroadcast(false, false, false); 7800 } 7801 7802 /** 7803 * Returns true if application is not found or there was an error. Otherwise it returns 7804 * the blocked state of the package for the given user. 7805 */ 7806 @Override 7807 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7808 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7809 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7810 "getApplicationBlocked for user " + userId); 7811 PackageSetting pkgSetting; 7812 long callingId = Binder.clearCallingIdentity(); 7813 try { 7814 // writer 7815 synchronized (mPackages) { 7816 pkgSetting = mSettings.mPackages.get(packageName); 7817 if (pkgSetting == null) { 7818 return true; 7819 } 7820 return pkgSetting.getBlocked(userId); 7821 } 7822 } finally { 7823 Binder.restoreCallingIdentity(callingId); 7824 } 7825 } 7826 7827 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer2, 7828 PackageInstallerParams params, String installerPackageName, int installerUid, 7829 UserHandle user) { 7830 Slog.e(TAG, "TODO: install stage!"); 7831 try { 7832 observer2.packageInstalled(packageName, null, 7833 PackageManager.INSTALL_FAILED_INTERNAL_ERROR); 7834 } catch (RemoteException ignored) { 7835 } 7836 } 7837 7838 /** 7839 * @hide 7840 */ 7841 @Override 7842 public int installExistingPackageAsUser(String packageName, int userId) { 7843 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7844 null); 7845 PackageSetting pkgSetting; 7846 final int uid = Binder.getCallingUid(); 7847 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7848 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7849 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7850 } 7851 7852 long callingId = Binder.clearCallingIdentity(); 7853 try { 7854 boolean sendAdded = false; 7855 Bundle extras = new Bundle(1); 7856 7857 // writer 7858 synchronized (mPackages) { 7859 pkgSetting = mSettings.mPackages.get(packageName); 7860 if (pkgSetting == null) { 7861 return PackageManager.INSTALL_FAILED_INVALID_URI; 7862 } 7863 if (!pkgSetting.getInstalled(userId)) { 7864 pkgSetting.setInstalled(true, userId); 7865 pkgSetting.setBlocked(false, userId); 7866 mSettings.writePackageRestrictionsLPr(userId); 7867 sendAdded = true; 7868 } 7869 } 7870 7871 if (sendAdded) { 7872 sendPackageAddedForUser(packageName, pkgSetting, userId); 7873 } 7874 } finally { 7875 Binder.restoreCallingIdentity(callingId); 7876 } 7877 7878 return PackageManager.INSTALL_SUCCEEDED; 7879 } 7880 7881 boolean isUserRestricted(int userId, String restrictionKey) { 7882 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7883 if (restrictions.getBoolean(restrictionKey, false)) { 7884 Log.w(TAG, "User is restricted: " + restrictionKey); 7885 return true; 7886 } 7887 return false; 7888 } 7889 7890 @Override 7891 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7892 mContext.enforceCallingOrSelfPermission( 7893 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7894 "Only package verification agents can verify applications"); 7895 7896 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7897 final PackageVerificationResponse response = new PackageVerificationResponse( 7898 verificationCode, Binder.getCallingUid()); 7899 msg.arg1 = id; 7900 msg.obj = response; 7901 mHandler.sendMessage(msg); 7902 } 7903 7904 @Override 7905 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7906 long millisecondsToDelay) { 7907 mContext.enforceCallingOrSelfPermission( 7908 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7909 "Only package verification agents can extend verification timeouts"); 7910 7911 final PackageVerificationState state = mPendingVerification.get(id); 7912 final PackageVerificationResponse response = new PackageVerificationResponse( 7913 verificationCodeAtTimeout, Binder.getCallingUid()); 7914 7915 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7916 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7917 } 7918 if (millisecondsToDelay < 0) { 7919 millisecondsToDelay = 0; 7920 } 7921 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7922 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7923 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7924 } 7925 7926 if ((state != null) && !state.timeoutExtended()) { 7927 state.extendTimeout(); 7928 7929 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7930 msg.arg1 = id; 7931 msg.obj = response; 7932 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7933 } 7934 } 7935 7936 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7937 int verificationCode, UserHandle user) { 7938 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7939 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7940 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7941 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7942 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7943 7944 mContext.sendBroadcastAsUser(intent, user, 7945 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7946 } 7947 7948 private ComponentName matchComponentForVerifier(String packageName, 7949 List<ResolveInfo> receivers) { 7950 ActivityInfo targetReceiver = null; 7951 7952 final int NR = receivers.size(); 7953 for (int i = 0; i < NR; i++) { 7954 final ResolveInfo info = receivers.get(i); 7955 if (info.activityInfo == null) { 7956 continue; 7957 } 7958 7959 if (packageName.equals(info.activityInfo.packageName)) { 7960 targetReceiver = info.activityInfo; 7961 break; 7962 } 7963 } 7964 7965 if (targetReceiver == null) { 7966 return null; 7967 } 7968 7969 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 7970 } 7971 7972 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 7973 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 7974 if (pkgInfo.verifiers.length == 0) { 7975 return null; 7976 } 7977 7978 final int N = pkgInfo.verifiers.length; 7979 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 7980 for (int i = 0; i < N; i++) { 7981 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 7982 7983 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 7984 receivers); 7985 if (comp == null) { 7986 continue; 7987 } 7988 7989 final int verifierUid = getUidForVerifier(verifierInfo); 7990 if (verifierUid == -1) { 7991 continue; 7992 } 7993 7994 if (DEBUG_VERIFY) { 7995 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 7996 + " with the correct signature"); 7997 } 7998 sufficientVerifiers.add(comp); 7999 verificationState.addSufficientVerifier(verifierUid); 8000 } 8001 8002 return sufficientVerifiers; 8003 } 8004 8005 private int getUidForVerifier(VerifierInfo verifierInfo) { 8006 synchronized (mPackages) { 8007 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8008 if (pkg == null) { 8009 return -1; 8010 } else if (pkg.mSignatures.length != 1) { 8011 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8012 + " has more than one signature; ignoring"); 8013 return -1; 8014 } 8015 8016 /* 8017 * If the public key of the package's signature does not match 8018 * our expected public key, then this is a different package and 8019 * we should skip. 8020 */ 8021 8022 final byte[] expectedPublicKey; 8023 try { 8024 final Signature verifierSig = pkg.mSignatures[0]; 8025 final PublicKey publicKey = verifierSig.getPublicKey(); 8026 expectedPublicKey = publicKey.getEncoded(); 8027 } catch (CertificateException e) { 8028 return -1; 8029 } 8030 8031 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8032 8033 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8034 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8035 + " does not have the expected public key; ignoring"); 8036 return -1; 8037 } 8038 8039 return pkg.applicationInfo.uid; 8040 } 8041 } 8042 8043 @Override 8044 public void finishPackageInstall(int token) { 8045 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8046 8047 if (DEBUG_INSTALL) { 8048 Slog.v(TAG, "BM finishing package install for " + token); 8049 } 8050 8051 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8052 mHandler.sendMessage(msg); 8053 } 8054 8055 /** 8056 * Get the verification agent timeout. 8057 * 8058 * @return verification timeout in milliseconds 8059 */ 8060 private long getVerificationTimeout() { 8061 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8062 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8063 DEFAULT_VERIFICATION_TIMEOUT); 8064 } 8065 8066 /** 8067 * Get the default verification agent response code. 8068 * 8069 * @return default verification response code 8070 */ 8071 private int getDefaultVerificationResponse() { 8072 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8073 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8074 DEFAULT_VERIFICATION_RESPONSE); 8075 } 8076 8077 /** 8078 * Check whether or not package verification has been enabled. 8079 * 8080 * @return true if verification should be performed 8081 */ 8082 private boolean isVerificationEnabled(int userId, int flags) { 8083 if (!DEFAULT_VERIFY_ENABLE) { 8084 return false; 8085 } 8086 8087 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8088 8089 // Check if installing from ADB 8090 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8091 // Do not run verification in a test harness environment 8092 if (ActivityManager.isRunningInTestHarness()) { 8093 return false; 8094 } 8095 if (ensureVerifyAppsEnabled) { 8096 return true; 8097 } 8098 // Check if the developer does not want package verification for ADB installs 8099 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8100 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8101 return false; 8102 } 8103 } 8104 8105 if (ensureVerifyAppsEnabled) { 8106 return true; 8107 } 8108 8109 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8110 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8111 } 8112 8113 /** 8114 * Get the "allow unknown sources" setting. 8115 * 8116 * @return the current "allow unknown sources" setting 8117 */ 8118 private int getUnknownSourcesSettings() { 8119 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8120 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8121 -1); 8122 } 8123 8124 @Override 8125 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8126 final int uid = Binder.getCallingUid(); 8127 // writer 8128 synchronized (mPackages) { 8129 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8130 if (targetPackageSetting == null) { 8131 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8132 } 8133 8134 PackageSetting installerPackageSetting; 8135 if (installerPackageName != null) { 8136 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8137 if (installerPackageSetting == null) { 8138 throw new IllegalArgumentException("Unknown installer package: " 8139 + installerPackageName); 8140 } 8141 } else { 8142 installerPackageSetting = null; 8143 } 8144 8145 Signature[] callerSignature; 8146 Object obj = mSettings.getUserIdLPr(uid); 8147 if (obj != null) { 8148 if (obj instanceof SharedUserSetting) { 8149 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8150 } else if (obj instanceof PackageSetting) { 8151 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8152 } else { 8153 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8154 } 8155 } else { 8156 throw new SecurityException("Unknown calling uid " + uid); 8157 } 8158 8159 // Verify: can't set installerPackageName to a package that is 8160 // not signed with the same cert as the caller. 8161 if (installerPackageSetting != null) { 8162 if (compareSignatures(callerSignature, 8163 installerPackageSetting.signatures.mSignatures) 8164 != PackageManager.SIGNATURE_MATCH) { 8165 throw new SecurityException( 8166 "Caller does not have same cert as new installer package " 8167 + installerPackageName); 8168 } 8169 } 8170 8171 // Verify: if target already has an installer package, it must 8172 // be signed with the same cert as the caller. 8173 if (targetPackageSetting.installerPackageName != null) { 8174 PackageSetting setting = mSettings.mPackages.get( 8175 targetPackageSetting.installerPackageName); 8176 // If the currently set package isn't valid, then it's always 8177 // okay to change it. 8178 if (setting != null) { 8179 if (compareSignatures(callerSignature, 8180 setting.signatures.mSignatures) 8181 != PackageManager.SIGNATURE_MATCH) { 8182 throw new SecurityException( 8183 "Caller does not have same cert as old installer package " 8184 + targetPackageSetting.installerPackageName); 8185 } 8186 } 8187 } 8188 8189 // Okay! 8190 targetPackageSetting.installerPackageName = installerPackageName; 8191 scheduleWriteSettingsLocked(); 8192 } 8193 } 8194 8195 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8196 // Queue up an async operation since the package installation may take a little while. 8197 mHandler.post(new Runnable() { 8198 public void run() { 8199 mHandler.removeCallbacks(this); 8200 // Result object to be returned 8201 PackageInstalledInfo res = new PackageInstalledInfo(); 8202 res.returnCode = currentStatus; 8203 res.uid = -1; 8204 res.pkg = null; 8205 res.removedInfo = new PackageRemovedInfo(); 8206 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8207 args.doPreInstall(res.returnCode); 8208 synchronized (mInstallLock) { 8209 installPackageLI(args, true, res); 8210 } 8211 args.doPostInstall(res.returnCode, res.uid); 8212 } 8213 8214 // A restore should be performed at this point if (a) the install 8215 // succeeded, (b) the operation is not an update, and (c) the new 8216 // package has a backupAgent defined. 8217 final boolean update = res.removedInfo.removedPackage != null; 8218 boolean doRestore = (!update 8219 && res.pkg != null 8220 && res.pkg.applicationInfo.backupAgentName != null); 8221 8222 // Set up the post-install work request bookkeeping. This will be used 8223 // and cleaned up by the post-install event handling regardless of whether 8224 // there's a restore pass performed. Token values are >= 1. 8225 int token; 8226 if (mNextInstallToken < 0) mNextInstallToken = 1; 8227 token = mNextInstallToken++; 8228 8229 PostInstallData data = new PostInstallData(args, res); 8230 mRunningInstalls.put(token, data); 8231 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8232 8233 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8234 // Pass responsibility to the Backup Manager. It will perform a 8235 // restore if appropriate, then pass responsibility back to the 8236 // Package Manager to run the post-install observer callbacks 8237 // and broadcasts. 8238 IBackupManager bm = IBackupManager.Stub.asInterface( 8239 ServiceManager.getService(Context.BACKUP_SERVICE)); 8240 if (bm != null) { 8241 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8242 + " to BM for possible restore"); 8243 try { 8244 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8245 } catch (RemoteException e) { 8246 // can't happen; the backup manager is local 8247 } catch (Exception e) { 8248 Slog.e(TAG, "Exception trying to enqueue restore", e); 8249 doRestore = false; 8250 } 8251 } else { 8252 Slog.e(TAG, "Backup Manager not found!"); 8253 doRestore = false; 8254 } 8255 } 8256 8257 if (!doRestore) { 8258 // No restore possible, or the Backup Manager was mysteriously not 8259 // available -- just fire the post-install work request directly. 8260 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8261 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8262 mHandler.sendMessage(msg); 8263 } 8264 } 8265 }); 8266 } 8267 8268 private abstract class HandlerParams { 8269 private static final int MAX_RETRIES = 4; 8270 8271 /** 8272 * Number of times startCopy() has been attempted and had a non-fatal 8273 * error. 8274 */ 8275 private int mRetries = 0; 8276 8277 /** User handle for the user requesting the information or installation. */ 8278 private final UserHandle mUser; 8279 8280 HandlerParams(UserHandle user) { 8281 mUser = user; 8282 } 8283 8284 UserHandle getUser() { 8285 return mUser; 8286 } 8287 8288 final boolean startCopy() { 8289 boolean res; 8290 try { 8291 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8292 8293 if (++mRetries > MAX_RETRIES) { 8294 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8295 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8296 handleServiceError(); 8297 return false; 8298 } else { 8299 handleStartCopy(); 8300 res = true; 8301 } 8302 } catch (RemoteException e) { 8303 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8304 mHandler.sendEmptyMessage(MCS_RECONNECT); 8305 res = false; 8306 } 8307 handleReturnCode(); 8308 return res; 8309 } 8310 8311 final void serviceError() { 8312 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8313 handleServiceError(); 8314 handleReturnCode(); 8315 } 8316 8317 abstract void handleStartCopy() throws RemoteException; 8318 abstract void handleServiceError(); 8319 abstract void handleReturnCode(); 8320 } 8321 8322 class MeasureParams extends HandlerParams { 8323 private final PackageStats mStats; 8324 private boolean mSuccess; 8325 8326 private final IPackageStatsObserver mObserver; 8327 8328 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8329 super(new UserHandle(stats.userHandle)); 8330 mObserver = observer; 8331 mStats = stats; 8332 } 8333 8334 @Override 8335 public String toString() { 8336 return "MeasureParams{" 8337 + Integer.toHexString(System.identityHashCode(this)) 8338 + " " + mStats.packageName + "}"; 8339 } 8340 8341 @Override 8342 void handleStartCopy() throws RemoteException { 8343 synchronized (mInstallLock) { 8344 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8345 } 8346 8347 if (mSuccess) { 8348 final boolean mounted; 8349 if (Environment.isExternalStorageEmulated()) { 8350 mounted = true; 8351 } else { 8352 final String status = Environment.getExternalStorageState(); 8353 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8354 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8355 } 8356 8357 if (mounted) { 8358 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8359 8360 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8361 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8362 8363 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8364 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8365 8366 // Always subtract cache size, since it's a subdirectory 8367 mStats.externalDataSize -= mStats.externalCacheSize; 8368 8369 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8370 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8371 8372 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8373 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8374 } 8375 } 8376 } 8377 8378 @Override 8379 void handleReturnCode() { 8380 if (mObserver != null) { 8381 try { 8382 mObserver.onGetStatsCompleted(mStats, mSuccess); 8383 } catch (RemoteException e) { 8384 Slog.i(TAG, "Observer no longer exists."); 8385 } 8386 } 8387 } 8388 8389 @Override 8390 void handleServiceError() { 8391 Slog.e(TAG, "Could not measure application " + mStats.packageName 8392 + " external storage"); 8393 } 8394 } 8395 8396 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8397 throws RemoteException { 8398 long result = 0; 8399 for (File path : paths) { 8400 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8401 } 8402 return result; 8403 } 8404 8405 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8406 for (File path : paths) { 8407 try { 8408 mcs.clearDirectory(path.getAbsolutePath()); 8409 } catch (RemoteException e) { 8410 } 8411 } 8412 } 8413 8414 class InstallParams extends HandlerParams { 8415 /** 8416 * Location where install is coming from, before it has been 8417 * copied/renamed into place. This could be a single monolithic APK 8418 * file, or a cluster directory. This location may be untrusted. 8419 */ 8420 private final File mFromFile; 8421 8422 /** 8423 * Local copy of {@link #mFromFile}, if generated. 8424 */ 8425 private File mLocalFromFile; 8426 8427 final IPackageInstallObserver observer; 8428 final IPackageInstallObserver2 observer2; 8429 int flags; 8430 final String installerPackageName; 8431 final VerificationParams verificationParams; 8432 private InstallArgs mArgs; 8433 private int mRet; 8434 final ContainerEncryptionParams encryptionParams; 8435 final String packageAbiOverride; 8436 final String packageInstructionSetOverride; 8437 8438 InstallParams(File fromFile, IPackageInstallObserver observer, 8439 IPackageInstallObserver2 observer2, int flags, String installerPackageName, 8440 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams, 8441 UserHandle user, String packageAbiOverride) { 8442 super(user); 8443 mFromFile = Preconditions.checkNotNull(fromFile); 8444 this.observer = observer; 8445 this.observer2 = observer2; 8446 this.flags = flags; 8447 this.installerPackageName = installerPackageName; 8448 this.verificationParams = verificationParams; 8449 this.encryptionParams = encryptionParams; 8450 this.packageAbiOverride = packageAbiOverride; 8451 this.packageInstructionSetOverride = (packageAbiOverride == null) ? 8452 packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride); 8453 } 8454 8455 @Override 8456 public String toString() { 8457 return "InstallParams{" 8458 + Integer.toHexString(System.identityHashCode(this)) 8459 + " " + mFromFile + "}"; 8460 } 8461 8462 public ManifestDigest getManifestDigest() { 8463 if (verificationParams == null) { 8464 return null; 8465 } 8466 return verificationParams.getManifestDigest(); 8467 } 8468 8469 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8470 String packageName = pkgLite.packageName; 8471 int installLocation = pkgLite.installLocation; 8472 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8473 // reader 8474 synchronized (mPackages) { 8475 PackageParser.Package pkg = mPackages.get(packageName); 8476 if (pkg != null) { 8477 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8478 // Check for downgrading. 8479 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8480 if (pkgLite.versionCode < pkg.mVersionCode) { 8481 Slog.w(TAG, "Can't install update of " + packageName 8482 + " update version " + pkgLite.versionCode 8483 + " is older than installed version " 8484 + pkg.mVersionCode); 8485 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8486 } 8487 } 8488 // Check for updated system application. 8489 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8490 if (onSd) { 8491 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8492 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8493 } 8494 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8495 } else { 8496 if (onSd) { 8497 // Install flag overrides everything. 8498 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8499 } 8500 // If current upgrade specifies particular preference 8501 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8502 // Application explicitly specified internal. 8503 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8504 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8505 // App explictly prefers external. Let policy decide 8506 } else { 8507 // Prefer previous location 8508 if (isExternal(pkg)) { 8509 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8510 } 8511 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8512 } 8513 } 8514 } else { 8515 // Invalid install. Return error code 8516 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8517 } 8518 } 8519 } 8520 // All the special cases have been taken care of. 8521 // Return result based on recommended install location. 8522 if (onSd) { 8523 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8524 } 8525 return pkgLite.recommendedInstallLocation; 8526 } 8527 8528 private long getMemoryLowThreshold() { 8529 final DeviceStorageMonitorInternal 8530 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8531 if (dsm == null) { 8532 return 0L; 8533 } 8534 return dsm.getMemoryLowThreshold(); 8535 } 8536 8537 /* 8538 * Invoke remote method to get package information and install 8539 * location values. Override install location based on default 8540 * policy if needed and then create install arguments based 8541 * on the install location. 8542 */ 8543 public void handleStartCopy() throws RemoteException { 8544 int ret = PackageManager.INSTALL_SUCCEEDED; 8545 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8546 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8547 PackageInfoLite pkgLite = null; 8548 8549 if (onInt && onSd) { 8550 // Check if both bits are set. 8551 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8552 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8553 } else { 8554 final long lowThreshold = getMemoryLowThreshold(); 8555 if (lowThreshold == 0L) { 8556 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8557 } 8558 8559 if (encryptionParams != null) { 8560 // Make a temporary file for decryption. 8561 mLocalFromFile = createTempPackageFile(mDrmAppPrivateInstallDir); 8562 if (mLocalFromFile != null) { 8563 ParcelFileDescriptor out = null; 8564 try { 8565 out = ParcelFileDescriptor.open(mLocalFromFile, 8566 ParcelFileDescriptor.MODE_READ_WRITE); 8567 ret = mContainerService.copyResource(mFromFile.getAbsolutePath(), 8568 encryptionParams, out); 8569 } catch (FileNotFoundException e) { 8570 Slog.e(TAG, "Failed to create temporary file for: " + mFromFile); 8571 } finally { 8572 IoUtils.closeQuietly(out); 8573 } 8574 8575 FileUtils.setPermissions(mLocalFromFile, 0644, -1, -1); 8576 } 8577 } 8578 8579 // Remote call to find out default install location 8580 final String fromPath = getFromFile().getAbsolutePath(); 8581 pkgLite = mContainerService.getMinimalPackageInfo(fromPath, flags, lowThreshold, 8582 packageAbiOverride); 8583 8584 /* 8585 * If we have too little free space, try to free cache 8586 * before giving up. 8587 */ 8588 if (pkgLite.recommendedInstallLocation 8589 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8590 final long size = mContainerService.calculateInstalledSize( 8591 fromPath, isForwardLocked(), packageAbiOverride); 8592 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8593 pkgLite = mContainerService.getMinimalPackageInfo(fromPath, 8594 flags, lowThreshold, packageAbiOverride); 8595 } 8596 /* 8597 * The cache free must have deleted the file we 8598 * downloaded to install. 8599 * 8600 * TODO: fix the "freeCache" call to not delete 8601 * the file we care about. 8602 */ 8603 if (pkgLite.recommendedInstallLocation 8604 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8605 pkgLite.recommendedInstallLocation 8606 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8607 } 8608 } 8609 } 8610 8611 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8612 int loc = pkgLite.recommendedInstallLocation; 8613 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8614 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8615 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8616 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8617 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8618 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8619 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8620 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8621 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8622 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8623 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8624 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8625 } else { 8626 // Override with defaults if needed. 8627 loc = installLocationPolicy(pkgLite, flags); 8628 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8629 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8630 } else if (!onSd && !onInt) { 8631 // Override install location with flags 8632 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8633 // Set the flag to install on external media. 8634 flags |= PackageManager.INSTALL_EXTERNAL; 8635 flags &= ~PackageManager.INSTALL_INTERNAL; 8636 } else { 8637 // Make sure the flag for installing on external 8638 // media is unset 8639 flags |= PackageManager.INSTALL_INTERNAL; 8640 flags &= ~PackageManager.INSTALL_EXTERNAL; 8641 } 8642 } 8643 } 8644 } 8645 8646 final InstallArgs args = createInstallArgs(this); 8647 mArgs = args; 8648 8649 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8650 /* 8651 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8652 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8653 */ 8654 int userIdentifier = getUser().getIdentifier(); 8655 if (userIdentifier == UserHandle.USER_ALL 8656 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8657 userIdentifier = UserHandle.USER_OWNER; 8658 } 8659 8660 /* 8661 * Determine if we have any installed package verifiers. If we 8662 * do, then we'll defer to them to verify the packages. 8663 */ 8664 final int requiredUid = mRequiredVerifierPackage == null ? -1 8665 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8666 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8667 // TODO: send verifier the install session instead of uri 8668 final Intent verification = new Intent( 8669 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8670 verification.setDataAndType(Uri.fromFile(getFromFile()), PACKAGE_MIME_TYPE); 8671 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8672 8673 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8674 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8675 0 /* TODO: Which userId? */); 8676 8677 if (DEBUG_VERIFY) { 8678 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8679 + verification.toString() + " with " + pkgLite.verifiers.length 8680 + " optional verifiers"); 8681 } 8682 8683 final int verificationId = mPendingVerificationToken++; 8684 8685 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8686 8687 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8688 installerPackageName); 8689 8690 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8691 8692 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8693 pkgLite.packageName); 8694 8695 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8696 pkgLite.versionCode); 8697 8698 if (verificationParams != null) { 8699 if (verificationParams.getVerificationURI() != null) { 8700 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8701 verificationParams.getVerificationURI()); 8702 } 8703 if (verificationParams.getOriginatingURI() != null) { 8704 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8705 verificationParams.getOriginatingURI()); 8706 } 8707 if (verificationParams.getReferrer() != null) { 8708 verification.putExtra(Intent.EXTRA_REFERRER, 8709 verificationParams.getReferrer()); 8710 } 8711 if (verificationParams.getOriginatingUid() >= 0) { 8712 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8713 verificationParams.getOriginatingUid()); 8714 } 8715 if (verificationParams.getInstallerUid() >= 0) { 8716 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8717 verificationParams.getInstallerUid()); 8718 } 8719 } 8720 8721 final PackageVerificationState verificationState = new PackageVerificationState( 8722 requiredUid, args); 8723 8724 mPendingVerification.append(verificationId, verificationState); 8725 8726 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8727 receivers, verificationState); 8728 8729 /* 8730 * If any sufficient verifiers were listed in the package 8731 * manifest, attempt to ask them. 8732 */ 8733 if (sufficientVerifiers != null) { 8734 final int N = sufficientVerifiers.size(); 8735 if (N == 0) { 8736 Slog.i(TAG, "Additional verifiers required, but none installed."); 8737 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8738 } else { 8739 for (int i = 0; i < N; i++) { 8740 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8741 8742 final Intent sufficientIntent = new Intent(verification); 8743 sufficientIntent.setComponent(verifierComponent); 8744 8745 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8746 } 8747 } 8748 } 8749 8750 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8751 mRequiredVerifierPackage, receivers); 8752 if (ret == PackageManager.INSTALL_SUCCEEDED 8753 && mRequiredVerifierPackage != null) { 8754 /* 8755 * Send the intent to the required verification agent, 8756 * but only start the verification timeout after the 8757 * target BroadcastReceivers have run. 8758 */ 8759 verification.setComponent(requiredVerifierComponent); 8760 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8761 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8762 new BroadcastReceiver() { 8763 @Override 8764 public void onReceive(Context context, Intent intent) { 8765 final Message msg = mHandler 8766 .obtainMessage(CHECK_PENDING_VERIFICATION); 8767 msg.arg1 = verificationId; 8768 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8769 } 8770 }, null, 0, null, null); 8771 8772 /* 8773 * We don't want the copy to proceed until verification 8774 * succeeds, so null out this field. 8775 */ 8776 mArgs = null; 8777 } 8778 } else { 8779 /* 8780 * No package verification is enabled, so immediately start 8781 * the remote call to initiate copy using temporary file. 8782 */ 8783 ret = args.copyApk(mContainerService, true); 8784 } 8785 } 8786 8787 mRet = ret; 8788 } 8789 8790 @Override 8791 void handleReturnCode() { 8792 // If mArgs is null, then MCS couldn't be reached. When it 8793 // reconnects, it will try again to install. At that point, this 8794 // will succeed. 8795 if (mArgs != null) { 8796 processPendingInstall(mArgs, mRet); 8797 8798 if (mLocalFromFile != null) { 8799 if (!mLocalFromFile.delete()) { 8800 Slog.w(TAG, "Couldn't delete temporary file: " + mLocalFromFile); 8801 } 8802 } 8803 } 8804 } 8805 8806 @Override 8807 void handleServiceError() { 8808 mArgs = createInstallArgs(this); 8809 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8810 } 8811 8812 public boolean isForwardLocked() { 8813 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8814 } 8815 8816 public File getFromFile() { 8817 if (mLocalFromFile != null) { 8818 return mLocalFromFile; 8819 } else { 8820 return mFromFile; 8821 } 8822 } 8823 } 8824 8825 /* 8826 * Utility class used in movePackage api. 8827 * srcArgs and targetArgs are not set for invalid flags and make 8828 * sure to do null checks when invoking methods on them. 8829 * We probably want to return ErrorPrams for both failed installs 8830 * and moves. 8831 */ 8832 class MoveParams extends HandlerParams { 8833 final IPackageMoveObserver observer; 8834 final int flags; 8835 final String packageName; 8836 final InstallArgs srcArgs; 8837 final InstallArgs targetArgs; 8838 int uid; 8839 int mRet; 8840 8841 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8842 String packageName, String dataDir, String instructionSet, 8843 int uid, UserHandle user) { 8844 super(user); 8845 this.srcArgs = srcArgs; 8846 this.observer = observer; 8847 this.flags = flags; 8848 this.packageName = packageName; 8849 this.uid = uid; 8850 if (srcArgs != null) { 8851 final String codePath = srcArgs.getCodePath(); 8852 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, dataDir, 8853 instructionSet); 8854 } else { 8855 targetArgs = null; 8856 } 8857 } 8858 8859 @Override 8860 public String toString() { 8861 return "MoveParams{" 8862 + Integer.toHexString(System.identityHashCode(this)) 8863 + " " + packageName + "}"; 8864 } 8865 8866 public void handleStartCopy() throws RemoteException { 8867 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8868 // Check for storage space on target medium 8869 if (!targetArgs.checkFreeStorage(mContainerService)) { 8870 Log.w(TAG, "Insufficient storage to install"); 8871 return; 8872 } 8873 8874 mRet = srcArgs.doPreCopy(); 8875 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8876 return; 8877 } 8878 8879 mRet = targetArgs.copyApk(mContainerService, false); 8880 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8881 srcArgs.doPostCopy(uid); 8882 return; 8883 } 8884 8885 mRet = srcArgs.doPostCopy(uid); 8886 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8887 return; 8888 } 8889 8890 mRet = targetArgs.doPreInstall(mRet); 8891 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8892 return; 8893 } 8894 8895 if (DEBUG_SD_INSTALL) { 8896 StringBuilder builder = new StringBuilder(); 8897 if (srcArgs != null) { 8898 builder.append("src: "); 8899 builder.append(srcArgs.getCodePath()); 8900 } 8901 if (targetArgs != null) { 8902 builder.append(" target : "); 8903 builder.append(targetArgs.getCodePath()); 8904 } 8905 Log.i(TAG, builder.toString()); 8906 } 8907 } 8908 8909 @Override 8910 void handleReturnCode() { 8911 targetArgs.doPostInstall(mRet, uid); 8912 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8913 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8914 currentStatus = PackageManager.MOVE_SUCCEEDED; 8915 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8916 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8917 } 8918 processPendingMove(this, currentStatus); 8919 } 8920 8921 @Override 8922 void handleServiceError() { 8923 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8924 } 8925 } 8926 8927 /** 8928 * Used during creation of InstallArgs 8929 * 8930 * @param flags package installation flags 8931 * @return true if should be installed on external storage 8932 */ 8933 private static boolean installOnSd(int flags) { 8934 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8935 return false; 8936 } 8937 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8938 return true; 8939 } 8940 return false; 8941 } 8942 8943 /** 8944 * Used during creation of InstallArgs 8945 * 8946 * @param flags package installation flags 8947 * @return true if should be installed as forward locked 8948 */ 8949 private static boolean installForwardLocked(int flags) { 8950 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8951 } 8952 8953 private InstallArgs createInstallArgs(InstallParams params) { 8954 // TODO: extend to support incoming zero-copy locations 8955 8956 if (installOnSd(params.flags) || params.isForwardLocked()) { 8957 return new AsecInstallArgs(params); 8958 } else { 8959 return new FileInstallArgs(params); 8960 } 8961 } 8962 8963 /** 8964 * Create args that describe an existing installed package. Typically used 8965 * when cleaning up old installs, or used as a move source. 8966 */ 8967 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 8968 String resourcePath, String nativeLibraryPath, String instructionSet) { 8969 final boolean isInAsec; 8970 if (installOnSd(flags)) { 8971 /* Apps on SD card are always in ASEC containers. */ 8972 isInAsec = true; 8973 } else if (installForwardLocked(flags) 8974 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8975 /* 8976 * Forward-locked apps are only in ASEC containers if they're the 8977 * new style 8978 */ 8979 isInAsec = true; 8980 } else { 8981 isInAsec = false; 8982 } 8983 8984 if (isInAsec) { 8985 return new AsecInstallArgs(codePath, resourcePath, nativeLibraryPath, 8986 instructionSet, installOnSd(flags), installForwardLocked(flags)); 8987 } else { 8988 return new FileInstallArgs(codePath, resourcePath, nativeLibraryPath, instructionSet); 8989 } 8990 } 8991 8992 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 8993 String dataDir, String instructionSet) { 8994 final File codeFile = new File(codePath); 8995 if (installOnSd(flags) || installForwardLocked(flags)) { 8996 String cid = getNextCodePath(codePath, pkgName, "/" 8997 + AsecInstallArgs.RES_FILE_NAME); 8998 return new AsecInstallArgs(codeFile, cid, instructionSet, installOnSd(flags), 8999 installForwardLocked(flags)); 9000 } else { 9001 return new FileInstallArgs(codeFile, pkgName, dataDir, instructionSet); 9002 } 9003 } 9004 9005 static abstract class InstallArgs { 9006 /** 9007 * Location where install is coming from, before it has been 9008 * copied/renamed into place. This could be a single monolithic APK 9009 * file, or a cluster directory. This location is typically untrusted. 9010 */ 9011 final File fromFile; 9012 9013 final IPackageInstallObserver observer; 9014 final IPackageInstallObserver2 observer2; 9015 // Always refers to PackageManager flags only 9016 final int flags; 9017 final String installerPackageName; 9018 final ManifestDigest manifestDigest; 9019 final UserHandle user; 9020 final String instructionSet; 9021 final String abiOverride; 9022 9023 InstallArgs(File fromFile, IPackageInstallObserver observer, 9024 IPackageInstallObserver2 observer2, int flags, String installerPackageName, 9025 ManifestDigest manifestDigest, UserHandle user, String instructionSet, 9026 String abiOverride) { 9027 this.fromFile = fromFile; 9028 this.flags = flags; 9029 this.observer = observer; 9030 this.observer2 = observer2; 9031 this.installerPackageName = installerPackageName; 9032 this.manifestDigest = manifestDigest; 9033 this.user = user; 9034 this.instructionSet = instructionSet; 9035 this.abiOverride = abiOverride; 9036 } 9037 9038 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9039 abstract int doPreInstall(int status); 9040 abstract boolean doRename(int status, String pkgName, String oldCodePath); 9041 abstract int doPostInstall(int status, int uid); 9042 9043 /** @see PackageSettingBase#codePathString */ 9044 abstract String getCodePath(); 9045 /** @see PackageSettingBase#resourcePathString */ 9046 abstract String getResourcePath(); 9047 /** @see PackageSettingBase#nativeLibraryPathString */ 9048 abstract String getNativeLibraryPath(); 9049 9050 // Need installer lock especially for dex file removal. 9051 abstract void cleanUpResourcesLI(); 9052 abstract boolean doPostDeleteLI(boolean delete); 9053 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9054 9055 /** 9056 * Called before the source arguments are copied. This is used mostly 9057 * for MoveParams when it needs to read the source file to put it in the 9058 * destination. 9059 */ 9060 int doPreCopy() { 9061 return PackageManager.INSTALL_SUCCEEDED; 9062 } 9063 9064 /** 9065 * Called after the source arguments are copied. This is used mostly for 9066 * MoveParams when it needs to read the source file to put it in the 9067 * destination. 9068 * 9069 * @return 9070 */ 9071 int doPostCopy(int uid) { 9072 return PackageManager.INSTALL_SUCCEEDED; 9073 } 9074 9075 protected boolean isFwdLocked() { 9076 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9077 } 9078 9079 UserHandle getUser() { 9080 return user; 9081 } 9082 } 9083 9084 /** 9085 * Logic to handle installation of non-ASEC applications, including copying 9086 * and renaming logic. 9087 */ 9088 class FileInstallArgs extends InstallArgs { 9089 // TODO: teach about handling cluster directories 9090 9091 File installDir; 9092 String codeFileName; 9093 String resourceFileName; 9094 String libraryPath; 9095 boolean created = false; 9096 9097 /** New install */ 9098 FileInstallArgs(InstallParams params) { 9099 super(params.getFromFile(), params.observer, params.observer2, params.flags, 9100 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9101 params.packageInstructionSetOverride, params.packageAbiOverride); 9102 } 9103 9104 /** Existing install */ 9105 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9106 String instructionSet) { 9107 super(null, null, null, 0, null, null, null, instructionSet, null); 9108 File codeFile = new File(fullCodePath); 9109 installDir = codeFile.getParentFile(); 9110 codeFileName = fullCodePath; 9111 resourceFileName = fullResourcePath; 9112 libraryPath = nativeLibraryPath; 9113 } 9114 9115 /** New install from existing */ 9116 FileInstallArgs(File fromFile, String pkgName, String dataDir, String instructionSet) { 9117 super(fromFile, null, null, 0, null, null, null, instructionSet, null); 9118 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 9119 String apkName = getNextCodePath(null, pkgName, ".apk"); 9120 codeFileName = new File(installDir, apkName + ".apk").getPath(); 9121 resourceFileName = getResourcePathFromCodePath(); 9122 libraryPath = new File(mAppLibInstallDir, pkgName).getPath(); 9123 } 9124 9125 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9126 final long lowThreshold; 9127 9128 final DeviceStorageMonitorInternal 9129 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9130 if (dsm == null) { 9131 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9132 lowThreshold = 0L; 9133 } else { 9134 if (dsm.isMemoryLow()) { 9135 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9136 return false; 9137 } 9138 9139 lowThreshold = dsm.getMemoryLowThreshold(); 9140 } 9141 9142 return imcs.checkInternalFreeStorage(fromFile.getAbsolutePath(), isFwdLocked(), 9143 lowThreshold); 9144 } 9145 9146 void createCopyFile() { 9147 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 9148 codeFileName = createTempPackageFile(installDir).getPath(); 9149 resourceFileName = getResourcePathFromCodePath(); 9150 libraryPath = getLibraryPathFromCodePath(); 9151 created = true; 9152 } 9153 9154 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9155 if (temp) { 9156 // Generate temp file name 9157 createCopyFile(); 9158 } 9159 // Get a ParcelFileDescriptor to write to the output file 9160 File codeFile = new File(codeFileName); 9161 if (!created) { 9162 try { 9163 codeFile.createNewFile(); 9164 // Set permissions 9165 if (!setPermissions()) { 9166 // Failed setting permissions. 9167 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9168 } 9169 } catch (IOException e) { 9170 Slog.w(TAG, "Failed to create file " + codeFile); 9171 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9172 } 9173 } 9174 ParcelFileDescriptor out = null; 9175 try { 9176 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 9177 } catch (FileNotFoundException e) { 9178 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 9179 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9180 } 9181 // Copy the resource now 9182 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9183 try { 9184 ret = imcs.copyResource(fromFile.getAbsolutePath(), null, out); 9185 } finally { 9186 IoUtils.closeQuietly(out); 9187 } 9188 9189 if (isFwdLocked()) { 9190 final File destResourceFile = new File(getResourcePath()); 9191 9192 // Copy the public files 9193 try { 9194 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 9195 } catch (IOException e) { 9196 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 9197 + " forward-locked app."); 9198 destResourceFile.delete(); 9199 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9200 } 9201 } 9202 9203 final File nativeLibraryFile = new File(getNativeLibraryPath()); 9204 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath()); 9205 if (nativeLibraryFile.exists()) { 9206 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 9207 nativeLibraryFile.delete(); 9208 } 9209 9210 String[] abiList = (abiOverride != null) ? 9211 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9212 NativeLibraryHelper.Handle handle = null; 9213 try { 9214 handle = NativeLibraryHelper.Handle.create(codeFile); 9215 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 9216 abiOverride == null && 9217 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9218 abiList = Build.SUPPORTED_32_BIT_ABIS; 9219 } 9220 9221 int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList); 9222 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9223 return copyRet; 9224 } 9225 } catch (IOException e) { 9226 Slog.e(TAG, "Copying native libraries failed", e); 9227 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9228 } finally { 9229 IoUtils.closeQuietly(handle); 9230 } 9231 9232 return ret; 9233 } 9234 9235 int doPreInstall(int status) { 9236 if (status != PackageManager.INSTALL_SUCCEEDED) { 9237 cleanUp(); 9238 } 9239 return status; 9240 } 9241 9242 boolean doRename(int status, final String pkgName, String oldCodePath) { 9243 if (status != PackageManager.INSTALL_SUCCEEDED) { 9244 cleanUp(); 9245 return false; 9246 } else { 9247 final File oldCodeFile = new File(getCodePath()); 9248 final File oldResourceFile = new File(getResourcePath()); 9249 final File oldLibraryFile = new File(getNativeLibraryPath()); 9250 9251 // Rename APK file based on packageName 9252 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 9253 final File newCodeFile = new File(installDir, apkName + ".apk"); 9254 if (!oldCodeFile.renameTo(newCodeFile)) { 9255 return false; 9256 } 9257 codeFileName = newCodeFile.getPath(); 9258 9259 // Rename public resource file if it's forward-locked. 9260 final File newResFile = new File(getResourcePathFromCodePath()); 9261 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 9262 return false; 9263 } 9264 resourceFileName = newResFile.getPath(); 9265 9266 // Rename library path 9267 final File newLibraryFile = new File(getLibraryPathFromCodePath()); 9268 if (newLibraryFile.exists()) { 9269 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile); 9270 newLibraryFile.delete(); 9271 } 9272 if (!oldLibraryFile.renameTo(newLibraryFile)) { 9273 Slog.e(TAG, "Cannot rename native library directory " 9274 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath()); 9275 return false; 9276 } 9277 libraryPath = newLibraryFile.getPath(); 9278 9279 // Attempt to set permissions 9280 if (!setPermissions()) { 9281 return false; 9282 } 9283 9284 if (!SELinux.restorecon(newCodeFile)) { 9285 return false; 9286 } 9287 9288 return true; 9289 } 9290 } 9291 9292 int doPostInstall(int status, int uid) { 9293 if (status != PackageManager.INSTALL_SUCCEEDED) { 9294 cleanUp(); 9295 } 9296 return status; 9297 } 9298 9299 private String getResourcePathFromCodePath() { 9300 final String codePath = getCodePath(); 9301 if (isFwdLocked()) { 9302 final StringBuilder sb = new StringBuilder(); 9303 9304 sb.append(mAppInstallDir.getPath()); 9305 sb.append('/'); 9306 sb.append(getApkName(codePath)); 9307 sb.append(".zip"); 9308 9309 /* 9310 * If our APK is a temporary file, mark the resource as a 9311 * temporary file as well so it can be cleaned up after 9312 * catastrophic failure. 9313 */ 9314 if (codePath.endsWith(".tmp")) { 9315 sb.append(".tmp"); 9316 } 9317 9318 return sb.toString(); 9319 } else { 9320 return codePath; 9321 } 9322 } 9323 9324 private String getLibraryPathFromCodePath() { 9325 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath(); 9326 } 9327 9328 @Override 9329 String getCodePath() { 9330 return codeFileName; 9331 } 9332 9333 @Override 9334 String getResourcePath() { 9335 return resourceFileName; 9336 } 9337 9338 @Override 9339 String getNativeLibraryPath() { 9340 if (libraryPath == null) { 9341 libraryPath = getLibraryPathFromCodePath(); 9342 } 9343 return libraryPath; 9344 } 9345 9346 private boolean cleanUp() { 9347 boolean ret = true; 9348 String sourceDir = getCodePath(); 9349 String publicSourceDir = getResourcePath(); 9350 if (sourceDir != null) { 9351 File sourceFile = new File(sourceDir); 9352 if (!sourceFile.exists()) { 9353 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 9354 ret = false; 9355 } 9356 // Delete application's code and resources 9357 sourceFile.delete(); 9358 } 9359 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 9360 final File publicSourceFile = new File(publicSourceDir); 9361 if (!publicSourceFile.exists()) { 9362 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 9363 } 9364 if (publicSourceFile.exists()) { 9365 publicSourceFile.delete(); 9366 } 9367 } 9368 9369 if (libraryPath != null) { 9370 File nativeLibraryFile = new File(libraryPath); 9371 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 9372 if (!nativeLibraryFile.delete()) { 9373 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath); 9374 } 9375 } 9376 9377 return ret; 9378 } 9379 9380 void cleanUpResourcesLI() { 9381 String sourceDir = getCodePath(); 9382 if (cleanUp()) { 9383 if (instructionSet == null) { 9384 throw new IllegalStateException("instructionSet == null"); 9385 } 9386 int retCode = mInstaller.rmdex(sourceDir, instructionSet); 9387 if (retCode < 0) { 9388 Slog.w(TAG, "Couldn't remove dex file for package: " 9389 + " at location " 9390 + sourceDir + ", retcode=" + retCode); 9391 // we don't consider this to be a failure of the core package deletion 9392 } 9393 } 9394 } 9395 9396 private boolean setPermissions() { 9397 // TODO Do this in a more elegant way later on. for now just a hack 9398 if (!isFwdLocked()) { 9399 final int filePermissions = 9400 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 9401 |FileUtils.S_IROTH; 9402 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 9403 if (retCode != 0) { 9404 Slog.e(TAG, "Couldn't set new package file permissions for " + 9405 getCodePath() 9406 + ". The return code was: " + retCode); 9407 // TODO Define new internal error 9408 return false; 9409 } 9410 return true; 9411 } 9412 return true; 9413 } 9414 9415 boolean doPostDeleteLI(boolean delete) { 9416 // XXX err, shouldn't we respect the delete flag? 9417 cleanUpResourcesLI(); 9418 return true; 9419 } 9420 } 9421 9422 private boolean isAsecExternal(String cid) { 9423 final String asecPath = PackageHelper.getSdFilesystem(cid); 9424 return !asecPath.startsWith(mAsecInternalPath); 9425 } 9426 9427 /** 9428 * Extract the MountService "container ID" from the full code path of an 9429 * .apk. 9430 */ 9431 static String cidFromCodePath(String fullCodePath) { 9432 int eidx = fullCodePath.lastIndexOf("/"); 9433 String subStr1 = fullCodePath.substring(0, eidx); 9434 int sidx = subStr1.lastIndexOf("/"); 9435 return subStr1.substring(sidx+1, eidx); 9436 } 9437 9438 /** 9439 * Logic to handle installation of ASEC applications, including copying and 9440 * renaming logic. 9441 */ 9442 class AsecInstallArgs extends InstallArgs { 9443 // TODO: teach about handling cluster directories 9444 9445 static final String RES_FILE_NAME = "pkg.apk"; 9446 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9447 9448 String cid; 9449 String packagePath; 9450 String resourcePath; 9451 String libraryPath; 9452 9453 /** New install */ 9454 AsecInstallArgs(InstallParams params) { 9455 super(params.getFromFile(), params.observer, params.observer2, params.flags, 9456 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9457 params.packageInstructionSetOverride, params.packageAbiOverride); 9458 } 9459 9460 /** Existing install */ 9461 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9462 String instructionSet, boolean isExternal, boolean isForwardLocked) { 9463 super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9464 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9465 null, null, null, instructionSet, null); 9466 // Extract cid from fullCodePath 9467 int eidx = fullCodePath.lastIndexOf("/"); 9468 String subStr1 = fullCodePath.substring(0, eidx); 9469 int sidx = subStr1.lastIndexOf("/"); 9470 cid = subStr1.substring(sidx+1, eidx); 9471 setCachePath(subStr1); 9472 } 9473 9474 AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) { 9475 super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 9476 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9477 null, null, null, instructionSet, null); 9478 this.cid = cid; 9479 setCachePath(PackageHelper.getSdDir(cid)); 9480 } 9481 9482 /** New install from existing */ 9483 AsecInstallArgs(File fromFile, String cid, String instructionSet, 9484 boolean isExternal, boolean isForwardLocked) { 9485 super(fromFile, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9486 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9487 null, null, null, instructionSet, null); 9488 this.cid = cid; 9489 } 9490 9491 void createCopyFile() { 9492 cid = getTempContainerId(); 9493 } 9494 9495 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9496 return imcs.checkExternalFreeStorage(fromFile.getAbsolutePath(), isFwdLocked(), 9497 abiOverride); 9498 } 9499 9500 private final boolean isExternal() { 9501 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9502 } 9503 9504 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9505 if (temp) { 9506 createCopyFile(); 9507 } else { 9508 /* 9509 * Pre-emptively destroy the container since it's destroyed if 9510 * copying fails due to it existing anyway. 9511 */ 9512 PackageHelper.destroySdDir(cid); 9513 } 9514 9515 final String newCachePath = imcs.copyResourceToContainer(fromFile.getAbsolutePath(), 9516 cid, getEncryptKey(), RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), 9517 isFwdLocked(), abiOverride); 9518 9519 if (newCachePath != null) { 9520 setCachePath(newCachePath); 9521 return PackageManager.INSTALL_SUCCEEDED; 9522 } else { 9523 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9524 } 9525 } 9526 9527 @Override 9528 String getCodePath() { 9529 return packagePath; 9530 } 9531 9532 @Override 9533 String getResourcePath() { 9534 return resourcePath; 9535 } 9536 9537 @Override 9538 String getNativeLibraryPath() { 9539 return libraryPath; 9540 } 9541 9542 int doPreInstall(int status) { 9543 if (status != PackageManager.INSTALL_SUCCEEDED) { 9544 // Destroy container 9545 PackageHelper.destroySdDir(cid); 9546 } else { 9547 boolean mounted = PackageHelper.isContainerMounted(cid); 9548 if (!mounted) { 9549 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9550 Process.SYSTEM_UID); 9551 if (newCachePath != null) { 9552 setCachePath(newCachePath); 9553 } else { 9554 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9555 } 9556 } 9557 } 9558 return status; 9559 } 9560 9561 boolean doRename(int status, final String pkgName, 9562 String oldCodePath) { 9563 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 9564 String newCachePath = null; 9565 if (PackageHelper.isContainerMounted(cid)) { 9566 // Unmount the container 9567 if (!PackageHelper.unMountSdDir(cid)) { 9568 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9569 return false; 9570 } 9571 } 9572 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9573 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9574 " which might be stale. Will try to clean up."); 9575 // Clean up the stale container and proceed to recreate. 9576 if (!PackageHelper.destroySdDir(newCacheId)) { 9577 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9578 return false; 9579 } 9580 // Successfully cleaned up stale container. Try to rename again. 9581 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9582 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9583 + " inspite of cleaning it up."); 9584 return false; 9585 } 9586 } 9587 if (!PackageHelper.isContainerMounted(newCacheId)) { 9588 Slog.w(TAG, "Mounting container " + newCacheId); 9589 newCachePath = PackageHelper.mountSdDir(newCacheId, 9590 getEncryptKey(), Process.SYSTEM_UID); 9591 } else { 9592 newCachePath = PackageHelper.getSdDir(newCacheId); 9593 } 9594 if (newCachePath == null) { 9595 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9596 return false; 9597 } 9598 Log.i(TAG, "Succesfully renamed " + cid + 9599 " to " + newCacheId + 9600 " at new path: " + newCachePath); 9601 cid = newCacheId; 9602 setCachePath(newCachePath); 9603 return true; 9604 } 9605 9606 private void setCachePath(String newCachePath) { 9607 File cachePath = new File(newCachePath); 9608 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 9609 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9610 9611 if (isFwdLocked()) { 9612 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9613 } else { 9614 resourcePath = packagePath; 9615 } 9616 } 9617 9618 int doPostInstall(int status, int uid) { 9619 if (status != PackageManager.INSTALL_SUCCEEDED) { 9620 cleanUp(); 9621 } else { 9622 final int groupOwner; 9623 final String protectedFile; 9624 if (isFwdLocked()) { 9625 groupOwner = UserHandle.getSharedAppGid(uid); 9626 protectedFile = RES_FILE_NAME; 9627 } else { 9628 groupOwner = -1; 9629 protectedFile = null; 9630 } 9631 9632 if (uid < Process.FIRST_APPLICATION_UID 9633 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9634 Slog.e(TAG, "Failed to finalize " + cid); 9635 PackageHelper.destroySdDir(cid); 9636 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9637 } 9638 9639 boolean mounted = PackageHelper.isContainerMounted(cid); 9640 if (!mounted) { 9641 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9642 } 9643 } 9644 return status; 9645 } 9646 9647 private void cleanUp() { 9648 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9649 9650 // Destroy secure container 9651 PackageHelper.destroySdDir(cid); 9652 } 9653 9654 void cleanUpResourcesLI() { 9655 String sourceFile = getCodePath(); 9656 // Remove dex file 9657 if (instructionSet == null) { 9658 throw new IllegalStateException("instructionSet == null"); 9659 } 9660 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9661 if (retCode < 0) { 9662 Slog.w(TAG, "Couldn't remove dex file for package: " 9663 + " at location " 9664 + sourceFile.toString() + ", retcode=" + retCode); 9665 // we don't consider this to be a failure of the core package deletion 9666 } 9667 cleanUp(); 9668 } 9669 9670 boolean matchContainer(String app) { 9671 if (cid.startsWith(app)) { 9672 return true; 9673 } 9674 return false; 9675 } 9676 9677 String getPackageName() { 9678 return getAsecPackageName(cid); 9679 } 9680 9681 boolean doPostDeleteLI(boolean delete) { 9682 boolean ret = false; 9683 boolean mounted = PackageHelper.isContainerMounted(cid); 9684 if (mounted) { 9685 // Unmount first 9686 ret = PackageHelper.unMountSdDir(cid); 9687 } 9688 if (ret && delete) { 9689 cleanUpResourcesLI(); 9690 } 9691 return ret; 9692 } 9693 9694 @Override 9695 int doPreCopy() { 9696 if (isFwdLocked()) { 9697 if (!PackageHelper.fixSdPermissions(cid, 9698 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9699 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9700 } 9701 } 9702 9703 return PackageManager.INSTALL_SUCCEEDED; 9704 } 9705 9706 @Override 9707 int doPostCopy(int uid) { 9708 if (isFwdLocked()) { 9709 if (uid < Process.FIRST_APPLICATION_UID 9710 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9711 RES_FILE_NAME)) { 9712 Slog.e(TAG, "Failed to finalize " + cid); 9713 PackageHelper.destroySdDir(cid); 9714 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9715 } 9716 } 9717 9718 return PackageManager.INSTALL_SUCCEEDED; 9719 } 9720 } 9721 9722 static String getAsecPackageName(String packageCid) { 9723 int idx = packageCid.lastIndexOf("-"); 9724 if (idx == -1) { 9725 return packageCid; 9726 } 9727 return packageCid.substring(0, idx); 9728 } 9729 9730 // Utility method used to create code paths based on package name and available index. 9731 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9732 String idxStr = ""; 9733 int idx = 1; 9734 // Fall back to default value of idx=1 if prefix is not 9735 // part of oldCodePath 9736 if (oldCodePath != null) { 9737 String subStr = oldCodePath; 9738 // Drop the suffix right away 9739 if (subStr.endsWith(suffix)) { 9740 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9741 } 9742 // If oldCodePath already contains prefix find out the 9743 // ending index to either increment or decrement. 9744 int sidx = subStr.lastIndexOf(prefix); 9745 if (sidx != -1) { 9746 subStr = subStr.substring(sidx + prefix.length()); 9747 if (subStr != null) { 9748 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9749 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9750 } 9751 try { 9752 idx = Integer.parseInt(subStr); 9753 if (idx <= 1) { 9754 idx++; 9755 } else { 9756 idx--; 9757 } 9758 } catch(NumberFormatException e) { 9759 } 9760 } 9761 } 9762 } 9763 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9764 return prefix + idxStr; 9765 } 9766 9767 // Utility method used to ignore ADD/REMOVE events 9768 // by directory observer. 9769 private static boolean ignoreCodePath(String fullPathStr) { 9770 String apkName = getApkName(fullPathStr); 9771 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9772 if (idx != -1 && ((idx+1) < apkName.length())) { 9773 // Make sure the package ends with a numeral 9774 String version = apkName.substring(idx+1); 9775 try { 9776 Integer.parseInt(version); 9777 return true; 9778 } catch (NumberFormatException e) {} 9779 } 9780 return false; 9781 } 9782 9783 // Utility method that returns the relative package path with respect 9784 // to the installation directory. Like say for /data/data/com.test-1.apk 9785 // string com.test-1 is returned. 9786 static String getApkName(String codePath) { 9787 if (codePath == null) { 9788 return null; 9789 } 9790 int sidx = codePath.lastIndexOf("/"); 9791 int eidx = codePath.lastIndexOf("."); 9792 if (eidx == -1) { 9793 eidx = codePath.length(); 9794 } else if (eidx == 0) { 9795 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 9796 return null; 9797 } 9798 return codePath.substring(sidx+1, eidx); 9799 } 9800 9801 private static String[] deriveSplitResPaths(String[] splitCodePaths) { 9802 String[] splitResPaths = null; 9803 if (!ArrayUtils.isEmpty(splitCodePaths)) { 9804 splitResPaths = new String[splitCodePaths.length]; 9805 for (int i = 0; i < splitCodePaths.length; i++) { 9806 final String splitCodePath = splitCodePaths[i]; 9807 final String resName = getApkName(splitCodePath) + ".zip"; 9808 splitResPaths[i] = new File(new File(splitCodePath).getParentFile(), 9809 resName).getAbsolutePath(); 9810 } 9811 } 9812 return splitResPaths; 9813 } 9814 9815 class PackageInstalledInfo { 9816 String name; 9817 int uid; 9818 // The set of users that originally had this package installed. 9819 int[] origUsers; 9820 // The set of users that now have this package installed. 9821 int[] newUsers; 9822 PackageParser.Package pkg; 9823 int returnCode; 9824 PackageRemovedInfo removedInfo; 9825 9826 // In some error cases we want to convey more info back to the observer 9827 String origPackage; 9828 String origPermission; 9829 } 9830 9831 /* 9832 * Install a non-existing package. 9833 */ 9834 private void installNewPackageLI(PackageParser.Package pkg, 9835 int parseFlags, int scanMode, UserHandle user, 9836 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9837 // Remember this for later, in case we need to rollback this install 9838 String pkgName = pkg.packageName; 9839 9840 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9841 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9842 synchronized(mPackages) { 9843 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9844 // A package with the same name is already installed, though 9845 // it has been renamed to an older name. The package we 9846 // are trying to install should be installed as an update to 9847 // the existing one, but that has not been requested, so bail. 9848 Slog.w(TAG, "Attempt to re-install " + pkgName 9849 + " without first uninstalling package running as " 9850 + mSettings.mRenamedPackages.get(pkgName)); 9851 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9852 return; 9853 } 9854 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9855 // Don't allow installation over an existing package with the same name. 9856 Slog.w(TAG, "Attempt to re-install " + pkgName 9857 + " without first uninstalling."); 9858 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9859 return; 9860 } 9861 } 9862 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9863 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9864 System.currentTimeMillis(), user, abiOverride); 9865 if (newPackage == null) { 9866 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9867 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9868 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9869 } 9870 } else { 9871 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9872 // delete the partially installed application. the data directory will have to be 9873 // restored if it was already existing 9874 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9875 // remove package from internal structures. Note that we want deletePackageX to 9876 // delete the package data and cache directories that it created in 9877 // scanPackageLocked, unless those directories existed before we even tried to 9878 // install. 9879 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9880 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9881 res.removedInfo, true); 9882 } 9883 } 9884 } 9885 9886 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9887 // Upgrade keysets are being used. Determine if new package has a superset of the 9888 // required keys. 9889 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9890 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9891 Set<Long> newSigningKeyIds = new ArraySet<Long>(); 9892 for (PublicKey pk : newPkg.mSigningKeys) { 9893 newSigningKeyIds.add(ksms.getIdForPublicKey(pk)); 9894 } 9895 //remove PUBLIC_KEY_NOT_FOUND, although not necessary 9896 newSigningKeyIds.remove(ksms.PUBLIC_KEY_NOT_FOUND); 9897 for (int i = 0; i < upgradeKeySets.length; i++) { 9898 if (newSigningKeyIds.containsAll(ksms.mKeySetMapping.get(upgradeKeySets[i]))) { 9899 return true; 9900 } 9901 } 9902 return false; 9903 } 9904 9905 private void replacePackageLI(PackageParser.Package pkg, 9906 int parseFlags, int scanMode, UserHandle user, 9907 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9908 PackageParser.Package oldPackage; 9909 String pkgName = pkg.packageName; 9910 int[] allUsers; 9911 boolean[] perUserInstalled; 9912 9913 // First find the old package info and check signatures 9914 synchronized(mPackages) { 9915 oldPackage = mPackages.get(pkgName); 9916 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9917 PackageSetting ps = mSettings.mPackages.get(pkgName); 9918 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9919 // default to original signature matching 9920 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9921 != PackageManager.SIGNATURE_MATCH) { 9922 Slog.w(TAG, "New package has a different signature: " + pkgName); 9923 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9924 return; 9925 } 9926 } else { 9927 if(!checkUpgradeKeySetLP(ps, pkg)) { 9928 Slog.w(TAG, "New package not signed by keys specified by upgrade-keysets: " 9929 + pkgName); 9930 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9931 return; 9932 } 9933 } 9934 9935 // In case of rollback, remember per-user/profile install state 9936 allUsers = sUserManager.getUserIds(); 9937 perUserInstalled = new boolean[allUsers.length]; 9938 for (int i = 0; i < allUsers.length; i++) { 9939 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9940 } 9941 } 9942 boolean sysPkg = (isSystemApp(oldPackage)); 9943 if (sysPkg) { 9944 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9945 user, allUsers, perUserInstalled, installerPackageName, res, 9946 abiOverride); 9947 } else { 9948 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9949 user, allUsers, perUserInstalled, installerPackageName, res, 9950 abiOverride); 9951 } 9952 } 9953 9954 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9955 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9956 int[] allUsers, boolean[] perUserInstalled, 9957 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9958 PackageParser.Package newPackage = null; 9959 String pkgName = deletedPackage.packageName; 9960 boolean deletedPkg = true; 9961 boolean updatedSettings = false; 9962 9963 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9964 + deletedPackage); 9965 long origUpdateTime; 9966 if (pkg.mExtras != null) { 9967 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9968 } else { 9969 origUpdateTime = 0; 9970 } 9971 9972 // First delete the existing package while retaining the data directory 9973 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9974 res.removedInfo, true)) { 9975 // If the existing package wasn't successfully deleted 9976 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9977 deletedPkg = false; 9978 } else { 9979 // Successfully deleted the old package. Now proceed with re-installation 9980 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9981 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9982 System.currentTimeMillis(), user, abiOverride); 9983 if (newPackage == null) { 9984 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9985 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9986 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9987 } 9988 } else { 9989 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9990 updatedSettings = true; 9991 } 9992 } 9993 9994 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9995 // remove package from internal structures. Note that we want deletePackageX to 9996 // delete the package data and cache directories that it created in 9997 // scanPackageLocked, unless those directories existed before we even tried to 9998 // install. 9999 if(updatedSettings) { 10000 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10001 deletePackageLI( 10002 pkgName, null, true, allUsers, perUserInstalled, 10003 PackageManager.DELETE_KEEP_DATA, 10004 res.removedInfo, true); 10005 } 10006 // Since we failed to install the new package we need to restore the old 10007 // package that we deleted. 10008 if (deletedPkg) { 10009 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10010 File restoreFile = new File(deletedPackage.codePath); 10011 // Parse old package 10012 boolean oldOnSd = isExternal(deletedPackage); 10013 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10014 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10015 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10016 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10017 | SCAN_UPDATE_TIME; 10018 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 10019 origUpdateTime, null, null) == null) { 10020 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 10021 return; 10022 } 10023 // Restore of old package succeeded. Update permissions. 10024 // writer 10025 synchronized (mPackages) { 10026 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10027 UPDATE_PERMISSIONS_ALL); 10028 // can downgrade to reader 10029 mSettings.writeLPr(); 10030 } 10031 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10032 } 10033 } 10034 } 10035 10036 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10037 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10038 int[] allUsers, boolean[] perUserInstalled, 10039 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10040 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10041 + ", old=" + deletedPackage); 10042 PackageParser.Package newPackage = null; 10043 boolean updatedSettings = false; 10044 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10045 PackageParser.PARSE_IS_SYSTEM; 10046 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10047 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10048 } 10049 String packageName = deletedPackage.packageName; 10050 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 10051 if (packageName == null) { 10052 Slog.w(TAG, "Attempt to delete null packageName."); 10053 return; 10054 } 10055 PackageParser.Package oldPkg; 10056 PackageSetting oldPkgSetting; 10057 // reader 10058 synchronized (mPackages) { 10059 oldPkg = mPackages.get(packageName); 10060 oldPkgSetting = mSettings.mPackages.get(packageName); 10061 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10062 (oldPkgSetting == null)) { 10063 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 10064 return; 10065 } 10066 } 10067 10068 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10069 10070 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10071 res.removedInfo.removedPackage = packageName; 10072 // Remove existing system package 10073 removePackageLI(oldPkgSetting, true); 10074 // writer 10075 synchronized (mPackages) { 10076 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10077 // We didn't need to disable the .apk as a current system package, 10078 // which means we are replacing another update that is already 10079 // installed. We need to make sure to delete the older one's .apk. 10080 res.removedInfo.args = createInstallArgsForExisting(0, 10081 deletedPackage.applicationInfo.sourceDir, 10082 deletedPackage.applicationInfo.publicSourceDir, 10083 deletedPackage.applicationInfo.nativeLibraryDir, 10084 getAppInstructionSet(deletedPackage.applicationInfo)); 10085 } else { 10086 res.removedInfo.args = null; 10087 } 10088 } 10089 10090 // Successfully disabled the old package. Now proceed with re-installation 10091 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 10092 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10093 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10094 if (newPackage == null) { 10095 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 10096 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 10097 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 10098 } 10099 } else { 10100 if (newPackage.mExtras != null) { 10101 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 10102 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10103 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10104 10105 // is the update attempting to change shared user? that isn't going to work... 10106 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10107 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 10108 + " to " + newPkgSetting.sharedUser); 10109 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 10110 updatedSettings = true; 10111 } 10112 } 10113 10114 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10115 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10116 updatedSettings = true; 10117 } 10118 } 10119 10120 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10121 // Re installation failed. Restore old information 10122 // Remove new pkg information 10123 if (newPackage != null) { 10124 removeInstalledPackageLI(newPackage, true); 10125 } 10126 // Add back the old system package 10127 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null); 10128 // Restore the old system information in Settings 10129 synchronized(mPackages) { 10130 if (updatedSettings) { 10131 mSettings.enableSystemPackageLPw(packageName); 10132 mSettings.setInstallerPackageName(packageName, 10133 oldPkgSetting.installerPackageName); 10134 } 10135 mSettings.writeLPr(); 10136 } 10137 } 10138 } 10139 10140 // Utility method used to move dex files during install. 10141 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10142 // TODO: extend to move split APK dex files 10143 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10144 final String instructionSet = getAppInstructionSet(newPackage.applicationInfo); 10145 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10146 instructionSet); 10147 if (retCode != 0) { 10148 /* 10149 * Programs may be lazily run through dexopt, so the 10150 * source may not exist. However, something seems to 10151 * have gone wrong, so note that dexopt needs to be 10152 * run again and remove the source file. In addition, 10153 * remove the target to make sure there isn't a stale 10154 * file from a previous version of the package. 10155 */ 10156 newPackage.mDexOptNeeded = true; 10157 mInstaller.rmdex(oldCodePath, instructionSet); 10158 mInstaller.rmdex(newPackage.baseCodePath, instructionSet); 10159 } 10160 } 10161 return PackageManager.INSTALL_SUCCEEDED; 10162 } 10163 10164 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10165 int[] allUsers, boolean[] perUserInstalled, 10166 PackageInstalledInfo res) { 10167 String pkgName = newPackage.packageName; 10168 synchronized (mPackages) { 10169 //write settings. the installStatus will be incomplete at this stage. 10170 //note that the new package setting would have already been 10171 //added to mPackages. It hasn't been persisted yet. 10172 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10173 mSettings.writeLPr(); 10174 } 10175 10176 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10177 10178 synchronized (mPackages) { 10179 updatePermissionsLPw(newPackage.packageName, newPackage, 10180 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10181 ? UPDATE_PERMISSIONS_ALL : 0)); 10182 // For system-bundled packages, we assume that installing an upgraded version 10183 // of the package implies that the user actually wants to run that new code, 10184 // so we enable the package. 10185 if (isSystemApp(newPackage)) { 10186 // NB: implicit assumption that system package upgrades apply to all users 10187 if (DEBUG_INSTALL) { 10188 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10189 } 10190 PackageSetting ps = mSettings.mPackages.get(pkgName); 10191 if (ps != null) { 10192 if (res.origUsers != null) { 10193 for (int userHandle : res.origUsers) { 10194 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10195 userHandle, installerPackageName); 10196 } 10197 } 10198 // Also convey the prior install/uninstall state 10199 if (allUsers != null && perUserInstalled != null) { 10200 for (int i = 0; i < allUsers.length; i++) { 10201 if (DEBUG_INSTALL) { 10202 Slog.d(TAG, " user " + allUsers[i] 10203 + " => " + perUserInstalled[i]); 10204 } 10205 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10206 } 10207 // these install state changes will be persisted in the 10208 // upcoming call to mSettings.writeLPr(). 10209 } 10210 } 10211 } 10212 res.name = pkgName; 10213 res.uid = newPackage.applicationInfo.uid; 10214 res.pkg = newPackage; 10215 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10216 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10217 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10218 //to update install status 10219 mSettings.writeLPr(); 10220 } 10221 } 10222 10223 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10224 int pFlags = args.flags; 10225 String installerPackageName = args.installerPackageName; 10226 File tmpPackageFile = new File(args.getCodePath()); 10227 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10228 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10229 boolean replace = false; 10230 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10231 | (newInstall ? SCAN_NEW_INSTALL : 0); 10232 // Result object to be returned 10233 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10234 10235 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10236 // Retrieve PackageSettings and parse package 10237 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10238 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10239 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10240 PackageParser pp = new PackageParser(); 10241 pp.setSeparateProcesses(mSeparateProcesses); 10242 pp.setDisplayMetrics(mMetrics); 10243 10244 final PackageParser.Package pkg; 10245 try { 10246 pkg = pp.parseMonolithicPackage(tmpPackageFile, parseFlags); 10247 } catch (PackageParserException e) { 10248 res.returnCode = e.error; 10249 return; 10250 } 10251 10252 String pkgName = res.name = pkg.packageName; 10253 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10254 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10255 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 10256 return; 10257 } 10258 } 10259 10260 try { 10261 pp.collectCertificates(pkg, parseFlags); 10262 pp.collectManifestDigest(pkg); 10263 } catch (PackageParserException e) { 10264 res.returnCode = e.error; 10265 return; 10266 } 10267 10268 /* If the installer passed in a manifest digest, compare it now. */ 10269 if (args.manifestDigest != null) { 10270 if (DEBUG_INSTALL) { 10271 final String parsedManifest = pkg.manifestDigest == null ? "null" 10272 : pkg.manifestDigest.toString(); 10273 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10274 + parsedManifest); 10275 } 10276 10277 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10278 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 10279 return; 10280 } 10281 } else if (DEBUG_INSTALL) { 10282 final String parsedManifest = pkg.manifestDigest == null 10283 ? "null" : pkg.manifestDigest.toString(); 10284 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10285 } 10286 10287 // Get rid of all references to package scan path via parser. 10288 pp = null; 10289 String oldCodePath = null; 10290 boolean systemApp = false; 10291 synchronized (mPackages) { 10292 // Check whether the newly-scanned package wants to define an already-defined perm 10293 int N = pkg.permissions.size(); 10294 for (int i = N-1; i >= 0; i--) { 10295 PackageParser.Permission perm = pkg.permissions.get(i); 10296 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10297 if (bp != null) { 10298 // If the defining package is signed with our cert, it's okay. This 10299 // also includes the "updating the same package" case, of course. 10300 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10301 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10302 // If the owning package is the system itself, we log but allow 10303 // install to proceed; we fail the install on all other permission 10304 // redefinitions. 10305 if (!bp.sourcePackage.equals("android")) { 10306 Slog.w(TAG, "Package " + pkg.packageName 10307 + " attempting to redeclare permission " + perm.info.name 10308 + " already owned by " + bp.sourcePackage); 10309 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 10310 res.origPermission = perm.info.name; 10311 res.origPackage = bp.sourcePackage; 10312 return; 10313 } else { 10314 Slog.w(TAG, "Package " + pkg.packageName 10315 + " attempting to redeclare system permission " 10316 + perm.info.name + "; ignoring new declaration"); 10317 pkg.permissions.remove(i); 10318 } 10319 } 10320 } 10321 } 10322 10323 // Check if installing already existing package 10324 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10325 String oldName = mSettings.mRenamedPackages.get(pkgName); 10326 if (pkg.mOriginalPackages != null 10327 && pkg.mOriginalPackages.contains(oldName) 10328 && mPackages.containsKey(oldName)) { 10329 // This package is derived from an original package, 10330 // and this device has been updating from that original 10331 // name. We must continue using the original name, so 10332 // rename the new package here. 10333 pkg.setPackageName(oldName); 10334 pkgName = pkg.packageName; 10335 replace = true; 10336 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10337 + oldName + " pkgName=" + pkgName); 10338 } else if (mPackages.containsKey(pkgName)) { 10339 // This package, under its official name, already exists 10340 // on the device; we should replace it. 10341 replace = true; 10342 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10343 } 10344 } 10345 PackageSetting ps = mSettings.mPackages.get(pkgName); 10346 if (ps != null) { 10347 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10348 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10349 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10350 systemApp = (ps.pkg.applicationInfo.flags & 10351 ApplicationInfo.FLAG_SYSTEM) != 0; 10352 } 10353 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10354 } 10355 } 10356 10357 if (systemApp && onSd) { 10358 // Disable updates to system apps on sdcard 10359 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 10360 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10361 return; 10362 } 10363 10364 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 10365 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10366 return; 10367 } 10368 10369 // Set application objects path explicitly after the rename 10370 // TODO: derive split paths from original scan after rename 10371 pkg.codePath = args.getCodePath(); 10372 pkg.baseCodePath = args.getCodePath(); 10373 pkg.splitCodePaths = null; 10374 pkg.applicationInfo.sourceDir = args.getCodePath(); 10375 pkg.applicationInfo.publicSourceDir = args.getResourcePath(); 10376 pkg.applicationInfo.splitSourceDirs = null; 10377 pkg.applicationInfo.splitPublicSourceDirs = null; 10378 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 10379 10380 if (replace) { 10381 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10382 installerPackageName, res, args.abiOverride); 10383 } else { 10384 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10385 installerPackageName, res, args.abiOverride); 10386 } 10387 synchronized (mPackages) { 10388 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10389 if (ps != null) { 10390 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10391 } 10392 } 10393 } 10394 10395 private static boolean isForwardLocked(PackageParser.Package pkg) { 10396 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10397 } 10398 10399 10400 private boolean isForwardLocked(PackageSetting ps) { 10401 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10402 } 10403 10404 private static boolean isExternal(PackageParser.Package pkg) { 10405 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10406 } 10407 10408 private static boolean isExternal(PackageSetting ps) { 10409 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10410 } 10411 10412 private static boolean isSystemApp(PackageParser.Package pkg) { 10413 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10414 } 10415 10416 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10417 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10418 } 10419 10420 private static boolean isSystemApp(ApplicationInfo info) { 10421 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10422 } 10423 10424 private static boolean isSystemApp(PackageSetting ps) { 10425 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10426 } 10427 10428 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10429 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10430 } 10431 10432 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10433 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10434 } 10435 10436 private int packageFlagsToInstallFlags(PackageSetting ps) { 10437 int installFlags = 0; 10438 if (isExternal(ps)) { 10439 installFlags |= PackageManager.INSTALL_EXTERNAL; 10440 } 10441 if (isForwardLocked(ps)) { 10442 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10443 } 10444 return installFlags; 10445 } 10446 10447 private void deleteTempPackageFiles() { 10448 final FilenameFilter filter = new FilenameFilter() { 10449 public boolean accept(File dir, String name) { 10450 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10451 } 10452 }; 10453 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 10454 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 10455 } 10456 10457 private static final void deleteTempPackageFilesInDirectory(File directory, 10458 FilenameFilter filter) { 10459 final String[] tmpFilesList = directory.list(filter); 10460 if (tmpFilesList == null) { 10461 return; 10462 } 10463 for (int i = 0; i < tmpFilesList.length; i++) { 10464 final File tmpFile = new File(directory, tmpFilesList[i]); 10465 tmpFile.delete(); 10466 } 10467 } 10468 10469 private File createTempPackageFile(File installDir) { 10470 File tmpPackageFile; 10471 try { 10472 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 10473 } catch (IOException e) { 10474 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 10475 return null; 10476 } 10477 try { 10478 FileUtils.setPermissions( 10479 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 10480 -1, -1); 10481 if (!SELinux.restorecon(tmpPackageFile)) { 10482 return null; 10483 } 10484 } catch (IOException e) { 10485 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 10486 return null; 10487 } 10488 return tmpPackageFile; 10489 } 10490 10491 @Override 10492 public void deletePackageAsUser(final String packageName, 10493 final IPackageDeleteObserver observer, 10494 final int userId, final int flags) { 10495 mContext.enforceCallingOrSelfPermission( 10496 android.Manifest.permission.DELETE_PACKAGES, null); 10497 final int uid = Binder.getCallingUid(); 10498 if (UserHandle.getUserId(uid) != userId) { 10499 mContext.enforceCallingPermission( 10500 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10501 "deletePackage for user " + userId); 10502 } 10503 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10504 try { 10505 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10506 } catch (RemoteException re) { 10507 } 10508 return; 10509 } 10510 10511 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10512 // Queue up an async operation since the package deletion may take a little while. 10513 mHandler.post(new Runnable() { 10514 public void run() { 10515 mHandler.removeCallbacks(this); 10516 final int returnCode = deletePackageX(packageName, userId, flags); 10517 if (observer != null) { 10518 try { 10519 observer.packageDeleted(packageName, returnCode); 10520 } catch (RemoteException e) { 10521 Log.i(TAG, "Observer no longer exists."); 10522 } //end catch 10523 } //end if 10524 } //end run 10525 }); 10526 } 10527 10528 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10529 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10530 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10531 try { 10532 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10533 || dpm.isDeviceOwner(packageName))) { 10534 return true; 10535 } 10536 } catch (RemoteException e) { 10537 } 10538 return false; 10539 } 10540 10541 /** 10542 * This method is an internal method that could be get invoked either 10543 * to delete an installed package or to clean up a failed installation. 10544 * After deleting an installed package, a broadcast is sent to notify any 10545 * listeners that the package has been installed. For cleaning up a failed 10546 * installation, the broadcast is not necessary since the package's 10547 * installation wouldn't have sent the initial broadcast either 10548 * The key steps in deleting a package are 10549 * deleting the package information in internal structures like mPackages, 10550 * deleting the packages base directories through installd 10551 * updating mSettings to reflect current status 10552 * persisting settings for later use 10553 * sending a broadcast if necessary 10554 */ 10555 private int deletePackageX(String packageName, int userId, int flags) { 10556 final PackageRemovedInfo info = new PackageRemovedInfo(); 10557 final boolean res; 10558 10559 if (isPackageDeviceAdmin(packageName, userId)) { 10560 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10561 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10562 } 10563 10564 boolean removedForAllUsers = false; 10565 boolean systemUpdate = false; 10566 10567 // for the uninstall-updates case and restricted profiles, remember the per- 10568 // userhandle installed state 10569 int[] allUsers; 10570 boolean[] perUserInstalled; 10571 synchronized (mPackages) { 10572 PackageSetting ps = mSettings.mPackages.get(packageName); 10573 allUsers = sUserManager.getUserIds(); 10574 perUserInstalled = new boolean[allUsers.length]; 10575 for (int i = 0; i < allUsers.length; i++) { 10576 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10577 } 10578 } 10579 10580 synchronized (mInstallLock) { 10581 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10582 res = deletePackageLI(packageName, 10583 (flags & PackageManager.DELETE_ALL_USERS) != 0 10584 ? UserHandle.ALL : new UserHandle(userId), 10585 true, allUsers, perUserInstalled, 10586 flags | REMOVE_CHATTY, info, true); 10587 systemUpdate = info.isRemovedPackageSystemUpdate; 10588 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10589 removedForAllUsers = true; 10590 } 10591 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10592 + " removedForAllUsers=" + removedForAllUsers); 10593 } 10594 10595 if (res) { 10596 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10597 10598 // If the removed package was a system update, the old system package 10599 // was re-enabled; we need to broadcast this information 10600 if (systemUpdate) { 10601 Bundle extras = new Bundle(1); 10602 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10603 ? info.removedAppId : info.uid); 10604 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10605 10606 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10607 extras, null, null, null); 10608 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10609 extras, null, null, null); 10610 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10611 null, packageName, null, null); 10612 } 10613 } 10614 // Force a gc here. 10615 Runtime.getRuntime().gc(); 10616 // Delete the resources here after sending the broadcast to let 10617 // other processes clean up before deleting resources. 10618 if (info.args != null) { 10619 synchronized (mInstallLock) { 10620 info.args.doPostDeleteLI(true); 10621 } 10622 } 10623 10624 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10625 } 10626 10627 static class PackageRemovedInfo { 10628 String removedPackage; 10629 int uid = -1; 10630 int removedAppId = -1; 10631 int[] removedUsers = null; 10632 boolean isRemovedPackageSystemUpdate = false; 10633 // Clean up resources deleted packages. 10634 InstallArgs args = null; 10635 10636 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10637 Bundle extras = new Bundle(1); 10638 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10639 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10640 if (replacing) { 10641 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10642 } 10643 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10644 if (removedPackage != null) { 10645 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10646 extras, null, null, removedUsers); 10647 if (fullRemove && !replacing) { 10648 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10649 extras, null, null, removedUsers); 10650 } 10651 } 10652 if (removedAppId >= 0) { 10653 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10654 removedUsers); 10655 } 10656 } 10657 } 10658 10659 /* 10660 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10661 * flag is not set, the data directory is removed as well. 10662 * make sure this flag is set for partially installed apps. If not its meaningless to 10663 * delete a partially installed application. 10664 */ 10665 private void removePackageDataLI(PackageSetting ps, 10666 int[] allUserHandles, boolean[] perUserInstalled, 10667 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10668 String packageName = ps.name; 10669 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10670 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10671 // Retrieve object to delete permissions for shared user later on 10672 final PackageSetting deletedPs; 10673 // reader 10674 synchronized (mPackages) { 10675 deletedPs = mSettings.mPackages.get(packageName); 10676 if (outInfo != null) { 10677 outInfo.removedPackage = packageName; 10678 outInfo.removedUsers = deletedPs != null 10679 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10680 : null; 10681 } 10682 } 10683 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10684 removeDataDirsLI(packageName); 10685 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10686 } 10687 // writer 10688 synchronized (mPackages) { 10689 if (deletedPs != null) { 10690 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10691 if (outInfo != null) { 10692 mSettings.mKeySetManagerService.removeAppKeySetData(packageName); 10693 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10694 } 10695 if (deletedPs != null) { 10696 updatePermissionsLPw(deletedPs.name, null, 0); 10697 if (deletedPs.sharedUser != null) { 10698 // remove permissions associated with package 10699 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10700 } 10701 } 10702 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10703 } 10704 // make sure to preserve per-user disabled state if this removal was just 10705 // a downgrade of a system app to the factory package 10706 if (allUserHandles != null && perUserInstalled != null) { 10707 if (DEBUG_REMOVE) { 10708 Slog.d(TAG, "Propagating install state across downgrade"); 10709 } 10710 for (int i = 0; i < allUserHandles.length; i++) { 10711 if (DEBUG_REMOVE) { 10712 Slog.d(TAG, " user " + allUserHandles[i] 10713 + " => " + perUserInstalled[i]); 10714 } 10715 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10716 } 10717 } 10718 } 10719 // can downgrade to reader 10720 if (writeSettings) { 10721 // Save settings now 10722 mSettings.writeLPr(); 10723 } 10724 } 10725 if (outInfo != null) { 10726 // A user ID was deleted here. Go through all users and remove it 10727 // from KeyStore. 10728 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10729 } 10730 } 10731 10732 static boolean locationIsPrivileged(File path) { 10733 try { 10734 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10735 .getCanonicalPath(); 10736 return path.getCanonicalPath().startsWith(privilegedAppDir); 10737 } catch (IOException e) { 10738 Slog.e(TAG, "Unable to access code path " + path); 10739 } 10740 return false; 10741 } 10742 10743 /* 10744 * Tries to delete system package. 10745 */ 10746 private boolean deleteSystemPackageLI(PackageSetting newPs, 10747 int[] allUserHandles, boolean[] perUserInstalled, 10748 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10749 final boolean applyUserRestrictions 10750 = (allUserHandles != null) && (perUserInstalled != null); 10751 PackageSetting disabledPs = null; 10752 // Confirm if the system package has been updated 10753 // An updated system app can be deleted. This will also have to restore 10754 // the system pkg from system partition 10755 // reader 10756 synchronized (mPackages) { 10757 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10758 } 10759 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10760 + " disabledPs=" + disabledPs); 10761 if (disabledPs == null) { 10762 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10763 return false; 10764 } else if (DEBUG_REMOVE) { 10765 Slog.d(TAG, "Deleting system pkg from data partition"); 10766 } 10767 if (DEBUG_REMOVE) { 10768 if (applyUserRestrictions) { 10769 Slog.d(TAG, "Remembering install states:"); 10770 for (int i = 0; i < allUserHandles.length; i++) { 10771 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10772 } 10773 } 10774 } 10775 // Delete the updated package 10776 outInfo.isRemovedPackageSystemUpdate = true; 10777 if (disabledPs.versionCode < newPs.versionCode) { 10778 // Delete data for downgrades 10779 flags &= ~PackageManager.DELETE_KEEP_DATA; 10780 } else { 10781 // Preserve data by setting flag 10782 flags |= PackageManager.DELETE_KEEP_DATA; 10783 } 10784 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10785 allUserHandles, perUserInstalled, outInfo, writeSettings); 10786 if (!ret) { 10787 return false; 10788 } 10789 // writer 10790 synchronized (mPackages) { 10791 // Reinstate the old system package 10792 mSettings.enableSystemPackageLPw(newPs.name); 10793 // Remove any native libraries from the upgraded package. 10794 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 10795 } 10796 // Install the system package 10797 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10798 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10799 if (locationIsPrivileged(disabledPs.codePath)) { 10800 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10801 } 10802 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10803 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null); 10804 10805 if (newPkg == null) { 10806 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10807 + " with error:" + mLastScanError); 10808 return false; 10809 } 10810 // writer 10811 synchronized (mPackages) { 10812 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10813 setInternalAppNativeLibraryPath(newPkg, ps); 10814 updatePermissionsLPw(newPkg.packageName, newPkg, 10815 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10816 if (applyUserRestrictions) { 10817 if (DEBUG_REMOVE) { 10818 Slog.d(TAG, "Propagating install state across reinstall"); 10819 } 10820 for (int i = 0; i < allUserHandles.length; i++) { 10821 if (DEBUG_REMOVE) { 10822 Slog.d(TAG, " user " + allUserHandles[i] 10823 + " => " + perUserInstalled[i]); 10824 } 10825 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10826 } 10827 // Regardless of writeSettings we need to ensure that this restriction 10828 // state propagation is persisted 10829 mSettings.writeAllUsersPackageRestrictionsLPr(); 10830 } 10831 // can downgrade to reader here 10832 if (writeSettings) { 10833 mSettings.writeLPr(); 10834 } 10835 } 10836 return true; 10837 } 10838 10839 private boolean deleteInstalledPackageLI(PackageSetting ps, 10840 boolean deleteCodeAndResources, int flags, 10841 int[] allUserHandles, boolean[] perUserInstalled, 10842 PackageRemovedInfo outInfo, boolean writeSettings) { 10843 if (outInfo != null) { 10844 outInfo.uid = ps.appId; 10845 } 10846 10847 // Delete package data from internal structures and also remove data if flag is set 10848 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10849 10850 // Delete application code and resources 10851 if (deleteCodeAndResources && (outInfo != null)) { 10852 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10853 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 10854 getAppInstructionSetFromSettings(ps)); 10855 } 10856 return true; 10857 } 10858 10859 @Override 10860 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10861 int userId) { 10862 mContext.enforceCallingOrSelfPermission( 10863 android.Manifest.permission.DELETE_PACKAGES, null); 10864 synchronized (mPackages) { 10865 PackageSetting ps = mSettings.mPackages.get(packageName); 10866 if (ps == null) { 10867 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10868 return false; 10869 } 10870 if (!ps.getInstalled(userId)) { 10871 // Can't block uninstall for an app that is not installed or enabled. 10872 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10873 return false; 10874 } 10875 ps.setBlockUninstall(blockUninstall, userId); 10876 mSettings.writePackageRestrictionsLPr(userId); 10877 } 10878 return true; 10879 } 10880 10881 @Override 10882 public boolean getBlockUninstallForUser(String packageName, int userId) { 10883 synchronized (mPackages) { 10884 PackageSetting ps = mSettings.mPackages.get(packageName); 10885 if (ps == null) { 10886 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10887 return false; 10888 } 10889 return ps.getBlockUninstall(userId); 10890 } 10891 } 10892 10893 /* 10894 * This method handles package deletion in general 10895 */ 10896 private boolean deletePackageLI(String packageName, UserHandle user, 10897 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10898 int flags, PackageRemovedInfo outInfo, 10899 boolean writeSettings) { 10900 if (packageName == null) { 10901 Slog.w(TAG, "Attempt to delete null packageName."); 10902 return false; 10903 } 10904 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10905 PackageSetting ps; 10906 boolean dataOnly = false; 10907 int removeUser = -1; 10908 int appId = -1; 10909 synchronized (mPackages) { 10910 ps = mSettings.mPackages.get(packageName); 10911 if (ps == null) { 10912 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10913 return false; 10914 } 10915 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10916 && user.getIdentifier() != UserHandle.USER_ALL) { 10917 // The caller is asking that the package only be deleted for a single 10918 // user. To do this, we just mark its uninstalled state and delete 10919 // its data. If this is a system app, we only allow this to happen if 10920 // they have set the special DELETE_SYSTEM_APP which requests different 10921 // semantics than normal for uninstalling system apps. 10922 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10923 ps.setUserState(user.getIdentifier(), 10924 COMPONENT_ENABLED_STATE_DEFAULT, 10925 false, //installed 10926 true, //stopped 10927 true, //notLaunched 10928 false, //blocked 10929 null, null, null, 10930 false // blockUninstall 10931 ); 10932 if (!isSystemApp(ps)) { 10933 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10934 // Other user still have this package installed, so all 10935 // we need to do is clear this user's data and save that 10936 // it is uninstalled. 10937 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10938 removeUser = user.getIdentifier(); 10939 appId = ps.appId; 10940 mSettings.writePackageRestrictionsLPr(removeUser); 10941 } else { 10942 // We need to set it back to 'installed' so the uninstall 10943 // broadcasts will be sent correctly. 10944 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10945 ps.setInstalled(true, user.getIdentifier()); 10946 } 10947 } else { 10948 // This is a system app, so we assume that the 10949 // other users still have this package installed, so all 10950 // we need to do is clear this user's data and save that 10951 // it is uninstalled. 10952 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10953 removeUser = user.getIdentifier(); 10954 appId = ps.appId; 10955 mSettings.writePackageRestrictionsLPr(removeUser); 10956 } 10957 } 10958 } 10959 10960 if (removeUser >= 0) { 10961 // From above, we determined that we are deleting this only 10962 // for a single user. Continue the work here. 10963 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10964 if (outInfo != null) { 10965 outInfo.removedPackage = packageName; 10966 outInfo.removedAppId = appId; 10967 outInfo.removedUsers = new int[] {removeUser}; 10968 } 10969 mInstaller.clearUserData(packageName, removeUser); 10970 removeKeystoreDataIfNeeded(removeUser, appId); 10971 schedulePackageCleaning(packageName, removeUser, false); 10972 return true; 10973 } 10974 10975 if (dataOnly) { 10976 // Delete application data first 10977 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10978 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10979 return true; 10980 } 10981 10982 boolean ret = false; 10983 if (isSystemApp(ps)) { 10984 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10985 // When an updated system application is deleted we delete the existing resources as well and 10986 // fall back to existing code in system partition 10987 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10988 flags, outInfo, writeSettings); 10989 } else { 10990 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10991 // Kill application pre-emptively especially for apps on sd. 10992 killApplication(packageName, ps.appId, "uninstall pkg"); 10993 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10994 allUserHandles, perUserInstalled, 10995 outInfo, writeSettings); 10996 } 10997 10998 return ret; 10999 } 11000 11001 private final class ClearStorageConnection implements ServiceConnection { 11002 IMediaContainerService mContainerService; 11003 11004 @Override 11005 public void onServiceConnected(ComponentName name, IBinder service) { 11006 synchronized (this) { 11007 mContainerService = IMediaContainerService.Stub.asInterface(service); 11008 notifyAll(); 11009 } 11010 } 11011 11012 @Override 11013 public void onServiceDisconnected(ComponentName name) { 11014 } 11015 } 11016 11017 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11018 final boolean mounted; 11019 if (Environment.isExternalStorageEmulated()) { 11020 mounted = true; 11021 } else { 11022 final String status = Environment.getExternalStorageState(); 11023 11024 mounted = status.equals(Environment.MEDIA_MOUNTED) 11025 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11026 } 11027 11028 if (!mounted) { 11029 return; 11030 } 11031 11032 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11033 int[] users; 11034 if (userId == UserHandle.USER_ALL) { 11035 users = sUserManager.getUserIds(); 11036 } else { 11037 users = new int[] { userId }; 11038 } 11039 final ClearStorageConnection conn = new ClearStorageConnection(); 11040 if (mContext.bindServiceAsUser( 11041 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11042 try { 11043 for (int curUser : users) { 11044 long timeout = SystemClock.uptimeMillis() + 5000; 11045 synchronized (conn) { 11046 long now = SystemClock.uptimeMillis(); 11047 while (conn.mContainerService == null && now < timeout) { 11048 try { 11049 conn.wait(timeout - now); 11050 } catch (InterruptedException e) { 11051 } 11052 } 11053 } 11054 if (conn.mContainerService == null) { 11055 return; 11056 } 11057 11058 final UserEnvironment userEnv = new UserEnvironment(curUser); 11059 clearDirectory(conn.mContainerService, 11060 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11061 if (allData) { 11062 clearDirectory(conn.mContainerService, 11063 userEnv.buildExternalStorageAppDataDirs(packageName)); 11064 clearDirectory(conn.mContainerService, 11065 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11066 } 11067 } 11068 } finally { 11069 mContext.unbindService(conn); 11070 } 11071 } 11072 } 11073 11074 @Override 11075 public void clearApplicationUserData(final String packageName, 11076 final IPackageDataObserver observer, final int userId) { 11077 mContext.enforceCallingOrSelfPermission( 11078 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11079 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11080 // Queue up an async operation since the package deletion may take a little while. 11081 mHandler.post(new Runnable() { 11082 public void run() { 11083 mHandler.removeCallbacks(this); 11084 final boolean succeeded; 11085 synchronized (mInstallLock) { 11086 succeeded = clearApplicationUserDataLI(packageName, userId); 11087 } 11088 clearExternalStorageDataSync(packageName, userId, true); 11089 if (succeeded) { 11090 // invoke DeviceStorageMonitor's update method to clear any notifications 11091 DeviceStorageMonitorInternal 11092 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11093 if (dsm != null) { 11094 dsm.checkMemory(); 11095 } 11096 } 11097 if(observer != null) { 11098 try { 11099 observer.onRemoveCompleted(packageName, succeeded); 11100 } catch (RemoteException e) { 11101 Log.i(TAG, "Observer no longer exists."); 11102 } 11103 } //end if observer 11104 } //end run 11105 }); 11106 } 11107 11108 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11109 if (packageName == null) { 11110 Slog.w(TAG, "Attempt to delete null packageName."); 11111 return false; 11112 } 11113 PackageParser.Package p; 11114 boolean dataOnly = false; 11115 final int appId; 11116 synchronized (mPackages) { 11117 p = mPackages.get(packageName); 11118 if (p == null) { 11119 dataOnly = true; 11120 PackageSetting ps = mSettings.mPackages.get(packageName); 11121 if ((ps == null) || (ps.pkg == null)) { 11122 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11123 return false; 11124 } 11125 p = ps.pkg; 11126 } 11127 if (!dataOnly) { 11128 // need to check this only for fully installed applications 11129 if (p == null) { 11130 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11131 return false; 11132 } 11133 final ApplicationInfo applicationInfo = p.applicationInfo; 11134 if (applicationInfo == null) { 11135 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11136 return false; 11137 } 11138 } 11139 if (p != null && p.applicationInfo != null) { 11140 appId = p.applicationInfo.uid; 11141 } else { 11142 appId = -1; 11143 } 11144 } 11145 int retCode = mInstaller.clearUserData(packageName, userId); 11146 if (retCode < 0) { 11147 Slog.w(TAG, "Couldn't remove cache files for package: " 11148 + packageName); 11149 return false; 11150 } 11151 removeKeystoreDataIfNeeded(userId, appId); 11152 return true; 11153 } 11154 11155 /** 11156 * Remove entries from the keystore daemon. Will only remove it if the 11157 * {@code appId} is valid. 11158 */ 11159 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11160 if (appId < 0) { 11161 return; 11162 } 11163 11164 final KeyStore keyStore = KeyStore.getInstance(); 11165 if (keyStore != null) { 11166 if (userId == UserHandle.USER_ALL) { 11167 for (final int individual : sUserManager.getUserIds()) { 11168 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11169 } 11170 } else { 11171 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11172 } 11173 } else { 11174 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11175 } 11176 } 11177 11178 @Override 11179 public void deleteApplicationCacheFiles(final String packageName, 11180 final IPackageDataObserver observer) { 11181 mContext.enforceCallingOrSelfPermission( 11182 android.Manifest.permission.DELETE_CACHE_FILES, null); 11183 // Queue up an async operation since the package deletion may take a little while. 11184 final int userId = UserHandle.getCallingUserId(); 11185 mHandler.post(new Runnable() { 11186 public void run() { 11187 mHandler.removeCallbacks(this); 11188 final boolean succeded; 11189 synchronized (mInstallLock) { 11190 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11191 } 11192 clearExternalStorageDataSync(packageName, userId, false); 11193 if(observer != null) { 11194 try { 11195 observer.onRemoveCompleted(packageName, succeded); 11196 } catch (RemoteException e) { 11197 Log.i(TAG, "Observer no longer exists."); 11198 } 11199 } //end if observer 11200 } //end run 11201 }); 11202 } 11203 11204 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11205 if (packageName == null) { 11206 Slog.w(TAG, "Attempt to delete null packageName."); 11207 return false; 11208 } 11209 PackageParser.Package p; 11210 synchronized (mPackages) { 11211 p = mPackages.get(packageName); 11212 } 11213 if (p == null) { 11214 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11215 return false; 11216 } 11217 final ApplicationInfo applicationInfo = p.applicationInfo; 11218 if (applicationInfo == null) { 11219 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11220 return false; 11221 } 11222 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11223 if (retCode < 0) { 11224 Slog.w(TAG, "Couldn't remove cache files for package: " 11225 + packageName + " u" + userId); 11226 return false; 11227 } 11228 return true; 11229 } 11230 11231 @Override 11232 public void getPackageSizeInfo(final String packageName, int userHandle, 11233 final IPackageStatsObserver observer) { 11234 mContext.enforceCallingOrSelfPermission( 11235 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11236 if (packageName == null) { 11237 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11238 } 11239 11240 PackageStats stats = new PackageStats(packageName, userHandle); 11241 11242 /* 11243 * Queue up an async operation since the package measurement may take a 11244 * little while. 11245 */ 11246 Message msg = mHandler.obtainMessage(INIT_COPY); 11247 msg.obj = new MeasureParams(stats, observer); 11248 mHandler.sendMessage(msg); 11249 } 11250 11251 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11252 PackageStats pStats) { 11253 if (packageName == null) { 11254 Slog.w(TAG, "Attempt to get size of null packageName."); 11255 return false; 11256 } 11257 PackageParser.Package p; 11258 boolean dataOnly = false; 11259 String libDirPath = null; 11260 String asecPath = null; 11261 PackageSetting ps = null; 11262 synchronized (mPackages) { 11263 p = mPackages.get(packageName); 11264 ps = mSettings.mPackages.get(packageName); 11265 if(p == null) { 11266 dataOnly = true; 11267 if((ps == null) || (ps.pkg == null)) { 11268 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11269 return false; 11270 } 11271 p = ps.pkg; 11272 } 11273 if (ps != null) { 11274 libDirPath = ps.nativeLibraryPathString; 11275 } 11276 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11277 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 11278 if (secureContainerId != null) { 11279 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11280 } 11281 } 11282 } 11283 String publicSrcDir = null; 11284 if(!dataOnly) { 11285 final ApplicationInfo applicationInfo = p.applicationInfo; 11286 if (applicationInfo == null) { 11287 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11288 return false; 11289 } 11290 if (isForwardLocked(p)) { 11291 publicSrcDir = applicationInfo.publicSourceDir; 11292 } 11293 } 11294 // TODO: extend to measure size of split APKs 11295 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirPath, 11296 publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps), 11297 pStats); 11298 if (res < 0) { 11299 return false; 11300 } 11301 11302 // Fix-up for forward-locked applications in ASEC containers. 11303 if (!isExternal(p)) { 11304 pStats.codeSize += pStats.externalCodeSize; 11305 pStats.externalCodeSize = 0L; 11306 } 11307 11308 return true; 11309 } 11310 11311 11312 @Override 11313 public void addPackageToPreferred(String packageName) { 11314 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11315 } 11316 11317 @Override 11318 public void removePackageFromPreferred(String packageName) { 11319 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11320 } 11321 11322 @Override 11323 public List<PackageInfo> getPreferredPackages(int flags) { 11324 return new ArrayList<PackageInfo>(); 11325 } 11326 11327 private int getUidTargetSdkVersionLockedLPr(int uid) { 11328 Object obj = mSettings.getUserIdLPr(uid); 11329 if (obj instanceof SharedUserSetting) { 11330 final SharedUserSetting sus = (SharedUserSetting) obj; 11331 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11332 final Iterator<PackageSetting> it = sus.packages.iterator(); 11333 while (it.hasNext()) { 11334 final PackageSetting ps = it.next(); 11335 if (ps.pkg != null) { 11336 int v = ps.pkg.applicationInfo.targetSdkVersion; 11337 if (v < vers) vers = v; 11338 } 11339 } 11340 return vers; 11341 } else if (obj instanceof PackageSetting) { 11342 final PackageSetting ps = (PackageSetting) obj; 11343 if (ps.pkg != null) { 11344 return ps.pkg.applicationInfo.targetSdkVersion; 11345 } 11346 } 11347 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11348 } 11349 11350 @Override 11351 public void addPreferredActivity(IntentFilter filter, int match, 11352 ComponentName[] set, ComponentName activity, int userId) { 11353 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11354 } 11355 11356 private void addPreferredActivityInternal(IntentFilter filter, int match, 11357 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11358 // writer 11359 int callingUid = Binder.getCallingUid(); 11360 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11361 if (filter.countActions() == 0) { 11362 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11363 return; 11364 } 11365 synchronized (mPackages) { 11366 if (mContext.checkCallingOrSelfPermission( 11367 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11368 != PackageManager.PERMISSION_GRANTED) { 11369 if (getUidTargetSdkVersionLockedLPr(callingUid) 11370 < Build.VERSION_CODES.FROYO) { 11371 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11372 + callingUid); 11373 return; 11374 } 11375 mContext.enforceCallingOrSelfPermission( 11376 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11377 } 11378 11379 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11380 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11381 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11382 new PreferredActivity(filter, match, set, activity, always)); 11383 mSettings.writePackageRestrictionsLPr(userId); 11384 } 11385 } 11386 11387 @Override 11388 public void replacePreferredActivity(IntentFilter filter, int match, 11389 ComponentName[] set, ComponentName activity) { 11390 if (filter.countActions() != 1) { 11391 throw new IllegalArgumentException( 11392 "replacePreferredActivity expects filter to have only 1 action."); 11393 } 11394 if (filter.countDataAuthorities() != 0 11395 || filter.countDataPaths() != 0 11396 || filter.countDataSchemes() > 1 11397 || filter.countDataTypes() != 0) { 11398 throw new IllegalArgumentException( 11399 "replacePreferredActivity expects filter to have no data authorities, " + 11400 "paths, or types; and at most one scheme."); 11401 } 11402 synchronized (mPackages) { 11403 if (mContext.checkCallingOrSelfPermission( 11404 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11405 != PackageManager.PERMISSION_GRANTED) { 11406 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11407 < Build.VERSION_CODES.FROYO) { 11408 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11409 + Binder.getCallingUid()); 11410 return; 11411 } 11412 mContext.enforceCallingOrSelfPermission( 11413 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11414 } 11415 11416 final int callingUserId = UserHandle.getCallingUserId(); 11417 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11418 if (pir != null) { 11419 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11420 if (filter.countDataSchemes() == 1) { 11421 Uri.Builder builder = new Uri.Builder(); 11422 builder.scheme(filter.getDataScheme(0)); 11423 intent.setData(builder.build()); 11424 } 11425 List<PreferredActivity> matches = pir.queryIntent( 11426 intent, null, true, callingUserId); 11427 if (DEBUG_PREFERRED) { 11428 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11429 } 11430 for (int i = 0; i < matches.size(); i++) { 11431 PreferredActivity pa = matches.get(i); 11432 if (DEBUG_PREFERRED) { 11433 Slog.i(TAG, "Removing preferred activity " 11434 + pa.mPref.mComponent + ":"); 11435 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11436 } 11437 pir.removeFilter(pa); 11438 } 11439 } 11440 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11441 } 11442 } 11443 11444 @Override 11445 public void clearPackagePreferredActivities(String packageName) { 11446 final int uid = Binder.getCallingUid(); 11447 // writer 11448 synchronized (mPackages) { 11449 PackageParser.Package pkg = mPackages.get(packageName); 11450 if (pkg == null || pkg.applicationInfo.uid != uid) { 11451 if (mContext.checkCallingOrSelfPermission( 11452 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11453 != PackageManager.PERMISSION_GRANTED) { 11454 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11455 < Build.VERSION_CODES.FROYO) { 11456 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11457 + Binder.getCallingUid()); 11458 return; 11459 } 11460 mContext.enforceCallingOrSelfPermission( 11461 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11462 } 11463 } 11464 11465 int user = UserHandle.getCallingUserId(); 11466 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11467 mSettings.writePackageRestrictionsLPr(user); 11468 scheduleWriteSettingsLocked(); 11469 } 11470 } 11471 } 11472 11473 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11474 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11475 ArrayList<PreferredActivity> removed = null; 11476 boolean changed = false; 11477 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11478 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11479 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11480 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11481 continue; 11482 } 11483 Iterator<PreferredActivity> it = pir.filterIterator(); 11484 while (it.hasNext()) { 11485 PreferredActivity pa = it.next(); 11486 // Mark entry for removal only if it matches the package name 11487 // and the entry is of type "always". 11488 if (packageName == null || 11489 (pa.mPref.mComponent.getPackageName().equals(packageName) 11490 && pa.mPref.mAlways)) { 11491 if (removed == null) { 11492 removed = new ArrayList<PreferredActivity>(); 11493 } 11494 removed.add(pa); 11495 } 11496 } 11497 if (removed != null) { 11498 for (int j=0; j<removed.size(); j++) { 11499 PreferredActivity pa = removed.get(j); 11500 pir.removeFilter(pa); 11501 } 11502 changed = true; 11503 } 11504 } 11505 return changed; 11506 } 11507 11508 @Override 11509 public void resetPreferredActivities(int userId) { 11510 mContext.enforceCallingOrSelfPermission( 11511 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11512 // writer 11513 synchronized (mPackages) { 11514 int user = UserHandle.getCallingUserId(); 11515 clearPackagePreferredActivitiesLPw(null, user); 11516 mSettings.readDefaultPreferredAppsLPw(this, user); 11517 mSettings.writePackageRestrictionsLPr(user); 11518 scheduleWriteSettingsLocked(); 11519 } 11520 } 11521 11522 @Override 11523 public int getPreferredActivities(List<IntentFilter> outFilters, 11524 List<ComponentName> outActivities, String packageName) { 11525 11526 int num = 0; 11527 final int userId = UserHandle.getCallingUserId(); 11528 // reader 11529 synchronized (mPackages) { 11530 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11531 if (pir != null) { 11532 final Iterator<PreferredActivity> it = pir.filterIterator(); 11533 while (it.hasNext()) { 11534 final PreferredActivity pa = it.next(); 11535 if (packageName == null 11536 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11537 && pa.mPref.mAlways)) { 11538 if (outFilters != null) { 11539 outFilters.add(new IntentFilter(pa)); 11540 } 11541 if (outActivities != null) { 11542 outActivities.add(pa.mPref.mComponent); 11543 } 11544 } 11545 } 11546 } 11547 } 11548 11549 return num; 11550 } 11551 11552 @Override 11553 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11554 int userId) { 11555 int callingUid = Binder.getCallingUid(); 11556 if (callingUid != Process.SYSTEM_UID) { 11557 throw new SecurityException( 11558 "addPersistentPreferredActivity can only be run by the system"); 11559 } 11560 if (filter.countActions() == 0) { 11561 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11562 return; 11563 } 11564 synchronized (mPackages) { 11565 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11566 " :"); 11567 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11568 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11569 new PersistentPreferredActivity(filter, activity)); 11570 mSettings.writePackageRestrictionsLPr(userId); 11571 } 11572 } 11573 11574 @Override 11575 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11576 int callingUid = Binder.getCallingUid(); 11577 if (callingUid != Process.SYSTEM_UID) { 11578 throw new SecurityException( 11579 "clearPackagePersistentPreferredActivities can only be run by the system"); 11580 } 11581 ArrayList<PersistentPreferredActivity> removed = null; 11582 boolean changed = false; 11583 synchronized (mPackages) { 11584 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11585 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11586 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11587 .valueAt(i); 11588 if (userId != thisUserId) { 11589 continue; 11590 } 11591 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11592 while (it.hasNext()) { 11593 PersistentPreferredActivity ppa = it.next(); 11594 // Mark entry for removal only if it matches the package name. 11595 if (ppa.mComponent.getPackageName().equals(packageName)) { 11596 if (removed == null) { 11597 removed = new ArrayList<PersistentPreferredActivity>(); 11598 } 11599 removed.add(ppa); 11600 } 11601 } 11602 if (removed != null) { 11603 for (int j=0; j<removed.size(); j++) { 11604 PersistentPreferredActivity ppa = removed.get(j); 11605 ppir.removeFilter(ppa); 11606 } 11607 changed = true; 11608 } 11609 } 11610 11611 if (changed) { 11612 mSettings.writePackageRestrictionsLPr(userId); 11613 } 11614 } 11615 } 11616 11617 @Override 11618 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11619 int targetUserId, int flags) { 11620 mContext.enforceCallingOrSelfPermission( 11621 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11622 if (intentFilter.countActions() == 0) { 11623 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11624 return; 11625 } 11626 synchronized (mPackages) { 11627 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11628 targetUserId, flags); 11629 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11630 mSettings.writePackageRestrictionsLPr(sourceUserId); 11631 } 11632 } 11633 11634 public void addCrossProfileIntentsForPackage(String packageName, 11635 int sourceUserId, int targetUserId) { 11636 mContext.enforceCallingOrSelfPermission( 11637 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11638 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11639 mSettings.writePackageRestrictionsLPr(sourceUserId); 11640 } 11641 11642 public void removeCrossProfileIntentsForPackage(String packageName, 11643 int sourceUserId, int targetUserId) { 11644 mContext.enforceCallingOrSelfPermission( 11645 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11646 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11647 mSettings.writePackageRestrictionsLPr(sourceUserId); 11648 } 11649 11650 @Override 11651 public void clearCrossProfileIntentFilters(int sourceUserId) { 11652 mContext.enforceCallingOrSelfPermission( 11653 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11654 synchronized (mPackages) { 11655 CrossProfileIntentResolver resolver = 11656 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11657 HashSet<CrossProfileIntentFilter> set = 11658 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11659 for (CrossProfileIntentFilter filter : set) { 11660 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11661 resolver.removeFilter(filter); 11662 } 11663 } 11664 mSettings.writePackageRestrictionsLPr(sourceUserId); 11665 } 11666 } 11667 11668 @Override 11669 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11670 Intent intent = new Intent(Intent.ACTION_MAIN); 11671 intent.addCategory(Intent.CATEGORY_HOME); 11672 11673 final int callingUserId = UserHandle.getCallingUserId(); 11674 List<ResolveInfo> list = queryIntentActivities(intent, null, 11675 PackageManager.GET_META_DATA, callingUserId); 11676 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11677 true, false, false, callingUserId); 11678 11679 allHomeCandidates.clear(); 11680 if (list != null) { 11681 for (ResolveInfo ri : list) { 11682 allHomeCandidates.add(ri); 11683 } 11684 } 11685 return (preferred == null || preferred.activityInfo == null) 11686 ? null 11687 : new ComponentName(preferred.activityInfo.packageName, 11688 preferred.activityInfo.name); 11689 } 11690 11691 @Override 11692 public void setApplicationEnabledSetting(String appPackageName, 11693 int newState, int flags, int userId, String callingPackage) { 11694 if (!sUserManager.exists(userId)) return; 11695 if (callingPackage == null) { 11696 callingPackage = Integer.toString(Binder.getCallingUid()); 11697 } 11698 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11699 } 11700 11701 @Override 11702 public void setComponentEnabledSetting(ComponentName componentName, 11703 int newState, int flags, int userId) { 11704 if (!sUserManager.exists(userId)) return; 11705 setEnabledSetting(componentName.getPackageName(), 11706 componentName.getClassName(), newState, flags, userId, null); 11707 } 11708 11709 private void setEnabledSetting(final String packageName, String className, int newState, 11710 final int flags, int userId, String callingPackage) { 11711 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11712 || newState == COMPONENT_ENABLED_STATE_ENABLED 11713 || newState == COMPONENT_ENABLED_STATE_DISABLED 11714 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11715 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11716 throw new IllegalArgumentException("Invalid new component state: " 11717 + newState); 11718 } 11719 PackageSetting pkgSetting; 11720 final int uid = Binder.getCallingUid(); 11721 final int permission = mContext.checkCallingOrSelfPermission( 11722 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11723 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11724 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11725 boolean sendNow = false; 11726 boolean isApp = (className == null); 11727 String componentName = isApp ? packageName : className; 11728 int packageUid = -1; 11729 ArrayList<String> components; 11730 11731 // writer 11732 synchronized (mPackages) { 11733 pkgSetting = mSettings.mPackages.get(packageName); 11734 if (pkgSetting == null) { 11735 if (className == null) { 11736 throw new IllegalArgumentException( 11737 "Unknown package: " + packageName); 11738 } 11739 throw new IllegalArgumentException( 11740 "Unknown component: " + packageName 11741 + "/" + className); 11742 } 11743 // Allow root and verify that userId is not being specified by a different user 11744 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11745 throw new SecurityException( 11746 "Permission Denial: attempt to change component state from pid=" 11747 + Binder.getCallingPid() 11748 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11749 } 11750 if (className == null) { 11751 // We're dealing with an application/package level state change 11752 if (pkgSetting.getEnabled(userId) == newState) { 11753 // Nothing to do 11754 return; 11755 } 11756 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11757 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11758 // Don't care about who enables an app. 11759 callingPackage = null; 11760 } 11761 pkgSetting.setEnabled(newState, userId, callingPackage); 11762 // pkgSetting.pkg.mSetEnabled = newState; 11763 } else { 11764 // We're dealing with a component level state change 11765 // First, verify that this is a valid class name. 11766 PackageParser.Package pkg = pkgSetting.pkg; 11767 if (pkg == null || !pkg.hasComponentClassName(className)) { 11768 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11769 throw new IllegalArgumentException("Component class " + className 11770 + " does not exist in " + packageName); 11771 } else { 11772 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11773 + className + " does not exist in " + packageName); 11774 } 11775 } 11776 switch (newState) { 11777 case COMPONENT_ENABLED_STATE_ENABLED: 11778 if (!pkgSetting.enableComponentLPw(className, userId)) { 11779 return; 11780 } 11781 break; 11782 case COMPONENT_ENABLED_STATE_DISABLED: 11783 if (!pkgSetting.disableComponentLPw(className, userId)) { 11784 return; 11785 } 11786 break; 11787 case COMPONENT_ENABLED_STATE_DEFAULT: 11788 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11789 return; 11790 } 11791 break; 11792 default: 11793 Slog.e(TAG, "Invalid new component state: " + newState); 11794 return; 11795 } 11796 } 11797 mSettings.writePackageRestrictionsLPr(userId); 11798 components = mPendingBroadcasts.get(userId, packageName); 11799 final boolean newPackage = components == null; 11800 if (newPackage) { 11801 components = new ArrayList<String>(); 11802 } 11803 if (!components.contains(componentName)) { 11804 components.add(componentName); 11805 } 11806 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11807 sendNow = true; 11808 // Purge entry from pending broadcast list if another one exists already 11809 // since we are sending one right away. 11810 mPendingBroadcasts.remove(userId, packageName); 11811 } else { 11812 if (newPackage) { 11813 mPendingBroadcasts.put(userId, packageName, components); 11814 } 11815 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11816 // Schedule a message 11817 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11818 } 11819 } 11820 } 11821 11822 long callingId = Binder.clearCallingIdentity(); 11823 try { 11824 if (sendNow) { 11825 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11826 sendPackageChangedBroadcast(packageName, 11827 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11828 } 11829 } finally { 11830 Binder.restoreCallingIdentity(callingId); 11831 } 11832 } 11833 11834 private void sendPackageChangedBroadcast(String packageName, 11835 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11836 if (DEBUG_INSTALL) 11837 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11838 + componentNames); 11839 Bundle extras = new Bundle(4); 11840 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11841 String nameList[] = new String[componentNames.size()]; 11842 componentNames.toArray(nameList); 11843 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11844 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11845 extras.putInt(Intent.EXTRA_UID, packageUid); 11846 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11847 new int[] {UserHandle.getUserId(packageUid)}); 11848 } 11849 11850 @Override 11851 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11852 if (!sUserManager.exists(userId)) return; 11853 final int uid = Binder.getCallingUid(); 11854 final int permission = mContext.checkCallingOrSelfPermission( 11855 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11856 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11857 enforceCrossUserPermission(uid, userId, true, "stop package"); 11858 // writer 11859 synchronized (mPackages) { 11860 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11861 uid, userId)) { 11862 scheduleWritePackageRestrictionsLocked(userId); 11863 } 11864 } 11865 } 11866 11867 @Override 11868 public String getInstallerPackageName(String packageName) { 11869 // reader 11870 synchronized (mPackages) { 11871 return mSettings.getInstallerPackageNameLPr(packageName); 11872 } 11873 } 11874 11875 @Override 11876 public int getApplicationEnabledSetting(String packageName, int userId) { 11877 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11878 int uid = Binder.getCallingUid(); 11879 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11880 // reader 11881 synchronized (mPackages) { 11882 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11883 } 11884 } 11885 11886 @Override 11887 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11888 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11889 int uid = Binder.getCallingUid(); 11890 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11891 // reader 11892 synchronized (mPackages) { 11893 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11894 } 11895 } 11896 11897 @Override 11898 public void enterSafeMode() { 11899 enforceSystemOrRoot("Only the system can request entering safe mode"); 11900 11901 if (!mSystemReady) { 11902 mSafeMode = true; 11903 } 11904 } 11905 11906 @Override 11907 public void systemReady() { 11908 mSystemReady = true; 11909 11910 // Read the compatibilty setting when the system is ready. 11911 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11912 mContext.getContentResolver(), 11913 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11914 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11915 if (DEBUG_SETTINGS) { 11916 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11917 } 11918 11919 synchronized (mPackages) { 11920 // Verify that all of the preferred activity components actually 11921 // exist. It is possible for applications to be updated and at 11922 // that point remove a previously declared activity component that 11923 // had been set as a preferred activity. We try to clean this up 11924 // the next time we encounter that preferred activity, but it is 11925 // possible for the user flow to never be able to return to that 11926 // situation so here we do a sanity check to make sure we haven't 11927 // left any junk around. 11928 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11929 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11930 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11931 removed.clear(); 11932 for (PreferredActivity pa : pir.filterSet()) { 11933 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11934 removed.add(pa); 11935 } 11936 } 11937 if (removed.size() > 0) { 11938 for (int r=0; r<removed.size(); r++) { 11939 PreferredActivity pa = removed.get(r); 11940 Slog.w(TAG, "Removing dangling preferred activity: " 11941 + pa.mPref.mComponent); 11942 pir.removeFilter(pa); 11943 } 11944 mSettings.writePackageRestrictionsLPr( 11945 mSettings.mPreferredActivities.keyAt(i)); 11946 } 11947 } 11948 } 11949 sUserManager.systemReady(); 11950 } 11951 11952 @Override 11953 public boolean isSafeMode() { 11954 return mSafeMode; 11955 } 11956 11957 @Override 11958 public boolean hasSystemUidErrors() { 11959 return mHasSystemUidErrors; 11960 } 11961 11962 static String arrayToString(int[] array) { 11963 StringBuffer buf = new StringBuffer(128); 11964 buf.append('['); 11965 if (array != null) { 11966 for (int i=0; i<array.length; i++) { 11967 if (i > 0) buf.append(", "); 11968 buf.append(array[i]); 11969 } 11970 } 11971 buf.append(']'); 11972 return buf.toString(); 11973 } 11974 11975 static class DumpState { 11976 public static final int DUMP_LIBS = 1 << 0; 11977 11978 public static final int DUMP_FEATURES = 1 << 1; 11979 11980 public static final int DUMP_RESOLVERS = 1 << 2; 11981 11982 public static final int DUMP_PERMISSIONS = 1 << 3; 11983 11984 public static final int DUMP_PACKAGES = 1 << 4; 11985 11986 public static final int DUMP_SHARED_USERS = 1 << 5; 11987 11988 public static final int DUMP_MESSAGES = 1 << 6; 11989 11990 public static final int DUMP_PROVIDERS = 1 << 7; 11991 11992 public static final int DUMP_VERIFIERS = 1 << 8; 11993 11994 public static final int DUMP_PREFERRED = 1 << 9; 11995 11996 public static final int DUMP_PREFERRED_XML = 1 << 10; 11997 11998 public static final int DUMP_KEYSETS = 1 << 11; 11999 12000 public static final int DUMP_VERSION = 1 << 12; 12001 12002 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12003 12004 private int mTypes; 12005 12006 private int mOptions; 12007 12008 private boolean mTitlePrinted; 12009 12010 private SharedUserSetting mSharedUser; 12011 12012 public boolean isDumping(int type) { 12013 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12014 return true; 12015 } 12016 12017 return (mTypes & type) != 0; 12018 } 12019 12020 public void setDump(int type) { 12021 mTypes |= type; 12022 } 12023 12024 public boolean isOptionEnabled(int option) { 12025 return (mOptions & option) != 0; 12026 } 12027 12028 public void setOptionEnabled(int option) { 12029 mOptions |= option; 12030 } 12031 12032 public boolean onTitlePrinted() { 12033 final boolean printed = mTitlePrinted; 12034 mTitlePrinted = true; 12035 return printed; 12036 } 12037 12038 public boolean getTitlePrinted() { 12039 return mTitlePrinted; 12040 } 12041 12042 public void setTitlePrinted(boolean enabled) { 12043 mTitlePrinted = enabled; 12044 } 12045 12046 public SharedUserSetting getSharedUser() { 12047 return mSharedUser; 12048 } 12049 12050 public void setSharedUser(SharedUserSetting user) { 12051 mSharedUser = user; 12052 } 12053 } 12054 12055 @Override 12056 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12057 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12058 != PackageManager.PERMISSION_GRANTED) { 12059 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12060 + Binder.getCallingPid() 12061 + ", uid=" + Binder.getCallingUid() 12062 + " without permission " 12063 + android.Manifest.permission.DUMP); 12064 return; 12065 } 12066 12067 DumpState dumpState = new DumpState(); 12068 boolean fullPreferred = false; 12069 boolean checkin = false; 12070 12071 String packageName = null; 12072 12073 int opti = 0; 12074 while (opti < args.length) { 12075 String opt = args[opti]; 12076 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12077 break; 12078 } 12079 opti++; 12080 if ("-a".equals(opt)) { 12081 // Right now we only know how to print all. 12082 } else if ("-h".equals(opt)) { 12083 pw.println("Package manager dump options:"); 12084 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12085 pw.println(" --checkin: dump for a checkin"); 12086 pw.println(" -f: print details of intent filters"); 12087 pw.println(" -h: print this help"); 12088 pw.println(" cmd may be one of:"); 12089 pw.println(" l[ibraries]: list known shared libraries"); 12090 pw.println(" f[ibraries]: list device features"); 12091 pw.println(" k[eysets]: print known keysets"); 12092 pw.println(" r[esolvers]: dump intent resolvers"); 12093 pw.println(" perm[issions]: dump permissions"); 12094 pw.println(" pref[erred]: print preferred package settings"); 12095 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12096 pw.println(" prov[iders]: dump content providers"); 12097 pw.println(" p[ackages]: dump installed packages"); 12098 pw.println(" s[hared-users]: dump shared user IDs"); 12099 pw.println(" m[essages]: print collected runtime messages"); 12100 pw.println(" v[erifiers]: print package verifier info"); 12101 pw.println(" version: print database version info"); 12102 pw.println(" write: write current settings now"); 12103 pw.println(" <package.name>: info about given package"); 12104 return; 12105 } else if ("--checkin".equals(opt)) { 12106 checkin = true; 12107 } else if ("-f".equals(opt)) { 12108 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12109 } else { 12110 pw.println("Unknown argument: " + opt + "; use -h for help"); 12111 } 12112 } 12113 12114 // Is the caller requesting to dump a particular piece of data? 12115 if (opti < args.length) { 12116 String cmd = args[opti]; 12117 opti++; 12118 // Is this a package name? 12119 if ("android".equals(cmd) || cmd.contains(".")) { 12120 packageName = cmd; 12121 // When dumping a single package, we always dump all of its 12122 // filter information since the amount of data will be reasonable. 12123 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12124 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12125 dumpState.setDump(DumpState.DUMP_LIBS); 12126 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12127 dumpState.setDump(DumpState.DUMP_FEATURES); 12128 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12129 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12130 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12131 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12132 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12133 dumpState.setDump(DumpState.DUMP_PREFERRED); 12134 } else if ("preferred-xml".equals(cmd)) { 12135 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12136 if (opti < args.length && "--full".equals(args[opti])) { 12137 fullPreferred = true; 12138 opti++; 12139 } 12140 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12141 dumpState.setDump(DumpState.DUMP_PACKAGES); 12142 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12143 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12144 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12145 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12146 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12147 dumpState.setDump(DumpState.DUMP_MESSAGES); 12148 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12149 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12150 } else if ("version".equals(cmd)) { 12151 dumpState.setDump(DumpState.DUMP_VERSION); 12152 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12153 dumpState.setDump(DumpState.DUMP_KEYSETS); 12154 } else if ("write".equals(cmd)) { 12155 synchronized (mPackages) { 12156 mSettings.writeLPr(); 12157 pw.println("Settings written."); 12158 return; 12159 } 12160 } 12161 } 12162 12163 if (checkin) { 12164 pw.println("vers,1"); 12165 } 12166 12167 // reader 12168 synchronized (mPackages) { 12169 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12170 if (!checkin) { 12171 if (dumpState.onTitlePrinted()) 12172 pw.println(); 12173 pw.println("Database versions:"); 12174 pw.print(" SDK Version:"); 12175 pw.print(" internal="); 12176 pw.print(mSettings.mInternalSdkPlatform); 12177 pw.print(" external="); 12178 pw.println(mSettings.mExternalSdkPlatform); 12179 pw.print(" DB Version:"); 12180 pw.print(" internal="); 12181 pw.print(mSettings.mInternalDatabaseVersion); 12182 pw.print(" external="); 12183 pw.println(mSettings.mExternalDatabaseVersion); 12184 } 12185 } 12186 12187 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12188 if (!checkin) { 12189 if (dumpState.onTitlePrinted()) 12190 pw.println(); 12191 pw.println("Verifiers:"); 12192 pw.print(" Required: "); 12193 pw.print(mRequiredVerifierPackage); 12194 pw.print(" (uid="); 12195 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12196 pw.println(")"); 12197 } else if (mRequiredVerifierPackage != null) { 12198 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12199 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12200 } 12201 } 12202 12203 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12204 boolean printedHeader = false; 12205 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12206 while (it.hasNext()) { 12207 String name = it.next(); 12208 SharedLibraryEntry ent = mSharedLibraries.get(name); 12209 if (!checkin) { 12210 if (!printedHeader) { 12211 if (dumpState.onTitlePrinted()) 12212 pw.println(); 12213 pw.println("Libraries:"); 12214 printedHeader = true; 12215 } 12216 pw.print(" "); 12217 } else { 12218 pw.print("lib,"); 12219 } 12220 pw.print(name); 12221 if (!checkin) { 12222 pw.print(" -> "); 12223 } 12224 if (ent.path != null) { 12225 if (!checkin) { 12226 pw.print("(jar) "); 12227 pw.print(ent.path); 12228 } else { 12229 pw.print(",jar,"); 12230 pw.print(ent.path); 12231 } 12232 } else { 12233 if (!checkin) { 12234 pw.print("(apk) "); 12235 pw.print(ent.apk); 12236 } else { 12237 pw.print(",apk,"); 12238 pw.print(ent.apk); 12239 } 12240 } 12241 pw.println(); 12242 } 12243 } 12244 12245 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12246 if (dumpState.onTitlePrinted()) 12247 pw.println(); 12248 if (!checkin) { 12249 pw.println("Features:"); 12250 } 12251 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12252 while (it.hasNext()) { 12253 String name = it.next(); 12254 if (!checkin) { 12255 pw.print(" "); 12256 } else { 12257 pw.print("feat,"); 12258 } 12259 pw.println(name); 12260 } 12261 } 12262 12263 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12264 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12265 : "Activity Resolver Table:", " ", packageName, 12266 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12267 dumpState.setTitlePrinted(true); 12268 } 12269 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12270 : "Receiver Resolver Table:", " ", packageName, 12271 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12272 dumpState.setTitlePrinted(true); 12273 } 12274 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12275 : "Service Resolver Table:", " ", packageName, 12276 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12277 dumpState.setTitlePrinted(true); 12278 } 12279 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12280 : "Provider Resolver Table:", " ", packageName, 12281 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12282 dumpState.setTitlePrinted(true); 12283 } 12284 } 12285 12286 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12287 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12288 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12289 int user = mSettings.mPreferredActivities.keyAt(i); 12290 if (pir.dump(pw, 12291 dumpState.getTitlePrinted() 12292 ? "\nPreferred Activities User " + user + ":" 12293 : "Preferred Activities User " + user + ":", " ", 12294 packageName, true)) { 12295 dumpState.setTitlePrinted(true); 12296 } 12297 } 12298 } 12299 12300 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12301 pw.flush(); 12302 FileOutputStream fout = new FileOutputStream(fd); 12303 BufferedOutputStream str = new BufferedOutputStream(fout); 12304 XmlSerializer serializer = new FastXmlSerializer(); 12305 try { 12306 serializer.setOutput(str, "utf-8"); 12307 serializer.startDocument(null, true); 12308 serializer.setFeature( 12309 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12310 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12311 serializer.endDocument(); 12312 serializer.flush(); 12313 } catch (IllegalArgumentException e) { 12314 pw.println("Failed writing: " + e); 12315 } catch (IllegalStateException e) { 12316 pw.println("Failed writing: " + e); 12317 } catch (IOException e) { 12318 pw.println("Failed writing: " + e); 12319 } 12320 } 12321 12322 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12323 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12324 } 12325 12326 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12327 boolean printedSomething = false; 12328 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12329 if (packageName != null && !packageName.equals(p.info.packageName)) { 12330 continue; 12331 } 12332 if (!printedSomething) { 12333 if (dumpState.onTitlePrinted()) 12334 pw.println(); 12335 pw.println("Registered ContentProviders:"); 12336 printedSomething = true; 12337 } 12338 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12339 pw.print(" "); pw.println(p.toString()); 12340 } 12341 printedSomething = false; 12342 for (Map.Entry<String, PackageParser.Provider> entry : 12343 mProvidersByAuthority.entrySet()) { 12344 PackageParser.Provider p = entry.getValue(); 12345 if (packageName != null && !packageName.equals(p.info.packageName)) { 12346 continue; 12347 } 12348 if (!printedSomething) { 12349 if (dumpState.onTitlePrinted()) 12350 pw.println(); 12351 pw.println("ContentProvider Authorities:"); 12352 printedSomething = true; 12353 } 12354 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12355 pw.print(" "); pw.println(p.toString()); 12356 if (p.info != null && p.info.applicationInfo != null) { 12357 final String appInfo = p.info.applicationInfo.toString(); 12358 pw.print(" applicationInfo="); pw.println(appInfo); 12359 } 12360 } 12361 } 12362 12363 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12364 mSettings.mKeySetManagerService.dump(pw, packageName, dumpState); 12365 } 12366 12367 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12368 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12369 } 12370 12371 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12372 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12373 } 12374 12375 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12376 if (dumpState.onTitlePrinted()) 12377 pw.println(); 12378 mSettings.dumpReadMessagesLPr(pw, dumpState); 12379 12380 pw.println(); 12381 pw.println("Package warning messages:"); 12382 final File fname = getSettingsProblemFile(); 12383 FileInputStream in = null; 12384 try { 12385 in = new FileInputStream(fname); 12386 final int avail = in.available(); 12387 final byte[] data = new byte[avail]; 12388 in.read(data); 12389 pw.print(new String(data)); 12390 } catch (FileNotFoundException e) { 12391 } catch (IOException e) { 12392 } finally { 12393 if (in != null) { 12394 try { 12395 in.close(); 12396 } catch (IOException e) { 12397 } 12398 } 12399 } 12400 } 12401 } 12402 } 12403 12404 // ------- apps on sdcard specific code ------- 12405 static final boolean DEBUG_SD_INSTALL = false; 12406 12407 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12408 12409 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12410 12411 private boolean mMediaMounted = false; 12412 12413 private String getEncryptKey() { 12414 try { 12415 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12416 SD_ENCRYPTION_KEYSTORE_NAME); 12417 if (sdEncKey == null) { 12418 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12419 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12420 if (sdEncKey == null) { 12421 Slog.e(TAG, "Failed to create encryption keys"); 12422 return null; 12423 } 12424 } 12425 return sdEncKey; 12426 } catch (NoSuchAlgorithmException nsae) { 12427 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12428 return null; 12429 } catch (IOException ioe) { 12430 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12431 return null; 12432 } 12433 12434 } 12435 12436 /* package */static String getTempContainerId() { 12437 int tmpIdx = 1; 12438 String list[] = PackageHelper.getSecureContainerList(); 12439 if (list != null) { 12440 for (final String name : list) { 12441 // Ignore null and non-temporary container entries 12442 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12443 continue; 12444 } 12445 12446 String subStr = name.substring(mTempContainerPrefix.length()); 12447 try { 12448 int cid = Integer.parseInt(subStr); 12449 if (cid >= tmpIdx) { 12450 tmpIdx = cid + 1; 12451 } 12452 } catch (NumberFormatException e) { 12453 } 12454 } 12455 } 12456 return mTempContainerPrefix + tmpIdx; 12457 } 12458 12459 /* 12460 * Update media status on PackageManager. 12461 */ 12462 @Override 12463 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12464 int callingUid = Binder.getCallingUid(); 12465 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12466 throw new SecurityException("Media status can only be updated by the system"); 12467 } 12468 // reader; this apparently protects mMediaMounted, but should probably 12469 // be a different lock in that case. 12470 synchronized (mPackages) { 12471 Log.i(TAG, "Updating external media status from " 12472 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12473 + (mediaStatus ? "mounted" : "unmounted")); 12474 if (DEBUG_SD_INSTALL) 12475 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12476 + ", mMediaMounted=" + mMediaMounted); 12477 if (mediaStatus == mMediaMounted) { 12478 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12479 : 0, -1); 12480 mHandler.sendMessage(msg); 12481 return; 12482 } 12483 mMediaMounted = mediaStatus; 12484 } 12485 // Queue up an async operation since the package installation may take a 12486 // little while. 12487 mHandler.post(new Runnable() { 12488 public void run() { 12489 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12490 } 12491 }); 12492 } 12493 12494 /** 12495 * Called by MountService when the initial ASECs to scan are available. 12496 * Should block until all the ASEC containers are finished being scanned. 12497 */ 12498 public void scanAvailableAsecs() { 12499 updateExternalMediaStatusInner(true, false, false); 12500 if (mShouldRestoreconData) { 12501 SELinuxMMAC.setRestoreconDone(); 12502 mShouldRestoreconData = false; 12503 } 12504 } 12505 12506 /* 12507 * Collect information of applications on external media, map them against 12508 * existing containers and update information based on current mount status. 12509 * Please note that we always have to report status if reportStatus has been 12510 * set to true especially when unloading packages. 12511 */ 12512 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12513 boolean externalStorage) { 12514 // Collection of uids 12515 int uidArr[] = null; 12516 // Collection of stale containers 12517 HashSet<String> removeCids = new HashSet<String>(); 12518 // Collection of packages on external media with valid containers. 12519 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12520 // Get list of secure containers. 12521 final String list[] = PackageHelper.getSecureContainerList(); 12522 if (list == null || list.length == 0) { 12523 Log.i(TAG, "No secure containers on sdcard"); 12524 } else { 12525 // Process list of secure containers and categorize them 12526 // as active or stale based on their package internal state. 12527 int uidList[] = new int[list.length]; 12528 int num = 0; 12529 // reader 12530 synchronized (mPackages) { 12531 for (String cid : list) { 12532 if (DEBUG_SD_INSTALL) 12533 Log.i(TAG, "Processing container " + cid); 12534 String pkgName = getAsecPackageName(cid); 12535 if (pkgName == null) { 12536 if (DEBUG_SD_INSTALL) 12537 Log.i(TAG, "Container : " + cid + " stale"); 12538 removeCids.add(cid); 12539 continue; 12540 } 12541 if (DEBUG_SD_INSTALL) 12542 Log.i(TAG, "Looking for pkg : " + pkgName); 12543 12544 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12545 if (ps == null) { 12546 Log.i(TAG, "Deleting container with no matching settings " + cid); 12547 removeCids.add(cid); 12548 continue; 12549 } 12550 12551 /* 12552 * Skip packages that are not external if we're unmounting 12553 * external storage. 12554 */ 12555 if (externalStorage && !isMounted && !isExternal(ps)) { 12556 continue; 12557 } 12558 12559 final AsecInstallArgs args = new AsecInstallArgs(cid, 12560 getAppInstructionSetFromSettings(ps), 12561 isForwardLocked(ps)); 12562 // The package status is changed only if the code path 12563 // matches between settings and the container id. 12564 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12565 if (DEBUG_SD_INSTALL) { 12566 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12567 + " at code path: " + ps.codePathString); 12568 } 12569 12570 // We do have a valid package installed on sdcard 12571 processCids.put(args, ps.codePathString); 12572 final int uid = ps.appId; 12573 if (uid != -1) { 12574 uidList[num++] = uid; 12575 } 12576 } else { 12577 Log.i(TAG, "Deleting stale container for " + cid); 12578 removeCids.add(cid); 12579 } 12580 } 12581 } 12582 12583 if (num > 0) { 12584 // Sort uid list 12585 Arrays.sort(uidList, 0, num); 12586 // Throw away duplicates 12587 uidArr = new int[num]; 12588 uidArr[0] = uidList[0]; 12589 int di = 0; 12590 for (int i = 1; i < num; i++) { 12591 if (uidList[i - 1] != uidList[i]) { 12592 uidArr[di++] = uidList[i]; 12593 } 12594 } 12595 } 12596 } 12597 // Process packages with valid entries. 12598 if (isMounted) { 12599 if (DEBUG_SD_INSTALL) 12600 Log.i(TAG, "Loading packages"); 12601 loadMediaPackages(processCids, uidArr, removeCids); 12602 startCleaningPackages(); 12603 } else { 12604 if (DEBUG_SD_INSTALL) 12605 Log.i(TAG, "Unloading packages"); 12606 unloadMediaPackages(processCids, uidArr, reportStatus); 12607 } 12608 } 12609 12610 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12611 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12612 int size = pkgList.size(); 12613 if (size > 0) { 12614 // Send broadcasts here 12615 Bundle extras = new Bundle(); 12616 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12617 .toArray(new String[size])); 12618 if (uidArr != null) { 12619 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12620 } 12621 if (replacing) { 12622 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12623 } 12624 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12625 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12626 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12627 } 12628 } 12629 12630 /* 12631 * Look at potentially valid container ids from processCids If package 12632 * information doesn't match the one on record or package scanning fails, 12633 * the cid is added to list of removeCids. We currently don't delete stale 12634 * containers. 12635 */ 12636 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12637 HashSet<String> removeCids) { 12638 ArrayList<String> pkgList = new ArrayList<String>(); 12639 Set<AsecInstallArgs> keys = processCids.keySet(); 12640 boolean doGc = false; 12641 for (AsecInstallArgs args : keys) { 12642 String codePath = processCids.get(args); 12643 if (DEBUG_SD_INSTALL) 12644 Log.i(TAG, "Loading container : " + args.cid); 12645 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12646 try { 12647 // Make sure there are no container errors first. 12648 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12649 Slog.e(TAG, "Failed to mount cid : " + args.cid 12650 + " when installing from sdcard"); 12651 continue; 12652 } 12653 // Check code path here. 12654 if (codePath == null || !codePath.equals(args.getCodePath())) { 12655 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12656 + " does not match one in settings " + codePath); 12657 continue; 12658 } 12659 // Parse package 12660 int parseFlags = mDefParseFlags; 12661 if (args.isExternal()) { 12662 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12663 } 12664 if (args.isFwdLocked()) { 12665 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12666 } 12667 12668 doGc = true; 12669 synchronized (mInstallLock) { 12670 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 12671 0, 0, null, null); 12672 // Scan the package 12673 if (pkg != null) { 12674 /* 12675 * TODO why is the lock being held? doPostInstall is 12676 * called in other places without the lock. This needs 12677 * to be straightened out. 12678 */ 12679 // writer 12680 synchronized (mPackages) { 12681 retCode = PackageManager.INSTALL_SUCCEEDED; 12682 pkgList.add(pkg.packageName); 12683 // Post process args 12684 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12685 pkg.applicationInfo.uid); 12686 } 12687 } else { 12688 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12689 } 12690 } 12691 12692 } finally { 12693 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12694 // Don't destroy container here. Wait till gc clears things 12695 // up. 12696 removeCids.add(args.cid); 12697 } 12698 } 12699 } 12700 // writer 12701 synchronized (mPackages) { 12702 // If the platform SDK has changed since the last time we booted, 12703 // we need to re-grant app permission to catch any new ones that 12704 // appear. This is really a hack, and means that apps can in some 12705 // cases get permissions that the user didn't initially explicitly 12706 // allow... it would be nice to have some better way to handle 12707 // this situation. 12708 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12709 if (regrantPermissions) 12710 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12711 + mSdkVersion + "; regranting permissions for external storage"); 12712 mSettings.mExternalSdkPlatform = mSdkVersion; 12713 12714 // Make sure group IDs have been assigned, and any permission 12715 // changes in other apps are accounted for 12716 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12717 | (regrantPermissions 12718 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12719 : 0)); 12720 12721 mSettings.updateExternalDatabaseVersion(); 12722 12723 // can downgrade to reader 12724 // Persist settings 12725 mSettings.writeLPr(); 12726 } 12727 // Send a broadcast to let everyone know we are done processing 12728 if (pkgList.size() > 0) { 12729 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12730 } 12731 // Force gc to avoid any stale parser references that we might have. 12732 if (doGc) { 12733 Runtime.getRuntime().gc(); 12734 } 12735 // List stale containers and destroy stale temporary containers. 12736 if (removeCids != null) { 12737 for (String cid : removeCids) { 12738 if (cid.startsWith(mTempContainerPrefix)) { 12739 Log.i(TAG, "Destroying stale temporary container " + cid); 12740 PackageHelper.destroySdDir(cid); 12741 } else { 12742 Log.w(TAG, "Container " + cid + " is stale"); 12743 } 12744 } 12745 } 12746 } 12747 12748 /* 12749 * Utility method to unload a list of specified containers 12750 */ 12751 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12752 // Just unmount all valid containers. 12753 for (AsecInstallArgs arg : cidArgs) { 12754 synchronized (mInstallLock) { 12755 arg.doPostDeleteLI(false); 12756 } 12757 } 12758 } 12759 12760 /* 12761 * Unload packages mounted on external media. This involves deleting package 12762 * data from internal structures, sending broadcasts about diabled packages, 12763 * gc'ing to free up references, unmounting all secure containers 12764 * corresponding to packages on external media, and posting a 12765 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12766 * that we always have to post this message if status has been requested no 12767 * matter what. 12768 */ 12769 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12770 final boolean reportStatus) { 12771 if (DEBUG_SD_INSTALL) 12772 Log.i(TAG, "unloading media packages"); 12773 ArrayList<String> pkgList = new ArrayList<String>(); 12774 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12775 final Set<AsecInstallArgs> keys = processCids.keySet(); 12776 for (AsecInstallArgs args : keys) { 12777 String pkgName = args.getPackageName(); 12778 if (DEBUG_SD_INSTALL) 12779 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12780 // Delete package internally 12781 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12782 synchronized (mInstallLock) { 12783 boolean res = deletePackageLI(pkgName, null, false, null, null, 12784 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12785 if (res) { 12786 pkgList.add(pkgName); 12787 } else { 12788 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12789 failedList.add(args); 12790 } 12791 } 12792 } 12793 12794 // reader 12795 synchronized (mPackages) { 12796 // We didn't update the settings after removing each package; 12797 // write them now for all packages. 12798 mSettings.writeLPr(); 12799 } 12800 12801 // We have to absolutely send UPDATED_MEDIA_STATUS only 12802 // after confirming that all the receivers processed the ordered 12803 // broadcast when packages get disabled, force a gc to clean things up. 12804 // and unload all the containers. 12805 if (pkgList.size() > 0) { 12806 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12807 new IIntentReceiver.Stub() { 12808 public void performReceive(Intent intent, int resultCode, String data, 12809 Bundle extras, boolean ordered, boolean sticky, 12810 int sendingUser) throws RemoteException { 12811 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12812 reportStatus ? 1 : 0, 1, keys); 12813 mHandler.sendMessage(msg); 12814 } 12815 }); 12816 } else { 12817 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12818 keys); 12819 mHandler.sendMessage(msg); 12820 } 12821 } 12822 12823 /** Binder call */ 12824 @Override 12825 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12826 final int flags) { 12827 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12828 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12829 int returnCode = PackageManager.MOVE_SUCCEEDED; 12830 int currFlags = 0; 12831 int newFlags = 0; 12832 // reader 12833 synchronized (mPackages) { 12834 PackageParser.Package pkg = mPackages.get(packageName); 12835 if (pkg == null) { 12836 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12837 } else { 12838 // Disable moving fwd locked apps and system packages 12839 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12840 Slog.w(TAG, "Cannot move system application"); 12841 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12842 } else if (pkg.mOperationPending) { 12843 Slog.w(TAG, "Attempt to move package which has pending operations"); 12844 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12845 } else { 12846 // Find install location first 12847 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12848 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12849 Slog.w(TAG, "Ambigous flags specified for move location."); 12850 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12851 } else { 12852 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12853 : PackageManager.INSTALL_INTERNAL; 12854 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12855 : PackageManager.INSTALL_INTERNAL; 12856 12857 if (newFlags == currFlags) { 12858 Slog.w(TAG, "No move required. Trying to move to same location"); 12859 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12860 } else { 12861 if (isForwardLocked(pkg)) { 12862 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12863 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12864 } 12865 } 12866 } 12867 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12868 pkg.mOperationPending = true; 12869 } 12870 } 12871 } 12872 12873 /* 12874 * TODO this next block probably shouldn't be inside the lock. We 12875 * can't guarantee these won't change after this is fired off 12876 * anyway. 12877 */ 12878 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12879 processPendingMove(new MoveParams(null, observer, 0, packageName, null, 12880 null, -1, user), 12881 returnCode); 12882 } else { 12883 Message msg = mHandler.obtainMessage(INIT_COPY); 12884 final String instructionSet = getAppInstructionSet(pkg.applicationInfo); 12885 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 12886 pkg.applicationInfo.sourceDir, pkg.applicationInfo.publicSourceDir, 12887 pkg.applicationInfo.nativeLibraryDir, instructionSet); 12888 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12889 pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user); 12890 msg.obj = mp; 12891 mHandler.sendMessage(msg); 12892 } 12893 } 12894 } 12895 12896 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12897 // Queue up an async operation since the package deletion may take a 12898 // little while. 12899 mHandler.post(new Runnable() { 12900 public void run() { 12901 // TODO fix this; this does nothing. 12902 mHandler.removeCallbacks(this); 12903 int returnCode = currentStatus; 12904 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12905 int uidArr[] = null; 12906 ArrayList<String> pkgList = null; 12907 synchronized (mPackages) { 12908 PackageParser.Package pkg = mPackages.get(mp.packageName); 12909 if (pkg == null) { 12910 Slog.w(TAG, " Package " + mp.packageName 12911 + " doesn't exist. Aborting move"); 12912 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12913 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 12914 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12915 + mp.srcArgs.getCodePath() + " to " 12916 + pkg.applicationInfo.sourceDir 12917 + " Aborting move and returning error"); 12918 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12919 } else { 12920 uidArr = new int[] { 12921 pkg.applicationInfo.uid 12922 }; 12923 pkgList = new ArrayList<String>(); 12924 pkgList.add(mp.packageName); 12925 } 12926 } 12927 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12928 // Send resources unavailable broadcast 12929 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12930 // Update package code and resource paths 12931 synchronized (mInstallLock) { 12932 synchronized (mPackages) { 12933 PackageParser.Package pkg = mPackages.get(mp.packageName); 12934 // Recheck for package again. 12935 if (pkg == null) { 12936 Slog.w(TAG, " Package " + mp.packageName 12937 + " doesn't exist. Aborting move"); 12938 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12939 } else if (!mp.srcArgs.getCodePath().equals( 12940 pkg.applicationInfo.sourceDir)) { 12941 Slog.w(TAG, "Package " + mp.packageName 12942 + " code path changed from " + mp.srcArgs.getCodePath() 12943 + " to " + pkg.applicationInfo.sourceDir 12944 + " Aborting move and returning error"); 12945 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12946 } else { 12947 final String oldCodePath = pkg.codePath; 12948 final String newCodePath = mp.targetArgs.getCodePath(); 12949 final String newResPath = mp.targetArgs.getResourcePath(); 12950 final String newNativePath = mp.targetArgs 12951 .getNativeLibraryPath(); 12952 12953 final File newNativeDir = new File(newNativePath); 12954 12955 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12956 NativeLibraryHelper.Handle handle = null; 12957 try { 12958 handle = NativeLibraryHelper.Handle.create( 12959 new File(newCodePath)); 12960 final int abi = NativeLibraryHelper.findSupportedAbi( 12961 handle, Build.SUPPORTED_ABIS); 12962 if (abi >= 0) { 12963 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12964 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12965 } 12966 } catch (IOException ioe) { 12967 Slog.w(TAG, "Unable to extract native libs for package :" 12968 + mp.packageName, ioe); 12969 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12970 } finally { 12971 IoUtils.closeQuietly(handle); 12972 } 12973 } 12974 final int[] users = sUserManager.getUserIds(); 12975 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12976 for (int user : users) { 12977 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 12978 newNativePath, user) < 0) { 12979 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12980 } 12981 } 12982 } 12983 12984 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12985 pkg.codePath = newCodePath; 12986 pkg.baseCodePath = newCodePath; 12987 // Move dex files around 12988 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 12989 // Moving of dex files failed. Set 12990 // error code and abort move. 12991 pkg.codePath = oldCodePath; 12992 pkg.baseCodePath = oldCodePath; 12993 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12994 } 12995 } 12996 12997 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12998 pkg.applicationInfo.sourceDir = newCodePath; 12999 pkg.applicationInfo.publicSourceDir = newResPath; 13000 pkg.applicationInfo.nativeLibraryDir = newNativePath; 13001 PackageSetting ps = (PackageSetting) pkg.mExtras; 13002 ps.codePath = new File(pkg.applicationInfo.sourceDir); 13003 ps.codePathString = ps.codePath.getPath(); 13004 ps.resourcePath = new File( 13005 pkg.applicationInfo.publicSourceDir); 13006 ps.resourcePathString = ps.resourcePath.getPath(); 13007 ps.nativeLibraryPathString = newNativePath; 13008 // Set the application info flag 13009 // correctly. 13010 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13011 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13012 } else { 13013 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13014 } 13015 ps.setFlags(pkg.applicationInfo.flags); 13016 mAppDirs.remove(oldCodePath); 13017 mAppDirs.put(newCodePath, pkg); 13018 // Persist settings 13019 mSettings.writeLPr(); 13020 } 13021 } 13022 } 13023 } 13024 // Send resources available broadcast 13025 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13026 } 13027 } 13028 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13029 // Clean up failed installation 13030 if (mp.targetArgs != null) { 13031 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13032 -1); 13033 } 13034 } else { 13035 // Force a gc to clear things up. 13036 Runtime.getRuntime().gc(); 13037 // Delete older code 13038 synchronized (mInstallLock) { 13039 mp.srcArgs.doPostDeleteLI(true); 13040 } 13041 } 13042 13043 // Allow more operations on this file if we didn't fail because 13044 // an operation was already pending for this package. 13045 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13046 synchronized (mPackages) { 13047 PackageParser.Package pkg = mPackages.get(mp.packageName); 13048 if (pkg != null) { 13049 pkg.mOperationPending = false; 13050 } 13051 } 13052 } 13053 13054 IPackageMoveObserver observer = mp.observer; 13055 if (observer != null) { 13056 try { 13057 observer.packageMoved(mp.packageName, returnCode); 13058 } catch (RemoteException e) { 13059 Log.i(TAG, "Observer no longer exists."); 13060 } 13061 } 13062 } 13063 }); 13064 } 13065 13066 @Override 13067 public boolean setInstallLocation(int loc) { 13068 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13069 null); 13070 if (getInstallLocation() == loc) { 13071 return true; 13072 } 13073 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13074 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13075 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13076 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13077 return true; 13078 } 13079 return false; 13080 } 13081 13082 @Override 13083 public int getInstallLocation() { 13084 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13085 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13086 PackageHelper.APP_INSTALL_AUTO); 13087 } 13088 13089 /** Called by UserManagerService */ 13090 void cleanUpUserLILPw(int userHandle) { 13091 mDirtyUsers.remove(userHandle); 13092 mSettings.removeUserLPr(userHandle); 13093 mPendingBroadcasts.remove(userHandle); 13094 if (mInstaller != null) { 13095 // Technically, we shouldn't be doing this with the package lock 13096 // held. However, this is very rare, and there is already so much 13097 // other disk I/O going on, that we'll let it slide for now. 13098 mInstaller.removeUserDataDirs(userHandle); 13099 } 13100 mUserNeedsBadging.delete(userHandle); 13101 } 13102 13103 /** Called by UserManagerService */ 13104 void createNewUserLILPw(int userHandle, File path) { 13105 if (mInstaller != null) { 13106 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13107 } 13108 } 13109 13110 @Override 13111 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13112 mContext.enforceCallingOrSelfPermission( 13113 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13114 "Only package verification agents can read the verifier device identity"); 13115 13116 synchronized (mPackages) { 13117 return mSettings.getVerifierDeviceIdentityLPw(); 13118 } 13119 } 13120 13121 @Override 13122 public void setPermissionEnforced(String permission, boolean enforced) { 13123 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13124 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13125 synchronized (mPackages) { 13126 if (mSettings.mReadExternalStorageEnforced == null 13127 || mSettings.mReadExternalStorageEnforced != enforced) { 13128 mSettings.mReadExternalStorageEnforced = enforced; 13129 mSettings.writeLPr(); 13130 } 13131 } 13132 // kill any non-foreground processes so we restart them and 13133 // grant/revoke the GID. 13134 final IActivityManager am = ActivityManagerNative.getDefault(); 13135 if (am != null) { 13136 final long token = Binder.clearCallingIdentity(); 13137 try { 13138 am.killProcessesBelowForeground("setPermissionEnforcement"); 13139 } catch (RemoteException e) { 13140 } finally { 13141 Binder.restoreCallingIdentity(token); 13142 } 13143 } 13144 } else { 13145 throw new IllegalArgumentException("No selective enforcement for " + permission); 13146 } 13147 } 13148 13149 @Override 13150 @Deprecated 13151 public boolean isPermissionEnforced(String permission) { 13152 return true; 13153 } 13154 13155 @Override 13156 public boolean isStorageLow() { 13157 final long token = Binder.clearCallingIdentity(); 13158 try { 13159 final DeviceStorageMonitorInternal 13160 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13161 if (dsm != null) { 13162 return dsm.isMemoryLow(); 13163 } else { 13164 return false; 13165 } 13166 } finally { 13167 Binder.restoreCallingIdentity(token); 13168 } 13169 } 13170 13171 @Override 13172 public IPackageInstaller getPackageInstaller() { 13173 return mInstallerService; 13174 } 13175 13176 private boolean userNeedsBadging(int userId) { 13177 int index = mUserNeedsBadging.indexOfKey(userId); 13178 if (index < 0) { 13179 final UserInfo userInfo; 13180 final long token = Binder.clearCallingIdentity(); 13181 try { 13182 userInfo = sUserManager.getUserInfo(userId); 13183 } finally { 13184 Binder.restoreCallingIdentity(token); 13185 } 13186 final boolean b; 13187 if (userInfo != null && userInfo.isManagedProfile()) { 13188 b = true; 13189 } else { 13190 b = false; 13191 } 13192 mUserNeedsBadging.put(userId, b); 13193 return b; 13194 } 13195 return mUserNeedsBadging.valueAt(index); 13196 } 13197} 13198