PackageManagerService.java revision cef0b39b9211882f59b6bfe1148e2cd247056693
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.Manifest.permission.INSTALL_PACKAGES; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.os.Process.PACKAGE_INFO_GID; 28import static android.os.Process.SYSTEM_UID; 29import static android.system.OsConstants.S_IRGRP; 30import static android.system.OsConstants.S_IROTH; 31import static android.system.OsConstants.S_IRWXU; 32import static android.system.OsConstants.S_IXGRP; 33import static android.system.OsConstants.S_IXOTH; 34import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 35import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 36import static com.android.internal.util.ArrayUtils.appendInt; 37import static com.android.internal.util.ArrayUtils.removeInt; 38 39import android.util.ArrayMap; 40import com.android.internal.R; 41import com.android.internal.app.IMediaContainerService; 42import com.android.internal.app.ResolverActivity; 43import com.android.internal.content.NativeLibraryHelper; 44import com.android.internal.content.NativeLibraryHelper.ApkHandle; 45import com.android.internal.content.PackageHelper; 46import com.android.internal.util.ArrayUtils; 47import com.android.internal.util.FastPrintWriter; 48import com.android.internal.util.FastXmlSerializer; 49import com.android.internal.util.XmlUtils; 50import com.android.server.EventLogTags; 51import com.android.server.IntentResolver; 52import com.android.server.LocalServices; 53import com.android.server.ServiceThread; 54import com.android.server.SystemConfig; 55import com.android.server.Watchdog; 56import com.android.server.pm.Settings.DatabaseVersion; 57import com.android.server.storage.DeviceStorageMonitorInternal; 58 59import org.xmlpull.v1.XmlPullParser; 60import org.xmlpull.v1.XmlPullParserException; 61import org.xmlpull.v1.XmlSerializer; 62 63import android.app.ActivityManager; 64import android.app.ActivityManagerNative; 65import android.app.IActivityManager; 66import android.app.PackageInstallObserver; 67import android.app.admin.IDevicePolicyManager; 68import android.app.backup.IBackupManager; 69import android.content.BroadcastReceiver; 70import android.content.ComponentName; 71import android.content.Context; 72import android.content.IIntentReceiver; 73import android.content.Intent; 74import android.content.IntentFilter; 75import android.content.IntentSender; 76import android.content.IntentSender.SendIntentException; 77import android.content.ServiceConnection; 78import android.content.pm.ActivityInfo; 79import android.content.pm.ApplicationInfo; 80import android.content.pm.ContainerEncryptionParams; 81import android.content.pm.FeatureInfo; 82import android.content.pm.IPackageDataObserver; 83import android.content.pm.IPackageDeleteObserver; 84import android.content.pm.IPackageInstallObserver; 85import android.content.pm.IPackageInstallObserver2; 86import android.content.pm.IPackageInstaller; 87import android.content.pm.IPackageManager; 88import android.content.pm.IPackageMoveObserver; 89import android.content.pm.IPackageStatsObserver; 90import android.content.pm.InstrumentationInfo; 91import android.content.pm.ManifestDigest; 92import android.content.pm.PackageCleanItem; 93import android.content.pm.PackageInfo; 94import android.content.pm.PackageInfoLite; 95import android.content.pm.PackageManager; 96import android.content.pm.PackageParser.ActivityIntentInfo; 97import android.content.pm.PackageParser.PackageParserException; 98import android.content.pm.PackageParser; 99import android.content.pm.PackageStats; 100import android.content.pm.PackageUserState; 101import android.content.pm.ParceledListSlice; 102import android.content.pm.PermissionGroupInfo; 103import android.content.pm.PermissionInfo; 104import android.content.pm.ProviderInfo; 105import android.content.pm.ResolveInfo; 106import android.content.pm.ServiceInfo; 107import android.content.pm.Signature; 108import android.content.pm.VerificationParams; 109import android.content.pm.VerifierDeviceIdentity; 110import android.content.pm.VerifierInfo; 111import android.content.res.Resources; 112import android.hardware.display.DisplayManager; 113import android.net.Uri; 114import android.os.Binder; 115import android.os.Build; 116import android.os.Bundle; 117import android.os.Environment; 118import android.os.Environment.UserEnvironment; 119import android.os.FileObserver; 120import android.os.FileUtils; 121import android.os.Handler; 122import android.os.IBinder; 123import android.os.Looper; 124import android.os.Message; 125import android.os.Parcel; 126import android.os.ParcelFileDescriptor; 127import android.os.Process; 128import android.os.RemoteException; 129import android.os.SELinux; 130import android.os.ServiceManager; 131import android.os.SystemClock; 132import android.os.SystemProperties; 133import android.os.UserHandle; 134import android.os.UserManager; 135import android.security.KeyStore; 136import android.security.SystemKeyStore; 137import android.system.ErrnoException; 138import android.system.Os; 139import android.system.StructStat; 140import android.text.TextUtils; 141import android.util.ArraySet; 142import android.util.AtomicFile; 143import android.util.DisplayMetrics; 144import android.util.EventLog; 145import android.util.Log; 146import android.util.LogPrinter; 147import android.util.PrintStreamPrinter; 148import android.util.Slog; 149import android.util.SparseArray; 150import android.util.SparseBooleanArray; 151import android.util.Xml; 152import android.view.Display; 153 154import java.io.BufferedInputStream; 155import java.io.BufferedOutputStream; 156import java.io.File; 157import java.io.FileDescriptor; 158import java.io.FileInputStream; 159import java.io.FileNotFoundException; 160import java.io.FileOutputStream; 161import java.io.FileReader; 162import java.io.FilenameFilter; 163import java.io.IOException; 164import java.io.InputStream; 165import java.io.PrintWriter; 166import java.nio.charset.StandardCharsets; 167import java.security.NoSuchAlgorithmException; 168import java.security.PublicKey; 169import java.security.cert.CertificateEncodingException; 170import java.security.cert.CertificateException; 171import java.text.SimpleDateFormat; 172import java.util.ArrayList; 173import java.util.Arrays; 174import java.util.Collection; 175import java.util.Collections; 176import java.util.Comparator; 177import java.util.Date; 178import java.util.HashMap; 179import java.util.HashSet; 180import java.util.Iterator; 181import java.util.List; 182import java.util.Map; 183import java.util.Set; 184import java.util.concurrent.atomic.AtomicBoolean; 185import java.util.concurrent.atomic.AtomicLong; 186 187import dalvik.system.DexFile; 188import dalvik.system.StaleDexCacheError; 189import dalvik.system.VMRuntime; 190 191import libcore.io.IoUtils; 192 193/** 194 * Keep track of all those .apks everywhere. 195 * 196 * This is very central to the platform's security; please run the unit 197 * tests whenever making modifications here: 198 * 199mmm frameworks/base/tests/AndroidTests 200adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 201adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 202 * 203 * {@hide} 204 */ 205public class PackageManagerService extends IPackageManager.Stub { 206 static final String TAG = "PackageManager"; 207 static final boolean DEBUG_SETTINGS = false; 208 static final boolean DEBUG_PREFERRED = false; 209 static final boolean DEBUG_UPGRADE = false; 210 private static final boolean DEBUG_INSTALL = false; 211 private static final boolean DEBUG_REMOVE = false; 212 private static final boolean DEBUG_BROADCASTS = false; 213 private static final boolean DEBUG_SHOW_INFO = false; 214 private static final boolean DEBUG_PACKAGE_INFO = false; 215 private static final boolean DEBUG_INTENT_MATCHING = false; 216 private static final boolean DEBUG_PACKAGE_SCANNING = false; 217 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 218 private static final boolean DEBUG_VERIFY = false; 219 private static final boolean DEBUG_DEXOPT = false; 220 221 private static final int RADIO_UID = Process.PHONE_UID; 222 private static final int LOG_UID = Process.LOG_UID; 223 private static final int NFC_UID = Process.NFC_UID; 224 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 225 private static final int SHELL_UID = Process.SHELL_UID; 226 227 // Cap the size of permission trees that 3rd party apps can define 228 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 229 230 private static final int REMOVE_EVENTS = 231 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 232 private static final int ADD_EVENTS = 233 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 234 235 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 236 // Suffix used during package installation when copying/moving 237 // package apks to install directory. 238 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 239 240 static final int SCAN_MONITOR = 1<<0; 241 static final int SCAN_NO_DEX = 1<<1; 242 static final int SCAN_FORCE_DEX = 1<<2; 243 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 244 static final int SCAN_NEW_INSTALL = 1<<4; 245 static final int SCAN_NO_PATHS = 1<<5; 246 static final int SCAN_UPDATE_TIME = 1<<6; 247 static final int SCAN_DEFER_DEX = 1<<7; 248 static final int SCAN_BOOTING = 1<<8; 249 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 250 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 251 252 static final int REMOVE_CHATTY = 1<<16; 253 254 /** 255 * Timeout (in milliseconds) after which the watchdog should declare that 256 * our handler thread is wedged. The usual default for such things is one 257 * minute but we sometimes do very lengthy I/O operations on this thread, 258 * such as installing multi-gigabyte applications, so ours needs to be longer. 259 */ 260 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 261 262 /** 263 * Whether verification is enabled by default. 264 */ 265 private static final boolean DEFAULT_VERIFY_ENABLE = true; 266 267 /** 268 * The default maximum time to wait for the verification agent to return in 269 * milliseconds. 270 */ 271 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 272 273 /** 274 * The default response for package verification timeout. 275 * 276 * This can be either PackageManager.VERIFICATION_ALLOW or 277 * PackageManager.VERIFICATION_REJECT. 278 */ 279 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 280 281 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 282 283 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 284 DEFAULT_CONTAINER_PACKAGE, 285 "com.android.defcontainer.DefaultContainerService"); 286 287 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 288 289 private static final String LIB_DIR_NAME = "lib"; 290 private static final String LIB64_DIR_NAME = "lib64"; 291 292 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 293 294 static final String mTempContainerPrefix = "smdl2tmp"; 295 296 private static String sPreferredInstructionSet; 297 298 final ServiceThread mHandlerThread; 299 300 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 301 private static final String IDMAP_SUFFIX = "@idmap"; 302 303 final PackageHandler mHandler; 304 305 final int mSdkVersion = Build.VERSION.SDK_INT; 306 307 final Context mContext; 308 final boolean mFactoryTest; 309 final boolean mOnlyCore; 310 final DisplayMetrics mMetrics; 311 final int mDefParseFlags; 312 final String[] mSeparateProcesses; 313 314 // This is where all application persistent data goes. 315 final File mAppDataDir; 316 317 // This is where all application persistent data goes for secondary users. 318 final File mUserAppDataDir; 319 320 /** The location for ASEC container files on internal storage. */ 321 final String mAsecInternalPath; 322 323 // This is the object monitoring the framework dir. 324 final FileObserver mFrameworkInstallObserver; 325 326 // This is the object monitoring the system app dir. 327 final FileObserver mSystemInstallObserver; 328 329 // This is the object monitoring the privileged system app dir. 330 final FileObserver mPrivilegedInstallObserver; 331 332 // This is the object monitoring the vendor app dir. 333 final FileObserver mVendorInstallObserver; 334 335 // This is the object monitoring the vendor overlay package dir. 336 final FileObserver mVendorOverlayInstallObserver; 337 338 // This is the object monitoring the OEM app dir. 339 final FileObserver mOemInstallObserver; 340 341 // This is the object monitoring mAppInstallDir. 342 final FileObserver mAppInstallObserver; 343 344 // This is the object monitoring mDrmAppPrivateInstallDir. 345 final FileObserver mDrmAppInstallObserver; 346 347 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 348 // LOCK HELD. Can be called with mInstallLock held. 349 final Installer mInstaller; 350 351 final File mAppInstallDir; 352 353 /** 354 * Directory to which applications installed internally have native 355 * libraries copied. 356 */ 357 private File mAppLibInstallDir; 358 359 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 360 // apps. 361 final File mDrmAppPrivateInstallDir; 362 363 final File mAppStagingDir; 364 365 // ---------------------------------------------------------------- 366 367 // Lock for state used when installing and doing other long running 368 // operations. Methods that must be called with this lock held have 369 // the suffix "LI". 370 final Object mInstallLock = new Object(); 371 372 // These are the directories in the 3rd party applications installed dir 373 // that we have currently loaded packages from. Keys are the application's 374 // installed zip file (absolute codePath), and values are Package. 375 final HashMap<String, PackageParser.Package> mAppDirs = 376 new HashMap<String, PackageParser.Package>(); 377 378 // Information for the parser to write more useful error messages. 379 int mLastScanError; 380 381 // ---------------------------------------------------------------- 382 383 // Keys are String (package name), values are Package. This also serves 384 // as the lock for the global state. Methods that must be called with 385 // this lock held have the prefix "LP". 386 final HashMap<String, PackageParser.Package> mPackages = 387 new HashMap<String, PackageParser.Package>(); 388 389 // Tracks available target package names -> overlay package paths. 390 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 391 new HashMap<String, HashMap<String, PackageParser.Package>>(); 392 393 final Settings mSettings; 394 boolean mRestoredSettings; 395 396 // System configuration read by SystemConfig. 397 final int[] mGlobalGids; 398 final SparseArray<HashSet<String>> mSystemPermissions; 399 final HashMap<String, FeatureInfo> mAvailableFeatures; 400 401 // If mac_permissions.xml was found for seinfo labeling. 402 boolean mFoundPolicyFile; 403 404 // If a recursive restorecon of /data/data/<pkg> is needed. 405 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 406 407 public static final class SharedLibraryEntry { 408 public final String path; 409 public final String apk; 410 411 SharedLibraryEntry(String _path, String _apk) { 412 path = _path; 413 apk = _apk; 414 } 415 } 416 417 // Currently known shared libraries. 418 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 419 new HashMap<String, SharedLibraryEntry>(); 420 421 // All available activities, for your resolving pleasure. 422 final ActivityIntentResolver mActivities = 423 new ActivityIntentResolver(); 424 425 // All available receivers, for your resolving pleasure. 426 final ActivityIntentResolver mReceivers = 427 new ActivityIntentResolver(); 428 429 // All available services, for your resolving pleasure. 430 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 431 432 // All available providers, for your resolving pleasure. 433 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 434 435 // Mapping from provider base names (first directory in content URI codePath) 436 // to the provider information. 437 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 438 new HashMap<String, PackageParser.Provider>(); 439 440 // Mapping from instrumentation class names to info about them. 441 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 442 new HashMap<ComponentName, PackageParser.Instrumentation>(); 443 444 // Mapping from permission names to info about them. 445 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 446 new HashMap<String, PackageParser.PermissionGroup>(); 447 448 // Packages whose data we have transfered into another package, thus 449 // should no longer exist. 450 final HashSet<String> mTransferedPackages = new HashSet<String>(); 451 452 // Broadcast actions that are only available to the system. 453 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 454 455 /** List of packages waiting for verification. */ 456 final SparseArray<PackageVerificationState> mPendingVerification 457 = new SparseArray<PackageVerificationState>(); 458 459 final PackageInstallerService mInstallerService; 460 461 HashSet<PackageParser.Package> mDeferredDexOpt = null; 462 463 /** Token for keys in mPendingVerification. */ 464 private int mPendingVerificationToken = 0; 465 466 boolean mSystemReady; 467 boolean mSafeMode; 468 boolean mHasSystemUidErrors; 469 470 ApplicationInfo mAndroidApplication; 471 final ActivityInfo mResolveActivity = new ActivityInfo(); 472 final ResolveInfo mResolveInfo = new ResolveInfo(); 473 ComponentName mResolveComponentName; 474 PackageParser.Package mPlatformPackage; 475 ComponentName mCustomResolverComponentName; 476 477 boolean mResolverReplaced = false; 478 479 // Set of pending broadcasts for aggregating enable/disable of components. 480 static class PendingPackageBroadcasts { 481 // for each user id, a map of <package name -> components within that package> 482 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 483 484 public PendingPackageBroadcasts() { 485 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 486 } 487 488 public ArrayList<String> get(int userId, String packageName) { 489 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 490 return packages.get(packageName); 491 } 492 493 public void put(int userId, String packageName, ArrayList<String> components) { 494 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 495 packages.put(packageName, components); 496 } 497 498 public void remove(int userId, String packageName) { 499 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 500 if (packages != null) { 501 packages.remove(packageName); 502 } 503 } 504 505 public void remove(int userId) { 506 mUidMap.remove(userId); 507 } 508 509 public int userIdCount() { 510 return mUidMap.size(); 511 } 512 513 public int userIdAt(int n) { 514 return mUidMap.keyAt(n); 515 } 516 517 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 518 return mUidMap.get(userId); 519 } 520 521 public int size() { 522 // total number of pending broadcast entries across all userIds 523 int num = 0; 524 for (int i = 0; i< mUidMap.size(); i++) { 525 num += mUidMap.valueAt(i).size(); 526 } 527 return num; 528 } 529 530 public void clear() { 531 mUidMap.clear(); 532 } 533 534 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 535 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 536 if (map == null) { 537 map = new HashMap<String, ArrayList<String>>(); 538 mUidMap.put(userId, map); 539 } 540 return map; 541 } 542 } 543 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 544 545 // Service Connection to remote media container service to copy 546 // package uri's from external media onto secure containers 547 // or internal storage. 548 private IMediaContainerService mContainerService = null; 549 550 static final int SEND_PENDING_BROADCAST = 1; 551 static final int MCS_BOUND = 3; 552 static final int END_COPY = 4; 553 static final int INIT_COPY = 5; 554 static final int MCS_UNBIND = 6; 555 static final int START_CLEANING_PACKAGE = 7; 556 static final int FIND_INSTALL_LOC = 8; 557 static final int POST_INSTALL = 9; 558 static final int MCS_RECONNECT = 10; 559 static final int MCS_GIVE_UP = 11; 560 static final int UPDATED_MEDIA_STATUS = 12; 561 static final int WRITE_SETTINGS = 13; 562 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 563 static final int PACKAGE_VERIFIED = 15; 564 static final int CHECK_PENDING_VERIFICATION = 16; 565 566 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 567 568 // Delay time in millisecs 569 static final int BROADCAST_DELAY = 10 * 1000; 570 571 static UserManagerService sUserManager; 572 573 // Stores a list of users whose package restrictions file needs to be updated 574 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 575 576 final private DefaultContainerConnection mDefContainerConn = 577 new DefaultContainerConnection(); 578 class DefaultContainerConnection implements ServiceConnection { 579 public void onServiceConnected(ComponentName name, IBinder service) { 580 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 581 IMediaContainerService imcs = 582 IMediaContainerService.Stub.asInterface(service); 583 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 584 } 585 586 public void onServiceDisconnected(ComponentName name) { 587 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 588 } 589 }; 590 591 // Recordkeeping of restore-after-install operations that are currently in flight 592 // between the Package Manager and the Backup Manager 593 class PostInstallData { 594 public InstallArgs args; 595 public PackageInstalledInfo res; 596 597 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 598 args = _a; 599 res = _r; 600 } 601 }; 602 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 603 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 604 605 private final String mRequiredVerifierPackage; 606 607 private final PackageUsage mPackageUsage = new PackageUsage(); 608 609 private class PackageUsage { 610 private static final int WRITE_INTERVAL 611 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 612 613 private final Object mFileLock = new Object(); 614 private final AtomicLong mLastWritten = new AtomicLong(0); 615 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 616 617 private boolean mIsHistoricalPackageUsageAvailable = true; 618 619 boolean isHistoricalPackageUsageAvailable() { 620 return mIsHistoricalPackageUsageAvailable; 621 } 622 623 void write(boolean force) { 624 if (force) { 625 writeInternal(); 626 return; 627 } 628 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 629 && !DEBUG_DEXOPT) { 630 return; 631 } 632 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 633 new Thread("PackageUsage_DiskWriter") { 634 @Override 635 public void run() { 636 try { 637 writeInternal(); 638 } finally { 639 mBackgroundWriteRunning.set(false); 640 } 641 } 642 }.start(); 643 } 644 } 645 646 private void writeInternal() { 647 synchronized (mPackages) { 648 synchronized (mFileLock) { 649 AtomicFile file = getFile(); 650 FileOutputStream f = null; 651 try { 652 f = file.startWrite(); 653 BufferedOutputStream out = new BufferedOutputStream(f); 654 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 655 StringBuilder sb = new StringBuilder(); 656 for (PackageParser.Package pkg : mPackages.values()) { 657 if (pkg.mLastPackageUsageTimeInMills == 0) { 658 continue; 659 } 660 sb.setLength(0); 661 sb.append(pkg.packageName); 662 sb.append(' '); 663 sb.append((long)pkg.mLastPackageUsageTimeInMills); 664 sb.append('\n'); 665 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 666 } 667 out.flush(); 668 file.finishWrite(f); 669 } catch (IOException e) { 670 if (f != null) { 671 file.failWrite(f); 672 } 673 Log.e(TAG, "Failed to write package usage times", e); 674 } 675 } 676 } 677 mLastWritten.set(SystemClock.elapsedRealtime()); 678 } 679 680 void readLP() { 681 synchronized (mFileLock) { 682 AtomicFile file = getFile(); 683 BufferedInputStream in = null; 684 try { 685 in = new BufferedInputStream(file.openRead()); 686 StringBuffer sb = new StringBuffer(); 687 while (true) { 688 String packageName = readToken(in, sb, ' '); 689 if (packageName == null) { 690 break; 691 } 692 String timeInMillisString = readToken(in, sb, '\n'); 693 if (timeInMillisString == null) { 694 throw new IOException("Failed to find last usage time for package " 695 + packageName); 696 } 697 PackageParser.Package pkg = mPackages.get(packageName); 698 if (pkg == null) { 699 continue; 700 } 701 long timeInMillis; 702 try { 703 timeInMillis = Long.parseLong(timeInMillisString.toString()); 704 } catch (NumberFormatException e) { 705 throw new IOException("Failed to parse " + timeInMillisString 706 + " as a long.", e); 707 } 708 pkg.mLastPackageUsageTimeInMills = timeInMillis; 709 } 710 } catch (FileNotFoundException expected) { 711 mIsHistoricalPackageUsageAvailable = false; 712 } catch (IOException e) { 713 Log.w(TAG, "Failed to read package usage times", e); 714 } finally { 715 IoUtils.closeQuietly(in); 716 } 717 } 718 mLastWritten.set(SystemClock.elapsedRealtime()); 719 } 720 721 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 722 throws IOException { 723 sb.setLength(0); 724 while (true) { 725 int ch = in.read(); 726 if (ch == -1) { 727 if (sb.length() == 0) { 728 return null; 729 } 730 throw new IOException("Unexpected EOF"); 731 } 732 if (ch == endOfToken) { 733 return sb.toString(); 734 } 735 sb.append((char)ch); 736 } 737 } 738 739 private AtomicFile getFile() { 740 File dataDir = Environment.getDataDirectory(); 741 File systemDir = new File(dataDir, "system"); 742 File fname = new File(systemDir, "package-usage.list"); 743 return new AtomicFile(fname); 744 } 745 } 746 747 class PackageHandler extends Handler { 748 private boolean mBound = false; 749 final ArrayList<HandlerParams> mPendingInstalls = 750 new ArrayList<HandlerParams>(); 751 752 private boolean connectToService() { 753 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 754 " DefaultContainerService"); 755 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 756 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 757 if (mContext.bindServiceAsUser(service, mDefContainerConn, 758 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 759 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 760 mBound = true; 761 return true; 762 } 763 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 764 return false; 765 } 766 767 private void disconnectService() { 768 mContainerService = null; 769 mBound = false; 770 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 771 mContext.unbindService(mDefContainerConn); 772 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 773 } 774 775 PackageHandler(Looper looper) { 776 super(looper); 777 } 778 779 public void handleMessage(Message msg) { 780 try { 781 doHandleMessage(msg); 782 } finally { 783 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 784 } 785 } 786 787 void doHandleMessage(Message msg) { 788 switch (msg.what) { 789 case INIT_COPY: { 790 HandlerParams params = (HandlerParams) msg.obj; 791 int idx = mPendingInstalls.size(); 792 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 793 // If a bind was already initiated we dont really 794 // need to do anything. The pending install 795 // will be processed later on. 796 if (!mBound) { 797 // If this is the only one pending we might 798 // have to bind to the service again. 799 if (!connectToService()) { 800 Slog.e(TAG, "Failed to bind to media container service"); 801 params.serviceError(); 802 return; 803 } else { 804 // Once we bind to the service, the first 805 // pending request will be processed. 806 mPendingInstalls.add(idx, params); 807 } 808 } else { 809 mPendingInstalls.add(idx, params); 810 // Already bound to the service. Just make 811 // sure we trigger off processing the first request. 812 if (idx == 0) { 813 mHandler.sendEmptyMessage(MCS_BOUND); 814 } 815 } 816 break; 817 } 818 case MCS_BOUND: { 819 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 820 if (msg.obj != null) { 821 mContainerService = (IMediaContainerService) msg.obj; 822 } 823 if (mContainerService == null) { 824 // Something seriously wrong. Bail out 825 Slog.e(TAG, "Cannot bind to media container service"); 826 for (HandlerParams params : mPendingInstalls) { 827 // Indicate service bind error 828 params.serviceError(); 829 } 830 mPendingInstalls.clear(); 831 } else if (mPendingInstalls.size() > 0) { 832 HandlerParams params = mPendingInstalls.get(0); 833 if (params != null) { 834 if (params.startCopy()) { 835 // We are done... look for more work or to 836 // go idle. 837 if (DEBUG_SD_INSTALL) Log.i(TAG, 838 "Checking for more work or unbind..."); 839 // Delete pending install 840 if (mPendingInstalls.size() > 0) { 841 mPendingInstalls.remove(0); 842 } 843 if (mPendingInstalls.size() == 0) { 844 if (mBound) { 845 if (DEBUG_SD_INSTALL) Log.i(TAG, 846 "Posting delayed MCS_UNBIND"); 847 removeMessages(MCS_UNBIND); 848 Message ubmsg = obtainMessage(MCS_UNBIND); 849 // Unbind after a little delay, to avoid 850 // continual thrashing. 851 sendMessageDelayed(ubmsg, 10000); 852 } 853 } else { 854 // There are more pending requests in queue. 855 // Just post MCS_BOUND message to trigger processing 856 // of next pending install. 857 if (DEBUG_SD_INSTALL) Log.i(TAG, 858 "Posting MCS_BOUND for next work"); 859 mHandler.sendEmptyMessage(MCS_BOUND); 860 } 861 } 862 } 863 } else { 864 // Should never happen ideally. 865 Slog.w(TAG, "Empty queue"); 866 } 867 break; 868 } 869 case MCS_RECONNECT: { 870 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 871 if (mPendingInstalls.size() > 0) { 872 if (mBound) { 873 disconnectService(); 874 } 875 if (!connectToService()) { 876 Slog.e(TAG, "Failed to bind to media container service"); 877 for (HandlerParams params : mPendingInstalls) { 878 // Indicate service bind error 879 params.serviceError(); 880 } 881 mPendingInstalls.clear(); 882 } 883 } 884 break; 885 } 886 case MCS_UNBIND: { 887 // If there is no actual work left, then time to unbind. 888 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 889 890 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 891 if (mBound) { 892 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 893 894 disconnectService(); 895 } 896 } else if (mPendingInstalls.size() > 0) { 897 // There are more pending requests in queue. 898 // Just post MCS_BOUND message to trigger processing 899 // of next pending install. 900 mHandler.sendEmptyMessage(MCS_BOUND); 901 } 902 903 break; 904 } 905 case MCS_GIVE_UP: { 906 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 907 mPendingInstalls.remove(0); 908 break; 909 } 910 case SEND_PENDING_BROADCAST: { 911 String packages[]; 912 ArrayList<String> components[]; 913 int size = 0; 914 int uids[]; 915 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 916 synchronized (mPackages) { 917 if (mPendingBroadcasts == null) { 918 return; 919 } 920 size = mPendingBroadcasts.size(); 921 if (size <= 0) { 922 // Nothing to be done. Just return 923 return; 924 } 925 packages = new String[size]; 926 components = new ArrayList[size]; 927 uids = new int[size]; 928 int i = 0; // filling out the above arrays 929 930 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 931 int packageUserId = mPendingBroadcasts.userIdAt(n); 932 Iterator<Map.Entry<String, ArrayList<String>>> it 933 = mPendingBroadcasts.packagesForUserId(packageUserId) 934 .entrySet().iterator(); 935 while (it.hasNext() && i < size) { 936 Map.Entry<String, ArrayList<String>> ent = it.next(); 937 packages[i] = ent.getKey(); 938 components[i] = ent.getValue(); 939 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 940 uids[i] = (ps != null) 941 ? UserHandle.getUid(packageUserId, ps.appId) 942 : -1; 943 i++; 944 } 945 } 946 size = i; 947 mPendingBroadcasts.clear(); 948 } 949 // Send broadcasts 950 for (int i = 0; i < size; i++) { 951 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 952 } 953 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 954 break; 955 } 956 case START_CLEANING_PACKAGE: { 957 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 958 final String packageName = (String)msg.obj; 959 final int userId = msg.arg1; 960 final boolean andCode = msg.arg2 != 0; 961 synchronized (mPackages) { 962 if (userId == UserHandle.USER_ALL) { 963 int[] users = sUserManager.getUserIds(); 964 for (int user : users) { 965 mSettings.addPackageToCleanLPw( 966 new PackageCleanItem(user, packageName, andCode)); 967 } 968 } else { 969 mSettings.addPackageToCleanLPw( 970 new PackageCleanItem(userId, packageName, andCode)); 971 } 972 } 973 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 974 startCleaningPackages(); 975 } break; 976 case POST_INSTALL: { 977 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 978 PostInstallData data = mRunningInstalls.get(msg.arg1); 979 mRunningInstalls.delete(msg.arg1); 980 boolean deleteOld = false; 981 982 if (data != null) { 983 InstallArgs args = data.args; 984 PackageInstalledInfo res = data.res; 985 986 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 987 res.removedInfo.sendBroadcast(false, true, false); 988 Bundle extras = new Bundle(1); 989 extras.putInt(Intent.EXTRA_UID, res.uid); 990 // Determine the set of users who are adding this 991 // package for the first time vs. those who are seeing 992 // an update. 993 int[] firstUsers; 994 int[] updateUsers = new int[0]; 995 if (res.origUsers == null || res.origUsers.length == 0) { 996 firstUsers = res.newUsers; 997 } else { 998 firstUsers = new int[0]; 999 for (int i=0; i<res.newUsers.length; i++) { 1000 int user = res.newUsers[i]; 1001 boolean isNew = true; 1002 for (int j=0; j<res.origUsers.length; j++) { 1003 if (res.origUsers[j] == user) { 1004 isNew = false; 1005 break; 1006 } 1007 } 1008 if (isNew) { 1009 int[] newFirst = new int[firstUsers.length+1]; 1010 System.arraycopy(firstUsers, 0, newFirst, 0, 1011 firstUsers.length); 1012 newFirst[firstUsers.length] = user; 1013 firstUsers = newFirst; 1014 } else { 1015 int[] newUpdate = new int[updateUsers.length+1]; 1016 System.arraycopy(updateUsers, 0, newUpdate, 0, 1017 updateUsers.length); 1018 newUpdate[updateUsers.length] = user; 1019 updateUsers = newUpdate; 1020 } 1021 } 1022 } 1023 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1024 res.pkg.applicationInfo.packageName, 1025 extras, null, null, firstUsers); 1026 final boolean update = res.removedInfo.removedPackage != null; 1027 if (update) { 1028 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1029 } 1030 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1031 res.pkg.applicationInfo.packageName, 1032 extras, null, null, updateUsers); 1033 if (update) { 1034 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1035 res.pkg.applicationInfo.packageName, 1036 extras, null, null, updateUsers); 1037 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1038 null, null, 1039 res.pkg.applicationInfo.packageName, null, updateUsers); 1040 1041 // treat asec-hosted packages like removable media on upgrade 1042 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1043 if (DEBUG_INSTALL) { 1044 Slog.i(TAG, "upgrading pkg " + res.pkg 1045 + " is ASEC-hosted -> AVAILABLE"); 1046 } 1047 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1048 ArrayList<String> pkgList = new ArrayList<String>(1); 1049 pkgList.add(res.pkg.applicationInfo.packageName); 1050 sendResourcesChangedBroadcast(true, true, 1051 pkgList,uidArray, null); 1052 } 1053 } 1054 if (res.removedInfo.args != null) { 1055 // Remove the replaced package's older resources safely now 1056 deleteOld = true; 1057 } 1058 1059 // Log current value of "unknown sources" setting 1060 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1061 getUnknownSourcesSettings()); 1062 } 1063 // Force a gc to clear up things 1064 Runtime.getRuntime().gc(); 1065 // We delete after a gc for applications on sdcard. 1066 if (deleteOld) { 1067 synchronized (mInstallLock) { 1068 res.removedInfo.args.doPostDeleteLI(true); 1069 } 1070 } 1071 if (args.observer != null) { 1072 try { 1073 args.observer.packageInstalled(res.name, res.returnCode); 1074 } catch (RemoteException e) { 1075 Slog.i(TAG, "Observer no longer exists."); 1076 } 1077 } 1078 if (args.observer2 != null) { 1079 try { 1080 Bundle extras = extrasForInstallResult(res); 1081 args.observer2.packageInstalled(res.name, extras, res.returnCode); 1082 } catch (RemoteException e) { 1083 Slog.i(TAG, "Observer no longer exists."); 1084 } 1085 } 1086 } else { 1087 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1088 } 1089 } break; 1090 case UPDATED_MEDIA_STATUS: { 1091 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1092 boolean reportStatus = msg.arg1 == 1; 1093 boolean doGc = msg.arg2 == 1; 1094 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1095 if (doGc) { 1096 // Force a gc to clear up stale containers. 1097 Runtime.getRuntime().gc(); 1098 } 1099 if (msg.obj != null) { 1100 @SuppressWarnings("unchecked") 1101 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1102 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1103 // Unload containers 1104 unloadAllContainers(args); 1105 } 1106 if (reportStatus) { 1107 try { 1108 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1109 PackageHelper.getMountService().finishMediaUpdate(); 1110 } catch (RemoteException e) { 1111 Log.e(TAG, "MountService not running?"); 1112 } 1113 } 1114 } break; 1115 case WRITE_SETTINGS: { 1116 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1117 synchronized (mPackages) { 1118 removeMessages(WRITE_SETTINGS); 1119 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1120 mSettings.writeLPr(); 1121 mDirtyUsers.clear(); 1122 } 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1124 } break; 1125 case WRITE_PACKAGE_RESTRICTIONS: { 1126 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1127 synchronized (mPackages) { 1128 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1129 for (int userId : mDirtyUsers) { 1130 mSettings.writePackageRestrictionsLPr(userId); 1131 } 1132 mDirtyUsers.clear(); 1133 } 1134 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1135 } break; 1136 case CHECK_PENDING_VERIFICATION: { 1137 final int verificationId = msg.arg1; 1138 final PackageVerificationState state = mPendingVerification.get(verificationId); 1139 1140 if ((state != null) && !state.timeoutExtended()) { 1141 final InstallArgs args = state.getInstallArgs(); 1142 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString()); 1143 mPendingVerification.remove(verificationId); 1144 1145 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1146 1147 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1148 Slog.i(TAG, "Continuing with installation of " 1149 + args.packageURI.toString()); 1150 state.setVerifierResponse(Binder.getCallingUid(), 1151 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1152 broadcastPackageVerified(verificationId, args.packageURI, 1153 PackageManager.VERIFICATION_ALLOW, 1154 state.getInstallArgs().getUser()); 1155 try { 1156 ret = args.copyApk(mContainerService, true); 1157 } catch (RemoteException e) { 1158 Slog.e(TAG, "Could not contact the ContainerService"); 1159 } 1160 } else { 1161 broadcastPackageVerified(verificationId, args.packageURI, 1162 PackageManager.VERIFICATION_REJECT, 1163 state.getInstallArgs().getUser()); 1164 } 1165 1166 processPendingInstall(args, ret); 1167 mHandler.sendEmptyMessage(MCS_UNBIND); 1168 } 1169 break; 1170 } 1171 case PACKAGE_VERIFIED: { 1172 final int verificationId = msg.arg1; 1173 1174 final PackageVerificationState state = mPendingVerification.get(verificationId); 1175 if (state == null) { 1176 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1177 break; 1178 } 1179 1180 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1181 1182 state.setVerifierResponse(response.callerUid, response.code); 1183 1184 if (state.isVerificationComplete()) { 1185 mPendingVerification.remove(verificationId); 1186 1187 final InstallArgs args = state.getInstallArgs(); 1188 1189 int ret; 1190 if (state.isInstallAllowed()) { 1191 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1192 broadcastPackageVerified(verificationId, args.packageURI, 1193 response.code, state.getInstallArgs().getUser()); 1194 try { 1195 ret = args.copyApk(mContainerService, true); 1196 } catch (RemoteException e) { 1197 Slog.e(TAG, "Could not contact the ContainerService"); 1198 } 1199 } else { 1200 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1201 } 1202 1203 processPendingInstall(args, ret); 1204 1205 mHandler.sendEmptyMessage(MCS_UNBIND); 1206 } 1207 1208 break; 1209 } 1210 } 1211 } 1212 } 1213 1214 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1215 Bundle extras = null; 1216 switch (res.returnCode) { 1217 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1218 extras = new Bundle(); 1219 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1220 res.origPermission); 1221 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1222 res.origPackage); 1223 break; 1224 } 1225 } 1226 return extras; 1227 } 1228 1229 void scheduleWriteSettingsLocked() { 1230 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1231 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1232 } 1233 } 1234 1235 void scheduleWritePackageRestrictionsLocked(int userId) { 1236 if (!sUserManager.exists(userId)) return; 1237 mDirtyUsers.add(userId); 1238 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1239 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1240 } 1241 } 1242 1243 public static final PackageManagerService main(Context context, Installer installer, 1244 boolean factoryTest, boolean onlyCore) { 1245 PackageManagerService m = new PackageManagerService(context, installer, 1246 factoryTest, onlyCore); 1247 ServiceManager.addService("package", m); 1248 return m; 1249 } 1250 1251 static String[] splitString(String str, char sep) { 1252 int count = 1; 1253 int i = 0; 1254 while ((i=str.indexOf(sep, i)) >= 0) { 1255 count++; 1256 i++; 1257 } 1258 1259 String[] res = new String[count]; 1260 i=0; 1261 count = 0; 1262 int lastI=0; 1263 while ((i=str.indexOf(sep, i)) >= 0) { 1264 res[count] = str.substring(lastI, i); 1265 count++; 1266 i++; 1267 lastI = i; 1268 } 1269 res[count] = str.substring(lastI, str.length()); 1270 return res; 1271 } 1272 1273 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1274 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1275 Context.DISPLAY_SERVICE); 1276 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1277 } 1278 1279 public PackageManagerService(Context context, Installer installer, 1280 boolean factoryTest, boolean onlyCore) { 1281 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1282 SystemClock.uptimeMillis()); 1283 1284 if (mSdkVersion <= 0) { 1285 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1286 } 1287 1288 mContext = context; 1289 mFactoryTest = factoryTest; 1290 mOnlyCore = onlyCore; 1291 mMetrics = new DisplayMetrics(); 1292 mSettings = new Settings(context); 1293 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1294 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1295 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1296 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1297 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1298 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1299 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1300 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1301 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1302 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1303 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1304 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1305 1306 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1307 if (separateProcesses != null && separateProcesses.length() > 0) { 1308 if ("*".equals(separateProcesses)) { 1309 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1310 mSeparateProcesses = null; 1311 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1312 } else { 1313 mDefParseFlags = 0; 1314 mSeparateProcesses = separateProcesses.split(","); 1315 Slog.w(TAG, "Running with debug.separate_processes: " 1316 + separateProcesses); 1317 } 1318 } else { 1319 mDefParseFlags = 0; 1320 mSeparateProcesses = null; 1321 } 1322 1323 mInstaller = installer; 1324 1325 getDefaultDisplayMetrics(context, mMetrics); 1326 1327 SystemConfig systemConfig = SystemConfig.getInstance(); 1328 mGlobalGids = systemConfig.getGlobalGids(); 1329 mSystemPermissions = systemConfig.getSystemPermissions(); 1330 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1331 1332 synchronized (mInstallLock) { 1333 // writer 1334 synchronized (mPackages) { 1335 mHandlerThread = new ServiceThread(TAG, 1336 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1337 mHandlerThread.start(); 1338 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1339 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1340 1341 File dataDir = Environment.getDataDirectory(); 1342 mAppDataDir = new File(dataDir, "data"); 1343 mAppInstallDir = new File(dataDir, "app"); 1344 mAppLibInstallDir = new File(dataDir, "app-lib"); 1345 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1346 mUserAppDataDir = new File(dataDir, "user"); 1347 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1348 mAppStagingDir = new File(dataDir, "app-staging"); 1349 1350 sUserManager = new UserManagerService(context, this, 1351 mInstallLock, mPackages); 1352 1353 // Propagate permission configuration in to package manager. 1354 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1355 = systemConfig.getPermissions(); 1356 for (int i=0; i<permConfig.size(); i++) { 1357 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1358 BasePermission bp = mSettings.mPermissions.get(perm.name); 1359 if (bp == null) { 1360 bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN); 1361 mSettings.mPermissions.put(perm.name, bp); 1362 } 1363 if (perm.gids != null) { 1364 bp.gids = appendInts(bp.gids, perm.gids); 1365 } 1366 } 1367 1368 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1369 for (int i=0; i<libConfig.size(); i++) { 1370 mSharedLibraries.put(libConfig.keyAt(i), 1371 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1372 } 1373 1374 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1375 1376 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1377 mSdkVersion, mOnlyCore); 1378 1379 String customResolverActivity = Resources.getSystem().getString( 1380 R.string.config_customResolverActivity); 1381 if (TextUtils.isEmpty(customResolverActivity)) { 1382 customResolverActivity = null; 1383 } else { 1384 mCustomResolverComponentName = ComponentName.unflattenFromString( 1385 customResolverActivity); 1386 } 1387 1388 long startTime = SystemClock.uptimeMillis(); 1389 1390 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1391 startTime); 1392 1393 // Set flag to monitor and not change apk file paths when 1394 // scanning install directories. 1395 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1396 1397 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1398 1399 /** 1400 * Add everything in the in the boot class path to the 1401 * list of process files because dexopt will have been run 1402 * if necessary during zygote startup. 1403 */ 1404 String bootClassPath = System.getProperty("java.boot.class.path"); 1405 if (bootClassPath != null) { 1406 String[] paths = splitString(bootClassPath, ':'); 1407 for (int i=0; i<paths.length; i++) { 1408 alreadyDexOpted.add(paths[i]); 1409 } 1410 } else { 1411 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1412 } 1413 1414 boolean didDexOptLibraryOrTool = false; 1415 1416 final List<String> instructionSets = getAllInstructionSets(); 1417 1418 /** 1419 * Ensure all external libraries have had dexopt run on them. 1420 */ 1421 if (mSharedLibraries.size() > 0) { 1422 // NOTE: For now, we're compiling these system "shared libraries" 1423 // (and framework jars) into all available architectures. It's possible 1424 // to compile them only when we come across an app that uses them (there's 1425 // already logic for that in scanPackageLI) but that adds some complexity. 1426 for (String instructionSet : instructionSets) { 1427 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1428 final String lib = libEntry.path; 1429 if (lib == null) { 1430 continue; 1431 } 1432 1433 try { 1434 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1435 alreadyDexOpted.add(lib); 1436 1437 // The list of "shared libraries" we have at this point is 1438 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1439 didDexOptLibraryOrTool = true; 1440 } 1441 } catch (FileNotFoundException e) { 1442 Slog.w(TAG, "Library not found: " + lib); 1443 } catch (IOException e) { 1444 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1445 + e.getMessage()); 1446 } 1447 } 1448 } 1449 } 1450 1451 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1452 1453 // Gross hack for now: we know this file doesn't contain any 1454 // code, so don't dexopt it to avoid the resulting log spew. 1455 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1456 1457 // Gross hack for now: we know this file is only part of 1458 // the boot class path for art, so don't dexopt it to 1459 // avoid the resulting log spew. 1460 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1461 1462 /** 1463 * And there are a number of commands implemented in Java, which 1464 * we currently need to do the dexopt on so that they can be 1465 * run from a non-root shell. 1466 */ 1467 String[] frameworkFiles = frameworkDir.list(); 1468 if (frameworkFiles != null) { 1469 // TODO: We could compile these only for the most preferred ABI. We should 1470 // first double check that the dex files for these commands are not referenced 1471 // by other system apps. 1472 for (String instructionSet : instructionSets) { 1473 for (int i=0; i<frameworkFiles.length; i++) { 1474 File libPath = new File(frameworkDir, frameworkFiles[i]); 1475 String path = libPath.getPath(); 1476 // Skip the file if we already did it. 1477 if (alreadyDexOpted.contains(path)) { 1478 continue; 1479 } 1480 // Skip the file if it is not a type we want to dexopt. 1481 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1482 continue; 1483 } 1484 try { 1485 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1486 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1487 didDexOptLibraryOrTool = true; 1488 } 1489 } catch (FileNotFoundException e) { 1490 Slog.w(TAG, "Jar not found: " + path); 1491 } catch (IOException e) { 1492 Slog.w(TAG, "Exception reading jar: " + path, e); 1493 } 1494 } 1495 } 1496 } 1497 1498 if (didDexOptLibraryOrTool) { 1499 // If we dexopted a library or tool, then something on the system has 1500 // changed. Consider this significant, and wipe away all other 1501 // existing dexopt files to ensure we don't leave any dangling around. 1502 // 1503 // TODO: This should be revisited because it isn't as good an indicator 1504 // as it used to be. It used to include the boot classpath but at some point 1505 // DexFile.isDexOptNeeded started returning false for the boot 1506 // class path files in all cases. It is very possible in a 1507 // small maintenance release update that the library and tool 1508 // jars may be unchanged but APK could be removed resulting in 1509 // unused dalvik-cache files. 1510 for (String instructionSet : instructionSets) { 1511 mInstaller.pruneDexCache(instructionSet); 1512 } 1513 1514 // Additionally, delete all dex files from the root directory 1515 // since there shouldn't be any there anyway, unless we're upgrading 1516 // from an older OS version or a build that contained the "old" style 1517 // flat scheme. 1518 mInstaller.pruneDexCache("."); 1519 } 1520 1521 // Collect vendor overlay packages. 1522 // (Do this before scanning any apps.) 1523 // For security and version matching reason, only consider 1524 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1525 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1526 mVendorOverlayInstallObserver = new AppDirObserver( 1527 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1528 mVendorOverlayInstallObserver.startWatching(); 1529 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1530 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1531 1532 // Find base frameworks (resource packages without code). 1533 mFrameworkInstallObserver = new AppDirObserver( 1534 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1535 mFrameworkInstallObserver.startWatching(); 1536 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1537 | PackageParser.PARSE_IS_SYSTEM_DIR 1538 | PackageParser.PARSE_IS_PRIVILEGED, 1539 scanMode | SCAN_NO_DEX, 0); 1540 1541 // Collected privileged system packages. 1542 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1543 mPrivilegedInstallObserver = new AppDirObserver( 1544 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1545 mPrivilegedInstallObserver.startWatching(); 1546 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1547 | PackageParser.PARSE_IS_SYSTEM_DIR 1548 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1549 1550 // Collect ordinary system packages. 1551 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1552 mSystemInstallObserver = new AppDirObserver( 1553 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1554 mSystemInstallObserver.startWatching(); 1555 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1556 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1557 1558 // Collect all vendor packages. 1559 File vendorAppDir = new File("/vendor/app"); 1560 try { 1561 vendorAppDir = vendorAppDir.getCanonicalFile(); 1562 } catch (IOException e) { 1563 // failed to look up canonical path, continue with original one 1564 } 1565 mVendorInstallObserver = new AppDirObserver( 1566 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1567 mVendorInstallObserver.startWatching(); 1568 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1569 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1570 1571 // Collect all OEM packages. 1572 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1573 mOemInstallObserver = new AppDirObserver( 1574 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1575 mOemInstallObserver.startWatching(); 1576 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1577 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1578 1579 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1580 mInstaller.moveFiles(); 1581 1582 // Prune any system packages that no longer exist. 1583 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1584 if (!mOnlyCore) { 1585 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1586 while (psit.hasNext()) { 1587 PackageSetting ps = psit.next(); 1588 1589 /* 1590 * If this is not a system app, it can't be a 1591 * disable system app. 1592 */ 1593 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1594 continue; 1595 } 1596 1597 /* 1598 * If the package is scanned, it's not erased. 1599 */ 1600 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1601 if (scannedPkg != null) { 1602 /* 1603 * If the system app is both scanned and in the 1604 * disabled packages list, then it must have been 1605 * added via OTA. Remove it from the currently 1606 * scanned package so the previously user-installed 1607 * application can be scanned. 1608 */ 1609 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1610 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1611 + "; removing system app"); 1612 removePackageLI(ps, true); 1613 } 1614 1615 continue; 1616 } 1617 1618 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1619 psit.remove(); 1620 String msg = "System package " + ps.name 1621 + " no longer exists; wiping its data"; 1622 reportSettingsProblem(Log.WARN, msg); 1623 removeDataDirsLI(ps.name); 1624 } else { 1625 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1626 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1627 possiblyDeletedUpdatedSystemApps.add(ps.name); 1628 } 1629 } 1630 } 1631 } 1632 1633 //look for any incomplete package installations 1634 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1635 //clean up list 1636 for(int i = 0; i < deletePkgsList.size(); i++) { 1637 //clean up here 1638 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1639 } 1640 //delete tmp files 1641 deleteTempPackageFiles(); 1642 1643 // Remove any shared userIDs that have no associated packages 1644 mSettings.pruneSharedUsersLPw(); 1645 1646 if (!mOnlyCore) { 1647 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1648 SystemClock.uptimeMillis()); 1649 mAppInstallObserver = new AppDirObserver( 1650 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1651 mAppInstallObserver.startWatching(); 1652 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1653 1654 mDrmAppInstallObserver = new AppDirObserver( 1655 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1656 mDrmAppInstallObserver.startWatching(); 1657 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1658 scanMode, 0); 1659 1660 /** 1661 * Remove disable package settings for any updated system 1662 * apps that were removed via an OTA. If they're not a 1663 * previously-updated app, remove them completely. 1664 * Otherwise, just revoke their system-level permissions. 1665 */ 1666 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1667 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1668 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1669 1670 String msg; 1671 if (deletedPkg == null) { 1672 msg = "Updated system package " + deletedAppName 1673 + " no longer exists; wiping its data"; 1674 removeDataDirsLI(deletedAppName); 1675 } else { 1676 msg = "Updated system app + " + deletedAppName 1677 + " no longer present; removing system privileges for " 1678 + deletedAppName; 1679 1680 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1681 1682 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1683 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1684 } 1685 reportSettingsProblem(Log.WARN, msg); 1686 } 1687 } else { 1688 mAppInstallObserver = null; 1689 mDrmAppInstallObserver = null; 1690 } 1691 1692 // Now that we know all of the shared libraries, update all clients to have 1693 // the correct library paths. 1694 updateAllSharedLibrariesLPw(); 1695 1696 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1697 // NOTE: We ignore potential failures here during a system scan (like 1698 // the rest of the commands above) because there's precious little we 1699 // can do about it. A settings error is reported, though. 1700 adjustCpuAbisForSharedUserLPw(setting.packages, null, 1701 false /* force dexopt */, false /* defer dexopt */); 1702 } 1703 1704 // Now that we know all the packages we are keeping, 1705 // read and update their last usage times. 1706 mPackageUsage.readLP(); 1707 1708 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1709 SystemClock.uptimeMillis()); 1710 Slog.i(TAG, "Time to scan packages: " 1711 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1712 + " seconds"); 1713 1714 // If the platform SDK has changed since the last time we booted, 1715 // we need to re-grant app permission to catch any new ones that 1716 // appear. This is really a hack, and means that apps can in some 1717 // cases get permissions that the user didn't initially explicitly 1718 // allow... it would be nice to have some better way to handle 1719 // this situation. 1720 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1721 != mSdkVersion; 1722 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1723 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1724 + "; regranting permissions for internal storage"); 1725 mSettings.mInternalSdkPlatform = mSdkVersion; 1726 1727 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1728 | (regrantPermissions 1729 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1730 : 0)); 1731 1732 // If this is the first boot, and it is a normal boot, then 1733 // we need to initialize the default preferred apps. 1734 if (!mRestoredSettings && !onlyCore) { 1735 mSettings.readDefaultPreferredAppsLPw(this, 0); 1736 } 1737 1738 // All the changes are done during package scanning. 1739 mSettings.updateInternalDatabaseVersion(); 1740 1741 // can downgrade to reader 1742 mSettings.writeLPr(); 1743 1744 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1745 SystemClock.uptimeMillis()); 1746 1747 1748 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1749 } // synchronized (mPackages) 1750 } // synchronized (mInstallLock) 1751 1752 mInstallerService = new PackageInstallerService(context, this, mAppStagingDir); 1753 1754 // Now after opening every single application zip, make sure they 1755 // are all flushed. Not really needed, but keeps things nice and 1756 // tidy. 1757 Runtime.getRuntime().gc(); 1758 } 1759 1760 @Override 1761 public boolean isFirstBoot() { 1762 return !mRestoredSettings; 1763 } 1764 1765 @Override 1766 public boolean isOnlyCoreApps() { 1767 return mOnlyCore; 1768 } 1769 1770 private String getRequiredVerifierLPr() { 1771 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1772 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1773 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1774 1775 String requiredVerifier = null; 1776 1777 final int N = receivers.size(); 1778 for (int i = 0; i < N; i++) { 1779 final ResolveInfo info = receivers.get(i); 1780 1781 if (info.activityInfo == null) { 1782 continue; 1783 } 1784 1785 final String packageName = info.activityInfo.packageName; 1786 1787 final PackageSetting ps = mSettings.mPackages.get(packageName); 1788 if (ps == null) { 1789 continue; 1790 } 1791 1792 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1793 if (!gp.grantedPermissions 1794 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1795 continue; 1796 } 1797 1798 if (requiredVerifier != null) { 1799 throw new RuntimeException("There can be only one required verifier"); 1800 } 1801 1802 requiredVerifier = packageName; 1803 } 1804 1805 return requiredVerifier; 1806 } 1807 1808 @Override 1809 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1810 throws RemoteException { 1811 try { 1812 return super.onTransact(code, data, reply, flags); 1813 } catch (RuntimeException e) { 1814 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1815 Slog.wtf(TAG, "Package Manager Crash", e); 1816 } 1817 throw e; 1818 } 1819 } 1820 1821 void cleanupInstallFailedPackage(PackageSetting ps) { 1822 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1823 removeDataDirsLI(ps.name); 1824 if (ps.codePath != null) { 1825 if (!ps.codePath.delete()) { 1826 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1827 } 1828 } 1829 if (ps.resourcePath != null) { 1830 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1831 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1832 } 1833 } 1834 mSettings.removePackageLPw(ps.name); 1835 } 1836 1837 static int[] appendInts(int[] cur, int[] add) { 1838 if (add == null) return cur; 1839 if (cur == null) return add; 1840 final int N = add.length; 1841 for (int i=0; i<N; i++) { 1842 cur = appendInt(cur, add[i]); 1843 } 1844 return cur; 1845 } 1846 1847 static int[] removeInts(int[] cur, int[] rem) { 1848 if (rem == null) return cur; 1849 if (cur == null) return cur; 1850 final int N = rem.length; 1851 for (int i=0; i<N; i++) { 1852 cur = removeInt(cur, rem[i]); 1853 } 1854 return cur; 1855 } 1856 1857 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1858 if (!sUserManager.exists(userId)) return null; 1859 final PackageSetting ps = (PackageSetting) p.mExtras; 1860 if (ps == null) { 1861 return null; 1862 } 1863 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1864 final PackageUserState state = ps.readUserState(userId); 1865 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1866 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1867 state, userId); 1868 } 1869 1870 @Override 1871 public boolean isPackageAvailable(String packageName, int userId) { 1872 if (!sUserManager.exists(userId)) return false; 1873 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1874 synchronized (mPackages) { 1875 PackageParser.Package p = mPackages.get(packageName); 1876 if (p != null) { 1877 final PackageSetting ps = (PackageSetting) p.mExtras; 1878 if (ps != null) { 1879 final PackageUserState state = ps.readUserState(userId); 1880 if (state != null) { 1881 return PackageParser.isAvailable(state); 1882 } 1883 } 1884 } 1885 } 1886 return false; 1887 } 1888 1889 @Override 1890 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1891 if (!sUserManager.exists(userId)) return null; 1892 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1893 // reader 1894 synchronized (mPackages) { 1895 PackageParser.Package p = mPackages.get(packageName); 1896 if (DEBUG_PACKAGE_INFO) 1897 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1898 if (p != null) { 1899 return generatePackageInfo(p, flags, userId); 1900 } 1901 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1902 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1903 } 1904 } 1905 return null; 1906 } 1907 1908 @Override 1909 public String[] currentToCanonicalPackageNames(String[] names) { 1910 String[] out = new String[names.length]; 1911 // reader 1912 synchronized (mPackages) { 1913 for (int i=names.length-1; i>=0; i--) { 1914 PackageSetting ps = mSettings.mPackages.get(names[i]); 1915 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1916 } 1917 } 1918 return out; 1919 } 1920 1921 @Override 1922 public String[] canonicalToCurrentPackageNames(String[] names) { 1923 String[] out = new String[names.length]; 1924 // reader 1925 synchronized (mPackages) { 1926 for (int i=names.length-1; i>=0; i--) { 1927 String cur = mSettings.mRenamedPackages.get(names[i]); 1928 out[i] = cur != null ? cur : names[i]; 1929 } 1930 } 1931 return out; 1932 } 1933 1934 @Override 1935 public int getPackageUid(String packageName, int userId) { 1936 if (!sUserManager.exists(userId)) return -1; 1937 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1938 // reader 1939 synchronized (mPackages) { 1940 PackageParser.Package p = mPackages.get(packageName); 1941 if(p != null) { 1942 return UserHandle.getUid(userId, p.applicationInfo.uid); 1943 } 1944 PackageSetting ps = mSettings.mPackages.get(packageName); 1945 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1946 return -1; 1947 } 1948 p = ps.pkg; 1949 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1950 } 1951 } 1952 1953 @Override 1954 public int[] getPackageGids(String packageName) { 1955 // reader 1956 synchronized (mPackages) { 1957 PackageParser.Package p = mPackages.get(packageName); 1958 if (DEBUG_PACKAGE_INFO) 1959 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1960 if (p != null) { 1961 final PackageSetting ps = (PackageSetting)p.mExtras; 1962 return ps.getGids(); 1963 } 1964 } 1965 // stupid thing to indicate an error. 1966 return new int[0]; 1967 } 1968 1969 static final PermissionInfo generatePermissionInfo( 1970 BasePermission bp, int flags) { 1971 if (bp.perm != null) { 1972 return PackageParser.generatePermissionInfo(bp.perm, flags); 1973 } 1974 PermissionInfo pi = new PermissionInfo(); 1975 pi.name = bp.name; 1976 pi.packageName = bp.sourcePackage; 1977 pi.nonLocalizedLabel = bp.name; 1978 pi.protectionLevel = bp.protectionLevel; 1979 return pi; 1980 } 1981 1982 @Override 1983 public PermissionInfo getPermissionInfo(String name, int flags) { 1984 // reader 1985 synchronized (mPackages) { 1986 final BasePermission p = mSettings.mPermissions.get(name); 1987 if (p != null) { 1988 return generatePermissionInfo(p, flags); 1989 } 1990 return null; 1991 } 1992 } 1993 1994 @Override 1995 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1996 // reader 1997 synchronized (mPackages) { 1998 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1999 for (BasePermission p : mSettings.mPermissions.values()) { 2000 if (group == null) { 2001 if (p.perm == null || p.perm.info.group == null) { 2002 out.add(generatePermissionInfo(p, flags)); 2003 } 2004 } else { 2005 if (p.perm != null && group.equals(p.perm.info.group)) { 2006 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2007 } 2008 } 2009 } 2010 2011 if (out.size() > 0) { 2012 return out; 2013 } 2014 return mPermissionGroups.containsKey(group) ? out : null; 2015 } 2016 } 2017 2018 @Override 2019 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2020 // reader 2021 synchronized (mPackages) { 2022 return PackageParser.generatePermissionGroupInfo( 2023 mPermissionGroups.get(name), flags); 2024 } 2025 } 2026 2027 @Override 2028 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2029 // reader 2030 synchronized (mPackages) { 2031 final int N = mPermissionGroups.size(); 2032 ArrayList<PermissionGroupInfo> out 2033 = new ArrayList<PermissionGroupInfo>(N); 2034 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2035 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2036 } 2037 return out; 2038 } 2039 } 2040 2041 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2042 int userId) { 2043 if (!sUserManager.exists(userId)) return null; 2044 PackageSetting ps = mSettings.mPackages.get(packageName); 2045 if (ps != null) { 2046 if (ps.pkg == null) { 2047 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2048 flags, userId); 2049 if (pInfo != null) { 2050 return pInfo.applicationInfo; 2051 } 2052 return null; 2053 } 2054 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2055 ps.readUserState(userId), userId); 2056 } 2057 return null; 2058 } 2059 2060 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2061 int userId) { 2062 if (!sUserManager.exists(userId)) return null; 2063 PackageSetting ps = mSettings.mPackages.get(packageName); 2064 if (ps != null) { 2065 PackageParser.Package pkg = ps.pkg; 2066 if (pkg == null) { 2067 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2068 return null; 2069 } 2070 // App code is gone, so we aren't worried about split paths 2071 pkg = new PackageParser.Package(packageName); 2072 pkg.applicationInfo.packageName = packageName; 2073 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2074 pkg.applicationInfo.sourceDir = ps.codePathString; 2075 pkg.applicationInfo.publicSourceDir = ps.resourcePathString; 2076 pkg.applicationInfo.dataDir = 2077 getDataPathForPackage(packageName, 0).getPath(); 2078 pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString; 2079 pkg.applicationInfo.cpuAbi = ps.cpuAbiString; 2080 } 2081 return generatePackageInfo(pkg, flags, userId); 2082 } 2083 return null; 2084 } 2085 2086 @Override 2087 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2088 if (!sUserManager.exists(userId)) return null; 2089 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2090 // writer 2091 synchronized (mPackages) { 2092 PackageParser.Package p = mPackages.get(packageName); 2093 if (DEBUG_PACKAGE_INFO) Log.v( 2094 TAG, "getApplicationInfo " + packageName 2095 + ": " + p); 2096 if (p != null) { 2097 PackageSetting ps = mSettings.mPackages.get(packageName); 2098 if (ps == null) return null; 2099 // Note: isEnabledLP() does not apply here - always return info 2100 return PackageParser.generateApplicationInfo( 2101 p, flags, ps.readUserState(userId), userId); 2102 } 2103 if ("android".equals(packageName)||"system".equals(packageName)) { 2104 return mAndroidApplication; 2105 } 2106 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2107 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2108 } 2109 } 2110 return null; 2111 } 2112 2113 2114 @Override 2115 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2116 mContext.enforceCallingOrSelfPermission( 2117 android.Manifest.permission.CLEAR_APP_CACHE, null); 2118 // Queue up an async operation since clearing cache may take a little while. 2119 mHandler.post(new Runnable() { 2120 public void run() { 2121 mHandler.removeCallbacks(this); 2122 int retCode = -1; 2123 synchronized (mInstallLock) { 2124 retCode = mInstaller.freeCache(freeStorageSize); 2125 if (retCode < 0) { 2126 Slog.w(TAG, "Couldn't clear application caches"); 2127 } 2128 } 2129 if (observer != null) { 2130 try { 2131 observer.onRemoveCompleted(null, (retCode >= 0)); 2132 } catch (RemoteException e) { 2133 Slog.w(TAG, "RemoveException when invoking call back"); 2134 } 2135 } 2136 } 2137 }); 2138 } 2139 2140 @Override 2141 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2142 mContext.enforceCallingOrSelfPermission( 2143 android.Manifest.permission.CLEAR_APP_CACHE, null); 2144 // Queue up an async operation since clearing cache may take a little while. 2145 mHandler.post(new Runnable() { 2146 public void run() { 2147 mHandler.removeCallbacks(this); 2148 int retCode = -1; 2149 synchronized (mInstallLock) { 2150 retCode = mInstaller.freeCache(freeStorageSize); 2151 if (retCode < 0) { 2152 Slog.w(TAG, "Couldn't clear application caches"); 2153 } 2154 } 2155 if(pi != null) { 2156 try { 2157 // Callback via pending intent 2158 int code = (retCode >= 0) ? 1 : 0; 2159 pi.sendIntent(null, code, null, 2160 null, null); 2161 } catch (SendIntentException e1) { 2162 Slog.i(TAG, "Failed to send pending intent"); 2163 } 2164 } 2165 } 2166 }); 2167 } 2168 2169 void freeStorage(long freeStorageSize) throws IOException { 2170 synchronized (mInstallLock) { 2171 if (mInstaller.freeCache(freeStorageSize) < 0) { 2172 throw new IOException("Failed to free enough space"); 2173 } 2174 } 2175 } 2176 2177 @Override 2178 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2179 if (!sUserManager.exists(userId)) return null; 2180 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2181 synchronized (mPackages) { 2182 PackageParser.Activity a = mActivities.mActivities.get(component); 2183 2184 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2185 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2186 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2187 if (ps == null) return null; 2188 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2189 userId); 2190 } 2191 if (mResolveComponentName.equals(component)) { 2192 return mResolveActivity; 2193 } 2194 } 2195 return null; 2196 } 2197 2198 @Override 2199 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2200 String resolvedType) { 2201 synchronized (mPackages) { 2202 PackageParser.Activity a = mActivities.mActivities.get(component); 2203 if (a == null) { 2204 return false; 2205 } 2206 for (int i=0; i<a.intents.size(); i++) { 2207 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2208 intent.getData(), intent.getCategories(), TAG) >= 0) { 2209 return true; 2210 } 2211 } 2212 return false; 2213 } 2214 } 2215 2216 @Override 2217 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2218 if (!sUserManager.exists(userId)) return null; 2219 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2220 synchronized (mPackages) { 2221 PackageParser.Activity a = mReceivers.mActivities.get(component); 2222 if (DEBUG_PACKAGE_INFO) Log.v( 2223 TAG, "getReceiverInfo " + component + ": " + a); 2224 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2225 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2226 if (ps == null) return null; 2227 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2228 userId); 2229 } 2230 } 2231 return null; 2232 } 2233 2234 @Override 2235 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2236 if (!sUserManager.exists(userId)) return null; 2237 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2238 synchronized (mPackages) { 2239 PackageParser.Service s = mServices.mServices.get(component); 2240 if (DEBUG_PACKAGE_INFO) Log.v( 2241 TAG, "getServiceInfo " + component + ": " + s); 2242 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2243 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2244 if (ps == null) return null; 2245 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2246 userId); 2247 } 2248 } 2249 return null; 2250 } 2251 2252 @Override 2253 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2254 if (!sUserManager.exists(userId)) return null; 2255 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2256 synchronized (mPackages) { 2257 PackageParser.Provider p = mProviders.mProviders.get(component); 2258 if (DEBUG_PACKAGE_INFO) Log.v( 2259 TAG, "getProviderInfo " + component + ": " + p); 2260 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2261 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2262 if (ps == null) return null; 2263 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2264 userId); 2265 } 2266 } 2267 return null; 2268 } 2269 2270 @Override 2271 public String[] getSystemSharedLibraryNames() { 2272 Set<String> libSet; 2273 synchronized (mPackages) { 2274 libSet = mSharedLibraries.keySet(); 2275 int size = libSet.size(); 2276 if (size > 0) { 2277 String[] libs = new String[size]; 2278 libSet.toArray(libs); 2279 return libs; 2280 } 2281 } 2282 return null; 2283 } 2284 2285 @Override 2286 public FeatureInfo[] getSystemAvailableFeatures() { 2287 Collection<FeatureInfo> featSet; 2288 synchronized (mPackages) { 2289 featSet = mAvailableFeatures.values(); 2290 int size = featSet.size(); 2291 if (size > 0) { 2292 FeatureInfo[] features = new FeatureInfo[size+1]; 2293 featSet.toArray(features); 2294 FeatureInfo fi = new FeatureInfo(); 2295 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2296 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2297 features[size] = fi; 2298 return features; 2299 } 2300 } 2301 return null; 2302 } 2303 2304 @Override 2305 public boolean hasSystemFeature(String name) { 2306 synchronized (mPackages) { 2307 return mAvailableFeatures.containsKey(name); 2308 } 2309 } 2310 2311 private void checkValidCaller(int uid, int userId) { 2312 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2313 return; 2314 2315 throw new SecurityException("Caller uid=" + uid 2316 + " is not privileged to communicate with user=" + userId); 2317 } 2318 2319 @Override 2320 public int checkPermission(String permName, String pkgName) { 2321 synchronized (mPackages) { 2322 PackageParser.Package p = mPackages.get(pkgName); 2323 if (p != null && p.mExtras != null) { 2324 PackageSetting ps = (PackageSetting)p.mExtras; 2325 if (ps.sharedUser != null) { 2326 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2327 return PackageManager.PERMISSION_GRANTED; 2328 } 2329 } else if (ps.grantedPermissions.contains(permName)) { 2330 return PackageManager.PERMISSION_GRANTED; 2331 } 2332 } 2333 } 2334 return PackageManager.PERMISSION_DENIED; 2335 } 2336 2337 @Override 2338 public int checkUidPermission(String permName, int uid) { 2339 synchronized (mPackages) { 2340 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2341 if (obj != null) { 2342 GrantedPermissions gp = (GrantedPermissions)obj; 2343 if (gp.grantedPermissions.contains(permName)) { 2344 return PackageManager.PERMISSION_GRANTED; 2345 } 2346 } else { 2347 HashSet<String> perms = mSystemPermissions.get(uid); 2348 if (perms != null && perms.contains(permName)) { 2349 return PackageManager.PERMISSION_GRANTED; 2350 } 2351 } 2352 } 2353 return PackageManager.PERMISSION_DENIED; 2354 } 2355 2356 /** 2357 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2358 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2359 * @param message the message to log on security exception 2360 */ 2361 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2362 String message) { 2363 if (userId < 0) { 2364 throw new IllegalArgumentException("Invalid userId " + userId); 2365 } 2366 if (userId == UserHandle.getUserId(callingUid)) return; 2367 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2368 if (requireFullPermission) { 2369 mContext.enforceCallingOrSelfPermission( 2370 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2371 } else { 2372 try { 2373 mContext.enforceCallingOrSelfPermission( 2374 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2375 } catch (SecurityException se) { 2376 mContext.enforceCallingOrSelfPermission( 2377 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2378 } 2379 } 2380 } 2381 } 2382 2383 private BasePermission findPermissionTreeLP(String permName) { 2384 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2385 if (permName.startsWith(bp.name) && 2386 permName.length() > bp.name.length() && 2387 permName.charAt(bp.name.length()) == '.') { 2388 return bp; 2389 } 2390 } 2391 return null; 2392 } 2393 2394 private BasePermission checkPermissionTreeLP(String permName) { 2395 if (permName != null) { 2396 BasePermission bp = findPermissionTreeLP(permName); 2397 if (bp != null) { 2398 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2399 return bp; 2400 } 2401 throw new SecurityException("Calling uid " 2402 + Binder.getCallingUid() 2403 + " is not allowed to add to permission tree " 2404 + bp.name + " owned by uid " + bp.uid); 2405 } 2406 } 2407 throw new SecurityException("No permission tree found for " + permName); 2408 } 2409 2410 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2411 if (s1 == null) { 2412 return s2 == null; 2413 } 2414 if (s2 == null) { 2415 return false; 2416 } 2417 if (s1.getClass() != s2.getClass()) { 2418 return false; 2419 } 2420 return s1.equals(s2); 2421 } 2422 2423 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2424 if (pi1.icon != pi2.icon) return false; 2425 if (pi1.logo != pi2.logo) return false; 2426 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2427 if (!compareStrings(pi1.name, pi2.name)) return false; 2428 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2429 // We'll take care of setting this one. 2430 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2431 // These are not currently stored in settings. 2432 //if (!compareStrings(pi1.group, pi2.group)) return false; 2433 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2434 //if (pi1.labelRes != pi2.labelRes) return false; 2435 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2436 return true; 2437 } 2438 2439 int permissionInfoFootprint(PermissionInfo info) { 2440 int size = info.name.length(); 2441 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2442 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2443 return size; 2444 } 2445 2446 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2447 int size = 0; 2448 for (BasePermission perm : mSettings.mPermissions.values()) { 2449 if (perm.uid == tree.uid) { 2450 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2451 } 2452 } 2453 return size; 2454 } 2455 2456 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2457 // We calculate the max size of permissions defined by this uid and throw 2458 // if that plus the size of 'info' would exceed our stated maximum. 2459 if (tree.uid != Process.SYSTEM_UID) { 2460 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2461 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2462 throw new SecurityException("Permission tree size cap exceeded"); 2463 } 2464 } 2465 } 2466 2467 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2468 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2469 throw new SecurityException("Label must be specified in permission"); 2470 } 2471 BasePermission tree = checkPermissionTreeLP(info.name); 2472 BasePermission bp = mSettings.mPermissions.get(info.name); 2473 boolean added = bp == null; 2474 boolean changed = true; 2475 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2476 if (added) { 2477 enforcePermissionCapLocked(info, tree); 2478 bp = new BasePermission(info.name, tree.sourcePackage, 2479 BasePermission.TYPE_DYNAMIC); 2480 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2481 throw new SecurityException( 2482 "Not allowed to modify non-dynamic permission " 2483 + info.name); 2484 } else { 2485 if (bp.protectionLevel == fixedLevel 2486 && bp.perm.owner.equals(tree.perm.owner) 2487 && bp.uid == tree.uid 2488 && comparePermissionInfos(bp.perm.info, info)) { 2489 changed = false; 2490 } 2491 } 2492 bp.protectionLevel = fixedLevel; 2493 info = new PermissionInfo(info); 2494 info.protectionLevel = fixedLevel; 2495 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2496 bp.perm.info.packageName = tree.perm.info.packageName; 2497 bp.uid = tree.uid; 2498 if (added) { 2499 mSettings.mPermissions.put(info.name, bp); 2500 } 2501 if (changed) { 2502 if (!async) { 2503 mSettings.writeLPr(); 2504 } else { 2505 scheduleWriteSettingsLocked(); 2506 } 2507 } 2508 return added; 2509 } 2510 2511 @Override 2512 public boolean addPermission(PermissionInfo info) { 2513 synchronized (mPackages) { 2514 return addPermissionLocked(info, false); 2515 } 2516 } 2517 2518 @Override 2519 public boolean addPermissionAsync(PermissionInfo info) { 2520 synchronized (mPackages) { 2521 return addPermissionLocked(info, true); 2522 } 2523 } 2524 2525 @Override 2526 public void removePermission(String name) { 2527 synchronized (mPackages) { 2528 checkPermissionTreeLP(name); 2529 BasePermission bp = mSettings.mPermissions.get(name); 2530 if (bp != null) { 2531 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2532 throw new SecurityException( 2533 "Not allowed to modify non-dynamic permission " 2534 + name); 2535 } 2536 mSettings.mPermissions.remove(name); 2537 mSettings.writeLPr(); 2538 } 2539 } 2540 } 2541 2542 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2543 int index = pkg.requestedPermissions.indexOf(bp.name); 2544 if (index == -1) { 2545 throw new SecurityException("Package " + pkg.packageName 2546 + " has not requested permission " + bp.name); 2547 } 2548 boolean isNormal = 2549 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2550 == PermissionInfo.PROTECTION_NORMAL); 2551 boolean isDangerous = 2552 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2553 == PermissionInfo.PROTECTION_DANGEROUS); 2554 boolean isDevelopment = 2555 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2556 2557 if (!isNormal && !isDangerous && !isDevelopment) { 2558 throw new SecurityException("Permission " + bp.name 2559 + " is not a changeable permission type"); 2560 } 2561 2562 if (isNormal || isDangerous) { 2563 if (pkg.requestedPermissionsRequired.get(index)) { 2564 throw new SecurityException("Can't change " + bp.name 2565 + ". It is required by the application"); 2566 } 2567 } 2568 } 2569 2570 @Override 2571 public void grantPermission(String packageName, String permissionName) { 2572 mContext.enforceCallingOrSelfPermission( 2573 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2574 synchronized (mPackages) { 2575 final PackageParser.Package pkg = mPackages.get(packageName); 2576 if (pkg == null) { 2577 throw new IllegalArgumentException("Unknown package: " + packageName); 2578 } 2579 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2580 if (bp == null) { 2581 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2582 } 2583 2584 checkGrantRevokePermissions(pkg, bp); 2585 2586 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2587 if (ps == null) { 2588 return; 2589 } 2590 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2591 if (gp.grantedPermissions.add(permissionName)) { 2592 if (ps.haveGids) { 2593 gp.gids = appendInts(gp.gids, bp.gids); 2594 } 2595 mSettings.writeLPr(); 2596 } 2597 } 2598 } 2599 2600 @Override 2601 public void revokePermission(String packageName, String permissionName) { 2602 int changedAppId = -1; 2603 2604 synchronized (mPackages) { 2605 final PackageParser.Package pkg = mPackages.get(packageName); 2606 if (pkg == null) { 2607 throw new IllegalArgumentException("Unknown package: " + packageName); 2608 } 2609 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2610 mContext.enforceCallingOrSelfPermission( 2611 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2612 } 2613 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2614 if (bp == null) { 2615 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2616 } 2617 2618 checkGrantRevokePermissions(pkg, bp); 2619 2620 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2621 if (ps == null) { 2622 return; 2623 } 2624 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2625 if (gp.grantedPermissions.remove(permissionName)) { 2626 gp.grantedPermissions.remove(permissionName); 2627 if (ps.haveGids) { 2628 gp.gids = removeInts(gp.gids, bp.gids); 2629 } 2630 mSettings.writeLPr(); 2631 changedAppId = ps.appId; 2632 } 2633 } 2634 2635 if (changedAppId >= 0) { 2636 // We changed the perm on someone, kill its processes. 2637 IActivityManager am = ActivityManagerNative.getDefault(); 2638 if (am != null) { 2639 final int callingUserId = UserHandle.getCallingUserId(); 2640 final long ident = Binder.clearCallingIdentity(); 2641 try { 2642 //XXX we should only revoke for the calling user's app permissions, 2643 // but for now we impact all users. 2644 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2645 // "revoke " + permissionName); 2646 int[] users = sUserManager.getUserIds(); 2647 for (int user : users) { 2648 am.killUid(UserHandle.getUid(user, changedAppId), 2649 "revoke " + permissionName); 2650 } 2651 } catch (RemoteException e) { 2652 } finally { 2653 Binder.restoreCallingIdentity(ident); 2654 } 2655 } 2656 } 2657 } 2658 2659 @Override 2660 public boolean isProtectedBroadcast(String actionName) { 2661 synchronized (mPackages) { 2662 return mProtectedBroadcasts.contains(actionName); 2663 } 2664 } 2665 2666 @Override 2667 public int checkSignatures(String pkg1, String pkg2) { 2668 synchronized (mPackages) { 2669 final PackageParser.Package p1 = mPackages.get(pkg1); 2670 final PackageParser.Package p2 = mPackages.get(pkg2); 2671 if (p1 == null || p1.mExtras == null 2672 || p2 == null || p2.mExtras == null) { 2673 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2674 } 2675 return compareSignatures(p1.mSignatures, p2.mSignatures); 2676 } 2677 } 2678 2679 @Override 2680 public int checkUidSignatures(int uid1, int uid2) { 2681 // Map to base uids. 2682 uid1 = UserHandle.getAppId(uid1); 2683 uid2 = UserHandle.getAppId(uid2); 2684 // reader 2685 synchronized (mPackages) { 2686 Signature[] s1; 2687 Signature[] s2; 2688 Object obj = mSettings.getUserIdLPr(uid1); 2689 if (obj != null) { 2690 if (obj instanceof SharedUserSetting) { 2691 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2692 } else if (obj instanceof PackageSetting) { 2693 s1 = ((PackageSetting)obj).signatures.mSignatures; 2694 } else { 2695 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2696 } 2697 } else { 2698 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2699 } 2700 obj = mSettings.getUserIdLPr(uid2); 2701 if (obj != null) { 2702 if (obj instanceof SharedUserSetting) { 2703 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2704 } else if (obj instanceof PackageSetting) { 2705 s2 = ((PackageSetting)obj).signatures.mSignatures; 2706 } else { 2707 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2708 } 2709 } else { 2710 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2711 } 2712 return compareSignatures(s1, s2); 2713 } 2714 } 2715 2716 /** 2717 * Compares two sets of signatures. Returns: 2718 * <br /> 2719 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2720 * <br /> 2721 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2722 * <br /> 2723 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2724 * <br /> 2725 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2726 * <br /> 2727 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2728 */ 2729 static int compareSignatures(Signature[] s1, Signature[] s2) { 2730 if (s1 == null) { 2731 return s2 == null 2732 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2733 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2734 } 2735 2736 if (s2 == null) { 2737 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2738 } 2739 2740 if (s1.length != s2.length) { 2741 return PackageManager.SIGNATURE_NO_MATCH; 2742 } 2743 2744 // Since both signature sets are of size 1, we can compare without HashSets. 2745 if (s1.length == 1) { 2746 return s1[0].equals(s2[0]) ? 2747 PackageManager.SIGNATURE_MATCH : 2748 PackageManager.SIGNATURE_NO_MATCH; 2749 } 2750 2751 HashSet<Signature> set1 = new HashSet<Signature>(); 2752 for (Signature sig : s1) { 2753 set1.add(sig); 2754 } 2755 HashSet<Signature> set2 = new HashSet<Signature>(); 2756 for (Signature sig : s2) { 2757 set2.add(sig); 2758 } 2759 // Make sure s2 contains all signatures in s1. 2760 if (set1.equals(set2)) { 2761 return PackageManager.SIGNATURE_MATCH; 2762 } 2763 return PackageManager.SIGNATURE_NO_MATCH; 2764 } 2765 2766 /** 2767 * If the database version for this type of package (internal storage or 2768 * external storage) is less than the version where package signatures 2769 * were updated, return true. 2770 */ 2771 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2772 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2773 DatabaseVersion.SIGNATURE_END_ENTITY)) 2774 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2775 DatabaseVersion.SIGNATURE_END_ENTITY)); 2776 } 2777 2778 /** 2779 * Used for backward compatibility to make sure any packages with 2780 * certificate chains get upgraded to the new style. {@code existingSigs} 2781 * will be in the old format (since they were stored on disk from before the 2782 * system upgrade) and {@code scannedSigs} will be in the newer format. 2783 */ 2784 private int compareSignaturesCompat(PackageSignatures existingSigs, 2785 PackageParser.Package scannedPkg) { 2786 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2787 return PackageManager.SIGNATURE_NO_MATCH; 2788 } 2789 2790 HashSet<Signature> existingSet = new HashSet<Signature>(); 2791 for (Signature sig : existingSigs.mSignatures) { 2792 existingSet.add(sig); 2793 } 2794 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2795 for (Signature sig : scannedPkg.mSignatures) { 2796 try { 2797 Signature[] chainSignatures = sig.getChainSignatures(); 2798 for (Signature chainSig : chainSignatures) { 2799 scannedCompatSet.add(chainSig); 2800 } 2801 } catch (CertificateEncodingException e) { 2802 scannedCompatSet.add(sig); 2803 } 2804 } 2805 /* 2806 * Make sure the expanded scanned set contains all signatures in the 2807 * existing one. 2808 */ 2809 if (scannedCompatSet.equals(existingSet)) { 2810 // Migrate the old signatures to the new scheme. 2811 existingSigs.assignSignatures(scannedPkg.mSignatures); 2812 // The new KeySets will be re-added later in the scanning process. 2813 mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName); 2814 return PackageManager.SIGNATURE_MATCH; 2815 } 2816 return PackageManager.SIGNATURE_NO_MATCH; 2817 } 2818 2819 @Override 2820 public String[] getPackagesForUid(int uid) { 2821 uid = UserHandle.getAppId(uid); 2822 // reader 2823 synchronized (mPackages) { 2824 Object obj = mSettings.getUserIdLPr(uid); 2825 if (obj instanceof SharedUserSetting) { 2826 final SharedUserSetting sus = (SharedUserSetting) obj; 2827 final int N = sus.packages.size(); 2828 final String[] res = new String[N]; 2829 final Iterator<PackageSetting> it = sus.packages.iterator(); 2830 int i = 0; 2831 while (it.hasNext()) { 2832 res[i++] = it.next().name; 2833 } 2834 return res; 2835 } else if (obj instanceof PackageSetting) { 2836 final PackageSetting ps = (PackageSetting) obj; 2837 return new String[] { ps.name }; 2838 } 2839 } 2840 return null; 2841 } 2842 2843 @Override 2844 public String getNameForUid(int uid) { 2845 // reader 2846 synchronized (mPackages) { 2847 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2848 if (obj instanceof SharedUserSetting) { 2849 final SharedUserSetting sus = (SharedUserSetting) obj; 2850 return sus.name + ":" + sus.userId; 2851 } else if (obj instanceof PackageSetting) { 2852 final PackageSetting ps = (PackageSetting) obj; 2853 return ps.name; 2854 } 2855 } 2856 return null; 2857 } 2858 2859 @Override 2860 public int getUidForSharedUser(String sharedUserName) { 2861 if(sharedUserName == null) { 2862 return -1; 2863 } 2864 // reader 2865 synchronized (mPackages) { 2866 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2867 if (suid == null) { 2868 return -1; 2869 } 2870 return suid.userId; 2871 } 2872 } 2873 2874 @Override 2875 public int getFlagsForUid(int uid) { 2876 synchronized (mPackages) { 2877 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2878 if (obj instanceof SharedUserSetting) { 2879 final SharedUserSetting sus = (SharedUserSetting) obj; 2880 return sus.pkgFlags; 2881 } else if (obj instanceof PackageSetting) { 2882 final PackageSetting ps = (PackageSetting) obj; 2883 return ps.pkgFlags; 2884 } 2885 } 2886 return 0; 2887 } 2888 2889 @Override 2890 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2891 int flags, int userId) { 2892 if (!sUserManager.exists(userId)) return null; 2893 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2894 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2895 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2896 } 2897 2898 @Override 2899 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2900 IntentFilter filter, int match, ComponentName activity) { 2901 final int userId = UserHandle.getCallingUserId(); 2902 if (DEBUG_PREFERRED) { 2903 Log.v(TAG, "setLastChosenActivity intent=" + intent 2904 + " resolvedType=" + resolvedType 2905 + " flags=" + flags 2906 + " filter=" + filter 2907 + " match=" + match 2908 + " activity=" + activity); 2909 filter.dump(new PrintStreamPrinter(System.out), " "); 2910 } 2911 intent.setComponent(null); 2912 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2913 // Find any earlier preferred or last chosen entries and nuke them 2914 findPreferredActivity(intent, resolvedType, 2915 flags, query, 0, false, true, false, userId); 2916 // Add the new activity as the last chosen for this filter 2917 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2918 } 2919 2920 @Override 2921 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2922 final int userId = UserHandle.getCallingUserId(); 2923 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2924 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2925 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2926 false, false, false, userId); 2927 } 2928 2929 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2930 int flags, List<ResolveInfo> query, int userId) { 2931 if (query != null) { 2932 final int N = query.size(); 2933 if (N == 1) { 2934 return query.get(0); 2935 } else if (N > 1) { 2936 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2937 // If there is more than one activity with the same priority, 2938 // then let the user decide between them. 2939 ResolveInfo r0 = query.get(0); 2940 ResolveInfo r1 = query.get(1); 2941 if (DEBUG_INTENT_MATCHING || debug) { 2942 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2943 + r1.activityInfo.name + "=" + r1.priority); 2944 } 2945 // If the first activity has a higher priority, or a different 2946 // default, then it is always desireable to pick it. 2947 if (r0.priority != r1.priority 2948 || r0.preferredOrder != r1.preferredOrder 2949 || r0.isDefault != r1.isDefault) { 2950 return query.get(0); 2951 } 2952 // If we have saved a preference for a preferred activity for 2953 // this Intent, use that. 2954 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2955 flags, query, r0.priority, true, false, debug, userId); 2956 if (ri != null) { 2957 return ri; 2958 } 2959 if (userId != 0) { 2960 ri = new ResolveInfo(mResolveInfo); 2961 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2962 ri.activityInfo.applicationInfo = new ApplicationInfo( 2963 ri.activityInfo.applicationInfo); 2964 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2965 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2966 return ri; 2967 } 2968 return mResolveInfo; 2969 } 2970 } 2971 return null; 2972 } 2973 2974 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2975 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2976 final int N = query.size(); 2977 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2978 .get(userId); 2979 // Get the list of persistent preferred activities that handle the intent 2980 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2981 List<PersistentPreferredActivity> pprefs = ppir != null 2982 ? ppir.queryIntent(intent, resolvedType, 2983 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2984 : null; 2985 if (pprefs != null && pprefs.size() > 0) { 2986 final int M = pprefs.size(); 2987 for (int i=0; i<M; i++) { 2988 final PersistentPreferredActivity ppa = pprefs.get(i); 2989 if (DEBUG_PREFERRED || debug) { 2990 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2991 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2992 + "\n component=" + ppa.mComponent); 2993 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2994 } 2995 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2996 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2997 if (DEBUG_PREFERRED || debug) { 2998 Slog.v(TAG, "Found persistent preferred activity:"); 2999 if (ai != null) { 3000 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3001 } else { 3002 Slog.v(TAG, " null"); 3003 } 3004 } 3005 if (ai == null) { 3006 // This previously registered persistent preferred activity 3007 // component is no longer known. Ignore it and do NOT remove it. 3008 continue; 3009 } 3010 for (int j=0; j<N; j++) { 3011 final ResolveInfo ri = query.get(j); 3012 if (!ri.activityInfo.applicationInfo.packageName 3013 .equals(ai.applicationInfo.packageName)) { 3014 continue; 3015 } 3016 if (!ri.activityInfo.name.equals(ai.name)) { 3017 continue; 3018 } 3019 // Found a persistent preference that can handle the intent. 3020 if (DEBUG_PREFERRED || debug) { 3021 Slog.v(TAG, "Returning persistent preferred activity: " + 3022 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3023 } 3024 return ri; 3025 } 3026 } 3027 } 3028 return null; 3029 } 3030 3031 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3032 List<ResolveInfo> query, int priority, boolean always, 3033 boolean removeMatches, boolean debug, int userId) { 3034 if (!sUserManager.exists(userId)) return null; 3035 // writer 3036 synchronized (mPackages) { 3037 if (intent.getSelector() != null) { 3038 intent = intent.getSelector(); 3039 } 3040 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3041 3042 // Try to find a matching persistent preferred activity. 3043 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3044 debug, userId); 3045 3046 // If a persistent preferred activity matched, use it. 3047 if (pri != null) { 3048 return pri; 3049 } 3050 3051 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3052 // Get the list of preferred activities that handle the intent 3053 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3054 List<PreferredActivity> prefs = pir != null 3055 ? pir.queryIntent(intent, resolvedType, 3056 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3057 : null; 3058 if (prefs != null && prefs.size() > 0) { 3059 // First figure out how good the original match set is. 3060 // We will only allow preferred activities that came 3061 // from the same match quality. 3062 int match = 0; 3063 3064 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3065 3066 final int N = query.size(); 3067 for (int j=0; j<N; j++) { 3068 final ResolveInfo ri = query.get(j); 3069 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3070 + ": 0x" + Integer.toHexString(match)); 3071 if (ri.match > match) { 3072 match = ri.match; 3073 } 3074 } 3075 3076 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3077 + Integer.toHexString(match)); 3078 3079 match &= IntentFilter.MATCH_CATEGORY_MASK; 3080 final int M = prefs.size(); 3081 for (int i=0; i<M; i++) { 3082 final PreferredActivity pa = prefs.get(i); 3083 if (DEBUG_PREFERRED || debug) { 3084 Slog.v(TAG, "Checking PreferredActivity ds=" 3085 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3086 + "\n component=" + pa.mPref.mComponent); 3087 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3088 } 3089 if (pa.mPref.mMatch != match) { 3090 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3091 + Integer.toHexString(pa.mPref.mMatch)); 3092 continue; 3093 } 3094 // If it's not an "always" type preferred activity and that's what we're 3095 // looking for, skip it. 3096 if (always && !pa.mPref.mAlways) { 3097 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3098 continue; 3099 } 3100 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3101 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3102 if (DEBUG_PREFERRED || debug) { 3103 Slog.v(TAG, "Found preferred activity:"); 3104 if (ai != null) { 3105 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3106 } else { 3107 Slog.v(TAG, " null"); 3108 } 3109 } 3110 if (ai == null) { 3111 // This previously registered preferred activity 3112 // component is no longer known. Most likely an update 3113 // to the app was installed and in the new version this 3114 // component no longer exists. Clean it up by removing 3115 // it from the preferred activities list, and skip it. 3116 Slog.w(TAG, "Removing dangling preferred activity: " 3117 + pa.mPref.mComponent); 3118 pir.removeFilter(pa); 3119 continue; 3120 } 3121 for (int j=0; j<N; j++) { 3122 final ResolveInfo ri = query.get(j); 3123 if (!ri.activityInfo.applicationInfo.packageName 3124 .equals(ai.applicationInfo.packageName)) { 3125 continue; 3126 } 3127 if (!ri.activityInfo.name.equals(ai.name)) { 3128 continue; 3129 } 3130 3131 if (removeMatches) { 3132 pir.removeFilter(pa); 3133 if (DEBUG_PREFERRED) { 3134 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3135 } 3136 break; 3137 } 3138 3139 // Okay we found a previously set preferred or last chosen app. 3140 // If the result set is different from when this 3141 // was created, we need to clear it and re-ask the 3142 // user their preference, if we're looking for an "always" type entry. 3143 if (always && !pa.mPref.sameSet(query, priority)) { 3144 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3145 + intent + " type " + resolvedType); 3146 if (DEBUG_PREFERRED) { 3147 Slog.v(TAG, "Removing preferred activity since set changed " 3148 + pa.mPref.mComponent); 3149 } 3150 pir.removeFilter(pa); 3151 // Re-add the filter as a "last chosen" entry (!always) 3152 PreferredActivity lastChosen = new PreferredActivity( 3153 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3154 pir.addFilter(lastChosen); 3155 mSettings.writePackageRestrictionsLPr(userId); 3156 return null; 3157 } 3158 3159 // Yay! Either the set matched or we're looking for the last chosen 3160 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3161 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3162 mSettings.writePackageRestrictionsLPr(userId); 3163 return ri; 3164 } 3165 } 3166 } 3167 mSettings.writePackageRestrictionsLPr(userId); 3168 } 3169 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3170 return null; 3171 } 3172 3173 /* 3174 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3175 */ 3176 @Override 3177 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3178 int targetUserId) { 3179 mContext.enforceCallingOrSelfPermission( 3180 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3181 List<CrossProfileIntentFilter> matches = 3182 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3183 if (matches != null) { 3184 int size = matches.size(); 3185 for (int i = 0; i < size; i++) { 3186 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3187 } 3188 } 3189 3190 ArrayList<String> packageNames = null; 3191 SparseArray<ArrayList<String>> fromSource = 3192 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3193 if (fromSource != null) { 3194 packageNames = fromSource.get(targetUserId); 3195 } 3196 if (packageNames.contains(intent.getPackage())) { 3197 return true; 3198 } 3199 // We need the package name, so we try to resolve with the loosest flags possible 3200 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3201 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3202 int count = resolveInfos.size(); 3203 for (int i = 0; i < count; i++) { 3204 ResolveInfo resolveInfo = resolveInfos.get(i); 3205 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3206 return true; 3207 } 3208 } 3209 return false; 3210 } 3211 3212 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3213 String resolvedType, int userId) { 3214 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3215 if (resolver != null) { 3216 return resolver.queryIntent(intent, resolvedType, false, userId); 3217 } 3218 return null; 3219 } 3220 3221 @Override 3222 public List<ResolveInfo> queryIntentActivities(Intent intent, 3223 String resolvedType, int flags, int userId) { 3224 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3225 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3226 ComponentName comp = intent.getComponent(); 3227 if (comp == null) { 3228 if (intent.getSelector() != null) { 3229 intent = intent.getSelector(); 3230 comp = intent.getComponent(); 3231 } 3232 } 3233 3234 if (comp != null) { 3235 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3236 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3237 if (ai != null) { 3238 final ResolveInfo ri = new ResolveInfo(); 3239 ri.activityInfo = ai; 3240 list.add(ri); 3241 } 3242 return list; 3243 } 3244 3245 // reader 3246 synchronized (mPackages) { 3247 final String pkgName = intent.getPackage(); 3248 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3249 if (pkgName == null) { 3250 ResolveInfo resolveInfo = null; 3251 if (queryCrossProfile) { 3252 // Check if the intent needs to be forwarded to another user for this package 3253 ArrayList<ResolveInfo> crossProfileResult = 3254 queryIntentActivitiesCrossProfilePackage( 3255 intent, resolvedType, flags, userId); 3256 if (!crossProfileResult.isEmpty()) { 3257 // Skip the current profile 3258 return crossProfileResult; 3259 } 3260 List<CrossProfileIntentFilter> matchingFilters = 3261 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3262 // Check for results that need to skip the current profile. 3263 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3264 resolvedType, flags, userId); 3265 if (resolveInfo != null) { 3266 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3267 result.add(resolveInfo); 3268 return result; 3269 } 3270 // Check for cross profile results. 3271 resolveInfo = queryCrossProfileIntents( 3272 matchingFilters, intent, resolvedType, flags, userId); 3273 } 3274 // Check for results in the current profile. 3275 List<ResolveInfo> result = mActivities.queryIntent( 3276 intent, resolvedType, flags, userId); 3277 if (resolveInfo != null) { 3278 result.add(resolveInfo); 3279 } 3280 return result; 3281 } 3282 final PackageParser.Package pkg = mPackages.get(pkgName); 3283 if (pkg != null) { 3284 if (queryCrossProfile) { 3285 ArrayList<ResolveInfo> crossProfileResult = 3286 queryIntentActivitiesCrossProfilePackage( 3287 intent, resolvedType, flags, userId, pkg, pkgName); 3288 if (!crossProfileResult.isEmpty()) { 3289 // Skip the current profile 3290 return crossProfileResult; 3291 } 3292 } 3293 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3294 pkg.activities, userId); 3295 } 3296 return new ArrayList<ResolveInfo>(); 3297 } 3298 } 3299 3300 private ResolveInfo querySkipCurrentProfileIntents( 3301 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3302 int flags, int sourceUserId) { 3303 if (matchingFilters != null) { 3304 int size = matchingFilters.size(); 3305 for (int i = 0; i < size; i ++) { 3306 CrossProfileIntentFilter filter = matchingFilters.get(i); 3307 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3308 // Checking if there are activities in the target user that can handle the 3309 // intent. 3310 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3311 flags, sourceUserId); 3312 if (resolveInfo != null) { 3313 return resolveInfo; 3314 } 3315 } 3316 } 3317 } 3318 return null; 3319 } 3320 3321 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3322 Intent intent, String resolvedType, int flags, int userId) { 3323 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3324 SparseArray<ArrayList<String>> sourceForwardingInfo = 3325 mSettings.mCrossProfilePackageInfo.get(userId); 3326 if (sourceForwardingInfo != null) { 3327 int NI = sourceForwardingInfo.size(); 3328 for (int i = 0; i < NI; i++) { 3329 int targetUserId = sourceForwardingInfo.keyAt(i); 3330 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3331 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3332 intent, resolvedType, flags, targetUserId); 3333 int NJ = resolveInfos.size(); 3334 for (int j = 0; j < NJ; j++) { 3335 ResolveInfo resolveInfo = resolveInfos.get(j); 3336 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3337 matchingResolveInfos.add(createForwardingResolveInfo( 3338 resolveInfo.filter, userId, targetUserId)); 3339 } 3340 } 3341 } 3342 } 3343 return matchingResolveInfos; 3344 } 3345 3346 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3347 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3348 String packageName) { 3349 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3350 SparseArray<ArrayList<String>> sourceForwardingInfo = 3351 mSettings.mCrossProfilePackageInfo.get(userId); 3352 if (sourceForwardingInfo != null) { 3353 int NI = sourceForwardingInfo.size(); 3354 for (int i = 0; i < NI; i++) { 3355 int targetUserId = sourceForwardingInfo.keyAt(i); 3356 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3357 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3358 intent, resolvedType, flags, pkg.activities, targetUserId); 3359 int NJ = resolveInfos.size(); 3360 for (int j = 0; j < NJ; j++) { 3361 ResolveInfo resolveInfo = resolveInfos.get(j); 3362 matchingResolveInfos.add(createForwardingResolveInfo( 3363 resolveInfo.filter, userId, targetUserId)); 3364 } 3365 } 3366 } 3367 } 3368 return matchingResolveInfos; 3369 } 3370 3371 // Return matching ResolveInfo if any for skip current profile intent filters. 3372 private ResolveInfo queryCrossProfileIntents( 3373 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3374 int flags, int sourceUserId) { 3375 if (matchingFilters != null) { 3376 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3377 // match the same intent. For performance reasons, it is better not to 3378 // run queryIntent twice for the same userId 3379 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3380 int size = matchingFilters.size(); 3381 for (int i = 0; i < size; i++) { 3382 CrossProfileIntentFilter filter = matchingFilters.get(i); 3383 int targetUserId = filter.getTargetUserId(); 3384 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3385 && !alreadyTriedUserIds.get(targetUserId)) { 3386 // Checking if there are activities in the target user that can handle the 3387 // intent. 3388 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3389 flags, sourceUserId); 3390 if (resolveInfo != null) return resolveInfo; 3391 alreadyTriedUserIds.put(targetUserId, true); 3392 } 3393 } 3394 } 3395 return null; 3396 } 3397 3398 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3399 String resolvedType, int flags, int sourceUserId) { 3400 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3401 resolvedType, flags, filter.getTargetUserId()); 3402 if (resultTargetUser != null) { 3403 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3404 } 3405 return null; 3406 } 3407 3408 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3409 int sourceUserId, int targetUserId) { 3410 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3411 String className; 3412 if (targetUserId == UserHandle.USER_OWNER) { 3413 className = FORWARD_INTENT_TO_USER_OWNER; 3414 forwardingResolveInfo.showTargetUserIcon = true; 3415 } else { 3416 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3417 } 3418 ComponentName forwardingActivityComponentName = new ComponentName( 3419 mAndroidApplication.packageName, className); 3420 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3421 sourceUserId); 3422 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3423 forwardingResolveInfo.priority = 0; 3424 forwardingResolveInfo.preferredOrder = 0; 3425 forwardingResolveInfo.match = 0; 3426 forwardingResolveInfo.isDefault = true; 3427 forwardingResolveInfo.filter = filter; 3428 forwardingResolveInfo.targetUserId = targetUserId; 3429 return forwardingResolveInfo; 3430 } 3431 3432 @Override 3433 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3434 Intent[] specifics, String[] specificTypes, Intent intent, 3435 String resolvedType, int flags, int userId) { 3436 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3437 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3438 "query intent activity options"); 3439 final String resultsAction = intent.getAction(); 3440 3441 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3442 | PackageManager.GET_RESOLVED_FILTER, userId); 3443 3444 if (DEBUG_INTENT_MATCHING) { 3445 Log.v(TAG, "Query " + intent + ": " + results); 3446 } 3447 3448 int specificsPos = 0; 3449 int N; 3450 3451 // todo: note that the algorithm used here is O(N^2). This 3452 // isn't a problem in our current environment, but if we start running 3453 // into situations where we have more than 5 or 10 matches then this 3454 // should probably be changed to something smarter... 3455 3456 // First we go through and resolve each of the specific items 3457 // that were supplied, taking care of removing any corresponding 3458 // duplicate items in the generic resolve list. 3459 if (specifics != null) { 3460 for (int i=0; i<specifics.length; i++) { 3461 final Intent sintent = specifics[i]; 3462 if (sintent == null) { 3463 continue; 3464 } 3465 3466 if (DEBUG_INTENT_MATCHING) { 3467 Log.v(TAG, "Specific #" + i + ": " + sintent); 3468 } 3469 3470 String action = sintent.getAction(); 3471 if (resultsAction != null && resultsAction.equals(action)) { 3472 // If this action was explicitly requested, then don't 3473 // remove things that have it. 3474 action = null; 3475 } 3476 3477 ResolveInfo ri = null; 3478 ActivityInfo ai = null; 3479 3480 ComponentName comp = sintent.getComponent(); 3481 if (comp == null) { 3482 ri = resolveIntent( 3483 sintent, 3484 specificTypes != null ? specificTypes[i] : null, 3485 flags, userId); 3486 if (ri == null) { 3487 continue; 3488 } 3489 if (ri == mResolveInfo) { 3490 // ACK! Must do something better with this. 3491 } 3492 ai = ri.activityInfo; 3493 comp = new ComponentName(ai.applicationInfo.packageName, 3494 ai.name); 3495 } else { 3496 ai = getActivityInfo(comp, flags, userId); 3497 if (ai == null) { 3498 continue; 3499 } 3500 } 3501 3502 // Look for any generic query activities that are duplicates 3503 // of this specific one, and remove them from the results. 3504 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3505 N = results.size(); 3506 int j; 3507 for (j=specificsPos; j<N; j++) { 3508 ResolveInfo sri = results.get(j); 3509 if ((sri.activityInfo.name.equals(comp.getClassName()) 3510 && sri.activityInfo.applicationInfo.packageName.equals( 3511 comp.getPackageName())) 3512 || (action != null && sri.filter.matchAction(action))) { 3513 results.remove(j); 3514 if (DEBUG_INTENT_MATCHING) Log.v( 3515 TAG, "Removing duplicate item from " + j 3516 + " due to specific " + specificsPos); 3517 if (ri == null) { 3518 ri = sri; 3519 } 3520 j--; 3521 N--; 3522 } 3523 } 3524 3525 // Add this specific item to its proper place. 3526 if (ri == null) { 3527 ri = new ResolveInfo(); 3528 ri.activityInfo = ai; 3529 } 3530 results.add(specificsPos, ri); 3531 ri.specificIndex = i; 3532 specificsPos++; 3533 } 3534 } 3535 3536 // Now we go through the remaining generic results and remove any 3537 // duplicate actions that are found here. 3538 N = results.size(); 3539 for (int i=specificsPos; i<N-1; i++) { 3540 final ResolveInfo rii = results.get(i); 3541 if (rii.filter == null) { 3542 continue; 3543 } 3544 3545 // Iterate over all of the actions of this result's intent 3546 // filter... typically this should be just one. 3547 final Iterator<String> it = rii.filter.actionsIterator(); 3548 if (it == null) { 3549 continue; 3550 } 3551 while (it.hasNext()) { 3552 final String action = it.next(); 3553 if (resultsAction != null && resultsAction.equals(action)) { 3554 // If this action was explicitly requested, then don't 3555 // remove things that have it. 3556 continue; 3557 } 3558 for (int j=i+1; j<N; j++) { 3559 final ResolveInfo rij = results.get(j); 3560 if (rij.filter != null && rij.filter.hasAction(action)) { 3561 results.remove(j); 3562 if (DEBUG_INTENT_MATCHING) Log.v( 3563 TAG, "Removing duplicate item from " + j 3564 + " due to action " + action + " at " + i); 3565 j--; 3566 N--; 3567 } 3568 } 3569 } 3570 3571 // If the caller didn't request filter information, drop it now 3572 // so we don't have to marshall/unmarshall it. 3573 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3574 rii.filter = null; 3575 } 3576 } 3577 3578 // Filter out the caller activity if so requested. 3579 if (caller != null) { 3580 N = results.size(); 3581 for (int i=0; i<N; i++) { 3582 ActivityInfo ainfo = results.get(i).activityInfo; 3583 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3584 && caller.getClassName().equals(ainfo.name)) { 3585 results.remove(i); 3586 break; 3587 } 3588 } 3589 } 3590 3591 // If the caller didn't request filter information, 3592 // drop them now so we don't have to 3593 // marshall/unmarshall it. 3594 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3595 N = results.size(); 3596 for (int i=0; i<N; i++) { 3597 results.get(i).filter = null; 3598 } 3599 } 3600 3601 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3602 return results; 3603 } 3604 3605 @Override 3606 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3607 int userId) { 3608 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3609 ComponentName comp = intent.getComponent(); 3610 if (comp == null) { 3611 if (intent.getSelector() != null) { 3612 intent = intent.getSelector(); 3613 comp = intent.getComponent(); 3614 } 3615 } 3616 if (comp != null) { 3617 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3618 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3619 if (ai != null) { 3620 ResolveInfo ri = new ResolveInfo(); 3621 ri.activityInfo = ai; 3622 list.add(ri); 3623 } 3624 return list; 3625 } 3626 3627 // reader 3628 synchronized (mPackages) { 3629 String pkgName = intent.getPackage(); 3630 if (pkgName == null) { 3631 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3632 } 3633 final PackageParser.Package pkg = mPackages.get(pkgName); 3634 if (pkg != null) { 3635 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3636 userId); 3637 } 3638 return null; 3639 } 3640 } 3641 3642 @Override 3643 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3644 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3645 if (!sUserManager.exists(userId)) return null; 3646 if (query != null) { 3647 if (query.size() >= 1) { 3648 // If there is more than one service with the same priority, 3649 // just arbitrarily pick the first one. 3650 return query.get(0); 3651 } 3652 } 3653 return null; 3654 } 3655 3656 @Override 3657 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3658 int userId) { 3659 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3660 ComponentName comp = intent.getComponent(); 3661 if (comp == null) { 3662 if (intent.getSelector() != null) { 3663 intent = intent.getSelector(); 3664 comp = intent.getComponent(); 3665 } 3666 } 3667 if (comp != null) { 3668 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3669 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3670 if (si != null) { 3671 final ResolveInfo ri = new ResolveInfo(); 3672 ri.serviceInfo = si; 3673 list.add(ri); 3674 } 3675 return list; 3676 } 3677 3678 // reader 3679 synchronized (mPackages) { 3680 String pkgName = intent.getPackage(); 3681 if (pkgName == null) { 3682 return mServices.queryIntent(intent, resolvedType, flags, userId); 3683 } 3684 final PackageParser.Package pkg = mPackages.get(pkgName); 3685 if (pkg != null) { 3686 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3687 userId); 3688 } 3689 return null; 3690 } 3691 } 3692 3693 @Override 3694 public List<ResolveInfo> queryIntentContentProviders( 3695 Intent intent, String resolvedType, int flags, int userId) { 3696 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3697 ComponentName comp = intent.getComponent(); 3698 if (comp == null) { 3699 if (intent.getSelector() != null) { 3700 intent = intent.getSelector(); 3701 comp = intent.getComponent(); 3702 } 3703 } 3704 if (comp != null) { 3705 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3706 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3707 if (pi != null) { 3708 final ResolveInfo ri = new ResolveInfo(); 3709 ri.providerInfo = pi; 3710 list.add(ri); 3711 } 3712 return list; 3713 } 3714 3715 // reader 3716 synchronized (mPackages) { 3717 String pkgName = intent.getPackage(); 3718 if (pkgName == null) { 3719 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3720 } 3721 final PackageParser.Package pkg = mPackages.get(pkgName); 3722 if (pkg != null) { 3723 return mProviders.queryIntentForPackage( 3724 intent, resolvedType, flags, pkg.providers, userId); 3725 } 3726 return null; 3727 } 3728 } 3729 3730 @Override 3731 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3732 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3733 3734 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3735 3736 // writer 3737 synchronized (mPackages) { 3738 ArrayList<PackageInfo> list; 3739 if (listUninstalled) { 3740 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3741 for (PackageSetting ps : mSettings.mPackages.values()) { 3742 PackageInfo pi; 3743 if (ps.pkg != null) { 3744 pi = generatePackageInfo(ps.pkg, flags, userId); 3745 } else { 3746 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3747 } 3748 if (pi != null) { 3749 list.add(pi); 3750 } 3751 } 3752 } else { 3753 list = new ArrayList<PackageInfo>(mPackages.size()); 3754 for (PackageParser.Package p : mPackages.values()) { 3755 PackageInfo pi = generatePackageInfo(p, flags, userId); 3756 if (pi != null) { 3757 list.add(pi); 3758 } 3759 } 3760 } 3761 3762 return new ParceledListSlice<PackageInfo>(list); 3763 } 3764 } 3765 3766 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3767 String[] permissions, boolean[] tmp, int flags, int userId) { 3768 int numMatch = 0; 3769 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3770 for (int i=0; i<permissions.length; i++) { 3771 if (gp.grantedPermissions.contains(permissions[i])) { 3772 tmp[i] = true; 3773 numMatch++; 3774 } else { 3775 tmp[i] = false; 3776 } 3777 } 3778 if (numMatch == 0) { 3779 return; 3780 } 3781 PackageInfo pi; 3782 if (ps.pkg != null) { 3783 pi = generatePackageInfo(ps.pkg, flags, userId); 3784 } else { 3785 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3786 } 3787 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3788 if (numMatch == permissions.length) { 3789 pi.requestedPermissions = permissions; 3790 } else { 3791 pi.requestedPermissions = new String[numMatch]; 3792 numMatch = 0; 3793 for (int i=0; i<permissions.length; i++) { 3794 if (tmp[i]) { 3795 pi.requestedPermissions[numMatch] = permissions[i]; 3796 numMatch++; 3797 } 3798 } 3799 } 3800 } 3801 list.add(pi); 3802 } 3803 3804 @Override 3805 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3806 String[] permissions, int flags, int userId) { 3807 if (!sUserManager.exists(userId)) return null; 3808 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3809 3810 // writer 3811 synchronized (mPackages) { 3812 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3813 boolean[] tmpBools = new boolean[permissions.length]; 3814 if (listUninstalled) { 3815 for (PackageSetting ps : mSettings.mPackages.values()) { 3816 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3817 } 3818 } else { 3819 for (PackageParser.Package pkg : mPackages.values()) { 3820 PackageSetting ps = (PackageSetting)pkg.mExtras; 3821 if (ps != null) { 3822 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3823 userId); 3824 } 3825 } 3826 } 3827 3828 return new ParceledListSlice<PackageInfo>(list); 3829 } 3830 } 3831 3832 @Override 3833 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3834 if (!sUserManager.exists(userId)) return null; 3835 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3836 3837 // writer 3838 synchronized (mPackages) { 3839 ArrayList<ApplicationInfo> list; 3840 if (listUninstalled) { 3841 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3842 for (PackageSetting ps : mSettings.mPackages.values()) { 3843 ApplicationInfo ai; 3844 if (ps.pkg != null) { 3845 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3846 ps.readUserState(userId), userId); 3847 } else { 3848 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3849 } 3850 if (ai != null) { 3851 list.add(ai); 3852 } 3853 } 3854 } else { 3855 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3856 for (PackageParser.Package p : mPackages.values()) { 3857 if (p.mExtras != null) { 3858 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3859 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3860 if (ai != null) { 3861 list.add(ai); 3862 } 3863 } 3864 } 3865 } 3866 3867 return new ParceledListSlice<ApplicationInfo>(list); 3868 } 3869 } 3870 3871 public List<ApplicationInfo> getPersistentApplications(int flags) { 3872 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3873 3874 // reader 3875 synchronized (mPackages) { 3876 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3877 final int userId = UserHandle.getCallingUserId(); 3878 while (i.hasNext()) { 3879 final PackageParser.Package p = i.next(); 3880 if (p.applicationInfo != null 3881 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3882 && (!mSafeMode || isSystemApp(p))) { 3883 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3884 if (ps != null) { 3885 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3886 ps.readUserState(userId), userId); 3887 if (ai != null) { 3888 finalList.add(ai); 3889 } 3890 } 3891 } 3892 } 3893 } 3894 3895 return finalList; 3896 } 3897 3898 @Override 3899 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3900 if (!sUserManager.exists(userId)) return null; 3901 // reader 3902 synchronized (mPackages) { 3903 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3904 PackageSetting ps = provider != null 3905 ? mSettings.mPackages.get(provider.owner.packageName) 3906 : null; 3907 return ps != null 3908 && mSettings.isEnabledLPr(provider.info, flags, userId) 3909 && (!mSafeMode || (provider.info.applicationInfo.flags 3910 &ApplicationInfo.FLAG_SYSTEM) != 0) 3911 ? PackageParser.generateProviderInfo(provider, flags, 3912 ps.readUserState(userId), userId) 3913 : null; 3914 } 3915 } 3916 3917 /** 3918 * @deprecated 3919 */ 3920 @Deprecated 3921 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3922 // reader 3923 synchronized (mPackages) { 3924 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3925 .entrySet().iterator(); 3926 final int userId = UserHandle.getCallingUserId(); 3927 while (i.hasNext()) { 3928 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3929 PackageParser.Provider p = entry.getValue(); 3930 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3931 3932 if (ps != null && p.syncable 3933 && (!mSafeMode || (p.info.applicationInfo.flags 3934 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3935 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3936 ps.readUserState(userId), userId); 3937 if (info != null) { 3938 outNames.add(entry.getKey()); 3939 outInfo.add(info); 3940 } 3941 } 3942 } 3943 } 3944 } 3945 3946 @Override 3947 public List<ProviderInfo> queryContentProviders(String processName, 3948 int uid, int flags) { 3949 ArrayList<ProviderInfo> finalList = null; 3950 // reader 3951 synchronized (mPackages) { 3952 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3953 final int userId = processName != null ? 3954 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3955 while (i.hasNext()) { 3956 final PackageParser.Provider p = i.next(); 3957 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3958 if (ps != null && p.info.authority != null 3959 && (processName == null 3960 || (p.info.processName.equals(processName) 3961 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3962 && mSettings.isEnabledLPr(p.info, flags, userId) 3963 && (!mSafeMode 3964 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3965 if (finalList == null) { 3966 finalList = new ArrayList<ProviderInfo>(3); 3967 } 3968 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3969 ps.readUserState(userId), userId); 3970 if (info != null) { 3971 finalList.add(info); 3972 } 3973 } 3974 } 3975 } 3976 3977 if (finalList != null) { 3978 Collections.sort(finalList, mProviderInitOrderSorter); 3979 } 3980 3981 return finalList; 3982 } 3983 3984 @Override 3985 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3986 int flags) { 3987 // reader 3988 synchronized (mPackages) { 3989 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3990 return PackageParser.generateInstrumentationInfo(i, flags); 3991 } 3992 } 3993 3994 @Override 3995 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3996 int flags) { 3997 ArrayList<InstrumentationInfo> finalList = 3998 new ArrayList<InstrumentationInfo>(); 3999 4000 // reader 4001 synchronized (mPackages) { 4002 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4003 while (i.hasNext()) { 4004 final PackageParser.Instrumentation p = i.next(); 4005 if (targetPackage == null 4006 || targetPackage.equals(p.info.targetPackage)) { 4007 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4008 flags); 4009 if (ii != null) { 4010 finalList.add(ii); 4011 } 4012 } 4013 } 4014 } 4015 4016 return finalList; 4017 } 4018 4019 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4020 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4021 if (overlays == null) { 4022 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4023 return; 4024 } 4025 for (PackageParser.Package opkg : overlays.values()) { 4026 // Not much to do if idmap fails: we already logged the error 4027 // and we certainly don't want to abort installation of pkg simply 4028 // because an overlay didn't fit properly. For these reasons, 4029 // ignore the return value of createIdmapForPackagePairLI. 4030 createIdmapForPackagePairLI(pkg, opkg); 4031 } 4032 } 4033 4034 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4035 PackageParser.Package opkg) { 4036 if (!opkg.mTrustedOverlay) { 4037 Slog.w(TAG, "Skipping target and overlay pair " + pkg.codePath + " and " + 4038 opkg.codePath + ": overlay not trusted"); 4039 return false; 4040 } 4041 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4042 if (overlaySet == null) { 4043 Slog.e(TAG, "was about to create idmap for " + pkg.codePath + " and " + 4044 opkg.codePath + " but target package has no known overlays"); 4045 return false; 4046 } 4047 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4048 // TODO: generate idmap for split APKs 4049 if (mInstaller.idmap(pkg.codePath, opkg.codePath, sharedGid) != 0) { 4050 Slog.e(TAG, "Failed to generate idmap for " + pkg.codePath + " and " + opkg.codePath); 4051 return false; 4052 } 4053 PackageParser.Package[] overlayArray = 4054 overlaySet.values().toArray(new PackageParser.Package[0]); 4055 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4056 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4057 return p1.mOverlayPriority - p2.mOverlayPriority; 4058 } 4059 }; 4060 Arrays.sort(overlayArray, cmp); 4061 4062 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4063 int i = 0; 4064 for (PackageParser.Package p : overlayArray) { 4065 pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir; 4066 } 4067 return true; 4068 } 4069 4070 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4071 String[] files = dir.list(); 4072 if (files == null) { 4073 Log.d(TAG, "No files in app dir " + dir); 4074 return; 4075 } 4076 4077 if (DEBUG_PACKAGE_SCANNING) { 4078 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4079 + " flags=0x" + Integer.toHexString(flags)); 4080 } 4081 4082 int i; 4083 for (i=0; i<files.length; i++) { 4084 File file = new File(dir, files[i]); 4085 if (!isPackageFilename(files[i])) { 4086 // Ignore entries which are not apk's 4087 continue; 4088 } 4089 PackageParser.Package pkg = scanPackageLI(file, 4090 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null); 4091 // Don't mess around with apps in system partition. 4092 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4093 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 4094 // Delete the apk 4095 Slog.w(TAG, "Cleaning up failed install of " + file); 4096 file.delete(); 4097 } 4098 } 4099 } 4100 4101 private static File getSettingsProblemFile() { 4102 File dataDir = Environment.getDataDirectory(); 4103 File systemDir = new File(dataDir, "system"); 4104 File fname = new File(systemDir, "uiderrors.txt"); 4105 return fname; 4106 } 4107 4108 static void reportSettingsProblem(int priority, String msg) { 4109 try { 4110 File fname = getSettingsProblemFile(); 4111 FileOutputStream out = new FileOutputStream(fname, true); 4112 PrintWriter pw = new FastPrintWriter(out); 4113 SimpleDateFormat formatter = new SimpleDateFormat(); 4114 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4115 pw.println(dateString + ": " + msg); 4116 pw.close(); 4117 FileUtils.setPermissions( 4118 fname.toString(), 4119 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4120 -1, -1); 4121 } catch (java.io.IOException e) { 4122 } 4123 Slog.println(priority, TAG, msg); 4124 } 4125 4126 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 4127 PackageParser.Package pkg, File srcFile, int parseFlags) { 4128 if (ps != null 4129 && ps.codePath.equals(srcFile) 4130 && ps.timeStamp == srcFile.lastModified() 4131 && !isCompatSignatureUpdateNeeded(pkg)) { 4132 if (ps.signatures.mSignatures != null 4133 && ps.signatures.mSignatures.length != 0) { 4134 // Optimization: reuse the existing cached certificates 4135 // if the package appears to be unchanged. 4136 pkg.mSignatures = ps.signatures.mSignatures; 4137 return true; 4138 } 4139 4140 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 4141 } else { 4142 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4143 } 4144 4145 try { 4146 pp.collectCertificates(pkg, parseFlags); 4147 pp.collectManifestDigest(pkg); 4148 } catch (PackageParserException e) { 4149 mLastScanError = e.error; 4150 return false; 4151 } 4152 return true; 4153 } 4154 4155 /* 4156 * Scan a package and return the newly parsed package. 4157 * Returns null in case of errors and the error code is stored in mLastScanError 4158 */ 4159 private PackageParser.Package scanPackageLI(File scanFile, 4160 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4161 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 4162 String scanPath = scanFile.getPath(); 4163 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath); 4164 parseFlags |= mDefParseFlags; 4165 PackageParser pp = new PackageParser(); 4166 pp.setSeparateProcesses(mSeparateProcesses); 4167 pp.setOnlyCoreApps(mOnlyCore); 4168 pp.setDisplayMetrics(mMetrics); 4169 4170 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4171 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4172 } 4173 4174 final PackageParser.Package pkg; 4175 try { 4176 pkg = pp.parseMonolithicPackage(scanFile, parseFlags); 4177 } catch (PackageParserException e) { 4178 mLastScanError = e.error; 4179 return null; 4180 } 4181 4182 PackageSetting ps = null; 4183 PackageSetting updatedPkg; 4184 // reader 4185 synchronized (mPackages) { 4186 // Look to see if we already know about this package. 4187 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4188 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4189 // This package has been renamed to its original name. Let's 4190 // use that. 4191 ps = mSettings.peekPackageLPr(oldName); 4192 } 4193 // If there was no original package, see one for the real package name. 4194 if (ps == null) { 4195 ps = mSettings.peekPackageLPr(pkg.packageName); 4196 } 4197 // Check to see if this package could be hiding/updating a system 4198 // package. Must look for it either under the original or real 4199 // package name depending on our state. 4200 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4201 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4202 } 4203 boolean updatedPkgBetter = false; 4204 // First check if this is a system package that may involve an update 4205 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4206 if (ps != null && !ps.codePath.equals(scanFile)) { 4207 // The path has changed from what was last scanned... check the 4208 // version of the new path against what we have stored to determine 4209 // what to do. 4210 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4211 if (pkg.mVersionCode < ps.versionCode) { 4212 // The system package has been updated and the code path does not match 4213 // Ignore entry. Skip it. 4214 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4215 + " ignored: updated version " + ps.versionCode 4216 + " better than this " + pkg.mVersionCode); 4217 if (!updatedPkg.codePath.equals(scanFile)) { 4218 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4219 + ps.name + " changing from " + updatedPkg.codePathString 4220 + " to " + scanFile); 4221 updatedPkg.codePath = scanFile; 4222 updatedPkg.codePathString = scanFile.toString(); 4223 // This is the point at which we know that the system-disk APK 4224 // for this package has moved during a reboot (e.g. due to an OTA), 4225 // so we need to reevaluate it for privilege policy. 4226 if (locationIsPrivileged(scanFile)) { 4227 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4228 } 4229 } 4230 updatedPkg.pkg = pkg; 4231 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4232 return null; 4233 } else { 4234 // The current app on the system partition is better than 4235 // what we have updated to on the data partition; switch 4236 // back to the system partition version. 4237 // At this point, its safely assumed that package installation for 4238 // apps in system partition will go through. If not there won't be a working 4239 // version of the app 4240 // writer 4241 synchronized (mPackages) { 4242 // Just remove the loaded entries from package lists. 4243 mPackages.remove(ps.name); 4244 } 4245 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4246 + "reverting from " + ps.codePathString 4247 + ": new version " + pkg.mVersionCode 4248 + " better than installed " + ps.versionCode); 4249 4250 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4251 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4252 getAppInstructionSetFromSettings(ps)); 4253 synchronized (mInstallLock) { 4254 args.cleanUpResourcesLI(); 4255 } 4256 synchronized (mPackages) { 4257 mSettings.enableSystemPackageLPw(ps.name); 4258 } 4259 updatedPkgBetter = true; 4260 } 4261 } 4262 } 4263 4264 if (updatedPkg != null) { 4265 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4266 // initially 4267 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4268 4269 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4270 // flag set initially 4271 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4272 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4273 } 4274 } 4275 // Verify certificates against what was last scanned 4276 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 4277 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 4278 return null; 4279 } 4280 4281 /* 4282 * A new system app appeared, but we already had a non-system one of the 4283 * same name installed earlier. 4284 */ 4285 boolean shouldHideSystemApp = false; 4286 if (updatedPkg == null && ps != null 4287 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4288 /* 4289 * Check to make sure the signatures match first. If they don't, 4290 * wipe the installed application and its data. 4291 */ 4292 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4293 != PackageManager.SIGNATURE_MATCH) { 4294 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4295 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4296 ps = null; 4297 } else { 4298 /* 4299 * If the newly-added system app is an older version than the 4300 * already installed version, hide it. It will be scanned later 4301 * and re-added like an update. 4302 */ 4303 if (pkg.mVersionCode < ps.versionCode) { 4304 shouldHideSystemApp = true; 4305 } else { 4306 /* 4307 * The newly found system app is a newer version that the 4308 * one previously installed. Simply remove the 4309 * already-installed application and replace it with our own 4310 * while keeping the application data. 4311 */ 4312 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4313 + ps.codePathString + ": new version " + pkg.mVersionCode 4314 + " better than installed " + ps.versionCode); 4315 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4316 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4317 getAppInstructionSetFromSettings(ps)); 4318 synchronized (mInstallLock) { 4319 args.cleanUpResourcesLI(); 4320 } 4321 } 4322 } 4323 } 4324 4325 // The apk is forward locked (not public) if its code and resources 4326 // are kept in different files. (except for app in either system or 4327 // vendor path). 4328 // TODO grab this value from PackageSettings 4329 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4330 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4331 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4332 } 4333 } 4334 4335 final String codePath = pkg.codePath; 4336 final String[] splitCodePaths = pkg.splitCodePaths; 4337 4338 String resPath = null; 4339 String[] splitResPaths = null; 4340 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4341 if (ps != null && ps.resourcePathString != null) { 4342 resPath = ps.resourcePathString; 4343 splitResPaths = deriveSplitResPaths(pkg.splitCodePaths); 4344 } else { 4345 // Should not happen at all. Just log an error. 4346 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4347 } 4348 } else { 4349 resPath = pkg.codePath; 4350 splitResPaths = pkg.splitCodePaths; 4351 } 4352 4353 // Set application objects path explicitly. 4354 pkg.applicationInfo.sourceDir = codePath; 4355 pkg.applicationInfo.publicSourceDir = resPath; 4356 pkg.applicationInfo.splitSourceDirs = splitCodePaths; 4357 pkg.applicationInfo.splitPublicSourceDirs = splitResPaths; 4358 4359 // Note that we invoke the following method only if we are about to unpack an application 4360 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4361 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4362 4363 /* 4364 * If the system app should be overridden by a previously installed 4365 * data, hide the system app now and let the /data/app scan pick it up 4366 * again. 4367 */ 4368 if (shouldHideSystemApp) { 4369 synchronized (mPackages) { 4370 /* 4371 * We have to grant systems permissions before we hide, because 4372 * grantPermissions will assume the package update is trying to 4373 * expand its permissions. 4374 */ 4375 grantPermissionsLPw(pkg, true); 4376 mSettings.disableSystemPackageLPw(pkg.packageName); 4377 } 4378 } 4379 4380 return scannedPkg; 4381 } 4382 4383 private static String fixProcessName(String defProcessName, 4384 String processName, int uid) { 4385 if (processName == null) { 4386 return defProcessName; 4387 } 4388 return processName; 4389 } 4390 4391 private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) { 4392 if (pkgSetting.signatures.mSignatures != null) { 4393 // Already existing package. Make sure signatures match 4394 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4395 == PackageManager.SIGNATURE_MATCH; 4396 if (!match) { 4397 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4398 == PackageManager.SIGNATURE_MATCH; 4399 } 4400 if (!match) { 4401 Slog.e(TAG, "Package " + pkg.packageName 4402 + " signatures do not match the previously installed version; ignoring!"); 4403 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4404 return false; 4405 } 4406 } 4407 // Check for shared user signatures 4408 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4409 // Already existing package. Make sure signatures match 4410 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4411 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4412 if (!match) { 4413 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4414 == PackageManager.SIGNATURE_MATCH; 4415 } 4416 if (!match) { 4417 Slog.e(TAG, "Package " + pkg.packageName 4418 + " has no signatures that match those in shared user " 4419 + pkgSetting.sharedUser.name + "; ignoring!"); 4420 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4421 return false; 4422 } 4423 } 4424 return true; 4425 } 4426 4427 /** 4428 * Enforces that only the system UID or root's UID can call a method exposed 4429 * via Binder. 4430 * 4431 * @param message used as message if SecurityException is thrown 4432 * @throws SecurityException if the caller is not system or root 4433 */ 4434 private static final void enforceSystemOrRoot(String message) { 4435 final int uid = Binder.getCallingUid(); 4436 if (uid != Process.SYSTEM_UID && uid != 0) { 4437 throw new SecurityException(message); 4438 } 4439 } 4440 4441 @Override 4442 public void performBootDexOpt() { 4443 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4444 4445 final HashSet<PackageParser.Package> pkgs; 4446 synchronized (mPackages) { 4447 pkgs = mDeferredDexOpt; 4448 mDeferredDexOpt = null; 4449 } 4450 4451 if (pkgs != null) { 4452 // Filter out packages that aren't recently used. 4453 // 4454 // The exception is first boot of a non-eng device, which 4455 // should do a full dexopt. 4456 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4457 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4458 // TODO: add a property to control this? 4459 long dexOptLRUThresholdInMinutes; 4460 if (eng) { 4461 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4462 } else { 4463 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4464 } 4465 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4466 4467 int total = pkgs.size(); 4468 int skipped = 0; 4469 long now = System.currentTimeMillis(); 4470 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4471 PackageParser.Package pkg = i.next(); 4472 long then = pkg.mLastPackageUsageTimeInMills; 4473 if (then + dexOptLRUThresholdInMills < now) { 4474 if (DEBUG_DEXOPT) { 4475 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4476 ((then == 0) ? "never" : new Date(then))); 4477 } 4478 i.remove(); 4479 skipped++; 4480 } 4481 } 4482 if (DEBUG_DEXOPT) { 4483 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4484 } 4485 } 4486 4487 int i = 0; 4488 for (PackageParser.Package pkg : pkgs) { 4489 i++; 4490 if (DEBUG_DEXOPT) { 4491 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4492 + ": " + pkg.packageName); 4493 } 4494 if (!isFirstBoot()) { 4495 try { 4496 ActivityManagerNative.getDefault().showBootMessage( 4497 mContext.getResources().getString( 4498 R.string.android_upgrading_apk, 4499 i, pkgs.size()), true); 4500 } catch (RemoteException e) { 4501 } 4502 } 4503 PackageParser.Package p = pkg; 4504 synchronized (mInstallLock) { 4505 if (p.mDexOptNeeded) { 4506 performDexOptLI(p, false /* force dex */, false /* defer */, 4507 true /* include dependencies */); 4508 } 4509 } 4510 } 4511 } 4512 } 4513 4514 @Override 4515 public boolean performDexOpt(String packageName) { 4516 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4517 return performDexOpt(packageName, true); 4518 } 4519 4520 public boolean performDexOpt(String packageName, boolean updateUsage) { 4521 4522 PackageParser.Package p; 4523 synchronized (mPackages) { 4524 p = mPackages.get(packageName); 4525 if (p == null) { 4526 return false; 4527 } 4528 if (updateUsage) { 4529 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4530 } 4531 mPackageUsage.write(false); 4532 if (!p.mDexOptNeeded) { 4533 return false; 4534 } 4535 } 4536 4537 synchronized (mInstallLock) { 4538 return performDexOptLI(p, false /* force dex */, false /* defer */, 4539 true /* include dependencies */) == DEX_OPT_PERFORMED; 4540 } 4541 } 4542 4543 public HashSet<String> getPackagesThatNeedDexOpt() { 4544 HashSet<String> pkgs = null; 4545 synchronized (mPackages) { 4546 for (PackageParser.Package p : mPackages.values()) { 4547 if (DEBUG_DEXOPT) { 4548 Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded); 4549 } 4550 if (!p.mDexOptNeeded) { 4551 continue; 4552 } 4553 if (pkgs == null) { 4554 pkgs = new HashSet<String>(); 4555 } 4556 pkgs.add(p.packageName); 4557 } 4558 } 4559 return pkgs; 4560 } 4561 4562 public void shutdown() { 4563 mPackageUsage.write(true); 4564 } 4565 4566 private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, 4567 boolean forceDex, boolean defer, HashSet<String> done) { 4568 for (int i=0; i<libs.size(); i++) { 4569 PackageParser.Package libPkg; 4570 String libName; 4571 synchronized (mPackages) { 4572 libName = libs.get(i); 4573 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4574 if (lib != null && lib.apk != null) { 4575 libPkg = mPackages.get(lib.apk); 4576 } else { 4577 libPkg = null; 4578 } 4579 } 4580 if (libPkg != null && !done.contains(libName)) { 4581 performDexOptLI(libPkg, instructionSet, forceDex, defer, done); 4582 } 4583 } 4584 } 4585 4586 static final int DEX_OPT_SKIPPED = 0; 4587 static final int DEX_OPT_PERFORMED = 1; 4588 static final int DEX_OPT_DEFERRED = 2; 4589 static final int DEX_OPT_FAILED = -1; 4590 4591 private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride, 4592 boolean forceDex, boolean defer, HashSet<String> done) { 4593 final String instructionSet = instructionSetOverride != null ? 4594 instructionSetOverride : getAppInstructionSet(pkg.applicationInfo); 4595 4596 if (done != null) { 4597 done.add(pkg.packageName); 4598 if (pkg.usesLibraries != null) { 4599 performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done); 4600 } 4601 if (pkg.usesOptionalLibraries != null) { 4602 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done); 4603 } 4604 } 4605 4606 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) { 4607 final Collection<String> paths = pkg.getAllCodePaths(); 4608 for (String path : paths) { 4609 try { 4610 boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path, 4611 pkg.packageName, instructionSet, defer); 4612 // There are three basic cases here: 4613 // 1.) we need to dexopt, either because we are forced or it is needed 4614 // 2.) we are defering a needed dexopt 4615 // 3.) we are skipping an unneeded dexopt 4616 if (forceDex || (!defer && isDexOptNeededInternal)) { 4617 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName); 4618 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4619 int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4620 pkg.packageName, instructionSet); 4621 // Note that we ran dexopt, since rerunning will 4622 // probably just result in an error again. 4623 pkg.mDexOptNeeded = false; 4624 if (ret < 0) { 4625 return DEX_OPT_FAILED; 4626 } 4627 return DEX_OPT_PERFORMED; 4628 } 4629 if (defer && isDexOptNeededInternal) { 4630 if (mDeferredDexOpt == null) { 4631 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4632 } 4633 mDeferredDexOpt.add(pkg); 4634 return DEX_OPT_DEFERRED; 4635 } 4636 pkg.mDexOptNeeded = false; 4637 return DEX_OPT_SKIPPED; 4638 } catch (FileNotFoundException e) { 4639 Slog.w(TAG, "Apk not found for dexopt: " + path); 4640 return DEX_OPT_FAILED; 4641 } catch (IOException e) { 4642 Slog.w(TAG, "IOException reading apk: " + path, e); 4643 return DEX_OPT_FAILED; 4644 } catch (StaleDexCacheError e) { 4645 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4646 return DEX_OPT_FAILED; 4647 } catch (Exception e) { 4648 Slog.w(TAG, "Exception when doing dexopt : ", e); 4649 return DEX_OPT_FAILED; 4650 } 4651 } 4652 } 4653 return DEX_OPT_SKIPPED; 4654 } 4655 4656 private String getAppInstructionSet(ApplicationInfo info) { 4657 String instructionSet = getPreferredInstructionSet(); 4658 4659 if (info.cpuAbi != null) { 4660 instructionSet = VMRuntime.getInstructionSet(info.cpuAbi); 4661 } 4662 4663 return instructionSet; 4664 } 4665 4666 private String getAppInstructionSetFromSettings(PackageSetting ps) { 4667 String instructionSet = getPreferredInstructionSet(); 4668 4669 if (ps.cpuAbiString != null) { 4670 instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 4671 } 4672 4673 return instructionSet; 4674 } 4675 4676 private static String getPreferredInstructionSet() { 4677 if (sPreferredInstructionSet == null) { 4678 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4679 } 4680 4681 return sPreferredInstructionSet; 4682 } 4683 4684 private static List<String> getAllInstructionSets() { 4685 final String[] allAbis = Build.SUPPORTED_ABIS; 4686 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4687 4688 for (String abi : allAbis) { 4689 final String instructionSet = VMRuntime.getInstructionSet(abi); 4690 if (!allInstructionSets.contains(instructionSet)) { 4691 allInstructionSets.add(instructionSet); 4692 } 4693 } 4694 4695 return allInstructionSets; 4696 } 4697 4698 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4699 boolean inclDependencies) { 4700 HashSet<String> done; 4701 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4702 done = new HashSet<String>(); 4703 done.add(pkg.packageName); 4704 } else { 4705 done = null; 4706 } 4707 return performDexOptLI(pkg, null /* instruction set override */, forceDex, defer, done); 4708 } 4709 4710 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4711 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4712 Slog.w(TAG, "Unable to update from " + oldPkg.name 4713 + " to " + newPkg.packageName 4714 + ": old package not in system partition"); 4715 return false; 4716 } else if (mPackages.get(oldPkg.name) != null) { 4717 Slog.w(TAG, "Unable to update from " + oldPkg.name 4718 + " to " + newPkg.packageName 4719 + ": old package still exists"); 4720 return false; 4721 } 4722 return true; 4723 } 4724 4725 File getDataPathForUser(int userId) { 4726 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4727 } 4728 4729 private File getDataPathForPackage(String packageName, int userId) { 4730 /* 4731 * Until we fully support multiple users, return the directory we 4732 * previously would have. The PackageManagerTests will need to be 4733 * revised when this is changed back.. 4734 */ 4735 if (userId == 0) { 4736 return new File(mAppDataDir, packageName); 4737 } else { 4738 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4739 + File.separator + packageName); 4740 } 4741 } 4742 4743 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4744 int[] users = sUserManager.getUserIds(); 4745 int res = mInstaller.install(packageName, uid, uid, seinfo); 4746 if (res < 0) { 4747 return res; 4748 } 4749 for (int user : users) { 4750 if (user != 0) { 4751 res = mInstaller.createUserData(packageName, 4752 UserHandle.getUid(user, uid), user, seinfo); 4753 if (res < 0) { 4754 return res; 4755 } 4756 } 4757 } 4758 return res; 4759 } 4760 4761 private int removeDataDirsLI(String packageName) { 4762 int[] users = sUserManager.getUserIds(); 4763 int res = 0; 4764 for (int user : users) { 4765 int resInner = mInstaller.remove(packageName, user); 4766 if (resInner < 0) { 4767 res = resInner; 4768 } 4769 } 4770 4771 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4772 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4773 if (!nativeLibraryFile.delete()) { 4774 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4775 } 4776 4777 return res; 4778 } 4779 4780 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4781 PackageParser.Package changingLib) { 4782 if (file.path != null) { 4783 usesLibraryFiles.add(file.path); 4784 return; 4785 } 4786 PackageParser.Package p = mPackages.get(file.apk); 4787 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4788 // If we are doing this while in the middle of updating a library apk, 4789 // then we need to make sure to use that new apk for determining the 4790 // dependencies here. (We haven't yet finished committing the new apk 4791 // to the package manager state.) 4792 if (p == null || p.packageName.equals(changingLib.packageName)) { 4793 p = changingLib; 4794 } 4795 } 4796 if (p != null) { 4797 usesLibraryFiles.addAll(p.getAllCodePaths()); 4798 } 4799 } 4800 4801 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4802 PackageParser.Package changingLib) { 4803 // We might be upgrading from a version of the platform that did not 4804 // provide per-package native library directories for system apps. 4805 // Fix that up here. 4806 if (isSystemApp(pkg)) { 4807 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4808 setInternalAppNativeLibraryPath(pkg, ps); 4809 } 4810 4811 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4812 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4813 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4814 for (int i=0; i<N; i++) { 4815 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4816 if (file == null) { 4817 Slog.e(TAG, "Package " + pkg.packageName 4818 + " requires unavailable shared library " 4819 + pkg.usesLibraries.get(i) + "; failing!"); 4820 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4821 return false; 4822 } 4823 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4824 } 4825 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4826 for (int i=0; i<N; i++) { 4827 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4828 if (file == null) { 4829 Slog.w(TAG, "Package " + pkg.packageName 4830 + " desires unavailable shared library " 4831 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4832 } else { 4833 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4834 } 4835 } 4836 N = usesLibraryFiles.size(); 4837 if (N > 0) { 4838 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4839 } else { 4840 pkg.usesLibraryFiles = null; 4841 } 4842 } 4843 return true; 4844 } 4845 4846 private static boolean hasString(List<String> list, List<String> which) { 4847 if (list == null) { 4848 return false; 4849 } 4850 for (int i=list.size()-1; i>=0; i--) { 4851 for (int j=which.size()-1; j>=0; j--) { 4852 if (which.get(j).equals(list.get(i))) { 4853 return true; 4854 } 4855 } 4856 } 4857 return false; 4858 } 4859 4860 private void updateAllSharedLibrariesLPw() { 4861 for (PackageParser.Package pkg : mPackages.values()) { 4862 updateSharedLibrariesLPw(pkg, null); 4863 } 4864 } 4865 4866 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4867 PackageParser.Package changingPkg) { 4868 ArrayList<PackageParser.Package> res = null; 4869 for (PackageParser.Package pkg : mPackages.values()) { 4870 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4871 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4872 if (res == null) { 4873 res = new ArrayList<PackageParser.Package>(); 4874 } 4875 res.add(pkg); 4876 updateSharedLibrariesLPw(pkg, changingPkg); 4877 } 4878 } 4879 return res; 4880 } 4881 4882 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4883 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4884 final File scanFile = new File(pkg.codePath); 4885 if (pkg.applicationInfo.sourceDir == null || 4886 pkg.applicationInfo.publicSourceDir == null) { 4887 // Bail out. The resource and code paths haven't been set. 4888 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4889 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4890 return null; 4891 } 4892 4893 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4894 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4895 } 4896 4897 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4898 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4899 } 4900 4901 if (mCustomResolverComponentName != null && 4902 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4903 setUpCustomResolverActivity(pkg); 4904 } 4905 4906 if (pkg.packageName.equals("android")) { 4907 synchronized (mPackages) { 4908 if (mAndroidApplication != null) { 4909 Slog.w(TAG, "*************************************************"); 4910 Slog.w(TAG, "Core android package being redefined. Skipping."); 4911 Slog.w(TAG, " file=" + scanFile); 4912 Slog.w(TAG, "*************************************************"); 4913 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4914 return null; 4915 } 4916 4917 // Set up information for our fall-back user intent resolution activity. 4918 mPlatformPackage = pkg; 4919 pkg.mVersionCode = mSdkVersion; 4920 mAndroidApplication = pkg.applicationInfo; 4921 4922 if (!mResolverReplaced) { 4923 mResolveActivity.applicationInfo = mAndroidApplication; 4924 mResolveActivity.name = ResolverActivity.class.getName(); 4925 mResolveActivity.packageName = mAndroidApplication.packageName; 4926 mResolveActivity.processName = "system:ui"; 4927 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4928 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 4929 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4930 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 4931 mResolveActivity.exported = true; 4932 mResolveActivity.enabled = true; 4933 mResolveInfo.activityInfo = mResolveActivity; 4934 mResolveInfo.priority = 0; 4935 mResolveInfo.preferredOrder = 0; 4936 mResolveInfo.match = 0; 4937 mResolveComponentName = new ComponentName( 4938 mAndroidApplication.packageName, mResolveActivity.name); 4939 } 4940 } 4941 } 4942 4943 if (DEBUG_PACKAGE_SCANNING) { 4944 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4945 Log.d(TAG, "Scanning package " + pkg.packageName); 4946 } 4947 4948 if (mPackages.containsKey(pkg.packageName) 4949 || mSharedLibraries.containsKey(pkg.packageName)) { 4950 Slog.w(TAG, "Application package " + pkg.packageName 4951 + " already installed. Skipping duplicate."); 4952 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4953 return null; 4954 } 4955 4956 // Initialize package source and resource directories 4957 File destCodeFile = new File(pkg.applicationInfo.sourceDir); 4958 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir); 4959 4960 SharedUserSetting suid = null; 4961 PackageSetting pkgSetting = null; 4962 4963 if (!isSystemApp(pkg)) { 4964 // Only system apps can use these features. 4965 pkg.mOriginalPackages = null; 4966 pkg.mRealPackage = null; 4967 pkg.mAdoptPermissions = null; 4968 } 4969 4970 // writer 4971 synchronized (mPackages) { 4972 if (pkg.mSharedUserId != null) { 4973 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 4974 if (suid == null) { 4975 Slog.w(TAG, "Creating application package " + pkg.packageName 4976 + " for shared user failed"); 4977 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4978 return null; 4979 } 4980 if (DEBUG_PACKAGE_SCANNING) { 4981 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4982 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 4983 + "): packages=" + suid.packages); 4984 } 4985 } 4986 4987 // Check if we are renaming from an original package name. 4988 PackageSetting origPackage = null; 4989 String realName = null; 4990 if (pkg.mOriginalPackages != null) { 4991 // This package may need to be renamed to a previously 4992 // installed name. Let's check on that... 4993 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 4994 if (pkg.mOriginalPackages.contains(renamed)) { 4995 // This package had originally been installed as the 4996 // original name, and we have already taken care of 4997 // transitioning to the new one. Just update the new 4998 // one to continue using the old name. 4999 realName = pkg.mRealPackage; 5000 if (!pkg.packageName.equals(renamed)) { 5001 // Callers into this function may have already taken 5002 // care of renaming the package; only do it here if 5003 // it is not already done. 5004 pkg.setPackageName(renamed); 5005 } 5006 5007 } else { 5008 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5009 if ((origPackage = mSettings.peekPackageLPr( 5010 pkg.mOriginalPackages.get(i))) != null) { 5011 // We do have the package already installed under its 5012 // original name... should we use it? 5013 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5014 // New package is not compatible with original. 5015 origPackage = null; 5016 continue; 5017 } else if (origPackage.sharedUser != null) { 5018 // Make sure uid is compatible between packages. 5019 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5020 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5021 + " to " + pkg.packageName + ": old uid " 5022 + origPackage.sharedUser.name 5023 + " differs from " + pkg.mSharedUserId); 5024 origPackage = null; 5025 continue; 5026 } 5027 } else { 5028 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5029 + pkg.packageName + " to old name " + origPackage.name); 5030 } 5031 break; 5032 } 5033 } 5034 } 5035 } 5036 5037 if (mTransferedPackages.contains(pkg.packageName)) { 5038 Slog.w(TAG, "Package " + pkg.packageName 5039 + " was transferred to another, but its .apk remains"); 5040 } 5041 5042 // Just create the setting, don't add it yet. For already existing packages 5043 // the PkgSetting exists already and doesn't have to be created. 5044 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5045 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 5046 pkg.applicationInfo.cpuAbi, 5047 pkg.applicationInfo.flags, user, false); 5048 if (pkgSetting == null) { 5049 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 5050 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5051 return null; 5052 } 5053 5054 if (pkgSetting.origPackage != null) { 5055 // If we are first transitioning from an original package, 5056 // fix up the new package's name now. We need to do this after 5057 // looking up the package under its new name, so getPackageLP 5058 // can take care of fiddling things correctly. 5059 pkg.setPackageName(origPackage.name); 5060 5061 // File a report about this. 5062 String msg = "New package " + pkgSetting.realName 5063 + " renamed to replace old package " + pkgSetting.name; 5064 reportSettingsProblem(Log.WARN, msg); 5065 5066 // Make a note of it. 5067 mTransferedPackages.add(origPackage.name); 5068 5069 // No longer need to retain this. 5070 pkgSetting.origPackage = null; 5071 } 5072 5073 if (realName != null) { 5074 // Make a note of it. 5075 mTransferedPackages.add(pkg.packageName); 5076 } 5077 5078 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5079 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5080 } 5081 5082 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5083 // Check all shared libraries and map to their actual file path. 5084 // We only do this here for apps not on a system dir, because those 5085 // are the only ones that can fail an install due to this. We 5086 // will take care of the system apps by updating all of their 5087 // library paths after the scan is done. 5088 if (!updateSharedLibrariesLPw(pkg, null)) { 5089 return null; 5090 } 5091 } 5092 5093 if (mFoundPolicyFile) { 5094 SELinuxMMAC.assignSeinfoValue(pkg); 5095 } 5096 5097 pkg.applicationInfo.uid = pkgSetting.appId; 5098 pkg.mExtras = pkgSetting; 5099 5100 if (!verifySignaturesLP(pkgSetting, pkg)) { 5101 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5102 return null; 5103 } 5104 // The signature has changed, but this package is in the system 5105 // image... let's recover! 5106 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5107 // However... if this package is part of a shared user, but it 5108 // doesn't match the signature of the shared user, let's fail. 5109 // What this means is that you can't change the signatures 5110 // associated with an overall shared user, which doesn't seem all 5111 // that unreasonable. 5112 if (pkgSetting.sharedUser != null) { 5113 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5114 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5115 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 5116 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 5117 return null; 5118 } 5119 } 5120 // File a report about this. 5121 String msg = "System package " + pkg.packageName 5122 + " signature changed; retaining data."; 5123 reportSettingsProblem(Log.WARN, msg); 5124 } 5125 5126 // Verify that this new package doesn't have any content providers 5127 // that conflict with existing packages. Only do this if the 5128 // package isn't already installed, since we don't want to break 5129 // things that are installed. 5130 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5131 final int N = pkg.providers.size(); 5132 int i; 5133 for (i=0; i<N; i++) { 5134 PackageParser.Provider p = pkg.providers.get(i); 5135 if (p.info.authority != null) { 5136 String names[] = p.info.authority.split(";"); 5137 for (int j = 0; j < names.length; j++) { 5138 if (mProvidersByAuthority.containsKey(names[j])) { 5139 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5140 Slog.w(TAG, "Can't install because provider name " + names[j] + 5141 " (in package " + pkg.applicationInfo.packageName + 5142 ") is already used by " 5143 + ((other != null && other.getComponentName() != null) 5144 ? other.getComponentName().getPackageName() : "?")); 5145 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 5146 return null; 5147 } 5148 } 5149 } 5150 } 5151 } 5152 5153 if (pkg.mAdoptPermissions != null) { 5154 // This package wants to adopt ownership of permissions from 5155 // another package. 5156 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5157 final String origName = pkg.mAdoptPermissions.get(i); 5158 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5159 if (orig != null) { 5160 if (verifyPackageUpdateLPr(orig, pkg)) { 5161 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5162 + pkg.packageName); 5163 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5164 } 5165 } 5166 } 5167 } 5168 } 5169 5170 final String pkgName = pkg.packageName; 5171 5172 final long scanFileTime = scanFile.lastModified(); 5173 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5174 pkg.applicationInfo.processName = fixProcessName( 5175 pkg.applicationInfo.packageName, 5176 pkg.applicationInfo.processName, 5177 pkg.applicationInfo.uid); 5178 5179 File dataPath; 5180 if (mPlatformPackage == pkg) { 5181 // The system package is special. 5182 dataPath = new File (Environment.getDataDirectory(), "system"); 5183 pkg.applicationInfo.dataDir = dataPath.getPath(); 5184 } else { 5185 // This is a normal package, need to make its data directory. 5186 dataPath = getDataPathForPackage(pkg.packageName, 0); 5187 5188 boolean uidError = false; 5189 5190 if (dataPath.exists()) { 5191 int currentUid = 0; 5192 try { 5193 StructStat stat = Os.stat(dataPath.getPath()); 5194 currentUid = stat.st_uid; 5195 } catch (ErrnoException e) { 5196 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5197 } 5198 5199 // If we have mismatched owners for the data path, we have a problem. 5200 if (currentUid != pkg.applicationInfo.uid) { 5201 boolean recovered = false; 5202 if (currentUid == 0) { 5203 // The directory somehow became owned by root. Wow. 5204 // This is probably because the system was stopped while 5205 // installd was in the middle of messing with its libs 5206 // directory. Ask installd to fix that. 5207 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5208 pkg.applicationInfo.uid); 5209 if (ret >= 0) { 5210 recovered = true; 5211 String msg = "Package " + pkg.packageName 5212 + " unexpectedly changed to uid 0; recovered to " + 5213 + pkg.applicationInfo.uid; 5214 reportSettingsProblem(Log.WARN, msg); 5215 } 5216 } 5217 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5218 || (scanMode&SCAN_BOOTING) != 0)) { 5219 // If this is a system app, we can at least delete its 5220 // current data so the application will still work. 5221 int ret = removeDataDirsLI(pkgName); 5222 if (ret >= 0) { 5223 // TODO: Kill the processes first 5224 // Old data gone! 5225 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5226 ? "System package " : "Third party package "; 5227 String msg = prefix + pkg.packageName 5228 + " has changed from uid: " 5229 + currentUid + " to " 5230 + pkg.applicationInfo.uid + "; old data erased"; 5231 reportSettingsProblem(Log.WARN, msg); 5232 recovered = true; 5233 5234 // And now re-install the app. 5235 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5236 pkg.applicationInfo.seinfo); 5237 if (ret == -1) { 5238 // Ack should not happen! 5239 msg = prefix + pkg.packageName 5240 + " could not have data directory re-created after delete."; 5241 reportSettingsProblem(Log.WARN, msg); 5242 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5243 return null; 5244 } 5245 } 5246 if (!recovered) { 5247 mHasSystemUidErrors = true; 5248 } 5249 } else if (!recovered) { 5250 // If we allow this install to proceed, we will be broken. 5251 // Abort, abort! 5252 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 5253 return null; 5254 } 5255 if (!recovered) { 5256 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5257 + pkg.applicationInfo.uid + "/fs_" 5258 + currentUid; 5259 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5260 String msg = "Package " + pkg.packageName 5261 + " has mismatched uid: " 5262 + currentUid + " on disk, " 5263 + pkg.applicationInfo.uid + " in settings"; 5264 // writer 5265 synchronized (mPackages) { 5266 mSettings.mReadMessages.append(msg); 5267 mSettings.mReadMessages.append('\n'); 5268 uidError = true; 5269 if (!pkgSetting.uidError) { 5270 reportSettingsProblem(Log.ERROR, msg); 5271 } 5272 } 5273 } 5274 } 5275 pkg.applicationInfo.dataDir = dataPath.getPath(); 5276 if (mShouldRestoreconData) { 5277 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5278 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5279 pkg.applicationInfo.uid); 5280 } 5281 } else { 5282 if (DEBUG_PACKAGE_SCANNING) { 5283 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5284 Log.v(TAG, "Want this data dir: " + dataPath); 5285 } 5286 //invoke installer to do the actual installation 5287 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5288 pkg.applicationInfo.seinfo); 5289 if (ret < 0) { 5290 // Error from installer 5291 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5292 return null; 5293 } 5294 5295 if (dataPath.exists()) { 5296 pkg.applicationInfo.dataDir = dataPath.getPath(); 5297 } else { 5298 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5299 pkg.applicationInfo.dataDir = null; 5300 } 5301 } 5302 5303 /* 5304 * Set the data dir to the default "/data/data/<package name>/lib" 5305 * if we got here without anyone telling us different (e.g., apps 5306 * stored on SD card have their native libraries stored in the ASEC 5307 * container with the APK). 5308 * 5309 * This happens during an upgrade from a package settings file that 5310 * doesn't have a native library path attribute at all. 5311 */ 5312 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 5313 if (pkgSetting.nativeLibraryPathString == null) { 5314 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5315 } else { 5316 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 5317 } 5318 } 5319 pkgSetting.uidError = uidError; 5320 } 5321 5322 final String path = scanFile.getPath(); 5323 /* Note: We don't want to unpack the native binaries for 5324 * system applications, unless they have been updated 5325 * (the binaries are already under /system/lib). 5326 * Also, don't unpack libs for apps on the external card 5327 * since they should have their libraries in the ASEC 5328 * container already. 5329 * 5330 * In other words, we're going to unpack the binaries 5331 * only for non-system apps and system app upgrades. 5332 */ 5333 if (pkg.applicationInfo.nativeLibraryDir != null) { 5334 // TODO: extend to extract native code from split APKs 5335 ApkHandle handle = null; 5336 try { 5337 handle = ApkHandle.create(scanFile.getPath()); 5338 // Enable gross and lame hacks for apps that are built with old 5339 // SDK tools. We must scan their APKs for renderscript bitcode and 5340 // not launch them if it's present. Don't bother checking on devices 5341 // that don't have 64 bit support. 5342 String[] abiList = Build.SUPPORTED_ABIS; 5343 boolean hasLegacyRenderscriptBitcode = false; 5344 if (abiOverride != null) { 5345 abiList = new String[] { abiOverride }; 5346 } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 5347 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5348 abiList = Build.SUPPORTED_32_BIT_ABIS; 5349 hasLegacyRenderscriptBitcode = true; 5350 } 5351 5352 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5353 final String dataPathString = dataPath.getCanonicalPath(); 5354 5355 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5356 /* 5357 * Upgrading from a previous version of the OS sometimes 5358 * leaves native libraries in the /data/data/<app>/lib 5359 * directory for system apps even when they shouldn't be. 5360 * Recent changes in the JNI library search path 5361 * necessitates we remove those to match previous behavior. 5362 */ 5363 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 5364 Log.i(TAG, "removed obsolete native libraries for system package " 5365 + path); 5366 } 5367 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5368 pkg.applicationInfo.cpuAbi = abiList[0]; 5369 pkgSetting.cpuAbiString = abiList[0]; 5370 } else { 5371 setInternalAppAbi(pkg, pkgSetting); 5372 } 5373 } else { 5374 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 5375 /* 5376 * Update native library dir if it starts with 5377 * /data/data 5378 */ 5379 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 5380 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5381 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5382 } 5383 5384 try { 5385 int copyRet = copyNativeLibrariesForInternalApp(handle, 5386 nativeLibraryDir, abiList); 5387 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5388 Slog.e(TAG, "Unable to copy native libraries"); 5389 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5390 return null; 5391 } 5392 5393 // We've successfully copied native libraries across, so we make a 5394 // note of what ABI we're using 5395 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5396 pkg.applicationInfo.cpuAbi = abiList[copyRet]; 5397 } else if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5398 pkg.applicationInfo.cpuAbi = abiList[0]; 5399 } else { 5400 pkg.applicationInfo.cpuAbi = null; 5401 } 5402 } catch (IOException e) { 5403 Slog.e(TAG, "Unable to copy native libraries", e); 5404 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5405 return null; 5406 } 5407 } else { 5408 // We don't have to copy the shared libraries if we're in the ASEC container 5409 // but we still need to scan the file to figure out what ABI the app needs. 5410 // 5411 // TODO: This duplicates work done in the default container service. It's possible 5412 // to clean this up but we'll need to change the interface between this service 5413 // and IMediaContainerService (but doing so will spread this logic out, rather 5414 // than centralizing it). 5415 final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5416 if (abi >= 0) { 5417 pkg.applicationInfo.cpuAbi = abiList[abi]; 5418 } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) { 5419 // Note that (non upgraded) system apps will not have any native 5420 // libraries bundled in their APK, but we're guaranteed not to be 5421 // such an app at this point. 5422 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5423 pkg.applicationInfo.cpuAbi = abiList[0]; 5424 } else { 5425 pkg.applicationInfo.cpuAbi = null; 5426 } 5427 } else { 5428 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5429 return null; 5430 } 5431 } 5432 5433 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5434 final int[] userIds = sUserManager.getUserIds(); 5435 synchronized (mInstallLock) { 5436 for (int userId : userIds) { 5437 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 5438 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 5439 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5440 + ")"); 5441 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5442 return null; 5443 } 5444 } 5445 } 5446 } 5447 5448 pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi; 5449 } catch (IOException ioe) { 5450 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5451 } finally { 5452 IoUtils.closeQuietly(handle); 5453 } 5454 } 5455 5456 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5457 // We don't do this here during boot because we can do it all 5458 // at once after scanning all existing packages. 5459 // 5460 // We also do this *before* we perform dexopt on this package, so that 5461 // we can avoid redundant dexopts, and also to make sure we've got the 5462 // code and package path correct. 5463 if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5464 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) { 5465 mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE; 5466 return null; 5467 } 5468 } 5469 5470 if ((scanMode&SCAN_NO_DEX) == 0) { 5471 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5472 == DEX_OPT_FAILED) { 5473 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5474 removeDataDirsLI(pkg.packageName); 5475 } 5476 5477 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5478 return null; 5479 } 5480 } 5481 5482 if (mFactoryTest && pkg.requestedPermissions.contains( 5483 android.Manifest.permission.FACTORY_TEST)) { 5484 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5485 } 5486 5487 ArrayList<PackageParser.Package> clientLibPkgs = null; 5488 5489 // writer 5490 synchronized (mPackages) { 5491 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5492 // Only system apps can add new shared libraries. 5493 if (pkg.libraryNames != null) { 5494 for (int i=0; i<pkg.libraryNames.size(); i++) { 5495 String name = pkg.libraryNames.get(i); 5496 boolean allowed = false; 5497 if (isUpdatedSystemApp(pkg)) { 5498 // New library entries can only be added through the 5499 // system image. This is important to get rid of a lot 5500 // of nasty edge cases: for example if we allowed a non- 5501 // system update of the app to add a library, then uninstalling 5502 // the update would make the library go away, and assumptions 5503 // we made such as through app install filtering would now 5504 // have allowed apps on the device which aren't compatible 5505 // with it. Better to just have the restriction here, be 5506 // conservative, and create many fewer cases that can negatively 5507 // impact the user experience. 5508 final PackageSetting sysPs = mSettings 5509 .getDisabledSystemPkgLPr(pkg.packageName); 5510 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5511 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5512 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5513 allowed = true; 5514 allowed = true; 5515 break; 5516 } 5517 } 5518 } 5519 } else { 5520 allowed = true; 5521 } 5522 if (allowed) { 5523 if (!mSharedLibraries.containsKey(name)) { 5524 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5525 } else if (!name.equals(pkg.packageName)) { 5526 Slog.w(TAG, "Package " + pkg.packageName + " library " 5527 + name + " already exists; skipping"); 5528 } 5529 } else { 5530 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5531 + name + " that is not declared on system image; skipping"); 5532 } 5533 } 5534 if ((scanMode&SCAN_BOOTING) == 0) { 5535 // If we are not booting, we need to update any applications 5536 // that are clients of our shared library. If we are booting, 5537 // this will all be done once the scan is complete. 5538 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5539 } 5540 } 5541 } 5542 } 5543 5544 // We also need to dexopt any apps that are dependent on this library. Note that 5545 // if these fail, we should abort the install since installing the library will 5546 // result in some apps being broken. 5547 if (clientLibPkgs != null) { 5548 if ((scanMode&SCAN_NO_DEX) == 0) { 5549 for (int i=0; i<clientLibPkgs.size(); i++) { 5550 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5551 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5552 == DEX_OPT_FAILED) { 5553 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5554 removeDataDirsLI(pkg.packageName); 5555 } 5556 5557 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5558 return null; 5559 } 5560 } 5561 } 5562 } 5563 5564 // Request the ActivityManager to kill the process(only for existing packages) 5565 // so that we do not end up in a confused state while the user is still using the older 5566 // version of the application while the new one gets installed. 5567 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5568 // If the package lives in an asec, tell everyone that the container is going 5569 // away so they can clean up any references to its resources (which would prevent 5570 // vold from being able to unmount the asec) 5571 if (isForwardLocked(pkg) || isExternal(pkg)) { 5572 if (DEBUG_INSTALL) { 5573 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5574 } 5575 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5576 final ArrayList<String> pkgList = new ArrayList<String>(1); 5577 pkgList.add(pkg.applicationInfo.packageName); 5578 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5579 } 5580 5581 // Post the request that it be killed now that the going-away broadcast is en route 5582 killApplication(pkg.applicationInfo.packageName, 5583 pkg.applicationInfo.uid, "update pkg"); 5584 } 5585 5586 // Also need to kill any apps that are dependent on the library. 5587 if (clientLibPkgs != null) { 5588 for (int i=0; i<clientLibPkgs.size(); i++) { 5589 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5590 killApplication(clientPkg.applicationInfo.packageName, 5591 clientPkg.applicationInfo.uid, "update lib"); 5592 } 5593 } 5594 5595 // writer 5596 synchronized (mPackages) { 5597 // We don't expect installation to fail beyond this point, 5598 if ((scanMode&SCAN_MONITOR) != 0) { 5599 mAppDirs.put(pkg.codePath, pkg); 5600 } 5601 // Add the new setting to mSettings 5602 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5603 // Add the new setting to mPackages 5604 mPackages.put(pkg.applicationInfo.packageName, pkg); 5605 // Make sure we don't accidentally delete its data. 5606 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5607 while (iter.hasNext()) { 5608 PackageCleanItem item = iter.next(); 5609 if (pkgName.equals(item.packageName)) { 5610 iter.remove(); 5611 } 5612 } 5613 5614 // Take care of first install / last update times. 5615 if (currentTime != 0) { 5616 if (pkgSetting.firstInstallTime == 0) { 5617 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5618 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5619 pkgSetting.lastUpdateTime = currentTime; 5620 } 5621 } else if (pkgSetting.firstInstallTime == 0) { 5622 // We need *something*. Take time time stamp of the file. 5623 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5624 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5625 if (scanFileTime != pkgSetting.timeStamp) { 5626 // A package on the system image has changed; consider this 5627 // to be an update. 5628 pkgSetting.lastUpdateTime = scanFileTime; 5629 } 5630 } 5631 5632 // Add the package's KeySets to the global KeySetManager 5633 KeySetManager ksm = mSettings.mKeySetManager; 5634 try { 5635 ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5636 if (pkg.mKeySetMapping != null) { 5637 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5638 pkg.mKeySetMapping.entrySet()) { 5639 if (entry.getValue() != null) { 5640 ksm.addDefinedKeySetToPackage(pkg.packageName, 5641 entry.getValue(), entry.getKey()); 5642 } 5643 } 5644 } 5645 } catch (NullPointerException e) { 5646 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5647 } catch (IllegalArgumentException e) { 5648 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5649 } 5650 5651 int N = pkg.providers.size(); 5652 StringBuilder r = null; 5653 int i; 5654 for (i=0; i<N; i++) { 5655 PackageParser.Provider p = pkg.providers.get(i); 5656 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5657 p.info.processName, pkg.applicationInfo.uid); 5658 mProviders.addProvider(p); 5659 p.syncable = p.info.isSyncable; 5660 if (p.info.authority != null) { 5661 String names[] = p.info.authority.split(";"); 5662 p.info.authority = null; 5663 for (int j = 0; j < names.length; j++) { 5664 if (j == 1 && p.syncable) { 5665 // We only want the first authority for a provider to possibly be 5666 // syncable, so if we already added this provider using a different 5667 // authority clear the syncable flag. We copy the provider before 5668 // changing it because the mProviders object contains a reference 5669 // to a provider that we don't want to change. 5670 // Only do this for the second authority since the resulting provider 5671 // object can be the same for all future authorities for this provider. 5672 p = new PackageParser.Provider(p); 5673 p.syncable = false; 5674 } 5675 if (!mProvidersByAuthority.containsKey(names[j])) { 5676 mProvidersByAuthority.put(names[j], p); 5677 if (p.info.authority == null) { 5678 p.info.authority = names[j]; 5679 } else { 5680 p.info.authority = p.info.authority + ";" + names[j]; 5681 } 5682 if (DEBUG_PACKAGE_SCANNING) { 5683 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5684 Log.d(TAG, "Registered content provider: " + names[j] 5685 + ", className = " + p.info.name + ", isSyncable = " 5686 + p.info.isSyncable); 5687 } 5688 } else { 5689 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5690 Slog.w(TAG, "Skipping provider name " + names[j] + 5691 " (in package " + pkg.applicationInfo.packageName + 5692 "): name already used by " 5693 + ((other != null && other.getComponentName() != null) 5694 ? other.getComponentName().getPackageName() : "?")); 5695 } 5696 } 5697 } 5698 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5699 if (r == null) { 5700 r = new StringBuilder(256); 5701 } else { 5702 r.append(' '); 5703 } 5704 r.append(p.info.name); 5705 } 5706 } 5707 if (r != null) { 5708 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5709 } 5710 5711 N = pkg.services.size(); 5712 r = null; 5713 for (i=0; i<N; i++) { 5714 PackageParser.Service s = pkg.services.get(i); 5715 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5716 s.info.processName, pkg.applicationInfo.uid); 5717 mServices.addService(s); 5718 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5719 if (r == null) { 5720 r = new StringBuilder(256); 5721 } else { 5722 r.append(' '); 5723 } 5724 r.append(s.info.name); 5725 } 5726 } 5727 if (r != null) { 5728 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5729 } 5730 5731 N = pkg.receivers.size(); 5732 r = null; 5733 for (i=0; i<N; i++) { 5734 PackageParser.Activity a = pkg.receivers.get(i); 5735 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5736 a.info.processName, pkg.applicationInfo.uid); 5737 mReceivers.addActivity(a, "receiver"); 5738 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5739 if (r == null) { 5740 r = new StringBuilder(256); 5741 } else { 5742 r.append(' '); 5743 } 5744 r.append(a.info.name); 5745 } 5746 } 5747 if (r != null) { 5748 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5749 } 5750 5751 N = pkg.activities.size(); 5752 r = null; 5753 for (i=0; i<N; i++) { 5754 PackageParser.Activity a = pkg.activities.get(i); 5755 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5756 a.info.processName, pkg.applicationInfo.uid); 5757 mActivities.addActivity(a, "activity"); 5758 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5759 if (r == null) { 5760 r = new StringBuilder(256); 5761 } else { 5762 r.append(' '); 5763 } 5764 r.append(a.info.name); 5765 } 5766 } 5767 if (r != null) { 5768 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5769 } 5770 5771 N = pkg.permissionGroups.size(); 5772 r = null; 5773 for (i=0; i<N; i++) { 5774 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5775 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5776 if (cur == null) { 5777 mPermissionGroups.put(pg.info.name, pg); 5778 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5779 if (r == null) { 5780 r = new StringBuilder(256); 5781 } else { 5782 r.append(' '); 5783 } 5784 r.append(pg.info.name); 5785 } 5786 } else { 5787 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5788 + pg.info.packageName + " ignored: original from " 5789 + cur.info.packageName); 5790 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5791 if (r == null) { 5792 r = new StringBuilder(256); 5793 } else { 5794 r.append(' '); 5795 } 5796 r.append("DUP:"); 5797 r.append(pg.info.name); 5798 } 5799 } 5800 } 5801 if (r != null) { 5802 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5803 } 5804 5805 N = pkg.permissions.size(); 5806 r = null; 5807 for (i=0; i<N; i++) { 5808 PackageParser.Permission p = pkg.permissions.get(i); 5809 HashMap<String, BasePermission> permissionMap = 5810 p.tree ? mSettings.mPermissionTrees 5811 : mSettings.mPermissions; 5812 p.group = mPermissionGroups.get(p.info.group); 5813 if (p.info.group == null || p.group != null) { 5814 BasePermission bp = permissionMap.get(p.info.name); 5815 if (bp == null) { 5816 bp = new BasePermission(p.info.name, p.info.packageName, 5817 BasePermission.TYPE_NORMAL); 5818 permissionMap.put(p.info.name, bp); 5819 } 5820 if (bp.perm == null) { 5821 if (bp.sourcePackage != null 5822 && !bp.sourcePackage.equals(p.info.packageName)) { 5823 // If this is a permission that was formerly defined by a non-system 5824 // app, but is now defined by a system app (following an upgrade), 5825 // discard the previous declaration and consider the system's to be 5826 // canonical. 5827 if (isSystemApp(p.owner)) { 5828 String msg = "New decl " + p.owner + " of permission " 5829 + p.info.name + " is system"; 5830 reportSettingsProblem(Log.WARN, msg); 5831 bp.sourcePackage = null; 5832 } 5833 } 5834 if (bp.sourcePackage == null 5835 || bp.sourcePackage.equals(p.info.packageName)) { 5836 BasePermission tree = findPermissionTreeLP(p.info.name); 5837 if (tree == null 5838 || tree.sourcePackage.equals(p.info.packageName)) { 5839 bp.packageSetting = pkgSetting; 5840 bp.perm = p; 5841 bp.uid = pkg.applicationInfo.uid; 5842 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5843 if (r == null) { 5844 r = new StringBuilder(256); 5845 } else { 5846 r.append(' '); 5847 } 5848 r.append(p.info.name); 5849 } 5850 } else { 5851 Slog.w(TAG, "Permission " + p.info.name + " from package " 5852 + p.info.packageName + " ignored: base tree " 5853 + tree.name + " is from package " 5854 + tree.sourcePackage); 5855 } 5856 } else { 5857 Slog.w(TAG, "Permission " + p.info.name + " from package " 5858 + p.info.packageName + " ignored: original from " 5859 + bp.sourcePackage); 5860 } 5861 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5862 if (r == null) { 5863 r = new StringBuilder(256); 5864 } else { 5865 r.append(' '); 5866 } 5867 r.append("DUP:"); 5868 r.append(p.info.name); 5869 } 5870 if (bp.perm == p) { 5871 bp.protectionLevel = p.info.protectionLevel; 5872 } 5873 } else { 5874 Slog.w(TAG, "Permission " + p.info.name + " from package " 5875 + p.info.packageName + " ignored: no group " 5876 + p.group); 5877 } 5878 } 5879 if (r != null) { 5880 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5881 } 5882 5883 N = pkg.instrumentation.size(); 5884 r = null; 5885 for (i=0; i<N; i++) { 5886 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5887 a.info.packageName = pkg.applicationInfo.packageName; 5888 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5889 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5890 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 5891 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 5892 a.info.dataDir = pkg.applicationInfo.dataDir; 5893 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5894 mInstrumentation.put(a.getComponentName(), a); 5895 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5896 if (r == null) { 5897 r = new StringBuilder(256); 5898 } else { 5899 r.append(' '); 5900 } 5901 r.append(a.info.name); 5902 } 5903 } 5904 if (r != null) { 5905 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5906 } 5907 5908 if (pkg.protectedBroadcasts != null) { 5909 N = pkg.protectedBroadcasts.size(); 5910 for (i=0; i<N; i++) { 5911 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5912 } 5913 } 5914 5915 pkgSetting.setTimeStamp(scanFileTime); 5916 5917 // Create idmap files for pairs of (packages, overlay packages). 5918 // Note: "android", ie framework-res.apk, is handled by native layers. 5919 if (pkg.mOverlayTarget != null) { 5920 // This is an overlay package. 5921 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 5922 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 5923 mOverlays.put(pkg.mOverlayTarget, 5924 new HashMap<String, PackageParser.Package>()); 5925 } 5926 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 5927 map.put(pkg.packageName, pkg); 5928 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 5929 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 5930 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5931 return null; 5932 } 5933 } 5934 } else if (mOverlays.containsKey(pkg.packageName) && 5935 !pkg.packageName.equals("android")) { 5936 // This is a regular package, with one or more known overlay packages. 5937 createIdmapsForPackageLI(pkg); 5938 } 5939 } 5940 5941 return pkg; 5942 } 5943 5944 /** 5945 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 5946 * i.e, so that all packages can be run inside a single process if required. 5947 * 5948 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 5949 * this function will either try and make the ABI for all packages in {@code packagesForUser} 5950 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 5951 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 5952 * updating a package that belongs to a shared user. 5953 */ 5954 private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 5955 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 5956 String requiredInstructionSet = null; 5957 if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) { 5958 requiredInstructionSet = VMRuntime.getInstructionSet( 5959 scannedPackage.applicationInfo.cpuAbi); 5960 } 5961 5962 PackageSetting requirer = null; 5963 for (PackageSetting ps : packagesForUser) { 5964 // If packagesForUser contains scannedPackage, we skip it. This will happen 5965 // when scannedPackage is an update of an existing package. Without this check, 5966 // we will never be able to change the ABI of any package belonging to a shared 5967 // user, even if it's compatible with other packages. 5968 if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) { 5969 if (ps.cpuAbiString == null) { 5970 continue; 5971 } 5972 5973 final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 5974 if (requiredInstructionSet != null) { 5975 if (!instructionSet.equals(requiredInstructionSet)) { 5976 // We have a mismatch between instruction sets (say arm vs arm64). 5977 // bail out. 5978 String errorMessage = "Instruction set mismatch, " 5979 + ((requirer == null) ? "[caller]" : requirer) 5980 + " requires " + requiredInstructionSet + " whereas " + ps 5981 + " requires " + instructionSet; 5982 Slog.e(TAG, errorMessage); 5983 5984 reportSettingsProblem(Log.WARN, errorMessage); 5985 // Give up, don't bother making any other changes to the package settings. 5986 return false; 5987 } 5988 } else { 5989 requiredInstructionSet = instructionSet; 5990 requirer = ps; 5991 } 5992 } 5993 } 5994 5995 if (requiredInstructionSet != null) { 5996 String adjustedAbi; 5997 if (requirer != null) { 5998 // requirer != null implies that either scannedPackage was null or that scannedPackage 5999 // did not require an ABI, in which case we have to adjust scannedPackage to match 6000 // the ABI of the set (which is the same as requirer's ABI) 6001 adjustedAbi = requirer.cpuAbiString; 6002 if (scannedPackage != null) { 6003 scannedPackage.applicationInfo.cpuAbi = adjustedAbi; 6004 } 6005 } else { 6006 // requirer == null implies that we're updating all ABIs in the set to 6007 // match scannedPackage. 6008 adjustedAbi = scannedPackage.applicationInfo.cpuAbi; 6009 } 6010 6011 for (PackageSetting ps : packagesForUser) { 6012 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6013 if (ps.cpuAbiString != null) { 6014 continue; 6015 } 6016 6017 ps.cpuAbiString = adjustedAbi; 6018 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6019 ps.pkg.applicationInfo.cpuAbi = adjustedAbi; 6020 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6021 6022 if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) { 6023 ps.cpuAbiString = null; 6024 ps.pkg.applicationInfo.cpuAbi = null; 6025 return false; 6026 } else { 6027 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6028 } 6029 } 6030 } 6031 } 6032 } 6033 6034 return true; 6035 } 6036 6037 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6038 synchronized (mPackages) { 6039 mResolverReplaced = true; 6040 // Set up information for custom user intent resolution activity. 6041 mResolveActivity.applicationInfo = pkg.applicationInfo; 6042 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6043 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6044 mResolveActivity.processName = null; 6045 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6046 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6047 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6048 mResolveActivity.theme = 0; 6049 mResolveActivity.exported = true; 6050 mResolveActivity.enabled = true; 6051 mResolveInfo.activityInfo = mResolveActivity; 6052 mResolveInfo.priority = 0; 6053 mResolveInfo.preferredOrder = 0; 6054 mResolveInfo.match = 0; 6055 mResolveComponentName = mCustomResolverComponentName; 6056 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6057 mResolveComponentName); 6058 } 6059 } 6060 6061 private String calculateApkRoot(final String codePathString) { 6062 final File codePath = new File(codePathString); 6063 final File codeRoot; 6064 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6065 codeRoot = Environment.getRootDirectory(); 6066 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6067 codeRoot = Environment.getOemDirectory(); 6068 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6069 codeRoot = Environment.getVendorDirectory(); 6070 } else { 6071 // Unrecognized code path; take its top real segment as the apk root: 6072 // e.g. /something/app/blah.apk => /something 6073 try { 6074 File f = codePath.getCanonicalFile(); 6075 File parent = f.getParentFile(); // non-null because codePath is a file 6076 File tmp; 6077 while ((tmp = parent.getParentFile()) != null) { 6078 f = parent; 6079 parent = tmp; 6080 } 6081 codeRoot = f; 6082 Slog.w(TAG, "Unrecognized code path " 6083 + codePath + " - using " + codeRoot); 6084 } catch (IOException e) { 6085 // Can't canonicalize the lib path -- shenanigans? 6086 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6087 return Environment.getRootDirectory().getPath(); 6088 } 6089 } 6090 return codeRoot.getPath(); 6091 } 6092 6093 // This is the initial scan-time determination of how to handle a given 6094 // package for purposes of native library location. 6095 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 6096 PackageSetting pkgSetting) { 6097 // "bundled" here means system-installed with no overriding update 6098 final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg); 6099 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 6100 final File libDir; 6101 if (bundledApk) { 6102 // If "/system/lib64/apkname" exists, assume that is the per-package 6103 // native library directory to use; otherwise use "/system/lib/apkname". 6104 String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6105 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 6106 File packLib64 = new File(lib64, apkName); 6107 libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 6108 } else { 6109 libDir = mAppLibInstallDir; 6110 } 6111 final String nativeLibraryPath = (new File(libDir, apkName)).getPath(); 6112 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 6113 // pkgSetting might be null during rescan following uninstall of updates 6114 // to a bundled app, so accommodate that possibility. The settings in 6115 // that case will be established later from the parsed package. 6116 if (pkgSetting != null) { 6117 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 6118 } 6119 } 6120 6121 // Deduces the required ABI of an upgraded system app. 6122 private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) { 6123 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6124 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 6125 6126 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 6127 // or similar. 6128 final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath()); 6129 final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath()); 6130 6131 // Assume that the bundled native libraries always correspond to the 6132 // most preferred 32 or 64 bit ABI. 6133 if (lib64.exists()) { 6134 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6135 pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0]; 6136 } else if (lib.exists()) { 6137 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6138 pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0]; 6139 } else { 6140 // This is the case where the app has no native code. 6141 pkg.applicationInfo.cpuAbi = null; 6142 pkgSetting.cpuAbiString = null; 6143 } 6144 } 6145 6146 private static int copyNativeLibrariesForInternalApp(ApkHandle handle, 6147 final File nativeLibraryDir, String[] abiList) throws IOException { 6148 if (!nativeLibraryDir.isDirectory()) { 6149 nativeLibraryDir.delete(); 6150 6151 if (!nativeLibraryDir.mkdir()) { 6152 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 6153 } 6154 6155 try { 6156 Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6157 } catch (ErrnoException e) { 6158 throw new IOException("Cannot chmod native library directory " 6159 + nativeLibraryDir.getPath(), e); 6160 } 6161 } else if (!SELinux.restorecon(nativeLibraryDir)) { 6162 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 6163 } 6164 6165 /* 6166 * If this is an internal application or our nativeLibraryPath points to 6167 * the app-lib directory, unpack the libraries if necessary. 6168 */ 6169 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6170 if (abi >= 0) { 6171 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 6172 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 6173 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6174 return copyRet; 6175 } 6176 } 6177 6178 return abi; 6179 } 6180 6181 private void killApplication(String pkgName, int appId, String reason) { 6182 // Request the ActivityManager to kill the process(only for existing packages) 6183 // so that we do not end up in a confused state while the user is still using the older 6184 // version of the application while the new one gets installed. 6185 IActivityManager am = ActivityManagerNative.getDefault(); 6186 if (am != null) { 6187 try { 6188 am.killApplicationWithAppId(pkgName, appId, reason); 6189 } catch (RemoteException e) { 6190 } 6191 } 6192 } 6193 6194 void removePackageLI(PackageSetting ps, boolean chatty) { 6195 if (DEBUG_INSTALL) { 6196 if (chatty) 6197 Log.d(TAG, "Removing package " + ps.name); 6198 } 6199 6200 // writer 6201 synchronized (mPackages) { 6202 mPackages.remove(ps.name); 6203 if (ps.codePathString != null) { 6204 mAppDirs.remove(ps.codePathString); 6205 } 6206 6207 final PackageParser.Package pkg = ps.pkg; 6208 if (pkg != null) { 6209 cleanPackageDataStructuresLILPw(pkg, chatty); 6210 } 6211 } 6212 } 6213 6214 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6215 if (DEBUG_INSTALL) { 6216 if (chatty) 6217 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6218 } 6219 6220 // writer 6221 synchronized (mPackages) { 6222 mPackages.remove(pkg.applicationInfo.packageName); 6223 if (pkg.codePath != null) { 6224 mAppDirs.remove(pkg.codePath); 6225 } 6226 cleanPackageDataStructuresLILPw(pkg, chatty); 6227 } 6228 } 6229 6230 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6231 int N = pkg.providers.size(); 6232 StringBuilder r = null; 6233 int i; 6234 for (i=0; i<N; i++) { 6235 PackageParser.Provider p = pkg.providers.get(i); 6236 mProviders.removeProvider(p); 6237 if (p.info.authority == null) { 6238 6239 /* There was another ContentProvider with this authority when 6240 * this app was installed so this authority is null, 6241 * Ignore it as we don't have to unregister the provider. 6242 */ 6243 continue; 6244 } 6245 String names[] = p.info.authority.split(";"); 6246 for (int j = 0; j < names.length; j++) { 6247 if (mProvidersByAuthority.get(names[j]) == p) { 6248 mProvidersByAuthority.remove(names[j]); 6249 if (DEBUG_REMOVE) { 6250 if (chatty) 6251 Log.d(TAG, "Unregistered content provider: " + names[j] 6252 + ", className = " + p.info.name + ", isSyncable = " 6253 + p.info.isSyncable); 6254 } 6255 } 6256 } 6257 if (DEBUG_REMOVE && chatty) { 6258 if (r == null) { 6259 r = new StringBuilder(256); 6260 } else { 6261 r.append(' '); 6262 } 6263 r.append(p.info.name); 6264 } 6265 } 6266 if (r != null) { 6267 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6268 } 6269 6270 N = pkg.services.size(); 6271 r = null; 6272 for (i=0; i<N; i++) { 6273 PackageParser.Service s = pkg.services.get(i); 6274 mServices.removeService(s); 6275 if (chatty) { 6276 if (r == null) { 6277 r = new StringBuilder(256); 6278 } else { 6279 r.append(' '); 6280 } 6281 r.append(s.info.name); 6282 } 6283 } 6284 if (r != null) { 6285 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6286 } 6287 6288 N = pkg.receivers.size(); 6289 r = null; 6290 for (i=0; i<N; i++) { 6291 PackageParser.Activity a = pkg.receivers.get(i); 6292 mReceivers.removeActivity(a, "receiver"); 6293 if (DEBUG_REMOVE && chatty) { 6294 if (r == null) { 6295 r = new StringBuilder(256); 6296 } else { 6297 r.append(' '); 6298 } 6299 r.append(a.info.name); 6300 } 6301 } 6302 if (r != null) { 6303 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6304 } 6305 6306 N = pkg.activities.size(); 6307 r = null; 6308 for (i=0; i<N; i++) { 6309 PackageParser.Activity a = pkg.activities.get(i); 6310 mActivities.removeActivity(a, "activity"); 6311 if (DEBUG_REMOVE && chatty) { 6312 if (r == null) { 6313 r = new StringBuilder(256); 6314 } else { 6315 r.append(' '); 6316 } 6317 r.append(a.info.name); 6318 } 6319 } 6320 if (r != null) { 6321 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6322 } 6323 6324 N = pkg.permissions.size(); 6325 r = null; 6326 for (i=0; i<N; i++) { 6327 PackageParser.Permission p = pkg.permissions.get(i); 6328 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6329 if (bp == null) { 6330 bp = mSettings.mPermissionTrees.get(p.info.name); 6331 } 6332 if (bp != null && bp.perm == p) { 6333 bp.perm = null; 6334 if (DEBUG_REMOVE && chatty) { 6335 if (r == null) { 6336 r = new StringBuilder(256); 6337 } else { 6338 r.append(' '); 6339 } 6340 r.append(p.info.name); 6341 } 6342 } 6343 } 6344 if (r != null) { 6345 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6346 } 6347 6348 N = pkg.instrumentation.size(); 6349 r = null; 6350 for (i=0; i<N; i++) { 6351 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6352 mInstrumentation.remove(a.getComponentName()); 6353 if (DEBUG_REMOVE && chatty) { 6354 if (r == null) { 6355 r = new StringBuilder(256); 6356 } else { 6357 r.append(' '); 6358 } 6359 r.append(a.info.name); 6360 } 6361 } 6362 if (r != null) { 6363 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6364 } 6365 6366 r = null; 6367 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6368 // Only system apps can hold shared libraries. 6369 if (pkg.libraryNames != null) { 6370 for (i=0; i<pkg.libraryNames.size(); i++) { 6371 String name = pkg.libraryNames.get(i); 6372 SharedLibraryEntry cur = mSharedLibraries.get(name); 6373 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6374 mSharedLibraries.remove(name); 6375 if (DEBUG_REMOVE && chatty) { 6376 if (r == null) { 6377 r = new StringBuilder(256); 6378 } else { 6379 r.append(' '); 6380 } 6381 r.append(name); 6382 } 6383 } 6384 } 6385 } 6386 } 6387 if (r != null) { 6388 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6389 } 6390 } 6391 6392 private static final boolean isPackageFilename(String name) { 6393 return name != null && name.endsWith(".apk"); 6394 } 6395 6396 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6397 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6398 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6399 return true; 6400 } 6401 } 6402 return false; 6403 } 6404 6405 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6406 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6407 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6408 6409 private void updatePermissionsLPw(String changingPkg, 6410 PackageParser.Package pkgInfo, int flags) { 6411 // Make sure there are no dangling permission trees. 6412 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6413 while (it.hasNext()) { 6414 final BasePermission bp = it.next(); 6415 if (bp.packageSetting == null) { 6416 // We may not yet have parsed the package, so just see if 6417 // we still know about its settings. 6418 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6419 } 6420 if (bp.packageSetting == null) { 6421 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6422 + " from package " + bp.sourcePackage); 6423 it.remove(); 6424 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6425 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6426 Slog.i(TAG, "Removing old permission tree: " + bp.name 6427 + " from package " + bp.sourcePackage); 6428 flags |= UPDATE_PERMISSIONS_ALL; 6429 it.remove(); 6430 } 6431 } 6432 } 6433 6434 // Make sure all dynamic permissions have been assigned to a package, 6435 // and make sure there are no dangling permissions. 6436 it = mSettings.mPermissions.values().iterator(); 6437 while (it.hasNext()) { 6438 final BasePermission bp = it.next(); 6439 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6440 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6441 + bp.name + " pkg=" + bp.sourcePackage 6442 + " info=" + bp.pendingInfo); 6443 if (bp.packageSetting == null && bp.pendingInfo != null) { 6444 final BasePermission tree = findPermissionTreeLP(bp.name); 6445 if (tree != null && tree.perm != null) { 6446 bp.packageSetting = tree.packageSetting; 6447 bp.perm = new PackageParser.Permission(tree.perm.owner, 6448 new PermissionInfo(bp.pendingInfo)); 6449 bp.perm.info.packageName = tree.perm.info.packageName; 6450 bp.perm.info.name = bp.name; 6451 bp.uid = tree.uid; 6452 } 6453 } 6454 } 6455 if (bp.packageSetting == null) { 6456 // We may not yet have parsed the package, so just see if 6457 // we still know about its settings. 6458 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6459 } 6460 if (bp.packageSetting == null) { 6461 Slog.w(TAG, "Removing dangling permission: " + bp.name 6462 + " from package " + bp.sourcePackage); 6463 it.remove(); 6464 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6465 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6466 Slog.i(TAG, "Removing old permission: " + bp.name 6467 + " from package " + bp.sourcePackage); 6468 flags |= UPDATE_PERMISSIONS_ALL; 6469 it.remove(); 6470 } 6471 } 6472 } 6473 6474 // Now update the permissions for all packages, in particular 6475 // replace the granted permissions of the system packages. 6476 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6477 for (PackageParser.Package pkg : mPackages.values()) { 6478 if (pkg != pkgInfo) { 6479 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6480 } 6481 } 6482 } 6483 6484 if (pkgInfo != null) { 6485 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6486 } 6487 } 6488 6489 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6490 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6491 if (ps == null) { 6492 return; 6493 } 6494 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6495 HashSet<String> origPermissions = gp.grantedPermissions; 6496 boolean changedPermission = false; 6497 6498 if (replace) { 6499 ps.permissionsFixed = false; 6500 if (gp == ps) { 6501 origPermissions = new HashSet<String>(gp.grantedPermissions); 6502 gp.grantedPermissions.clear(); 6503 gp.gids = mGlobalGids; 6504 } 6505 } 6506 6507 if (gp.gids == null) { 6508 gp.gids = mGlobalGids; 6509 } 6510 6511 final int N = pkg.requestedPermissions.size(); 6512 for (int i=0; i<N; i++) { 6513 final String name = pkg.requestedPermissions.get(i); 6514 final boolean required = pkg.requestedPermissionsRequired.get(i); 6515 final BasePermission bp = mSettings.mPermissions.get(name); 6516 if (DEBUG_INSTALL) { 6517 if (gp != ps) { 6518 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6519 } 6520 } 6521 6522 if (bp == null || bp.packageSetting == null) { 6523 Slog.w(TAG, "Unknown permission " + name 6524 + " in package " + pkg.packageName); 6525 continue; 6526 } 6527 6528 final String perm = bp.name; 6529 boolean allowed; 6530 boolean allowedSig = false; 6531 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6532 if (level == PermissionInfo.PROTECTION_NORMAL 6533 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6534 // We grant a normal or dangerous permission if any of the following 6535 // are true: 6536 // 1) The permission is required 6537 // 2) The permission is optional, but was granted in the past 6538 // 3) The permission is optional, but was requested by an 6539 // app in /system (not /data) 6540 // 6541 // Otherwise, reject the permission. 6542 allowed = (required || origPermissions.contains(perm) 6543 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6544 } else if (bp.packageSetting == null) { 6545 // This permission is invalid; skip it. 6546 allowed = false; 6547 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6548 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6549 if (allowed) { 6550 allowedSig = true; 6551 } 6552 } else { 6553 allowed = false; 6554 } 6555 if (DEBUG_INSTALL) { 6556 if (gp != ps) { 6557 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6558 } 6559 } 6560 if (allowed) { 6561 if (!isSystemApp(ps) && ps.permissionsFixed) { 6562 // If this is an existing, non-system package, then 6563 // we can't add any new permissions to it. 6564 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6565 // Except... if this is a permission that was added 6566 // to the platform (note: need to only do this when 6567 // updating the platform). 6568 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6569 } 6570 } 6571 if (allowed) { 6572 if (!gp.grantedPermissions.contains(perm)) { 6573 changedPermission = true; 6574 gp.grantedPermissions.add(perm); 6575 gp.gids = appendInts(gp.gids, bp.gids); 6576 } else if (!ps.haveGids) { 6577 gp.gids = appendInts(gp.gids, bp.gids); 6578 } 6579 } else { 6580 Slog.w(TAG, "Not granting permission " + perm 6581 + " to package " + pkg.packageName 6582 + " because it was previously installed without"); 6583 } 6584 } else { 6585 if (gp.grantedPermissions.remove(perm)) { 6586 changedPermission = true; 6587 gp.gids = removeInts(gp.gids, bp.gids); 6588 Slog.i(TAG, "Un-granting permission " + perm 6589 + " from package " + pkg.packageName 6590 + " (protectionLevel=" + bp.protectionLevel 6591 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6592 + ")"); 6593 } else { 6594 Slog.w(TAG, "Not granting permission " + perm 6595 + " to package " + pkg.packageName 6596 + " (protectionLevel=" + bp.protectionLevel 6597 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6598 + ")"); 6599 } 6600 } 6601 } 6602 6603 if ((changedPermission || replace) && !ps.permissionsFixed && 6604 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6605 // This is the first that we have heard about this package, so the 6606 // permissions we have now selected are fixed until explicitly 6607 // changed. 6608 ps.permissionsFixed = true; 6609 } 6610 ps.haveGids = true; 6611 } 6612 6613 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6614 boolean allowed = false; 6615 final int NP = PackageParser.NEW_PERMISSIONS.length; 6616 for (int ip=0; ip<NP; ip++) { 6617 final PackageParser.NewPermissionInfo npi 6618 = PackageParser.NEW_PERMISSIONS[ip]; 6619 if (npi.name.equals(perm) 6620 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6621 allowed = true; 6622 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6623 + pkg.packageName); 6624 break; 6625 } 6626 } 6627 return allowed; 6628 } 6629 6630 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6631 BasePermission bp, HashSet<String> origPermissions) { 6632 boolean allowed; 6633 allowed = (compareSignatures( 6634 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6635 == PackageManager.SIGNATURE_MATCH) 6636 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6637 == PackageManager.SIGNATURE_MATCH); 6638 if (!allowed && (bp.protectionLevel 6639 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6640 if (isSystemApp(pkg)) { 6641 // For updated system applications, a system permission 6642 // is granted only if it had been defined by the original application. 6643 if (isUpdatedSystemApp(pkg)) { 6644 final PackageSetting sysPs = mSettings 6645 .getDisabledSystemPkgLPr(pkg.packageName); 6646 final GrantedPermissions origGp = sysPs.sharedUser != null 6647 ? sysPs.sharedUser : sysPs; 6648 6649 if (origGp.grantedPermissions.contains(perm)) { 6650 // If the original was granted this permission, we take 6651 // that grant decision as read and propagate it to the 6652 // update. 6653 allowed = true; 6654 } else { 6655 // The system apk may have been updated with an older 6656 // version of the one on the data partition, but which 6657 // granted a new system permission that it didn't have 6658 // before. In this case we do want to allow the app to 6659 // now get the new permission if the ancestral apk is 6660 // privileged to get it. 6661 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6662 for (int j=0; 6663 j<sysPs.pkg.requestedPermissions.size(); j++) { 6664 if (perm.equals( 6665 sysPs.pkg.requestedPermissions.get(j))) { 6666 allowed = true; 6667 break; 6668 } 6669 } 6670 } 6671 } 6672 } else { 6673 allowed = isPrivilegedApp(pkg); 6674 } 6675 } 6676 } 6677 if (!allowed && (bp.protectionLevel 6678 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6679 // For development permissions, a development permission 6680 // is granted only if it was already granted. 6681 allowed = origPermissions.contains(perm); 6682 } 6683 return allowed; 6684 } 6685 6686 final class ActivityIntentResolver 6687 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6688 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6689 boolean defaultOnly, int userId) { 6690 if (!sUserManager.exists(userId)) return null; 6691 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6692 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6693 } 6694 6695 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6696 int userId) { 6697 if (!sUserManager.exists(userId)) return null; 6698 mFlags = flags; 6699 return super.queryIntent(intent, resolvedType, 6700 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6701 } 6702 6703 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6704 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6705 if (!sUserManager.exists(userId)) return null; 6706 if (packageActivities == null) { 6707 return null; 6708 } 6709 mFlags = flags; 6710 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6711 final int N = packageActivities.size(); 6712 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6713 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6714 6715 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6716 for (int i = 0; i < N; ++i) { 6717 intentFilters = packageActivities.get(i).intents; 6718 if (intentFilters != null && intentFilters.size() > 0) { 6719 PackageParser.ActivityIntentInfo[] array = 6720 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6721 intentFilters.toArray(array); 6722 listCut.add(array); 6723 } 6724 } 6725 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6726 } 6727 6728 public final void addActivity(PackageParser.Activity a, String type) { 6729 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6730 mActivities.put(a.getComponentName(), a); 6731 if (DEBUG_SHOW_INFO) 6732 Log.v( 6733 TAG, " " + type + " " + 6734 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6735 if (DEBUG_SHOW_INFO) 6736 Log.v(TAG, " Class=" + a.info.name); 6737 final int NI = a.intents.size(); 6738 for (int j=0; j<NI; j++) { 6739 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6740 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6741 intent.setPriority(0); 6742 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6743 + a.className + " with priority > 0, forcing to 0"); 6744 } 6745 if (DEBUG_SHOW_INFO) { 6746 Log.v(TAG, " IntentFilter:"); 6747 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6748 } 6749 if (!intent.debugCheck()) { 6750 Log.w(TAG, "==> For Activity " + a.info.name); 6751 } 6752 addFilter(intent); 6753 } 6754 } 6755 6756 public final void removeActivity(PackageParser.Activity a, String type) { 6757 mActivities.remove(a.getComponentName()); 6758 if (DEBUG_SHOW_INFO) { 6759 Log.v(TAG, " " + type + " " 6760 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6761 : a.info.name) + ":"); 6762 Log.v(TAG, " Class=" + a.info.name); 6763 } 6764 final int NI = a.intents.size(); 6765 for (int j=0; j<NI; j++) { 6766 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6767 if (DEBUG_SHOW_INFO) { 6768 Log.v(TAG, " IntentFilter:"); 6769 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6770 } 6771 removeFilter(intent); 6772 } 6773 } 6774 6775 @Override 6776 protected boolean allowFilterResult( 6777 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6778 ActivityInfo filterAi = filter.activity.info; 6779 for (int i=dest.size()-1; i>=0; i--) { 6780 ActivityInfo destAi = dest.get(i).activityInfo; 6781 if (destAi.name == filterAi.name 6782 && destAi.packageName == filterAi.packageName) { 6783 return false; 6784 } 6785 } 6786 return true; 6787 } 6788 6789 @Override 6790 protected ActivityIntentInfo[] newArray(int size) { 6791 return new ActivityIntentInfo[size]; 6792 } 6793 6794 @Override 6795 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6796 if (!sUserManager.exists(userId)) return true; 6797 PackageParser.Package p = filter.activity.owner; 6798 if (p != null) { 6799 PackageSetting ps = (PackageSetting)p.mExtras; 6800 if (ps != null) { 6801 // System apps are never considered stopped for purposes of 6802 // filtering, because there may be no way for the user to 6803 // actually re-launch them. 6804 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6805 && ps.getStopped(userId); 6806 } 6807 } 6808 return false; 6809 } 6810 6811 @Override 6812 protected boolean isPackageForFilter(String packageName, 6813 PackageParser.ActivityIntentInfo info) { 6814 return packageName.equals(info.activity.owner.packageName); 6815 } 6816 6817 @Override 6818 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6819 int match, int userId) { 6820 if (!sUserManager.exists(userId)) return null; 6821 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6822 return null; 6823 } 6824 final PackageParser.Activity activity = info.activity; 6825 if (mSafeMode && (activity.info.applicationInfo.flags 6826 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6827 return null; 6828 } 6829 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6830 if (ps == null) { 6831 return null; 6832 } 6833 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6834 ps.readUserState(userId), userId); 6835 if (ai == null) { 6836 return null; 6837 } 6838 final ResolveInfo res = new ResolveInfo(); 6839 res.activityInfo = ai; 6840 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6841 res.filter = info; 6842 } 6843 res.priority = info.getPriority(); 6844 res.preferredOrder = activity.owner.mPreferredOrder; 6845 //System.out.println("Result: " + res.activityInfo.className + 6846 // " = " + res.priority); 6847 res.match = match; 6848 res.isDefault = info.hasDefault; 6849 res.labelRes = info.labelRes; 6850 res.nonLocalizedLabel = info.nonLocalizedLabel; 6851 res.icon = info.icon; 6852 res.system = isSystemApp(res.activityInfo.applicationInfo); 6853 return res; 6854 } 6855 6856 @Override 6857 protected void sortResults(List<ResolveInfo> results) { 6858 Collections.sort(results, mResolvePrioritySorter); 6859 } 6860 6861 @Override 6862 protected void dumpFilter(PrintWriter out, String prefix, 6863 PackageParser.ActivityIntentInfo filter) { 6864 out.print(prefix); out.print( 6865 Integer.toHexString(System.identityHashCode(filter.activity))); 6866 out.print(' '); 6867 filter.activity.printComponentShortName(out); 6868 out.print(" filter "); 6869 out.println(Integer.toHexString(System.identityHashCode(filter))); 6870 } 6871 6872// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6873// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6874// final List<ResolveInfo> retList = Lists.newArrayList(); 6875// while (i.hasNext()) { 6876// final ResolveInfo resolveInfo = i.next(); 6877// if (isEnabledLP(resolveInfo.activityInfo)) { 6878// retList.add(resolveInfo); 6879// } 6880// } 6881// return retList; 6882// } 6883 6884 // Keys are String (activity class name), values are Activity. 6885 private final HashMap<ComponentName, PackageParser.Activity> mActivities 6886 = new HashMap<ComponentName, PackageParser.Activity>(); 6887 private int mFlags; 6888 } 6889 6890 private final class ServiceIntentResolver 6891 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 6892 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6893 boolean defaultOnly, int userId) { 6894 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6895 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6896 } 6897 6898 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6899 int userId) { 6900 if (!sUserManager.exists(userId)) return null; 6901 mFlags = flags; 6902 return super.queryIntent(intent, resolvedType, 6903 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6904 } 6905 6906 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6907 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 6908 if (!sUserManager.exists(userId)) return null; 6909 if (packageServices == null) { 6910 return null; 6911 } 6912 mFlags = flags; 6913 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6914 final int N = packageServices.size(); 6915 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 6916 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 6917 6918 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 6919 for (int i = 0; i < N; ++i) { 6920 intentFilters = packageServices.get(i).intents; 6921 if (intentFilters != null && intentFilters.size() > 0) { 6922 PackageParser.ServiceIntentInfo[] array = 6923 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 6924 intentFilters.toArray(array); 6925 listCut.add(array); 6926 } 6927 } 6928 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6929 } 6930 6931 public final void addService(PackageParser.Service s) { 6932 mServices.put(s.getComponentName(), s); 6933 if (DEBUG_SHOW_INFO) { 6934 Log.v(TAG, " " 6935 + (s.info.nonLocalizedLabel != null 6936 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6937 Log.v(TAG, " Class=" + s.info.name); 6938 } 6939 final int NI = s.intents.size(); 6940 int j; 6941 for (j=0; j<NI; j++) { 6942 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6943 if (DEBUG_SHOW_INFO) { 6944 Log.v(TAG, " IntentFilter:"); 6945 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6946 } 6947 if (!intent.debugCheck()) { 6948 Log.w(TAG, "==> For Service " + s.info.name); 6949 } 6950 addFilter(intent); 6951 } 6952 } 6953 6954 public final void removeService(PackageParser.Service s) { 6955 mServices.remove(s.getComponentName()); 6956 if (DEBUG_SHOW_INFO) { 6957 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 6958 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6959 Log.v(TAG, " Class=" + s.info.name); 6960 } 6961 final int NI = s.intents.size(); 6962 int j; 6963 for (j=0; j<NI; j++) { 6964 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6965 if (DEBUG_SHOW_INFO) { 6966 Log.v(TAG, " IntentFilter:"); 6967 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6968 } 6969 removeFilter(intent); 6970 } 6971 } 6972 6973 @Override 6974 protected boolean allowFilterResult( 6975 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 6976 ServiceInfo filterSi = filter.service.info; 6977 for (int i=dest.size()-1; i>=0; i--) { 6978 ServiceInfo destAi = dest.get(i).serviceInfo; 6979 if (destAi.name == filterSi.name 6980 && destAi.packageName == filterSi.packageName) { 6981 return false; 6982 } 6983 } 6984 return true; 6985 } 6986 6987 @Override 6988 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 6989 return new PackageParser.ServiceIntentInfo[size]; 6990 } 6991 6992 @Override 6993 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 6994 if (!sUserManager.exists(userId)) return true; 6995 PackageParser.Package p = filter.service.owner; 6996 if (p != null) { 6997 PackageSetting ps = (PackageSetting)p.mExtras; 6998 if (ps != null) { 6999 // System apps are never considered stopped for purposes of 7000 // filtering, because there may be no way for the user to 7001 // actually re-launch them. 7002 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7003 && ps.getStopped(userId); 7004 } 7005 } 7006 return false; 7007 } 7008 7009 @Override 7010 protected boolean isPackageForFilter(String packageName, 7011 PackageParser.ServiceIntentInfo info) { 7012 return packageName.equals(info.service.owner.packageName); 7013 } 7014 7015 @Override 7016 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7017 int match, int userId) { 7018 if (!sUserManager.exists(userId)) return null; 7019 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7020 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7021 return null; 7022 } 7023 final PackageParser.Service service = info.service; 7024 if (mSafeMode && (service.info.applicationInfo.flags 7025 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7026 return null; 7027 } 7028 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7029 if (ps == null) { 7030 return null; 7031 } 7032 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7033 ps.readUserState(userId), userId); 7034 if (si == null) { 7035 return null; 7036 } 7037 final ResolveInfo res = new ResolveInfo(); 7038 res.serviceInfo = si; 7039 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7040 res.filter = filter; 7041 } 7042 res.priority = info.getPriority(); 7043 res.preferredOrder = service.owner.mPreferredOrder; 7044 //System.out.println("Result: " + res.activityInfo.className + 7045 // " = " + res.priority); 7046 res.match = match; 7047 res.isDefault = info.hasDefault; 7048 res.labelRes = info.labelRes; 7049 res.nonLocalizedLabel = info.nonLocalizedLabel; 7050 res.icon = info.icon; 7051 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7052 return res; 7053 } 7054 7055 @Override 7056 protected void sortResults(List<ResolveInfo> results) { 7057 Collections.sort(results, mResolvePrioritySorter); 7058 } 7059 7060 @Override 7061 protected void dumpFilter(PrintWriter out, String prefix, 7062 PackageParser.ServiceIntentInfo filter) { 7063 out.print(prefix); out.print( 7064 Integer.toHexString(System.identityHashCode(filter.service))); 7065 out.print(' '); 7066 filter.service.printComponentShortName(out); 7067 out.print(" filter "); 7068 out.println(Integer.toHexString(System.identityHashCode(filter))); 7069 } 7070 7071// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7072// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7073// final List<ResolveInfo> retList = Lists.newArrayList(); 7074// while (i.hasNext()) { 7075// final ResolveInfo resolveInfo = (ResolveInfo) i; 7076// if (isEnabledLP(resolveInfo.serviceInfo)) { 7077// retList.add(resolveInfo); 7078// } 7079// } 7080// return retList; 7081// } 7082 7083 // Keys are String (activity class name), values are Activity. 7084 private final HashMap<ComponentName, PackageParser.Service> mServices 7085 = new HashMap<ComponentName, PackageParser.Service>(); 7086 private int mFlags; 7087 }; 7088 7089 private final class ProviderIntentResolver 7090 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7091 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7092 boolean defaultOnly, int userId) { 7093 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7094 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7095 } 7096 7097 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7098 int userId) { 7099 if (!sUserManager.exists(userId)) 7100 return null; 7101 mFlags = flags; 7102 return super.queryIntent(intent, resolvedType, 7103 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7104 } 7105 7106 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7107 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7108 if (!sUserManager.exists(userId)) 7109 return null; 7110 if (packageProviders == null) { 7111 return null; 7112 } 7113 mFlags = flags; 7114 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7115 final int N = packageProviders.size(); 7116 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7117 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7118 7119 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7120 for (int i = 0; i < N; ++i) { 7121 intentFilters = packageProviders.get(i).intents; 7122 if (intentFilters != null && intentFilters.size() > 0) { 7123 PackageParser.ProviderIntentInfo[] array = 7124 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7125 intentFilters.toArray(array); 7126 listCut.add(array); 7127 } 7128 } 7129 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7130 } 7131 7132 public final void addProvider(PackageParser.Provider p) { 7133 if (mProviders.containsKey(p.getComponentName())) { 7134 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7135 return; 7136 } 7137 7138 mProviders.put(p.getComponentName(), p); 7139 if (DEBUG_SHOW_INFO) { 7140 Log.v(TAG, " " 7141 + (p.info.nonLocalizedLabel != null 7142 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7143 Log.v(TAG, " Class=" + p.info.name); 7144 } 7145 final int NI = p.intents.size(); 7146 int j; 7147 for (j = 0; j < NI; j++) { 7148 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7149 if (DEBUG_SHOW_INFO) { 7150 Log.v(TAG, " IntentFilter:"); 7151 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7152 } 7153 if (!intent.debugCheck()) { 7154 Log.w(TAG, "==> For Provider " + p.info.name); 7155 } 7156 addFilter(intent); 7157 } 7158 } 7159 7160 public final void removeProvider(PackageParser.Provider p) { 7161 mProviders.remove(p.getComponentName()); 7162 if (DEBUG_SHOW_INFO) { 7163 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7164 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7165 Log.v(TAG, " Class=" + p.info.name); 7166 } 7167 final int NI = p.intents.size(); 7168 int j; 7169 for (j = 0; j < NI; j++) { 7170 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7171 if (DEBUG_SHOW_INFO) { 7172 Log.v(TAG, " IntentFilter:"); 7173 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7174 } 7175 removeFilter(intent); 7176 } 7177 } 7178 7179 @Override 7180 protected boolean allowFilterResult( 7181 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7182 ProviderInfo filterPi = filter.provider.info; 7183 for (int i = dest.size() - 1; i >= 0; i--) { 7184 ProviderInfo destPi = dest.get(i).providerInfo; 7185 if (destPi.name == filterPi.name 7186 && destPi.packageName == filterPi.packageName) { 7187 return false; 7188 } 7189 } 7190 return true; 7191 } 7192 7193 @Override 7194 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7195 return new PackageParser.ProviderIntentInfo[size]; 7196 } 7197 7198 @Override 7199 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7200 if (!sUserManager.exists(userId)) 7201 return true; 7202 PackageParser.Package p = filter.provider.owner; 7203 if (p != null) { 7204 PackageSetting ps = (PackageSetting) p.mExtras; 7205 if (ps != null) { 7206 // System apps are never considered stopped for purposes of 7207 // filtering, because there may be no way for the user to 7208 // actually re-launch them. 7209 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7210 && ps.getStopped(userId); 7211 } 7212 } 7213 return false; 7214 } 7215 7216 @Override 7217 protected boolean isPackageForFilter(String packageName, 7218 PackageParser.ProviderIntentInfo info) { 7219 return packageName.equals(info.provider.owner.packageName); 7220 } 7221 7222 @Override 7223 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7224 int match, int userId) { 7225 if (!sUserManager.exists(userId)) 7226 return null; 7227 final PackageParser.ProviderIntentInfo info = filter; 7228 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7229 return null; 7230 } 7231 final PackageParser.Provider provider = info.provider; 7232 if (mSafeMode && (provider.info.applicationInfo.flags 7233 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7234 return null; 7235 } 7236 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7237 if (ps == null) { 7238 return null; 7239 } 7240 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7241 ps.readUserState(userId), userId); 7242 if (pi == null) { 7243 return null; 7244 } 7245 final ResolveInfo res = new ResolveInfo(); 7246 res.providerInfo = pi; 7247 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7248 res.filter = filter; 7249 } 7250 res.priority = info.getPriority(); 7251 res.preferredOrder = provider.owner.mPreferredOrder; 7252 res.match = match; 7253 res.isDefault = info.hasDefault; 7254 res.labelRes = info.labelRes; 7255 res.nonLocalizedLabel = info.nonLocalizedLabel; 7256 res.icon = info.icon; 7257 res.system = isSystemApp(res.providerInfo.applicationInfo); 7258 return res; 7259 } 7260 7261 @Override 7262 protected void sortResults(List<ResolveInfo> results) { 7263 Collections.sort(results, mResolvePrioritySorter); 7264 } 7265 7266 @Override 7267 protected void dumpFilter(PrintWriter out, String prefix, 7268 PackageParser.ProviderIntentInfo filter) { 7269 out.print(prefix); 7270 out.print( 7271 Integer.toHexString(System.identityHashCode(filter.provider))); 7272 out.print(' '); 7273 filter.provider.printComponentShortName(out); 7274 out.print(" filter "); 7275 out.println(Integer.toHexString(System.identityHashCode(filter))); 7276 } 7277 7278 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7279 = new HashMap<ComponentName, PackageParser.Provider>(); 7280 private int mFlags; 7281 }; 7282 7283 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7284 new Comparator<ResolveInfo>() { 7285 public int compare(ResolveInfo r1, ResolveInfo r2) { 7286 int v1 = r1.priority; 7287 int v2 = r2.priority; 7288 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7289 if (v1 != v2) { 7290 return (v1 > v2) ? -1 : 1; 7291 } 7292 v1 = r1.preferredOrder; 7293 v2 = r2.preferredOrder; 7294 if (v1 != v2) { 7295 return (v1 > v2) ? -1 : 1; 7296 } 7297 if (r1.isDefault != r2.isDefault) { 7298 return r1.isDefault ? -1 : 1; 7299 } 7300 v1 = r1.match; 7301 v2 = r2.match; 7302 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7303 if (v1 != v2) { 7304 return (v1 > v2) ? -1 : 1; 7305 } 7306 if (r1.system != r2.system) { 7307 return r1.system ? -1 : 1; 7308 } 7309 return 0; 7310 } 7311 }; 7312 7313 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7314 new Comparator<ProviderInfo>() { 7315 public int compare(ProviderInfo p1, ProviderInfo p2) { 7316 final int v1 = p1.initOrder; 7317 final int v2 = p2.initOrder; 7318 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7319 } 7320 }; 7321 7322 static final void sendPackageBroadcast(String action, String pkg, 7323 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7324 int[] userIds) { 7325 IActivityManager am = ActivityManagerNative.getDefault(); 7326 if (am != null) { 7327 try { 7328 if (userIds == null) { 7329 userIds = am.getRunningUserIds(); 7330 } 7331 for (int id : userIds) { 7332 final Intent intent = new Intent(action, 7333 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7334 if (extras != null) { 7335 intent.putExtras(extras); 7336 } 7337 if (targetPkg != null) { 7338 intent.setPackage(targetPkg); 7339 } 7340 // Modify the UID when posting to other users 7341 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7342 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7343 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7344 intent.putExtra(Intent.EXTRA_UID, uid); 7345 } 7346 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7347 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7348 if (DEBUG_BROADCASTS) { 7349 RuntimeException here = new RuntimeException("here"); 7350 here.fillInStackTrace(); 7351 Slog.d(TAG, "Sending to user " + id + ": " 7352 + intent.toShortString(false, true, false, false) 7353 + " " + intent.getExtras(), here); 7354 } 7355 am.broadcastIntent(null, intent, null, finishedReceiver, 7356 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7357 finishedReceiver != null, false, id); 7358 } 7359 } catch (RemoteException ex) { 7360 } 7361 } 7362 } 7363 7364 /** 7365 * Check if the external storage media is available. This is true if there 7366 * is a mounted external storage medium or if the external storage is 7367 * emulated. 7368 */ 7369 private boolean isExternalMediaAvailable() { 7370 return mMediaMounted || Environment.isExternalStorageEmulated(); 7371 } 7372 7373 @Override 7374 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7375 // writer 7376 synchronized (mPackages) { 7377 if (!isExternalMediaAvailable()) { 7378 // If the external storage is no longer mounted at this point, 7379 // the caller may not have been able to delete all of this 7380 // packages files and can not delete any more. Bail. 7381 return null; 7382 } 7383 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7384 if (lastPackage != null) { 7385 pkgs.remove(lastPackage); 7386 } 7387 if (pkgs.size() > 0) { 7388 return pkgs.get(0); 7389 } 7390 } 7391 return null; 7392 } 7393 7394 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7395 if (false) { 7396 RuntimeException here = new RuntimeException("here"); 7397 here.fillInStackTrace(); 7398 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7399 + " andCode=" + andCode, here); 7400 } 7401 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7402 userId, andCode ? 1 : 0, packageName)); 7403 } 7404 7405 void startCleaningPackages() { 7406 // reader 7407 synchronized (mPackages) { 7408 if (!isExternalMediaAvailable()) { 7409 return; 7410 } 7411 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7412 return; 7413 } 7414 } 7415 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7416 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7417 IActivityManager am = ActivityManagerNative.getDefault(); 7418 if (am != null) { 7419 try { 7420 am.startService(null, intent, null, UserHandle.USER_OWNER); 7421 } catch (RemoteException e) { 7422 } 7423 } 7424 } 7425 7426 private final class AppDirObserver extends FileObserver { 7427 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7428 super(path, mask); 7429 mRootDir = path; 7430 mIsRom = isrom; 7431 mIsPrivileged = isPrivileged; 7432 } 7433 7434 public void onEvent(int event, String path) { 7435 String removedPackage = null; 7436 int removedAppId = -1; 7437 int[] removedUsers = null; 7438 String addedPackage = null; 7439 int addedAppId = -1; 7440 int[] addedUsers = null; 7441 7442 // TODO post a message to the handler to obtain serial ordering 7443 synchronized (mInstallLock) { 7444 String fullPathStr = null; 7445 File fullPath = null; 7446 if (path != null) { 7447 fullPath = new File(mRootDir, path); 7448 fullPathStr = fullPath.getPath(); 7449 } 7450 7451 if (DEBUG_APP_DIR_OBSERVER) 7452 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7453 7454 if (!isPackageFilename(path)) { 7455 if (DEBUG_APP_DIR_OBSERVER) 7456 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7457 return; 7458 } 7459 7460 // Ignore packages that are being installed or 7461 // have just been installed. 7462 if (ignoreCodePath(fullPathStr)) { 7463 return; 7464 } 7465 PackageParser.Package p = null; 7466 PackageSetting ps = null; 7467 // reader 7468 synchronized (mPackages) { 7469 p = mAppDirs.get(fullPathStr); 7470 if (p != null) { 7471 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7472 if (ps != null) { 7473 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7474 } else { 7475 removedUsers = sUserManager.getUserIds(); 7476 } 7477 } 7478 addedUsers = sUserManager.getUserIds(); 7479 } 7480 if ((event&REMOVE_EVENTS) != 0) { 7481 if (ps != null) { 7482 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7483 removePackageLI(ps, true); 7484 removedPackage = ps.name; 7485 removedAppId = ps.appId; 7486 } 7487 } 7488 7489 if ((event&ADD_EVENTS) != 0) { 7490 if (p == null) { 7491 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7492 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7493 if (mIsRom) { 7494 flags |= PackageParser.PARSE_IS_SYSTEM 7495 | PackageParser.PARSE_IS_SYSTEM_DIR; 7496 if (mIsPrivileged) { 7497 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7498 } 7499 } 7500 p = scanPackageLI(fullPath, flags, 7501 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7502 System.currentTimeMillis(), UserHandle.ALL, null); 7503 if (p != null) { 7504 /* 7505 * TODO this seems dangerous as the package may have 7506 * changed since we last acquired the mPackages 7507 * lock. 7508 */ 7509 // writer 7510 synchronized (mPackages) { 7511 updatePermissionsLPw(p.packageName, p, 7512 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7513 } 7514 addedPackage = p.applicationInfo.packageName; 7515 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7516 } 7517 } 7518 } 7519 7520 // reader 7521 synchronized (mPackages) { 7522 mSettings.writeLPr(); 7523 } 7524 } 7525 7526 if (removedPackage != null) { 7527 Bundle extras = new Bundle(1); 7528 extras.putInt(Intent.EXTRA_UID, removedAppId); 7529 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7530 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7531 extras, null, null, removedUsers); 7532 } 7533 if (addedPackage != null) { 7534 Bundle extras = new Bundle(1); 7535 extras.putInt(Intent.EXTRA_UID, addedAppId); 7536 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7537 extras, null, null, addedUsers); 7538 } 7539 } 7540 7541 private final String mRootDir; 7542 private final boolean mIsRom; 7543 private final boolean mIsPrivileged; 7544 } 7545 7546 /* 7547 * The old-style observer methods all just trampoline to the newer signature with 7548 * expanded install observer API. The older API continues to work but does not 7549 * supply the additional details of the Observer2 API. 7550 */ 7551 7552 /* Called when a downloaded package installation has been confirmed by the user */ 7553 public void installPackage( 7554 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 7555 installPackageEtc(packageURI, observer, null, flags, null); 7556 } 7557 7558 /* Called when a downloaded package installation has been confirmed by the user */ 7559 @Override 7560 public void installPackage( 7561 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 7562 final String installerPackageName) { 7563 installPackageWithVerificationEtc(packageURI, observer, null, flags, 7564 installerPackageName, null, null, null); 7565 } 7566 7567 @Override 7568 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 7569 int flags, String installerPackageName, Uri verificationURI, 7570 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7571 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7572 VerificationParams.NO_UID, manifestDigest); 7573 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7574 installerPackageName, verificationParams, encryptionParams); 7575 } 7576 7577 @Override 7578 public void installPackageWithVerificationAndEncryption(Uri packageURI, 7579 IPackageInstallObserver observer, int flags, String installerPackageName, 7580 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7581 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7582 installerPackageName, verificationParams, encryptionParams); 7583 } 7584 7585 /* 7586 * And here are the "live" versions that take both observer arguments 7587 */ 7588 public void installPackageEtc( 7589 final Uri packageURI, final IPackageInstallObserver observer, 7590 IPackageInstallObserver2 observer2, final int flags) { 7591 installPackageEtc(packageURI, observer, observer2, flags, null); 7592 } 7593 7594 public void installPackageEtc( 7595 final Uri packageURI, final IPackageInstallObserver observer, 7596 final IPackageInstallObserver2 observer2, final int flags, 7597 final String installerPackageName) { 7598 installPackageWithVerificationEtc(packageURI, observer, observer2, flags, 7599 installerPackageName, null, null, null); 7600 } 7601 7602 @Override 7603 public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer, 7604 IPackageInstallObserver2 observer2, 7605 int flags, String installerPackageName, Uri verificationURI, 7606 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7607 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7608 VerificationParams.NO_UID, manifestDigest); 7609 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags, 7610 installerPackageName, verificationParams, encryptionParams); 7611 } 7612 7613 /* 7614 * All of the installPackage...*() methods redirect to this one for the master implementation 7615 */ 7616 public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI, 7617 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7618 int flags, String installerPackageName, 7619 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7620 if (observer == null && observer2 == null) { 7621 throw new IllegalArgumentException("No install observer supplied"); 7622 } 7623 installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2, 7624 flags, installerPackageName, verificationParams, encryptionParams, null); 7625 } 7626 7627 @Override 7628 public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI, 7629 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7630 int flags, String installerPackageName, 7631 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams, 7632 String packageAbiOverride) { 7633 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7634 null); 7635 7636 final int uid = Binder.getCallingUid(); 7637 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7638 try { 7639 if (observer != null) { 7640 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7641 } 7642 if (observer2 != null) { 7643 observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7644 } 7645 } catch (RemoteException re) { 7646 } 7647 return; 7648 } 7649 7650 UserHandle user; 7651 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7652 user = UserHandle.ALL; 7653 } else { 7654 user = new UserHandle(UserHandle.getUserId(uid)); 7655 } 7656 7657 final int filteredFlags; 7658 7659 if (uid == Process.SHELL_UID || uid == 0) { 7660 if (DEBUG_INSTALL) { 7661 Slog.v(TAG, "Install from ADB"); 7662 } 7663 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7664 } else { 7665 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7666 } 7667 7668 verificationParams.setInstallerUid(uid); 7669 7670 final Message msg = mHandler.obtainMessage(INIT_COPY); 7671 msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags, 7672 installerPackageName, verificationParams, encryptionParams, user, 7673 packageAbiOverride); 7674 mHandler.sendMessage(msg); 7675 } 7676 7677 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7678 Bundle extras = new Bundle(1); 7679 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7680 7681 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7682 packageName, extras, null, null, new int[] {userId}); 7683 try { 7684 IActivityManager am = ActivityManagerNative.getDefault(); 7685 final boolean isSystem = 7686 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7687 if (isSystem && am.isUserRunning(userId, false)) { 7688 // The just-installed/enabled app is bundled on the system, so presumed 7689 // to be able to run automatically without needing an explicit launch. 7690 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7691 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7692 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7693 .setPackage(packageName); 7694 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7695 android.app.AppOpsManager.OP_NONE, false, false, userId); 7696 } 7697 } catch (RemoteException e) { 7698 // shouldn't happen 7699 Slog.w(TAG, "Unable to bootstrap installed package", e); 7700 } 7701 } 7702 7703 @Override 7704 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7705 int userId) { 7706 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7707 PackageSetting pkgSetting; 7708 final int uid = Binder.getCallingUid(); 7709 if (UserHandle.getUserId(uid) != userId) { 7710 mContext.enforceCallingOrSelfPermission( 7711 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7712 "setApplicationBlockedSetting for user " + userId); 7713 } 7714 7715 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7716 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7717 return false; 7718 } 7719 7720 long callingId = Binder.clearCallingIdentity(); 7721 try { 7722 boolean sendAdded = false; 7723 boolean sendRemoved = false; 7724 // writer 7725 synchronized (mPackages) { 7726 pkgSetting = mSettings.mPackages.get(packageName); 7727 if (pkgSetting == null) { 7728 return false; 7729 } 7730 if (pkgSetting.getBlocked(userId) != blocked) { 7731 pkgSetting.setBlocked(blocked, userId); 7732 mSettings.writePackageRestrictionsLPr(userId); 7733 if (blocked) { 7734 sendRemoved = true; 7735 } else { 7736 sendAdded = true; 7737 } 7738 } 7739 } 7740 if (sendAdded) { 7741 sendPackageAddedForUser(packageName, pkgSetting, userId); 7742 return true; 7743 } 7744 if (sendRemoved) { 7745 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7746 "blocking pkg"); 7747 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7748 } 7749 } finally { 7750 Binder.restoreCallingIdentity(callingId); 7751 } 7752 return false; 7753 } 7754 7755 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7756 int userId) { 7757 final PackageRemovedInfo info = new PackageRemovedInfo(); 7758 info.removedPackage = packageName; 7759 info.removedUsers = new int[] {userId}; 7760 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7761 info.sendBroadcast(false, false, false); 7762 } 7763 7764 /** 7765 * Returns true if application is not found or there was an error. Otherwise it returns 7766 * the blocked state of the package for the given user. 7767 */ 7768 @Override 7769 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7770 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7771 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7772 "getApplicationBlocked for user " + userId); 7773 PackageSetting pkgSetting; 7774 long callingId = Binder.clearCallingIdentity(); 7775 try { 7776 // writer 7777 synchronized (mPackages) { 7778 pkgSetting = mSettings.mPackages.get(packageName); 7779 if (pkgSetting == null) { 7780 return true; 7781 } 7782 return pkgSetting.getBlocked(userId); 7783 } 7784 } finally { 7785 Binder.restoreCallingIdentity(callingId); 7786 } 7787 } 7788 7789 void installStage(String basePackageName, File stageDir, IPackageInstallObserver2 observer, 7790 int flags) { 7791 // TODO: install stage! 7792 try { 7793 observer.packageInstalled(basePackageName, null, 7794 PackageManager.INSTALL_FAILED_INTERNAL_ERROR); 7795 } catch (RemoteException ignored) { 7796 } 7797 } 7798 7799 /** 7800 * @hide 7801 */ 7802 @Override 7803 public int installExistingPackageAsUser(String packageName, int userId) { 7804 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7805 null); 7806 PackageSetting pkgSetting; 7807 final int uid = Binder.getCallingUid(); 7808 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7809 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7810 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7811 } 7812 7813 long callingId = Binder.clearCallingIdentity(); 7814 try { 7815 boolean sendAdded = false; 7816 Bundle extras = new Bundle(1); 7817 7818 // writer 7819 synchronized (mPackages) { 7820 pkgSetting = mSettings.mPackages.get(packageName); 7821 if (pkgSetting == null) { 7822 return PackageManager.INSTALL_FAILED_INVALID_URI; 7823 } 7824 if (!pkgSetting.getInstalled(userId)) { 7825 pkgSetting.setInstalled(true, userId); 7826 pkgSetting.setBlocked(false, userId); 7827 mSettings.writePackageRestrictionsLPr(userId); 7828 sendAdded = true; 7829 } 7830 } 7831 7832 if (sendAdded) { 7833 sendPackageAddedForUser(packageName, pkgSetting, userId); 7834 } 7835 } finally { 7836 Binder.restoreCallingIdentity(callingId); 7837 } 7838 7839 return PackageManager.INSTALL_SUCCEEDED; 7840 } 7841 7842 boolean isUserRestricted(int userId, String restrictionKey) { 7843 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7844 if (restrictions.getBoolean(restrictionKey, false)) { 7845 Log.w(TAG, "User is restricted: " + restrictionKey); 7846 return true; 7847 } 7848 return false; 7849 } 7850 7851 @Override 7852 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7853 mContext.enforceCallingOrSelfPermission( 7854 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7855 "Only package verification agents can verify applications"); 7856 7857 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7858 final PackageVerificationResponse response = new PackageVerificationResponse( 7859 verificationCode, Binder.getCallingUid()); 7860 msg.arg1 = id; 7861 msg.obj = response; 7862 mHandler.sendMessage(msg); 7863 } 7864 7865 @Override 7866 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7867 long millisecondsToDelay) { 7868 mContext.enforceCallingOrSelfPermission( 7869 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7870 "Only package verification agents can extend verification timeouts"); 7871 7872 final PackageVerificationState state = mPendingVerification.get(id); 7873 final PackageVerificationResponse response = new PackageVerificationResponse( 7874 verificationCodeAtTimeout, Binder.getCallingUid()); 7875 7876 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7877 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7878 } 7879 if (millisecondsToDelay < 0) { 7880 millisecondsToDelay = 0; 7881 } 7882 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7883 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7884 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7885 } 7886 7887 if ((state != null) && !state.timeoutExtended()) { 7888 state.extendTimeout(); 7889 7890 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7891 msg.arg1 = id; 7892 msg.obj = response; 7893 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7894 } 7895 } 7896 7897 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7898 int verificationCode, UserHandle user) { 7899 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7900 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7901 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7902 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7903 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7904 7905 mContext.sendBroadcastAsUser(intent, user, 7906 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7907 } 7908 7909 private ComponentName matchComponentForVerifier(String packageName, 7910 List<ResolveInfo> receivers) { 7911 ActivityInfo targetReceiver = null; 7912 7913 final int NR = receivers.size(); 7914 for (int i = 0; i < NR; i++) { 7915 final ResolveInfo info = receivers.get(i); 7916 if (info.activityInfo == null) { 7917 continue; 7918 } 7919 7920 if (packageName.equals(info.activityInfo.packageName)) { 7921 targetReceiver = info.activityInfo; 7922 break; 7923 } 7924 } 7925 7926 if (targetReceiver == null) { 7927 return null; 7928 } 7929 7930 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 7931 } 7932 7933 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 7934 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 7935 if (pkgInfo.verifiers.length == 0) { 7936 return null; 7937 } 7938 7939 final int N = pkgInfo.verifiers.length; 7940 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 7941 for (int i = 0; i < N; i++) { 7942 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 7943 7944 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 7945 receivers); 7946 if (comp == null) { 7947 continue; 7948 } 7949 7950 final int verifierUid = getUidForVerifier(verifierInfo); 7951 if (verifierUid == -1) { 7952 continue; 7953 } 7954 7955 if (DEBUG_VERIFY) { 7956 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 7957 + " with the correct signature"); 7958 } 7959 sufficientVerifiers.add(comp); 7960 verificationState.addSufficientVerifier(verifierUid); 7961 } 7962 7963 return sufficientVerifiers; 7964 } 7965 7966 private int getUidForVerifier(VerifierInfo verifierInfo) { 7967 synchronized (mPackages) { 7968 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 7969 if (pkg == null) { 7970 return -1; 7971 } else if (pkg.mSignatures.length != 1) { 7972 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7973 + " has more than one signature; ignoring"); 7974 return -1; 7975 } 7976 7977 /* 7978 * If the public key of the package's signature does not match 7979 * our expected public key, then this is a different package and 7980 * we should skip. 7981 */ 7982 7983 final byte[] expectedPublicKey; 7984 try { 7985 final Signature verifierSig = pkg.mSignatures[0]; 7986 final PublicKey publicKey = verifierSig.getPublicKey(); 7987 expectedPublicKey = publicKey.getEncoded(); 7988 } catch (CertificateException e) { 7989 return -1; 7990 } 7991 7992 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 7993 7994 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 7995 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7996 + " does not have the expected public key; ignoring"); 7997 return -1; 7998 } 7999 8000 return pkg.applicationInfo.uid; 8001 } 8002 } 8003 8004 @Override 8005 public void finishPackageInstall(int token) { 8006 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8007 8008 if (DEBUG_INSTALL) { 8009 Slog.v(TAG, "BM finishing package install for " + token); 8010 } 8011 8012 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8013 mHandler.sendMessage(msg); 8014 } 8015 8016 /** 8017 * Get the verification agent timeout. 8018 * 8019 * @return verification timeout in milliseconds 8020 */ 8021 private long getVerificationTimeout() { 8022 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8023 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8024 DEFAULT_VERIFICATION_TIMEOUT); 8025 } 8026 8027 /** 8028 * Get the default verification agent response code. 8029 * 8030 * @return default verification response code 8031 */ 8032 private int getDefaultVerificationResponse() { 8033 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8034 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8035 DEFAULT_VERIFICATION_RESPONSE); 8036 } 8037 8038 /** 8039 * Check whether or not package verification has been enabled. 8040 * 8041 * @return true if verification should be performed 8042 */ 8043 private boolean isVerificationEnabled(int flags) { 8044 if (!DEFAULT_VERIFY_ENABLE) { 8045 return false; 8046 } 8047 8048 // Check if installing from ADB 8049 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8050 // Do not run verification in a test harness environment 8051 if (ActivityManager.isRunningInTestHarness()) { 8052 return false; 8053 } 8054 // Check if the developer does not want package verification for ADB installs 8055 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8056 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8057 return false; 8058 } 8059 } 8060 8061 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8062 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8063 } 8064 8065 /** 8066 * Get the "allow unknown sources" setting. 8067 * 8068 * @return the current "allow unknown sources" setting 8069 */ 8070 private int getUnknownSourcesSettings() { 8071 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8072 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8073 -1); 8074 } 8075 8076 @Override 8077 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8078 final int uid = Binder.getCallingUid(); 8079 // writer 8080 synchronized (mPackages) { 8081 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8082 if (targetPackageSetting == null) { 8083 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8084 } 8085 8086 PackageSetting installerPackageSetting; 8087 if (installerPackageName != null) { 8088 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8089 if (installerPackageSetting == null) { 8090 throw new IllegalArgumentException("Unknown installer package: " 8091 + installerPackageName); 8092 } 8093 } else { 8094 installerPackageSetting = null; 8095 } 8096 8097 Signature[] callerSignature; 8098 Object obj = mSettings.getUserIdLPr(uid); 8099 if (obj != null) { 8100 if (obj instanceof SharedUserSetting) { 8101 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8102 } else if (obj instanceof PackageSetting) { 8103 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8104 } else { 8105 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8106 } 8107 } else { 8108 throw new SecurityException("Unknown calling uid " + uid); 8109 } 8110 8111 // Verify: can't set installerPackageName to a package that is 8112 // not signed with the same cert as the caller. 8113 if (installerPackageSetting != null) { 8114 if (compareSignatures(callerSignature, 8115 installerPackageSetting.signatures.mSignatures) 8116 != PackageManager.SIGNATURE_MATCH) { 8117 throw new SecurityException( 8118 "Caller does not have same cert as new installer package " 8119 + installerPackageName); 8120 } 8121 } 8122 8123 // Verify: if target already has an installer package, it must 8124 // be signed with the same cert as the caller. 8125 if (targetPackageSetting.installerPackageName != null) { 8126 PackageSetting setting = mSettings.mPackages.get( 8127 targetPackageSetting.installerPackageName); 8128 // If the currently set package isn't valid, then it's always 8129 // okay to change it. 8130 if (setting != null) { 8131 if (compareSignatures(callerSignature, 8132 setting.signatures.mSignatures) 8133 != PackageManager.SIGNATURE_MATCH) { 8134 throw new SecurityException( 8135 "Caller does not have same cert as old installer package " 8136 + targetPackageSetting.installerPackageName); 8137 } 8138 } 8139 } 8140 8141 // Okay! 8142 targetPackageSetting.installerPackageName = installerPackageName; 8143 scheduleWriteSettingsLocked(); 8144 } 8145 } 8146 8147 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8148 // Queue up an async operation since the package installation may take a little while. 8149 mHandler.post(new Runnable() { 8150 public void run() { 8151 mHandler.removeCallbacks(this); 8152 // Result object to be returned 8153 PackageInstalledInfo res = new PackageInstalledInfo(); 8154 res.returnCode = currentStatus; 8155 res.uid = -1; 8156 res.pkg = null; 8157 res.removedInfo = new PackageRemovedInfo(); 8158 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8159 args.doPreInstall(res.returnCode); 8160 synchronized (mInstallLock) { 8161 installPackageLI(args, true, res); 8162 } 8163 args.doPostInstall(res.returnCode, res.uid); 8164 } 8165 8166 // A restore should be performed at this point if (a) the install 8167 // succeeded, (b) the operation is not an update, and (c) the new 8168 // package has a backupAgent defined. 8169 final boolean update = res.removedInfo.removedPackage != null; 8170 boolean doRestore = (!update 8171 && res.pkg != null 8172 && res.pkg.applicationInfo.backupAgentName != null); 8173 8174 // Set up the post-install work request bookkeeping. This will be used 8175 // and cleaned up by the post-install event handling regardless of whether 8176 // there's a restore pass performed. Token values are >= 1. 8177 int token; 8178 if (mNextInstallToken < 0) mNextInstallToken = 1; 8179 token = mNextInstallToken++; 8180 8181 PostInstallData data = new PostInstallData(args, res); 8182 mRunningInstalls.put(token, data); 8183 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8184 8185 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8186 // Pass responsibility to the Backup Manager. It will perform a 8187 // restore if appropriate, then pass responsibility back to the 8188 // Package Manager to run the post-install observer callbacks 8189 // and broadcasts. 8190 IBackupManager bm = IBackupManager.Stub.asInterface( 8191 ServiceManager.getService(Context.BACKUP_SERVICE)); 8192 if (bm != null) { 8193 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8194 + " to BM for possible restore"); 8195 try { 8196 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8197 } catch (RemoteException e) { 8198 // can't happen; the backup manager is local 8199 } catch (Exception e) { 8200 Slog.e(TAG, "Exception trying to enqueue restore", e); 8201 doRestore = false; 8202 } 8203 } else { 8204 Slog.e(TAG, "Backup Manager not found!"); 8205 doRestore = false; 8206 } 8207 } 8208 8209 if (!doRestore) { 8210 // No restore possible, or the Backup Manager was mysteriously not 8211 // available -- just fire the post-install work request directly. 8212 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8213 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8214 mHandler.sendMessage(msg); 8215 } 8216 } 8217 }); 8218 } 8219 8220 private abstract class HandlerParams { 8221 private static final int MAX_RETRIES = 4; 8222 8223 /** 8224 * Number of times startCopy() has been attempted and had a non-fatal 8225 * error. 8226 */ 8227 private int mRetries = 0; 8228 8229 /** User handle for the user requesting the information or installation. */ 8230 private final UserHandle mUser; 8231 8232 HandlerParams(UserHandle user) { 8233 mUser = user; 8234 } 8235 8236 UserHandle getUser() { 8237 return mUser; 8238 } 8239 8240 final boolean startCopy() { 8241 boolean res; 8242 try { 8243 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8244 8245 if (++mRetries > MAX_RETRIES) { 8246 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8247 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8248 handleServiceError(); 8249 return false; 8250 } else { 8251 handleStartCopy(); 8252 res = true; 8253 } 8254 } catch (RemoteException e) { 8255 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8256 mHandler.sendEmptyMessage(MCS_RECONNECT); 8257 res = false; 8258 } 8259 handleReturnCode(); 8260 return res; 8261 } 8262 8263 final void serviceError() { 8264 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8265 handleServiceError(); 8266 handleReturnCode(); 8267 } 8268 8269 abstract void handleStartCopy() throws RemoteException; 8270 abstract void handleServiceError(); 8271 abstract void handleReturnCode(); 8272 } 8273 8274 class MeasureParams extends HandlerParams { 8275 private final PackageStats mStats; 8276 private boolean mSuccess; 8277 8278 private final IPackageStatsObserver mObserver; 8279 8280 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8281 super(new UserHandle(stats.userHandle)); 8282 mObserver = observer; 8283 mStats = stats; 8284 } 8285 8286 @Override 8287 public String toString() { 8288 return "MeasureParams{" 8289 + Integer.toHexString(System.identityHashCode(this)) 8290 + " " + mStats.packageName + "}"; 8291 } 8292 8293 @Override 8294 void handleStartCopy() throws RemoteException { 8295 synchronized (mInstallLock) { 8296 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8297 } 8298 8299 if (mSuccess) { 8300 final boolean mounted; 8301 if (Environment.isExternalStorageEmulated()) { 8302 mounted = true; 8303 } else { 8304 final String status = Environment.getExternalStorageState(); 8305 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8306 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8307 } 8308 8309 if (mounted) { 8310 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8311 8312 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8313 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8314 8315 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8316 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8317 8318 // Always subtract cache size, since it's a subdirectory 8319 mStats.externalDataSize -= mStats.externalCacheSize; 8320 8321 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8322 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8323 8324 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8325 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8326 } 8327 } 8328 } 8329 8330 @Override 8331 void handleReturnCode() { 8332 if (mObserver != null) { 8333 try { 8334 mObserver.onGetStatsCompleted(mStats, mSuccess); 8335 } catch (RemoteException e) { 8336 Slog.i(TAG, "Observer no longer exists."); 8337 } 8338 } 8339 } 8340 8341 @Override 8342 void handleServiceError() { 8343 Slog.e(TAG, "Could not measure application " + mStats.packageName 8344 + " external storage"); 8345 } 8346 } 8347 8348 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8349 throws RemoteException { 8350 long result = 0; 8351 for (File path : paths) { 8352 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8353 } 8354 return result; 8355 } 8356 8357 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8358 for (File path : paths) { 8359 try { 8360 mcs.clearDirectory(path.getAbsolutePath()); 8361 } catch (RemoteException e) { 8362 } 8363 } 8364 } 8365 8366 class InstallParams extends HandlerParams { 8367 final IPackageInstallObserver observer; 8368 final IPackageInstallObserver2 observer2; 8369 int flags; 8370 8371 private final Uri mPackageURI; 8372 final String installerPackageName; 8373 final VerificationParams verificationParams; 8374 private InstallArgs mArgs; 8375 private int mRet; 8376 private File mTempPackage; 8377 final ContainerEncryptionParams encryptionParams; 8378 final String packageAbiOverride; 8379 final String packageInstructionSetOverride; 8380 8381 InstallParams(Uri packageURI, 8382 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 8383 int flags, String installerPackageName, VerificationParams verificationParams, 8384 ContainerEncryptionParams encryptionParams, UserHandle user, 8385 String packageAbiOverride) { 8386 super(user); 8387 this.mPackageURI = packageURI; 8388 this.flags = flags; 8389 this.observer = observer; 8390 this.observer2 = observer2; 8391 this.installerPackageName = installerPackageName; 8392 this.verificationParams = verificationParams; 8393 this.encryptionParams = encryptionParams; 8394 this.packageAbiOverride = packageAbiOverride; 8395 this.packageInstructionSetOverride = (packageAbiOverride == null) ? 8396 packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride); 8397 } 8398 8399 @Override 8400 public String toString() { 8401 return "InstallParams{" 8402 + Integer.toHexString(System.identityHashCode(this)) 8403 + " " + mPackageURI + "}"; 8404 } 8405 8406 public ManifestDigest getManifestDigest() { 8407 if (verificationParams == null) { 8408 return null; 8409 } 8410 return verificationParams.getManifestDigest(); 8411 } 8412 8413 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8414 String packageName = pkgLite.packageName; 8415 int installLocation = pkgLite.installLocation; 8416 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8417 // reader 8418 synchronized (mPackages) { 8419 PackageParser.Package pkg = mPackages.get(packageName); 8420 if (pkg != null) { 8421 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8422 // Check for downgrading. 8423 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8424 if (pkgLite.versionCode < pkg.mVersionCode) { 8425 Slog.w(TAG, "Can't install update of " + packageName 8426 + " update version " + pkgLite.versionCode 8427 + " is older than installed version " 8428 + pkg.mVersionCode); 8429 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8430 } 8431 } 8432 // Check for updated system application. 8433 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8434 if (onSd) { 8435 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8436 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8437 } 8438 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8439 } else { 8440 if (onSd) { 8441 // Install flag overrides everything. 8442 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8443 } 8444 // If current upgrade specifies particular preference 8445 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8446 // Application explicitly specified internal. 8447 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8448 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8449 // App explictly prefers external. Let policy decide 8450 } else { 8451 // Prefer previous location 8452 if (isExternal(pkg)) { 8453 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8454 } 8455 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8456 } 8457 } 8458 } else { 8459 // Invalid install. Return error code 8460 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8461 } 8462 } 8463 } 8464 // All the special cases have been taken care of. 8465 // Return result based on recommended install location. 8466 if (onSd) { 8467 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8468 } 8469 return pkgLite.recommendedInstallLocation; 8470 } 8471 8472 private long getMemoryLowThreshold() { 8473 final DeviceStorageMonitorInternal 8474 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8475 if (dsm == null) { 8476 return 0L; 8477 } 8478 return dsm.getMemoryLowThreshold(); 8479 } 8480 8481 /* 8482 * Invoke remote method to get package information and install 8483 * location values. Override install location based on default 8484 * policy if needed and then create install arguments based 8485 * on the install location. 8486 */ 8487 public void handleStartCopy() throws RemoteException { 8488 int ret = PackageManager.INSTALL_SUCCEEDED; 8489 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8490 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8491 PackageInfoLite pkgLite = null; 8492 8493 if (onInt && onSd) { 8494 // Check if both bits are set. 8495 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8496 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8497 } else { 8498 final long lowThreshold = getMemoryLowThreshold(); 8499 if (lowThreshold == 0L) { 8500 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8501 } 8502 8503 try { 8504 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI, 8505 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8506 8507 final File packageFile; 8508 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) { 8509 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir); 8510 if (mTempPackage != null) { 8511 ParcelFileDescriptor out; 8512 try { 8513 out = ParcelFileDescriptor.open(mTempPackage, 8514 ParcelFileDescriptor.MODE_READ_WRITE); 8515 } catch (FileNotFoundException e) { 8516 out = null; 8517 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI); 8518 } 8519 8520 // Make a temporary file for decryption. 8521 ret = mContainerService 8522 .copyResource(mPackageURI, encryptionParams, out); 8523 IoUtils.closeQuietly(out); 8524 8525 packageFile = mTempPackage; 8526 8527 FileUtils.setPermissions(packageFile.getAbsolutePath(), 8528 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP 8529 | FileUtils.S_IROTH, 8530 -1, -1); 8531 } else { 8532 packageFile = null; 8533 } 8534 } else { 8535 packageFile = new File(mPackageURI.getPath()); 8536 } 8537 8538 if (packageFile != null) { 8539 // Remote call to find out default install location 8540 final String packageFilePath = packageFile.getAbsolutePath(); 8541 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags, 8542 lowThreshold, packageAbiOverride); 8543 8544 /* 8545 * If we have too little free space, try to free cache 8546 * before giving up. 8547 */ 8548 if (pkgLite.recommendedInstallLocation 8549 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8550 final long size = mContainerService.calculateInstalledSize( 8551 packageFilePath, isForwardLocked(), packageAbiOverride); 8552 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8553 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, 8554 flags, lowThreshold, packageAbiOverride); 8555 } 8556 /* 8557 * The cache free must have deleted the file we 8558 * downloaded to install. 8559 * 8560 * TODO: fix the "freeCache" call to not delete 8561 * the file we care about. 8562 */ 8563 if (pkgLite.recommendedInstallLocation 8564 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8565 pkgLite.recommendedInstallLocation 8566 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8567 } 8568 } 8569 } 8570 } finally { 8571 mContext.revokeUriPermission(mPackageURI, 8572 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8573 } 8574 } 8575 8576 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8577 int loc = pkgLite.recommendedInstallLocation; 8578 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8579 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8580 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8581 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8582 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8583 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8584 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8585 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8586 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8587 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8588 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8589 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8590 } else { 8591 // Override with defaults if needed. 8592 loc = installLocationPolicy(pkgLite, flags); 8593 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8594 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8595 } else if (!onSd && !onInt) { 8596 // Override install location with flags 8597 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8598 // Set the flag to install on external media. 8599 flags |= PackageManager.INSTALL_EXTERNAL; 8600 flags &= ~PackageManager.INSTALL_INTERNAL; 8601 } else { 8602 // Make sure the flag for installing on external 8603 // media is unset 8604 flags |= PackageManager.INSTALL_INTERNAL; 8605 flags &= ~PackageManager.INSTALL_EXTERNAL; 8606 } 8607 } 8608 } 8609 } 8610 8611 final InstallArgs args = createInstallArgs(this); 8612 mArgs = args; 8613 8614 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8615 /* 8616 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8617 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8618 */ 8619 int userIdentifier = getUser().getIdentifier(); 8620 if (userIdentifier == UserHandle.USER_ALL 8621 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8622 userIdentifier = UserHandle.USER_OWNER; 8623 } 8624 8625 /* 8626 * Determine if we have any installed package verifiers. If we 8627 * do, then we'll defer to them to verify the packages. 8628 */ 8629 final int requiredUid = mRequiredVerifierPackage == null ? -1 8630 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8631 if (requiredUid != -1 && isVerificationEnabled(flags)) { 8632 final Intent verification = new Intent( 8633 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8634 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE); 8635 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8636 8637 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8638 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8639 0 /* TODO: Which userId? */); 8640 8641 if (DEBUG_VERIFY) { 8642 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8643 + verification.toString() + " with " + pkgLite.verifiers.length 8644 + " optional verifiers"); 8645 } 8646 8647 final int verificationId = mPendingVerificationToken++; 8648 8649 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8650 8651 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8652 installerPackageName); 8653 8654 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8655 8656 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8657 pkgLite.packageName); 8658 8659 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8660 pkgLite.versionCode); 8661 8662 if (verificationParams != null) { 8663 if (verificationParams.getVerificationURI() != null) { 8664 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8665 verificationParams.getVerificationURI()); 8666 } 8667 if (verificationParams.getOriginatingURI() != null) { 8668 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8669 verificationParams.getOriginatingURI()); 8670 } 8671 if (verificationParams.getReferrer() != null) { 8672 verification.putExtra(Intent.EXTRA_REFERRER, 8673 verificationParams.getReferrer()); 8674 } 8675 if (verificationParams.getOriginatingUid() >= 0) { 8676 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8677 verificationParams.getOriginatingUid()); 8678 } 8679 if (verificationParams.getInstallerUid() >= 0) { 8680 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8681 verificationParams.getInstallerUid()); 8682 } 8683 } 8684 8685 final PackageVerificationState verificationState = new PackageVerificationState( 8686 requiredUid, args); 8687 8688 mPendingVerification.append(verificationId, verificationState); 8689 8690 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8691 receivers, verificationState); 8692 8693 /* 8694 * If any sufficient verifiers were listed in the package 8695 * manifest, attempt to ask them. 8696 */ 8697 if (sufficientVerifiers != null) { 8698 final int N = sufficientVerifiers.size(); 8699 if (N == 0) { 8700 Slog.i(TAG, "Additional verifiers required, but none installed."); 8701 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8702 } else { 8703 for (int i = 0; i < N; i++) { 8704 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8705 8706 final Intent sufficientIntent = new Intent(verification); 8707 sufficientIntent.setComponent(verifierComponent); 8708 8709 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8710 } 8711 } 8712 } 8713 8714 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8715 mRequiredVerifierPackage, receivers); 8716 if (ret == PackageManager.INSTALL_SUCCEEDED 8717 && mRequiredVerifierPackage != null) { 8718 /* 8719 * Send the intent to the required verification agent, 8720 * but only start the verification timeout after the 8721 * target BroadcastReceivers have run. 8722 */ 8723 verification.setComponent(requiredVerifierComponent); 8724 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8725 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8726 new BroadcastReceiver() { 8727 @Override 8728 public void onReceive(Context context, Intent intent) { 8729 final Message msg = mHandler 8730 .obtainMessage(CHECK_PENDING_VERIFICATION); 8731 msg.arg1 = verificationId; 8732 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8733 } 8734 }, null, 0, null, null); 8735 8736 /* 8737 * We don't want the copy to proceed until verification 8738 * succeeds, so null out this field. 8739 */ 8740 mArgs = null; 8741 } 8742 } else { 8743 /* 8744 * No package verification is enabled, so immediately start 8745 * the remote call to initiate copy using temporary file. 8746 */ 8747 ret = args.copyApk(mContainerService, true); 8748 } 8749 } 8750 8751 mRet = ret; 8752 } 8753 8754 @Override 8755 void handleReturnCode() { 8756 // If mArgs is null, then MCS couldn't be reached. When it 8757 // reconnects, it will try again to install. At that point, this 8758 // will succeed. 8759 if (mArgs != null) { 8760 processPendingInstall(mArgs, mRet); 8761 8762 if (mTempPackage != null) { 8763 if (!mTempPackage.delete()) { 8764 Slog.w(TAG, "Couldn't delete temporary file: " + 8765 mTempPackage.getAbsolutePath()); 8766 } 8767 } 8768 } 8769 } 8770 8771 @Override 8772 void handleServiceError() { 8773 mArgs = createInstallArgs(this); 8774 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8775 } 8776 8777 public boolean isForwardLocked() { 8778 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8779 } 8780 8781 public Uri getPackageUri() { 8782 if (mTempPackage != null) { 8783 return Uri.fromFile(mTempPackage); 8784 } else { 8785 return mPackageURI; 8786 } 8787 } 8788 } 8789 8790 /* 8791 * Utility class used in movePackage api. 8792 * srcArgs and targetArgs are not set for invalid flags and make 8793 * sure to do null checks when invoking methods on them. 8794 * We probably want to return ErrorPrams for both failed installs 8795 * and moves. 8796 */ 8797 class MoveParams extends HandlerParams { 8798 final IPackageMoveObserver observer; 8799 final int flags; 8800 final String packageName; 8801 final InstallArgs srcArgs; 8802 final InstallArgs targetArgs; 8803 int uid; 8804 int mRet; 8805 8806 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8807 String packageName, String dataDir, String instructionSet, 8808 int uid, UserHandle user) { 8809 super(user); 8810 this.srcArgs = srcArgs; 8811 this.observer = observer; 8812 this.flags = flags; 8813 this.packageName = packageName; 8814 this.uid = uid; 8815 if (srcArgs != null) { 8816 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath())); 8817 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet); 8818 } else { 8819 targetArgs = null; 8820 } 8821 } 8822 8823 @Override 8824 public String toString() { 8825 return "MoveParams{" 8826 + Integer.toHexString(System.identityHashCode(this)) 8827 + " " + packageName + "}"; 8828 } 8829 8830 public void handleStartCopy() throws RemoteException { 8831 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8832 // Check for storage space on target medium 8833 if (!targetArgs.checkFreeStorage(mContainerService)) { 8834 Log.w(TAG, "Insufficient storage to install"); 8835 return; 8836 } 8837 8838 mRet = srcArgs.doPreCopy(); 8839 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8840 return; 8841 } 8842 8843 mRet = targetArgs.copyApk(mContainerService, false); 8844 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8845 srcArgs.doPostCopy(uid); 8846 return; 8847 } 8848 8849 mRet = srcArgs.doPostCopy(uid); 8850 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8851 return; 8852 } 8853 8854 mRet = targetArgs.doPreInstall(mRet); 8855 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8856 return; 8857 } 8858 8859 if (DEBUG_SD_INSTALL) { 8860 StringBuilder builder = new StringBuilder(); 8861 if (srcArgs != null) { 8862 builder.append("src: "); 8863 builder.append(srcArgs.getCodePath()); 8864 } 8865 if (targetArgs != null) { 8866 builder.append(" target : "); 8867 builder.append(targetArgs.getCodePath()); 8868 } 8869 Log.i(TAG, builder.toString()); 8870 } 8871 } 8872 8873 @Override 8874 void handleReturnCode() { 8875 targetArgs.doPostInstall(mRet, uid); 8876 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8877 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8878 currentStatus = PackageManager.MOVE_SUCCEEDED; 8879 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8880 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8881 } 8882 processPendingMove(this, currentStatus); 8883 } 8884 8885 @Override 8886 void handleServiceError() { 8887 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8888 } 8889 } 8890 8891 /** 8892 * Used during creation of InstallArgs 8893 * 8894 * @param flags package installation flags 8895 * @return true if should be installed on external storage 8896 */ 8897 private static boolean installOnSd(int flags) { 8898 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8899 return false; 8900 } 8901 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8902 return true; 8903 } 8904 return false; 8905 } 8906 8907 /** 8908 * Used during creation of InstallArgs 8909 * 8910 * @param flags package installation flags 8911 * @return true if should be installed as forward locked 8912 */ 8913 private static boolean installForwardLocked(int flags) { 8914 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8915 } 8916 8917 private InstallArgs createInstallArgs(InstallParams params) { 8918 if (installOnSd(params.flags) || params.isForwardLocked()) { 8919 return new AsecInstallArgs(params); 8920 } else { 8921 return new FileInstallArgs(params); 8922 } 8923 } 8924 8925 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath, 8926 String nativeLibraryPath, String instructionSet) { 8927 final boolean isInAsec; 8928 if (installOnSd(flags)) { 8929 /* Apps on SD card are always in ASEC containers. */ 8930 isInAsec = true; 8931 } else if (installForwardLocked(flags) 8932 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8933 /* 8934 * Forward-locked apps are only in ASEC containers if they're the 8935 * new style 8936 */ 8937 isInAsec = true; 8938 } else { 8939 isInAsec = false; 8940 } 8941 8942 if (isInAsec) { 8943 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8944 instructionSet, installOnSd(flags), installForwardLocked(flags)); 8945 } else { 8946 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8947 instructionSet); 8948 } 8949 } 8950 8951 // Used by package mover 8952 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir, 8953 String instructionSet) { 8954 if (installOnSd(flags) || installForwardLocked(flags)) { 8955 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/" 8956 + AsecInstallArgs.RES_FILE_NAME); 8957 return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags), 8958 installForwardLocked(flags)); 8959 } else { 8960 return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet); 8961 } 8962 } 8963 8964 static abstract class InstallArgs { 8965 final IPackageInstallObserver observer; 8966 final IPackageInstallObserver2 observer2; 8967 // Always refers to PackageManager flags only 8968 final int flags; 8969 final Uri packageURI; 8970 final String installerPackageName; 8971 final ManifestDigest manifestDigest; 8972 final UserHandle user; 8973 final String instructionSet; 8974 final String abiOverride; 8975 8976 InstallArgs(Uri packageURI, 8977 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 8978 int flags, String installerPackageName, ManifestDigest manifestDigest, 8979 UserHandle user, String instructionSet, String abiOverride) { 8980 this.packageURI = packageURI; 8981 this.flags = flags; 8982 this.observer = observer; 8983 this.observer2 = observer2; 8984 this.installerPackageName = installerPackageName; 8985 this.manifestDigest = manifestDigest; 8986 this.user = user; 8987 this.instructionSet = instructionSet; 8988 this.abiOverride = abiOverride; 8989 } 8990 8991 abstract void createCopyFile(); 8992 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 8993 abstract int doPreInstall(int status); 8994 abstract boolean doRename(int status, String pkgName, String oldCodePath); 8995 8996 abstract int doPostInstall(int status, int uid); 8997 abstract String getCodePath(); 8998 abstract String getResourcePath(); 8999 abstract String getNativeLibraryPath(); 9000 // Need installer lock especially for dex file removal. 9001 abstract void cleanUpResourcesLI(); 9002 abstract boolean doPostDeleteLI(boolean delete); 9003 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9004 9005 String[] getSplitCodePaths() { 9006 return null; 9007 } 9008 9009 /** 9010 * Called before the source arguments are copied. This is used mostly 9011 * for MoveParams when it needs to read the source file to put it in the 9012 * destination. 9013 */ 9014 int doPreCopy() { 9015 return PackageManager.INSTALL_SUCCEEDED; 9016 } 9017 9018 /** 9019 * Called after the source arguments are copied. This is used mostly for 9020 * MoveParams when it needs to read the source file to put it in the 9021 * destination. 9022 * 9023 * @return 9024 */ 9025 int doPostCopy(int uid) { 9026 return PackageManager.INSTALL_SUCCEEDED; 9027 } 9028 9029 protected boolean isFwdLocked() { 9030 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9031 } 9032 9033 UserHandle getUser() { 9034 return user; 9035 } 9036 } 9037 9038 class FileInstallArgs extends InstallArgs { 9039 File installDir; 9040 String codeFileName; 9041 String resourceFileName; 9042 String libraryPath; 9043 boolean created = false; 9044 9045 FileInstallArgs(InstallParams params) { 9046 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 9047 params.installerPackageName, params.getManifestDigest(), 9048 params.getUser(), params.packageInstructionSetOverride, 9049 params.packageAbiOverride); 9050 } 9051 9052 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9053 String instructionSet) { 9054 super(null, null, null, 0, null, null, null, instructionSet, null); 9055 File codeFile = new File(fullCodePath); 9056 installDir = codeFile.getParentFile(); 9057 codeFileName = fullCodePath; 9058 resourceFileName = fullResourcePath; 9059 libraryPath = nativeLibraryPath; 9060 } 9061 9062 FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) { 9063 super(packageURI, null, null, 0, null, null, null, instructionSet, null); 9064 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 9065 String apkName = getNextCodePath(null, pkgName, ".apk"); 9066 codeFileName = new File(installDir, apkName + ".apk").getPath(); 9067 resourceFileName = getResourcePathFromCodePath(); 9068 libraryPath = new File(mAppLibInstallDir, pkgName).getPath(); 9069 } 9070 9071 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9072 final long lowThreshold; 9073 9074 final DeviceStorageMonitorInternal 9075 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9076 if (dsm == null) { 9077 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9078 lowThreshold = 0L; 9079 } else { 9080 if (dsm.isMemoryLow()) { 9081 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9082 return false; 9083 } 9084 9085 lowThreshold = dsm.getMemoryLowThreshold(); 9086 } 9087 9088 try { 9089 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9090 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9091 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold); 9092 } finally { 9093 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9094 } 9095 } 9096 9097 void createCopyFile() { 9098 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 9099 codeFileName = createTempPackageFile(installDir).getPath(); 9100 resourceFileName = getResourcePathFromCodePath(); 9101 libraryPath = getLibraryPathFromCodePath(); 9102 created = true; 9103 } 9104 9105 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9106 if (temp) { 9107 // Generate temp file name 9108 createCopyFile(); 9109 } 9110 // Get a ParcelFileDescriptor to write to the output file 9111 File codeFile = new File(codeFileName); 9112 if (!created) { 9113 try { 9114 codeFile.createNewFile(); 9115 // Set permissions 9116 if (!setPermissions()) { 9117 // Failed setting permissions. 9118 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9119 } 9120 } catch (IOException e) { 9121 Slog.w(TAG, "Failed to create file " + codeFile); 9122 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9123 } 9124 } 9125 ParcelFileDescriptor out = null; 9126 try { 9127 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 9128 } catch (FileNotFoundException e) { 9129 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 9130 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9131 } 9132 // Copy the resource now 9133 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9134 try { 9135 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9136 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9137 ret = imcs.copyResource(packageURI, null, out); 9138 } finally { 9139 IoUtils.closeQuietly(out); 9140 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9141 } 9142 9143 if (isFwdLocked()) { 9144 final File destResourceFile = new File(getResourcePath()); 9145 9146 // Copy the public files 9147 try { 9148 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 9149 } catch (IOException e) { 9150 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 9151 + " forward-locked app."); 9152 destResourceFile.delete(); 9153 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9154 } 9155 } 9156 9157 final File nativeLibraryFile = new File(getNativeLibraryPath()); 9158 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath()); 9159 if (nativeLibraryFile.exists()) { 9160 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 9161 nativeLibraryFile.delete(); 9162 } 9163 9164 String[] abiList = (abiOverride != null) ? 9165 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9166 ApkHandle handle = null; 9167 try { 9168 handle = ApkHandle.create(codeFile); 9169 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 9170 abiOverride == null && 9171 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9172 abiList = Build.SUPPORTED_32_BIT_ABIS; 9173 } 9174 9175 int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList); 9176 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9177 return copyRet; 9178 } 9179 } catch (IOException e) { 9180 Slog.e(TAG, "Copying native libraries failed", e); 9181 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9182 } finally { 9183 IoUtils.closeQuietly(handle); 9184 } 9185 9186 return ret; 9187 } 9188 9189 int doPreInstall(int status) { 9190 if (status != PackageManager.INSTALL_SUCCEEDED) { 9191 cleanUp(); 9192 } 9193 return status; 9194 } 9195 9196 boolean doRename(int status, final String pkgName, String oldCodePath) { 9197 if (status != PackageManager.INSTALL_SUCCEEDED) { 9198 cleanUp(); 9199 return false; 9200 } else { 9201 final File oldCodeFile = new File(getCodePath()); 9202 final File oldResourceFile = new File(getResourcePath()); 9203 final File oldLibraryFile = new File(getNativeLibraryPath()); 9204 9205 // Rename APK file based on packageName 9206 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 9207 final File newCodeFile = new File(installDir, apkName + ".apk"); 9208 if (!oldCodeFile.renameTo(newCodeFile)) { 9209 return false; 9210 } 9211 codeFileName = newCodeFile.getPath(); 9212 9213 // Rename public resource file if it's forward-locked. 9214 final File newResFile = new File(getResourcePathFromCodePath()); 9215 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 9216 return false; 9217 } 9218 resourceFileName = newResFile.getPath(); 9219 9220 // Rename library path 9221 final File newLibraryFile = new File(getLibraryPathFromCodePath()); 9222 if (newLibraryFile.exists()) { 9223 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile); 9224 newLibraryFile.delete(); 9225 } 9226 if (!oldLibraryFile.renameTo(newLibraryFile)) { 9227 Slog.e(TAG, "Cannot rename native library directory " 9228 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath()); 9229 return false; 9230 } 9231 libraryPath = newLibraryFile.getPath(); 9232 9233 // Attempt to set permissions 9234 if (!setPermissions()) { 9235 return false; 9236 } 9237 9238 if (!SELinux.restorecon(newCodeFile)) { 9239 return false; 9240 } 9241 9242 return true; 9243 } 9244 } 9245 9246 int doPostInstall(int status, int uid) { 9247 if (status != PackageManager.INSTALL_SUCCEEDED) { 9248 cleanUp(); 9249 } 9250 return status; 9251 } 9252 9253 private String getResourcePathFromCodePath() { 9254 final String codePath = getCodePath(); 9255 if (isFwdLocked()) { 9256 final StringBuilder sb = new StringBuilder(); 9257 9258 sb.append(mAppInstallDir.getPath()); 9259 sb.append('/'); 9260 sb.append(getApkName(codePath)); 9261 sb.append(".zip"); 9262 9263 /* 9264 * If our APK is a temporary file, mark the resource as a 9265 * temporary file as well so it can be cleaned up after 9266 * catastrophic failure. 9267 */ 9268 if (codePath.endsWith(".tmp")) { 9269 sb.append(".tmp"); 9270 } 9271 9272 return sb.toString(); 9273 } else { 9274 return codePath; 9275 } 9276 } 9277 9278 private String getLibraryPathFromCodePath() { 9279 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath(); 9280 } 9281 9282 @Override 9283 String getCodePath() { 9284 return codeFileName; 9285 } 9286 9287 @Override 9288 String getResourcePath() { 9289 return resourceFileName; 9290 } 9291 9292 @Override 9293 String getNativeLibraryPath() { 9294 if (libraryPath == null) { 9295 libraryPath = getLibraryPathFromCodePath(); 9296 } 9297 return libraryPath; 9298 } 9299 9300 private boolean cleanUp() { 9301 boolean ret = true; 9302 String sourceDir = getCodePath(); 9303 String publicSourceDir = getResourcePath(); 9304 if (sourceDir != null) { 9305 File sourceFile = new File(sourceDir); 9306 if (!sourceFile.exists()) { 9307 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 9308 ret = false; 9309 } 9310 // Delete application's code and resources 9311 sourceFile.delete(); 9312 } 9313 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 9314 final File publicSourceFile = new File(publicSourceDir); 9315 if (!publicSourceFile.exists()) { 9316 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 9317 } 9318 if (publicSourceFile.exists()) { 9319 publicSourceFile.delete(); 9320 } 9321 } 9322 9323 if (libraryPath != null) { 9324 File nativeLibraryFile = new File(libraryPath); 9325 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 9326 if (!nativeLibraryFile.delete()) { 9327 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath); 9328 } 9329 } 9330 9331 return ret; 9332 } 9333 9334 void cleanUpResourcesLI() { 9335 String sourceDir = getCodePath(); 9336 if (cleanUp()) { 9337 if (instructionSet == null) { 9338 throw new IllegalStateException("instructionSet == null"); 9339 } 9340 int retCode = mInstaller.rmdex(sourceDir, instructionSet); 9341 if (retCode < 0) { 9342 Slog.w(TAG, "Couldn't remove dex file for package: " 9343 + " at location " 9344 + sourceDir + ", retcode=" + retCode); 9345 // we don't consider this to be a failure of the core package deletion 9346 } 9347 } 9348 } 9349 9350 private boolean setPermissions() { 9351 // TODO Do this in a more elegant way later on. for now just a hack 9352 if (!isFwdLocked()) { 9353 final int filePermissions = 9354 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 9355 |FileUtils.S_IROTH; 9356 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 9357 if (retCode != 0) { 9358 Slog.e(TAG, "Couldn't set new package file permissions for " + 9359 getCodePath() 9360 + ". The return code was: " + retCode); 9361 // TODO Define new internal error 9362 return false; 9363 } 9364 return true; 9365 } 9366 return true; 9367 } 9368 9369 boolean doPostDeleteLI(boolean delete) { 9370 // XXX err, shouldn't we respect the delete flag? 9371 cleanUpResourcesLI(); 9372 return true; 9373 } 9374 } 9375 9376 private boolean isAsecExternal(String cid) { 9377 final String asecPath = PackageHelper.getSdFilesystem(cid); 9378 return !asecPath.startsWith(mAsecInternalPath); 9379 } 9380 9381 /** 9382 * Extract the MountService "container ID" from the full code path of an 9383 * .apk. 9384 */ 9385 static String cidFromCodePath(String fullCodePath) { 9386 int eidx = fullCodePath.lastIndexOf("/"); 9387 String subStr1 = fullCodePath.substring(0, eidx); 9388 int sidx = subStr1.lastIndexOf("/"); 9389 return subStr1.substring(sidx+1, eidx); 9390 } 9391 9392 class AsecInstallArgs extends InstallArgs { 9393 static final String RES_FILE_NAME = "pkg.apk"; 9394 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9395 9396 String cid; 9397 String packagePath; 9398 String resourcePath; 9399 String libraryPath; 9400 9401 AsecInstallArgs(InstallParams params) { 9402 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 9403 params.installerPackageName, params.getManifestDigest(), 9404 params.getUser(), params.packageInstructionSetOverride, 9405 params.packageAbiOverride); 9406 } 9407 9408 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9409 String instructionSet, boolean isExternal, boolean isForwardLocked) { 9410 super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9411 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9412 null, null, null, instructionSet, null); 9413 // Extract cid from fullCodePath 9414 int eidx = fullCodePath.lastIndexOf("/"); 9415 String subStr1 = fullCodePath.substring(0, eidx); 9416 int sidx = subStr1.lastIndexOf("/"); 9417 cid = subStr1.substring(sidx+1, eidx); 9418 setCachePath(subStr1); 9419 } 9420 9421 AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) { 9422 super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 9423 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9424 null, null, null, instructionSet, null); 9425 this.cid = cid; 9426 setCachePath(PackageHelper.getSdDir(cid)); 9427 } 9428 9429 AsecInstallArgs(Uri packageURI, String cid, String instructionSet, 9430 boolean isExternal, boolean isForwardLocked) { 9431 super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9432 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9433 null, null, null, instructionSet, null); 9434 this.cid = cid; 9435 } 9436 9437 void createCopyFile() { 9438 cid = getTempContainerId(); 9439 } 9440 9441 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9442 try { 9443 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9444 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9445 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked(), abiOverride); 9446 } finally { 9447 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9448 } 9449 } 9450 9451 private final boolean isExternal() { 9452 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9453 } 9454 9455 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9456 if (temp) { 9457 createCopyFile(); 9458 } else { 9459 /* 9460 * Pre-emptively destroy the container since it's destroyed if 9461 * copying fails due to it existing anyway. 9462 */ 9463 PackageHelper.destroySdDir(cid); 9464 } 9465 9466 final String newCachePath; 9467 try { 9468 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9469 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9470 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(), 9471 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked(), 9472 abiOverride); 9473 } finally { 9474 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9475 } 9476 9477 if (newCachePath != null) { 9478 setCachePath(newCachePath); 9479 return PackageManager.INSTALL_SUCCEEDED; 9480 } else { 9481 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9482 } 9483 } 9484 9485 @Override 9486 String getCodePath() { 9487 return packagePath; 9488 } 9489 9490 @Override 9491 String getResourcePath() { 9492 return resourcePath; 9493 } 9494 9495 @Override 9496 String getNativeLibraryPath() { 9497 return libraryPath; 9498 } 9499 9500 int doPreInstall(int status) { 9501 if (status != PackageManager.INSTALL_SUCCEEDED) { 9502 // Destroy container 9503 PackageHelper.destroySdDir(cid); 9504 } else { 9505 boolean mounted = PackageHelper.isContainerMounted(cid); 9506 if (!mounted) { 9507 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9508 Process.SYSTEM_UID); 9509 if (newCachePath != null) { 9510 setCachePath(newCachePath); 9511 } else { 9512 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9513 } 9514 } 9515 } 9516 return status; 9517 } 9518 9519 boolean doRename(int status, final String pkgName, 9520 String oldCodePath) { 9521 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 9522 String newCachePath = null; 9523 if (PackageHelper.isContainerMounted(cid)) { 9524 // Unmount the container 9525 if (!PackageHelper.unMountSdDir(cid)) { 9526 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9527 return false; 9528 } 9529 } 9530 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9531 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9532 " which might be stale. Will try to clean up."); 9533 // Clean up the stale container and proceed to recreate. 9534 if (!PackageHelper.destroySdDir(newCacheId)) { 9535 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9536 return false; 9537 } 9538 // Successfully cleaned up stale container. Try to rename again. 9539 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9540 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9541 + " inspite of cleaning it up."); 9542 return false; 9543 } 9544 } 9545 if (!PackageHelper.isContainerMounted(newCacheId)) { 9546 Slog.w(TAG, "Mounting container " + newCacheId); 9547 newCachePath = PackageHelper.mountSdDir(newCacheId, 9548 getEncryptKey(), Process.SYSTEM_UID); 9549 } else { 9550 newCachePath = PackageHelper.getSdDir(newCacheId); 9551 } 9552 if (newCachePath == null) { 9553 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9554 return false; 9555 } 9556 Log.i(TAG, "Succesfully renamed " + cid + 9557 " to " + newCacheId + 9558 " at new path: " + newCachePath); 9559 cid = newCacheId; 9560 setCachePath(newCachePath); 9561 return true; 9562 } 9563 9564 private void setCachePath(String newCachePath) { 9565 File cachePath = new File(newCachePath); 9566 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 9567 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9568 9569 if (isFwdLocked()) { 9570 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9571 } else { 9572 resourcePath = packagePath; 9573 } 9574 } 9575 9576 int doPostInstall(int status, int uid) { 9577 if (status != PackageManager.INSTALL_SUCCEEDED) { 9578 cleanUp(); 9579 } else { 9580 final int groupOwner; 9581 final String protectedFile; 9582 if (isFwdLocked()) { 9583 groupOwner = UserHandle.getSharedAppGid(uid); 9584 protectedFile = RES_FILE_NAME; 9585 } else { 9586 groupOwner = -1; 9587 protectedFile = null; 9588 } 9589 9590 if (uid < Process.FIRST_APPLICATION_UID 9591 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9592 Slog.e(TAG, "Failed to finalize " + cid); 9593 PackageHelper.destroySdDir(cid); 9594 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9595 } 9596 9597 boolean mounted = PackageHelper.isContainerMounted(cid); 9598 if (!mounted) { 9599 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9600 } 9601 } 9602 return status; 9603 } 9604 9605 private void cleanUp() { 9606 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9607 9608 // Destroy secure container 9609 PackageHelper.destroySdDir(cid); 9610 } 9611 9612 void cleanUpResourcesLI() { 9613 String sourceFile = getCodePath(); 9614 // Remove dex file 9615 if (instructionSet == null) { 9616 throw new IllegalStateException("instructionSet == null"); 9617 } 9618 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9619 if (retCode < 0) { 9620 Slog.w(TAG, "Couldn't remove dex file for package: " 9621 + " at location " 9622 + sourceFile.toString() + ", retcode=" + retCode); 9623 // we don't consider this to be a failure of the core package deletion 9624 } 9625 cleanUp(); 9626 } 9627 9628 boolean matchContainer(String app) { 9629 if (cid.startsWith(app)) { 9630 return true; 9631 } 9632 return false; 9633 } 9634 9635 String getPackageName() { 9636 return getAsecPackageName(cid); 9637 } 9638 9639 boolean doPostDeleteLI(boolean delete) { 9640 boolean ret = false; 9641 boolean mounted = PackageHelper.isContainerMounted(cid); 9642 if (mounted) { 9643 // Unmount first 9644 ret = PackageHelper.unMountSdDir(cid); 9645 } 9646 if (ret && delete) { 9647 cleanUpResourcesLI(); 9648 } 9649 return ret; 9650 } 9651 9652 @Override 9653 int doPreCopy() { 9654 if (isFwdLocked()) { 9655 if (!PackageHelper.fixSdPermissions(cid, 9656 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9657 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9658 } 9659 } 9660 9661 return PackageManager.INSTALL_SUCCEEDED; 9662 } 9663 9664 @Override 9665 int doPostCopy(int uid) { 9666 if (isFwdLocked()) { 9667 if (uid < Process.FIRST_APPLICATION_UID 9668 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9669 RES_FILE_NAME)) { 9670 Slog.e(TAG, "Failed to finalize " + cid); 9671 PackageHelper.destroySdDir(cid); 9672 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9673 } 9674 } 9675 9676 return PackageManager.INSTALL_SUCCEEDED; 9677 } 9678 } 9679 9680 static String getAsecPackageName(String packageCid) { 9681 int idx = packageCid.lastIndexOf("-"); 9682 if (idx == -1) { 9683 return packageCid; 9684 } 9685 return packageCid.substring(0, idx); 9686 } 9687 9688 // Utility method used to create code paths based on package name and available index. 9689 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9690 String idxStr = ""; 9691 int idx = 1; 9692 // Fall back to default value of idx=1 if prefix is not 9693 // part of oldCodePath 9694 if (oldCodePath != null) { 9695 String subStr = oldCodePath; 9696 // Drop the suffix right away 9697 if (subStr.endsWith(suffix)) { 9698 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9699 } 9700 // If oldCodePath already contains prefix find out the 9701 // ending index to either increment or decrement. 9702 int sidx = subStr.lastIndexOf(prefix); 9703 if (sidx != -1) { 9704 subStr = subStr.substring(sidx + prefix.length()); 9705 if (subStr != null) { 9706 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9707 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9708 } 9709 try { 9710 idx = Integer.parseInt(subStr); 9711 if (idx <= 1) { 9712 idx++; 9713 } else { 9714 idx--; 9715 } 9716 } catch(NumberFormatException e) { 9717 } 9718 } 9719 } 9720 } 9721 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9722 return prefix + idxStr; 9723 } 9724 9725 // Utility method used to ignore ADD/REMOVE events 9726 // by directory observer. 9727 private static boolean ignoreCodePath(String fullPathStr) { 9728 String apkName = getApkName(fullPathStr); 9729 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9730 if (idx != -1 && ((idx+1) < apkName.length())) { 9731 // Make sure the package ends with a numeral 9732 String version = apkName.substring(idx+1); 9733 try { 9734 Integer.parseInt(version); 9735 return true; 9736 } catch (NumberFormatException e) {} 9737 } 9738 return false; 9739 } 9740 9741 // Utility method that returns the relative package path with respect 9742 // to the installation directory. Like say for /data/data/com.test-1.apk 9743 // string com.test-1 is returned. 9744 static String getApkName(String codePath) { 9745 if (codePath == null) { 9746 return null; 9747 } 9748 int sidx = codePath.lastIndexOf("/"); 9749 int eidx = codePath.lastIndexOf("."); 9750 if (eidx == -1) { 9751 eidx = codePath.length(); 9752 } else if (eidx == 0) { 9753 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 9754 return null; 9755 } 9756 return codePath.substring(sidx+1, eidx); 9757 } 9758 9759 private static String[] deriveSplitResPaths(String[] splitCodePaths) { 9760 String[] splitResPaths = null; 9761 if (!ArrayUtils.isEmpty(splitCodePaths)) { 9762 splitResPaths = new String[splitCodePaths.length]; 9763 for (int i = 0; i < splitCodePaths.length; i++) { 9764 final String splitCodePath = splitCodePaths[i]; 9765 final String resName = getApkName(splitCodePath) + ".zip"; 9766 splitResPaths[i] = new File(new File(splitCodePath).getParentFile(), 9767 resName).getAbsolutePath(); 9768 } 9769 } 9770 return splitResPaths; 9771 } 9772 9773 class PackageInstalledInfo { 9774 String name; 9775 int uid; 9776 // The set of users that originally had this package installed. 9777 int[] origUsers; 9778 // The set of users that now have this package installed. 9779 int[] newUsers; 9780 PackageParser.Package pkg; 9781 int returnCode; 9782 PackageRemovedInfo removedInfo; 9783 9784 // In some error cases we want to convey more info back to the observer 9785 String origPackage; 9786 String origPermission; 9787 } 9788 9789 /* 9790 * Install a non-existing package. 9791 */ 9792 private void installNewPackageLI(PackageParser.Package pkg, 9793 int parseFlags, int scanMode, UserHandle user, 9794 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9795 // Remember this for later, in case we need to rollback this install 9796 String pkgName = pkg.packageName; 9797 9798 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9799 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9800 synchronized(mPackages) { 9801 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9802 // A package with the same name is already installed, though 9803 // it has been renamed to an older name. The package we 9804 // are trying to install should be installed as an update to 9805 // the existing one, but that has not been requested, so bail. 9806 Slog.w(TAG, "Attempt to re-install " + pkgName 9807 + " without first uninstalling package running as " 9808 + mSettings.mRenamedPackages.get(pkgName)); 9809 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9810 return; 9811 } 9812 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9813 // Don't allow installation over an existing package with the same name. 9814 Slog.w(TAG, "Attempt to re-install " + pkgName 9815 + " without first uninstalling."); 9816 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9817 return; 9818 } 9819 } 9820 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9821 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9822 System.currentTimeMillis(), user, abiOverride); 9823 if (newPackage == null) { 9824 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9825 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9826 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9827 } 9828 } else { 9829 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9830 // delete the partially installed application. the data directory will have to be 9831 // restored if it was already existing 9832 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9833 // remove package from internal structures. Note that we want deletePackageX to 9834 // delete the package data and cache directories that it created in 9835 // scanPackageLocked, unless those directories existed before we even tried to 9836 // install. 9837 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9838 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9839 res.removedInfo, true); 9840 } 9841 } 9842 } 9843 9844 private void replacePackageLI(PackageParser.Package pkg, 9845 int parseFlags, int scanMode, UserHandle user, 9846 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9847 9848 PackageParser.Package oldPackage; 9849 String pkgName = pkg.packageName; 9850 int[] allUsers; 9851 boolean[] perUserInstalled; 9852 9853 // First find the old package info and check signatures 9854 synchronized(mPackages) { 9855 oldPackage = mPackages.get(pkgName); 9856 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9857 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9858 != PackageManager.SIGNATURE_MATCH) { 9859 Slog.w(TAG, "New package has a different signature: " + pkgName); 9860 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9861 return; 9862 } 9863 9864 // In case of rollback, remember per-user/profile install state 9865 PackageSetting ps = mSettings.mPackages.get(pkgName); 9866 allUsers = sUserManager.getUserIds(); 9867 perUserInstalled = new boolean[allUsers.length]; 9868 for (int i = 0; i < allUsers.length; i++) { 9869 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9870 } 9871 } 9872 boolean sysPkg = (isSystemApp(oldPackage)); 9873 if (sysPkg) { 9874 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9875 user, allUsers, perUserInstalled, installerPackageName, res, 9876 abiOverride); 9877 } else { 9878 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9879 user, allUsers, perUserInstalled, installerPackageName, res, 9880 abiOverride); 9881 } 9882 } 9883 9884 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9885 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9886 int[] allUsers, boolean[] perUserInstalled, 9887 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9888 PackageParser.Package newPackage = null; 9889 String pkgName = deletedPackage.packageName; 9890 boolean deletedPkg = true; 9891 boolean updatedSettings = false; 9892 9893 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9894 + deletedPackage); 9895 long origUpdateTime; 9896 if (pkg.mExtras != null) { 9897 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9898 } else { 9899 origUpdateTime = 0; 9900 } 9901 9902 // First delete the existing package while retaining the data directory 9903 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9904 res.removedInfo, true)) { 9905 // If the existing package wasn't successfully deleted 9906 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9907 deletedPkg = false; 9908 } else { 9909 // Successfully deleted the old package. Now proceed with re-installation 9910 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9911 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9912 System.currentTimeMillis(), user, abiOverride); 9913 if (newPackage == null) { 9914 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9915 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9916 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9917 } 9918 } else { 9919 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9920 updatedSettings = true; 9921 } 9922 } 9923 9924 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9925 // remove package from internal structures. Note that we want deletePackageX to 9926 // delete the package data and cache directories that it created in 9927 // scanPackageLocked, unless those directories existed before we even tried to 9928 // install. 9929 if(updatedSettings) { 9930 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9931 deletePackageLI( 9932 pkgName, null, true, allUsers, perUserInstalled, 9933 PackageManager.DELETE_KEEP_DATA, 9934 res.removedInfo, true); 9935 } 9936 // Since we failed to install the new package we need to restore the old 9937 // package that we deleted. 9938 if (deletedPkg) { 9939 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9940 File restoreFile = new File(deletedPackage.codePath); 9941 // Parse old package 9942 boolean oldOnSd = isExternal(deletedPackage); 9943 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9944 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9945 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9946 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 9947 | SCAN_UPDATE_TIME; 9948 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 9949 origUpdateTime, null, null) == null) { 9950 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 9951 return; 9952 } 9953 // Restore of old package succeeded. Update permissions. 9954 // writer 9955 synchronized (mPackages) { 9956 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9957 UPDATE_PERMISSIONS_ALL); 9958 // can downgrade to reader 9959 mSettings.writeLPr(); 9960 } 9961 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9962 } 9963 } 9964 } 9965 9966 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9967 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9968 int[] allUsers, boolean[] perUserInstalled, 9969 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9970 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9971 + ", old=" + deletedPackage); 9972 PackageParser.Package newPackage = null; 9973 boolean updatedSettings = false; 9974 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 9975 PackageParser.PARSE_IS_SYSTEM; 9976 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9977 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9978 } 9979 String packageName = deletedPackage.packageName; 9980 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9981 if (packageName == null) { 9982 Slog.w(TAG, "Attempt to delete null packageName."); 9983 return; 9984 } 9985 PackageParser.Package oldPkg; 9986 PackageSetting oldPkgSetting; 9987 // reader 9988 synchronized (mPackages) { 9989 oldPkg = mPackages.get(packageName); 9990 oldPkgSetting = mSettings.mPackages.get(packageName); 9991 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 9992 (oldPkgSetting == null)) { 9993 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 9994 return; 9995 } 9996 } 9997 9998 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 9999 10000 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10001 res.removedInfo.removedPackage = packageName; 10002 // Remove existing system package 10003 removePackageLI(oldPkgSetting, true); 10004 // writer 10005 synchronized (mPackages) { 10006 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10007 // We didn't need to disable the .apk as a current system package, 10008 // which means we are replacing another update that is already 10009 // installed. We need to make sure to delete the older one's .apk. 10010 res.removedInfo.args = createInstallArgs(0, 10011 deletedPackage.applicationInfo.sourceDir, 10012 deletedPackage.applicationInfo.publicSourceDir, 10013 deletedPackage.applicationInfo.nativeLibraryDir, 10014 getAppInstructionSet(deletedPackage.applicationInfo)); 10015 } else { 10016 res.removedInfo.args = null; 10017 } 10018 } 10019 10020 // Successfully disabled the old package. Now proceed with re-installation 10021 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 10022 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10023 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10024 if (newPackage == null) { 10025 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 10026 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 10027 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 10028 } 10029 } else { 10030 if (newPackage.mExtras != null) { 10031 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 10032 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10033 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10034 10035 // is the update attempting to change shared user? that isn't going to work... 10036 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10037 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 10038 + " to " + newPkgSetting.sharedUser); 10039 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 10040 updatedSettings = true; 10041 } 10042 } 10043 10044 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10045 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10046 updatedSettings = true; 10047 } 10048 } 10049 10050 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10051 // Re installation failed. Restore old information 10052 // Remove new pkg information 10053 if (newPackage != null) { 10054 removeInstalledPackageLI(newPackage, true); 10055 } 10056 // Add back the old system package 10057 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null); 10058 // Restore the old system information in Settings 10059 synchronized(mPackages) { 10060 if (updatedSettings) { 10061 mSettings.enableSystemPackageLPw(packageName); 10062 mSettings.setInstallerPackageName(packageName, 10063 oldPkgSetting.installerPackageName); 10064 } 10065 mSettings.writeLPr(); 10066 } 10067 } 10068 } 10069 10070 // Utility method used to move dex files during install. 10071 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10072 // TODO: extend to move split APK dex files 10073 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10074 final String instructionSet = getAppInstructionSet(newPackage.applicationInfo); 10075 int retCode = mInstaller.movedex(oldCodePath, newPackage.codePath, 10076 instructionSet); 10077 if (retCode != 0) { 10078 /* 10079 * Programs may be lazily run through dexopt, so the 10080 * source may not exist. However, something seems to 10081 * have gone wrong, so note that dexopt needs to be 10082 * run again and remove the source file. In addition, 10083 * remove the target to make sure there isn't a stale 10084 * file from a previous version of the package. 10085 */ 10086 newPackage.mDexOptNeeded = true; 10087 mInstaller.rmdex(oldCodePath, instructionSet); 10088 mInstaller.rmdex(newPackage.codePath, instructionSet); 10089 } 10090 } 10091 return PackageManager.INSTALL_SUCCEEDED; 10092 } 10093 10094 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10095 int[] allUsers, boolean[] perUserInstalled, 10096 PackageInstalledInfo res) { 10097 String pkgName = newPackage.packageName; 10098 synchronized (mPackages) { 10099 //write settings. the installStatus will be incomplete at this stage. 10100 //note that the new package setting would have already been 10101 //added to mPackages. It hasn't been persisted yet. 10102 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10103 mSettings.writeLPr(); 10104 } 10105 10106 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10107 10108 synchronized (mPackages) { 10109 updatePermissionsLPw(newPackage.packageName, newPackage, 10110 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10111 ? UPDATE_PERMISSIONS_ALL : 0)); 10112 // For system-bundled packages, we assume that installing an upgraded version 10113 // of the package implies that the user actually wants to run that new code, 10114 // so we enable the package. 10115 if (isSystemApp(newPackage)) { 10116 // NB: implicit assumption that system package upgrades apply to all users 10117 if (DEBUG_INSTALL) { 10118 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10119 } 10120 PackageSetting ps = mSettings.mPackages.get(pkgName); 10121 if (ps != null) { 10122 if (res.origUsers != null) { 10123 for (int userHandle : res.origUsers) { 10124 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10125 userHandle, installerPackageName); 10126 } 10127 } 10128 // Also convey the prior install/uninstall state 10129 if (allUsers != null && perUserInstalled != null) { 10130 for (int i = 0; i < allUsers.length; i++) { 10131 if (DEBUG_INSTALL) { 10132 Slog.d(TAG, " user " + allUsers[i] 10133 + " => " + perUserInstalled[i]); 10134 } 10135 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10136 } 10137 // these install state changes will be persisted in the 10138 // upcoming call to mSettings.writeLPr(). 10139 } 10140 } 10141 } 10142 res.name = pkgName; 10143 res.uid = newPackage.applicationInfo.uid; 10144 res.pkg = newPackage; 10145 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10146 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10147 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10148 //to update install status 10149 mSettings.writeLPr(); 10150 } 10151 } 10152 10153 private void installPackageLI(InstallArgs args, 10154 boolean newInstall, PackageInstalledInfo res) { 10155 int pFlags = args.flags; 10156 String installerPackageName = args.installerPackageName; 10157 File tmpPackageFile = new File(args.getCodePath()); 10158 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10159 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10160 boolean replace = false; 10161 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10162 | (newInstall ? SCAN_NEW_INSTALL : 0); 10163 // Result object to be returned 10164 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10165 10166 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10167 // Retrieve PackageSettings and parse package 10168 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10169 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10170 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10171 PackageParser pp = new PackageParser(); 10172 pp.setSeparateProcesses(mSeparateProcesses); 10173 pp.setDisplayMetrics(mMetrics); 10174 10175 final PackageParser.Package pkg; 10176 try { 10177 pkg = pp.parseMonolithicPackage(tmpPackageFile, parseFlags); 10178 } catch (PackageParserException e) { 10179 res.returnCode = e.error; 10180 return; 10181 } 10182 10183 String pkgName = res.name = pkg.packageName; 10184 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10185 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10186 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 10187 return; 10188 } 10189 } 10190 10191 try { 10192 pp.collectCertificates(pkg, parseFlags); 10193 pp.collectManifestDigest(pkg); 10194 } catch (PackageParserException e) { 10195 res.returnCode = e.error; 10196 return; 10197 } 10198 10199 /* If the installer passed in a manifest digest, compare it now. */ 10200 if (args.manifestDigest != null) { 10201 if (DEBUG_INSTALL) { 10202 final String parsedManifest = pkg.manifestDigest == null ? "null" 10203 : pkg.manifestDigest.toString(); 10204 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10205 + parsedManifest); 10206 } 10207 10208 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10209 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 10210 return; 10211 } 10212 } else if (DEBUG_INSTALL) { 10213 final String parsedManifest = pkg.manifestDigest == null 10214 ? "null" : pkg.manifestDigest.toString(); 10215 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10216 } 10217 10218 // Get rid of all references to package scan path via parser. 10219 pp = null; 10220 String oldCodePath = null; 10221 boolean systemApp = false; 10222 synchronized (mPackages) { 10223 // Check whether the newly-scanned package wants to define an already-defined perm 10224 int N = pkg.permissions.size(); 10225 for (int i = N-1; i >= 0; i--) { 10226 PackageParser.Permission perm = pkg.permissions.get(i); 10227 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10228 if (bp != null) { 10229 // If the defining package is signed with our cert, it's okay. This 10230 // also includes the "updating the same package" case, of course. 10231 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10232 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10233 // If the owning package is the system itself, we log but allow 10234 // install to proceed; we fail the install on all other permission 10235 // redefinitions. 10236 if (!bp.sourcePackage.equals("android")) { 10237 Slog.w(TAG, "Package " + pkg.packageName 10238 + " attempting to redeclare permission " + perm.info.name 10239 + " already owned by " + bp.sourcePackage); 10240 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 10241 res.origPermission = perm.info.name; 10242 res.origPackage = bp.sourcePackage; 10243 return; 10244 } else { 10245 Slog.w(TAG, "Package " + pkg.packageName 10246 + " attempting to redeclare system permission " 10247 + perm.info.name + "; ignoring new declaration"); 10248 pkg.permissions.remove(i); 10249 } 10250 } 10251 } 10252 } 10253 10254 // Check if installing already existing package 10255 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10256 String oldName = mSettings.mRenamedPackages.get(pkgName); 10257 if (pkg.mOriginalPackages != null 10258 && pkg.mOriginalPackages.contains(oldName) 10259 && mPackages.containsKey(oldName)) { 10260 // This package is derived from an original package, 10261 // and this device has been updating from that original 10262 // name. We must continue using the original name, so 10263 // rename the new package here. 10264 pkg.setPackageName(oldName); 10265 pkgName = pkg.packageName; 10266 replace = true; 10267 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10268 + oldName + " pkgName=" + pkgName); 10269 } else if (mPackages.containsKey(pkgName)) { 10270 // This package, under its official name, already exists 10271 // on the device; we should replace it. 10272 replace = true; 10273 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10274 } 10275 } 10276 PackageSetting ps = mSettings.mPackages.get(pkgName); 10277 if (ps != null) { 10278 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10279 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10280 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10281 systemApp = (ps.pkg.applicationInfo.flags & 10282 ApplicationInfo.FLAG_SYSTEM) != 0; 10283 } 10284 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10285 } 10286 } 10287 10288 if (systemApp && onSd) { 10289 // Disable updates to system apps on sdcard 10290 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 10291 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10292 return; 10293 } 10294 10295 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 10296 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10297 return; 10298 } 10299 // Set application objects path explicitly after the rename 10300 pkg.codePath = args.getCodePath(); 10301 pkg.applicationInfo.sourceDir = args.getCodePath(); 10302 pkg.applicationInfo.publicSourceDir = args.getResourcePath(); 10303 pkg.applicationInfo.splitSourceDirs = args.getSplitCodePaths(); 10304 pkg.applicationInfo.splitPublicSourceDirs = deriveSplitResPaths( 10305 pkg.applicationInfo.splitSourceDirs); 10306 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 10307 if (replace) { 10308 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10309 installerPackageName, res, args.abiOverride); 10310 } else { 10311 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10312 installerPackageName, res, args.abiOverride); 10313 } 10314 synchronized (mPackages) { 10315 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10316 if (ps != null) { 10317 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10318 } 10319 } 10320 } 10321 10322 private static boolean isForwardLocked(PackageParser.Package pkg) { 10323 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10324 } 10325 10326 10327 private boolean isForwardLocked(PackageSetting ps) { 10328 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10329 } 10330 10331 private static boolean isExternal(PackageParser.Package pkg) { 10332 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10333 } 10334 10335 private static boolean isExternal(PackageSetting ps) { 10336 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10337 } 10338 10339 private static boolean isSystemApp(PackageParser.Package pkg) { 10340 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10341 } 10342 10343 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10344 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10345 } 10346 10347 private static boolean isSystemApp(ApplicationInfo info) { 10348 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10349 } 10350 10351 private static boolean isSystemApp(PackageSetting ps) { 10352 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10353 } 10354 10355 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10356 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10357 } 10358 10359 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10360 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10361 } 10362 10363 private int packageFlagsToInstallFlags(PackageSetting ps) { 10364 int installFlags = 0; 10365 if (isExternal(ps)) { 10366 installFlags |= PackageManager.INSTALL_EXTERNAL; 10367 } 10368 if (isForwardLocked(ps)) { 10369 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10370 } 10371 return installFlags; 10372 } 10373 10374 private void deleteTempPackageFiles() { 10375 final FilenameFilter filter = new FilenameFilter() { 10376 public boolean accept(File dir, String name) { 10377 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10378 } 10379 }; 10380 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 10381 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 10382 } 10383 10384 private static final void deleteTempPackageFilesInDirectory(File directory, 10385 FilenameFilter filter) { 10386 final String[] tmpFilesList = directory.list(filter); 10387 if (tmpFilesList == null) { 10388 return; 10389 } 10390 for (int i = 0; i < tmpFilesList.length; i++) { 10391 final File tmpFile = new File(directory, tmpFilesList[i]); 10392 tmpFile.delete(); 10393 } 10394 } 10395 10396 private File createTempPackageFile(File installDir) { 10397 File tmpPackageFile; 10398 try { 10399 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 10400 } catch (IOException e) { 10401 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 10402 return null; 10403 } 10404 try { 10405 FileUtils.setPermissions( 10406 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 10407 -1, -1); 10408 if (!SELinux.restorecon(tmpPackageFile)) { 10409 return null; 10410 } 10411 } catch (IOException e) { 10412 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 10413 return null; 10414 } 10415 return tmpPackageFile; 10416 } 10417 10418 @Override 10419 public void deletePackageAsUser(final String packageName, 10420 final IPackageDeleteObserver observer, 10421 final int userId, final int flags) { 10422 mContext.enforceCallingOrSelfPermission( 10423 android.Manifest.permission.DELETE_PACKAGES, null); 10424 final int uid = Binder.getCallingUid(); 10425 if (UserHandle.getUserId(uid) != userId) { 10426 mContext.enforceCallingPermission( 10427 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10428 "deletePackage for user " + userId); 10429 } 10430 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10431 try { 10432 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10433 } catch (RemoteException re) { 10434 } 10435 return; 10436 } 10437 10438 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10439 // Queue up an async operation since the package deletion may take a little while. 10440 mHandler.post(new Runnable() { 10441 public void run() { 10442 mHandler.removeCallbacks(this); 10443 final int returnCode = deletePackageX(packageName, userId, flags); 10444 if (observer != null) { 10445 try { 10446 observer.packageDeleted(packageName, returnCode); 10447 } catch (RemoteException e) { 10448 Log.i(TAG, "Observer no longer exists."); 10449 } //end catch 10450 } //end if 10451 } //end run 10452 }); 10453 } 10454 10455 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10456 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10457 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10458 try { 10459 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10460 || dpm.isDeviceOwner(packageName))) { 10461 return true; 10462 } 10463 } catch (RemoteException e) { 10464 } 10465 return false; 10466 } 10467 10468 /** 10469 * This method is an internal method that could be get invoked either 10470 * to delete an installed package or to clean up a failed installation. 10471 * After deleting an installed package, a broadcast is sent to notify any 10472 * listeners that the package has been installed. For cleaning up a failed 10473 * installation, the broadcast is not necessary since the package's 10474 * installation wouldn't have sent the initial broadcast either 10475 * The key steps in deleting a package are 10476 * deleting the package information in internal structures like mPackages, 10477 * deleting the packages base directories through installd 10478 * updating mSettings to reflect current status 10479 * persisting settings for later use 10480 * sending a broadcast if necessary 10481 */ 10482 private int deletePackageX(String packageName, int userId, int flags) { 10483 final PackageRemovedInfo info = new PackageRemovedInfo(); 10484 final boolean res; 10485 10486 if (isPackageDeviceAdmin(packageName, userId)) { 10487 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10488 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10489 } 10490 10491 boolean removedForAllUsers = false; 10492 boolean systemUpdate = false; 10493 10494 // for the uninstall-updates case and restricted profiles, remember the per- 10495 // userhandle installed state 10496 int[] allUsers; 10497 boolean[] perUserInstalled; 10498 synchronized (mPackages) { 10499 PackageSetting ps = mSettings.mPackages.get(packageName); 10500 allUsers = sUserManager.getUserIds(); 10501 perUserInstalled = new boolean[allUsers.length]; 10502 for (int i = 0; i < allUsers.length; i++) { 10503 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10504 } 10505 } 10506 10507 synchronized (mInstallLock) { 10508 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10509 res = deletePackageLI(packageName, 10510 (flags & PackageManager.DELETE_ALL_USERS) != 0 10511 ? UserHandle.ALL : new UserHandle(userId), 10512 true, allUsers, perUserInstalled, 10513 flags | REMOVE_CHATTY, info, true); 10514 systemUpdate = info.isRemovedPackageSystemUpdate; 10515 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10516 removedForAllUsers = true; 10517 } 10518 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10519 + " removedForAllUsers=" + removedForAllUsers); 10520 } 10521 10522 if (res) { 10523 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10524 10525 // If the removed package was a system update, the old system package 10526 // was re-enabled; we need to broadcast this information 10527 if (systemUpdate) { 10528 Bundle extras = new Bundle(1); 10529 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10530 ? info.removedAppId : info.uid); 10531 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10532 10533 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10534 extras, null, null, null); 10535 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10536 extras, null, null, null); 10537 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10538 null, packageName, null, null); 10539 } 10540 } 10541 // Force a gc here. 10542 Runtime.getRuntime().gc(); 10543 // Delete the resources here after sending the broadcast to let 10544 // other processes clean up before deleting resources. 10545 if (info.args != null) { 10546 synchronized (mInstallLock) { 10547 info.args.doPostDeleteLI(true); 10548 } 10549 } 10550 10551 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10552 } 10553 10554 static class PackageRemovedInfo { 10555 String removedPackage; 10556 int uid = -1; 10557 int removedAppId = -1; 10558 int[] removedUsers = null; 10559 boolean isRemovedPackageSystemUpdate = false; 10560 // Clean up resources deleted packages. 10561 InstallArgs args = null; 10562 10563 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10564 Bundle extras = new Bundle(1); 10565 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10566 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10567 if (replacing) { 10568 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10569 } 10570 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10571 if (removedPackage != null) { 10572 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10573 extras, null, null, removedUsers); 10574 if (fullRemove && !replacing) { 10575 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10576 extras, null, null, removedUsers); 10577 } 10578 } 10579 if (removedAppId >= 0) { 10580 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10581 removedUsers); 10582 } 10583 } 10584 } 10585 10586 /* 10587 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10588 * flag is not set, the data directory is removed as well. 10589 * make sure this flag is set for partially installed apps. If not its meaningless to 10590 * delete a partially installed application. 10591 */ 10592 private void removePackageDataLI(PackageSetting ps, 10593 int[] allUserHandles, boolean[] perUserInstalled, 10594 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10595 String packageName = ps.name; 10596 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10597 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10598 // Retrieve object to delete permissions for shared user later on 10599 final PackageSetting deletedPs; 10600 // reader 10601 synchronized (mPackages) { 10602 deletedPs = mSettings.mPackages.get(packageName); 10603 if (outInfo != null) { 10604 outInfo.removedPackage = packageName; 10605 outInfo.removedUsers = deletedPs != null 10606 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10607 : null; 10608 } 10609 } 10610 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10611 removeDataDirsLI(packageName); 10612 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10613 } 10614 // writer 10615 synchronized (mPackages) { 10616 if (deletedPs != null) { 10617 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10618 if (outInfo != null) { 10619 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10620 } 10621 if (deletedPs != null) { 10622 updatePermissionsLPw(deletedPs.name, null, 0); 10623 if (deletedPs.sharedUser != null) { 10624 // remove permissions associated with package 10625 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10626 } 10627 } 10628 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10629 } 10630 // make sure to preserve per-user disabled state if this removal was just 10631 // a downgrade of a system app to the factory package 10632 if (allUserHandles != null && perUserInstalled != null) { 10633 if (DEBUG_REMOVE) { 10634 Slog.d(TAG, "Propagating install state across downgrade"); 10635 } 10636 for (int i = 0; i < allUserHandles.length; i++) { 10637 if (DEBUG_REMOVE) { 10638 Slog.d(TAG, " user " + allUserHandles[i] 10639 + " => " + perUserInstalled[i]); 10640 } 10641 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10642 } 10643 } 10644 } 10645 // can downgrade to reader 10646 if (writeSettings) { 10647 // Save settings now 10648 mSettings.writeLPr(); 10649 } 10650 } 10651 if (outInfo != null) { 10652 // A user ID was deleted here. Go through all users and remove it 10653 // from KeyStore. 10654 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10655 } 10656 } 10657 10658 static boolean locationIsPrivileged(File path) { 10659 try { 10660 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10661 .getCanonicalPath(); 10662 return path.getCanonicalPath().startsWith(privilegedAppDir); 10663 } catch (IOException e) { 10664 Slog.e(TAG, "Unable to access code path " + path); 10665 } 10666 return false; 10667 } 10668 10669 /* 10670 * Tries to delete system package. 10671 */ 10672 private boolean deleteSystemPackageLI(PackageSetting newPs, 10673 int[] allUserHandles, boolean[] perUserInstalled, 10674 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10675 final boolean applyUserRestrictions 10676 = (allUserHandles != null) && (perUserInstalled != null); 10677 PackageSetting disabledPs = null; 10678 // Confirm if the system package has been updated 10679 // An updated system app can be deleted. This will also have to restore 10680 // the system pkg from system partition 10681 // reader 10682 synchronized (mPackages) { 10683 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10684 } 10685 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10686 + " disabledPs=" + disabledPs); 10687 if (disabledPs == null) { 10688 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10689 return false; 10690 } else if (DEBUG_REMOVE) { 10691 Slog.d(TAG, "Deleting system pkg from data partition"); 10692 } 10693 if (DEBUG_REMOVE) { 10694 if (applyUserRestrictions) { 10695 Slog.d(TAG, "Remembering install states:"); 10696 for (int i = 0; i < allUserHandles.length; i++) { 10697 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10698 } 10699 } 10700 } 10701 // Delete the updated package 10702 outInfo.isRemovedPackageSystemUpdate = true; 10703 if (disabledPs.versionCode < newPs.versionCode) { 10704 // Delete data for downgrades 10705 flags &= ~PackageManager.DELETE_KEEP_DATA; 10706 } else { 10707 // Preserve data by setting flag 10708 flags |= PackageManager.DELETE_KEEP_DATA; 10709 } 10710 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10711 allUserHandles, perUserInstalled, outInfo, writeSettings); 10712 if (!ret) { 10713 return false; 10714 } 10715 // writer 10716 synchronized (mPackages) { 10717 // Reinstate the old system package 10718 mSettings.enableSystemPackageLPw(newPs.name); 10719 // Remove any native libraries from the upgraded package. 10720 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 10721 } 10722 // Install the system package 10723 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10724 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10725 if (locationIsPrivileged(disabledPs.codePath)) { 10726 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10727 } 10728 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10729 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null); 10730 10731 if (newPkg == null) { 10732 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10733 + " with error:" + mLastScanError); 10734 return false; 10735 } 10736 // writer 10737 synchronized (mPackages) { 10738 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10739 setInternalAppNativeLibraryPath(newPkg, ps); 10740 updatePermissionsLPw(newPkg.packageName, newPkg, 10741 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10742 if (applyUserRestrictions) { 10743 if (DEBUG_REMOVE) { 10744 Slog.d(TAG, "Propagating install state across reinstall"); 10745 } 10746 for (int i = 0; i < allUserHandles.length; i++) { 10747 if (DEBUG_REMOVE) { 10748 Slog.d(TAG, " user " + allUserHandles[i] 10749 + " => " + perUserInstalled[i]); 10750 } 10751 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10752 } 10753 // Regardless of writeSettings we need to ensure that this restriction 10754 // state propagation is persisted 10755 mSettings.writeAllUsersPackageRestrictionsLPr(); 10756 } 10757 // can downgrade to reader here 10758 if (writeSettings) { 10759 mSettings.writeLPr(); 10760 } 10761 } 10762 return true; 10763 } 10764 10765 private boolean deleteInstalledPackageLI(PackageSetting ps, 10766 boolean deleteCodeAndResources, int flags, 10767 int[] allUserHandles, boolean[] perUserInstalled, 10768 PackageRemovedInfo outInfo, boolean writeSettings) { 10769 if (outInfo != null) { 10770 outInfo.uid = ps.appId; 10771 } 10772 10773 // Delete package data from internal structures and also remove data if flag is set 10774 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10775 10776 // Delete application code and resources 10777 if (deleteCodeAndResources && (outInfo != null)) { 10778 outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString, 10779 ps.resourcePathString, ps.nativeLibraryPathString, 10780 getAppInstructionSetFromSettings(ps)); 10781 } 10782 return true; 10783 } 10784 10785 /* 10786 * This method handles package deletion in general 10787 */ 10788 private boolean deletePackageLI(String packageName, UserHandle user, 10789 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10790 int flags, PackageRemovedInfo outInfo, 10791 boolean writeSettings) { 10792 if (packageName == null) { 10793 Slog.w(TAG, "Attempt to delete null packageName."); 10794 return false; 10795 } 10796 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10797 PackageSetting ps; 10798 boolean dataOnly = false; 10799 int removeUser = -1; 10800 int appId = -1; 10801 synchronized (mPackages) { 10802 ps = mSettings.mPackages.get(packageName); 10803 if (ps == null) { 10804 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10805 return false; 10806 } 10807 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10808 && user.getIdentifier() != UserHandle.USER_ALL) { 10809 // The caller is asking that the package only be deleted for a single 10810 // user. To do this, we just mark its uninstalled state and delete 10811 // its data. If this is a system app, we only allow this to happen if 10812 // they have set the special DELETE_SYSTEM_APP which requests different 10813 // semantics than normal for uninstalling system apps. 10814 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10815 ps.setUserState(user.getIdentifier(), 10816 COMPONENT_ENABLED_STATE_DEFAULT, 10817 false, //installed 10818 true, //stopped 10819 true, //notLaunched 10820 false, //blocked 10821 null, null, null); 10822 if (!isSystemApp(ps)) { 10823 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10824 // Other user still have this package installed, so all 10825 // we need to do is clear this user's data and save that 10826 // it is uninstalled. 10827 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10828 removeUser = user.getIdentifier(); 10829 appId = ps.appId; 10830 mSettings.writePackageRestrictionsLPr(removeUser); 10831 } else { 10832 // We need to set it back to 'installed' so the uninstall 10833 // broadcasts will be sent correctly. 10834 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10835 ps.setInstalled(true, user.getIdentifier()); 10836 } 10837 } else { 10838 // This is a system app, so we assume that the 10839 // other users still have this package installed, so all 10840 // we need to do is clear this user's data and save that 10841 // it is uninstalled. 10842 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10843 removeUser = user.getIdentifier(); 10844 appId = ps.appId; 10845 mSettings.writePackageRestrictionsLPr(removeUser); 10846 } 10847 } 10848 } 10849 10850 if (removeUser >= 0) { 10851 // From above, we determined that we are deleting this only 10852 // for a single user. Continue the work here. 10853 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10854 if (outInfo != null) { 10855 outInfo.removedPackage = packageName; 10856 outInfo.removedAppId = appId; 10857 outInfo.removedUsers = new int[] {removeUser}; 10858 } 10859 mInstaller.clearUserData(packageName, removeUser); 10860 removeKeystoreDataIfNeeded(removeUser, appId); 10861 schedulePackageCleaning(packageName, removeUser, false); 10862 return true; 10863 } 10864 10865 if (dataOnly) { 10866 // Delete application data first 10867 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10868 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10869 return true; 10870 } 10871 10872 boolean ret = false; 10873 mSettings.mKeySetManager.removeAppKeySetData(packageName); 10874 if (isSystemApp(ps)) { 10875 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10876 // When an updated system application is deleted we delete the existing resources as well and 10877 // fall back to existing code in system partition 10878 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10879 flags, outInfo, writeSettings); 10880 } else { 10881 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10882 // Kill application pre-emptively especially for apps on sd. 10883 killApplication(packageName, ps.appId, "uninstall pkg"); 10884 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10885 allUserHandles, perUserInstalled, 10886 outInfo, writeSettings); 10887 } 10888 10889 return ret; 10890 } 10891 10892 private final class ClearStorageConnection implements ServiceConnection { 10893 IMediaContainerService mContainerService; 10894 10895 @Override 10896 public void onServiceConnected(ComponentName name, IBinder service) { 10897 synchronized (this) { 10898 mContainerService = IMediaContainerService.Stub.asInterface(service); 10899 notifyAll(); 10900 } 10901 } 10902 10903 @Override 10904 public void onServiceDisconnected(ComponentName name) { 10905 } 10906 } 10907 10908 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10909 final boolean mounted; 10910 if (Environment.isExternalStorageEmulated()) { 10911 mounted = true; 10912 } else { 10913 final String status = Environment.getExternalStorageState(); 10914 10915 mounted = status.equals(Environment.MEDIA_MOUNTED) 10916 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10917 } 10918 10919 if (!mounted) { 10920 return; 10921 } 10922 10923 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10924 int[] users; 10925 if (userId == UserHandle.USER_ALL) { 10926 users = sUserManager.getUserIds(); 10927 } else { 10928 users = new int[] { userId }; 10929 } 10930 final ClearStorageConnection conn = new ClearStorageConnection(); 10931 if (mContext.bindServiceAsUser( 10932 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10933 try { 10934 for (int curUser : users) { 10935 long timeout = SystemClock.uptimeMillis() + 5000; 10936 synchronized (conn) { 10937 long now = SystemClock.uptimeMillis(); 10938 while (conn.mContainerService == null && now < timeout) { 10939 try { 10940 conn.wait(timeout - now); 10941 } catch (InterruptedException e) { 10942 } 10943 } 10944 } 10945 if (conn.mContainerService == null) { 10946 return; 10947 } 10948 10949 final UserEnvironment userEnv = new UserEnvironment(curUser); 10950 clearDirectory(conn.mContainerService, 10951 userEnv.buildExternalStorageAppCacheDirs(packageName)); 10952 if (allData) { 10953 clearDirectory(conn.mContainerService, 10954 userEnv.buildExternalStorageAppDataDirs(packageName)); 10955 clearDirectory(conn.mContainerService, 10956 userEnv.buildExternalStorageAppMediaDirs(packageName)); 10957 } 10958 } 10959 } finally { 10960 mContext.unbindService(conn); 10961 } 10962 } 10963 } 10964 10965 @Override 10966 public void clearApplicationUserData(final String packageName, 10967 final IPackageDataObserver observer, final int userId) { 10968 mContext.enforceCallingOrSelfPermission( 10969 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 10970 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 10971 // Queue up an async operation since the package deletion may take a little while. 10972 mHandler.post(new Runnable() { 10973 public void run() { 10974 mHandler.removeCallbacks(this); 10975 final boolean succeeded; 10976 synchronized (mInstallLock) { 10977 succeeded = clearApplicationUserDataLI(packageName, userId); 10978 } 10979 clearExternalStorageDataSync(packageName, userId, true); 10980 if (succeeded) { 10981 // invoke DeviceStorageMonitor's update method to clear any notifications 10982 DeviceStorageMonitorInternal 10983 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 10984 if (dsm != null) { 10985 dsm.checkMemory(); 10986 } 10987 } 10988 if(observer != null) { 10989 try { 10990 observer.onRemoveCompleted(packageName, succeeded); 10991 } catch (RemoteException e) { 10992 Log.i(TAG, "Observer no longer exists."); 10993 } 10994 } //end if observer 10995 } //end run 10996 }); 10997 } 10998 10999 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11000 if (packageName == null) { 11001 Slog.w(TAG, "Attempt to delete null packageName."); 11002 return false; 11003 } 11004 PackageParser.Package p; 11005 boolean dataOnly = false; 11006 final int appId; 11007 synchronized (mPackages) { 11008 p = mPackages.get(packageName); 11009 if (p == null) { 11010 dataOnly = true; 11011 PackageSetting ps = mSettings.mPackages.get(packageName); 11012 if ((ps == null) || (ps.pkg == null)) { 11013 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11014 return false; 11015 } 11016 p = ps.pkg; 11017 } 11018 if (!dataOnly) { 11019 // need to check this only for fully installed applications 11020 if (p == null) { 11021 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11022 return false; 11023 } 11024 final ApplicationInfo applicationInfo = p.applicationInfo; 11025 if (applicationInfo == null) { 11026 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11027 return false; 11028 } 11029 } 11030 if (p != null && p.applicationInfo != null) { 11031 appId = p.applicationInfo.uid; 11032 } else { 11033 appId = -1; 11034 } 11035 } 11036 int retCode = mInstaller.clearUserData(packageName, userId); 11037 if (retCode < 0) { 11038 Slog.w(TAG, "Couldn't remove cache files for package: " 11039 + packageName); 11040 return false; 11041 } 11042 removeKeystoreDataIfNeeded(userId, appId); 11043 return true; 11044 } 11045 11046 /** 11047 * Remove entries from the keystore daemon. Will only remove it if the 11048 * {@code appId} is valid. 11049 */ 11050 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11051 if (appId < 0) { 11052 return; 11053 } 11054 11055 final KeyStore keyStore = KeyStore.getInstance(); 11056 if (keyStore != null) { 11057 if (userId == UserHandle.USER_ALL) { 11058 for (final int individual : sUserManager.getUserIds()) { 11059 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11060 } 11061 } else { 11062 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11063 } 11064 } else { 11065 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11066 } 11067 } 11068 11069 @Override 11070 public void deleteApplicationCacheFiles(final String packageName, 11071 final IPackageDataObserver observer) { 11072 mContext.enforceCallingOrSelfPermission( 11073 android.Manifest.permission.DELETE_CACHE_FILES, null); 11074 // Queue up an async operation since the package deletion may take a little while. 11075 final int userId = UserHandle.getCallingUserId(); 11076 mHandler.post(new Runnable() { 11077 public void run() { 11078 mHandler.removeCallbacks(this); 11079 final boolean succeded; 11080 synchronized (mInstallLock) { 11081 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11082 } 11083 clearExternalStorageDataSync(packageName, userId, false); 11084 if(observer != null) { 11085 try { 11086 observer.onRemoveCompleted(packageName, succeded); 11087 } catch (RemoteException e) { 11088 Log.i(TAG, "Observer no longer exists."); 11089 } 11090 } //end if observer 11091 } //end run 11092 }); 11093 } 11094 11095 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11096 if (packageName == null) { 11097 Slog.w(TAG, "Attempt to delete null packageName."); 11098 return false; 11099 } 11100 PackageParser.Package p; 11101 synchronized (mPackages) { 11102 p = mPackages.get(packageName); 11103 } 11104 if (p == null) { 11105 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11106 return false; 11107 } 11108 final ApplicationInfo applicationInfo = p.applicationInfo; 11109 if (applicationInfo == null) { 11110 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11111 return false; 11112 } 11113 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11114 if (retCode < 0) { 11115 Slog.w(TAG, "Couldn't remove cache files for package: " 11116 + packageName + " u" + userId); 11117 return false; 11118 } 11119 return true; 11120 } 11121 11122 @Override 11123 public void getPackageSizeInfo(final String packageName, int userHandle, 11124 final IPackageStatsObserver observer) { 11125 mContext.enforceCallingOrSelfPermission( 11126 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11127 if (packageName == null) { 11128 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11129 } 11130 11131 PackageStats stats = new PackageStats(packageName, userHandle); 11132 11133 /* 11134 * Queue up an async operation since the package measurement may take a 11135 * little while. 11136 */ 11137 Message msg = mHandler.obtainMessage(INIT_COPY); 11138 msg.obj = new MeasureParams(stats, observer); 11139 mHandler.sendMessage(msg); 11140 } 11141 11142 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11143 PackageStats pStats) { 11144 if (packageName == null) { 11145 Slog.w(TAG, "Attempt to get size of null packageName."); 11146 return false; 11147 } 11148 PackageParser.Package p; 11149 boolean dataOnly = false; 11150 String libDirPath = null; 11151 String asecPath = null; 11152 PackageSetting ps = null; 11153 synchronized (mPackages) { 11154 p = mPackages.get(packageName); 11155 ps = mSettings.mPackages.get(packageName); 11156 if(p == null) { 11157 dataOnly = true; 11158 if((ps == null) || (ps.pkg == null)) { 11159 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11160 return false; 11161 } 11162 p = ps.pkg; 11163 } 11164 if (ps != null) { 11165 libDirPath = ps.nativeLibraryPathString; 11166 } 11167 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11168 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 11169 if (secureContainerId != null) { 11170 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11171 } 11172 } 11173 } 11174 String publicSrcDir = null; 11175 if(!dataOnly) { 11176 final ApplicationInfo applicationInfo = p.applicationInfo; 11177 if (applicationInfo == null) { 11178 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11179 return false; 11180 } 11181 if (isForwardLocked(p)) { 11182 publicSrcDir = applicationInfo.publicSourceDir; 11183 } 11184 } 11185 int res = mInstaller.getSizeInfo(packageName, userHandle, p.codePath, libDirPath, 11186 publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps), 11187 pStats); 11188 if (res < 0) { 11189 return false; 11190 } 11191 11192 // Fix-up for forward-locked applications in ASEC containers. 11193 if (!isExternal(p)) { 11194 pStats.codeSize += pStats.externalCodeSize; 11195 pStats.externalCodeSize = 0L; 11196 } 11197 11198 return true; 11199 } 11200 11201 11202 @Override 11203 public void addPackageToPreferred(String packageName) { 11204 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11205 } 11206 11207 @Override 11208 public void removePackageFromPreferred(String packageName) { 11209 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11210 } 11211 11212 @Override 11213 public List<PackageInfo> getPreferredPackages(int flags) { 11214 return new ArrayList<PackageInfo>(); 11215 } 11216 11217 private int getUidTargetSdkVersionLockedLPr(int uid) { 11218 Object obj = mSettings.getUserIdLPr(uid); 11219 if (obj instanceof SharedUserSetting) { 11220 final SharedUserSetting sus = (SharedUserSetting) obj; 11221 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11222 final Iterator<PackageSetting> it = sus.packages.iterator(); 11223 while (it.hasNext()) { 11224 final PackageSetting ps = it.next(); 11225 if (ps.pkg != null) { 11226 int v = ps.pkg.applicationInfo.targetSdkVersion; 11227 if (v < vers) vers = v; 11228 } 11229 } 11230 return vers; 11231 } else if (obj instanceof PackageSetting) { 11232 final PackageSetting ps = (PackageSetting) obj; 11233 if (ps.pkg != null) { 11234 return ps.pkg.applicationInfo.targetSdkVersion; 11235 } 11236 } 11237 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11238 } 11239 11240 @Override 11241 public void addPreferredActivity(IntentFilter filter, int match, 11242 ComponentName[] set, ComponentName activity, int userId) { 11243 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11244 } 11245 11246 private void addPreferredActivityInternal(IntentFilter filter, int match, 11247 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11248 // writer 11249 int callingUid = Binder.getCallingUid(); 11250 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11251 if (filter.countActions() == 0) { 11252 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11253 return; 11254 } 11255 synchronized (mPackages) { 11256 if (mContext.checkCallingOrSelfPermission( 11257 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11258 != PackageManager.PERMISSION_GRANTED) { 11259 if (getUidTargetSdkVersionLockedLPr(callingUid) 11260 < Build.VERSION_CODES.FROYO) { 11261 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11262 + callingUid); 11263 return; 11264 } 11265 mContext.enforceCallingOrSelfPermission( 11266 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11267 } 11268 11269 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11270 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11271 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11272 new PreferredActivity(filter, match, set, activity, always)); 11273 mSettings.writePackageRestrictionsLPr(userId); 11274 } 11275 } 11276 11277 @Override 11278 public void replacePreferredActivity(IntentFilter filter, int match, 11279 ComponentName[] set, ComponentName activity) { 11280 if (filter.countActions() != 1) { 11281 throw new IllegalArgumentException( 11282 "replacePreferredActivity expects filter to have only 1 action."); 11283 } 11284 if (filter.countDataAuthorities() != 0 11285 || filter.countDataPaths() != 0 11286 || filter.countDataSchemes() > 1 11287 || filter.countDataTypes() != 0) { 11288 throw new IllegalArgumentException( 11289 "replacePreferredActivity expects filter to have no data authorities, " + 11290 "paths, or types; and at most one scheme."); 11291 } 11292 synchronized (mPackages) { 11293 if (mContext.checkCallingOrSelfPermission( 11294 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11295 != PackageManager.PERMISSION_GRANTED) { 11296 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11297 < Build.VERSION_CODES.FROYO) { 11298 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11299 + Binder.getCallingUid()); 11300 return; 11301 } 11302 mContext.enforceCallingOrSelfPermission( 11303 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11304 } 11305 11306 final int callingUserId = UserHandle.getCallingUserId(); 11307 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11308 if (pir != null) { 11309 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11310 if (filter.countDataSchemes() == 1) { 11311 Uri.Builder builder = new Uri.Builder(); 11312 builder.scheme(filter.getDataScheme(0)); 11313 intent.setData(builder.build()); 11314 } 11315 List<PreferredActivity> matches = pir.queryIntent( 11316 intent, null, true, callingUserId); 11317 if (DEBUG_PREFERRED) { 11318 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11319 } 11320 for (int i = 0; i < matches.size(); i++) { 11321 PreferredActivity pa = matches.get(i); 11322 if (DEBUG_PREFERRED) { 11323 Slog.i(TAG, "Removing preferred activity " 11324 + pa.mPref.mComponent + ":"); 11325 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11326 } 11327 pir.removeFilter(pa); 11328 } 11329 } 11330 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11331 } 11332 } 11333 11334 @Override 11335 public void clearPackagePreferredActivities(String packageName) { 11336 final int uid = Binder.getCallingUid(); 11337 // writer 11338 synchronized (mPackages) { 11339 PackageParser.Package pkg = mPackages.get(packageName); 11340 if (pkg == null || pkg.applicationInfo.uid != uid) { 11341 if (mContext.checkCallingOrSelfPermission( 11342 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11343 != PackageManager.PERMISSION_GRANTED) { 11344 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11345 < Build.VERSION_CODES.FROYO) { 11346 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11347 + Binder.getCallingUid()); 11348 return; 11349 } 11350 mContext.enforceCallingOrSelfPermission( 11351 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11352 } 11353 } 11354 11355 int user = UserHandle.getCallingUserId(); 11356 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11357 mSettings.writePackageRestrictionsLPr(user); 11358 scheduleWriteSettingsLocked(); 11359 } 11360 } 11361 } 11362 11363 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11364 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11365 ArrayList<PreferredActivity> removed = null; 11366 boolean changed = false; 11367 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11368 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11369 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11370 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11371 continue; 11372 } 11373 Iterator<PreferredActivity> it = pir.filterIterator(); 11374 while (it.hasNext()) { 11375 PreferredActivity pa = it.next(); 11376 // Mark entry for removal only if it matches the package name 11377 // and the entry is of type "always". 11378 if (packageName == null || 11379 (pa.mPref.mComponent.getPackageName().equals(packageName) 11380 && pa.mPref.mAlways)) { 11381 if (removed == null) { 11382 removed = new ArrayList<PreferredActivity>(); 11383 } 11384 removed.add(pa); 11385 } 11386 } 11387 if (removed != null) { 11388 for (int j=0; j<removed.size(); j++) { 11389 PreferredActivity pa = removed.get(j); 11390 pir.removeFilter(pa); 11391 } 11392 changed = true; 11393 } 11394 } 11395 return changed; 11396 } 11397 11398 @Override 11399 public void resetPreferredActivities(int userId) { 11400 mContext.enforceCallingOrSelfPermission( 11401 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11402 // writer 11403 synchronized (mPackages) { 11404 int user = UserHandle.getCallingUserId(); 11405 clearPackagePreferredActivitiesLPw(null, user); 11406 mSettings.readDefaultPreferredAppsLPw(this, user); 11407 mSettings.writePackageRestrictionsLPr(user); 11408 scheduleWriteSettingsLocked(); 11409 } 11410 } 11411 11412 @Override 11413 public int getPreferredActivities(List<IntentFilter> outFilters, 11414 List<ComponentName> outActivities, String packageName) { 11415 11416 int num = 0; 11417 final int userId = UserHandle.getCallingUserId(); 11418 // reader 11419 synchronized (mPackages) { 11420 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11421 if (pir != null) { 11422 final Iterator<PreferredActivity> it = pir.filterIterator(); 11423 while (it.hasNext()) { 11424 final PreferredActivity pa = it.next(); 11425 if (packageName == null 11426 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11427 && pa.mPref.mAlways)) { 11428 if (outFilters != null) { 11429 outFilters.add(new IntentFilter(pa)); 11430 } 11431 if (outActivities != null) { 11432 outActivities.add(pa.mPref.mComponent); 11433 } 11434 } 11435 } 11436 } 11437 } 11438 11439 return num; 11440 } 11441 11442 @Override 11443 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11444 int userId) { 11445 int callingUid = Binder.getCallingUid(); 11446 if (callingUid != Process.SYSTEM_UID) { 11447 throw new SecurityException( 11448 "addPersistentPreferredActivity can only be run by the system"); 11449 } 11450 if (filter.countActions() == 0) { 11451 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11452 return; 11453 } 11454 synchronized (mPackages) { 11455 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11456 " :"); 11457 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11458 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11459 new PersistentPreferredActivity(filter, activity)); 11460 mSettings.writePackageRestrictionsLPr(userId); 11461 } 11462 } 11463 11464 @Override 11465 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11466 int callingUid = Binder.getCallingUid(); 11467 if (callingUid != Process.SYSTEM_UID) { 11468 throw new SecurityException( 11469 "clearPackagePersistentPreferredActivities can only be run by the system"); 11470 } 11471 ArrayList<PersistentPreferredActivity> removed = null; 11472 boolean changed = false; 11473 synchronized (mPackages) { 11474 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11475 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11476 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11477 .valueAt(i); 11478 if (userId != thisUserId) { 11479 continue; 11480 } 11481 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11482 while (it.hasNext()) { 11483 PersistentPreferredActivity ppa = it.next(); 11484 // Mark entry for removal only if it matches the package name. 11485 if (ppa.mComponent.getPackageName().equals(packageName)) { 11486 if (removed == null) { 11487 removed = new ArrayList<PersistentPreferredActivity>(); 11488 } 11489 removed.add(ppa); 11490 } 11491 } 11492 if (removed != null) { 11493 for (int j=0; j<removed.size(); j++) { 11494 PersistentPreferredActivity ppa = removed.get(j); 11495 ppir.removeFilter(ppa); 11496 } 11497 changed = true; 11498 } 11499 } 11500 11501 if (changed) { 11502 mSettings.writePackageRestrictionsLPr(userId); 11503 } 11504 } 11505 } 11506 11507 @Override 11508 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11509 int targetUserId, int flags) { 11510 mContext.enforceCallingOrSelfPermission( 11511 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11512 if (intentFilter.countActions() == 0) { 11513 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11514 return; 11515 } 11516 synchronized (mPackages) { 11517 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11518 targetUserId, flags); 11519 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11520 mSettings.writePackageRestrictionsLPr(sourceUserId); 11521 } 11522 } 11523 11524 public void addCrossProfileIntentsForPackage(String packageName, 11525 int sourceUserId, int targetUserId) { 11526 mContext.enforceCallingOrSelfPermission( 11527 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11528 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11529 mSettings.writePackageRestrictionsLPr(sourceUserId); 11530 } 11531 11532 public void removeCrossProfileIntentsForPackage(String packageName, 11533 int sourceUserId, int targetUserId) { 11534 mContext.enforceCallingOrSelfPermission( 11535 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11536 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11537 mSettings.writePackageRestrictionsLPr(sourceUserId); 11538 } 11539 11540 @Override 11541 public void clearCrossProfileIntentFilters(int sourceUserId) { 11542 mContext.enforceCallingOrSelfPermission( 11543 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11544 synchronized (mPackages) { 11545 CrossProfileIntentResolver resolver = 11546 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11547 HashSet<CrossProfileIntentFilter> set = 11548 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11549 for (CrossProfileIntentFilter filter : set) { 11550 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11551 resolver.removeFilter(filter); 11552 } 11553 } 11554 mSettings.writePackageRestrictionsLPr(sourceUserId); 11555 } 11556 } 11557 11558 @Override 11559 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11560 Intent intent = new Intent(Intent.ACTION_MAIN); 11561 intent.addCategory(Intent.CATEGORY_HOME); 11562 11563 final int callingUserId = UserHandle.getCallingUserId(); 11564 List<ResolveInfo> list = queryIntentActivities(intent, null, 11565 PackageManager.GET_META_DATA, callingUserId); 11566 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11567 true, false, false, callingUserId); 11568 11569 allHomeCandidates.clear(); 11570 if (list != null) { 11571 for (ResolveInfo ri : list) { 11572 allHomeCandidates.add(ri); 11573 } 11574 } 11575 return (preferred == null || preferred.activityInfo == null) 11576 ? null 11577 : new ComponentName(preferred.activityInfo.packageName, 11578 preferred.activityInfo.name); 11579 } 11580 11581 @Override 11582 public void setApplicationEnabledSetting(String appPackageName, 11583 int newState, int flags, int userId, String callingPackage) { 11584 if (!sUserManager.exists(userId)) return; 11585 if (callingPackage == null) { 11586 callingPackage = Integer.toString(Binder.getCallingUid()); 11587 } 11588 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11589 } 11590 11591 @Override 11592 public void setComponentEnabledSetting(ComponentName componentName, 11593 int newState, int flags, int userId) { 11594 if (!sUserManager.exists(userId)) return; 11595 setEnabledSetting(componentName.getPackageName(), 11596 componentName.getClassName(), newState, flags, userId, null); 11597 } 11598 11599 private void setEnabledSetting(final String packageName, String className, int newState, 11600 final int flags, int userId, String callingPackage) { 11601 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11602 || newState == COMPONENT_ENABLED_STATE_ENABLED 11603 || newState == COMPONENT_ENABLED_STATE_DISABLED 11604 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11605 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11606 throw new IllegalArgumentException("Invalid new component state: " 11607 + newState); 11608 } 11609 PackageSetting pkgSetting; 11610 final int uid = Binder.getCallingUid(); 11611 final int permission = mContext.checkCallingOrSelfPermission( 11612 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11613 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11614 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11615 boolean sendNow = false; 11616 boolean isApp = (className == null); 11617 String componentName = isApp ? packageName : className; 11618 int packageUid = -1; 11619 ArrayList<String> components; 11620 11621 // writer 11622 synchronized (mPackages) { 11623 pkgSetting = mSettings.mPackages.get(packageName); 11624 if (pkgSetting == null) { 11625 if (className == null) { 11626 throw new IllegalArgumentException( 11627 "Unknown package: " + packageName); 11628 } 11629 throw new IllegalArgumentException( 11630 "Unknown component: " + packageName 11631 + "/" + className); 11632 } 11633 // Allow root and verify that userId is not being specified by a different user 11634 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11635 throw new SecurityException( 11636 "Permission Denial: attempt to change component state from pid=" 11637 + Binder.getCallingPid() 11638 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11639 } 11640 if (className == null) { 11641 // We're dealing with an application/package level state change 11642 if (pkgSetting.getEnabled(userId) == newState) { 11643 // Nothing to do 11644 return; 11645 } 11646 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11647 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11648 // Don't care about who enables an app. 11649 callingPackage = null; 11650 } 11651 pkgSetting.setEnabled(newState, userId, callingPackage); 11652 // pkgSetting.pkg.mSetEnabled = newState; 11653 } else { 11654 // We're dealing with a component level state change 11655 // First, verify that this is a valid class name. 11656 PackageParser.Package pkg = pkgSetting.pkg; 11657 if (pkg == null || !pkg.hasComponentClassName(className)) { 11658 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11659 throw new IllegalArgumentException("Component class " + className 11660 + " does not exist in " + packageName); 11661 } else { 11662 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11663 + className + " does not exist in " + packageName); 11664 } 11665 } 11666 switch (newState) { 11667 case COMPONENT_ENABLED_STATE_ENABLED: 11668 if (!pkgSetting.enableComponentLPw(className, userId)) { 11669 return; 11670 } 11671 break; 11672 case COMPONENT_ENABLED_STATE_DISABLED: 11673 if (!pkgSetting.disableComponentLPw(className, userId)) { 11674 return; 11675 } 11676 break; 11677 case COMPONENT_ENABLED_STATE_DEFAULT: 11678 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11679 return; 11680 } 11681 break; 11682 default: 11683 Slog.e(TAG, "Invalid new component state: " + newState); 11684 return; 11685 } 11686 } 11687 mSettings.writePackageRestrictionsLPr(userId); 11688 components = mPendingBroadcasts.get(userId, packageName); 11689 final boolean newPackage = components == null; 11690 if (newPackage) { 11691 components = new ArrayList<String>(); 11692 } 11693 if (!components.contains(componentName)) { 11694 components.add(componentName); 11695 } 11696 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11697 sendNow = true; 11698 // Purge entry from pending broadcast list if another one exists already 11699 // since we are sending one right away. 11700 mPendingBroadcasts.remove(userId, packageName); 11701 } else { 11702 if (newPackage) { 11703 mPendingBroadcasts.put(userId, packageName, components); 11704 } 11705 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11706 // Schedule a message 11707 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11708 } 11709 } 11710 } 11711 11712 long callingId = Binder.clearCallingIdentity(); 11713 try { 11714 if (sendNow) { 11715 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11716 sendPackageChangedBroadcast(packageName, 11717 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11718 } 11719 } finally { 11720 Binder.restoreCallingIdentity(callingId); 11721 } 11722 } 11723 11724 private void sendPackageChangedBroadcast(String packageName, 11725 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11726 if (DEBUG_INSTALL) 11727 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11728 + componentNames); 11729 Bundle extras = new Bundle(4); 11730 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11731 String nameList[] = new String[componentNames.size()]; 11732 componentNames.toArray(nameList); 11733 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11734 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11735 extras.putInt(Intent.EXTRA_UID, packageUid); 11736 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11737 new int[] {UserHandle.getUserId(packageUid)}); 11738 } 11739 11740 @Override 11741 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11742 if (!sUserManager.exists(userId)) return; 11743 final int uid = Binder.getCallingUid(); 11744 final int permission = mContext.checkCallingOrSelfPermission( 11745 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11746 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11747 enforceCrossUserPermission(uid, userId, true, "stop package"); 11748 // writer 11749 synchronized (mPackages) { 11750 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11751 uid, userId)) { 11752 scheduleWritePackageRestrictionsLocked(userId); 11753 } 11754 } 11755 } 11756 11757 @Override 11758 public String getInstallerPackageName(String packageName) { 11759 // reader 11760 synchronized (mPackages) { 11761 return mSettings.getInstallerPackageNameLPr(packageName); 11762 } 11763 } 11764 11765 @Override 11766 public int getApplicationEnabledSetting(String packageName, int userId) { 11767 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11768 int uid = Binder.getCallingUid(); 11769 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11770 // reader 11771 synchronized (mPackages) { 11772 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11773 } 11774 } 11775 11776 @Override 11777 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11778 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11779 int uid = Binder.getCallingUid(); 11780 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11781 // reader 11782 synchronized (mPackages) { 11783 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11784 } 11785 } 11786 11787 @Override 11788 public void enterSafeMode() { 11789 enforceSystemOrRoot("Only the system can request entering safe mode"); 11790 11791 if (!mSystemReady) { 11792 mSafeMode = true; 11793 } 11794 } 11795 11796 @Override 11797 public void systemReady() { 11798 mSystemReady = true; 11799 11800 // Read the compatibilty setting when the system is ready. 11801 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11802 mContext.getContentResolver(), 11803 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11804 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11805 if (DEBUG_SETTINGS) { 11806 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11807 } 11808 11809 synchronized (mPackages) { 11810 // Verify that all of the preferred activity components actually 11811 // exist. It is possible for applications to be updated and at 11812 // that point remove a previously declared activity component that 11813 // had been set as a preferred activity. We try to clean this up 11814 // the next time we encounter that preferred activity, but it is 11815 // possible for the user flow to never be able to return to that 11816 // situation so here we do a sanity check to make sure we haven't 11817 // left any junk around. 11818 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11819 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11820 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11821 removed.clear(); 11822 for (PreferredActivity pa : pir.filterSet()) { 11823 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11824 removed.add(pa); 11825 } 11826 } 11827 if (removed.size() > 0) { 11828 for (int r=0; r<removed.size(); r++) { 11829 PreferredActivity pa = removed.get(r); 11830 Slog.w(TAG, "Removing dangling preferred activity: " 11831 + pa.mPref.mComponent); 11832 pir.removeFilter(pa); 11833 } 11834 mSettings.writePackageRestrictionsLPr( 11835 mSettings.mPreferredActivities.keyAt(i)); 11836 } 11837 } 11838 } 11839 sUserManager.systemReady(); 11840 } 11841 11842 @Override 11843 public boolean isSafeMode() { 11844 return mSafeMode; 11845 } 11846 11847 @Override 11848 public boolean hasSystemUidErrors() { 11849 return mHasSystemUidErrors; 11850 } 11851 11852 static String arrayToString(int[] array) { 11853 StringBuffer buf = new StringBuffer(128); 11854 buf.append('['); 11855 if (array != null) { 11856 for (int i=0; i<array.length; i++) { 11857 if (i > 0) buf.append(", "); 11858 buf.append(array[i]); 11859 } 11860 } 11861 buf.append(']'); 11862 return buf.toString(); 11863 } 11864 11865 static class DumpState { 11866 public static final int DUMP_LIBS = 1 << 0; 11867 11868 public static final int DUMP_FEATURES = 1 << 1; 11869 11870 public static final int DUMP_RESOLVERS = 1 << 2; 11871 11872 public static final int DUMP_PERMISSIONS = 1 << 3; 11873 11874 public static final int DUMP_PACKAGES = 1 << 4; 11875 11876 public static final int DUMP_SHARED_USERS = 1 << 5; 11877 11878 public static final int DUMP_MESSAGES = 1 << 6; 11879 11880 public static final int DUMP_PROVIDERS = 1 << 7; 11881 11882 public static final int DUMP_VERIFIERS = 1 << 8; 11883 11884 public static final int DUMP_PREFERRED = 1 << 9; 11885 11886 public static final int DUMP_PREFERRED_XML = 1 << 10; 11887 11888 public static final int DUMP_KEYSETS = 1 << 11; 11889 11890 public static final int DUMP_VERSION = 1 << 12; 11891 11892 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11893 11894 private int mTypes; 11895 11896 private int mOptions; 11897 11898 private boolean mTitlePrinted; 11899 11900 private SharedUserSetting mSharedUser; 11901 11902 public boolean isDumping(int type) { 11903 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11904 return true; 11905 } 11906 11907 return (mTypes & type) != 0; 11908 } 11909 11910 public void setDump(int type) { 11911 mTypes |= type; 11912 } 11913 11914 public boolean isOptionEnabled(int option) { 11915 return (mOptions & option) != 0; 11916 } 11917 11918 public void setOptionEnabled(int option) { 11919 mOptions |= option; 11920 } 11921 11922 public boolean onTitlePrinted() { 11923 final boolean printed = mTitlePrinted; 11924 mTitlePrinted = true; 11925 return printed; 11926 } 11927 11928 public boolean getTitlePrinted() { 11929 return mTitlePrinted; 11930 } 11931 11932 public void setTitlePrinted(boolean enabled) { 11933 mTitlePrinted = enabled; 11934 } 11935 11936 public SharedUserSetting getSharedUser() { 11937 return mSharedUser; 11938 } 11939 11940 public void setSharedUser(SharedUserSetting user) { 11941 mSharedUser = user; 11942 } 11943 } 11944 11945 @Override 11946 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 11947 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 11948 != PackageManager.PERMISSION_GRANTED) { 11949 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 11950 + Binder.getCallingPid() 11951 + ", uid=" + Binder.getCallingUid() 11952 + " without permission " 11953 + android.Manifest.permission.DUMP); 11954 return; 11955 } 11956 11957 DumpState dumpState = new DumpState(); 11958 boolean fullPreferred = false; 11959 boolean checkin = false; 11960 11961 String packageName = null; 11962 11963 int opti = 0; 11964 while (opti < args.length) { 11965 String opt = args[opti]; 11966 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 11967 break; 11968 } 11969 opti++; 11970 if ("-a".equals(opt)) { 11971 // Right now we only know how to print all. 11972 } else if ("-h".equals(opt)) { 11973 pw.println("Package manager dump options:"); 11974 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 11975 pw.println(" --checkin: dump for a checkin"); 11976 pw.println(" -f: print details of intent filters"); 11977 pw.println(" -h: print this help"); 11978 pw.println(" cmd may be one of:"); 11979 pw.println(" l[ibraries]: list known shared libraries"); 11980 pw.println(" f[ibraries]: list device features"); 11981 pw.println(" k[eysets]: print known keysets"); 11982 pw.println(" r[esolvers]: dump intent resolvers"); 11983 pw.println(" perm[issions]: dump permissions"); 11984 pw.println(" pref[erred]: print preferred package settings"); 11985 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 11986 pw.println(" prov[iders]: dump content providers"); 11987 pw.println(" p[ackages]: dump installed packages"); 11988 pw.println(" s[hared-users]: dump shared user IDs"); 11989 pw.println(" m[essages]: print collected runtime messages"); 11990 pw.println(" v[erifiers]: print package verifier info"); 11991 pw.println(" version: print database version info"); 11992 pw.println(" write: write current settings now"); 11993 pw.println(" <package.name>: info about given package"); 11994 return; 11995 } else if ("--checkin".equals(opt)) { 11996 checkin = true; 11997 } else if ("-f".equals(opt)) { 11998 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11999 } else { 12000 pw.println("Unknown argument: " + opt + "; use -h for help"); 12001 } 12002 } 12003 12004 // Is the caller requesting to dump a particular piece of data? 12005 if (opti < args.length) { 12006 String cmd = args[opti]; 12007 opti++; 12008 // Is this a package name? 12009 if ("android".equals(cmd) || cmd.contains(".")) { 12010 packageName = cmd; 12011 // When dumping a single package, we always dump all of its 12012 // filter information since the amount of data will be reasonable. 12013 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12014 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12015 dumpState.setDump(DumpState.DUMP_LIBS); 12016 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12017 dumpState.setDump(DumpState.DUMP_FEATURES); 12018 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12019 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12020 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12021 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12022 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12023 dumpState.setDump(DumpState.DUMP_PREFERRED); 12024 } else if ("preferred-xml".equals(cmd)) { 12025 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12026 if (opti < args.length && "--full".equals(args[opti])) { 12027 fullPreferred = true; 12028 opti++; 12029 } 12030 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12031 dumpState.setDump(DumpState.DUMP_PACKAGES); 12032 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12033 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12034 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12035 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12036 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12037 dumpState.setDump(DumpState.DUMP_MESSAGES); 12038 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12039 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12040 } else if ("version".equals(cmd)) { 12041 dumpState.setDump(DumpState.DUMP_VERSION); 12042 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12043 dumpState.setDump(DumpState.DUMP_KEYSETS); 12044 } else if ("write".equals(cmd)) { 12045 synchronized (mPackages) { 12046 mSettings.writeLPr(); 12047 pw.println("Settings written."); 12048 return; 12049 } 12050 } 12051 } 12052 12053 if (checkin) { 12054 pw.println("vers,1"); 12055 } 12056 12057 // reader 12058 synchronized (mPackages) { 12059 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12060 if (!checkin) { 12061 if (dumpState.onTitlePrinted()) 12062 pw.println(); 12063 pw.println("Database versions:"); 12064 pw.print(" SDK Version:"); 12065 pw.print(" internal="); 12066 pw.print(mSettings.mInternalSdkPlatform); 12067 pw.print(" external="); 12068 pw.println(mSettings.mExternalSdkPlatform); 12069 pw.print(" DB Version:"); 12070 pw.print(" internal="); 12071 pw.print(mSettings.mInternalDatabaseVersion); 12072 pw.print(" external="); 12073 pw.println(mSettings.mExternalDatabaseVersion); 12074 } 12075 } 12076 12077 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12078 if (!checkin) { 12079 if (dumpState.onTitlePrinted()) 12080 pw.println(); 12081 pw.println("Verifiers:"); 12082 pw.print(" Required: "); 12083 pw.print(mRequiredVerifierPackage); 12084 pw.print(" (uid="); 12085 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12086 pw.println(")"); 12087 } else if (mRequiredVerifierPackage != null) { 12088 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12089 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12090 } 12091 } 12092 12093 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12094 boolean printedHeader = false; 12095 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12096 while (it.hasNext()) { 12097 String name = it.next(); 12098 SharedLibraryEntry ent = mSharedLibraries.get(name); 12099 if (!checkin) { 12100 if (!printedHeader) { 12101 if (dumpState.onTitlePrinted()) 12102 pw.println(); 12103 pw.println("Libraries:"); 12104 printedHeader = true; 12105 } 12106 pw.print(" "); 12107 } else { 12108 pw.print("lib,"); 12109 } 12110 pw.print(name); 12111 if (!checkin) { 12112 pw.print(" -> "); 12113 } 12114 if (ent.path != null) { 12115 if (!checkin) { 12116 pw.print("(jar) "); 12117 pw.print(ent.path); 12118 } else { 12119 pw.print(",jar,"); 12120 pw.print(ent.path); 12121 } 12122 } else { 12123 if (!checkin) { 12124 pw.print("(apk) "); 12125 pw.print(ent.apk); 12126 } else { 12127 pw.print(",apk,"); 12128 pw.print(ent.apk); 12129 } 12130 } 12131 pw.println(); 12132 } 12133 } 12134 12135 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12136 if (dumpState.onTitlePrinted()) 12137 pw.println(); 12138 if (!checkin) { 12139 pw.println("Features:"); 12140 } 12141 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12142 while (it.hasNext()) { 12143 String name = it.next(); 12144 if (!checkin) { 12145 pw.print(" "); 12146 } else { 12147 pw.print("feat,"); 12148 } 12149 pw.println(name); 12150 } 12151 } 12152 12153 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12154 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12155 : "Activity Resolver Table:", " ", packageName, 12156 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12157 dumpState.setTitlePrinted(true); 12158 } 12159 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12160 : "Receiver Resolver Table:", " ", packageName, 12161 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12162 dumpState.setTitlePrinted(true); 12163 } 12164 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12165 : "Service Resolver Table:", " ", packageName, 12166 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12167 dumpState.setTitlePrinted(true); 12168 } 12169 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12170 : "Provider Resolver Table:", " ", packageName, 12171 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12172 dumpState.setTitlePrinted(true); 12173 } 12174 } 12175 12176 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12177 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12178 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12179 int user = mSettings.mPreferredActivities.keyAt(i); 12180 if (pir.dump(pw, 12181 dumpState.getTitlePrinted() 12182 ? "\nPreferred Activities User " + user + ":" 12183 : "Preferred Activities User " + user + ":", " ", 12184 packageName, true)) { 12185 dumpState.setTitlePrinted(true); 12186 } 12187 } 12188 } 12189 12190 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12191 pw.flush(); 12192 FileOutputStream fout = new FileOutputStream(fd); 12193 BufferedOutputStream str = new BufferedOutputStream(fout); 12194 XmlSerializer serializer = new FastXmlSerializer(); 12195 try { 12196 serializer.setOutput(str, "utf-8"); 12197 serializer.startDocument(null, true); 12198 serializer.setFeature( 12199 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12200 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12201 serializer.endDocument(); 12202 serializer.flush(); 12203 } catch (IllegalArgumentException e) { 12204 pw.println("Failed writing: " + e); 12205 } catch (IllegalStateException e) { 12206 pw.println("Failed writing: " + e); 12207 } catch (IOException e) { 12208 pw.println("Failed writing: " + e); 12209 } 12210 } 12211 12212 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12213 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12214 } 12215 12216 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12217 boolean printedSomething = false; 12218 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12219 if (packageName != null && !packageName.equals(p.info.packageName)) { 12220 continue; 12221 } 12222 if (!printedSomething) { 12223 if (dumpState.onTitlePrinted()) 12224 pw.println(); 12225 pw.println("Registered ContentProviders:"); 12226 printedSomething = true; 12227 } 12228 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12229 pw.print(" "); pw.println(p.toString()); 12230 } 12231 printedSomething = false; 12232 for (Map.Entry<String, PackageParser.Provider> entry : 12233 mProvidersByAuthority.entrySet()) { 12234 PackageParser.Provider p = entry.getValue(); 12235 if (packageName != null && !packageName.equals(p.info.packageName)) { 12236 continue; 12237 } 12238 if (!printedSomething) { 12239 if (dumpState.onTitlePrinted()) 12240 pw.println(); 12241 pw.println("ContentProvider Authorities:"); 12242 printedSomething = true; 12243 } 12244 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12245 pw.print(" "); pw.println(p.toString()); 12246 if (p.info != null && p.info.applicationInfo != null) { 12247 final String appInfo = p.info.applicationInfo.toString(); 12248 pw.print(" applicationInfo="); pw.println(appInfo); 12249 } 12250 } 12251 } 12252 12253 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12254 mSettings.mKeySetManager.dump(pw, packageName, dumpState); 12255 } 12256 12257 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12258 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12259 } 12260 12261 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12262 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12263 } 12264 12265 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12266 if (dumpState.onTitlePrinted()) 12267 pw.println(); 12268 mSettings.dumpReadMessagesLPr(pw, dumpState); 12269 12270 pw.println(); 12271 pw.println("Package warning messages:"); 12272 final File fname = getSettingsProblemFile(); 12273 FileInputStream in = null; 12274 try { 12275 in = new FileInputStream(fname); 12276 final int avail = in.available(); 12277 final byte[] data = new byte[avail]; 12278 in.read(data); 12279 pw.print(new String(data)); 12280 } catch (FileNotFoundException e) { 12281 } catch (IOException e) { 12282 } finally { 12283 if (in != null) { 12284 try { 12285 in.close(); 12286 } catch (IOException e) { 12287 } 12288 } 12289 } 12290 } 12291 } 12292 } 12293 12294 // ------- apps on sdcard specific code ------- 12295 static final boolean DEBUG_SD_INSTALL = false; 12296 12297 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12298 12299 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12300 12301 private boolean mMediaMounted = false; 12302 12303 private String getEncryptKey() { 12304 try { 12305 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12306 SD_ENCRYPTION_KEYSTORE_NAME); 12307 if (sdEncKey == null) { 12308 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12309 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12310 if (sdEncKey == null) { 12311 Slog.e(TAG, "Failed to create encryption keys"); 12312 return null; 12313 } 12314 } 12315 return sdEncKey; 12316 } catch (NoSuchAlgorithmException nsae) { 12317 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12318 return null; 12319 } catch (IOException ioe) { 12320 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12321 return null; 12322 } 12323 12324 } 12325 12326 /* package */static String getTempContainerId() { 12327 int tmpIdx = 1; 12328 String list[] = PackageHelper.getSecureContainerList(); 12329 if (list != null) { 12330 for (final String name : list) { 12331 // Ignore null and non-temporary container entries 12332 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12333 continue; 12334 } 12335 12336 String subStr = name.substring(mTempContainerPrefix.length()); 12337 try { 12338 int cid = Integer.parseInt(subStr); 12339 if (cid >= tmpIdx) { 12340 tmpIdx = cid + 1; 12341 } 12342 } catch (NumberFormatException e) { 12343 } 12344 } 12345 } 12346 return mTempContainerPrefix + tmpIdx; 12347 } 12348 12349 /* 12350 * Update media status on PackageManager. 12351 */ 12352 @Override 12353 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12354 int callingUid = Binder.getCallingUid(); 12355 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12356 throw new SecurityException("Media status can only be updated by the system"); 12357 } 12358 // reader; this apparently protects mMediaMounted, but should probably 12359 // be a different lock in that case. 12360 synchronized (mPackages) { 12361 Log.i(TAG, "Updating external media status from " 12362 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12363 + (mediaStatus ? "mounted" : "unmounted")); 12364 if (DEBUG_SD_INSTALL) 12365 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12366 + ", mMediaMounted=" + mMediaMounted); 12367 if (mediaStatus == mMediaMounted) { 12368 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12369 : 0, -1); 12370 mHandler.sendMessage(msg); 12371 return; 12372 } 12373 mMediaMounted = mediaStatus; 12374 } 12375 // Queue up an async operation since the package installation may take a 12376 // little while. 12377 mHandler.post(new Runnable() { 12378 public void run() { 12379 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12380 } 12381 }); 12382 } 12383 12384 /** 12385 * Called by MountService when the initial ASECs to scan are available. 12386 * Should block until all the ASEC containers are finished being scanned. 12387 */ 12388 public void scanAvailableAsecs() { 12389 updateExternalMediaStatusInner(true, false, false); 12390 if (mShouldRestoreconData) { 12391 SELinuxMMAC.setRestoreconDone(); 12392 mShouldRestoreconData = false; 12393 } 12394 } 12395 12396 /* 12397 * Collect information of applications on external media, map them against 12398 * existing containers and update information based on current mount status. 12399 * Please note that we always have to report status if reportStatus has been 12400 * set to true especially when unloading packages. 12401 */ 12402 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12403 boolean externalStorage) { 12404 // Collection of uids 12405 int uidArr[] = null; 12406 // Collection of stale containers 12407 HashSet<String> removeCids = new HashSet<String>(); 12408 // Collection of packages on external media with valid containers. 12409 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12410 // Get list of secure containers. 12411 final String list[] = PackageHelper.getSecureContainerList(); 12412 if (list == null || list.length == 0) { 12413 Log.i(TAG, "No secure containers on sdcard"); 12414 } else { 12415 // Process list of secure containers and categorize them 12416 // as active or stale based on their package internal state. 12417 int uidList[] = new int[list.length]; 12418 int num = 0; 12419 // reader 12420 synchronized (mPackages) { 12421 for (String cid : list) { 12422 if (DEBUG_SD_INSTALL) 12423 Log.i(TAG, "Processing container " + cid); 12424 String pkgName = getAsecPackageName(cid); 12425 if (pkgName == null) { 12426 if (DEBUG_SD_INSTALL) 12427 Log.i(TAG, "Container : " + cid + " stale"); 12428 removeCids.add(cid); 12429 continue; 12430 } 12431 if (DEBUG_SD_INSTALL) 12432 Log.i(TAG, "Looking for pkg : " + pkgName); 12433 12434 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12435 if (ps == null) { 12436 Log.i(TAG, "Deleting container with no matching settings " + cid); 12437 removeCids.add(cid); 12438 continue; 12439 } 12440 12441 /* 12442 * Skip packages that are not external if we're unmounting 12443 * external storage. 12444 */ 12445 if (externalStorage && !isMounted && !isExternal(ps)) { 12446 continue; 12447 } 12448 12449 final AsecInstallArgs args = new AsecInstallArgs(cid, 12450 getAppInstructionSetFromSettings(ps), 12451 isForwardLocked(ps)); 12452 // The package status is changed only if the code path 12453 // matches between settings and the container id. 12454 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12455 if (DEBUG_SD_INSTALL) { 12456 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12457 + " at code path: " + ps.codePathString); 12458 } 12459 12460 // We do have a valid package installed on sdcard 12461 processCids.put(args, ps.codePathString); 12462 final int uid = ps.appId; 12463 if (uid != -1) { 12464 uidList[num++] = uid; 12465 } 12466 } else { 12467 Log.i(TAG, "Deleting stale container for " + cid); 12468 removeCids.add(cid); 12469 } 12470 } 12471 } 12472 12473 if (num > 0) { 12474 // Sort uid list 12475 Arrays.sort(uidList, 0, num); 12476 // Throw away duplicates 12477 uidArr = new int[num]; 12478 uidArr[0] = uidList[0]; 12479 int di = 0; 12480 for (int i = 1; i < num; i++) { 12481 if (uidList[i - 1] != uidList[i]) { 12482 uidArr[di++] = uidList[i]; 12483 } 12484 } 12485 } 12486 } 12487 // Process packages with valid entries. 12488 if (isMounted) { 12489 if (DEBUG_SD_INSTALL) 12490 Log.i(TAG, "Loading packages"); 12491 loadMediaPackages(processCids, uidArr, removeCids); 12492 startCleaningPackages(); 12493 } else { 12494 if (DEBUG_SD_INSTALL) 12495 Log.i(TAG, "Unloading packages"); 12496 unloadMediaPackages(processCids, uidArr, reportStatus); 12497 } 12498 } 12499 12500 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12501 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12502 int size = pkgList.size(); 12503 if (size > 0) { 12504 // Send broadcasts here 12505 Bundle extras = new Bundle(); 12506 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12507 .toArray(new String[size])); 12508 if (uidArr != null) { 12509 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12510 } 12511 if (replacing) { 12512 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12513 } 12514 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12515 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12516 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12517 } 12518 } 12519 12520 /* 12521 * Look at potentially valid container ids from processCids If package 12522 * information doesn't match the one on record or package scanning fails, 12523 * the cid is added to list of removeCids. We currently don't delete stale 12524 * containers. 12525 */ 12526 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12527 HashSet<String> removeCids) { 12528 ArrayList<String> pkgList = new ArrayList<String>(); 12529 Set<AsecInstallArgs> keys = processCids.keySet(); 12530 boolean doGc = false; 12531 for (AsecInstallArgs args : keys) { 12532 String codePath = processCids.get(args); 12533 if (DEBUG_SD_INSTALL) 12534 Log.i(TAG, "Loading container : " + args.cid); 12535 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12536 try { 12537 // Make sure there are no container errors first. 12538 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12539 Slog.e(TAG, "Failed to mount cid : " + args.cid 12540 + " when installing from sdcard"); 12541 continue; 12542 } 12543 // Check code path here. 12544 if (codePath == null || !codePath.equals(args.getCodePath())) { 12545 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12546 + " does not match one in settings " + codePath); 12547 continue; 12548 } 12549 // Parse package 12550 int parseFlags = mDefParseFlags; 12551 if (args.isExternal()) { 12552 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12553 } 12554 if (args.isFwdLocked()) { 12555 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12556 } 12557 12558 doGc = true; 12559 synchronized (mInstallLock) { 12560 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 12561 0, 0, null, null); 12562 // Scan the package 12563 if (pkg != null) { 12564 /* 12565 * TODO why is the lock being held? doPostInstall is 12566 * called in other places without the lock. This needs 12567 * to be straightened out. 12568 */ 12569 // writer 12570 synchronized (mPackages) { 12571 retCode = PackageManager.INSTALL_SUCCEEDED; 12572 pkgList.add(pkg.packageName); 12573 // Post process args 12574 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12575 pkg.applicationInfo.uid); 12576 } 12577 } else { 12578 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12579 } 12580 } 12581 12582 } finally { 12583 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12584 // Don't destroy container here. Wait till gc clears things 12585 // up. 12586 removeCids.add(args.cid); 12587 } 12588 } 12589 } 12590 // writer 12591 synchronized (mPackages) { 12592 // If the platform SDK has changed since the last time we booted, 12593 // we need to re-grant app permission to catch any new ones that 12594 // appear. This is really a hack, and means that apps can in some 12595 // cases get permissions that the user didn't initially explicitly 12596 // allow... it would be nice to have some better way to handle 12597 // this situation. 12598 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12599 if (regrantPermissions) 12600 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12601 + mSdkVersion + "; regranting permissions for external storage"); 12602 mSettings.mExternalSdkPlatform = mSdkVersion; 12603 12604 // Make sure group IDs have been assigned, and any permission 12605 // changes in other apps are accounted for 12606 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12607 | (regrantPermissions 12608 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12609 : 0)); 12610 12611 mSettings.updateExternalDatabaseVersion(); 12612 12613 // can downgrade to reader 12614 // Persist settings 12615 mSettings.writeLPr(); 12616 } 12617 // Send a broadcast to let everyone know we are done processing 12618 if (pkgList.size() > 0) { 12619 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12620 } 12621 // Force gc to avoid any stale parser references that we might have. 12622 if (doGc) { 12623 Runtime.getRuntime().gc(); 12624 } 12625 // List stale containers and destroy stale temporary containers. 12626 if (removeCids != null) { 12627 for (String cid : removeCids) { 12628 if (cid.startsWith(mTempContainerPrefix)) { 12629 Log.i(TAG, "Destroying stale temporary container " + cid); 12630 PackageHelper.destroySdDir(cid); 12631 } else { 12632 Log.w(TAG, "Container " + cid + " is stale"); 12633 } 12634 } 12635 } 12636 } 12637 12638 /* 12639 * Utility method to unload a list of specified containers 12640 */ 12641 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12642 // Just unmount all valid containers. 12643 for (AsecInstallArgs arg : cidArgs) { 12644 synchronized (mInstallLock) { 12645 arg.doPostDeleteLI(false); 12646 } 12647 } 12648 } 12649 12650 /* 12651 * Unload packages mounted on external media. This involves deleting package 12652 * data from internal structures, sending broadcasts about diabled packages, 12653 * gc'ing to free up references, unmounting all secure containers 12654 * corresponding to packages on external media, and posting a 12655 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12656 * that we always have to post this message if status has been requested no 12657 * matter what. 12658 */ 12659 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12660 final boolean reportStatus) { 12661 if (DEBUG_SD_INSTALL) 12662 Log.i(TAG, "unloading media packages"); 12663 ArrayList<String> pkgList = new ArrayList<String>(); 12664 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12665 final Set<AsecInstallArgs> keys = processCids.keySet(); 12666 for (AsecInstallArgs args : keys) { 12667 String pkgName = args.getPackageName(); 12668 if (DEBUG_SD_INSTALL) 12669 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12670 // Delete package internally 12671 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12672 synchronized (mInstallLock) { 12673 boolean res = deletePackageLI(pkgName, null, false, null, null, 12674 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12675 if (res) { 12676 pkgList.add(pkgName); 12677 } else { 12678 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12679 failedList.add(args); 12680 } 12681 } 12682 } 12683 12684 // reader 12685 synchronized (mPackages) { 12686 // We didn't update the settings after removing each package; 12687 // write them now for all packages. 12688 mSettings.writeLPr(); 12689 } 12690 12691 // We have to absolutely send UPDATED_MEDIA_STATUS only 12692 // after confirming that all the receivers processed the ordered 12693 // broadcast when packages get disabled, force a gc to clean things up. 12694 // and unload all the containers. 12695 if (pkgList.size() > 0) { 12696 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12697 new IIntentReceiver.Stub() { 12698 public void performReceive(Intent intent, int resultCode, String data, 12699 Bundle extras, boolean ordered, boolean sticky, 12700 int sendingUser) throws RemoteException { 12701 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12702 reportStatus ? 1 : 0, 1, keys); 12703 mHandler.sendMessage(msg); 12704 } 12705 }); 12706 } else { 12707 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12708 keys); 12709 mHandler.sendMessage(msg); 12710 } 12711 } 12712 12713 /** Binder call */ 12714 @Override 12715 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12716 final int flags) { 12717 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12718 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12719 int returnCode = PackageManager.MOVE_SUCCEEDED; 12720 int currFlags = 0; 12721 int newFlags = 0; 12722 // reader 12723 synchronized (mPackages) { 12724 PackageParser.Package pkg = mPackages.get(packageName); 12725 if (pkg == null) { 12726 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12727 } else { 12728 // Disable moving fwd locked apps and system packages 12729 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12730 Slog.w(TAG, "Cannot move system application"); 12731 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12732 } else if (pkg.mOperationPending) { 12733 Slog.w(TAG, "Attempt to move package which has pending operations"); 12734 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12735 } else { 12736 // Find install location first 12737 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12738 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12739 Slog.w(TAG, "Ambigous flags specified for move location."); 12740 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12741 } else { 12742 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12743 : PackageManager.INSTALL_INTERNAL; 12744 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12745 : PackageManager.INSTALL_INTERNAL; 12746 12747 if (newFlags == currFlags) { 12748 Slog.w(TAG, "No move required. Trying to move to same location"); 12749 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12750 } else { 12751 if (isForwardLocked(pkg)) { 12752 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12753 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12754 } 12755 } 12756 } 12757 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12758 pkg.mOperationPending = true; 12759 } 12760 } 12761 } 12762 12763 /* 12764 * TODO this next block probably shouldn't be inside the lock. We 12765 * can't guarantee these won't change after this is fired off 12766 * anyway. 12767 */ 12768 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12769 processPendingMove(new MoveParams(null, observer, 0, packageName, null, 12770 null, -1, user), 12771 returnCode); 12772 } else { 12773 Message msg = mHandler.obtainMessage(INIT_COPY); 12774 final String instructionSet = getAppInstructionSet(pkg.applicationInfo); 12775 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir, 12776 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir, 12777 instructionSet); 12778 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12779 pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user); 12780 msg.obj = mp; 12781 mHandler.sendMessage(msg); 12782 } 12783 } 12784 } 12785 12786 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12787 // Queue up an async operation since the package deletion may take a 12788 // little while. 12789 mHandler.post(new Runnable() { 12790 public void run() { 12791 // TODO fix this; this does nothing. 12792 mHandler.removeCallbacks(this); 12793 int returnCode = currentStatus; 12794 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12795 int uidArr[] = null; 12796 ArrayList<String> pkgList = null; 12797 synchronized (mPackages) { 12798 PackageParser.Package pkg = mPackages.get(mp.packageName); 12799 if (pkg == null) { 12800 Slog.w(TAG, " Package " + mp.packageName 12801 + " doesn't exist. Aborting move"); 12802 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12803 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 12804 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12805 + mp.srcArgs.getCodePath() + " to " 12806 + pkg.applicationInfo.sourceDir 12807 + " Aborting move and returning error"); 12808 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12809 } else { 12810 uidArr = new int[] { 12811 pkg.applicationInfo.uid 12812 }; 12813 pkgList = new ArrayList<String>(); 12814 pkgList.add(mp.packageName); 12815 } 12816 } 12817 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12818 // Send resources unavailable broadcast 12819 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12820 // Update package code and resource paths 12821 synchronized (mInstallLock) { 12822 synchronized (mPackages) { 12823 PackageParser.Package pkg = mPackages.get(mp.packageName); 12824 // Recheck for package again. 12825 if (pkg == null) { 12826 Slog.w(TAG, " Package " + mp.packageName 12827 + " doesn't exist. Aborting move"); 12828 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12829 } else if (!mp.srcArgs.getCodePath().equals( 12830 pkg.applicationInfo.sourceDir)) { 12831 Slog.w(TAG, "Package " + mp.packageName 12832 + " code path changed from " + mp.srcArgs.getCodePath() 12833 + " to " + pkg.applicationInfo.sourceDir 12834 + " Aborting move and returning error"); 12835 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12836 } else { 12837 final String oldCodePath = pkg.codePath; 12838 final String newCodePath = mp.targetArgs.getCodePath(); 12839 final String newResPath = mp.targetArgs.getResourcePath(); 12840 final String newNativePath = mp.targetArgs 12841 .getNativeLibraryPath(); 12842 12843 final File newNativeDir = new File(newNativePath); 12844 12845 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12846 ApkHandle handle = null; 12847 try { 12848 handle = ApkHandle.create(newCodePath); 12849 final int abi = NativeLibraryHelper.findSupportedAbi( 12850 handle, Build.SUPPORTED_ABIS); 12851 if (abi >= 0) { 12852 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12853 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12854 } 12855 } catch (IOException ioe) { 12856 Slog.w(TAG, "Unable to extract native libs for package :" 12857 + mp.packageName, ioe); 12858 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12859 } finally { 12860 IoUtils.closeQuietly(handle); 12861 } 12862 } 12863 final int[] users = sUserManager.getUserIds(); 12864 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12865 for (int user : users) { 12866 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 12867 newNativePath, user) < 0) { 12868 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12869 } 12870 } 12871 } 12872 12873 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12874 pkg.codePath = newCodePath; 12875 // Move dex files around 12876 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 12877 // Moving of dex files failed. Set 12878 // error code and abort move. 12879 pkg.codePath = oldCodePath; 12880 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12881 } 12882 } 12883 12884 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12885 pkg.applicationInfo.sourceDir = newCodePath; 12886 pkg.applicationInfo.publicSourceDir = newResPath; 12887 pkg.applicationInfo.nativeLibraryDir = newNativePath; 12888 PackageSetting ps = (PackageSetting) pkg.mExtras; 12889 ps.codePath = new File(pkg.applicationInfo.sourceDir); 12890 ps.codePathString = ps.codePath.getPath(); 12891 ps.resourcePath = new File( 12892 pkg.applicationInfo.publicSourceDir); 12893 ps.resourcePathString = ps.resourcePath.getPath(); 12894 ps.nativeLibraryPathString = newNativePath; 12895 // Set the application info flag 12896 // correctly. 12897 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 12898 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12899 } else { 12900 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12901 } 12902 ps.setFlags(pkg.applicationInfo.flags); 12903 mAppDirs.remove(oldCodePath); 12904 mAppDirs.put(newCodePath, pkg); 12905 // Persist settings 12906 mSettings.writeLPr(); 12907 } 12908 } 12909 } 12910 } 12911 // Send resources available broadcast 12912 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12913 } 12914 } 12915 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12916 // Clean up failed installation 12917 if (mp.targetArgs != null) { 12918 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 12919 -1); 12920 } 12921 } else { 12922 // Force a gc to clear things up. 12923 Runtime.getRuntime().gc(); 12924 // Delete older code 12925 synchronized (mInstallLock) { 12926 mp.srcArgs.doPostDeleteLI(true); 12927 } 12928 } 12929 12930 // Allow more operations on this file if we didn't fail because 12931 // an operation was already pending for this package. 12932 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 12933 synchronized (mPackages) { 12934 PackageParser.Package pkg = mPackages.get(mp.packageName); 12935 if (pkg != null) { 12936 pkg.mOperationPending = false; 12937 } 12938 } 12939 } 12940 12941 IPackageMoveObserver observer = mp.observer; 12942 if (observer != null) { 12943 try { 12944 observer.packageMoved(mp.packageName, returnCode); 12945 } catch (RemoteException e) { 12946 Log.i(TAG, "Observer no longer exists."); 12947 } 12948 } 12949 } 12950 }); 12951 } 12952 12953 @Override 12954 public boolean setInstallLocation(int loc) { 12955 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12956 null); 12957 if (getInstallLocation() == loc) { 12958 return true; 12959 } 12960 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12961 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12962 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12963 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12964 return true; 12965 } 12966 return false; 12967 } 12968 12969 @Override 12970 public int getInstallLocation() { 12971 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12972 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12973 PackageHelper.APP_INSTALL_AUTO); 12974 } 12975 12976 /** Called by UserManagerService */ 12977 void cleanUpUserLILPw(int userHandle) { 12978 mDirtyUsers.remove(userHandle); 12979 mSettings.removeUserLPr(userHandle); 12980 mPendingBroadcasts.remove(userHandle); 12981 if (mInstaller != null) { 12982 // Technically, we shouldn't be doing this with the package lock 12983 // held. However, this is very rare, and there is already so much 12984 // other disk I/O going on, that we'll let it slide for now. 12985 mInstaller.removeUserDataDirs(userHandle); 12986 } 12987 } 12988 12989 /** Called by UserManagerService */ 12990 void createNewUserLILPw(int userHandle, File path) { 12991 if (mInstaller != null) { 12992 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 12993 } 12994 } 12995 12996 @Override 12997 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 12998 mContext.enforceCallingOrSelfPermission( 12999 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13000 "Only package verification agents can read the verifier device identity"); 13001 13002 synchronized (mPackages) { 13003 return mSettings.getVerifierDeviceIdentityLPw(); 13004 } 13005 } 13006 13007 @Override 13008 public void setPermissionEnforced(String permission, boolean enforced) { 13009 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13010 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13011 synchronized (mPackages) { 13012 if (mSettings.mReadExternalStorageEnforced == null 13013 || mSettings.mReadExternalStorageEnforced != enforced) { 13014 mSettings.mReadExternalStorageEnforced = enforced; 13015 mSettings.writeLPr(); 13016 } 13017 } 13018 // kill any non-foreground processes so we restart them and 13019 // grant/revoke the GID. 13020 final IActivityManager am = ActivityManagerNative.getDefault(); 13021 if (am != null) { 13022 final long token = Binder.clearCallingIdentity(); 13023 try { 13024 am.killProcessesBelowForeground("setPermissionEnforcement"); 13025 } catch (RemoteException e) { 13026 } finally { 13027 Binder.restoreCallingIdentity(token); 13028 } 13029 } 13030 } else { 13031 throw new IllegalArgumentException("No selective enforcement for " + permission); 13032 } 13033 } 13034 13035 @Override 13036 @Deprecated 13037 public boolean isPermissionEnforced(String permission) { 13038 return true; 13039 } 13040 13041 @Override 13042 public boolean isStorageLow() { 13043 final long token = Binder.clearCallingIdentity(); 13044 try { 13045 final DeviceStorageMonitorInternal 13046 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13047 if (dsm != null) { 13048 return dsm.isMemoryLow(); 13049 } else { 13050 return false; 13051 } 13052 } finally { 13053 Binder.restoreCallingIdentity(token); 13054 } 13055 } 13056 13057 @Override 13058 public IPackageInstaller getPackageInstaller() { 13059 return mInstallerService; 13060 } 13061} 13062