PackageManagerService.java revision f6b635e4f00cd40d4c46730f7d23df6cc8bf4aa4
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.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.system.OsConstants.S_IRWXU; 27import static android.system.OsConstants.S_IRGRP; 28import static android.system.OsConstants.S_IXGRP; 29import static android.system.OsConstants.S_IROTH; 30import static android.system.OsConstants.S_IXOTH; 31import static com.android.internal.util.ArrayUtils.appendInt; 32import static com.android.internal.util.ArrayUtils.removeInt; 33 34import android.content.pm.PackageParser.*; 35import com.android.internal.app.IMediaContainerService; 36import com.android.internal.app.ResolverActivity; 37import com.android.internal.content.NativeLibraryHelper; 38import com.android.internal.content.PackageHelper; 39import com.android.internal.util.FastPrintWriter; 40import com.android.internal.util.FastXmlSerializer; 41import com.android.internal.util.XmlUtils; 42import com.android.server.EventLogTags; 43import com.android.server.IntentResolver; 44import com.android.server.ServiceThread; 45 46import com.android.server.LocalServices; 47import com.android.server.Watchdog; 48import org.xmlpull.v1.XmlPullParser; 49import org.xmlpull.v1.XmlPullParserException; 50import org.xmlpull.v1.XmlSerializer; 51 52import android.app.ActivityManager; 53import android.app.ActivityManagerNative; 54import android.app.IActivityManager; 55import android.app.admin.IDevicePolicyManager; 56import android.app.backup.IBackupManager; 57import android.content.BroadcastReceiver; 58import android.content.ComponentName; 59import android.content.Context; 60import android.content.IIntentReceiver; 61import android.content.Intent; 62import android.content.IntentFilter; 63import android.content.IntentSender; 64import android.content.IntentSender.SendIntentException; 65import android.content.ServiceConnection; 66import android.content.pm.ActivityInfo; 67import android.content.pm.ApplicationInfo; 68import android.content.pm.ContainerEncryptionParams; 69import android.content.pm.FeatureInfo; 70import android.content.pm.IPackageDataObserver; 71import android.content.pm.IPackageDeleteObserver; 72import android.content.pm.IPackageInstallObserver; 73import android.content.pm.IPackageInstallObserver2; 74import android.content.pm.IPackageManager; 75import android.content.pm.IPackageMoveObserver; 76import android.content.pm.IPackageStatsObserver; 77import android.content.pm.InstrumentationInfo; 78import android.content.pm.ManifestDigest; 79import android.content.pm.PackageCleanItem; 80import android.content.pm.PackageInfo; 81import android.content.pm.PackageInfoLite; 82import android.content.pm.PackageManager; 83import android.content.pm.PackageParser; 84import android.content.pm.PackageStats; 85import android.content.pm.PackageUserState; 86import android.content.pm.ParceledListSlice; 87import android.content.pm.PermissionGroupInfo; 88import android.content.pm.PermissionInfo; 89import android.content.pm.ProviderInfo; 90import android.content.pm.ResolveInfo; 91import android.content.pm.ServiceInfo; 92import android.content.pm.Signature; 93import android.content.pm.VerificationParams; 94import android.content.pm.VerifierDeviceIdentity; 95import android.content.pm.VerifierInfo; 96import android.content.res.Resources; 97import android.hardware.display.DisplayManager; 98import android.net.Uri; 99import android.os.Binder; 100import android.os.Build; 101import android.os.Bundle; 102import android.os.Environment; 103import android.os.Environment.UserEnvironment; 104import android.os.FileObserver; 105import android.os.FileUtils; 106import android.os.Handler; 107import android.os.IBinder; 108import android.os.Looper; 109import android.os.Message; 110import android.os.Parcel; 111import android.os.ParcelFileDescriptor; 112import android.os.Process; 113import android.os.RemoteException; 114import android.os.SELinux; 115import android.os.ServiceManager; 116import android.os.SystemClock; 117import android.os.SystemProperties; 118import android.os.UserHandle; 119import android.os.UserManager; 120import android.security.KeyStore; 121import android.security.SystemKeyStore; 122import android.system.ErrnoException; 123import android.system.Os; 124import android.system.StructStat; 125import android.text.TextUtils; 126import android.util.DisplayMetrics; 127import android.util.EventLog; 128import android.util.Log; 129import android.util.LogPrinter; 130import android.util.PrintStreamPrinter; 131import android.util.Slog; 132import android.util.SparseArray; 133import android.util.Xml; 134import android.view.Display; 135 136import java.io.BufferedOutputStream; 137import java.io.File; 138import java.io.FileDescriptor; 139import java.io.FileInputStream; 140import java.io.FileNotFoundException; 141import java.io.FileOutputStream; 142import java.io.FileReader; 143import java.io.FilenameFilter; 144import java.io.IOException; 145import java.io.PrintWriter; 146import java.security.NoSuchAlgorithmException; 147import java.security.PublicKey; 148import java.security.cert.Certificate; 149import java.security.cert.CertificateEncodingException; 150import java.security.cert.CertificateException; 151import java.text.SimpleDateFormat; 152import java.util.ArrayList; 153import java.util.Arrays; 154import java.util.Collection; 155import java.util.Collections; 156import java.util.Comparator; 157import java.util.Date; 158import java.util.HashMap; 159import java.util.HashSet; 160import java.util.Iterator; 161import java.util.List; 162import java.util.Map; 163import java.util.Set; 164 165import dalvik.system.VMRuntime; 166import libcore.io.IoUtils; 167 168import com.android.internal.R; 169import com.android.server.pm.Settings.DatabaseVersion; 170import com.android.server.storage.DeviceStorageMonitorInternal; 171 172/** 173 * Keep track of all those .apks everywhere. 174 * 175 * This is very central to the platform's security; please run the unit 176 * tests whenever making modifications here: 177 * 178mmm frameworks/base/tests/AndroidTests 179adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 180adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 181 * 182 * {@hide} 183 */ 184public class PackageManagerService extends IPackageManager.Stub { 185 static final String TAG = "PackageManager"; 186 static final boolean DEBUG_SETTINGS = false; 187 static final boolean DEBUG_PREFERRED = false; 188 static final boolean DEBUG_UPGRADE = false; 189 private static final boolean DEBUG_INSTALL = false; 190 private static final boolean DEBUG_REMOVE = false; 191 private static final boolean DEBUG_BROADCASTS = false; 192 private static final boolean DEBUG_SHOW_INFO = false; 193 private static final boolean DEBUG_PACKAGE_INFO = false; 194 private static final boolean DEBUG_INTENT_MATCHING = false; 195 private static final boolean DEBUG_PACKAGE_SCANNING = false; 196 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 197 private static final boolean DEBUG_VERIFY = false; 198 199 private static final int RADIO_UID = Process.PHONE_UID; 200 private static final int LOG_UID = Process.LOG_UID; 201 private static final int NFC_UID = Process.NFC_UID; 202 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 203 private static final int SHELL_UID = Process.SHELL_UID; 204 205 // Cap the size of permission trees that 3rd party apps can define 206 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 207 208 private static final int REMOVE_EVENTS = 209 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 210 private static final int ADD_EVENTS = 211 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 212 213 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 214 // Suffix used during package installation when copying/moving 215 // package apks to install directory. 216 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 217 218 static final int SCAN_MONITOR = 1<<0; 219 static final int SCAN_NO_DEX = 1<<1; 220 static final int SCAN_FORCE_DEX = 1<<2; 221 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 222 static final int SCAN_NEW_INSTALL = 1<<4; 223 static final int SCAN_NO_PATHS = 1<<5; 224 static final int SCAN_UPDATE_TIME = 1<<6; 225 static final int SCAN_DEFER_DEX = 1<<7; 226 static final int SCAN_BOOTING = 1<<8; 227 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 228 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 229 230 static final int REMOVE_CHATTY = 1<<16; 231 232 /** 233 * Timeout (in milliseconds) after which the watchdog should declare that 234 * our handler thread is wedged. The usual default for such things is one 235 * minute but we sometimes do very lengthy I/O operations on this thread, 236 * such as installing multi-gigabyte applications, so ours needs to be longer. 237 */ 238 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 239 240 /** 241 * Whether verification is enabled by default. 242 */ 243 private static final boolean DEFAULT_VERIFY_ENABLE = true; 244 245 /** 246 * The default maximum time to wait for the verification agent to return in 247 * milliseconds. 248 */ 249 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 250 251 /** 252 * The default response for package verification timeout. 253 * 254 * This can be either PackageManager.VERIFICATION_ALLOW or 255 * PackageManager.VERIFICATION_REJECT. 256 */ 257 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 258 259 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 260 261 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 262 DEFAULT_CONTAINER_PACKAGE, 263 "com.android.defcontainer.DefaultContainerService"); 264 265 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 266 267 private static final String LIB_DIR_NAME = "lib"; 268 private static final String LIB64_DIR_NAME = "lib64"; 269 270 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 271 272 static final String mTempContainerPrefix = "smdl2tmp"; 273 274 private static String sPreferredInstructionSet; 275 276 final ServiceThread mHandlerThread; 277 278 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 279 private static final String IDMAP_SUFFIX = "@idmap"; 280 281 final PackageHandler mHandler; 282 283 final int mSdkVersion = Build.VERSION.SDK_INT; 284 285 final Context mContext; 286 final boolean mFactoryTest; 287 final boolean mOnlyCore; 288 final boolean mNoDexOpt; 289 final DisplayMetrics mMetrics; 290 final int mDefParseFlags; 291 final String[] mSeparateProcesses; 292 293 // This is where all application persistent data goes. 294 final File mAppDataDir; 295 296 // This is where all application persistent data goes for secondary users. 297 final File mUserAppDataDir; 298 299 /** The location for ASEC container files on internal storage. */ 300 final String mAsecInternalPath; 301 302 // This is the object monitoring the framework dir. 303 final FileObserver mFrameworkInstallObserver; 304 305 // This is the object monitoring the system app dir. 306 final FileObserver mSystemInstallObserver; 307 308 // This is the object monitoring the privileged system app dir. 309 final FileObserver mPrivilegedInstallObserver; 310 311 // This is the object monitoring the vendor app dir. 312 final FileObserver mVendorInstallObserver; 313 314 // This is the object monitoring the vendor overlay package dir. 315 final FileObserver mVendorOverlayInstallObserver; 316 317 // This is the object monitoring the OEM app dir. 318 final FileObserver mOemInstallObserver; 319 320 // This is the object monitoring mAppInstallDir. 321 final FileObserver mAppInstallObserver; 322 323 // This is the object monitoring mDrmAppPrivateInstallDir. 324 final FileObserver mDrmAppInstallObserver; 325 326 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 327 // LOCK HELD. Can be called with mInstallLock held. 328 final Installer mInstaller; 329 330 final File mAppInstallDir; 331 332 /** 333 * Directory to which applications installed internally have native 334 * libraries copied. 335 */ 336 private File mAppLibInstallDir; 337 338 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 339 // apps. 340 final File mDrmAppPrivateInstallDir; 341 342 // ---------------------------------------------------------------- 343 344 // Lock for state used when installing and doing other long running 345 // operations. Methods that must be called with this lock held have 346 // the suffix "LI". 347 final Object mInstallLock = new Object(); 348 349 // These are the directories in the 3rd party applications installed dir 350 // that we have currently loaded packages from. Keys are the application's 351 // installed zip file (absolute codePath), and values are Package. 352 final HashMap<String, PackageParser.Package> mAppDirs = 353 new HashMap<String, PackageParser.Package>(); 354 355 // Information for the parser to write more useful error messages. 356 int mLastScanError; 357 358 // ---------------------------------------------------------------- 359 360 // Keys are String (package name), values are Package. This also serves 361 // as the lock for the global state. Methods that must be called with 362 // this lock held have the prefix "LP". 363 final HashMap<String, PackageParser.Package> mPackages = 364 new HashMap<String, PackageParser.Package>(); 365 366 // Tracks available target package names -> overlay package paths. 367 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 368 new HashMap<String, HashMap<String, PackageParser.Package>>(); 369 370 final Settings mSettings; 371 boolean mRestoredSettings; 372 373 // Group-ids that are given to all packages as read from etc/permissions/*.xml. 374 int[] mGlobalGids; 375 376 // These are the built-in uid -> permission mappings that were read from the 377 // etc/permissions.xml file. 378 final SparseArray<HashSet<String>> mSystemPermissions = 379 new SparseArray<HashSet<String>>(); 380 381 static final class SharedLibraryEntry { 382 final String path; 383 final String apk; 384 385 SharedLibraryEntry(String _path, String _apk) { 386 path = _path; 387 apk = _apk; 388 } 389 } 390 391 // These are the built-in shared libraries that were read from the 392 // etc/permissions.xml file. 393 final HashMap<String, SharedLibraryEntry> mSharedLibraries 394 = new HashMap<String, SharedLibraryEntry>(); 395 396 // Temporary for building the final shared libraries for an .apk. 397 String[] mTmpSharedLibraries = null; 398 399 // These are the features this devices supports that were read from the 400 // etc/permissions.xml file. 401 final HashMap<String, FeatureInfo> mAvailableFeatures = 402 new HashMap<String, FeatureInfo>(); 403 404 // If mac_permissions.xml was found for seinfo labeling. 405 boolean mFoundPolicyFile; 406 407 // If a recursive restorecon of /data/data/<pkg> is needed. 408 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 409 410 // All available activities, for your resolving pleasure. 411 final ActivityIntentResolver mActivities = 412 new ActivityIntentResolver(); 413 414 // All available receivers, for your resolving pleasure. 415 final ActivityIntentResolver mReceivers = 416 new ActivityIntentResolver(); 417 418 // All available services, for your resolving pleasure. 419 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 420 421 // All available providers, for your resolving pleasure. 422 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 423 424 // Mapping from provider base names (first directory in content URI codePath) 425 // to the provider information. 426 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 427 new HashMap<String, PackageParser.Provider>(); 428 429 // Mapping from instrumentation class names to info about them. 430 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 431 new HashMap<ComponentName, PackageParser.Instrumentation>(); 432 433 // Mapping from permission names to info about them. 434 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 435 new HashMap<String, PackageParser.PermissionGroup>(); 436 437 // Packages whose data we have transfered into another package, thus 438 // should no longer exist. 439 final HashSet<String> mTransferedPackages = new HashSet<String>(); 440 441 // Broadcast actions that are only available to the system. 442 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 443 444 /** List of packages waiting for verification. */ 445 final SparseArray<PackageVerificationState> mPendingVerification 446 = new SparseArray<PackageVerificationState>(); 447 448 HashSet<PackageParser.Package> mDeferredDexOpt = null; 449 450 /** Token for keys in mPendingVerification. */ 451 private int mPendingVerificationToken = 0; 452 453 boolean mSystemReady; 454 boolean mSafeMode; 455 boolean mHasSystemUidErrors; 456 457 ApplicationInfo mAndroidApplication; 458 final ActivityInfo mResolveActivity = new ActivityInfo(); 459 final ResolveInfo mResolveInfo = new ResolveInfo(); 460 ComponentName mResolveComponentName; 461 PackageParser.Package mPlatformPackage; 462 ComponentName mCustomResolverComponentName; 463 464 boolean mResolverReplaced = false; 465 466 // Set of pending broadcasts for aggregating enable/disable of components. 467 static class PendingPackageBroadcasts { 468 // for each user id, a map of <package name -> components within that package> 469 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 470 471 public PendingPackageBroadcasts() { 472 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 473 } 474 475 public ArrayList<String> get(int userId, String packageName) { 476 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 477 return packages.get(packageName); 478 } 479 480 public void put(int userId, String packageName, ArrayList<String> components) { 481 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 482 packages.put(packageName, components); 483 } 484 485 public void remove(int userId, String packageName) { 486 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 487 if (packages != null) { 488 packages.remove(packageName); 489 } 490 } 491 492 public void remove(int userId) { 493 mUidMap.remove(userId); 494 } 495 496 public int userIdCount() { 497 return mUidMap.size(); 498 } 499 500 public int userIdAt(int n) { 501 return mUidMap.keyAt(n); 502 } 503 504 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 505 return mUidMap.get(userId); 506 } 507 508 public int size() { 509 // total number of pending broadcast entries across all userIds 510 int num = 0; 511 for (int i = 0; i< mUidMap.size(); i++) { 512 num += mUidMap.valueAt(i).size(); 513 } 514 return num; 515 } 516 517 public void clear() { 518 mUidMap.clear(); 519 } 520 521 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 522 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 523 if (map == null) { 524 map = new HashMap<String, ArrayList<String>>(); 525 mUidMap.put(userId, map); 526 } 527 return map; 528 } 529 } 530 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 531 532 // Service Connection to remote media container service to copy 533 // package uri's from external media onto secure containers 534 // or internal storage. 535 private IMediaContainerService mContainerService = null; 536 537 static final int SEND_PENDING_BROADCAST = 1; 538 static final int MCS_BOUND = 3; 539 static final int END_COPY = 4; 540 static final int INIT_COPY = 5; 541 static final int MCS_UNBIND = 6; 542 static final int START_CLEANING_PACKAGE = 7; 543 static final int FIND_INSTALL_LOC = 8; 544 static final int POST_INSTALL = 9; 545 static final int MCS_RECONNECT = 10; 546 static final int MCS_GIVE_UP = 11; 547 static final int UPDATED_MEDIA_STATUS = 12; 548 static final int WRITE_SETTINGS = 13; 549 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 550 static final int PACKAGE_VERIFIED = 15; 551 static final int CHECK_PENDING_VERIFICATION = 16; 552 553 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 554 555 // Delay time in millisecs 556 static final int BROADCAST_DELAY = 10 * 1000; 557 558 static UserManagerService sUserManager; 559 560 // Stores a list of users whose package restrictions file needs to be updated 561 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 562 563 final private DefaultContainerConnection mDefContainerConn = 564 new DefaultContainerConnection(); 565 class DefaultContainerConnection implements ServiceConnection { 566 public void onServiceConnected(ComponentName name, IBinder service) { 567 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 568 IMediaContainerService imcs = 569 IMediaContainerService.Stub.asInterface(service); 570 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 571 } 572 573 public void onServiceDisconnected(ComponentName name) { 574 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 575 } 576 }; 577 578 // Recordkeeping of restore-after-install operations that are currently in flight 579 // between the Package Manager and the Backup Manager 580 class PostInstallData { 581 public InstallArgs args; 582 public PackageInstalledInfo res; 583 584 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 585 args = _a; 586 res = _r; 587 } 588 }; 589 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 590 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 591 592 private final String mRequiredVerifierPackage; 593 594 class PackageHandler extends Handler { 595 private boolean mBound = false; 596 final ArrayList<HandlerParams> mPendingInstalls = 597 new ArrayList<HandlerParams>(); 598 599 private boolean connectToService() { 600 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 601 " DefaultContainerService"); 602 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 603 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 604 if (mContext.bindServiceAsUser(service, mDefContainerConn, 605 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 606 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 607 mBound = true; 608 return true; 609 } 610 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 611 return false; 612 } 613 614 private void disconnectService() { 615 mContainerService = null; 616 mBound = false; 617 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 618 mContext.unbindService(mDefContainerConn); 619 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 620 } 621 622 PackageHandler(Looper looper) { 623 super(looper); 624 } 625 626 public void handleMessage(Message msg) { 627 try { 628 doHandleMessage(msg); 629 } finally { 630 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 631 } 632 } 633 634 void doHandleMessage(Message msg) { 635 switch (msg.what) { 636 case INIT_COPY: { 637 HandlerParams params = (HandlerParams) msg.obj; 638 int idx = mPendingInstalls.size(); 639 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 640 // If a bind was already initiated we dont really 641 // need to do anything. The pending install 642 // will be processed later on. 643 if (!mBound) { 644 // If this is the only one pending we might 645 // have to bind to the service again. 646 if (!connectToService()) { 647 Slog.e(TAG, "Failed to bind to media container service"); 648 params.serviceError(); 649 return; 650 } else { 651 // Once we bind to the service, the first 652 // pending request will be processed. 653 mPendingInstalls.add(idx, params); 654 } 655 } else { 656 mPendingInstalls.add(idx, params); 657 // Already bound to the service. Just make 658 // sure we trigger off processing the first request. 659 if (idx == 0) { 660 mHandler.sendEmptyMessage(MCS_BOUND); 661 } 662 } 663 break; 664 } 665 case MCS_BOUND: { 666 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 667 if (msg.obj != null) { 668 mContainerService = (IMediaContainerService) msg.obj; 669 } 670 if (mContainerService == null) { 671 // Something seriously wrong. Bail out 672 Slog.e(TAG, "Cannot bind to media container service"); 673 for (HandlerParams params : mPendingInstalls) { 674 // Indicate service bind error 675 params.serviceError(); 676 } 677 mPendingInstalls.clear(); 678 } else if (mPendingInstalls.size() > 0) { 679 HandlerParams params = mPendingInstalls.get(0); 680 if (params != null) { 681 if (params.startCopy()) { 682 // We are done... look for more work or to 683 // go idle. 684 if (DEBUG_SD_INSTALL) Log.i(TAG, 685 "Checking for more work or unbind..."); 686 // Delete pending install 687 if (mPendingInstalls.size() > 0) { 688 mPendingInstalls.remove(0); 689 } 690 if (mPendingInstalls.size() == 0) { 691 if (mBound) { 692 if (DEBUG_SD_INSTALL) Log.i(TAG, 693 "Posting delayed MCS_UNBIND"); 694 removeMessages(MCS_UNBIND); 695 Message ubmsg = obtainMessage(MCS_UNBIND); 696 // Unbind after a little delay, to avoid 697 // continual thrashing. 698 sendMessageDelayed(ubmsg, 10000); 699 } 700 } else { 701 // There are more pending requests in queue. 702 // Just post MCS_BOUND message to trigger processing 703 // of next pending install. 704 if (DEBUG_SD_INSTALL) Log.i(TAG, 705 "Posting MCS_BOUND for next work"); 706 mHandler.sendEmptyMessage(MCS_BOUND); 707 } 708 } 709 } 710 } else { 711 // Should never happen ideally. 712 Slog.w(TAG, "Empty queue"); 713 } 714 break; 715 } 716 case MCS_RECONNECT: { 717 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 718 if (mPendingInstalls.size() > 0) { 719 if (mBound) { 720 disconnectService(); 721 } 722 if (!connectToService()) { 723 Slog.e(TAG, "Failed to bind to media container service"); 724 for (HandlerParams params : mPendingInstalls) { 725 // Indicate service bind error 726 params.serviceError(); 727 } 728 mPendingInstalls.clear(); 729 } 730 } 731 break; 732 } 733 case MCS_UNBIND: { 734 // If there is no actual work left, then time to unbind. 735 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 736 737 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 738 if (mBound) { 739 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 740 741 disconnectService(); 742 } 743 } else if (mPendingInstalls.size() > 0) { 744 // There are more pending requests in queue. 745 // Just post MCS_BOUND message to trigger processing 746 // of next pending install. 747 mHandler.sendEmptyMessage(MCS_BOUND); 748 } 749 750 break; 751 } 752 case MCS_GIVE_UP: { 753 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 754 mPendingInstalls.remove(0); 755 break; 756 } 757 case SEND_PENDING_BROADCAST: { 758 String packages[]; 759 ArrayList<String> components[]; 760 int size = 0; 761 int uids[]; 762 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 763 synchronized (mPackages) { 764 if (mPendingBroadcasts == null) { 765 return; 766 } 767 size = mPendingBroadcasts.size(); 768 if (size <= 0) { 769 // Nothing to be done. Just return 770 return; 771 } 772 packages = new String[size]; 773 components = new ArrayList[size]; 774 uids = new int[size]; 775 int i = 0; // filling out the above arrays 776 777 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 778 int packageUserId = mPendingBroadcasts.userIdAt(n); 779 Iterator<Map.Entry<String, ArrayList<String>>> it 780 = mPendingBroadcasts.packagesForUserId(packageUserId) 781 .entrySet().iterator(); 782 while (it.hasNext() && i < size) { 783 Map.Entry<String, ArrayList<String>> ent = it.next(); 784 packages[i] = ent.getKey(); 785 components[i] = ent.getValue(); 786 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 787 uids[i] = (ps != null) 788 ? UserHandle.getUid(packageUserId, ps.appId) 789 : -1; 790 i++; 791 } 792 } 793 size = i; 794 mPendingBroadcasts.clear(); 795 } 796 // Send broadcasts 797 for (int i = 0; i < size; i++) { 798 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 799 } 800 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 801 break; 802 } 803 case START_CLEANING_PACKAGE: { 804 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 805 final String packageName = (String)msg.obj; 806 final int userId = msg.arg1; 807 final boolean andCode = msg.arg2 != 0; 808 synchronized (mPackages) { 809 if (userId == UserHandle.USER_ALL) { 810 int[] users = sUserManager.getUserIds(); 811 for (int user : users) { 812 mSettings.addPackageToCleanLPw( 813 new PackageCleanItem(user, packageName, andCode)); 814 } 815 } else { 816 mSettings.addPackageToCleanLPw( 817 new PackageCleanItem(userId, packageName, andCode)); 818 } 819 } 820 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 821 startCleaningPackages(); 822 } break; 823 case POST_INSTALL: { 824 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 825 PostInstallData data = mRunningInstalls.get(msg.arg1); 826 mRunningInstalls.delete(msg.arg1); 827 boolean deleteOld = false; 828 829 if (data != null) { 830 InstallArgs args = data.args; 831 PackageInstalledInfo res = data.res; 832 833 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 834 res.removedInfo.sendBroadcast(false, true, false); 835 Bundle extras = new Bundle(1); 836 extras.putInt(Intent.EXTRA_UID, res.uid); 837 // Determine the set of users who are adding this 838 // package for the first time vs. those who are seeing 839 // an update. 840 int[] firstUsers; 841 int[] updateUsers = new int[0]; 842 if (res.origUsers == null || res.origUsers.length == 0) { 843 firstUsers = res.newUsers; 844 } else { 845 firstUsers = new int[0]; 846 for (int i=0; i<res.newUsers.length; i++) { 847 int user = res.newUsers[i]; 848 boolean isNew = true; 849 for (int j=0; j<res.origUsers.length; j++) { 850 if (res.origUsers[j] == user) { 851 isNew = false; 852 break; 853 } 854 } 855 if (isNew) { 856 int[] newFirst = new int[firstUsers.length+1]; 857 System.arraycopy(firstUsers, 0, newFirst, 0, 858 firstUsers.length); 859 newFirst[firstUsers.length] = user; 860 firstUsers = newFirst; 861 } else { 862 int[] newUpdate = new int[updateUsers.length+1]; 863 System.arraycopy(updateUsers, 0, newUpdate, 0, 864 updateUsers.length); 865 newUpdate[updateUsers.length] = user; 866 updateUsers = newUpdate; 867 } 868 } 869 } 870 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 871 res.pkg.applicationInfo.packageName, 872 extras, null, null, firstUsers); 873 final boolean update = res.removedInfo.removedPackage != null; 874 if (update) { 875 extras.putBoolean(Intent.EXTRA_REPLACING, true); 876 } 877 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 878 res.pkg.applicationInfo.packageName, 879 extras, null, null, updateUsers); 880 if (update) { 881 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 882 res.pkg.applicationInfo.packageName, 883 extras, null, null, updateUsers); 884 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 885 null, null, 886 res.pkg.applicationInfo.packageName, null, updateUsers); 887 888 // treat asec-hosted packages like removable media on upgrade 889 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 890 if (DEBUG_INSTALL) { 891 Slog.i(TAG, "upgrading pkg " + res.pkg 892 + " is ASEC-hosted -> AVAILABLE"); 893 } 894 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 895 ArrayList<String> pkgList = new ArrayList<String>(1); 896 pkgList.add(res.pkg.applicationInfo.packageName); 897 sendResourcesChangedBroadcast(true, true, 898 pkgList,uidArray, null); 899 } 900 } 901 if (res.removedInfo.args != null) { 902 // Remove the replaced package's older resources safely now 903 deleteOld = true; 904 } 905 906 // Log current value of "unknown sources" setting 907 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 908 getUnknownSourcesSettings()); 909 } 910 // Force a gc to clear up things 911 Runtime.getRuntime().gc(); 912 // We delete after a gc for applications on sdcard. 913 if (deleteOld) { 914 synchronized (mInstallLock) { 915 res.removedInfo.args.doPostDeleteLI(true); 916 } 917 } 918 if (args.observer != null) { 919 try { 920 args.observer.packageInstalled(res.name, res.returnCode); 921 } catch (RemoteException e) { 922 Slog.i(TAG, "Observer no longer exists."); 923 } 924 } 925 if (args.observer2 != null) { 926 try { 927 Bundle extras = extrasForInstallResult(res); 928 args.observer2.packageInstalled(res.name, extras, res.returnCode); 929 } catch (RemoteException e) { 930 Slog.i(TAG, "Observer no longer exists."); 931 } 932 } 933 } else { 934 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 935 } 936 } break; 937 case UPDATED_MEDIA_STATUS: { 938 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 939 boolean reportStatus = msg.arg1 == 1; 940 boolean doGc = msg.arg2 == 1; 941 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 942 if (doGc) { 943 // Force a gc to clear up stale containers. 944 Runtime.getRuntime().gc(); 945 } 946 if (msg.obj != null) { 947 @SuppressWarnings("unchecked") 948 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 949 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 950 // Unload containers 951 unloadAllContainers(args); 952 } 953 if (reportStatus) { 954 try { 955 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 956 PackageHelper.getMountService().finishMediaUpdate(); 957 } catch (RemoteException e) { 958 Log.e(TAG, "MountService not running?"); 959 } 960 } 961 } break; 962 case WRITE_SETTINGS: { 963 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 964 synchronized (mPackages) { 965 removeMessages(WRITE_SETTINGS); 966 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 967 mSettings.writeLPr(); 968 mDirtyUsers.clear(); 969 } 970 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 971 } break; 972 case WRITE_PACKAGE_RESTRICTIONS: { 973 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 974 synchronized (mPackages) { 975 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 976 for (int userId : mDirtyUsers) { 977 mSettings.writePackageRestrictionsLPr(userId); 978 } 979 mDirtyUsers.clear(); 980 } 981 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 982 } break; 983 case CHECK_PENDING_VERIFICATION: { 984 final int verificationId = msg.arg1; 985 final PackageVerificationState state = mPendingVerification.get(verificationId); 986 987 if ((state != null) && !state.timeoutExtended()) { 988 final InstallArgs args = state.getInstallArgs(); 989 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString()); 990 mPendingVerification.remove(verificationId); 991 992 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 993 994 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 995 Slog.i(TAG, "Continuing with installation of " 996 + args.packageURI.toString()); 997 state.setVerifierResponse(Binder.getCallingUid(), 998 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 999 broadcastPackageVerified(verificationId, args.packageURI, 1000 PackageManager.VERIFICATION_ALLOW, 1001 state.getInstallArgs().getUser()); 1002 try { 1003 ret = args.copyApk(mContainerService, true); 1004 } catch (RemoteException e) { 1005 Slog.e(TAG, "Could not contact the ContainerService"); 1006 } 1007 } else { 1008 broadcastPackageVerified(verificationId, args.packageURI, 1009 PackageManager.VERIFICATION_REJECT, 1010 state.getInstallArgs().getUser()); 1011 } 1012 1013 processPendingInstall(args, ret); 1014 mHandler.sendEmptyMessage(MCS_UNBIND); 1015 } 1016 break; 1017 } 1018 case PACKAGE_VERIFIED: { 1019 final int verificationId = msg.arg1; 1020 1021 final PackageVerificationState state = mPendingVerification.get(verificationId); 1022 if (state == null) { 1023 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1024 break; 1025 } 1026 1027 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1028 1029 state.setVerifierResponse(response.callerUid, response.code); 1030 1031 if (state.isVerificationComplete()) { 1032 mPendingVerification.remove(verificationId); 1033 1034 final InstallArgs args = state.getInstallArgs(); 1035 1036 int ret; 1037 if (state.isInstallAllowed()) { 1038 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1039 broadcastPackageVerified(verificationId, args.packageURI, 1040 response.code, state.getInstallArgs().getUser()); 1041 try { 1042 ret = args.copyApk(mContainerService, true); 1043 } catch (RemoteException e) { 1044 Slog.e(TAG, "Could not contact the ContainerService"); 1045 } 1046 } else { 1047 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1048 } 1049 1050 processPendingInstall(args, ret); 1051 1052 mHandler.sendEmptyMessage(MCS_UNBIND); 1053 } 1054 1055 break; 1056 } 1057 } 1058 } 1059 } 1060 1061 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1062 Bundle extras = null; 1063 switch (res.returnCode) { 1064 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1065 extras = new Bundle(); 1066 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1067 res.origPermission); 1068 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1069 res.origPackage); 1070 break; 1071 } 1072 } 1073 return extras; 1074 } 1075 1076 void scheduleWriteSettingsLocked() { 1077 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1078 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1079 } 1080 } 1081 1082 void scheduleWritePackageRestrictionsLocked(int userId) { 1083 if (!sUserManager.exists(userId)) return; 1084 mDirtyUsers.add(userId); 1085 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1086 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1087 } 1088 } 1089 1090 public static final IPackageManager main(Context context, Installer installer, 1091 boolean factoryTest, boolean onlyCore) { 1092 PackageManagerService m = new PackageManagerService(context, installer, 1093 factoryTest, onlyCore); 1094 ServiceManager.addService("package", m); 1095 return m; 1096 } 1097 1098 static String[] splitString(String str, char sep) { 1099 int count = 1; 1100 int i = 0; 1101 while ((i=str.indexOf(sep, i)) >= 0) { 1102 count++; 1103 i++; 1104 } 1105 1106 String[] res = new String[count]; 1107 i=0; 1108 count = 0; 1109 int lastI=0; 1110 while ((i=str.indexOf(sep, i)) >= 0) { 1111 res[count] = str.substring(lastI, i); 1112 count++; 1113 i++; 1114 lastI = i; 1115 } 1116 res[count] = str.substring(lastI, str.length()); 1117 return res; 1118 } 1119 1120 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1121 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1122 Context.DISPLAY_SERVICE); 1123 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1124 } 1125 1126 public PackageManagerService(Context context, Installer installer, 1127 boolean factoryTest, boolean onlyCore) { 1128 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1129 SystemClock.uptimeMillis()); 1130 1131 if (mSdkVersion <= 0) { 1132 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1133 } 1134 1135 mContext = context; 1136 mFactoryTest = factoryTest; 1137 mOnlyCore = onlyCore; 1138 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1139 mMetrics = new DisplayMetrics(); 1140 mSettings = new Settings(context); 1141 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1142 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1143 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1144 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1145 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1146 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1147 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1148 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1149 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1150 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1151 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1152 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1153 1154 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1155 if (separateProcesses != null && separateProcesses.length() > 0) { 1156 if ("*".equals(separateProcesses)) { 1157 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1158 mSeparateProcesses = null; 1159 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1160 } else { 1161 mDefParseFlags = 0; 1162 mSeparateProcesses = separateProcesses.split(","); 1163 Slog.w(TAG, "Running with debug.separate_processes: " 1164 + separateProcesses); 1165 } 1166 } else { 1167 mDefParseFlags = 0; 1168 mSeparateProcesses = null; 1169 } 1170 1171 mInstaller = installer; 1172 1173 getDefaultDisplayMetrics(context, mMetrics); 1174 1175 synchronized (mInstallLock) { 1176 // writer 1177 synchronized (mPackages) { 1178 mHandlerThread = new ServiceThread(TAG, 1179 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1180 mHandlerThread.start(); 1181 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1182 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1183 1184 File dataDir = Environment.getDataDirectory(); 1185 mAppDataDir = new File(dataDir, "data"); 1186 mAppInstallDir = new File(dataDir, "app"); 1187 mAppLibInstallDir = new File(dataDir, "app-lib"); 1188 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1189 mUserAppDataDir = new File(dataDir, "user"); 1190 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1191 1192 sUserManager = new UserManagerService(context, this, 1193 mInstallLock, mPackages); 1194 1195 // Read permissions and features from system 1196 readPermissions(Environment.buildPath( 1197 Environment.getRootDirectory(), "etc", "permissions"), false); 1198 // Only read features from OEM 1199 readPermissions(Environment.buildPath( 1200 Environment.getOemDirectory(), "etc", "permissions"), true); 1201 1202 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1203 1204 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1205 mSdkVersion, mOnlyCore); 1206 1207 String customResolverActivity = Resources.getSystem().getString( 1208 R.string.config_customResolverActivity); 1209 if (TextUtils.isEmpty(customResolverActivity)) { 1210 customResolverActivity = null; 1211 } else { 1212 mCustomResolverComponentName = ComponentName.unflattenFromString( 1213 customResolverActivity); 1214 } 1215 1216 long startTime = SystemClock.uptimeMillis(); 1217 1218 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1219 startTime); 1220 1221 // Set flag to monitor and not change apk file paths when 1222 // scanning install directories. 1223 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1224 if (mNoDexOpt) { 1225 Slog.w(TAG, "Running ENG build: no pre-dexopt!"); 1226 scanMode |= SCAN_NO_DEX; 1227 } 1228 1229 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1230 1231 /** 1232 * Add everything in the in the boot class path to the 1233 * list of process files because dexopt will have been run 1234 * if necessary during zygote startup. 1235 */ 1236 String bootClassPath = System.getProperty("java.boot.class.path"); 1237 if (bootClassPath != null) { 1238 String[] paths = splitString(bootClassPath, ':'); 1239 for (int i=0; i<paths.length; i++) { 1240 alreadyDexOpted.add(paths[i]); 1241 } 1242 } else { 1243 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1244 } 1245 1246 boolean didDexOpt = false; 1247 1248 final List<String> instructionSets = getAllInstructionSets(); 1249 1250 /** 1251 * Ensure all external libraries have had dexopt run on them. 1252 */ 1253 if (mSharedLibraries.size() > 0) { 1254 // NOTE: For now, we're compiling these system "shared libraries" 1255 // (and framework jars) into all available architectures. It's possible 1256 // to compile them only when we come across an app that uses them (there's 1257 // already logic for that in scanPackageLI) but that adds some complexity. 1258 for (String instructionSet : instructionSets) { 1259 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1260 final String lib = libEntry.path; 1261 if (lib == null) { 1262 continue; 1263 } 1264 1265 try { 1266 if (dalvik.system.DexFile.isDexOptNeededInternal( 1267 lib, null, instructionSet, false)) { 1268 alreadyDexOpted.add(lib); 1269 1270 // The list of "shared libraries" we have at this point is 1271 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1272 didDexOpt = true; 1273 } 1274 } catch (FileNotFoundException e) { 1275 Slog.w(TAG, "Library not found: " + lib); 1276 } catch (IOException e) { 1277 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1278 + e.getMessage()); 1279 } 1280 } 1281 } 1282 } 1283 1284 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1285 1286 // Gross hack for now: we know this file doesn't contain any 1287 // code, so don't dexopt it to avoid the resulting log spew. 1288 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1289 1290 // Gross hack for now: we know this file is only part of 1291 // the boot class path for art, so don't dexopt it to 1292 // avoid the resulting log spew. 1293 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1294 1295 /** 1296 * And there are a number of commands implemented in Java, which 1297 * we currently need to do the dexopt on so that they can be 1298 * run from a non-root shell. 1299 */ 1300 String[] frameworkFiles = frameworkDir.list(); 1301 if (frameworkFiles != null) { 1302 // TODO: We could compile these only for the most preferred ABI. We should 1303 // first double check that the dex files for these commands are not referenced 1304 // by other system apps. 1305 for (String instructionSet : instructionSets) { 1306 for (int i=0; i<frameworkFiles.length; i++) { 1307 File libPath = new File(frameworkDir, frameworkFiles[i]); 1308 String path = libPath.getPath(); 1309 // Skip the file if we already did it. 1310 if (alreadyDexOpted.contains(path)) { 1311 continue; 1312 } 1313 // Skip the file if it is not a type we want to dexopt. 1314 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1315 continue; 1316 } 1317 try { 1318 if (dalvik.system.DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1319 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1320 didDexOpt = true; 1321 } 1322 } catch (FileNotFoundException e) { 1323 Slog.w(TAG, "Jar not found: " + path); 1324 } catch (IOException e) { 1325 Slog.w(TAG, "Exception reading jar: " + path, e); 1326 } 1327 } 1328 } 1329 } 1330 1331 if (didDexOpt) { 1332 pruneDexFiles(new File(dataDir, "dalvik-cache")); 1333 } 1334 1335 // Collect vendor overlay packages. 1336 // (Do this before scanning any apps.) 1337 // For security and version matching reason, only consider 1338 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1339 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1340 mVendorOverlayInstallObserver = new AppDirObserver( 1341 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1342 mVendorOverlayInstallObserver.startWatching(); 1343 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1344 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1345 1346 // Find base frameworks (resource packages without code). 1347 mFrameworkInstallObserver = new AppDirObserver( 1348 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1349 mFrameworkInstallObserver.startWatching(); 1350 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1351 | PackageParser.PARSE_IS_SYSTEM_DIR 1352 | PackageParser.PARSE_IS_PRIVILEGED, 1353 scanMode | SCAN_NO_DEX, 0); 1354 1355 // Collected privileged system packages. 1356 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1357 mPrivilegedInstallObserver = new AppDirObserver( 1358 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1359 mPrivilegedInstallObserver.startWatching(); 1360 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1361 | PackageParser.PARSE_IS_SYSTEM_DIR 1362 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1363 1364 // Collect ordinary system packages. 1365 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1366 mSystemInstallObserver = new AppDirObserver( 1367 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1368 mSystemInstallObserver.startWatching(); 1369 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1370 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1371 1372 // Collect all vendor packages. 1373 File vendorAppDir = new File("/vendor/app"); 1374 try { 1375 vendorAppDir = vendorAppDir.getCanonicalFile(); 1376 } catch (IOException e) { 1377 // failed to look up canonical path, continue with original one 1378 } 1379 mVendorInstallObserver = new AppDirObserver( 1380 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1381 mVendorInstallObserver.startWatching(); 1382 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1383 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1384 1385 // Collect all OEM packages. 1386 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1387 mOemInstallObserver = new AppDirObserver( 1388 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1389 mOemInstallObserver.startWatching(); 1390 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1391 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1392 1393 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1394 mInstaller.moveFiles(); 1395 1396 // Prune any system packages that no longer exist. 1397 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1398 if (!mOnlyCore) { 1399 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1400 while (psit.hasNext()) { 1401 PackageSetting ps = psit.next(); 1402 1403 /* 1404 * If this is not a system app, it can't be a 1405 * disable system app. 1406 */ 1407 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1408 continue; 1409 } 1410 1411 /* 1412 * If the package is scanned, it's not erased. 1413 */ 1414 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1415 if (scannedPkg != null) { 1416 /* 1417 * If the system app is both scanned and in the 1418 * disabled packages list, then it must have been 1419 * added via OTA. Remove it from the currently 1420 * scanned package so the previously user-installed 1421 * application can be scanned. 1422 */ 1423 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1424 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1425 + "; removing system app"); 1426 removePackageLI(ps, true); 1427 } 1428 1429 continue; 1430 } 1431 1432 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1433 psit.remove(); 1434 String msg = "System package " + ps.name 1435 + " no longer exists; wiping its data"; 1436 reportSettingsProblem(Log.WARN, msg); 1437 removeDataDirsLI(ps.name); 1438 } else { 1439 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1440 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1441 possiblyDeletedUpdatedSystemApps.add(ps.name); 1442 } 1443 } 1444 } 1445 } 1446 1447 //look for any incomplete package installations 1448 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1449 //clean up list 1450 for(int i = 0; i < deletePkgsList.size(); i++) { 1451 //clean up here 1452 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1453 } 1454 //delete tmp files 1455 deleteTempPackageFiles(); 1456 1457 // Remove any shared userIDs that have no associated packages 1458 mSettings.pruneSharedUsersLPw(); 1459 1460 if (!mOnlyCore) { 1461 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1462 SystemClock.uptimeMillis()); 1463 mAppInstallObserver = new AppDirObserver( 1464 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1465 mAppInstallObserver.startWatching(); 1466 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1467 1468 mDrmAppInstallObserver = new AppDirObserver( 1469 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1470 mDrmAppInstallObserver.startWatching(); 1471 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1472 scanMode, 0); 1473 1474 /** 1475 * Remove disable package settings for any updated system 1476 * apps that were removed via an OTA. If they're not a 1477 * previously-updated app, remove them completely. 1478 * Otherwise, just revoke their system-level permissions. 1479 */ 1480 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1481 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1482 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1483 1484 String msg; 1485 if (deletedPkg == null) { 1486 msg = "Updated system package " + deletedAppName 1487 + " no longer exists; wiping its data"; 1488 removeDataDirsLI(deletedAppName); 1489 } else { 1490 msg = "Updated system app + " + deletedAppName 1491 + " no longer present; removing system privileges for " 1492 + deletedAppName; 1493 1494 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1495 1496 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1497 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1498 } 1499 reportSettingsProblem(Log.WARN, msg); 1500 } 1501 } else { 1502 mAppInstallObserver = null; 1503 mDrmAppInstallObserver = null; 1504 } 1505 1506 // Now that we know all of the shared libraries, update all clients to have 1507 // the correct library paths. 1508 updateAllSharedLibrariesLPw(); 1509 1510 1511 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1512 adjustCpuAbisForSharedUserLPw(setting.packages, true /* do dexopt */, 1513 false /* force dexopt */, false /* defer dexopt */); 1514 } 1515 1516 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1517 SystemClock.uptimeMillis()); 1518 Slog.i(TAG, "Time to scan packages: " 1519 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1520 + " seconds"); 1521 1522 // If the platform SDK has changed since the last time we booted, 1523 // we need to re-grant app permission to catch any new ones that 1524 // appear. This is really a hack, and means that apps can in some 1525 // cases get permissions that the user didn't initially explicitly 1526 // allow... it would be nice to have some better way to handle 1527 // this situation. 1528 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1529 != mSdkVersion; 1530 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1531 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1532 + "; regranting permissions for internal storage"); 1533 mSettings.mInternalSdkPlatform = mSdkVersion; 1534 1535 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1536 | (regrantPermissions 1537 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1538 : 0)); 1539 1540 // If this is the first boot, and it is a normal boot, then 1541 // we need to initialize the default preferred apps. 1542 if (!mRestoredSettings && !onlyCore) { 1543 mSettings.readDefaultPreferredAppsLPw(this, 0); 1544 } 1545 1546 // All the changes are done during package scanning. 1547 mSettings.updateInternalDatabaseVersion(); 1548 1549 // can downgrade to reader 1550 mSettings.writeLPr(); 1551 1552 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1553 SystemClock.uptimeMillis()); 1554 1555 // Now after opening every single application zip, make sure they 1556 // are all flushed. Not really needed, but keeps things nice and 1557 // tidy. 1558 Runtime.getRuntime().gc(); 1559 1560 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1561 } // synchronized (mPackages) 1562 } // synchronized (mInstallLock) 1563 } 1564 1565 private static void pruneDexFiles(File cacheDir) { 1566 // If we had to do a dexopt of one of the previous 1567 // things, then something on the system has changed. 1568 // Consider this significant, and wipe away all other 1569 // existing dexopt files to ensure we don't leave any 1570 // dangling around. 1571 // 1572 // Additionally, delete all dex files from the root directory 1573 // since there shouldn't be any there anyway. 1574 File[] files = cacheDir.listFiles(); 1575 if (files != null) { 1576 for (File file : files) { 1577 if (!file.isDirectory()) { 1578 Slog.i(TAG, "Pruning dalvik file: " + file.getAbsolutePath()); 1579 file.delete(); 1580 } else { 1581 File[] subDirList = file.listFiles(); 1582 if (subDirList != null) { 1583 for (File subDirFile : subDirList) { 1584 final String fn = subDirFile.getName(); 1585 if (fn.startsWith("data@app@") || fn.startsWith("data@app-private@")) { 1586 Slog.i(TAG, "Pruning dalvik file: " + fn); 1587 subDirFile.delete(); 1588 } 1589 } 1590 } 1591 } 1592 } 1593 } 1594 } 1595 1596 public boolean isFirstBoot() { 1597 return !mRestoredSettings; 1598 } 1599 1600 public boolean isOnlyCoreApps() { 1601 return mOnlyCore; 1602 } 1603 1604 private String getRequiredVerifierLPr() { 1605 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1606 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1607 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1608 1609 String requiredVerifier = null; 1610 1611 final int N = receivers.size(); 1612 for (int i = 0; i < N; i++) { 1613 final ResolveInfo info = receivers.get(i); 1614 1615 if (info.activityInfo == null) { 1616 continue; 1617 } 1618 1619 final String packageName = info.activityInfo.packageName; 1620 1621 final PackageSetting ps = mSettings.mPackages.get(packageName); 1622 if (ps == null) { 1623 continue; 1624 } 1625 1626 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1627 if (!gp.grantedPermissions 1628 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1629 continue; 1630 } 1631 1632 if (requiredVerifier != null) { 1633 throw new RuntimeException("There can be only one required verifier"); 1634 } 1635 1636 requiredVerifier = packageName; 1637 } 1638 1639 return requiredVerifier; 1640 } 1641 1642 @Override 1643 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1644 throws RemoteException { 1645 try { 1646 return super.onTransact(code, data, reply, flags); 1647 } catch (RuntimeException e) { 1648 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1649 Slog.wtf(TAG, "Package Manager Crash", e); 1650 } 1651 throw e; 1652 } 1653 } 1654 1655 void cleanupInstallFailedPackage(PackageSetting ps) { 1656 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1657 removeDataDirsLI(ps.name); 1658 if (ps.codePath != null) { 1659 if (!ps.codePath.delete()) { 1660 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1661 } 1662 } 1663 if (ps.resourcePath != null) { 1664 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1665 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1666 } 1667 } 1668 mSettings.removePackageLPw(ps.name); 1669 } 1670 1671 void readPermissions(File libraryDir, boolean onlyFeatures) { 1672 // Read permissions from .../etc/permission directory. 1673 if (!libraryDir.exists() || !libraryDir.isDirectory()) { 1674 Slog.w(TAG, "No directory " + libraryDir + ", skipping"); 1675 return; 1676 } 1677 if (!libraryDir.canRead()) { 1678 Slog.w(TAG, "Directory " + libraryDir + " cannot be read"); 1679 return; 1680 } 1681 1682 // Iterate over the files in the directory and scan .xml files 1683 for (File f : libraryDir.listFiles()) { 1684 // We'll read platform.xml last 1685 if (f.getPath().endsWith("etc/permissions/platform.xml")) { 1686 continue; 1687 } 1688 1689 if (!f.getPath().endsWith(".xml")) { 1690 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring"); 1691 continue; 1692 } 1693 if (!f.canRead()) { 1694 Slog.w(TAG, "Permissions library file " + f + " cannot be read"); 1695 continue; 1696 } 1697 1698 readPermissionsFromXml(f, onlyFeatures); 1699 } 1700 1701 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence 1702 final File permFile = new File(Environment.getRootDirectory(), 1703 "etc/permissions/platform.xml"); 1704 readPermissionsFromXml(permFile, onlyFeatures); 1705 } 1706 1707 private void readPermissionsFromXml(File permFile, boolean onlyFeatures) { 1708 FileReader permReader = null; 1709 try { 1710 permReader = new FileReader(permFile); 1711 } catch (FileNotFoundException e) { 1712 Slog.w(TAG, "Couldn't find or open permissions file " + permFile); 1713 return; 1714 } 1715 1716 try { 1717 XmlPullParser parser = Xml.newPullParser(); 1718 parser.setInput(permReader); 1719 1720 XmlUtils.beginDocument(parser, "permissions"); 1721 1722 while (true) { 1723 XmlUtils.nextElement(parser); 1724 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) { 1725 break; 1726 } 1727 1728 String name = parser.getName(); 1729 if ("group".equals(name) && !onlyFeatures) { 1730 String gidStr = parser.getAttributeValue(null, "gid"); 1731 if (gidStr != null) { 1732 int gid = Process.getGidForName(gidStr); 1733 mGlobalGids = appendInt(mGlobalGids, gid); 1734 } else { 1735 Slog.w(TAG, "<group> without gid at " 1736 + parser.getPositionDescription()); 1737 } 1738 1739 XmlUtils.skipCurrentTag(parser); 1740 continue; 1741 } else if ("permission".equals(name) && !onlyFeatures) { 1742 String perm = parser.getAttributeValue(null, "name"); 1743 if (perm == null) { 1744 Slog.w(TAG, "<permission> without name at " 1745 + parser.getPositionDescription()); 1746 XmlUtils.skipCurrentTag(parser); 1747 continue; 1748 } 1749 perm = perm.intern(); 1750 readPermission(parser, perm); 1751 1752 } else if ("assign-permission".equals(name) && !onlyFeatures) { 1753 String perm = parser.getAttributeValue(null, "name"); 1754 if (perm == null) { 1755 Slog.w(TAG, "<assign-permission> without name at " 1756 + parser.getPositionDescription()); 1757 XmlUtils.skipCurrentTag(parser); 1758 continue; 1759 } 1760 String uidStr = parser.getAttributeValue(null, "uid"); 1761 if (uidStr == null) { 1762 Slog.w(TAG, "<assign-permission> without uid at " 1763 + parser.getPositionDescription()); 1764 XmlUtils.skipCurrentTag(parser); 1765 continue; 1766 } 1767 int uid = Process.getUidForName(uidStr); 1768 if (uid < 0) { 1769 Slog.w(TAG, "<assign-permission> with unknown uid \"" 1770 + uidStr + "\" at " 1771 + parser.getPositionDescription()); 1772 XmlUtils.skipCurrentTag(parser); 1773 continue; 1774 } 1775 perm = perm.intern(); 1776 HashSet<String> perms = mSystemPermissions.get(uid); 1777 if (perms == null) { 1778 perms = new HashSet<String>(); 1779 mSystemPermissions.put(uid, perms); 1780 } 1781 perms.add(perm); 1782 XmlUtils.skipCurrentTag(parser); 1783 1784 } else if ("library".equals(name) && !onlyFeatures) { 1785 String lname = parser.getAttributeValue(null, "name"); 1786 String lfile = parser.getAttributeValue(null, "file"); 1787 if (lname == null) { 1788 Slog.w(TAG, "<library> without name at " 1789 + parser.getPositionDescription()); 1790 } else if (lfile == null) { 1791 Slog.w(TAG, "<library> without file at " 1792 + parser.getPositionDescription()); 1793 } else { 1794 //Log.i(TAG, "Got library " + lname + " in " + lfile); 1795 mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null)); 1796 } 1797 XmlUtils.skipCurrentTag(parser); 1798 continue; 1799 1800 } else if ("feature".equals(name)) { 1801 String fname = parser.getAttributeValue(null, "name"); 1802 if (fname == null) { 1803 Slog.w(TAG, "<feature> without name at " 1804 + parser.getPositionDescription()); 1805 } else { 1806 //Log.i(TAG, "Got feature " + fname); 1807 FeatureInfo fi = new FeatureInfo(); 1808 fi.name = fname; 1809 mAvailableFeatures.put(fname, fi); 1810 } 1811 XmlUtils.skipCurrentTag(parser); 1812 continue; 1813 1814 } else { 1815 XmlUtils.skipCurrentTag(parser); 1816 continue; 1817 } 1818 1819 } 1820 permReader.close(); 1821 } catch (XmlPullParserException e) { 1822 Slog.w(TAG, "Got execption parsing permissions.", e); 1823 } catch (IOException e) { 1824 Slog.w(TAG, "Got execption parsing permissions.", e); 1825 } 1826 } 1827 1828 void readPermission(XmlPullParser parser, String name) 1829 throws IOException, XmlPullParserException { 1830 1831 name = name.intern(); 1832 1833 BasePermission bp = mSettings.mPermissions.get(name); 1834 if (bp == null) { 1835 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN); 1836 mSettings.mPermissions.put(name, bp); 1837 } 1838 int outerDepth = parser.getDepth(); 1839 int type; 1840 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 1841 && (type != XmlPullParser.END_TAG 1842 || parser.getDepth() > outerDepth)) { 1843 if (type == XmlPullParser.END_TAG 1844 || type == XmlPullParser.TEXT) { 1845 continue; 1846 } 1847 1848 String tagName = parser.getName(); 1849 if ("group".equals(tagName)) { 1850 String gidStr = parser.getAttributeValue(null, "gid"); 1851 if (gidStr != null) { 1852 int gid = Process.getGidForName(gidStr); 1853 bp.gids = appendInt(bp.gids, gid); 1854 } else { 1855 Slog.w(TAG, "<group> without gid at " 1856 + parser.getPositionDescription()); 1857 } 1858 } 1859 XmlUtils.skipCurrentTag(parser); 1860 } 1861 } 1862 1863 static int[] appendInts(int[] cur, int[] add) { 1864 if (add == null) return cur; 1865 if (cur == null) return add; 1866 final int N = add.length; 1867 for (int i=0; i<N; i++) { 1868 cur = appendInt(cur, add[i]); 1869 } 1870 return cur; 1871 } 1872 1873 static int[] removeInts(int[] cur, int[] rem) { 1874 if (rem == null) return cur; 1875 if (cur == null) return cur; 1876 final int N = rem.length; 1877 for (int i=0; i<N; i++) { 1878 cur = removeInt(cur, rem[i]); 1879 } 1880 return cur; 1881 } 1882 1883 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1884 if (!sUserManager.exists(userId)) return null; 1885 final PackageSetting ps = (PackageSetting) p.mExtras; 1886 if (ps == null) { 1887 return null; 1888 } 1889 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1890 final PackageUserState state = ps.readUserState(userId); 1891 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1892 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1893 state, userId); 1894 } 1895 1896 public boolean isPackageAvailable(String packageName, int userId) { 1897 if (!sUserManager.exists(userId)) return false; 1898 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1899 synchronized (mPackages) { 1900 PackageParser.Package p = mPackages.get(packageName); 1901 if (p != null) { 1902 final PackageSetting ps = (PackageSetting) p.mExtras; 1903 if (ps != null) { 1904 final PackageUserState state = ps.readUserState(userId); 1905 if (state != null) { 1906 return PackageParser.isAvailable(state); 1907 } 1908 } 1909 } 1910 } 1911 return false; 1912 } 1913 1914 @Override 1915 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1916 if (!sUserManager.exists(userId)) return null; 1917 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1918 // reader 1919 synchronized (mPackages) { 1920 PackageParser.Package p = mPackages.get(packageName); 1921 if (DEBUG_PACKAGE_INFO) 1922 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1923 if (p != null) { 1924 return generatePackageInfo(p, flags, userId); 1925 } 1926 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1927 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1928 } 1929 } 1930 return null; 1931 } 1932 1933 public String[] currentToCanonicalPackageNames(String[] names) { 1934 String[] out = new String[names.length]; 1935 // reader 1936 synchronized (mPackages) { 1937 for (int i=names.length-1; i>=0; i--) { 1938 PackageSetting ps = mSettings.mPackages.get(names[i]); 1939 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1940 } 1941 } 1942 return out; 1943 } 1944 1945 public String[] canonicalToCurrentPackageNames(String[] names) { 1946 String[] out = new String[names.length]; 1947 // reader 1948 synchronized (mPackages) { 1949 for (int i=names.length-1; i>=0; i--) { 1950 String cur = mSettings.mRenamedPackages.get(names[i]); 1951 out[i] = cur != null ? cur : names[i]; 1952 } 1953 } 1954 return out; 1955 } 1956 1957 @Override 1958 public int getPackageUid(String packageName, int userId) { 1959 if (!sUserManager.exists(userId)) return -1; 1960 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1961 // reader 1962 synchronized (mPackages) { 1963 PackageParser.Package p = mPackages.get(packageName); 1964 if(p != null) { 1965 return UserHandle.getUid(userId, p.applicationInfo.uid); 1966 } 1967 PackageSetting ps = mSettings.mPackages.get(packageName); 1968 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1969 return -1; 1970 } 1971 p = ps.pkg; 1972 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1973 } 1974 } 1975 1976 @Override 1977 public int[] getPackageGids(String packageName) { 1978 // reader 1979 synchronized (mPackages) { 1980 PackageParser.Package p = mPackages.get(packageName); 1981 if (DEBUG_PACKAGE_INFO) 1982 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1983 if (p != null) { 1984 final PackageSetting ps = (PackageSetting)p.mExtras; 1985 return ps.getGids(); 1986 } 1987 } 1988 // stupid thing to indicate an error. 1989 return new int[0]; 1990 } 1991 1992 static final PermissionInfo generatePermissionInfo( 1993 BasePermission bp, int flags) { 1994 if (bp.perm != null) { 1995 return PackageParser.generatePermissionInfo(bp.perm, flags); 1996 } 1997 PermissionInfo pi = new PermissionInfo(); 1998 pi.name = bp.name; 1999 pi.packageName = bp.sourcePackage; 2000 pi.nonLocalizedLabel = bp.name; 2001 pi.protectionLevel = bp.protectionLevel; 2002 return pi; 2003 } 2004 2005 public PermissionInfo getPermissionInfo(String name, int flags) { 2006 // reader 2007 synchronized (mPackages) { 2008 final BasePermission p = mSettings.mPermissions.get(name); 2009 if (p != null) { 2010 return generatePermissionInfo(p, flags); 2011 } 2012 return null; 2013 } 2014 } 2015 2016 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2017 // reader 2018 synchronized (mPackages) { 2019 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2020 for (BasePermission p : mSettings.mPermissions.values()) { 2021 if (group == null) { 2022 if (p.perm == null || p.perm.info.group == null) { 2023 out.add(generatePermissionInfo(p, flags)); 2024 } 2025 } else { 2026 if (p.perm != null && group.equals(p.perm.info.group)) { 2027 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2028 } 2029 } 2030 } 2031 2032 if (out.size() > 0) { 2033 return out; 2034 } 2035 return mPermissionGroups.containsKey(group) ? out : null; 2036 } 2037 } 2038 2039 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2040 // reader 2041 synchronized (mPackages) { 2042 return PackageParser.generatePermissionGroupInfo( 2043 mPermissionGroups.get(name), flags); 2044 } 2045 } 2046 2047 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2048 // reader 2049 synchronized (mPackages) { 2050 final int N = mPermissionGroups.size(); 2051 ArrayList<PermissionGroupInfo> out 2052 = new ArrayList<PermissionGroupInfo>(N); 2053 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2054 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2055 } 2056 return out; 2057 } 2058 } 2059 2060 private ApplicationInfo generateApplicationInfoFromSettingsLPw(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 if (ps.pkg == null) { 2066 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2067 flags, userId); 2068 if (pInfo != null) { 2069 return pInfo.applicationInfo; 2070 } 2071 return null; 2072 } 2073 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2074 ps.readUserState(userId), userId); 2075 } 2076 return null; 2077 } 2078 2079 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2080 int userId) { 2081 if (!sUserManager.exists(userId)) return null; 2082 PackageSetting ps = mSettings.mPackages.get(packageName); 2083 if (ps != null) { 2084 PackageParser.Package pkg = ps.pkg; 2085 if (pkg == null) { 2086 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2087 return null; 2088 } 2089 pkg = new PackageParser.Package(packageName); 2090 pkg.applicationInfo.packageName = packageName; 2091 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2092 pkg.applicationInfo.publicSourceDir = ps.resourcePathString; 2093 pkg.applicationInfo.sourceDir = ps.codePathString; 2094 pkg.applicationInfo.dataDir = 2095 getDataPathForPackage(packageName, 0).getPath(); 2096 pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString; 2097 pkg.applicationInfo.requiredCpuAbi = ps.requiredCpuAbiString; 2098 } 2099 return generatePackageInfo(pkg, flags, userId); 2100 } 2101 return null; 2102 } 2103 2104 @Override 2105 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2106 if (!sUserManager.exists(userId)) return null; 2107 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2108 // writer 2109 synchronized (mPackages) { 2110 PackageParser.Package p = mPackages.get(packageName); 2111 if (DEBUG_PACKAGE_INFO) Log.v( 2112 TAG, "getApplicationInfo " + packageName 2113 + ": " + p); 2114 if (p != null) { 2115 PackageSetting ps = mSettings.mPackages.get(packageName); 2116 if (ps == null) return null; 2117 // Note: isEnabledLP() does not apply here - always return info 2118 return PackageParser.generateApplicationInfo( 2119 p, flags, ps.readUserState(userId), userId); 2120 } 2121 if ("android".equals(packageName)||"system".equals(packageName)) { 2122 return mAndroidApplication; 2123 } 2124 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2125 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2126 } 2127 } 2128 return null; 2129 } 2130 2131 2132 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2133 mContext.enforceCallingOrSelfPermission( 2134 android.Manifest.permission.CLEAR_APP_CACHE, null); 2135 // Queue up an async operation since clearing cache may take a little while. 2136 mHandler.post(new Runnable() { 2137 public void run() { 2138 mHandler.removeCallbacks(this); 2139 int retCode = -1; 2140 synchronized (mInstallLock) { 2141 retCode = mInstaller.freeCache(freeStorageSize); 2142 if (retCode < 0) { 2143 Slog.w(TAG, "Couldn't clear application caches"); 2144 } 2145 } 2146 if (observer != null) { 2147 try { 2148 observer.onRemoveCompleted(null, (retCode >= 0)); 2149 } catch (RemoteException e) { 2150 Slog.w(TAG, "RemoveException when invoking call back"); 2151 } 2152 } 2153 } 2154 }); 2155 } 2156 2157 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2158 mContext.enforceCallingOrSelfPermission( 2159 android.Manifest.permission.CLEAR_APP_CACHE, null); 2160 // Queue up an async operation since clearing cache may take a little while. 2161 mHandler.post(new Runnable() { 2162 public void run() { 2163 mHandler.removeCallbacks(this); 2164 int retCode = -1; 2165 synchronized (mInstallLock) { 2166 retCode = mInstaller.freeCache(freeStorageSize); 2167 if (retCode < 0) { 2168 Slog.w(TAG, "Couldn't clear application caches"); 2169 } 2170 } 2171 if(pi != null) { 2172 try { 2173 // Callback via pending intent 2174 int code = (retCode >= 0) ? 1 : 0; 2175 pi.sendIntent(null, code, null, 2176 null, null); 2177 } catch (SendIntentException e1) { 2178 Slog.i(TAG, "Failed to send pending intent"); 2179 } 2180 } 2181 } 2182 }); 2183 } 2184 2185 @Override 2186 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2187 if (!sUserManager.exists(userId)) return null; 2188 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2189 synchronized (mPackages) { 2190 PackageParser.Activity a = mActivities.mActivities.get(component); 2191 2192 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2193 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2194 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2195 if (ps == null) return null; 2196 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2197 userId); 2198 } 2199 if (mResolveComponentName.equals(component)) { 2200 return mResolveActivity; 2201 } 2202 } 2203 return null; 2204 } 2205 2206 @Override 2207 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2208 String resolvedType) { 2209 synchronized (mPackages) { 2210 PackageParser.Activity a = mActivities.mActivities.get(component); 2211 if (a == null) { 2212 return false; 2213 } 2214 for (int i=0; i<a.intents.size(); i++) { 2215 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2216 intent.getData(), intent.getCategories(), TAG) >= 0) { 2217 return true; 2218 } 2219 } 2220 return false; 2221 } 2222 } 2223 2224 @Override 2225 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2226 if (!sUserManager.exists(userId)) return null; 2227 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2228 synchronized (mPackages) { 2229 PackageParser.Activity a = mReceivers.mActivities.get(component); 2230 if (DEBUG_PACKAGE_INFO) Log.v( 2231 TAG, "getReceiverInfo " + component + ": " + a); 2232 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2233 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2234 if (ps == null) return null; 2235 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2236 userId); 2237 } 2238 } 2239 return null; 2240 } 2241 2242 @Override 2243 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2244 if (!sUserManager.exists(userId)) return null; 2245 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2246 synchronized (mPackages) { 2247 PackageParser.Service s = mServices.mServices.get(component); 2248 if (DEBUG_PACKAGE_INFO) Log.v( 2249 TAG, "getServiceInfo " + component + ": " + s); 2250 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2251 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2252 if (ps == null) return null; 2253 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2254 userId); 2255 } 2256 } 2257 return null; 2258 } 2259 2260 @Override 2261 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2262 if (!sUserManager.exists(userId)) return null; 2263 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2264 synchronized (mPackages) { 2265 PackageParser.Provider p = mProviders.mProviders.get(component); 2266 if (DEBUG_PACKAGE_INFO) Log.v( 2267 TAG, "getProviderInfo " + component + ": " + p); 2268 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2269 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2270 if (ps == null) return null; 2271 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2272 userId); 2273 } 2274 } 2275 return null; 2276 } 2277 2278 public String[] getSystemSharedLibraryNames() { 2279 Set<String> libSet; 2280 synchronized (mPackages) { 2281 libSet = mSharedLibraries.keySet(); 2282 int size = libSet.size(); 2283 if (size > 0) { 2284 String[] libs = new String[size]; 2285 libSet.toArray(libs); 2286 return libs; 2287 } 2288 } 2289 return null; 2290 } 2291 2292 public FeatureInfo[] getSystemAvailableFeatures() { 2293 Collection<FeatureInfo> featSet; 2294 synchronized (mPackages) { 2295 featSet = mAvailableFeatures.values(); 2296 int size = featSet.size(); 2297 if (size > 0) { 2298 FeatureInfo[] features = new FeatureInfo[size+1]; 2299 featSet.toArray(features); 2300 FeatureInfo fi = new FeatureInfo(); 2301 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2302 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2303 features[size] = fi; 2304 return features; 2305 } 2306 } 2307 return null; 2308 } 2309 2310 public boolean hasSystemFeature(String name) { 2311 synchronized (mPackages) { 2312 return mAvailableFeatures.containsKey(name); 2313 } 2314 } 2315 2316 private void checkValidCaller(int uid, int userId) { 2317 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2318 return; 2319 2320 throw new SecurityException("Caller uid=" + uid 2321 + " is not privileged to communicate with user=" + userId); 2322 } 2323 2324 public int checkPermission(String permName, String pkgName) { 2325 synchronized (mPackages) { 2326 PackageParser.Package p = mPackages.get(pkgName); 2327 if (p != null && p.mExtras != null) { 2328 PackageSetting ps = (PackageSetting)p.mExtras; 2329 if (ps.sharedUser != null) { 2330 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2331 return PackageManager.PERMISSION_GRANTED; 2332 } 2333 } else if (ps.grantedPermissions.contains(permName)) { 2334 return PackageManager.PERMISSION_GRANTED; 2335 } 2336 } 2337 } 2338 return PackageManager.PERMISSION_DENIED; 2339 } 2340 2341 public int checkUidPermission(String permName, int uid) { 2342 synchronized (mPackages) { 2343 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2344 if (obj != null) { 2345 GrantedPermissions gp = (GrantedPermissions)obj; 2346 if (gp.grantedPermissions.contains(permName)) { 2347 return PackageManager.PERMISSION_GRANTED; 2348 } 2349 } else { 2350 HashSet<String> perms = mSystemPermissions.get(uid); 2351 if (perms != null && perms.contains(permName)) { 2352 return PackageManager.PERMISSION_GRANTED; 2353 } 2354 } 2355 } 2356 return PackageManager.PERMISSION_DENIED; 2357 } 2358 2359 /** 2360 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2361 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2362 * @param message the message to log on security exception 2363 * @return 2364 */ 2365 private void enforceCrossUserPermission(int callingUid, int userId, 2366 boolean requireFullPermission, String message) { 2367 if (userId < 0) { 2368 throw new IllegalArgumentException("Invalid userId " + userId); 2369 } 2370 if (userId == UserHandle.getUserId(callingUid)) return; 2371 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2372 if (requireFullPermission) { 2373 mContext.enforceCallingOrSelfPermission( 2374 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2375 } else { 2376 try { 2377 mContext.enforceCallingOrSelfPermission( 2378 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2379 } catch (SecurityException se) { 2380 mContext.enforceCallingOrSelfPermission( 2381 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2382 } 2383 } 2384 } 2385 } 2386 2387 private BasePermission findPermissionTreeLP(String permName) { 2388 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2389 if (permName.startsWith(bp.name) && 2390 permName.length() > bp.name.length() && 2391 permName.charAt(bp.name.length()) == '.') { 2392 return bp; 2393 } 2394 } 2395 return null; 2396 } 2397 2398 private BasePermission checkPermissionTreeLP(String permName) { 2399 if (permName != null) { 2400 BasePermission bp = findPermissionTreeLP(permName); 2401 if (bp != null) { 2402 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2403 return bp; 2404 } 2405 throw new SecurityException("Calling uid " 2406 + Binder.getCallingUid() 2407 + " is not allowed to add to permission tree " 2408 + bp.name + " owned by uid " + bp.uid); 2409 } 2410 } 2411 throw new SecurityException("No permission tree found for " + permName); 2412 } 2413 2414 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2415 if (s1 == null) { 2416 return s2 == null; 2417 } 2418 if (s2 == null) { 2419 return false; 2420 } 2421 if (s1.getClass() != s2.getClass()) { 2422 return false; 2423 } 2424 return s1.equals(s2); 2425 } 2426 2427 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2428 if (pi1.icon != pi2.icon) return false; 2429 if (pi1.logo != pi2.logo) return false; 2430 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2431 if (!compareStrings(pi1.name, pi2.name)) return false; 2432 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2433 // We'll take care of setting this one. 2434 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2435 // These are not currently stored in settings. 2436 //if (!compareStrings(pi1.group, pi2.group)) return false; 2437 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2438 //if (pi1.labelRes != pi2.labelRes) return false; 2439 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2440 return true; 2441 } 2442 2443 int permissionInfoFootprint(PermissionInfo info) { 2444 int size = info.name.length(); 2445 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2446 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2447 return size; 2448 } 2449 2450 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2451 int size = 0; 2452 for (BasePermission perm : mSettings.mPermissions.values()) { 2453 if (perm.uid == tree.uid) { 2454 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2455 } 2456 } 2457 return size; 2458 } 2459 2460 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2461 // We calculate the max size of permissions defined by this uid and throw 2462 // if that plus the size of 'info' would exceed our stated maximum. 2463 if (tree.uid != Process.SYSTEM_UID) { 2464 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2465 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2466 throw new SecurityException("Permission tree size cap exceeded"); 2467 } 2468 } 2469 } 2470 2471 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2472 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2473 throw new SecurityException("Label must be specified in permission"); 2474 } 2475 BasePermission tree = checkPermissionTreeLP(info.name); 2476 BasePermission bp = mSettings.mPermissions.get(info.name); 2477 boolean added = bp == null; 2478 boolean changed = true; 2479 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2480 if (added) { 2481 enforcePermissionCapLocked(info, tree); 2482 bp = new BasePermission(info.name, tree.sourcePackage, 2483 BasePermission.TYPE_DYNAMIC); 2484 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2485 throw new SecurityException( 2486 "Not allowed to modify non-dynamic permission " 2487 + info.name); 2488 } else { 2489 if (bp.protectionLevel == fixedLevel 2490 && bp.perm.owner.equals(tree.perm.owner) 2491 && bp.uid == tree.uid 2492 && comparePermissionInfos(bp.perm.info, info)) { 2493 changed = false; 2494 } 2495 } 2496 bp.protectionLevel = fixedLevel; 2497 info = new PermissionInfo(info); 2498 info.protectionLevel = fixedLevel; 2499 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2500 bp.perm.info.packageName = tree.perm.info.packageName; 2501 bp.uid = tree.uid; 2502 if (added) { 2503 mSettings.mPermissions.put(info.name, bp); 2504 } 2505 if (changed) { 2506 if (!async) { 2507 mSettings.writeLPr(); 2508 } else { 2509 scheduleWriteSettingsLocked(); 2510 } 2511 } 2512 return added; 2513 } 2514 2515 public boolean addPermission(PermissionInfo info) { 2516 synchronized (mPackages) { 2517 return addPermissionLocked(info, false); 2518 } 2519 } 2520 2521 public boolean addPermissionAsync(PermissionInfo info) { 2522 synchronized (mPackages) { 2523 return addPermissionLocked(info, true); 2524 } 2525 } 2526 2527 public void removePermission(String name) { 2528 synchronized (mPackages) { 2529 checkPermissionTreeLP(name); 2530 BasePermission bp = mSettings.mPermissions.get(name); 2531 if (bp != null) { 2532 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2533 throw new SecurityException( 2534 "Not allowed to modify non-dynamic permission " 2535 + name); 2536 } 2537 mSettings.mPermissions.remove(name); 2538 mSettings.writeLPr(); 2539 } 2540 } 2541 } 2542 2543 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2544 int index = pkg.requestedPermissions.indexOf(bp.name); 2545 if (index == -1) { 2546 throw new SecurityException("Package " + pkg.packageName 2547 + " has not requested permission " + bp.name); 2548 } 2549 boolean isNormal = 2550 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2551 == PermissionInfo.PROTECTION_NORMAL); 2552 boolean isDangerous = 2553 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2554 == PermissionInfo.PROTECTION_DANGEROUS); 2555 boolean isDevelopment = 2556 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2557 2558 if (!isNormal && !isDangerous && !isDevelopment) { 2559 throw new SecurityException("Permission " + bp.name 2560 + " is not a changeable permission type"); 2561 } 2562 2563 if (isNormal || isDangerous) { 2564 if (pkg.requestedPermissionsRequired.get(index)) { 2565 throw new SecurityException("Can't change " + bp.name 2566 + ". It is required by the application"); 2567 } 2568 } 2569 } 2570 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 public void revokePermission(String packageName, String permissionName) { 2601 int changedAppId = -1; 2602 2603 synchronized (mPackages) { 2604 final PackageParser.Package pkg = mPackages.get(packageName); 2605 if (pkg == null) { 2606 throw new IllegalArgumentException("Unknown package: " + packageName); 2607 } 2608 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2609 mContext.enforceCallingOrSelfPermission( 2610 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2611 } 2612 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2613 if (bp == null) { 2614 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2615 } 2616 2617 checkGrantRevokePermissions(pkg, bp); 2618 2619 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2620 if (ps == null) { 2621 return; 2622 } 2623 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2624 if (gp.grantedPermissions.remove(permissionName)) { 2625 gp.grantedPermissions.remove(permissionName); 2626 if (ps.haveGids) { 2627 gp.gids = removeInts(gp.gids, bp.gids); 2628 } 2629 mSettings.writeLPr(); 2630 changedAppId = ps.appId; 2631 } 2632 } 2633 2634 if (changedAppId >= 0) { 2635 // We changed the perm on someone, kill its processes. 2636 IActivityManager am = ActivityManagerNative.getDefault(); 2637 if (am != null) { 2638 final int callingUserId = UserHandle.getCallingUserId(); 2639 final long ident = Binder.clearCallingIdentity(); 2640 try { 2641 //XXX we should only revoke for the calling user's app permissions, 2642 // but for now we impact all users. 2643 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2644 // "revoke " + permissionName); 2645 int[] users = sUserManager.getUserIds(); 2646 for (int user : users) { 2647 am.killUid(UserHandle.getUid(user, changedAppId), 2648 "revoke " + permissionName); 2649 } 2650 } catch (RemoteException e) { 2651 } finally { 2652 Binder.restoreCallingIdentity(ident); 2653 } 2654 } 2655 } 2656 } 2657 2658 public boolean isProtectedBroadcast(String actionName) { 2659 synchronized (mPackages) { 2660 return mProtectedBroadcasts.contains(actionName); 2661 } 2662 } 2663 2664 public int checkSignatures(String pkg1, String pkg2) { 2665 synchronized (mPackages) { 2666 final PackageParser.Package p1 = mPackages.get(pkg1); 2667 final PackageParser.Package p2 = mPackages.get(pkg2); 2668 if (p1 == null || p1.mExtras == null 2669 || p2 == null || p2.mExtras == null) { 2670 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2671 } 2672 return compareSignatures(p1.mSignatures, p2.mSignatures); 2673 } 2674 } 2675 2676 public int checkUidSignatures(int uid1, int uid2) { 2677 // Map to base uids. 2678 uid1 = UserHandle.getAppId(uid1); 2679 uid2 = UserHandle.getAppId(uid2); 2680 // reader 2681 synchronized (mPackages) { 2682 Signature[] s1; 2683 Signature[] s2; 2684 Object obj = mSettings.getUserIdLPr(uid1); 2685 if (obj != null) { 2686 if (obj instanceof SharedUserSetting) { 2687 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2688 } else if (obj instanceof PackageSetting) { 2689 s1 = ((PackageSetting)obj).signatures.mSignatures; 2690 } else { 2691 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2692 } 2693 } else { 2694 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2695 } 2696 obj = mSettings.getUserIdLPr(uid2); 2697 if (obj != null) { 2698 if (obj instanceof SharedUserSetting) { 2699 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2700 } else if (obj instanceof PackageSetting) { 2701 s2 = ((PackageSetting)obj).signatures.mSignatures; 2702 } else { 2703 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2704 } 2705 } else { 2706 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2707 } 2708 return compareSignatures(s1, s2); 2709 } 2710 } 2711 2712 /** 2713 * Compares two sets of signatures. Returns: 2714 * <br /> 2715 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2716 * <br /> 2717 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2718 * <br /> 2719 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2720 * <br /> 2721 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2722 * <br /> 2723 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2724 */ 2725 static int compareSignatures(Signature[] s1, Signature[] s2) { 2726 if (s1 == null) { 2727 return s2 == null 2728 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2729 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2730 } 2731 2732 if (s2 == null) { 2733 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2734 } 2735 2736 if (s1.length != s2.length) { 2737 return PackageManager.SIGNATURE_NO_MATCH; 2738 } 2739 2740 // Since both signature sets are of size 1, we can compare without HashSets. 2741 if (s1.length == 1) { 2742 return s1[0].equals(s2[0]) ? 2743 PackageManager.SIGNATURE_MATCH : 2744 PackageManager.SIGNATURE_NO_MATCH; 2745 } 2746 2747 HashSet<Signature> set1 = new HashSet<Signature>(); 2748 for (Signature sig : s1) { 2749 set1.add(sig); 2750 } 2751 HashSet<Signature> set2 = new HashSet<Signature>(); 2752 for (Signature sig : s2) { 2753 set2.add(sig); 2754 } 2755 // Make sure s2 contains all signatures in s1. 2756 if (set1.equals(set2)) { 2757 return PackageManager.SIGNATURE_MATCH; 2758 } 2759 return PackageManager.SIGNATURE_NO_MATCH; 2760 } 2761 2762 /** 2763 * If the database version for this type of package (internal storage or 2764 * external storage) is less than the version where package signatures 2765 * were updated, return true. 2766 */ 2767 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2768 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2769 DatabaseVersion.SIGNATURE_END_ENTITY)) 2770 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2771 DatabaseVersion.SIGNATURE_END_ENTITY)); 2772 } 2773 2774 /** 2775 * Used for backward compatibility to make sure any packages with 2776 * certificate chains get upgraded to the new style. {@code existingSigs} 2777 * will be in the old format (since they were stored on disk from before the 2778 * system upgrade) and {@code scannedSigs} will be in the newer format. 2779 */ 2780 private int compareSignaturesCompat(PackageSignatures existingSigs, 2781 PackageParser.Package scannedPkg) { 2782 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2783 return PackageManager.SIGNATURE_NO_MATCH; 2784 } 2785 2786 HashSet<Signature> existingSet = new HashSet<Signature>(); 2787 for (Signature sig : existingSigs.mSignatures) { 2788 existingSet.add(sig); 2789 } 2790 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2791 for (Signature sig : scannedPkg.mSignatures) { 2792 try { 2793 Signature[] chainSignatures = sig.getChainSignatures(); 2794 for (Signature chainSig : chainSignatures) { 2795 scannedCompatSet.add(chainSig); 2796 } 2797 } catch (CertificateEncodingException e) { 2798 scannedCompatSet.add(sig); 2799 } 2800 } 2801 /* 2802 * Make sure the expanded scanned set contains all signatures in the 2803 * existing one. 2804 */ 2805 if (scannedCompatSet.equals(existingSet)) { 2806 // Migrate the old signatures to the new scheme. 2807 existingSigs.assignSignatures(scannedPkg.mSignatures); 2808 // The new KeySets will be re-added later in the scanning process. 2809 mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName); 2810 return PackageManager.SIGNATURE_MATCH; 2811 } 2812 return PackageManager.SIGNATURE_NO_MATCH; 2813 } 2814 2815 public String[] getPackagesForUid(int uid) { 2816 uid = UserHandle.getAppId(uid); 2817 // reader 2818 synchronized (mPackages) { 2819 Object obj = mSettings.getUserIdLPr(uid); 2820 if (obj instanceof SharedUserSetting) { 2821 final SharedUserSetting sus = (SharedUserSetting) obj; 2822 final int N = sus.packages.size(); 2823 final String[] res = new String[N]; 2824 final Iterator<PackageSetting> it = sus.packages.iterator(); 2825 int i = 0; 2826 while (it.hasNext()) { 2827 res[i++] = it.next().name; 2828 } 2829 return res; 2830 } else if (obj instanceof PackageSetting) { 2831 final PackageSetting ps = (PackageSetting) obj; 2832 return new String[] { ps.name }; 2833 } 2834 } 2835 return null; 2836 } 2837 2838 public String getNameForUid(int uid) { 2839 // reader 2840 synchronized (mPackages) { 2841 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2842 if (obj instanceof SharedUserSetting) { 2843 final SharedUserSetting sus = (SharedUserSetting) obj; 2844 return sus.name + ":" + sus.userId; 2845 } else if (obj instanceof PackageSetting) { 2846 final PackageSetting ps = (PackageSetting) obj; 2847 return ps.name; 2848 } 2849 } 2850 return null; 2851 } 2852 2853 public int getUidForSharedUser(String sharedUserName) { 2854 if(sharedUserName == null) { 2855 return -1; 2856 } 2857 // reader 2858 synchronized (mPackages) { 2859 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2860 if (suid == null) { 2861 return -1; 2862 } 2863 return suid.userId; 2864 } 2865 } 2866 2867 public int getFlagsForUid(int uid) { 2868 synchronized (mPackages) { 2869 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2870 if (obj instanceof SharedUserSetting) { 2871 final SharedUserSetting sus = (SharedUserSetting) obj; 2872 return sus.pkgFlags; 2873 } else if (obj instanceof PackageSetting) { 2874 final PackageSetting ps = (PackageSetting) obj; 2875 return ps.pkgFlags; 2876 } 2877 } 2878 return 0; 2879 } 2880 2881 @Override 2882 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2883 int flags, int userId) { 2884 if (!sUserManager.exists(userId)) return null; 2885 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2886 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2887 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2888 } 2889 2890 @Override 2891 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2892 IntentFilter filter, int match, ComponentName activity) { 2893 final int userId = UserHandle.getCallingUserId(); 2894 if (DEBUG_PREFERRED) { 2895 Log.v(TAG, "setLastChosenActivity intent=" + intent 2896 + " resolvedType=" + resolvedType 2897 + " flags=" + flags 2898 + " filter=" + filter 2899 + " match=" + match 2900 + " activity=" + activity); 2901 filter.dump(new PrintStreamPrinter(System.out), " "); 2902 } 2903 intent.setComponent(null); 2904 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2905 // Find any earlier preferred or last chosen entries and nuke them 2906 findPreferredActivity(intent, resolvedType, 2907 flags, query, 0, false, true, false, userId); 2908 // Add the new activity as the last chosen for this filter 2909 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2910 } 2911 2912 @Override 2913 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2914 final int userId = UserHandle.getCallingUserId(); 2915 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2916 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2917 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2918 false, false, false, userId); 2919 } 2920 2921 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2922 int flags, List<ResolveInfo> query, int userId) { 2923 if (query != null) { 2924 final int N = query.size(); 2925 if (N == 1) { 2926 return query.get(0); 2927 } else if (N > 1) { 2928 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2929 // If there is more than one activity with the same priority, 2930 // then let the user decide between them. 2931 ResolveInfo r0 = query.get(0); 2932 ResolveInfo r1 = query.get(1); 2933 if (DEBUG_INTENT_MATCHING || debug) { 2934 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2935 + r1.activityInfo.name + "=" + r1.priority); 2936 } 2937 // If the first activity has a higher priority, or a different 2938 // default, then it is always desireable to pick it. 2939 if (r0.priority != r1.priority 2940 || r0.preferredOrder != r1.preferredOrder 2941 || r0.isDefault != r1.isDefault) { 2942 return query.get(0); 2943 } 2944 // If we have saved a preference for a preferred activity for 2945 // this Intent, use that. 2946 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2947 flags, query, r0.priority, true, false, debug, userId); 2948 if (ri != null) { 2949 return ri; 2950 } 2951 if (userId != 0) { 2952 ri = new ResolveInfo(mResolveInfo); 2953 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2954 ri.activityInfo.applicationInfo = new ApplicationInfo( 2955 ri.activityInfo.applicationInfo); 2956 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2957 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2958 return ri; 2959 } 2960 return mResolveInfo; 2961 } 2962 } 2963 return null; 2964 } 2965 2966 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2967 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2968 final int N = query.size(); 2969 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2970 .get(userId); 2971 // Get the list of persistent preferred activities that handle the intent 2972 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2973 List<PersistentPreferredActivity> pprefs = ppir != null 2974 ? ppir.queryIntent(intent, resolvedType, 2975 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2976 : null; 2977 if (pprefs != null && pprefs.size() > 0) { 2978 final int M = pprefs.size(); 2979 for (int i=0; i<M; i++) { 2980 final PersistentPreferredActivity ppa = pprefs.get(i); 2981 if (DEBUG_PREFERRED || debug) { 2982 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2983 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2984 + "\n component=" + ppa.mComponent); 2985 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2986 } 2987 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2988 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2989 if (DEBUG_PREFERRED || debug) { 2990 Slog.v(TAG, "Found persistent preferred activity:"); 2991 if (ai != null) { 2992 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2993 } else { 2994 Slog.v(TAG, " null"); 2995 } 2996 } 2997 if (ai == null) { 2998 // This previously registered persistent preferred activity 2999 // component is no longer known. Ignore it and do NOT remove it. 3000 continue; 3001 } 3002 for (int j=0; j<N; j++) { 3003 final ResolveInfo ri = query.get(j); 3004 if (!ri.activityInfo.applicationInfo.packageName 3005 .equals(ai.applicationInfo.packageName)) { 3006 continue; 3007 } 3008 if (!ri.activityInfo.name.equals(ai.name)) { 3009 continue; 3010 } 3011 // Found a persistent preference that can handle the intent. 3012 if (DEBUG_PREFERRED || debug) { 3013 Slog.v(TAG, "Returning persistent preferred activity: " + 3014 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3015 } 3016 return ri; 3017 } 3018 } 3019 } 3020 return null; 3021 } 3022 3023 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3024 List<ResolveInfo> query, int priority, boolean always, 3025 boolean removeMatches, boolean debug, int userId) { 3026 if (!sUserManager.exists(userId)) return null; 3027 // writer 3028 synchronized (mPackages) { 3029 if (intent.getSelector() != null) { 3030 intent = intent.getSelector(); 3031 } 3032 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3033 3034 // Try to find a matching persistent preferred activity. 3035 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3036 debug, userId); 3037 3038 // If a persistent preferred activity matched, use it. 3039 if (pri != null) { 3040 return pri; 3041 } 3042 3043 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3044 // Get the list of preferred activities that handle the intent 3045 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3046 List<PreferredActivity> prefs = pir != null 3047 ? pir.queryIntent(intent, resolvedType, 3048 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3049 : null; 3050 if (prefs != null && prefs.size() > 0) { 3051 // First figure out how good the original match set is. 3052 // We will only allow preferred activities that came 3053 // from the same match quality. 3054 int match = 0; 3055 3056 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3057 3058 final int N = query.size(); 3059 for (int j=0; j<N; j++) { 3060 final ResolveInfo ri = query.get(j); 3061 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3062 + ": 0x" + Integer.toHexString(match)); 3063 if (ri.match > match) { 3064 match = ri.match; 3065 } 3066 } 3067 3068 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3069 + Integer.toHexString(match)); 3070 3071 match &= IntentFilter.MATCH_CATEGORY_MASK; 3072 final int M = prefs.size(); 3073 for (int i=0; i<M; i++) { 3074 final PreferredActivity pa = prefs.get(i); 3075 if (DEBUG_PREFERRED || debug) { 3076 Slog.v(TAG, "Checking PreferredActivity ds=" 3077 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3078 + "\n component=" + pa.mPref.mComponent); 3079 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3080 } 3081 if (pa.mPref.mMatch != match) { 3082 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3083 + Integer.toHexString(pa.mPref.mMatch)); 3084 continue; 3085 } 3086 // If it's not an "always" type preferred activity and that's what we're 3087 // looking for, skip it. 3088 if (always && !pa.mPref.mAlways) { 3089 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3090 continue; 3091 } 3092 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3093 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3094 if (DEBUG_PREFERRED || debug) { 3095 Slog.v(TAG, "Found preferred activity:"); 3096 if (ai != null) { 3097 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3098 } else { 3099 Slog.v(TAG, " null"); 3100 } 3101 } 3102 if (ai == null) { 3103 // This previously registered preferred activity 3104 // component is no longer known. Most likely an update 3105 // to the app was installed and in the new version this 3106 // component no longer exists. Clean it up by removing 3107 // it from the preferred activities list, and skip it. 3108 Slog.w(TAG, "Removing dangling preferred activity: " 3109 + pa.mPref.mComponent); 3110 pir.removeFilter(pa); 3111 continue; 3112 } 3113 for (int j=0; j<N; j++) { 3114 final ResolveInfo ri = query.get(j); 3115 if (!ri.activityInfo.applicationInfo.packageName 3116 .equals(ai.applicationInfo.packageName)) { 3117 continue; 3118 } 3119 if (!ri.activityInfo.name.equals(ai.name)) { 3120 continue; 3121 } 3122 3123 if (removeMatches) { 3124 pir.removeFilter(pa); 3125 if (DEBUG_PREFERRED) { 3126 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3127 } 3128 break; 3129 } 3130 3131 // Okay we found a previously set preferred or last chosen app. 3132 // If the result set is different from when this 3133 // was created, we need to clear it and re-ask the 3134 // user their preference, if we're looking for an "always" type entry. 3135 if (always && !pa.mPref.sameSet(query, priority)) { 3136 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3137 + intent + " type " + resolvedType); 3138 if (DEBUG_PREFERRED) { 3139 Slog.v(TAG, "Removing preferred activity since set changed " 3140 + pa.mPref.mComponent); 3141 } 3142 pir.removeFilter(pa); 3143 // Re-add the filter as a "last chosen" entry (!always) 3144 PreferredActivity lastChosen = new PreferredActivity( 3145 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3146 pir.addFilter(lastChosen); 3147 mSettings.writePackageRestrictionsLPr(userId); 3148 return null; 3149 } 3150 3151 // Yay! Either the set matched or we're looking for the last chosen 3152 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3153 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3154 mSettings.writePackageRestrictionsLPr(userId); 3155 return ri; 3156 } 3157 } 3158 } 3159 mSettings.writePackageRestrictionsLPr(userId); 3160 } 3161 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3162 return null; 3163 } 3164 3165 @Override 3166 public List<ResolveInfo> queryIntentActivities(Intent intent, 3167 String resolvedType, int flags, int userId) { 3168 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3169 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3170 ComponentName comp = intent.getComponent(); 3171 if (comp == null) { 3172 if (intent.getSelector() != null) { 3173 intent = intent.getSelector(); 3174 comp = intent.getComponent(); 3175 } 3176 } 3177 3178 if (comp != null) { 3179 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3180 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3181 if (ai != null) { 3182 final ResolveInfo ri = new ResolveInfo(); 3183 ri.activityInfo = ai; 3184 list.add(ri); 3185 } 3186 return list; 3187 } 3188 3189 // reader 3190 synchronized (mPackages) { 3191 final String pkgName = intent.getPackage(); 3192 if (pkgName == null) { 3193 return mActivities.queryIntent(intent, resolvedType, flags, userId); 3194 } 3195 final PackageParser.Package pkg = mPackages.get(pkgName); 3196 if (pkg != null) { 3197 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3198 pkg.activities, userId); 3199 } 3200 return new ArrayList<ResolveInfo>(); 3201 } 3202 } 3203 3204 @Override 3205 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3206 Intent[] specifics, String[] specificTypes, Intent intent, 3207 String resolvedType, int flags, int userId) { 3208 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3209 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3210 "query intent activity options"); 3211 final String resultsAction = intent.getAction(); 3212 3213 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3214 | PackageManager.GET_RESOLVED_FILTER, userId); 3215 3216 if (DEBUG_INTENT_MATCHING) { 3217 Log.v(TAG, "Query " + intent + ": " + results); 3218 } 3219 3220 int specificsPos = 0; 3221 int N; 3222 3223 // todo: note that the algorithm used here is O(N^2). This 3224 // isn't a problem in our current environment, but if we start running 3225 // into situations where we have more than 5 or 10 matches then this 3226 // should probably be changed to something smarter... 3227 3228 // First we go through and resolve each of the specific items 3229 // that were supplied, taking care of removing any corresponding 3230 // duplicate items in the generic resolve list. 3231 if (specifics != null) { 3232 for (int i=0; i<specifics.length; i++) { 3233 final Intent sintent = specifics[i]; 3234 if (sintent == null) { 3235 continue; 3236 } 3237 3238 if (DEBUG_INTENT_MATCHING) { 3239 Log.v(TAG, "Specific #" + i + ": " + sintent); 3240 } 3241 3242 String action = sintent.getAction(); 3243 if (resultsAction != null && resultsAction.equals(action)) { 3244 // If this action was explicitly requested, then don't 3245 // remove things that have it. 3246 action = null; 3247 } 3248 3249 ResolveInfo ri = null; 3250 ActivityInfo ai = null; 3251 3252 ComponentName comp = sintent.getComponent(); 3253 if (comp == null) { 3254 ri = resolveIntent( 3255 sintent, 3256 specificTypes != null ? specificTypes[i] : null, 3257 flags, userId); 3258 if (ri == null) { 3259 continue; 3260 } 3261 if (ri == mResolveInfo) { 3262 // ACK! Must do something better with this. 3263 } 3264 ai = ri.activityInfo; 3265 comp = new ComponentName(ai.applicationInfo.packageName, 3266 ai.name); 3267 } else { 3268 ai = getActivityInfo(comp, flags, userId); 3269 if (ai == null) { 3270 continue; 3271 } 3272 } 3273 3274 // Look for any generic query activities that are duplicates 3275 // of this specific one, and remove them from the results. 3276 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3277 N = results.size(); 3278 int j; 3279 for (j=specificsPos; j<N; j++) { 3280 ResolveInfo sri = results.get(j); 3281 if ((sri.activityInfo.name.equals(comp.getClassName()) 3282 && sri.activityInfo.applicationInfo.packageName.equals( 3283 comp.getPackageName())) 3284 || (action != null && sri.filter.matchAction(action))) { 3285 results.remove(j); 3286 if (DEBUG_INTENT_MATCHING) Log.v( 3287 TAG, "Removing duplicate item from " + j 3288 + " due to specific " + specificsPos); 3289 if (ri == null) { 3290 ri = sri; 3291 } 3292 j--; 3293 N--; 3294 } 3295 } 3296 3297 // Add this specific item to its proper place. 3298 if (ri == null) { 3299 ri = new ResolveInfo(); 3300 ri.activityInfo = ai; 3301 } 3302 results.add(specificsPos, ri); 3303 ri.specificIndex = i; 3304 specificsPos++; 3305 } 3306 } 3307 3308 // Now we go through the remaining generic results and remove any 3309 // duplicate actions that are found here. 3310 N = results.size(); 3311 for (int i=specificsPos; i<N-1; i++) { 3312 final ResolveInfo rii = results.get(i); 3313 if (rii.filter == null) { 3314 continue; 3315 } 3316 3317 // Iterate over all of the actions of this result's intent 3318 // filter... typically this should be just one. 3319 final Iterator<String> it = rii.filter.actionsIterator(); 3320 if (it == null) { 3321 continue; 3322 } 3323 while (it.hasNext()) { 3324 final String action = it.next(); 3325 if (resultsAction != null && resultsAction.equals(action)) { 3326 // If this action was explicitly requested, then don't 3327 // remove things that have it. 3328 continue; 3329 } 3330 for (int j=i+1; j<N; j++) { 3331 final ResolveInfo rij = results.get(j); 3332 if (rij.filter != null && rij.filter.hasAction(action)) { 3333 results.remove(j); 3334 if (DEBUG_INTENT_MATCHING) Log.v( 3335 TAG, "Removing duplicate item from " + j 3336 + " due to action " + action + " at " + i); 3337 j--; 3338 N--; 3339 } 3340 } 3341 } 3342 3343 // If the caller didn't request filter information, drop it now 3344 // so we don't have to marshall/unmarshall it. 3345 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3346 rii.filter = null; 3347 } 3348 } 3349 3350 // Filter out the caller activity if so requested. 3351 if (caller != null) { 3352 N = results.size(); 3353 for (int i=0; i<N; i++) { 3354 ActivityInfo ainfo = results.get(i).activityInfo; 3355 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3356 && caller.getClassName().equals(ainfo.name)) { 3357 results.remove(i); 3358 break; 3359 } 3360 } 3361 } 3362 3363 // If the caller didn't request filter information, 3364 // drop them now so we don't have to 3365 // marshall/unmarshall it. 3366 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3367 N = results.size(); 3368 for (int i=0; i<N; i++) { 3369 results.get(i).filter = null; 3370 } 3371 } 3372 3373 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3374 return results; 3375 } 3376 3377 @Override 3378 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3379 int userId) { 3380 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3381 ComponentName comp = intent.getComponent(); 3382 if (comp == null) { 3383 if (intent.getSelector() != null) { 3384 intent = intent.getSelector(); 3385 comp = intent.getComponent(); 3386 } 3387 } 3388 if (comp != null) { 3389 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3390 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3391 if (ai != null) { 3392 ResolveInfo ri = new ResolveInfo(); 3393 ri.activityInfo = ai; 3394 list.add(ri); 3395 } 3396 return list; 3397 } 3398 3399 // reader 3400 synchronized (mPackages) { 3401 String pkgName = intent.getPackage(); 3402 if (pkgName == null) { 3403 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3404 } 3405 final PackageParser.Package pkg = mPackages.get(pkgName); 3406 if (pkg != null) { 3407 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3408 userId); 3409 } 3410 return null; 3411 } 3412 } 3413 3414 @Override 3415 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3416 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3417 if (!sUserManager.exists(userId)) return null; 3418 if (query != null) { 3419 if (query.size() >= 1) { 3420 // If there is more than one service with the same priority, 3421 // just arbitrarily pick the first one. 3422 return query.get(0); 3423 } 3424 } 3425 return null; 3426 } 3427 3428 @Override 3429 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3430 int userId) { 3431 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3432 ComponentName comp = intent.getComponent(); 3433 if (comp == null) { 3434 if (intent.getSelector() != null) { 3435 intent = intent.getSelector(); 3436 comp = intent.getComponent(); 3437 } 3438 } 3439 if (comp != null) { 3440 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3441 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3442 if (si != null) { 3443 final ResolveInfo ri = new ResolveInfo(); 3444 ri.serviceInfo = si; 3445 list.add(ri); 3446 } 3447 return list; 3448 } 3449 3450 // reader 3451 synchronized (mPackages) { 3452 String pkgName = intent.getPackage(); 3453 if (pkgName == null) { 3454 return mServices.queryIntent(intent, resolvedType, flags, userId); 3455 } 3456 final PackageParser.Package pkg = mPackages.get(pkgName); 3457 if (pkg != null) { 3458 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3459 userId); 3460 } 3461 return null; 3462 } 3463 } 3464 3465 @Override 3466 public List<ResolveInfo> queryIntentContentProviders( 3467 Intent intent, String resolvedType, int flags, int userId) { 3468 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3469 ComponentName comp = intent.getComponent(); 3470 if (comp == null) { 3471 if (intent.getSelector() != null) { 3472 intent = intent.getSelector(); 3473 comp = intent.getComponent(); 3474 } 3475 } 3476 if (comp != null) { 3477 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3478 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3479 if (pi != null) { 3480 final ResolveInfo ri = new ResolveInfo(); 3481 ri.providerInfo = pi; 3482 list.add(ri); 3483 } 3484 return list; 3485 } 3486 3487 // reader 3488 synchronized (mPackages) { 3489 String pkgName = intent.getPackage(); 3490 if (pkgName == null) { 3491 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3492 } 3493 final PackageParser.Package pkg = mPackages.get(pkgName); 3494 if (pkg != null) { 3495 return mProviders.queryIntentForPackage( 3496 intent, resolvedType, flags, pkg.providers, userId); 3497 } 3498 return null; 3499 } 3500 } 3501 3502 @Override 3503 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3504 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3505 3506 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3507 3508 // writer 3509 synchronized (mPackages) { 3510 ArrayList<PackageInfo> list; 3511 if (listUninstalled) { 3512 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3513 for (PackageSetting ps : mSettings.mPackages.values()) { 3514 PackageInfo pi; 3515 if (ps.pkg != null) { 3516 pi = generatePackageInfo(ps.pkg, flags, userId); 3517 } else { 3518 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3519 } 3520 if (pi != null) { 3521 list.add(pi); 3522 } 3523 } 3524 } else { 3525 list = new ArrayList<PackageInfo>(mPackages.size()); 3526 for (PackageParser.Package p : mPackages.values()) { 3527 PackageInfo pi = generatePackageInfo(p, flags, userId); 3528 if (pi != null) { 3529 list.add(pi); 3530 } 3531 } 3532 } 3533 3534 return new ParceledListSlice<PackageInfo>(list); 3535 } 3536 } 3537 3538 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3539 String[] permissions, boolean[] tmp, int flags, int userId) { 3540 int numMatch = 0; 3541 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3542 for (int i=0; i<permissions.length; i++) { 3543 if (gp.grantedPermissions.contains(permissions[i])) { 3544 tmp[i] = true; 3545 numMatch++; 3546 } else { 3547 tmp[i] = false; 3548 } 3549 } 3550 if (numMatch == 0) { 3551 return; 3552 } 3553 PackageInfo pi; 3554 if (ps.pkg != null) { 3555 pi = generatePackageInfo(ps.pkg, flags, userId); 3556 } else { 3557 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3558 } 3559 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3560 if (numMatch == permissions.length) { 3561 pi.requestedPermissions = permissions; 3562 } else { 3563 pi.requestedPermissions = new String[numMatch]; 3564 numMatch = 0; 3565 for (int i=0; i<permissions.length; i++) { 3566 if (tmp[i]) { 3567 pi.requestedPermissions[numMatch] = permissions[i]; 3568 numMatch++; 3569 } 3570 } 3571 } 3572 } 3573 list.add(pi); 3574 } 3575 3576 @Override 3577 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3578 String[] permissions, int flags, int userId) { 3579 if (!sUserManager.exists(userId)) return null; 3580 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3581 3582 // writer 3583 synchronized (mPackages) { 3584 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3585 boolean[] tmpBools = new boolean[permissions.length]; 3586 if (listUninstalled) { 3587 for (PackageSetting ps : mSettings.mPackages.values()) { 3588 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3589 } 3590 } else { 3591 for (PackageParser.Package pkg : mPackages.values()) { 3592 PackageSetting ps = (PackageSetting)pkg.mExtras; 3593 if (ps != null) { 3594 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3595 userId); 3596 } 3597 } 3598 } 3599 3600 return new ParceledListSlice<PackageInfo>(list); 3601 } 3602 } 3603 3604 @Override 3605 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3606 if (!sUserManager.exists(userId)) return null; 3607 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3608 3609 // writer 3610 synchronized (mPackages) { 3611 ArrayList<ApplicationInfo> list; 3612 if (listUninstalled) { 3613 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3614 for (PackageSetting ps : mSettings.mPackages.values()) { 3615 ApplicationInfo ai; 3616 if (ps.pkg != null) { 3617 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3618 ps.readUserState(userId), userId); 3619 } else { 3620 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3621 } 3622 if (ai != null) { 3623 list.add(ai); 3624 } 3625 } 3626 } else { 3627 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3628 for (PackageParser.Package p : mPackages.values()) { 3629 if (p.mExtras != null) { 3630 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3631 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3632 if (ai != null) { 3633 list.add(ai); 3634 } 3635 } 3636 } 3637 } 3638 3639 return new ParceledListSlice<ApplicationInfo>(list); 3640 } 3641 } 3642 3643 public List<ApplicationInfo> getPersistentApplications(int flags) { 3644 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3645 3646 // reader 3647 synchronized (mPackages) { 3648 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3649 final int userId = UserHandle.getCallingUserId(); 3650 while (i.hasNext()) { 3651 final PackageParser.Package p = i.next(); 3652 if (p.applicationInfo != null 3653 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3654 && (!mSafeMode || isSystemApp(p))) { 3655 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3656 if (ps != null) { 3657 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3658 ps.readUserState(userId), userId); 3659 if (ai != null) { 3660 finalList.add(ai); 3661 } 3662 } 3663 } 3664 } 3665 } 3666 3667 return finalList; 3668 } 3669 3670 @Override 3671 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3672 if (!sUserManager.exists(userId)) return null; 3673 // reader 3674 synchronized (mPackages) { 3675 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3676 PackageSetting ps = provider != null 3677 ? mSettings.mPackages.get(provider.owner.packageName) 3678 : null; 3679 return ps != null 3680 && mSettings.isEnabledLPr(provider.info, flags, userId) 3681 && (!mSafeMode || (provider.info.applicationInfo.flags 3682 &ApplicationInfo.FLAG_SYSTEM) != 0) 3683 ? PackageParser.generateProviderInfo(provider, flags, 3684 ps.readUserState(userId), userId) 3685 : null; 3686 } 3687 } 3688 3689 /** 3690 * @deprecated 3691 */ 3692 @Deprecated 3693 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3694 // reader 3695 synchronized (mPackages) { 3696 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3697 .entrySet().iterator(); 3698 final int userId = UserHandle.getCallingUserId(); 3699 while (i.hasNext()) { 3700 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3701 PackageParser.Provider p = entry.getValue(); 3702 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3703 3704 if (ps != null && p.syncable 3705 && (!mSafeMode || (p.info.applicationInfo.flags 3706 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3707 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3708 ps.readUserState(userId), userId); 3709 if (info != null) { 3710 outNames.add(entry.getKey()); 3711 outInfo.add(info); 3712 } 3713 } 3714 } 3715 } 3716 } 3717 3718 public List<ProviderInfo> queryContentProviders(String processName, 3719 int uid, int flags) { 3720 ArrayList<ProviderInfo> finalList = null; 3721 // reader 3722 synchronized (mPackages) { 3723 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3724 final int userId = processName != null ? 3725 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3726 while (i.hasNext()) { 3727 final PackageParser.Provider p = i.next(); 3728 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3729 if (ps != null && p.info.authority != null 3730 && (processName == null 3731 || (p.info.processName.equals(processName) 3732 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3733 && mSettings.isEnabledLPr(p.info, flags, userId) 3734 && (!mSafeMode 3735 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3736 if (finalList == null) { 3737 finalList = new ArrayList<ProviderInfo>(3); 3738 } 3739 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3740 ps.readUserState(userId), userId); 3741 if (info != null) { 3742 finalList.add(info); 3743 } 3744 } 3745 } 3746 } 3747 3748 if (finalList != null) { 3749 Collections.sort(finalList, mProviderInitOrderSorter); 3750 } 3751 3752 return finalList; 3753 } 3754 3755 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3756 int flags) { 3757 // reader 3758 synchronized (mPackages) { 3759 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3760 return PackageParser.generateInstrumentationInfo(i, flags); 3761 } 3762 } 3763 3764 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3765 int flags) { 3766 ArrayList<InstrumentationInfo> finalList = 3767 new ArrayList<InstrumentationInfo>(); 3768 3769 // reader 3770 synchronized (mPackages) { 3771 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3772 while (i.hasNext()) { 3773 final PackageParser.Instrumentation p = i.next(); 3774 if (targetPackage == null 3775 || targetPackage.equals(p.info.targetPackage)) { 3776 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3777 flags); 3778 if (ii != null) { 3779 finalList.add(ii); 3780 } 3781 } 3782 } 3783 } 3784 3785 return finalList; 3786 } 3787 3788 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 3789 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 3790 if (overlays == null) { 3791 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 3792 return; 3793 } 3794 for (PackageParser.Package opkg : overlays.values()) { 3795 // Not much to do if idmap fails: we already logged the error 3796 // and we certainly don't want to abort installation of pkg simply 3797 // because an overlay didn't fit properly. For these reasons, 3798 // ignore the return value of createIdmapForPackagePairLI. 3799 createIdmapForPackagePairLI(pkg, opkg); 3800 } 3801 } 3802 3803 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 3804 PackageParser.Package opkg) { 3805 if (!opkg.mTrustedOverlay) { 3806 Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " + 3807 opkg.mScanPath + ": overlay not trusted"); 3808 return false; 3809 } 3810 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 3811 if (overlaySet == null) { 3812 Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " + 3813 opkg.mScanPath + " but target package has no known overlays"); 3814 return false; 3815 } 3816 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 3817 if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) { 3818 Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath); 3819 return false; 3820 } 3821 PackageParser.Package[] overlayArray = 3822 overlaySet.values().toArray(new PackageParser.Package[0]); 3823 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 3824 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 3825 return p1.mOverlayPriority - p2.mOverlayPriority; 3826 } 3827 }; 3828 Arrays.sort(overlayArray, cmp); 3829 3830 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 3831 int i = 0; 3832 for (PackageParser.Package p : overlayArray) { 3833 pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir; 3834 } 3835 return true; 3836 } 3837 3838 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 3839 String[] files = dir.list(); 3840 if (files == null) { 3841 Log.d(TAG, "No files in app dir " + dir); 3842 return; 3843 } 3844 3845 if (DEBUG_PACKAGE_SCANNING) { 3846 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 3847 + " flags=0x" + Integer.toHexString(flags)); 3848 } 3849 3850 int i; 3851 for (i=0; i<files.length; i++) { 3852 File file = new File(dir, files[i]); 3853 if (!isPackageFilename(files[i])) { 3854 // Ignore entries which are not apk's 3855 continue; 3856 } 3857 PackageParser.Package pkg = scanPackageLI(file, 3858 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null); 3859 // Don't mess around with apps in system partition. 3860 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 3861 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 3862 // Delete the apk 3863 Slog.w(TAG, "Cleaning up failed install of " + file); 3864 file.delete(); 3865 } 3866 } 3867 } 3868 3869 private static File getSettingsProblemFile() { 3870 File dataDir = Environment.getDataDirectory(); 3871 File systemDir = new File(dataDir, "system"); 3872 File fname = new File(systemDir, "uiderrors.txt"); 3873 return fname; 3874 } 3875 3876 static void reportSettingsProblem(int priority, String msg) { 3877 try { 3878 File fname = getSettingsProblemFile(); 3879 FileOutputStream out = new FileOutputStream(fname, true); 3880 PrintWriter pw = new FastPrintWriter(out); 3881 SimpleDateFormat formatter = new SimpleDateFormat(); 3882 String dateString = formatter.format(new Date(System.currentTimeMillis())); 3883 pw.println(dateString + ": " + msg); 3884 pw.close(); 3885 FileUtils.setPermissions( 3886 fname.toString(), 3887 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 3888 -1, -1); 3889 } catch (java.io.IOException e) { 3890 } 3891 Slog.println(priority, TAG, msg); 3892 } 3893 3894 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 3895 PackageParser.Package pkg, File srcFile, int parseFlags) { 3896 if (ps != null 3897 && ps.codePath.equals(srcFile) 3898 && ps.timeStamp == srcFile.lastModified() 3899 && !isCompatSignatureUpdateNeeded(pkg)) { 3900 if (ps.signatures.mSignatures != null 3901 && ps.signatures.mSignatures.length != 0) { 3902 // Optimization: reuse the existing cached certificates 3903 // if the package appears to be unchanged. 3904 pkg.mSignatures = ps.signatures.mSignatures; 3905 return true; 3906 } 3907 3908 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 3909 } else { 3910 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 3911 } 3912 3913 if (!pp.collectCertificates(pkg, parseFlags)) { 3914 mLastScanError = pp.getParseError(); 3915 return false; 3916 } 3917 return true; 3918 } 3919 3920 /* 3921 * Scan a package and return the newly parsed package. 3922 * Returns null in case of errors and the error code is stored in mLastScanError 3923 */ 3924 private PackageParser.Package scanPackageLI(File scanFile, 3925 int parseFlags, int scanMode, long currentTime, UserHandle user) { 3926 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 3927 String scanPath = scanFile.getPath(); 3928 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath); 3929 parseFlags |= mDefParseFlags; 3930 PackageParser pp = new PackageParser(scanPath); 3931 pp.setSeparateProcesses(mSeparateProcesses); 3932 pp.setOnlyCoreApps(mOnlyCore); 3933 final PackageParser.Package pkg = pp.parsePackage(scanFile, 3934 scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0); 3935 3936 if (pkg == null) { 3937 mLastScanError = pp.getParseError(); 3938 return null; 3939 } 3940 3941 PackageSetting ps = null; 3942 PackageSetting updatedPkg; 3943 // reader 3944 synchronized (mPackages) { 3945 // Look to see if we already know about this package. 3946 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 3947 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 3948 // This package has been renamed to its original name. Let's 3949 // use that. 3950 ps = mSettings.peekPackageLPr(oldName); 3951 } 3952 // If there was no original package, see one for the real package name. 3953 if (ps == null) { 3954 ps = mSettings.peekPackageLPr(pkg.packageName); 3955 } 3956 // Check to see if this package could be hiding/updating a system 3957 // package. Must look for it either under the original or real 3958 // package name depending on our state. 3959 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 3960 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 3961 } 3962 boolean updatedPkgBetter = false; 3963 // First check if this is a system package that may involve an update 3964 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 3965 if (ps != null && !ps.codePath.equals(scanFile)) { 3966 // The path has changed from what was last scanned... check the 3967 // version of the new path against what we have stored to determine 3968 // what to do. 3969 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 3970 if (pkg.mVersionCode < ps.versionCode) { 3971 // The system package has been updated and the code path does not match 3972 // Ignore entry. Skip it. 3973 Log.i(TAG, "Package " + ps.name + " at " + scanFile 3974 + " ignored: updated version " + ps.versionCode 3975 + " better than this " + pkg.mVersionCode); 3976 if (!updatedPkg.codePath.equals(scanFile)) { 3977 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 3978 + ps.name + " changing from " + updatedPkg.codePathString 3979 + " to " + scanFile); 3980 updatedPkg.codePath = scanFile; 3981 updatedPkg.codePathString = scanFile.toString(); 3982 // This is the point at which we know that the system-disk APK 3983 // for this package has moved during a reboot (e.g. due to an OTA), 3984 // so we need to reevaluate it for privilege policy. 3985 if (locationIsPrivileged(scanFile)) { 3986 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 3987 } 3988 } 3989 updatedPkg.pkg = pkg; 3990 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 3991 return null; 3992 } else { 3993 // The current app on the system partion is better than 3994 // what we have updated to on the data partition; switch 3995 // back to the system partition version. 3996 // At this point, its safely assumed that package installation for 3997 // apps in system partition will go through. If not there won't be a working 3998 // version of the app 3999 // writer 4000 synchronized (mPackages) { 4001 // Just remove the loaded entries from package lists. 4002 mPackages.remove(ps.name); 4003 } 4004 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4005 + "reverting from " + ps.codePathString 4006 + ": new version " + pkg.mVersionCode 4007 + " better than installed " + ps.versionCode); 4008 4009 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4010 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4011 getAppInstructionSetFromSettings(ps)); 4012 synchronized (mInstallLock) { 4013 args.cleanUpResourcesLI(); 4014 } 4015 synchronized (mPackages) { 4016 mSettings.enableSystemPackageLPw(ps.name); 4017 } 4018 updatedPkgBetter = true; 4019 } 4020 } 4021 } 4022 4023 if (updatedPkg != null) { 4024 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4025 // initially 4026 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4027 4028 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4029 // flag set initially 4030 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4031 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4032 } 4033 } 4034 // Verify certificates against what was last scanned 4035 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 4036 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 4037 return null; 4038 } 4039 4040 /* 4041 * A new system app appeared, but we already had a non-system one of the 4042 * same name installed earlier. 4043 */ 4044 boolean shouldHideSystemApp = false; 4045 if (updatedPkg == null && ps != null 4046 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4047 /* 4048 * Check to make sure the signatures match first. If they don't, 4049 * wipe the installed application and its data. 4050 */ 4051 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4052 != PackageManager.SIGNATURE_MATCH) { 4053 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4054 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4055 ps = null; 4056 } else { 4057 /* 4058 * If the newly-added system app is an older version than the 4059 * already installed version, hide it. It will be scanned later 4060 * and re-added like an update. 4061 */ 4062 if (pkg.mVersionCode < ps.versionCode) { 4063 shouldHideSystemApp = true; 4064 } else { 4065 /* 4066 * The newly found system app is a newer version that the 4067 * one previously installed. Simply remove the 4068 * already-installed application and replace it with our own 4069 * while keeping the application data. 4070 */ 4071 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4072 + ps.codePathString + ": new version " + pkg.mVersionCode 4073 + " better than installed " + ps.versionCode); 4074 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4075 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4076 getAppInstructionSetFromSettings(ps)); 4077 synchronized (mInstallLock) { 4078 args.cleanUpResourcesLI(); 4079 } 4080 } 4081 } 4082 } 4083 4084 // The apk is forward locked (not public) if its code and resources 4085 // are kept in different files. (except for app in either system or 4086 // vendor path). 4087 // TODO grab this value from PackageSettings 4088 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4089 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4090 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4091 } 4092 } 4093 4094 String codePath = null; 4095 String resPath = null; 4096 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4097 if (ps != null && ps.resourcePathString != null) { 4098 resPath = ps.resourcePathString; 4099 } else { 4100 // Should not happen at all. Just log an error. 4101 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4102 } 4103 } else { 4104 resPath = pkg.mScanPath; 4105 } 4106 4107 codePath = pkg.mScanPath; 4108 // Set application objects path explicitly. 4109 setApplicationInfoPaths(pkg, codePath, resPath); 4110 // Note that we invoke the following method only if we are about to unpack an application 4111 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4112 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4113 4114 /* 4115 * If the system app should be overridden by a previously installed 4116 * data, hide the system app now and let the /data/app scan pick it up 4117 * again. 4118 */ 4119 if (shouldHideSystemApp) { 4120 synchronized (mPackages) { 4121 /* 4122 * We have to grant systems permissions before we hide, because 4123 * grantPermissions will assume the package update is trying to 4124 * expand its permissions. 4125 */ 4126 grantPermissionsLPw(pkg, true); 4127 mSettings.disableSystemPackageLPw(pkg.packageName); 4128 } 4129 } 4130 4131 return scannedPkg; 4132 } 4133 4134 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath, 4135 String destResPath) { 4136 pkg.mPath = pkg.mScanPath = destCodePath; 4137 pkg.applicationInfo.sourceDir = destCodePath; 4138 pkg.applicationInfo.publicSourceDir = destResPath; 4139 } 4140 4141 private static String fixProcessName(String defProcessName, 4142 String processName, int uid) { 4143 if (processName == null) { 4144 return defProcessName; 4145 } 4146 return processName; 4147 } 4148 4149 private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) { 4150 if (pkgSetting.signatures.mSignatures != null) { 4151 // Already existing package. Make sure signatures match 4152 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4153 == PackageManager.SIGNATURE_MATCH; 4154 if (!match) { 4155 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4156 == PackageManager.SIGNATURE_MATCH; 4157 } 4158 if (!match) { 4159 Slog.e(TAG, "Package " + pkg.packageName 4160 + " signatures do not match the previously installed version; ignoring!"); 4161 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4162 return false; 4163 } 4164 } 4165 // Check for shared user signatures 4166 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4167 // Already existing package. Make sure signatures match 4168 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4169 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4170 if (!match) { 4171 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4172 == PackageManager.SIGNATURE_MATCH; 4173 } 4174 if (!match) { 4175 Slog.e(TAG, "Package " + pkg.packageName 4176 + " has no signatures that match those in shared user " 4177 + pkgSetting.sharedUser.name + "; ignoring!"); 4178 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4179 return false; 4180 } 4181 } 4182 return true; 4183 } 4184 4185 /** 4186 * Enforces that only the system UID or root's UID can call a method exposed 4187 * via Binder. 4188 * 4189 * @param message used as message if SecurityException is thrown 4190 * @throws SecurityException if the caller is not system or root 4191 */ 4192 private static final void enforceSystemOrRoot(String message) { 4193 final int uid = Binder.getCallingUid(); 4194 if (uid != Process.SYSTEM_UID && uid != 0) { 4195 throw new SecurityException(message); 4196 } 4197 } 4198 4199 @Override 4200 public void performBootDexOpt() { 4201 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4202 4203 final HashSet<PackageParser.Package> pkgs; 4204 synchronized (mPackages) { 4205 pkgs = mDeferredDexOpt; 4206 mDeferredDexOpt = null; 4207 } 4208 4209 if (pkgs != null) { 4210 int i = 0; 4211 for (PackageParser.Package pkg : pkgs) { 4212 if (!isFirstBoot()) { 4213 i++; 4214 try { 4215 ActivityManagerNative.getDefault().showBootMessage( 4216 mContext.getResources().getString( 4217 com.android.internal.R.string.android_upgrading_apk, 4218 i, pkgs.size()), true); 4219 } catch (RemoteException e) { 4220 } 4221 } 4222 PackageParser.Package p = pkg; 4223 synchronized (mInstallLock) { 4224 if (!p.mDidDexOpt) { 4225 performDexOptLI(p, false /* force dex */, false /* defer */, 4226 true /* include dependencies */); 4227 } 4228 } 4229 } 4230 } 4231 } 4232 4233 @Override 4234 public boolean performDexOpt(String packageName) { 4235 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4236 if (!mNoDexOpt) { 4237 return false; 4238 } 4239 4240 PackageParser.Package p; 4241 synchronized (mPackages) { 4242 p = mPackages.get(packageName); 4243 if (p == null || p.mDidDexOpt) { 4244 return false; 4245 } 4246 } 4247 synchronized (mInstallLock) { 4248 return performDexOptLI(p, false /* force dex */, false /* defer */, 4249 true /* include dependencies */) == DEX_OPT_PERFORMED; 4250 } 4251 } 4252 4253 private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, boolean forceDex, 4254 boolean defer, HashSet<String> done) { 4255 for (int i=0; i<libs.size(); i++) { 4256 PackageParser.Package libPkg; 4257 String libName; 4258 synchronized (mPackages) { 4259 libName = libs.get(i); 4260 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4261 if (lib != null && lib.apk != null) { 4262 libPkg = mPackages.get(lib.apk); 4263 } else { 4264 libPkg = null; 4265 } 4266 } 4267 if (libPkg != null && !done.contains(libName)) { 4268 performDexOptLI(libPkg, instructionSet, forceDex, defer, done); 4269 } 4270 } 4271 } 4272 4273 static final int DEX_OPT_SKIPPED = 0; 4274 static final int DEX_OPT_PERFORMED = 1; 4275 static final int DEX_OPT_DEFERRED = 2; 4276 static final int DEX_OPT_FAILED = -1; 4277 4278 private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride, 4279 boolean forceDex, 4280 boolean defer, HashSet<String> done) { 4281 final String instructionSet = instructionSetOverride != null ? 4282 instructionSetOverride : getAppInstructionSet(pkg.applicationInfo); 4283 4284 if (done != null) { 4285 done.add(pkg.packageName); 4286 if (pkg.usesLibraries != null) { 4287 performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done); 4288 } 4289 if (pkg.usesOptionalLibraries != null) { 4290 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done); 4291 } 4292 } 4293 4294 boolean performed = false; 4295 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 4296 String path = pkg.mScanPath; 4297 int ret = 0; 4298 try { 4299 if (forceDex || dalvik.system.DexFile.isDexOptNeededInternal(path, 4300 pkg.packageName, instructionSet, defer)) { 4301 if (!forceDex && defer) { 4302 if (mDeferredDexOpt == null) { 4303 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4304 } 4305 mDeferredDexOpt.add(pkg); 4306 return DEX_OPT_DEFERRED; 4307 } else { 4308 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName + 4309 " (instructionSet=" + instructionSet + ")"); 4310 4311 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4312 ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4313 pkg.packageName, instructionSet); 4314 pkg.mDidDexOpt = true; 4315 performed = true; 4316 } 4317 } 4318 } catch (FileNotFoundException e) { 4319 Slog.w(TAG, "Apk not found for dexopt: " + path); 4320 ret = -1; 4321 } catch (IOException e) { 4322 Slog.w(TAG, "IOException reading apk: " + path, e); 4323 ret = -1; 4324 } catch (dalvik.system.StaleDexCacheError e) { 4325 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4326 ret = -1; 4327 } catch (Exception e) { 4328 Slog.w(TAG, "Exception when doing dexopt : ", e); 4329 ret = -1; 4330 } 4331 if (ret < 0) { 4332 //error from installer 4333 return DEX_OPT_FAILED; 4334 } 4335 } 4336 4337 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4338 } 4339 4340 private String getAppInstructionSet(ApplicationInfo info) { 4341 String instructionSet = getPreferredInstructionSet(); 4342 4343 if (info.requiredCpuAbi != null) { 4344 instructionSet = VMRuntime.getInstructionSet(info.requiredCpuAbi); 4345 } 4346 4347 return instructionSet; 4348 } 4349 4350 private String getAppInstructionSetFromSettings(PackageSetting ps) { 4351 String instructionSet = getPreferredInstructionSet(); 4352 4353 if (ps.requiredCpuAbiString != null) { 4354 instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString); 4355 } 4356 4357 return instructionSet; 4358 } 4359 4360 private static String getPreferredInstructionSet() { 4361 if (sPreferredInstructionSet == null) { 4362 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4363 } 4364 4365 return sPreferredInstructionSet; 4366 } 4367 4368 private static List<String> getAllInstructionSets() { 4369 final String[] allAbis = Build.SUPPORTED_ABIS; 4370 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4371 4372 for (String abi : allAbis) { 4373 final String instructionSet = VMRuntime.getInstructionSet(abi); 4374 if (!allInstructionSets.contains(instructionSet)) { 4375 allInstructionSets.add(instructionSet); 4376 } 4377 } 4378 4379 return allInstructionSets; 4380 } 4381 4382 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4383 boolean inclDependencies) { 4384 HashSet<String> done; 4385 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4386 done = new HashSet<String>(); 4387 done.add(pkg.packageName); 4388 } else { 4389 done = null; 4390 } 4391 return performDexOptLI(pkg, null /* instruction set override */, forceDex, defer, done); 4392 } 4393 4394 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4395 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4396 Slog.w(TAG, "Unable to update from " + oldPkg.name 4397 + " to " + newPkg.packageName 4398 + ": old package not in system partition"); 4399 return false; 4400 } else if (mPackages.get(oldPkg.name) != null) { 4401 Slog.w(TAG, "Unable to update from " + oldPkg.name 4402 + " to " + newPkg.packageName 4403 + ": old package still exists"); 4404 return false; 4405 } 4406 return true; 4407 } 4408 4409 File getDataPathForUser(int userId) { 4410 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4411 } 4412 4413 private File getDataPathForPackage(String packageName, int userId) { 4414 /* 4415 * Until we fully support multiple users, return the directory we 4416 * previously would have. The PackageManagerTests will need to be 4417 * revised when this is changed back.. 4418 */ 4419 if (userId == 0) { 4420 return new File(mAppDataDir, packageName); 4421 } else { 4422 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4423 + File.separator + packageName); 4424 } 4425 } 4426 4427 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4428 int[] users = sUserManager.getUserIds(); 4429 int res = mInstaller.install(packageName, uid, uid, seinfo); 4430 if (res < 0) { 4431 return res; 4432 } 4433 for (int user : users) { 4434 if (user != 0) { 4435 res = mInstaller.createUserData(packageName, 4436 UserHandle.getUid(user, uid), user, seinfo); 4437 if (res < 0) { 4438 return res; 4439 } 4440 } 4441 } 4442 return res; 4443 } 4444 4445 private int removeDataDirsLI(String packageName) { 4446 int[] users = sUserManager.getUserIds(); 4447 int res = 0; 4448 for (int user : users) { 4449 int resInner = mInstaller.remove(packageName, user); 4450 if (resInner < 0) { 4451 res = resInner; 4452 } 4453 } 4454 4455 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4456 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4457 if (!nativeLibraryFile.delete()) { 4458 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4459 } 4460 4461 return res; 4462 } 4463 4464 private int addSharedLibraryLPw(final SharedLibraryEntry file, int num, 4465 PackageParser.Package changingLib) { 4466 if (file.path != null) { 4467 mTmpSharedLibraries[num] = file.path; 4468 return num+1; 4469 } 4470 PackageParser.Package p = mPackages.get(file.apk); 4471 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4472 // If we are doing this while in the middle of updating a library apk, 4473 // then we need to make sure to use that new apk for determining the 4474 // dependencies here. (We haven't yet finished committing the new apk 4475 // to the package manager state.) 4476 if (p == null || p.packageName.equals(changingLib.packageName)) { 4477 p = changingLib; 4478 } 4479 } 4480 if (p != null) { 4481 String path = p.mPath; 4482 for (int i=0; i<num; i++) { 4483 if (mTmpSharedLibraries[i].equals(path)) { 4484 return num; 4485 } 4486 } 4487 mTmpSharedLibraries[num] = p.mPath; 4488 return num+1; 4489 } 4490 return num; 4491 } 4492 4493 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4494 PackageParser.Package changingLib) { 4495 // We might be upgrading from a version of the platform that did not 4496 // provide per-package native library directories for system apps. 4497 // Fix that up here. 4498 if (isSystemApp(pkg)) { 4499 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4500 setInternalAppNativeLibraryPath(pkg, ps); 4501 } 4502 4503 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4504 if (mTmpSharedLibraries == null || 4505 mTmpSharedLibraries.length < mSharedLibraries.size()) { 4506 mTmpSharedLibraries = new String[mSharedLibraries.size()]; 4507 } 4508 int num = 0; 4509 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4510 for (int i=0; i<N; i++) { 4511 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4512 if (file == null) { 4513 Slog.e(TAG, "Package " + pkg.packageName 4514 + " requires unavailable shared library " 4515 + pkg.usesLibraries.get(i) + "; failing!"); 4516 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4517 return false; 4518 } 4519 num = addSharedLibraryLPw(file, num, changingLib); 4520 } 4521 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4522 for (int i=0; i<N; i++) { 4523 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4524 if (file == null) { 4525 Slog.w(TAG, "Package " + pkg.packageName 4526 + " desires unavailable shared library " 4527 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4528 } else { 4529 num = addSharedLibraryLPw(file, num, changingLib); 4530 } 4531 } 4532 if (num > 0) { 4533 pkg.usesLibraryFiles = new String[num]; 4534 System.arraycopy(mTmpSharedLibraries, 0, 4535 pkg.usesLibraryFiles, 0, num); 4536 } else { 4537 pkg.usesLibraryFiles = null; 4538 } 4539 } 4540 return true; 4541 } 4542 4543 private static boolean hasString(List<String> list, List<String> which) { 4544 if (list == null) { 4545 return false; 4546 } 4547 for (int i=list.size()-1; i>=0; i--) { 4548 for (int j=which.size()-1; j>=0; j--) { 4549 if (which.get(j).equals(list.get(i))) { 4550 return true; 4551 } 4552 } 4553 } 4554 return false; 4555 } 4556 4557 private void updateAllSharedLibrariesLPw() { 4558 for (PackageParser.Package pkg : mPackages.values()) { 4559 updateSharedLibrariesLPw(pkg, null); 4560 } 4561 } 4562 4563 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4564 PackageParser.Package changingPkg) { 4565 ArrayList<PackageParser.Package> res = null; 4566 for (PackageParser.Package pkg : mPackages.values()) { 4567 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4568 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4569 if (res == null) { 4570 res = new ArrayList<PackageParser.Package>(); 4571 } 4572 res.add(pkg); 4573 updateSharedLibrariesLPw(pkg, changingPkg); 4574 } 4575 } 4576 return res; 4577 } 4578 4579 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4580 int parseFlags, int scanMode, long currentTime, UserHandle user) { 4581 File scanFile = new File(pkg.mScanPath); 4582 if (scanFile == null || pkg.applicationInfo.sourceDir == null || 4583 pkg.applicationInfo.publicSourceDir == null) { 4584 // Bail out. The resource and code paths haven't been set. 4585 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4586 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4587 return null; 4588 } 4589 4590 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4591 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4592 } 4593 4594 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4595 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4596 } 4597 4598 if (mCustomResolverComponentName != null && 4599 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4600 setUpCustomResolverActivity(pkg); 4601 } 4602 4603 if (pkg.packageName.equals("android")) { 4604 synchronized (mPackages) { 4605 if (mAndroidApplication != null) { 4606 Slog.w(TAG, "*************************************************"); 4607 Slog.w(TAG, "Core android package being redefined. Skipping."); 4608 Slog.w(TAG, " file=" + scanFile); 4609 Slog.w(TAG, "*************************************************"); 4610 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4611 return null; 4612 } 4613 4614 // Set up information for our fall-back user intent resolution activity. 4615 mPlatformPackage = pkg; 4616 pkg.mVersionCode = mSdkVersion; 4617 mAndroidApplication = pkg.applicationInfo; 4618 4619 if (!mResolverReplaced) { 4620 mResolveActivity.applicationInfo = mAndroidApplication; 4621 mResolveActivity.name = ResolverActivity.class.getName(); 4622 mResolveActivity.packageName = mAndroidApplication.packageName; 4623 mResolveActivity.processName = "system:ui"; 4624 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4625 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4626 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert; 4627 mResolveActivity.exported = true; 4628 mResolveActivity.enabled = true; 4629 mResolveInfo.activityInfo = mResolveActivity; 4630 mResolveInfo.priority = 0; 4631 mResolveInfo.preferredOrder = 0; 4632 mResolveInfo.match = 0; 4633 mResolveComponentName = new ComponentName( 4634 mAndroidApplication.packageName, mResolveActivity.name); 4635 } 4636 } 4637 } 4638 4639 if (DEBUG_PACKAGE_SCANNING) { 4640 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4641 Log.d(TAG, "Scanning package " + pkg.packageName); 4642 } 4643 4644 if (mPackages.containsKey(pkg.packageName) 4645 || mSharedLibraries.containsKey(pkg.packageName)) { 4646 Slog.w(TAG, "Application package " + pkg.packageName 4647 + " already installed. Skipping duplicate."); 4648 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4649 return null; 4650 } 4651 4652 // Initialize package source and resource directories 4653 File destCodeFile = new File(pkg.applicationInfo.sourceDir); 4654 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir); 4655 4656 SharedUserSetting suid = null; 4657 PackageSetting pkgSetting = null; 4658 4659 if (!isSystemApp(pkg)) { 4660 // Only system apps can use these features. 4661 pkg.mOriginalPackages = null; 4662 pkg.mRealPackage = null; 4663 pkg.mAdoptPermissions = null; 4664 } 4665 4666 // writer 4667 synchronized (mPackages) { 4668 if (pkg.mSharedUserId != null) { 4669 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 4670 if (suid == null) { 4671 Slog.w(TAG, "Creating application package " + pkg.packageName 4672 + " for shared user failed"); 4673 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4674 return null; 4675 } 4676 if (DEBUG_PACKAGE_SCANNING) { 4677 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4678 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 4679 + "): packages=" + suid.packages); 4680 } 4681 } 4682 4683 // Check if we are renaming from an original package name. 4684 PackageSetting origPackage = null; 4685 String realName = null; 4686 if (pkg.mOriginalPackages != null) { 4687 // This package may need to be renamed to a previously 4688 // installed name. Let's check on that... 4689 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 4690 if (pkg.mOriginalPackages.contains(renamed)) { 4691 // This package had originally been installed as the 4692 // original name, and we have already taken care of 4693 // transitioning to the new one. Just update the new 4694 // one to continue using the old name. 4695 realName = pkg.mRealPackage; 4696 if (!pkg.packageName.equals(renamed)) { 4697 // Callers into this function may have already taken 4698 // care of renaming the package; only do it here if 4699 // it is not already done. 4700 pkg.setPackageName(renamed); 4701 } 4702 4703 } else { 4704 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 4705 if ((origPackage = mSettings.peekPackageLPr( 4706 pkg.mOriginalPackages.get(i))) != null) { 4707 // We do have the package already installed under its 4708 // original name... should we use it? 4709 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 4710 // New package is not compatible with original. 4711 origPackage = null; 4712 continue; 4713 } else if (origPackage.sharedUser != null) { 4714 // Make sure uid is compatible between packages. 4715 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 4716 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 4717 + " to " + pkg.packageName + ": old uid " 4718 + origPackage.sharedUser.name 4719 + " differs from " + pkg.mSharedUserId); 4720 origPackage = null; 4721 continue; 4722 } 4723 } else { 4724 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 4725 + pkg.packageName + " to old name " + origPackage.name); 4726 } 4727 break; 4728 } 4729 } 4730 } 4731 } 4732 4733 if (mTransferedPackages.contains(pkg.packageName)) { 4734 Slog.w(TAG, "Package " + pkg.packageName 4735 + " was transferred to another, but its .apk remains"); 4736 } 4737 4738 // Just create the setting, don't add it yet. For already existing packages 4739 // the PkgSetting exists already and doesn't have to be created. 4740 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 4741 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 4742 pkg.applicationInfo.requiredCpuAbi, 4743 pkg.applicationInfo.flags, user, false); 4744 if (pkgSetting == null) { 4745 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 4746 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4747 return null; 4748 } 4749 4750 if (pkgSetting.origPackage != null) { 4751 // If we are first transitioning from an original package, 4752 // fix up the new package's name now. We need to do this after 4753 // looking up the package under its new name, so getPackageLP 4754 // can take care of fiddling things correctly. 4755 pkg.setPackageName(origPackage.name); 4756 4757 // File a report about this. 4758 String msg = "New package " + pkgSetting.realName 4759 + " renamed to replace old package " + pkgSetting.name; 4760 reportSettingsProblem(Log.WARN, msg); 4761 4762 // Make a note of it. 4763 mTransferedPackages.add(origPackage.name); 4764 4765 // No longer need to retain this. 4766 pkgSetting.origPackage = null; 4767 } 4768 4769 if (realName != null) { 4770 // Make a note of it. 4771 mTransferedPackages.add(pkg.packageName); 4772 } 4773 4774 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 4775 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 4776 } 4777 4778 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4779 // Check all shared libraries and map to their actual file path. 4780 // We only do this here for apps not on a system dir, because those 4781 // are the only ones that can fail an install due to this. We 4782 // will take care of the system apps by updating all of their 4783 // library paths after the scan is done. 4784 if (!updateSharedLibrariesLPw(pkg, null)) { 4785 return null; 4786 } 4787 } 4788 4789 if (mFoundPolicyFile) { 4790 SELinuxMMAC.assignSeinfoValue(pkg); 4791 } 4792 4793 pkg.applicationInfo.uid = pkgSetting.appId; 4794 pkg.mExtras = pkgSetting; 4795 4796 if (!verifySignaturesLP(pkgSetting, pkg)) { 4797 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4798 return null; 4799 } 4800 // The signature has changed, but this package is in the system 4801 // image... let's recover! 4802 pkgSetting.signatures.mSignatures = pkg.mSignatures; 4803 // However... if this package is part of a shared user, but it 4804 // doesn't match the signature of the shared user, let's fail. 4805 // What this means is that you can't change the signatures 4806 // associated with an overall shared user, which doesn't seem all 4807 // that unreasonable. 4808 if (pkgSetting.sharedUser != null) { 4809 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4810 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 4811 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 4812 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 4813 return null; 4814 } 4815 } 4816 // File a report about this. 4817 String msg = "System package " + pkg.packageName 4818 + " signature changed; retaining data."; 4819 reportSettingsProblem(Log.WARN, msg); 4820 } 4821 4822 // Verify that this new package doesn't have any content providers 4823 // that conflict with existing packages. Only do this if the 4824 // package isn't already installed, since we don't want to break 4825 // things that are installed. 4826 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 4827 final int N = pkg.providers.size(); 4828 int i; 4829 for (i=0; i<N; i++) { 4830 PackageParser.Provider p = pkg.providers.get(i); 4831 if (p.info.authority != null) { 4832 String names[] = p.info.authority.split(";"); 4833 for (int j = 0; j < names.length; j++) { 4834 if (mProvidersByAuthority.containsKey(names[j])) { 4835 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 4836 Slog.w(TAG, "Can't install because provider name " + names[j] + 4837 " (in package " + pkg.applicationInfo.packageName + 4838 ") is already used by " 4839 + ((other != null && other.getComponentName() != null) 4840 ? other.getComponentName().getPackageName() : "?")); 4841 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 4842 return null; 4843 } 4844 } 4845 } 4846 } 4847 } 4848 4849 if (pkg.mAdoptPermissions != null) { 4850 // This package wants to adopt ownership of permissions from 4851 // another package. 4852 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 4853 final String origName = pkg.mAdoptPermissions.get(i); 4854 final PackageSetting orig = mSettings.peekPackageLPr(origName); 4855 if (orig != null) { 4856 if (verifyPackageUpdateLPr(orig, pkg)) { 4857 Slog.i(TAG, "Adopting permissions from " + origName + " to " 4858 + pkg.packageName); 4859 mSettings.transferPermissionsLPw(origName, pkg.packageName); 4860 } 4861 } 4862 } 4863 } 4864 } 4865 4866 final String pkgName = pkg.packageName; 4867 4868 final long scanFileTime = scanFile.lastModified(); 4869 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 4870 pkg.applicationInfo.processName = fixProcessName( 4871 pkg.applicationInfo.packageName, 4872 pkg.applicationInfo.processName, 4873 pkg.applicationInfo.uid); 4874 4875 File dataPath; 4876 if (mPlatformPackage == pkg) { 4877 // The system package is special. 4878 dataPath = new File (Environment.getDataDirectory(), "system"); 4879 pkg.applicationInfo.dataDir = dataPath.getPath(); 4880 } else { 4881 // This is a normal package, need to make its data directory. 4882 dataPath = getDataPathForPackage(pkg.packageName, 0); 4883 4884 boolean uidError = false; 4885 4886 if (dataPath.exists()) { 4887 int currentUid = 0; 4888 try { 4889 StructStat stat = Os.stat(dataPath.getPath()); 4890 currentUid = stat.st_uid; 4891 } catch (ErrnoException e) { 4892 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 4893 } 4894 4895 // If we have mismatched owners for the data path, we have a problem. 4896 if (currentUid != pkg.applicationInfo.uid) { 4897 boolean recovered = false; 4898 if (currentUid == 0) { 4899 // The directory somehow became owned by root. Wow. 4900 // This is probably because the system was stopped while 4901 // installd was in the middle of messing with its libs 4902 // directory. Ask installd to fix that. 4903 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 4904 pkg.applicationInfo.uid); 4905 if (ret >= 0) { 4906 recovered = true; 4907 String msg = "Package " + pkg.packageName 4908 + " unexpectedly changed to uid 0; recovered to " + 4909 + pkg.applicationInfo.uid; 4910 reportSettingsProblem(Log.WARN, msg); 4911 } 4912 } 4913 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 4914 || (scanMode&SCAN_BOOTING) != 0)) { 4915 // If this is a system app, we can at least delete its 4916 // current data so the application will still work. 4917 int ret = removeDataDirsLI(pkgName); 4918 if (ret >= 0) { 4919 // TODO: Kill the processes first 4920 // Old data gone! 4921 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 4922 ? "System package " : "Third party package "; 4923 String msg = prefix + pkg.packageName 4924 + " has changed from uid: " 4925 + currentUid + " to " 4926 + pkg.applicationInfo.uid + "; old data erased"; 4927 reportSettingsProblem(Log.WARN, msg); 4928 recovered = true; 4929 4930 // And now re-install the app. 4931 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 4932 pkg.applicationInfo.seinfo); 4933 if (ret == -1) { 4934 // Ack should not happen! 4935 msg = prefix + pkg.packageName 4936 + " could not have data directory re-created after delete."; 4937 reportSettingsProblem(Log.WARN, msg); 4938 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4939 return null; 4940 } 4941 } 4942 if (!recovered) { 4943 mHasSystemUidErrors = true; 4944 } 4945 } else if (!recovered) { 4946 // If we allow this install to proceed, we will be broken. 4947 // Abort, abort! 4948 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 4949 return null; 4950 } 4951 if (!recovered) { 4952 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 4953 + pkg.applicationInfo.uid + "/fs_" 4954 + currentUid; 4955 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 4956 String msg = "Package " + pkg.packageName 4957 + " has mismatched uid: " 4958 + currentUid + " on disk, " 4959 + pkg.applicationInfo.uid + " in settings"; 4960 // writer 4961 synchronized (mPackages) { 4962 mSettings.mReadMessages.append(msg); 4963 mSettings.mReadMessages.append('\n'); 4964 uidError = true; 4965 if (!pkgSetting.uidError) { 4966 reportSettingsProblem(Log.ERROR, msg); 4967 } 4968 } 4969 } 4970 } 4971 pkg.applicationInfo.dataDir = dataPath.getPath(); 4972 if (mShouldRestoreconData) { 4973 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 4974 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 4975 pkg.applicationInfo.uid); 4976 } 4977 } else { 4978 if (DEBUG_PACKAGE_SCANNING) { 4979 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4980 Log.v(TAG, "Want this data dir: " + dataPath); 4981 } 4982 //invoke installer to do the actual installation 4983 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 4984 pkg.applicationInfo.seinfo); 4985 if (ret < 0) { 4986 // Error from installer 4987 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4988 return null; 4989 } 4990 4991 if (dataPath.exists()) { 4992 pkg.applicationInfo.dataDir = dataPath.getPath(); 4993 } else { 4994 Slog.w(TAG, "Unable to create data directory: " + dataPath); 4995 pkg.applicationInfo.dataDir = null; 4996 } 4997 } 4998 4999 /* 5000 * Set the data dir to the default "/data/data/<package name>/lib" 5001 * if we got here without anyone telling us different (e.g., apps 5002 * stored on SD card have their native libraries stored in the ASEC 5003 * container with the APK). 5004 * 5005 * This happens during an upgrade from a package settings file that 5006 * doesn't have a native library path attribute at all. 5007 */ 5008 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 5009 if (pkgSetting.nativeLibraryPathString == null) { 5010 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5011 } else { 5012 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 5013 } 5014 } 5015 pkgSetting.uidError = uidError; 5016 } 5017 5018 String path = scanFile.getPath(); 5019 /* Note: We don't want to unpack the native binaries for 5020 * system applications, unless they have been updated 5021 * (the binaries are already under /system/lib). 5022 * Also, don't unpack libs for apps on the external card 5023 * since they should have their libraries in the ASEC 5024 * container already. 5025 * 5026 * In other words, we're going to unpack the binaries 5027 * only for non-system apps and system app upgrades. 5028 */ 5029 if (pkg.applicationInfo.nativeLibraryDir != null) { 5030 try { 5031 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5032 final String dataPathString = dataPath.getCanonicalPath(); 5033 5034 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5035 /* 5036 * Upgrading from a previous version of the OS sometimes 5037 * leaves native libraries in the /data/data/<app>/lib 5038 * directory for system apps even when they shouldn't be. 5039 * Recent changes in the JNI library search path 5040 * necessitates we remove those to match previous behavior. 5041 */ 5042 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 5043 Log.i(TAG, "removed obsolete native libraries for system package " 5044 + path); 5045 } 5046 5047 setInternalAppAbi(pkg, pkgSetting); 5048 } else { 5049 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 5050 /* 5051 * Update native library dir if it starts with 5052 * /data/data 5053 */ 5054 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 5055 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5056 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5057 } 5058 5059 try { 5060 int copyRet = copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir); 5061 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5062 Slog.e(TAG, "Unable to copy native libraries"); 5063 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5064 return null; 5065 } 5066 5067 // We've successfully copied native libraries across, so we make a 5068 // note of what ABI we're using 5069 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5070 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[copyRet]; 5071 } else { 5072 pkg.applicationInfo.requiredCpuAbi = null; 5073 } 5074 } catch (IOException e) { 5075 Slog.e(TAG, "Unable to copy native libraries", e); 5076 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5077 return null; 5078 } 5079 } else { 5080 // We don't have to copy the shared libraries if we're in the ASEC container 5081 // but we still need to scan the file to figure out what ABI the app needs. 5082 // 5083 // TODO: This duplicates work done in the default container service. It's possible 5084 // to clean this up but we'll need to change the interface between this service 5085 // and IMediaContainerService (but doing so will spread this logic out, rather 5086 // than centralizing it). 5087 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile); 5088 final int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS); 5089 if (abi >= 0) { 5090 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[abi]; 5091 } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) { 5092 // Note that (non upgraded) system apps will not have any native 5093 // libraries bundled in their APK, but we're guaranteed not to be 5094 // such an app at this point. 5095 pkg.applicationInfo.requiredCpuAbi = null; 5096 } else { 5097 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5098 return null; 5099 } 5100 handle.close(); 5101 } 5102 5103 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5104 final int[] userIds = sUserManager.getUserIds(); 5105 synchronized (mInstallLock) { 5106 for (int userId : userIds) { 5107 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 5108 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 5109 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5110 + ")"); 5111 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5112 return null; 5113 } 5114 } 5115 } 5116 } 5117 } catch (IOException ioe) { 5118 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5119 } 5120 } 5121 pkg.mScanPath = path; 5122 5123 if ((scanMode&SCAN_NO_DEX) == 0) { 5124 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5125 == DEX_OPT_FAILED) { 5126 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5127 removeDataDirsLI(pkg.packageName); 5128 } 5129 5130 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5131 return null; 5132 } 5133 } 5134 5135 if (mFactoryTest && pkg.requestedPermissions.contains( 5136 android.Manifest.permission.FACTORY_TEST)) { 5137 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5138 } 5139 5140 ArrayList<PackageParser.Package> clientLibPkgs = null; 5141 5142 // writer 5143 synchronized (mPackages) { 5144 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5145 // Only system apps can add new shared libraries. 5146 if (pkg.libraryNames != null) { 5147 for (int i=0; i<pkg.libraryNames.size(); i++) { 5148 String name = pkg.libraryNames.get(i); 5149 boolean allowed = false; 5150 if (isUpdatedSystemApp(pkg)) { 5151 // New library entries can only be added through the 5152 // system image. This is important to get rid of a lot 5153 // of nasty edge cases: for example if we allowed a non- 5154 // system update of the app to add a library, then uninstalling 5155 // the update would make the library go away, and assumptions 5156 // we made such as through app install filtering would now 5157 // have allowed apps on the device which aren't compatible 5158 // with it. Better to just have the restriction here, be 5159 // conservative, and create many fewer cases that can negatively 5160 // impact the user experience. 5161 final PackageSetting sysPs = mSettings 5162 .getDisabledSystemPkgLPr(pkg.packageName); 5163 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5164 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5165 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5166 allowed = true; 5167 allowed = true; 5168 break; 5169 } 5170 } 5171 } 5172 } else { 5173 allowed = true; 5174 } 5175 if (allowed) { 5176 if (!mSharedLibraries.containsKey(name)) { 5177 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5178 } else if (!name.equals(pkg.packageName)) { 5179 Slog.w(TAG, "Package " + pkg.packageName + " library " 5180 + name + " already exists; skipping"); 5181 } 5182 } else { 5183 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5184 + name + " that is not declared on system image; skipping"); 5185 } 5186 } 5187 if ((scanMode&SCAN_BOOTING) == 0) { 5188 // If we are not booting, we need to update any applications 5189 // that are clients of our shared library. If we are booting, 5190 // this will all be done once the scan is complete. 5191 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5192 } 5193 } 5194 } 5195 } 5196 5197 // We also need to dexopt any apps that are dependent on this library. Note that 5198 // if these fail, we should abort the install since installing the library will 5199 // result in some apps being broken. 5200 if (clientLibPkgs != null) { 5201 if ((scanMode&SCAN_NO_DEX) == 0) { 5202 for (int i=0; i<clientLibPkgs.size(); i++) { 5203 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5204 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5205 == DEX_OPT_FAILED) { 5206 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5207 removeDataDirsLI(pkg.packageName); 5208 } 5209 5210 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5211 return null; 5212 } 5213 } 5214 } 5215 } 5216 5217 // Request the ActivityManager to kill the process(only for existing packages) 5218 // so that we do not end up in a confused state while the user is still using the older 5219 // version of the application while the new one gets installed. 5220 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5221 // If the package lives in an asec, tell everyone that the container is going 5222 // away so they can clean up any references to its resources (which would prevent 5223 // vold from being able to unmount the asec) 5224 if (isForwardLocked(pkg) || isExternal(pkg)) { 5225 if (DEBUG_INSTALL) { 5226 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5227 } 5228 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5229 final ArrayList<String> pkgList = new ArrayList<String>(1); 5230 pkgList.add(pkg.applicationInfo.packageName); 5231 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5232 } 5233 5234 // Post the request that it be killed now that the going-away broadcast is en route 5235 killApplication(pkg.applicationInfo.packageName, 5236 pkg.applicationInfo.uid, "update pkg"); 5237 } 5238 5239 // Also need to kill any apps that are dependent on the library. 5240 if (clientLibPkgs != null) { 5241 for (int i=0; i<clientLibPkgs.size(); i++) { 5242 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5243 killApplication(clientPkg.applicationInfo.packageName, 5244 clientPkg.applicationInfo.uid, "update lib"); 5245 } 5246 } 5247 5248 // writer 5249 synchronized (mPackages) { 5250 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5251 // We don't do this here during boot because we can do it all 5252 // at once after scanning all existing packages. 5253 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5254 true, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5255 } 5256 // We don't expect installation to fail beyond this point, 5257 if ((scanMode&SCAN_MONITOR) != 0) { 5258 mAppDirs.put(pkg.mPath, pkg); 5259 } 5260 // Add the new setting to mSettings 5261 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5262 // Add the new setting to mPackages 5263 mPackages.put(pkg.applicationInfo.packageName, pkg); 5264 // Make sure we don't accidentally delete its data. 5265 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5266 while (iter.hasNext()) { 5267 PackageCleanItem item = iter.next(); 5268 if (pkgName.equals(item.packageName)) { 5269 iter.remove(); 5270 } 5271 } 5272 5273 // Take care of first install / last update times. 5274 if (currentTime != 0) { 5275 if (pkgSetting.firstInstallTime == 0) { 5276 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5277 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5278 pkgSetting.lastUpdateTime = currentTime; 5279 } 5280 } else if (pkgSetting.firstInstallTime == 0) { 5281 // We need *something*. Take time time stamp of the file. 5282 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5283 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5284 if (scanFileTime != pkgSetting.timeStamp) { 5285 // A package on the system image has changed; consider this 5286 // to be an update. 5287 pkgSetting.lastUpdateTime = scanFileTime; 5288 } 5289 } 5290 5291 // Add the package's KeySets to the global KeySetManager 5292 KeySetManager ksm = mSettings.mKeySetManager; 5293 try { 5294 ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5295 if (pkg.mKeySetMapping != null) { 5296 for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) { 5297 if (entry.getValue() != null) { 5298 ksm.addDefinedKeySetToPackage(pkg.packageName, 5299 entry.getValue(), entry.getKey()); 5300 } 5301 } 5302 } 5303 } catch (NullPointerException e) { 5304 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5305 } catch (IllegalArgumentException e) { 5306 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5307 } 5308 5309 int N = pkg.providers.size(); 5310 StringBuilder r = null; 5311 int i; 5312 for (i=0; i<N; i++) { 5313 PackageParser.Provider p = pkg.providers.get(i); 5314 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5315 p.info.processName, pkg.applicationInfo.uid); 5316 mProviders.addProvider(p); 5317 p.syncable = p.info.isSyncable; 5318 if (p.info.authority != null) { 5319 String names[] = p.info.authority.split(";"); 5320 p.info.authority = null; 5321 for (int j = 0; j < names.length; j++) { 5322 if (j == 1 && p.syncable) { 5323 // We only want the first authority for a provider to possibly be 5324 // syncable, so if we already added this provider using a different 5325 // authority clear the syncable flag. We copy the provider before 5326 // changing it because the mProviders object contains a reference 5327 // to a provider that we don't want to change. 5328 // Only do this for the second authority since the resulting provider 5329 // object can be the same for all future authorities for this provider. 5330 p = new PackageParser.Provider(p); 5331 p.syncable = false; 5332 } 5333 if (!mProvidersByAuthority.containsKey(names[j])) { 5334 mProvidersByAuthority.put(names[j], p); 5335 if (p.info.authority == null) { 5336 p.info.authority = names[j]; 5337 } else { 5338 p.info.authority = p.info.authority + ";" + names[j]; 5339 } 5340 if (DEBUG_PACKAGE_SCANNING) { 5341 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5342 Log.d(TAG, "Registered content provider: " + names[j] 5343 + ", className = " + p.info.name + ", isSyncable = " 5344 + p.info.isSyncable); 5345 } 5346 } else { 5347 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5348 Slog.w(TAG, "Skipping provider name " + names[j] + 5349 " (in package " + pkg.applicationInfo.packageName + 5350 "): name already used by " 5351 + ((other != null && other.getComponentName() != null) 5352 ? other.getComponentName().getPackageName() : "?")); 5353 } 5354 } 5355 } 5356 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5357 if (r == null) { 5358 r = new StringBuilder(256); 5359 } else { 5360 r.append(' '); 5361 } 5362 r.append(p.info.name); 5363 } 5364 } 5365 if (r != null) { 5366 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5367 } 5368 5369 N = pkg.services.size(); 5370 r = null; 5371 for (i=0; i<N; i++) { 5372 PackageParser.Service s = pkg.services.get(i); 5373 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5374 s.info.processName, pkg.applicationInfo.uid); 5375 mServices.addService(s); 5376 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5377 if (r == null) { 5378 r = new StringBuilder(256); 5379 } else { 5380 r.append(' '); 5381 } 5382 r.append(s.info.name); 5383 } 5384 } 5385 if (r != null) { 5386 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5387 } 5388 5389 N = pkg.receivers.size(); 5390 r = null; 5391 for (i=0; i<N; i++) { 5392 PackageParser.Activity a = pkg.receivers.get(i); 5393 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5394 a.info.processName, pkg.applicationInfo.uid); 5395 mReceivers.addActivity(a, "receiver"); 5396 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5397 if (r == null) { 5398 r = new StringBuilder(256); 5399 } else { 5400 r.append(' '); 5401 } 5402 r.append(a.info.name); 5403 } 5404 } 5405 if (r != null) { 5406 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5407 } 5408 5409 N = pkg.activities.size(); 5410 r = null; 5411 for (i=0; i<N; i++) { 5412 PackageParser.Activity a = pkg.activities.get(i); 5413 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5414 a.info.processName, pkg.applicationInfo.uid); 5415 mActivities.addActivity(a, "activity"); 5416 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5417 if (r == null) { 5418 r = new StringBuilder(256); 5419 } else { 5420 r.append(' '); 5421 } 5422 r.append(a.info.name); 5423 } 5424 } 5425 if (r != null) { 5426 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5427 } 5428 5429 N = pkg.permissionGroups.size(); 5430 r = null; 5431 for (i=0; i<N; i++) { 5432 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5433 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5434 if (cur == null) { 5435 mPermissionGroups.put(pg.info.name, pg); 5436 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5437 if (r == null) { 5438 r = new StringBuilder(256); 5439 } else { 5440 r.append(' '); 5441 } 5442 r.append(pg.info.name); 5443 } 5444 } else { 5445 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5446 + pg.info.packageName + " ignored: original from " 5447 + cur.info.packageName); 5448 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5449 if (r == null) { 5450 r = new StringBuilder(256); 5451 } else { 5452 r.append(' '); 5453 } 5454 r.append("DUP:"); 5455 r.append(pg.info.name); 5456 } 5457 } 5458 } 5459 if (r != null) { 5460 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5461 } 5462 5463 N = pkg.permissions.size(); 5464 r = null; 5465 for (i=0; i<N; i++) { 5466 PackageParser.Permission p = pkg.permissions.get(i); 5467 HashMap<String, BasePermission> permissionMap = 5468 p.tree ? mSettings.mPermissionTrees 5469 : mSettings.mPermissions; 5470 p.group = mPermissionGroups.get(p.info.group); 5471 if (p.info.group == null || p.group != null) { 5472 BasePermission bp = permissionMap.get(p.info.name); 5473 if (bp == null) { 5474 bp = new BasePermission(p.info.name, p.info.packageName, 5475 BasePermission.TYPE_NORMAL); 5476 permissionMap.put(p.info.name, bp); 5477 } 5478 if (bp.perm == null) { 5479 if (bp.sourcePackage != null 5480 && !bp.sourcePackage.equals(p.info.packageName)) { 5481 // If this is a permission that was formerly defined by a non-system 5482 // app, but is now defined by a system app (following an upgrade), 5483 // discard the previous declaration and consider the system's to be 5484 // canonical. 5485 if (isSystemApp(p.owner)) { 5486 String msg = "New decl " + p.owner + " of permission " 5487 + p.info.name + " is system"; 5488 reportSettingsProblem(Log.WARN, msg); 5489 bp.sourcePackage = null; 5490 } 5491 } 5492 if (bp.sourcePackage == null 5493 || bp.sourcePackage.equals(p.info.packageName)) { 5494 BasePermission tree = findPermissionTreeLP(p.info.name); 5495 if (tree == null 5496 || tree.sourcePackage.equals(p.info.packageName)) { 5497 bp.packageSetting = pkgSetting; 5498 bp.perm = p; 5499 bp.uid = pkg.applicationInfo.uid; 5500 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5501 if (r == null) { 5502 r = new StringBuilder(256); 5503 } else { 5504 r.append(' '); 5505 } 5506 r.append(p.info.name); 5507 } 5508 } else { 5509 Slog.w(TAG, "Permission " + p.info.name + " from package " 5510 + p.info.packageName + " ignored: base tree " 5511 + tree.name + " is from package " 5512 + tree.sourcePackage); 5513 } 5514 } else { 5515 Slog.w(TAG, "Permission " + p.info.name + " from package " 5516 + p.info.packageName + " ignored: original from " 5517 + bp.sourcePackage); 5518 } 5519 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5520 if (r == null) { 5521 r = new StringBuilder(256); 5522 } else { 5523 r.append(' '); 5524 } 5525 r.append("DUP:"); 5526 r.append(p.info.name); 5527 } 5528 if (bp.perm == p) { 5529 bp.protectionLevel = p.info.protectionLevel; 5530 } 5531 } else { 5532 Slog.w(TAG, "Permission " + p.info.name + " from package " 5533 + p.info.packageName + " ignored: no group " 5534 + p.group); 5535 } 5536 } 5537 if (r != null) { 5538 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5539 } 5540 5541 N = pkg.instrumentation.size(); 5542 r = null; 5543 for (i=0; i<N; i++) { 5544 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5545 a.info.packageName = pkg.applicationInfo.packageName; 5546 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5547 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5548 a.info.dataDir = pkg.applicationInfo.dataDir; 5549 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5550 mInstrumentation.put(a.getComponentName(), a); 5551 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5552 if (r == null) { 5553 r = new StringBuilder(256); 5554 } else { 5555 r.append(' '); 5556 } 5557 r.append(a.info.name); 5558 } 5559 } 5560 if (r != null) { 5561 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5562 } 5563 5564 if (pkg.protectedBroadcasts != null) { 5565 N = pkg.protectedBroadcasts.size(); 5566 for (i=0; i<N; i++) { 5567 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5568 } 5569 } 5570 5571 pkgSetting.setTimeStamp(scanFileTime); 5572 5573 // Create idmap files for pairs of (packages, overlay packages). 5574 // Note: "android", ie framework-res.apk, is handled by native layers. 5575 if (pkg.mOverlayTarget != null) { 5576 // This is an overlay package. 5577 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 5578 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 5579 mOverlays.put(pkg.mOverlayTarget, 5580 new HashMap<String, PackageParser.Package>()); 5581 } 5582 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 5583 map.put(pkg.packageName, pkg); 5584 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 5585 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 5586 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5587 return null; 5588 } 5589 } 5590 } else if (mOverlays.containsKey(pkg.packageName) && 5591 !pkg.packageName.equals("android")) { 5592 // This is a regular package, with one or more known overlay packages. 5593 createIdmapsForPackageLI(pkg); 5594 } 5595 } 5596 5597 return pkg; 5598 } 5599 5600 public void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 5601 boolean doDexOpt, boolean forceDexOpt, boolean deferDexOpt) { 5602 String requiredInstructionSet = null; 5603 PackageSetting requirer = null; 5604 for (PackageSetting ps : packagesForUser) { 5605 if (ps.requiredCpuAbiString != null) { 5606 final String instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString); 5607 if (requiredInstructionSet != null) { 5608 if (!instructionSet.equals(requiredInstructionSet)) { 5609 // We have a mismatch between instruction sets (say arm vs arm64). 5610 // 5611 // TODO: We should rescan all the packages in a shared UID to check if 5612 // they do contain shared libs for other ABIs in addition to the ones we've 5613 // already extracted. For example, the package might contain both arm64-v8a 5614 // and armeabi-v7a shared libs, and we'd have chosen arm64-v8a on 64 bit 5615 // devices. 5616 String errorMessage = "Instruction set mismatch, " + requirer.pkg.packageName 5617 + " requires " + requiredInstructionSet + " whereas " + ps.pkg.packageName 5618 + " requires " + instructionSet; 5619 Slog.e(TAG, errorMessage); 5620 5621 reportSettingsProblem(Log.WARN, errorMessage); 5622 // Give up, don't bother making any other changes to the package settings. 5623 return; 5624 } 5625 } else { 5626 requiredInstructionSet = instructionSet; 5627 requirer = ps; 5628 } 5629 } 5630 } 5631 5632 if (requiredInstructionSet != null) { 5633 for (PackageSetting ps : packagesForUser) { 5634 if (ps.requiredCpuAbiString == null) { 5635 ps.requiredCpuAbiString = requirer.requiredCpuAbiString; 5636 ps.pkg.applicationInfo.requiredCpuAbi = requirer.requiredCpuAbiString; 5637 5638 Slog.i(TAG, "Adjusting ABI for : " + ps.pkg.packageName + " to " + ps.requiredCpuAbiString); 5639 if (doDexOpt) { 5640 performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true); 5641 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 5642 } 5643 } 5644 } 5645 } 5646 } 5647 5648 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 5649 synchronized (mPackages) { 5650 mResolverReplaced = true; 5651 // Set up information for custom user intent resolution activity. 5652 mResolveActivity.applicationInfo = pkg.applicationInfo; 5653 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 5654 mResolveActivity.packageName = pkg.applicationInfo.packageName; 5655 mResolveActivity.processName = null; 5656 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5657 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 5658 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 5659 mResolveActivity.theme = 0; 5660 mResolveActivity.exported = true; 5661 mResolveActivity.enabled = true; 5662 mResolveInfo.activityInfo = mResolveActivity; 5663 mResolveInfo.priority = 0; 5664 mResolveInfo.preferredOrder = 0; 5665 mResolveInfo.match = 0; 5666 mResolveComponentName = mCustomResolverComponentName; 5667 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 5668 mResolveComponentName); 5669 } 5670 } 5671 5672 private String calculateApkRoot(final String codePathString) { 5673 final File codePath = new File(codePathString); 5674 final File codeRoot; 5675 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 5676 codeRoot = Environment.getRootDirectory(); 5677 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 5678 codeRoot = Environment.getOemDirectory(); 5679 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 5680 codeRoot = Environment.getVendorDirectory(); 5681 } else { 5682 // Unrecognized code path; take its top real segment as the apk root: 5683 // e.g. /something/app/blah.apk => /something 5684 try { 5685 File f = codePath.getCanonicalFile(); 5686 File parent = f.getParentFile(); // non-null because codePath is a file 5687 File tmp; 5688 while ((tmp = parent.getParentFile()) != null) { 5689 f = parent; 5690 parent = tmp; 5691 } 5692 codeRoot = f; 5693 Slog.w(TAG, "Unrecognized code path " 5694 + codePath + " - using " + codeRoot); 5695 } catch (IOException e) { 5696 // Can't canonicalize the lib path -- shenanigans? 5697 Slog.w(TAG, "Can't canonicalize code path " + codePath); 5698 return Environment.getRootDirectory().getPath(); 5699 } 5700 } 5701 return codeRoot.getPath(); 5702 } 5703 5704 // This is the initial scan-time determination of how to handle a given 5705 // package for purposes of native library location. 5706 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 5707 PackageSetting pkgSetting) { 5708 // "bundled" here means system-installed with no overriding update 5709 final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg); 5710 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 5711 final File libDir; 5712 if (bundledApk) { 5713 // If "/system/lib64/apkname" exists, assume that is the per-package 5714 // native library directory to use; otherwise use "/system/lib/apkname". 5715 String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 5716 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 5717 File packLib64 = new File(lib64, apkName); 5718 libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 5719 } else { 5720 libDir = mAppLibInstallDir; 5721 } 5722 final String nativeLibraryPath = (new File(libDir, apkName)).getPath(); 5723 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 5724 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 5725 } 5726 5727 // Deduces the required ABI of an upgraded system app. 5728 private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) { 5729 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 5730 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 5731 5732 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 5733 // or similar. 5734 final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath()); 5735 final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath()); 5736 5737 // Assume that the bundled native libraries always correspond to the 5738 // most preferred 32 or 64 bit ABI. 5739 if (lib64.exists()) { 5740 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 5741 pkgSetting.requiredCpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0]; 5742 } else if (lib.exists()) { 5743 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5744 pkgSetting.requiredCpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0]; 5745 } else { 5746 // This is the case where the app has no native code. 5747 pkg.applicationInfo.requiredCpuAbi = null; 5748 pkgSetting.requiredCpuAbiString = null; 5749 } 5750 } 5751 5752 private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir) 5753 throws IOException { 5754 if (!nativeLibraryDir.isDirectory()) { 5755 nativeLibraryDir.delete(); 5756 5757 if (!nativeLibraryDir.mkdir()) { 5758 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 5759 } 5760 5761 try { 5762 Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 5763 } catch (ErrnoException e) { 5764 throw new IOException("Cannot chmod native library directory " 5765 + nativeLibraryDir.getPath(), e); 5766 } 5767 } else if (!SELinux.restorecon(nativeLibraryDir)) { 5768 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 5769 } 5770 5771 /* 5772 * If this is an internal application or our nativeLibraryPath points to 5773 * the app-lib directory, unpack the libraries if necessary. 5774 */ 5775 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile); 5776 try { 5777 int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS); 5778 if (abi >= 0) { 5779 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 5780 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 5781 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 5782 return copyRet; 5783 } 5784 } 5785 5786 return abi; 5787 } finally { 5788 handle.close(); 5789 } 5790 } 5791 5792 private void killApplication(String pkgName, int appId, String reason) { 5793 // Request the ActivityManager to kill the process(only for existing packages) 5794 // so that we do not end up in a confused state while the user is still using the older 5795 // version of the application while the new one gets installed. 5796 IActivityManager am = ActivityManagerNative.getDefault(); 5797 if (am != null) { 5798 try { 5799 am.killApplicationWithAppId(pkgName, appId, reason); 5800 } catch (RemoteException e) { 5801 } 5802 } 5803 } 5804 5805 void removePackageLI(PackageSetting ps, boolean chatty) { 5806 if (DEBUG_INSTALL) { 5807 if (chatty) 5808 Log.d(TAG, "Removing package " + ps.name); 5809 } 5810 5811 // writer 5812 synchronized (mPackages) { 5813 mPackages.remove(ps.name); 5814 if (ps.codePathString != null) { 5815 mAppDirs.remove(ps.codePathString); 5816 } 5817 5818 final PackageParser.Package pkg = ps.pkg; 5819 if (pkg != null) { 5820 cleanPackageDataStructuresLILPw(pkg, chatty); 5821 } 5822 } 5823 } 5824 5825 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 5826 if (DEBUG_INSTALL) { 5827 if (chatty) 5828 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 5829 } 5830 5831 // writer 5832 synchronized (mPackages) { 5833 mPackages.remove(pkg.applicationInfo.packageName); 5834 if (pkg.mPath != null) { 5835 mAppDirs.remove(pkg.mPath); 5836 } 5837 cleanPackageDataStructuresLILPw(pkg, chatty); 5838 } 5839 } 5840 5841 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 5842 int N = pkg.providers.size(); 5843 StringBuilder r = null; 5844 int i; 5845 for (i=0; i<N; i++) { 5846 PackageParser.Provider p = pkg.providers.get(i); 5847 mProviders.removeProvider(p); 5848 if (p.info.authority == null) { 5849 5850 /* There was another ContentProvider with this authority when 5851 * this app was installed so this authority is null, 5852 * Ignore it as we don't have to unregister the provider. 5853 */ 5854 continue; 5855 } 5856 String names[] = p.info.authority.split(";"); 5857 for (int j = 0; j < names.length; j++) { 5858 if (mProvidersByAuthority.get(names[j]) == p) { 5859 mProvidersByAuthority.remove(names[j]); 5860 if (DEBUG_REMOVE) { 5861 if (chatty) 5862 Log.d(TAG, "Unregistered content provider: " + names[j] 5863 + ", className = " + p.info.name + ", isSyncable = " 5864 + p.info.isSyncable); 5865 } 5866 } 5867 } 5868 if (DEBUG_REMOVE && chatty) { 5869 if (r == null) { 5870 r = new StringBuilder(256); 5871 } else { 5872 r.append(' '); 5873 } 5874 r.append(p.info.name); 5875 } 5876 } 5877 if (r != null) { 5878 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 5879 } 5880 5881 N = pkg.services.size(); 5882 r = null; 5883 for (i=0; i<N; i++) { 5884 PackageParser.Service s = pkg.services.get(i); 5885 mServices.removeService(s); 5886 if (chatty) { 5887 if (r == null) { 5888 r = new StringBuilder(256); 5889 } else { 5890 r.append(' '); 5891 } 5892 r.append(s.info.name); 5893 } 5894 } 5895 if (r != null) { 5896 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 5897 } 5898 5899 N = pkg.receivers.size(); 5900 r = null; 5901 for (i=0; i<N; i++) { 5902 PackageParser.Activity a = pkg.receivers.get(i); 5903 mReceivers.removeActivity(a, "receiver"); 5904 if (DEBUG_REMOVE && chatty) { 5905 if (r == null) { 5906 r = new StringBuilder(256); 5907 } else { 5908 r.append(' '); 5909 } 5910 r.append(a.info.name); 5911 } 5912 } 5913 if (r != null) { 5914 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 5915 } 5916 5917 N = pkg.activities.size(); 5918 r = null; 5919 for (i=0; i<N; i++) { 5920 PackageParser.Activity a = pkg.activities.get(i); 5921 mActivities.removeActivity(a, "activity"); 5922 if (DEBUG_REMOVE && chatty) { 5923 if (r == null) { 5924 r = new StringBuilder(256); 5925 } else { 5926 r.append(' '); 5927 } 5928 r.append(a.info.name); 5929 } 5930 } 5931 if (r != null) { 5932 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 5933 } 5934 5935 N = pkg.permissions.size(); 5936 r = null; 5937 for (i=0; i<N; i++) { 5938 PackageParser.Permission p = pkg.permissions.get(i); 5939 BasePermission bp = mSettings.mPermissions.get(p.info.name); 5940 if (bp == null) { 5941 bp = mSettings.mPermissionTrees.get(p.info.name); 5942 } 5943 if (bp != null && bp.perm == p) { 5944 bp.perm = null; 5945 if (DEBUG_REMOVE && chatty) { 5946 if (r == null) { 5947 r = new StringBuilder(256); 5948 } else { 5949 r.append(' '); 5950 } 5951 r.append(p.info.name); 5952 } 5953 } 5954 } 5955 if (r != null) { 5956 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 5957 } 5958 5959 N = pkg.instrumentation.size(); 5960 r = null; 5961 for (i=0; i<N; i++) { 5962 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5963 mInstrumentation.remove(a.getComponentName()); 5964 if (DEBUG_REMOVE && chatty) { 5965 if (r == null) { 5966 r = new StringBuilder(256); 5967 } else { 5968 r.append(' '); 5969 } 5970 r.append(a.info.name); 5971 } 5972 } 5973 if (r != null) { 5974 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 5975 } 5976 5977 r = null; 5978 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5979 // Only system apps can hold shared libraries. 5980 if (pkg.libraryNames != null) { 5981 for (i=0; i<pkg.libraryNames.size(); i++) { 5982 String name = pkg.libraryNames.get(i); 5983 SharedLibraryEntry cur = mSharedLibraries.get(name); 5984 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 5985 mSharedLibraries.remove(name); 5986 if (DEBUG_REMOVE && chatty) { 5987 if (r == null) { 5988 r = new StringBuilder(256); 5989 } else { 5990 r.append(' '); 5991 } 5992 r.append(name); 5993 } 5994 } 5995 } 5996 } 5997 } 5998 if (r != null) { 5999 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6000 } 6001 } 6002 6003 private static final boolean isPackageFilename(String name) { 6004 return name != null && name.endsWith(".apk"); 6005 } 6006 6007 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6008 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6009 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6010 return true; 6011 } 6012 } 6013 return false; 6014 } 6015 6016 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6017 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6018 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6019 6020 private void updatePermissionsLPw(String changingPkg, 6021 PackageParser.Package pkgInfo, int flags) { 6022 // Make sure there are no dangling permission trees. 6023 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6024 while (it.hasNext()) { 6025 final BasePermission bp = it.next(); 6026 if (bp.packageSetting == null) { 6027 // We may not yet have parsed the package, so just see if 6028 // we still know about its settings. 6029 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6030 } 6031 if (bp.packageSetting == null) { 6032 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6033 + " from package " + bp.sourcePackage); 6034 it.remove(); 6035 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6036 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6037 Slog.i(TAG, "Removing old permission tree: " + bp.name 6038 + " from package " + bp.sourcePackage); 6039 flags |= UPDATE_PERMISSIONS_ALL; 6040 it.remove(); 6041 } 6042 } 6043 } 6044 6045 // Make sure all dynamic permissions have been assigned to a package, 6046 // and make sure there are no dangling permissions. 6047 it = mSettings.mPermissions.values().iterator(); 6048 while (it.hasNext()) { 6049 final BasePermission bp = it.next(); 6050 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6051 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6052 + bp.name + " pkg=" + bp.sourcePackage 6053 + " info=" + bp.pendingInfo); 6054 if (bp.packageSetting == null && bp.pendingInfo != null) { 6055 final BasePermission tree = findPermissionTreeLP(bp.name); 6056 if (tree != null && tree.perm != null) { 6057 bp.packageSetting = tree.packageSetting; 6058 bp.perm = new PackageParser.Permission(tree.perm.owner, 6059 new PermissionInfo(bp.pendingInfo)); 6060 bp.perm.info.packageName = tree.perm.info.packageName; 6061 bp.perm.info.name = bp.name; 6062 bp.uid = tree.uid; 6063 } 6064 } 6065 } 6066 if (bp.packageSetting == null) { 6067 // We may not yet have parsed the package, so just see if 6068 // we still know about its settings. 6069 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6070 } 6071 if (bp.packageSetting == null) { 6072 Slog.w(TAG, "Removing dangling permission: " + bp.name 6073 + " from package " + bp.sourcePackage); 6074 it.remove(); 6075 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6076 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6077 Slog.i(TAG, "Removing old permission: " + bp.name 6078 + " from package " + bp.sourcePackage); 6079 flags |= UPDATE_PERMISSIONS_ALL; 6080 it.remove(); 6081 } 6082 } 6083 } 6084 6085 // Now update the permissions for all packages, in particular 6086 // replace the granted permissions of the system packages. 6087 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6088 for (PackageParser.Package pkg : mPackages.values()) { 6089 if (pkg != pkgInfo) { 6090 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6091 } 6092 } 6093 } 6094 6095 if (pkgInfo != null) { 6096 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6097 } 6098 } 6099 6100 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6101 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6102 if (ps == null) { 6103 return; 6104 } 6105 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6106 HashSet<String> origPermissions = gp.grantedPermissions; 6107 boolean changedPermission = false; 6108 6109 if (replace) { 6110 ps.permissionsFixed = false; 6111 if (gp == ps) { 6112 origPermissions = new HashSet<String>(gp.grantedPermissions); 6113 gp.grantedPermissions.clear(); 6114 gp.gids = mGlobalGids; 6115 } 6116 } 6117 6118 if (gp.gids == null) { 6119 gp.gids = mGlobalGids; 6120 } 6121 6122 final int N = pkg.requestedPermissions.size(); 6123 for (int i=0; i<N; i++) { 6124 final String name = pkg.requestedPermissions.get(i); 6125 final boolean required = pkg.requestedPermissionsRequired.get(i); 6126 final BasePermission bp = mSettings.mPermissions.get(name); 6127 if (DEBUG_INSTALL) { 6128 if (gp != ps) { 6129 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6130 } 6131 } 6132 6133 if (bp == null || bp.packageSetting == null) { 6134 Slog.w(TAG, "Unknown permission " + name 6135 + " in package " + pkg.packageName); 6136 continue; 6137 } 6138 6139 final String perm = bp.name; 6140 boolean allowed; 6141 boolean allowedSig = false; 6142 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6143 if (level == PermissionInfo.PROTECTION_NORMAL 6144 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6145 // We grant a normal or dangerous permission if any of the following 6146 // are true: 6147 // 1) The permission is required 6148 // 2) The permission is optional, but was granted in the past 6149 // 3) The permission is optional, but was requested by an 6150 // app in /system (not /data) 6151 // 6152 // Otherwise, reject the permission. 6153 allowed = (required || origPermissions.contains(perm) 6154 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6155 } else if (bp.packageSetting == null) { 6156 // This permission is invalid; skip it. 6157 allowed = false; 6158 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6159 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6160 if (allowed) { 6161 allowedSig = true; 6162 } 6163 } else { 6164 allowed = false; 6165 } 6166 if (DEBUG_INSTALL) { 6167 if (gp != ps) { 6168 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6169 } 6170 } 6171 if (allowed) { 6172 if (!isSystemApp(ps) && ps.permissionsFixed) { 6173 // If this is an existing, non-system package, then 6174 // we can't add any new permissions to it. 6175 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6176 // Except... if this is a permission that was added 6177 // to the platform (note: need to only do this when 6178 // updating the platform). 6179 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6180 } 6181 } 6182 if (allowed) { 6183 if (!gp.grantedPermissions.contains(perm)) { 6184 changedPermission = true; 6185 gp.grantedPermissions.add(perm); 6186 gp.gids = appendInts(gp.gids, bp.gids); 6187 } else if (!ps.haveGids) { 6188 gp.gids = appendInts(gp.gids, bp.gids); 6189 } 6190 } else { 6191 Slog.w(TAG, "Not granting permission " + perm 6192 + " to package " + pkg.packageName 6193 + " because it was previously installed without"); 6194 } 6195 } else { 6196 if (gp.grantedPermissions.remove(perm)) { 6197 changedPermission = true; 6198 gp.gids = removeInts(gp.gids, bp.gids); 6199 Slog.i(TAG, "Un-granting permission " + perm 6200 + " from package " + pkg.packageName 6201 + " (protectionLevel=" + bp.protectionLevel 6202 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6203 + ")"); 6204 } else { 6205 Slog.w(TAG, "Not granting permission " + perm 6206 + " to package " + pkg.packageName 6207 + " (protectionLevel=" + bp.protectionLevel 6208 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6209 + ")"); 6210 } 6211 } 6212 } 6213 6214 if ((changedPermission || replace) && !ps.permissionsFixed && 6215 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6216 // This is the first that we have heard about this package, so the 6217 // permissions we have now selected are fixed until explicitly 6218 // changed. 6219 ps.permissionsFixed = true; 6220 } 6221 ps.haveGids = true; 6222 } 6223 6224 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6225 boolean allowed = false; 6226 final int NP = PackageParser.NEW_PERMISSIONS.length; 6227 for (int ip=0; ip<NP; ip++) { 6228 final PackageParser.NewPermissionInfo npi 6229 = PackageParser.NEW_PERMISSIONS[ip]; 6230 if (npi.name.equals(perm) 6231 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6232 allowed = true; 6233 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6234 + pkg.packageName); 6235 break; 6236 } 6237 } 6238 return allowed; 6239 } 6240 6241 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6242 BasePermission bp, HashSet<String> origPermissions) { 6243 boolean allowed; 6244 allowed = (compareSignatures( 6245 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6246 == PackageManager.SIGNATURE_MATCH) 6247 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6248 == PackageManager.SIGNATURE_MATCH); 6249 if (!allowed && (bp.protectionLevel 6250 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6251 if (isSystemApp(pkg)) { 6252 // For updated system applications, a system permission 6253 // is granted only if it had been defined by the original application. 6254 if (isUpdatedSystemApp(pkg)) { 6255 final PackageSetting sysPs = mSettings 6256 .getDisabledSystemPkgLPr(pkg.packageName); 6257 final GrantedPermissions origGp = sysPs.sharedUser != null 6258 ? sysPs.sharedUser : sysPs; 6259 6260 if (origGp.grantedPermissions.contains(perm)) { 6261 // If the original was granted this permission, we take 6262 // that grant decision as read and propagate it to the 6263 // update. 6264 allowed = true; 6265 } else { 6266 // The system apk may have been updated with an older 6267 // version of the one on the data partition, but which 6268 // granted a new system permission that it didn't have 6269 // before. In this case we do want to allow the app to 6270 // now get the new permission if the ancestral apk is 6271 // privileged to get it. 6272 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6273 for (int j=0; 6274 j<sysPs.pkg.requestedPermissions.size(); j++) { 6275 if (perm.equals( 6276 sysPs.pkg.requestedPermissions.get(j))) { 6277 allowed = true; 6278 break; 6279 } 6280 } 6281 } 6282 } 6283 } else { 6284 allowed = isPrivilegedApp(pkg); 6285 } 6286 } 6287 } 6288 if (!allowed && (bp.protectionLevel 6289 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6290 // For development permissions, a development permission 6291 // is granted only if it was already granted. 6292 allowed = origPermissions.contains(perm); 6293 } 6294 return allowed; 6295 } 6296 6297 final class ActivityIntentResolver 6298 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6299 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6300 boolean defaultOnly, int userId) { 6301 if (!sUserManager.exists(userId)) return null; 6302 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6303 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6304 } 6305 6306 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6307 int userId) { 6308 if (!sUserManager.exists(userId)) return null; 6309 mFlags = flags; 6310 return super.queryIntent(intent, resolvedType, 6311 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6312 } 6313 6314 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6315 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6316 if (!sUserManager.exists(userId)) return null; 6317 if (packageActivities == null) { 6318 return null; 6319 } 6320 mFlags = flags; 6321 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6322 final int N = packageActivities.size(); 6323 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6324 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6325 6326 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6327 for (int i = 0; i < N; ++i) { 6328 intentFilters = packageActivities.get(i).intents; 6329 if (intentFilters != null && intentFilters.size() > 0) { 6330 PackageParser.ActivityIntentInfo[] array = 6331 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6332 intentFilters.toArray(array); 6333 listCut.add(array); 6334 } 6335 } 6336 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6337 } 6338 6339 public final void addActivity(PackageParser.Activity a, String type) { 6340 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6341 mActivities.put(a.getComponentName(), a); 6342 if (DEBUG_SHOW_INFO) 6343 Log.v( 6344 TAG, " " + type + " " + 6345 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6346 if (DEBUG_SHOW_INFO) 6347 Log.v(TAG, " Class=" + a.info.name); 6348 final int NI = a.intents.size(); 6349 for (int j=0; j<NI; j++) { 6350 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6351 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6352 intent.setPriority(0); 6353 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6354 + a.className + " with priority > 0, forcing to 0"); 6355 } 6356 if (DEBUG_SHOW_INFO) { 6357 Log.v(TAG, " IntentFilter:"); 6358 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6359 } 6360 if (!intent.debugCheck()) { 6361 Log.w(TAG, "==> For Activity " + a.info.name); 6362 } 6363 addFilter(intent); 6364 } 6365 } 6366 6367 public final void removeActivity(PackageParser.Activity a, String type) { 6368 mActivities.remove(a.getComponentName()); 6369 if (DEBUG_SHOW_INFO) { 6370 Log.v(TAG, " " + type + " " 6371 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6372 : a.info.name) + ":"); 6373 Log.v(TAG, " Class=" + a.info.name); 6374 } 6375 final int NI = a.intents.size(); 6376 for (int j=0; j<NI; j++) { 6377 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6378 if (DEBUG_SHOW_INFO) { 6379 Log.v(TAG, " IntentFilter:"); 6380 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6381 } 6382 removeFilter(intent); 6383 } 6384 } 6385 6386 @Override 6387 protected boolean allowFilterResult( 6388 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6389 ActivityInfo filterAi = filter.activity.info; 6390 for (int i=dest.size()-1; i>=0; i--) { 6391 ActivityInfo destAi = dest.get(i).activityInfo; 6392 if (destAi.name == filterAi.name 6393 && destAi.packageName == filterAi.packageName) { 6394 return false; 6395 } 6396 } 6397 return true; 6398 } 6399 6400 @Override 6401 protected ActivityIntentInfo[] newArray(int size) { 6402 return new ActivityIntentInfo[size]; 6403 } 6404 6405 @Override 6406 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6407 if (!sUserManager.exists(userId)) return true; 6408 PackageParser.Package p = filter.activity.owner; 6409 if (p != null) { 6410 PackageSetting ps = (PackageSetting)p.mExtras; 6411 if (ps != null) { 6412 // System apps are never considered stopped for purposes of 6413 // filtering, because there may be no way for the user to 6414 // actually re-launch them. 6415 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6416 && ps.getStopped(userId); 6417 } 6418 } 6419 return false; 6420 } 6421 6422 @Override 6423 protected boolean isPackageForFilter(String packageName, 6424 PackageParser.ActivityIntentInfo info) { 6425 return packageName.equals(info.activity.owner.packageName); 6426 } 6427 6428 @Override 6429 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6430 int match, int userId) { 6431 if (!sUserManager.exists(userId)) return null; 6432 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6433 return null; 6434 } 6435 final PackageParser.Activity activity = info.activity; 6436 if (mSafeMode && (activity.info.applicationInfo.flags 6437 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6438 return null; 6439 } 6440 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6441 if (ps == null) { 6442 return null; 6443 } 6444 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6445 ps.readUserState(userId), userId); 6446 if (ai == null) { 6447 return null; 6448 } 6449 final ResolveInfo res = new ResolveInfo(); 6450 res.activityInfo = ai; 6451 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6452 res.filter = info; 6453 } 6454 res.priority = info.getPriority(); 6455 res.preferredOrder = activity.owner.mPreferredOrder; 6456 //System.out.println("Result: " + res.activityInfo.className + 6457 // " = " + res.priority); 6458 res.match = match; 6459 res.isDefault = info.hasDefault; 6460 res.labelRes = info.labelRes; 6461 res.nonLocalizedLabel = info.nonLocalizedLabel; 6462 res.icon = info.icon; 6463 res.system = isSystemApp(res.activityInfo.applicationInfo); 6464 return res; 6465 } 6466 6467 @Override 6468 protected void sortResults(List<ResolveInfo> results) { 6469 Collections.sort(results, mResolvePrioritySorter); 6470 } 6471 6472 @Override 6473 protected void dumpFilter(PrintWriter out, String prefix, 6474 PackageParser.ActivityIntentInfo filter) { 6475 out.print(prefix); out.print( 6476 Integer.toHexString(System.identityHashCode(filter.activity))); 6477 out.print(' '); 6478 filter.activity.printComponentShortName(out); 6479 out.print(" filter "); 6480 out.println(Integer.toHexString(System.identityHashCode(filter))); 6481 } 6482 6483// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6484// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6485// final List<ResolveInfo> retList = Lists.newArrayList(); 6486// while (i.hasNext()) { 6487// final ResolveInfo resolveInfo = i.next(); 6488// if (isEnabledLP(resolveInfo.activityInfo)) { 6489// retList.add(resolveInfo); 6490// } 6491// } 6492// return retList; 6493// } 6494 6495 // Keys are String (activity class name), values are Activity. 6496 private final HashMap<ComponentName, PackageParser.Activity> mActivities 6497 = new HashMap<ComponentName, PackageParser.Activity>(); 6498 private int mFlags; 6499 } 6500 6501 private final class ServiceIntentResolver 6502 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 6503 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6504 boolean defaultOnly, int userId) { 6505 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6506 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6507 } 6508 6509 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6510 int userId) { 6511 if (!sUserManager.exists(userId)) return null; 6512 mFlags = flags; 6513 return super.queryIntent(intent, resolvedType, 6514 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6515 } 6516 6517 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6518 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 6519 if (!sUserManager.exists(userId)) return null; 6520 if (packageServices == null) { 6521 return null; 6522 } 6523 mFlags = flags; 6524 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6525 final int N = packageServices.size(); 6526 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 6527 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 6528 6529 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 6530 for (int i = 0; i < N; ++i) { 6531 intentFilters = packageServices.get(i).intents; 6532 if (intentFilters != null && intentFilters.size() > 0) { 6533 PackageParser.ServiceIntentInfo[] array = 6534 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 6535 intentFilters.toArray(array); 6536 listCut.add(array); 6537 } 6538 } 6539 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6540 } 6541 6542 public final void addService(PackageParser.Service s) { 6543 mServices.put(s.getComponentName(), s); 6544 if (DEBUG_SHOW_INFO) { 6545 Log.v(TAG, " " 6546 + (s.info.nonLocalizedLabel != null 6547 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6548 Log.v(TAG, " Class=" + s.info.name); 6549 } 6550 final int NI = s.intents.size(); 6551 int j; 6552 for (j=0; j<NI; j++) { 6553 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6554 if (DEBUG_SHOW_INFO) { 6555 Log.v(TAG, " IntentFilter:"); 6556 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6557 } 6558 if (!intent.debugCheck()) { 6559 Log.w(TAG, "==> For Service " + s.info.name); 6560 } 6561 addFilter(intent); 6562 } 6563 } 6564 6565 public final void removeService(PackageParser.Service s) { 6566 mServices.remove(s.getComponentName()); 6567 if (DEBUG_SHOW_INFO) { 6568 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 6569 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6570 Log.v(TAG, " Class=" + s.info.name); 6571 } 6572 final int NI = s.intents.size(); 6573 int j; 6574 for (j=0; j<NI; j++) { 6575 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6576 if (DEBUG_SHOW_INFO) { 6577 Log.v(TAG, " IntentFilter:"); 6578 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6579 } 6580 removeFilter(intent); 6581 } 6582 } 6583 6584 @Override 6585 protected boolean allowFilterResult( 6586 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 6587 ServiceInfo filterSi = filter.service.info; 6588 for (int i=dest.size()-1; i>=0; i--) { 6589 ServiceInfo destAi = dest.get(i).serviceInfo; 6590 if (destAi.name == filterSi.name 6591 && destAi.packageName == filterSi.packageName) { 6592 return false; 6593 } 6594 } 6595 return true; 6596 } 6597 6598 @Override 6599 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 6600 return new PackageParser.ServiceIntentInfo[size]; 6601 } 6602 6603 @Override 6604 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 6605 if (!sUserManager.exists(userId)) return true; 6606 PackageParser.Package p = filter.service.owner; 6607 if (p != null) { 6608 PackageSetting ps = (PackageSetting)p.mExtras; 6609 if (ps != null) { 6610 // System apps are never considered stopped for purposes of 6611 // filtering, because there may be no way for the user to 6612 // actually re-launch them. 6613 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 6614 && ps.getStopped(userId); 6615 } 6616 } 6617 return false; 6618 } 6619 6620 @Override 6621 protected boolean isPackageForFilter(String packageName, 6622 PackageParser.ServiceIntentInfo info) { 6623 return packageName.equals(info.service.owner.packageName); 6624 } 6625 6626 @Override 6627 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 6628 int match, int userId) { 6629 if (!sUserManager.exists(userId)) return null; 6630 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 6631 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 6632 return null; 6633 } 6634 final PackageParser.Service service = info.service; 6635 if (mSafeMode && (service.info.applicationInfo.flags 6636 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6637 return null; 6638 } 6639 PackageSetting ps = (PackageSetting) service.owner.mExtras; 6640 if (ps == null) { 6641 return null; 6642 } 6643 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 6644 ps.readUserState(userId), userId); 6645 if (si == null) { 6646 return null; 6647 } 6648 final ResolveInfo res = new ResolveInfo(); 6649 res.serviceInfo = si; 6650 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6651 res.filter = filter; 6652 } 6653 res.priority = info.getPriority(); 6654 res.preferredOrder = service.owner.mPreferredOrder; 6655 //System.out.println("Result: " + res.activityInfo.className + 6656 // " = " + res.priority); 6657 res.match = match; 6658 res.isDefault = info.hasDefault; 6659 res.labelRes = info.labelRes; 6660 res.nonLocalizedLabel = info.nonLocalizedLabel; 6661 res.icon = info.icon; 6662 res.system = isSystemApp(res.serviceInfo.applicationInfo); 6663 return res; 6664 } 6665 6666 @Override 6667 protected void sortResults(List<ResolveInfo> results) { 6668 Collections.sort(results, mResolvePrioritySorter); 6669 } 6670 6671 @Override 6672 protected void dumpFilter(PrintWriter out, String prefix, 6673 PackageParser.ServiceIntentInfo filter) { 6674 out.print(prefix); out.print( 6675 Integer.toHexString(System.identityHashCode(filter.service))); 6676 out.print(' '); 6677 filter.service.printComponentShortName(out); 6678 out.print(" filter "); 6679 out.println(Integer.toHexString(System.identityHashCode(filter))); 6680 } 6681 6682// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6683// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6684// final List<ResolveInfo> retList = Lists.newArrayList(); 6685// while (i.hasNext()) { 6686// final ResolveInfo resolveInfo = (ResolveInfo) i; 6687// if (isEnabledLP(resolveInfo.serviceInfo)) { 6688// retList.add(resolveInfo); 6689// } 6690// } 6691// return retList; 6692// } 6693 6694 // Keys are String (activity class name), values are Activity. 6695 private final HashMap<ComponentName, PackageParser.Service> mServices 6696 = new HashMap<ComponentName, PackageParser.Service>(); 6697 private int mFlags; 6698 }; 6699 6700 private final class ProviderIntentResolver 6701 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 6702 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6703 boolean defaultOnly, int userId) { 6704 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6705 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6706 } 6707 6708 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6709 int userId) { 6710 if (!sUserManager.exists(userId)) 6711 return null; 6712 mFlags = flags; 6713 return super.queryIntent(intent, resolvedType, 6714 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6715 } 6716 6717 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6718 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 6719 if (!sUserManager.exists(userId)) 6720 return null; 6721 if (packageProviders == null) { 6722 return null; 6723 } 6724 mFlags = flags; 6725 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 6726 final int N = packageProviders.size(); 6727 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 6728 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 6729 6730 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 6731 for (int i = 0; i < N; ++i) { 6732 intentFilters = packageProviders.get(i).intents; 6733 if (intentFilters != null && intentFilters.size() > 0) { 6734 PackageParser.ProviderIntentInfo[] array = 6735 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 6736 intentFilters.toArray(array); 6737 listCut.add(array); 6738 } 6739 } 6740 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6741 } 6742 6743 public final void addProvider(PackageParser.Provider p) { 6744 if (mProviders.containsKey(p.getComponentName())) { 6745 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 6746 return; 6747 } 6748 6749 mProviders.put(p.getComponentName(), p); 6750 if (DEBUG_SHOW_INFO) { 6751 Log.v(TAG, " " 6752 + (p.info.nonLocalizedLabel != null 6753 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 6754 Log.v(TAG, " Class=" + p.info.name); 6755 } 6756 final int NI = p.intents.size(); 6757 int j; 6758 for (j = 0; j < NI; j++) { 6759 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 6760 if (DEBUG_SHOW_INFO) { 6761 Log.v(TAG, " IntentFilter:"); 6762 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6763 } 6764 if (!intent.debugCheck()) { 6765 Log.w(TAG, "==> For Provider " + p.info.name); 6766 } 6767 addFilter(intent); 6768 } 6769 } 6770 6771 public final void removeProvider(PackageParser.Provider p) { 6772 mProviders.remove(p.getComponentName()); 6773 if (DEBUG_SHOW_INFO) { 6774 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 6775 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 6776 Log.v(TAG, " Class=" + p.info.name); 6777 } 6778 final int NI = p.intents.size(); 6779 int j; 6780 for (j = 0; j < NI; j++) { 6781 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 6782 if (DEBUG_SHOW_INFO) { 6783 Log.v(TAG, " IntentFilter:"); 6784 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6785 } 6786 removeFilter(intent); 6787 } 6788 } 6789 6790 @Override 6791 protected boolean allowFilterResult( 6792 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 6793 ProviderInfo filterPi = filter.provider.info; 6794 for (int i = dest.size() - 1; i >= 0; i--) { 6795 ProviderInfo destPi = dest.get(i).providerInfo; 6796 if (destPi.name == filterPi.name 6797 && destPi.packageName == filterPi.packageName) { 6798 return false; 6799 } 6800 } 6801 return true; 6802 } 6803 6804 @Override 6805 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 6806 return new PackageParser.ProviderIntentInfo[size]; 6807 } 6808 6809 @Override 6810 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 6811 if (!sUserManager.exists(userId)) 6812 return true; 6813 PackageParser.Package p = filter.provider.owner; 6814 if (p != null) { 6815 PackageSetting ps = (PackageSetting) p.mExtras; 6816 if (ps != null) { 6817 // System apps are never considered stopped for purposes of 6818 // filtering, because there may be no way for the user to 6819 // actually re-launch them. 6820 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 6821 && ps.getStopped(userId); 6822 } 6823 } 6824 return false; 6825 } 6826 6827 @Override 6828 protected boolean isPackageForFilter(String packageName, 6829 PackageParser.ProviderIntentInfo info) { 6830 return packageName.equals(info.provider.owner.packageName); 6831 } 6832 6833 @Override 6834 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 6835 int match, int userId) { 6836 if (!sUserManager.exists(userId)) 6837 return null; 6838 final PackageParser.ProviderIntentInfo info = filter; 6839 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 6840 return null; 6841 } 6842 final PackageParser.Provider provider = info.provider; 6843 if (mSafeMode && (provider.info.applicationInfo.flags 6844 & ApplicationInfo.FLAG_SYSTEM) == 0) { 6845 return null; 6846 } 6847 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 6848 if (ps == null) { 6849 return null; 6850 } 6851 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 6852 ps.readUserState(userId), userId); 6853 if (pi == null) { 6854 return null; 6855 } 6856 final ResolveInfo res = new ResolveInfo(); 6857 res.providerInfo = pi; 6858 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 6859 res.filter = filter; 6860 } 6861 res.priority = info.getPriority(); 6862 res.preferredOrder = provider.owner.mPreferredOrder; 6863 res.match = match; 6864 res.isDefault = info.hasDefault; 6865 res.labelRes = info.labelRes; 6866 res.nonLocalizedLabel = info.nonLocalizedLabel; 6867 res.icon = info.icon; 6868 res.system = isSystemApp(res.providerInfo.applicationInfo); 6869 return res; 6870 } 6871 6872 @Override 6873 protected void sortResults(List<ResolveInfo> results) { 6874 Collections.sort(results, mResolvePrioritySorter); 6875 } 6876 6877 @Override 6878 protected void dumpFilter(PrintWriter out, String prefix, 6879 PackageParser.ProviderIntentInfo filter) { 6880 out.print(prefix); 6881 out.print( 6882 Integer.toHexString(System.identityHashCode(filter.provider))); 6883 out.print(' '); 6884 filter.provider.printComponentShortName(out); 6885 out.print(" filter "); 6886 out.println(Integer.toHexString(System.identityHashCode(filter))); 6887 } 6888 6889 private final HashMap<ComponentName, PackageParser.Provider> mProviders 6890 = new HashMap<ComponentName, PackageParser.Provider>(); 6891 private int mFlags; 6892 }; 6893 6894 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 6895 new Comparator<ResolveInfo>() { 6896 public int compare(ResolveInfo r1, ResolveInfo r2) { 6897 int v1 = r1.priority; 6898 int v2 = r2.priority; 6899 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 6900 if (v1 != v2) { 6901 return (v1 > v2) ? -1 : 1; 6902 } 6903 v1 = r1.preferredOrder; 6904 v2 = r2.preferredOrder; 6905 if (v1 != v2) { 6906 return (v1 > v2) ? -1 : 1; 6907 } 6908 if (r1.isDefault != r2.isDefault) { 6909 return r1.isDefault ? -1 : 1; 6910 } 6911 v1 = r1.match; 6912 v2 = r2.match; 6913 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 6914 if (v1 != v2) { 6915 return (v1 > v2) ? -1 : 1; 6916 } 6917 if (r1.system != r2.system) { 6918 return r1.system ? -1 : 1; 6919 } 6920 return 0; 6921 } 6922 }; 6923 6924 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 6925 new Comparator<ProviderInfo>() { 6926 public int compare(ProviderInfo p1, ProviderInfo p2) { 6927 final int v1 = p1.initOrder; 6928 final int v2 = p2.initOrder; 6929 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 6930 } 6931 }; 6932 6933 static final void sendPackageBroadcast(String action, String pkg, 6934 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 6935 int[] userIds) { 6936 IActivityManager am = ActivityManagerNative.getDefault(); 6937 if (am != null) { 6938 try { 6939 if (userIds == null) { 6940 userIds = am.getRunningUserIds(); 6941 } 6942 for (int id : userIds) { 6943 final Intent intent = new Intent(action, 6944 pkg != null ? Uri.fromParts("package", pkg, null) : null); 6945 if (extras != null) { 6946 intent.putExtras(extras); 6947 } 6948 if (targetPkg != null) { 6949 intent.setPackage(targetPkg); 6950 } 6951 // Modify the UID when posting to other users 6952 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 6953 if (uid > 0 && UserHandle.getUserId(uid) != id) { 6954 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 6955 intent.putExtra(Intent.EXTRA_UID, uid); 6956 } 6957 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 6958 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 6959 if (DEBUG_BROADCASTS) { 6960 RuntimeException here = new RuntimeException("here"); 6961 here.fillInStackTrace(); 6962 Slog.d(TAG, "Sending to user " + id + ": " 6963 + intent.toShortString(false, true, false, false) 6964 + " " + intent.getExtras(), here); 6965 } 6966 am.broadcastIntent(null, intent, null, finishedReceiver, 6967 0, null, null, null, android.app.AppOpsManager.OP_NONE, 6968 finishedReceiver != null, false, id); 6969 } 6970 } catch (RemoteException ex) { 6971 } 6972 } 6973 } 6974 6975 /** 6976 * Check if the external storage media is available. This is true if there 6977 * is a mounted external storage medium or if the external storage is 6978 * emulated. 6979 */ 6980 private boolean isExternalMediaAvailable() { 6981 return mMediaMounted || Environment.isExternalStorageEmulated(); 6982 } 6983 6984 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 6985 // writer 6986 synchronized (mPackages) { 6987 if (!isExternalMediaAvailable()) { 6988 // If the external storage is no longer mounted at this point, 6989 // the caller may not have been able to delete all of this 6990 // packages files and can not delete any more. Bail. 6991 return null; 6992 } 6993 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 6994 if (lastPackage != null) { 6995 pkgs.remove(lastPackage); 6996 } 6997 if (pkgs.size() > 0) { 6998 return pkgs.get(0); 6999 } 7000 } 7001 return null; 7002 } 7003 7004 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7005 if (false) { 7006 RuntimeException here = new RuntimeException("here"); 7007 here.fillInStackTrace(); 7008 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7009 + " andCode=" + andCode, here); 7010 } 7011 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7012 userId, andCode ? 1 : 0, packageName)); 7013 } 7014 7015 void startCleaningPackages() { 7016 // reader 7017 synchronized (mPackages) { 7018 if (!isExternalMediaAvailable()) { 7019 return; 7020 } 7021 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7022 return; 7023 } 7024 } 7025 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7026 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7027 IActivityManager am = ActivityManagerNative.getDefault(); 7028 if (am != null) { 7029 try { 7030 am.startService(null, intent, null, UserHandle.USER_OWNER); 7031 } catch (RemoteException e) { 7032 } 7033 } 7034 } 7035 7036 private final class AppDirObserver extends FileObserver { 7037 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7038 super(path, mask); 7039 mRootDir = path; 7040 mIsRom = isrom; 7041 mIsPrivileged = isPrivileged; 7042 } 7043 7044 public void onEvent(int event, String path) { 7045 String removedPackage = null; 7046 int removedAppId = -1; 7047 int[] removedUsers = null; 7048 String addedPackage = null; 7049 int addedAppId = -1; 7050 int[] addedUsers = null; 7051 7052 // TODO post a message to the handler to obtain serial ordering 7053 synchronized (mInstallLock) { 7054 String fullPathStr = null; 7055 File fullPath = null; 7056 if (path != null) { 7057 fullPath = new File(mRootDir, path); 7058 fullPathStr = fullPath.getPath(); 7059 } 7060 7061 if (DEBUG_APP_DIR_OBSERVER) 7062 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7063 7064 if (!isPackageFilename(path)) { 7065 if (DEBUG_APP_DIR_OBSERVER) 7066 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7067 return; 7068 } 7069 7070 // Ignore packages that are being installed or 7071 // have just been installed. 7072 if (ignoreCodePath(fullPathStr)) { 7073 return; 7074 } 7075 PackageParser.Package p = null; 7076 PackageSetting ps = null; 7077 // reader 7078 synchronized (mPackages) { 7079 p = mAppDirs.get(fullPathStr); 7080 if (p != null) { 7081 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7082 if (ps != null) { 7083 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7084 } else { 7085 removedUsers = sUserManager.getUserIds(); 7086 } 7087 } 7088 addedUsers = sUserManager.getUserIds(); 7089 } 7090 if ((event&REMOVE_EVENTS) != 0) { 7091 if (ps != null) { 7092 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7093 removePackageLI(ps, true); 7094 removedPackage = ps.name; 7095 removedAppId = ps.appId; 7096 } 7097 } 7098 7099 if ((event&ADD_EVENTS) != 0) { 7100 if (p == null) { 7101 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7102 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7103 if (mIsRom) { 7104 flags |= PackageParser.PARSE_IS_SYSTEM 7105 | PackageParser.PARSE_IS_SYSTEM_DIR; 7106 if (mIsPrivileged) { 7107 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7108 } 7109 } 7110 p = scanPackageLI(fullPath, flags, 7111 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7112 System.currentTimeMillis(), UserHandle.ALL); 7113 if (p != null) { 7114 /* 7115 * TODO this seems dangerous as the package may have 7116 * changed since we last acquired the mPackages 7117 * lock. 7118 */ 7119 // writer 7120 synchronized (mPackages) { 7121 updatePermissionsLPw(p.packageName, p, 7122 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7123 } 7124 addedPackage = p.applicationInfo.packageName; 7125 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7126 } 7127 } 7128 } 7129 7130 // reader 7131 synchronized (mPackages) { 7132 mSettings.writeLPr(); 7133 } 7134 } 7135 7136 if (removedPackage != null) { 7137 Bundle extras = new Bundle(1); 7138 extras.putInt(Intent.EXTRA_UID, removedAppId); 7139 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7140 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7141 extras, null, null, removedUsers); 7142 } 7143 if (addedPackage != null) { 7144 Bundle extras = new Bundle(1); 7145 extras.putInt(Intent.EXTRA_UID, addedAppId); 7146 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7147 extras, null, null, addedUsers); 7148 } 7149 } 7150 7151 private final String mRootDir; 7152 private final boolean mIsRom; 7153 private final boolean mIsPrivileged; 7154 } 7155 7156 /* 7157 * The old-style observer methods all just trampoline to the newer signature with 7158 * expanded install observer API. The older API continues to work but does not 7159 * supply the additional details of the Observer2 API. 7160 */ 7161 7162 /* Called when a downloaded package installation has been confirmed by the user */ 7163 public void installPackage( 7164 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 7165 installPackageEtc(packageURI, observer, null, flags, null); 7166 } 7167 7168 /* Called when a downloaded package installation has been confirmed by the user */ 7169 public void installPackage( 7170 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 7171 final String installerPackageName) { 7172 installPackageWithVerificationEtc(packageURI, observer, null, flags, 7173 installerPackageName, null, null, null); 7174 } 7175 7176 @Override 7177 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 7178 int flags, String installerPackageName, Uri verificationURI, 7179 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7180 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7181 VerificationParams.NO_UID, manifestDigest); 7182 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7183 installerPackageName, verificationParams, encryptionParams); 7184 } 7185 7186 public void installPackageWithVerificationAndEncryption(Uri packageURI, 7187 IPackageInstallObserver observer, int flags, String installerPackageName, 7188 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7189 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7190 installerPackageName, verificationParams, encryptionParams); 7191 } 7192 7193 /* 7194 * And here are the "live" versions that take both observer arguments 7195 */ 7196 public void installPackageEtc( 7197 final Uri packageURI, final IPackageInstallObserver observer, 7198 IPackageInstallObserver2 observer2, final int flags) { 7199 installPackageEtc(packageURI, observer, observer2, flags, null); 7200 } 7201 7202 public void installPackageEtc( 7203 final Uri packageURI, final IPackageInstallObserver observer, 7204 final IPackageInstallObserver2 observer2, final int flags, 7205 final String installerPackageName) { 7206 installPackageWithVerificationEtc(packageURI, observer, observer2, flags, 7207 installerPackageName, null, null, null); 7208 } 7209 7210 @Override 7211 public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer, 7212 IPackageInstallObserver2 observer2, 7213 int flags, String installerPackageName, Uri verificationURI, 7214 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7215 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7216 VerificationParams.NO_UID, manifestDigest); 7217 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags, 7218 installerPackageName, verificationParams, encryptionParams); 7219 } 7220 7221 /* 7222 * All of the installPackage...*() methods redirect to this one for the master implementation 7223 */ 7224 public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI, 7225 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7226 int flags, String installerPackageName, 7227 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7228 if (observer == null && observer2 == null) { 7229 throw new IllegalArgumentException("No install observer supplied"); 7230 } 7231 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7232 null); 7233 7234 final int uid = Binder.getCallingUid(); 7235 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7236 try { 7237 if (observer != null) { 7238 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7239 } 7240 if (observer2 != null) { 7241 observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7242 } 7243 } catch (RemoteException re) { 7244 } 7245 return; 7246 } 7247 7248 UserHandle user; 7249 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7250 user = UserHandle.ALL; 7251 } else { 7252 user = new UserHandle(UserHandle.getUserId(uid)); 7253 } 7254 7255 final int filteredFlags; 7256 7257 if (uid == Process.SHELL_UID || uid == 0) { 7258 if (DEBUG_INSTALL) { 7259 Slog.v(TAG, "Install from ADB"); 7260 } 7261 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7262 } else { 7263 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7264 } 7265 7266 verificationParams.setInstallerUid(uid); 7267 7268 final Message msg = mHandler.obtainMessage(INIT_COPY); 7269 msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags, 7270 installerPackageName, verificationParams, encryptionParams, user); 7271 mHandler.sendMessage(msg); 7272 } 7273 7274 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7275 Bundle extras = new Bundle(1); 7276 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7277 7278 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7279 packageName, extras, null, null, new int[] {userId}); 7280 try { 7281 IActivityManager am = ActivityManagerNative.getDefault(); 7282 final boolean isSystem = 7283 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7284 if (isSystem && am.isUserRunning(userId, false)) { 7285 // The just-installed/enabled app is bundled on the system, so presumed 7286 // to be able to run automatically without needing an explicit launch. 7287 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7288 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7289 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7290 .setPackage(packageName); 7291 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7292 android.app.AppOpsManager.OP_NONE, false, false, userId); 7293 } 7294 } catch (RemoteException e) { 7295 // shouldn't happen 7296 Slog.w(TAG, "Unable to bootstrap installed package", e); 7297 } 7298 } 7299 7300 @Override 7301 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7302 int userId) { 7303 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7304 PackageSetting pkgSetting; 7305 final int uid = Binder.getCallingUid(); 7306 if (UserHandle.getUserId(uid) != userId) { 7307 mContext.enforceCallingOrSelfPermission( 7308 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7309 "setApplicationBlockedSetting for user " + userId); 7310 } 7311 7312 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7313 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7314 return false; 7315 } 7316 7317 long callingId = Binder.clearCallingIdentity(); 7318 try { 7319 boolean sendAdded = false; 7320 boolean sendRemoved = false; 7321 // writer 7322 synchronized (mPackages) { 7323 pkgSetting = mSettings.mPackages.get(packageName); 7324 if (pkgSetting == null) { 7325 return false; 7326 } 7327 if (pkgSetting.getBlocked(userId) != blocked) { 7328 pkgSetting.setBlocked(blocked, userId); 7329 mSettings.writePackageRestrictionsLPr(userId); 7330 if (blocked) { 7331 sendRemoved = true; 7332 } else { 7333 sendAdded = true; 7334 } 7335 } 7336 } 7337 if (sendAdded) { 7338 sendPackageAddedForUser(packageName, pkgSetting, userId); 7339 return true; 7340 } 7341 if (sendRemoved) { 7342 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7343 "blocking pkg"); 7344 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7345 } 7346 } finally { 7347 Binder.restoreCallingIdentity(callingId); 7348 } 7349 return false; 7350 } 7351 7352 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7353 int userId) { 7354 final PackageRemovedInfo info = new PackageRemovedInfo(); 7355 info.removedPackage = packageName; 7356 info.removedUsers = new int[] {userId}; 7357 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7358 info.sendBroadcast(false, false, false); 7359 } 7360 7361 /** 7362 * Returns true if application is not found or there was an error. Otherwise it returns 7363 * the blocked state of the package for the given user. 7364 */ 7365 @Override 7366 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7367 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7368 PackageSetting pkgSetting; 7369 final int uid = Binder.getCallingUid(); 7370 if (UserHandle.getUserId(uid) != userId) { 7371 mContext.enforceCallingPermission( 7372 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7373 "getApplicationBlocked for user " + userId); 7374 } 7375 long callingId = Binder.clearCallingIdentity(); 7376 try { 7377 // writer 7378 synchronized (mPackages) { 7379 pkgSetting = mSettings.mPackages.get(packageName); 7380 if (pkgSetting == null) { 7381 return true; 7382 } 7383 return pkgSetting.getBlocked(userId); 7384 } 7385 } finally { 7386 Binder.restoreCallingIdentity(callingId); 7387 } 7388 } 7389 7390 /** 7391 * @hide 7392 */ 7393 @Override 7394 public int installExistingPackageAsUser(String packageName, int userId) { 7395 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7396 null); 7397 PackageSetting pkgSetting; 7398 final int uid = Binder.getCallingUid(); 7399 if (UserHandle.getUserId(uid) != userId) { 7400 mContext.enforceCallingPermission( 7401 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7402 "installExistingPackage for user " + userId); 7403 } 7404 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7405 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7406 } 7407 7408 long callingId = Binder.clearCallingIdentity(); 7409 try { 7410 boolean sendAdded = false; 7411 Bundle extras = new Bundle(1); 7412 7413 // writer 7414 synchronized (mPackages) { 7415 pkgSetting = mSettings.mPackages.get(packageName); 7416 if (pkgSetting == null) { 7417 return PackageManager.INSTALL_FAILED_INVALID_URI; 7418 } 7419 if (!pkgSetting.getInstalled(userId)) { 7420 pkgSetting.setInstalled(true, userId); 7421 pkgSetting.setBlocked(false, userId); 7422 mSettings.writePackageRestrictionsLPr(userId); 7423 sendAdded = true; 7424 } 7425 } 7426 7427 if (sendAdded) { 7428 sendPackageAddedForUser(packageName, pkgSetting, userId); 7429 } 7430 } finally { 7431 Binder.restoreCallingIdentity(callingId); 7432 } 7433 7434 return PackageManager.INSTALL_SUCCEEDED; 7435 } 7436 7437 private boolean isUserRestricted(int userId, String restrictionKey) { 7438 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7439 if (restrictions.getBoolean(restrictionKey, false)) { 7440 Log.w(TAG, "User is restricted: " + restrictionKey); 7441 return true; 7442 } 7443 return false; 7444 } 7445 7446 @Override 7447 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7448 mContext.enforceCallingOrSelfPermission( 7449 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7450 "Only package verification agents can verify applications"); 7451 7452 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7453 final PackageVerificationResponse response = new PackageVerificationResponse( 7454 verificationCode, Binder.getCallingUid()); 7455 msg.arg1 = id; 7456 msg.obj = response; 7457 mHandler.sendMessage(msg); 7458 } 7459 7460 @Override 7461 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7462 long millisecondsToDelay) { 7463 mContext.enforceCallingOrSelfPermission( 7464 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7465 "Only package verification agents can extend verification timeouts"); 7466 7467 final PackageVerificationState state = mPendingVerification.get(id); 7468 final PackageVerificationResponse response = new PackageVerificationResponse( 7469 verificationCodeAtTimeout, Binder.getCallingUid()); 7470 7471 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7472 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7473 } 7474 if (millisecondsToDelay < 0) { 7475 millisecondsToDelay = 0; 7476 } 7477 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7478 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7479 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7480 } 7481 7482 if ((state != null) && !state.timeoutExtended()) { 7483 state.extendTimeout(); 7484 7485 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7486 msg.arg1 = id; 7487 msg.obj = response; 7488 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7489 } 7490 } 7491 7492 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7493 int verificationCode, UserHandle user) { 7494 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7495 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7496 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7497 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7498 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7499 7500 mContext.sendBroadcastAsUser(intent, user, 7501 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7502 } 7503 7504 private ComponentName matchComponentForVerifier(String packageName, 7505 List<ResolveInfo> receivers) { 7506 ActivityInfo targetReceiver = null; 7507 7508 final int NR = receivers.size(); 7509 for (int i = 0; i < NR; i++) { 7510 final ResolveInfo info = receivers.get(i); 7511 if (info.activityInfo == null) { 7512 continue; 7513 } 7514 7515 if (packageName.equals(info.activityInfo.packageName)) { 7516 targetReceiver = info.activityInfo; 7517 break; 7518 } 7519 } 7520 7521 if (targetReceiver == null) { 7522 return null; 7523 } 7524 7525 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 7526 } 7527 7528 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 7529 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 7530 if (pkgInfo.verifiers.length == 0) { 7531 return null; 7532 } 7533 7534 final int N = pkgInfo.verifiers.length; 7535 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 7536 for (int i = 0; i < N; i++) { 7537 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 7538 7539 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 7540 receivers); 7541 if (comp == null) { 7542 continue; 7543 } 7544 7545 final int verifierUid = getUidForVerifier(verifierInfo); 7546 if (verifierUid == -1) { 7547 continue; 7548 } 7549 7550 if (DEBUG_VERIFY) { 7551 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 7552 + " with the correct signature"); 7553 } 7554 sufficientVerifiers.add(comp); 7555 verificationState.addSufficientVerifier(verifierUid); 7556 } 7557 7558 return sufficientVerifiers; 7559 } 7560 7561 private int getUidForVerifier(VerifierInfo verifierInfo) { 7562 synchronized (mPackages) { 7563 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 7564 if (pkg == null) { 7565 return -1; 7566 } else if (pkg.mSignatures.length != 1) { 7567 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7568 + " has more than one signature; ignoring"); 7569 return -1; 7570 } 7571 7572 /* 7573 * If the public key of the package's signature does not match 7574 * our expected public key, then this is a different package and 7575 * we should skip. 7576 */ 7577 7578 final byte[] expectedPublicKey; 7579 try { 7580 final Signature verifierSig = pkg.mSignatures[0]; 7581 final PublicKey publicKey = verifierSig.getPublicKey(); 7582 expectedPublicKey = publicKey.getEncoded(); 7583 } catch (CertificateException e) { 7584 return -1; 7585 } 7586 7587 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 7588 7589 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 7590 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7591 + " does not have the expected public key; ignoring"); 7592 return -1; 7593 } 7594 7595 return pkg.applicationInfo.uid; 7596 } 7597 } 7598 7599 public void finishPackageInstall(int token) { 7600 enforceSystemOrRoot("Only the system is allowed to finish installs"); 7601 7602 if (DEBUG_INSTALL) { 7603 Slog.v(TAG, "BM finishing package install for " + token); 7604 } 7605 7606 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 7607 mHandler.sendMessage(msg); 7608 } 7609 7610 /** 7611 * Get the verification agent timeout. 7612 * 7613 * @return verification timeout in milliseconds 7614 */ 7615 private long getVerificationTimeout() { 7616 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 7617 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 7618 DEFAULT_VERIFICATION_TIMEOUT); 7619 } 7620 7621 /** 7622 * Get the default verification agent response code. 7623 * 7624 * @return default verification response code 7625 */ 7626 private int getDefaultVerificationResponse() { 7627 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7628 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 7629 DEFAULT_VERIFICATION_RESPONSE); 7630 } 7631 7632 /** 7633 * Check whether or not package verification has been enabled. 7634 * 7635 * @return true if verification should be performed 7636 */ 7637 private boolean isVerificationEnabled(int flags) { 7638 if (!DEFAULT_VERIFY_ENABLE) { 7639 return false; 7640 } 7641 7642 // Check if installing from ADB 7643 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 7644 // Do not run verification in a test harness environment 7645 if (ActivityManager.isRunningInTestHarness()) { 7646 return false; 7647 } 7648 // Check if the developer does not want package verification for ADB installs 7649 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7650 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 7651 return false; 7652 } 7653 } 7654 7655 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7656 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 7657 } 7658 7659 /** 7660 * Get the "allow unknown sources" setting. 7661 * 7662 * @return the current "allow unknown sources" setting 7663 */ 7664 private int getUnknownSourcesSettings() { 7665 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7666 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 7667 -1); 7668 } 7669 7670 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 7671 final int uid = Binder.getCallingUid(); 7672 // writer 7673 synchronized (mPackages) { 7674 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 7675 if (targetPackageSetting == null) { 7676 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 7677 } 7678 7679 PackageSetting installerPackageSetting; 7680 if (installerPackageName != null) { 7681 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 7682 if (installerPackageSetting == null) { 7683 throw new IllegalArgumentException("Unknown installer package: " 7684 + installerPackageName); 7685 } 7686 } else { 7687 installerPackageSetting = null; 7688 } 7689 7690 Signature[] callerSignature; 7691 Object obj = mSettings.getUserIdLPr(uid); 7692 if (obj != null) { 7693 if (obj instanceof SharedUserSetting) { 7694 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 7695 } else if (obj instanceof PackageSetting) { 7696 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 7697 } else { 7698 throw new SecurityException("Bad object " + obj + " for uid " + uid); 7699 } 7700 } else { 7701 throw new SecurityException("Unknown calling uid " + uid); 7702 } 7703 7704 // Verify: can't set installerPackageName to a package that is 7705 // not signed with the same cert as the caller. 7706 if (installerPackageSetting != null) { 7707 if (compareSignatures(callerSignature, 7708 installerPackageSetting.signatures.mSignatures) 7709 != PackageManager.SIGNATURE_MATCH) { 7710 throw new SecurityException( 7711 "Caller does not have same cert as new installer package " 7712 + installerPackageName); 7713 } 7714 } 7715 7716 // Verify: if target already has an installer package, it must 7717 // be signed with the same cert as the caller. 7718 if (targetPackageSetting.installerPackageName != null) { 7719 PackageSetting setting = mSettings.mPackages.get( 7720 targetPackageSetting.installerPackageName); 7721 // If the currently set package isn't valid, then it's always 7722 // okay to change it. 7723 if (setting != null) { 7724 if (compareSignatures(callerSignature, 7725 setting.signatures.mSignatures) 7726 != PackageManager.SIGNATURE_MATCH) { 7727 throw new SecurityException( 7728 "Caller does not have same cert as old installer package " 7729 + targetPackageSetting.installerPackageName); 7730 } 7731 } 7732 } 7733 7734 // Okay! 7735 targetPackageSetting.installerPackageName = installerPackageName; 7736 scheduleWriteSettingsLocked(); 7737 } 7738 } 7739 7740 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 7741 // Queue up an async operation since the package installation may take a little while. 7742 mHandler.post(new Runnable() { 7743 public void run() { 7744 mHandler.removeCallbacks(this); 7745 // Result object to be returned 7746 PackageInstalledInfo res = new PackageInstalledInfo(); 7747 res.returnCode = currentStatus; 7748 res.uid = -1; 7749 res.pkg = null; 7750 res.removedInfo = new PackageRemovedInfo(); 7751 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 7752 args.doPreInstall(res.returnCode); 7753 synchronized (mInstallLock) { 7754 installPackageLI(args, true, res); 7755 } 7756 args.doPostInstall(res.returnCode, res.uid); 7757 } 7758 7759 // A restore should be performed at this point if (a) the install 7760 // succeeded, (b) the operation is not an update, and (c) the new 7761 // package has a backupAgent defined. 7762 final boolean update = res.removedInfo.removedPackage != null; 7763 boolean doRestore = (!update 7764 && res.pkg != null 7765 && res.pkg.applicationInfo.backupAgentName != null); 7766 7767 // Set up the post-install work request bookkeeping. This will be used 7768 // and cleaned up by the post-install event handling regardless of whether 7769 // there's a restore pass performed. Token values are >= 1. 7770 int token; 7771 if (mNextInstallToken < 0) mNextInstallToken = 1; 7772 token = mNextInstallToken++; 7773 7774 PostInstallData data = new PostInstallData(args, res); 7775 mRunningInstalls.put(token, data); 7776 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 7777 7778 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 7779 // Pass responsibility to the Backup Manager. It will perform a 7780 // restore if appropriate, then pass responsibility back to the 7781 // Package Manager to run the post-install observer callbacks 7782 // and broadcasts. 7783 IBackupManager bm = IBackupManager.Stub.asInterface( 7784 ServiceManager.getService(Context.BACKUP_SERVICE)); 7785 if (bm != null) { 7786 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 7787 + " to BM for possible restore"); 7788 try { 7789 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 7790 } catch (RemoteException e) { 7791 // can't happen; the backup manager is local 7792 } catch (Exception e) { 7793 Slog.e(TAG, "Exception trying to enqueue restore", e); 7794 doRestore = false; 7795 } 7796 } else { 7797 Slog.e(TAG, "Backup Manager not found!"); 7798 doRestore = false; 7799 } 7800 } 7801 7802 if (!doRestore) { 7803 // No restore possible, or the Backup Manager was mysteriously not 7804 // available -- just fire the post-install work request directly. 7805 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 7806 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 7807 mHandler.sendMessage(msg); 7808 } 7809 } 7810 }); 7811 } 7812 7813 private abstract class HandlerParams { 7814 private static final int MAX_RETRIES = 4; 7815 7816 /** 7817 * Number of times startCopy() has been attempted and had a non-fatal 7818 * error. 7819 */ 7820 private int mRetries = 0; 7821 7822 /** User handle for the user requesting the information or installation. */ 7823 private final UserHandle mUser; 7824 7825 HandlerParams(UserHandle user) { 7826 mUser = user; 7827 } 7828 7829 UserHandle getUser() { 7830 return mUser; 7831 } 7832 7833 final boolean startCopy() { 7834 boolean res; 7835 try { 7836 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 7837 7838 if (++mRetries > MAX_RETRIES) { 7839 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 7840 mHandler.sendEmptyMessage(MCS_GIVE_UP); 7841 handleServiceError(); 7842 return false; 7843 } else { 7844 handleStartCopy(); 7845 res = true; 7846 } 7847 } catch (RemoteException e) { 7848 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 7849 mHandler.sendEmptyMessage(MCS_RECONNECT); 7850 res = false; 7851 } 7852 handleReturnCode(); 7853 return res; 7854 } 7855 7856 final void serviceError() { 7857 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 7858 handleServiceError(); 7859 handleReturnCode(); 7860 } 7861 7862 abstract void handleStartCopy() throws RemoteException; 7863 abstract void handleServiceError(); 7864 abstract void handleReturnCode(); 7865 } 7866 7867 class MeasureParams extends HandlerParams { 7868 private final PackageStats mStats; 7869 private boolean mSuccess; 7870 7871 private final IPackageStatsObserver mObserver; 7872 7873 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 7874 super(new UserHandle(stats.userHandle)); 7875 mObserver = observer; 7876 mStats = stats; 7877 } 7878 7879 @Override 7880 public String toString() { 7881 return "MeasureParams{" 7882 + Integer.toHexString(System.identityHashCode(this)) 7883 + " " + mStats.packageName + "}"; 7884 } 7885 7886 @Override 7887 void handleStartCopy() throws RemoteException { 7888 synchronized (mInstallLock) { 7889 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 7890 } 7891 7892 if (mSuccess) { 7893 final boolean mounted; 7894 if (Environment.isExternalStorageEmulated()) { 7895 mounted = true; 7896 } else { 7897 final String status = Environment.getExternalStorageState(); 7898 mounted = (Environment.MEDIA_MOUNTED.equals(status) 7899 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 7900 } 7901 7902 if (mounted) { 7903 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 7904 7905 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 7906 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 7907 7908 mStats.externalDataSize = calculateDirectorySize(mContainerService, 7909 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 7910 7911 // Always subtract cache size, since it's a subdirectory 7912 mStats.externalDataSize -= mStats.externalCacheSize; 7913 7914 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 7915 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 7916 7917 mStats.externalObbSize = calculateDirectorySize(mContainerService, 7918 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 7919 } 7920 } 7921 } 7922 7923 @Override 7924 void handleReturnCode() { 7925 if (mObserver != null) { 7926 try { 7927 mObserver.onGetStatsCompleted(mStats, mSuccess); 7928 } catch (RemoteException e) { 7929 Slog.i(TAG, "Observer no longer exists."); 7930 } 7931 } 7932 } 7933 7934 @Override 7935 void handleServiceError() { 7936 Slog.e(TAG, "Could not measure application " + mStats.packageName 7937 + " external storage"); 7938 } 7939 } 7940 7941 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 7942 throws RemoteException { 7943 long result = 0; 7944 for (File path : paths) { 7945 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 7946 } 7947 return result; 7948 } 7949 7950 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 7951 for (File path : paths) { 7952 try { 7953 mcs.clearDirectory(path.getAbsolutePath()); 7954 } catch (RemoteException e) { 7955 } 7956 } 7957 } 7958 7959 class InstallParams extends HandlerParams { 7960 final IPackageInstallObserver observer; 7961 final IPackageInstallObserver2 observer2; 7962 int flags; 7963 7964 private final Uri mPackageURI; 7965 final String installerPackageName; 7966 final VerificationParams verificationParams; 7967 private InstallArgs mArgs; 7968 private int mRet; 7969 private File mTempPackage; 7970 final ContainerEncryptionParams encryptionParams; 7971 7972 InstallParams(Uri packageURI, 7973 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7974 int flags, String installerPackageName, VerificationParams verificationParams, 7975 ContainerEncryptionParams encryptionParams, UserHandle user) { 7976 super(user); 7977 this.mPackageURI = packageURI; 7978 this.flags = flags; 7979 this.observer = observer; 7980 this.observer2 = observer2; 7981 this.installerPackageName = installerPackageName; 7982 this.verificationParams = verificationParams; 7983 this.encryptionParams = encryptionParams; 7984 } 7985 7986 @Override 7987 public String toString() { 7988 return "InstallParams{" 7989 + Integer.toHexString(System.identityHashCode(this)) 7990 + " " + mPackageURI + "}"; 7991 } 7992 7993 public ManifestDigest getManifestDigest() { 7994 if (verificationParams == null) { 7995 return null; 7996 } 7997 return verificationParams.getManifestDigest(); 7998 } 7999 8000 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8001 String packageName = pkgLite.packageName; 8002 int installLocation = pkgLite.installLocation; 8003 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8004 // reader 8005 synchronized (mPackages) { 8006 PackageParser.Package pkg = mPackages.get(packageName); 8007 if (pkg != null) { 8008 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8009 // Check for downgrading. 8010 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8011 if (pkgLite.versionCode < pkg.mVersionCode) { 8012 Slog.w(TAG, "Can't install update of " + packageName 8013 + " update version " + pkgLite.versionCode 8014 + " is older than installed version " 8015 + pkg.mVersionCode); 8016 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8017 } 8018 } 8019 // Check for updated system application. 8020 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8021 if (onSd) { 8022 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8023 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8024 } 8025 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8026 } else { 8027 if (onSd) { 8028 // Install flag overrides everything. 8029 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8030 } 8031 // If current upgrade specifies particular preference 8032 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8033 // Application explicitly specified internal. 8034 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8035 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8036 // App explictly prefers external. Let policy decide 8037 } else { 8038 // Prefer previous location 8039 if (isExternal(pkg)) { 8040 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8041 } 8042 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8043 } 8044 } 8045 } else { 8046 // Invalid install. Return error code 8047 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8048 } 8049 } 8050 } 8051 // All the special cases have been taken care of. 8052 // Return result based on recommended install location. 8053 if (onSd) { 8054 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8055 } 8056 return pkgLite.recommendedInstallLocation; 8057 } 8058 8059 private long getMemoryLowThreshold() { 8060 final DeviceStorageMonitorInternal 8061 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8062 if (dsm == null) { 8063 return 0L; 8064 } 8065 return dsm.getMemoryLowThreshold(); 8066 } 8067 8068 /* 8069 * Invoke remote method to get package information and install 8070 * location values. Override install location based on default 8071 * policy if needed and then create install arguments based 8072 * on the install location. 8073 */ 8074 public void handleStartCopy() throws RemoteException { 8075 int ret = PackageManager.INSTALL_SUCCEEDED; 8076 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8077 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8078 PackageInfoLite pkgLite = null; 8079 8080 if (onInt && onSd) { 8081 // Check if both bits are set. 8082 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8083 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8084 } else { 8085 final long lowThreshold = getMemoryLowThreshold(); 8086 if (lowThreshold == 0L) { 8087 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8088 } 8089 8090 try { 8091 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI, 8092 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8093 8094 final File packageFile; 8095 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) { 8096 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir); 8097 if (mTempPackage != null) { 8098 ParcelFileDescriptor out; 8099 try { 8100 out = ParcelFileDescriptor.open(mTempPackage, 8101 ParcelFileDescriptor.MODE_READ_WRITE); 8102 } catch (FileNotFoundException e) { 8103 out = null; 8104 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI); 8105 } 8106 8107 // Make a temporary file for decryption. 8108 ret = mContainerService 8109 .copyResource(mPackageURI, encryptionParams, out); 8110 IoUtils.closeQuietly(out); 8111 8112 packageFile = mTempPackage; 8113 8114 FileUtils.setPermissions(packageFile.getAbsolutePath(), 8115 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP 8116 | FileUtils.S_IROTH, 8117 -1, -1); 8118 } else { 8119 packageFile = null; 8120 } 8121 } else { 8122 packageFile = new File(mPackageURI.getPath()); 8123 } 8124 8125 if (packageFile != null) { 8126 // Remote call to find out default install location 8127 final String packageFilePath = packageFile.getAbsolutePath(); 8128 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags, 8129 lowThreshold); 8130 8131 /* 8132 * If we have too little free space, try to free cache 8133 * before giving up. 8134 */ 8135 if (pkgLite.recommendedInstallLocation 8136 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8137 final long size = mContainerService.calculateInstalledSize( 8138 packageFilePath, isForwardLocked()); 8139 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8140 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, 8141 flags, lowThreshold); 8142 } 8143 /* 8144 * The cache free must have deleted the file we 8145 * downloaded to install. 8146 * 8147 * TODO: fix the "freeCache" call to not delete 8148 * the file we care about. 8149 */ 8150 if (pkgLite.recommendedInstallLocation 8151 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8152 pkgLite.recommendedInstallLocation 8153 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8154 } 8155 } 8156 } 8157 } finally { 8158 mContext.revokeUriPermission(mPackageURI, 8159 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8160 } 8161 } 8162 8163 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8164 int loc = pkgLite.recommendedInstallLocation; 8165 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8166 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8167 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8168 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8169 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8170 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8171 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8172 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8173 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8174 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8175 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8176 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8177 } else { 8178 // Override with defaults if needed. 8179 loc = installLocationPolicy(pkgLite, flags); 8180 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8181 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8182 } else if (!onSd && !onInt) { 8183 // Override install location with flags 8184 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8185 // Set the flag to install on external media. 8186 flags |= PackageManager.INSTALL_EXTERNAL; 8187 flags &= ~PackageManager.INSTALL_INTERNAL; 8188 } else { 8189 // Make sure the flag for installing on external 8190 // media is unset 8191 flags |= PackageManager.INSTALL_INTERNAL; 8192 flags &= ~PackageManager.INSTALL_EXTERNAL; 8193 } 8194 } 8195 } 8196 } 8197 8198 final InstallArgs args = createInstallArgs(this); 8199 mArgs = args; 8200 8201 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8202 /* 8203 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8204 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8205 */ 8206 int userIdentifier = getUser().getIdentifier(); 8207 if (userIdentifier == UserHandle.USER_ALL 8208 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8209 userIdentifier = UserHandle.USER_OWNER; 8210 } 8211 8212 /* 8213 * Determine if we have any installed package verifiers. If we 8214 * do, then we'll defer to them to verify the packages. 8215 */ 8216 final int requiredUid = mRequiredVerifierPackage == null ? -1 8217 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8218 if (requiredUid != -1 && isVerificationEnabled(flags)) { 8219 final Intent verification = new Intent( 8220 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8221 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE); 8222 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8223 8224 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8225 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8226 0 /* TODO: Which userId? */); 8227 8228 if (DEBUG_VERIFY) { 8229 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8230 + verification.toString() + " with " + pkgLite.verifiers.length 8231 + " optional verifiers"); 8232 } 8233 8234 final int verificationId = mPendingVerificationToken++; 8235 8236 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8237 8238 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8239 installerPackageName); 8240 8241 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8242 8243 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8244 pkgLite.packageName); 8245 8246 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8247 pkgLite.versionCode); 8248 8249 if (verificationParams != null) { 8250 if (verificationParams.getVerificationURI() != null) { 8251 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8252 verificationParams.getVerificationURI()); 8253 } 8254 if (verificationParams.getOriginatingURI() != null) { 8255 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8256 verificationParams.getOriginatingURI()); 8257 } 8258 if (verificationParams.getReferrer() != null) { 8259 verification.putExtra(Intent.EXTRA_REFERRER, 8260 verificationParams.getReferrer()); 8261 } 8262 if (verificationParams.getOriginatingUid() >= 0) { 8263 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8264 verificationParams.getOriginatingUid()); 8265 } 8266 if (verificationParams.getInstallerUid() >= 0) { 8267 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8268 verificationParams.getInstallerUid()); 8269 } 8270 } 8271 8272 final PackageVerificationState verificationState = new PackageVerificationState( 8273 requiredUid, args); 8274 8275 mPendingVerification.append(verificationId, verificationState); 8276 8277 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8278 receivers, verificationState); 8279 8280 /* 8281 * If any sufficient verifiers were listed in the package 8282 * manifest, attempt to ask them. 8283 */ 8284 if (sufficientVerifiers != null) { 8285 final int N = sufficientVerifiers.size(); 8286 if (N == 0) { 8287 Slog.i(TAG, "Additional verifiers required, but none installed."); 8288 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8289 } else { 8290 for (int i = 0; i < N; i++) { 8291 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8292 8293 final Intent sufficientIntent = new Intent(verification); 8294 sufficientIntent.setComponent(verifierComponent); 8295 8296 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8297 } 8298 } 8299 } 8300 8301 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8302 mRequiredVerifierPackage, receivers); 8303 if (ret == PackageManager.INSTALL_SUCCEEDED 8304 && mRequiredVerifierPackage != null) { 8305 /* 8306 * Send the intent to the required verification agent, 8307 * but only start the verification timeout after the 8308 * target BroadcastReceivers have run. 8309 */ 8310 verification.setComponent(requiredVerifierComponent); 8311 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8312 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8313 new BroadcastReceiver() { 8314 @Override 8315 public void onReceive(Context context, Intent intent) { 8316 final Message msg = mHandler 8317 .obtainMessage(CHECK_PENDING_VERIFICATION); 8318 msg.arg1 = verificationId; 8319 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8320 } 8321 }, null, 0, null, null); 8322 8323 /* 8324 * We don't want the copy to proceed until verification 8325 * succeeds, so null out this field. 8326 */ 8327 mArgs = null; 8328 } 8329 } else { 8330 /* 8331 * No package verification is enabled, so immediately start 8332 * the remote call to initiate copy using temporary file. 8333 */ 8334 ret = args.copyApk(mContainerService, true); 8335 } 8336 } 8337 8338 mRet = ret; 8339 } 8340 8341 @Override 8342 void handleReturnCode() { 8343 // If mArgs is null, then MCS couldn't be reached. When it 8344 // reconnects, it will try again to install. At that point, this 8345 // will succeed. 8346 if (mArgs != null) { 8347 processPendingInstall(mArgs, mRet); 8348 8349 if (mTempPackage != null) { 8350 if (!mTempPackage.delete()) { 8351 Slog.w(TAG, "Couldn't delete temporary file: " + 8352 mTempPackage.getAbsolutePath()); 8353 } 8354 } 8355 } 8356 } 8357 8358 @Override 8359 void handleServiceError() { 8360 mArgs = createInstallArgs(this); 8361 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8362 } 8363 8364 public boolean isForwardLocked() { 8365 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8366 } 8367 8368 public Uri getPackageUri() { 8369 if (mTempPackage != null) { 8370 return Uri.fromFile(mTempPackage); 8371 } else { 8372 return mPackageURI; 8373 } 8374 } 8375 } 8376 8377 /* 8378 * Utility class used in movePackage api. 8379 * srcArgs and targetArgs are not set for invalid flags and make 8380 * sure to do null checks when invoking methods on them. 8381 * We probably want to return ErrorPrams for both failed installs 8382 * and moves. 8383 */ 8384 class MoveParams extends HandlerParams { 8385 final IPackageMoveObserver observer; 8386 final int flags; 8387 final String packageName; 8388 final InstallArgs srcArgs; 8389 final InstallArgs targetArgs; 8390 int uid; 8391 int mRet; 8392 8393 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8394 String packageName, String dataDir, String instructionSet, 8395 int uid, UserHandle user) { 8396 super(user); 8397 this.srcArgs = srcArgs; 8398 this.observer = observer; 8399 this.flags = flags; 8400 this.packageName = packageName; 8401 this.uid = uid; 8402 if (srcArgs != null) { 8403 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath())); 8404 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet); 8405 } else { 8406 targetArgs = null; 8407 } 8408 } 8409 8410 @Override 8411 public String toString() { 8412 return "MoveParams{" 8413 + Integer.toHexString(System.identityHashCode(this)) 8414 + " " + packageName + "}"; 8415 } 8416 8417 public void handleStartCopy() throws RemoteException { 8418 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8419 // Check for storage space on target medium 8420 if (!targetArgs.checkFreeStorage(mContainerService)) { 8421 Log.w(TAG, "Insufficient storage to install"); 8422 return; 8423 } 8424 8425 mRet = srcArgs.doPreCopy(); 8426 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8427 return; 8428 } 8429 8430 mRet = targetArgs.copyApk(mContainerService, false); 8431 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8432 srcArgs.doPostCopy(uid); 8433 return; 8434 } 8435 8436 mRet = srcArgs.doPostCopy(uid); 8437 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8438 return; 8439 } 8440 8441 mRet = targetArgs.doPreInstall(mRet); 8442 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8443 return; 8444 } 8445 8446 if (DEBUG_SD_INSTALL) { 8447 StringBuilder builder = new StringBuilder(); 8448 if (srcArgs != null) { 8449 builder.append("src: "); 8450 builder.append(srcArgs.getCodePath()); 8451 } 8452 if (targetArgs != null) { 8453 builder.append(" target : "); 8454 builder.append(targetArgs.getCodePath()); 8455 } 8456 Log.i(TAG, builder.toString()); 8457 } 8458 } 8459 8460 @Override 8461 void handleReturnCode() { 8462 targetArgs.doPostInstall(mRet, uid); 8463 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8464 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8465 currentStatus = PackageManager.MOVE_SUCCEEDED; 8466 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8467 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8468 } 8469 processPendingMove(this, currentStatus); 8470 } 8471 8472 @Override 8473 void handleServiceError() { 8474 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8475 } 8476 } 8477 8478 /** 8479 * Used during creation of InstallArgs 8480 * 8481 * @param flags package installation flags 8482 * @return true if should be installed on external storage 8483 */ 8484 private static boolean installOnSd(int flags) { 8485 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8486 return false; 8487 } 8488 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8489 return true; 8490 } 8491 return false; 8492 } 8493 8494 /** 8495 * Used during creation of InstallArgs 8496 * 8497 * @param flags package installation flags 8498 * @return true if should be installed as forward locked 8499 */ 8500 private static boolean installForwardLocked(int flags) { 8501 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8502 } 8503 8504 private InstallArgs createInstallArgs(InstallParams params) { 8505 if (installOnSd(params.flags) || params.isForwardLocked()) { 8506 return new AsecInstallArgs(params); 8507 } else { 8508 return new FileInstallArgs(params); 8509 } 8510 } 8511 8512 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath, 8513 String nativeLibraryPath, String instructionSet) { 8514 final boolean isInAsec; 8515 if (installOnSd(flags)) { 8516 /* Apps on SD card are always in ASEC containers. */ 8517 isInAsec = true; 8518 } else if (installForwardLocked(flags) 8519 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8520 /* 8521 * Forward-locked apps are only in ASEC containers if they're the 8522 * new style 8523 */ 8524 isInAsec = true; 8525 } else { 8526 isInAsec = false; 8527 } 8528 8529 if (isInAsec) { 8530 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8531 instructionSet, installOnSd(flags), installForwardLocked(flags)); 8532 } else { 8533 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8534 instructionSet); 8535 } 8536 } 8537 8538 // Used by package mover 8539 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir, 8540 String instructionSet) { 8541 if (installOnSd(flags) || installForwardLocked(flags)) { 8542 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/" 8543 + AsecInstallArgs.RES_FILE_NAME); 8544 return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags), 8545 installForwardLocked(flags)); 8546 } else { 8547 return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet); 8548 } 8549 } 8550 8551 static abstract class InstallArgs { 8552 final IPackageInstallObserver observer; 8553 final IPackageInstallObserver2 observer2; 8554 // Always refers to PackageManager flags only 8555 final int flags; 8556 final Uri packageURI; 8557 final String installerPackageName; 8558 final ManifestDigest manifestDigest; 8559 final UserHandle user; 8560 final String instructionSet; 8561 8562 InstallArgs(Uri packageURI, 8563 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 8564 int flags, String installerPackageName, ManifestDigest manifestDigest, 8565 UserHandle user, String instructionSet) { 8566 this.packageURI = packageURI; 8567 this.flags = flags; 8568 this.observer = observer; 8569 this.observer2 = observer2; 8570 this.installerPackageName = installerPackageName; 8571 this.manifestDigest = manifestDigest; 8572 this.user = user; 8573 this.instructionSet = instructionSet; 8574 } 8575 8576 abstract void createCopyFile(); 8577 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 8578 abstract int doPreInstall(int status); 8579 abstract boolean doRename(int status, String pkgName, String oldCodePath); 8580 8581 abstract int doPostInstall(int status, int uid); 8582 abstract String getCodePath(); 8583 abstract String getResourcePath(); 8584 abstract String getNativeLibraryPath(); 8585 // Need installer lock especially for dex file removal. 8586 abstract void cleanUpResourcesLI(); 8587 abstract boolean doPostDeleteLI(boolean delete); 8588 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 8589 8590 /** 8591 * Called before the source arguments are copied. This is used mostly 8592 * for MoveParams when it needs to read the source file to put it in the 8593 * destination. 8594 */ 8595 int doPreCopy() { 8596 return PackageManager.INSTALL_SUCCEEDED; 8597 } 8598 8599 /** 8600 * Called after the source arguments are copied. This is used mostly for 8601 * MoveParams when it needs to read the source file to put it in the 8602 * destination. 8603 * 8604 * @return 8605 */ 8606 int doPostCopy(int uid) { 8607 return PackageManager.INSTALL_SUCCEEDED; 8608 } 8609 8610 protected boolean isFwdLocked() { 8611 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8612 } 8613 8614 UserHandle getUser() { 8615 return user; 8616 } 8617 } 8618 8619 class FileInstallArgs extends InstallArgs { 8620 File installDir; 8621 String codeFileName; 8622 String resourceFileName; 8623 String libraryPath; 8624 boolean created = false; 8625 8626 FileInstallArgs(InstallParams params) { 8627 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 8628 params.installerPackageName, params.getManifestDigest(), 8629 params.getUser(), null /* instruction set */); 8630 } 8631 8632 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 8633 String instructionSet) { 8634 super(null, null, null, 0, null, null, null, instructionSet); 8635 File codeFile = new File(fullCodePath); 8636 installDir = codeFile.getParentFile(); 8637 codeFileName = fullCodePath; 8638 resourceFileName = fullResourcePath; 8639 libraryPath = nativeLibraryPath; 8640 } 8641 8642 FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) { 8643 super(packageURI, null, null, 0, null, null, null, instructionSet); 8644 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 8645 String apkName = getNextCodePath(null, pkgName, ".apk"); 8646 codeFileName = new File(installDir, apkName + ".apk").getPath(); 8647 resourceFileName = getResourcePathFromCodePath(); 8648 libraryPath = new File(mAppLibInstallDir, pkgName).getPath(); 8649 } 8650 8651 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 8652 final long lowThreshold; 8653 8654 final DeviceStorageMonitorInternal 8655 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8656 if (dsm == null) { 8657 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8658 lowThreshold = 0L; 8659 } else { 8660 if (dsm.isMemoryLow()) { 8661 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 8662 return false; 8663 } 8664 8665 lowThreshold = dsm.getMemoryLowThreshold(); 8666 } 8667 8668 try { 8669 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8670 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8671 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold); 8672 } finally { 8673 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8674 } 8675 } 8676 8677 String getCodePath() { 8678 return codeFileName; 8679 } 8680 8681 void createCopyFile() { 8682 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 8683 codeFileName = createTempPackageFile(installDir).getPath(); 8684 resourceFileName = getResourcePathFromCodePath(); 8685 libraryPath = getLibraryPathFromCodePath(); 8686 created = true; 8687 } 8688 8689 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 8690 if (temp) { 8691 // Generate temp file name 8692 createCopyFile(); 8693 } 8694 // Get a ParcelFileDescriptor to write to the output file 8695 File codeFile = new File(codeFileName); 8696 if (!created) { 8697 try { 8698 codeFile.createNewFile(); 8699 // Set permissions 8700 if (!setPermissions()) { 8701 // Failed setting permissions. 8702 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8703 } 8704 } catch (IOException e) { 8705 Slog.w(TAG, "Failed to create file " + codeFile); 8706 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8707 } 8708 } 8709 ParcelFileDescriptor out = null; 8710 try { 8711 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 8712 } catch (FileNotFoundException e) { 8713 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 8714 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8715 } 8716 // Copy the resource now 8717 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8718 try { 8719 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8720 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8721 ret = imcs.copyResource(packageURI, null, out); 8722 } finally { 8723 IoUtils.closeQuietly(out); 8724 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8725 } 8726 8727 if (isFwdLocked()) { 8728 final File destResourceFile = new File(getResourcePath()); 8729 8730 // Copy the public files 8731 try { 8732 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 8733 } catch (IOException e) { 8734 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 8735 + " forward-locked app."); 8736 destResourceFile.delete(); 8737 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8738 } 8739 } 8740 8741 final File nativeLibraryFile = new File(getNativeLibraryPath()); 8742 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath()); 8743 if (nativeLibraryFile.exists()) { 8744 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 8745 nativeLibraryFile.delete(); 8746 } 8747 try { 8748 int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile); 8749 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8750 return copyRet; 8751 } 8752 } catch (IOException e) { 8753 Slog.e(TAG, "Copying native libraries failed", e); 8754 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8755 } 8756 8757 return ret; 8758 } 8759 8760 int doPreInstall(int status) { 8761 if (status != PackageManager.INSTALL_SUCCEEDED) { 8762 cleanUp(); 8763 } 8764 return status; 8765 } 8766 8767 boolean doRename(int status, final String pkgName, String oldCodePath) { 8768 if (status != PackageManager.INSTALL_SUCCEEDED) { 8769 cleanUp(); 8770 return false; 8771 } else { 8772 final File oldCodeFile = new File(getCodePath()); 8773 final File oldResourceFile = new File(getResourcePath()); 8774 final File oldLibraryFile = new File(getNativeLibraryPath()); 8775 8776 // Rename APK file based on packageName 8777 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 8778 final File newCodeFile = new File(installDir, apkName + ".apk"); 8779 if (!oldCodeFile.renameTo(newCodeFile)) { 8780 return false; 8781 } 8782 codeFileName = newCodeFile.getPath(); 8783 8784 // Rename public resource file if it's forward-locked. 8785 final File newResFile = new File(getResourcePathFromCodePath()); 8786 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 8787 return false; 8788 } 8789 resourceFileName = newResFile.getPath(); 8790 8791 // Rename library path 8792 final File newLibraryFile = new File(getLibraryPathFromCodePath()); 8793 if (newLibraryFile.exists()) { 8794 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile); 8795 newLibraryFile.delete(); 8796 } 8797 if (!oldLibraryFile.renameTo(newLibraryFile)) { 8798 Slog.e(TAG, "Cannot rename native library directory " 8799 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath()); 8800 return false; 8801 } 8802 libraryPath = newLibraryFile.getPath(); 8803 8804 // Attempt to set permissions 8805 if (!setPermissions()) { 8806 return false; 8807 } 8808 8809 if (!SELinux.restorecon(newCodeFile)) { 8810 return false; 8811 } 8812 8813 return true; 8814 } 8815 } 8816 8817 int doPostInstall(int status, int uid) { 8818 if (status != PackageManager.INSTALL_SUCCEEDED) { 8819 cleanUp(); 8820 } 8821 return status; 8822 } 8823 8824 String getResourcePath() { 8825 return resourceFileName; 8826 } 8827 8828 private String getResourcePathFromCodePath() { 8829 final String codePath = getCodePath(); 8830 if (isFwdLocked()) { 8831 final StringBuilder sb = new StringBuilder(); 8832 8833 sb.append(mAppInstallDir.getPath()); 8834 sb.append('/'); 8835 sb.append(getApkName(codePath)); 8836 sb.append(".zip"); 8837 8838 /* 8839 * If our APK is a temporary file, mark the resource as a 8840 * temporary file as well so it can be cleaned up after 8841 * catastrophic failure. 8842 */ 8843 if (codePath.endsWith(".tmp")) { 8844 sb.append(".tmp"); 8845 } 8846 8847 return sb.toString(); 8848 } else { 8849 return codePath; 8850 } 8851 } 8852 8853 private String getLibraryPathFromCodePath() { 8854 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath(); 8855 } 8856 8857 @Override 8858 String getNativeLibraryPath() { 8859 if (libraryPath == null) { 8860 libraryPath = getLibraryPathFromCodePath(); 8861 } 8862 return libraryPath; 8863 } 8864 8865 private boolean cleanUp() { 8866 boolean ret = true; 8867 String sourceDir = getCodePath(); 8868 String publicSourceDir = getResourcePath(); 8869 if (sourceDir != null) { 8870 File sourceFile = new File(sourceDir); 8871 if (!sourceFile.exists()) { 8872 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 8873 ret = false; 8874 } 8875 // Delete application's code and resources 8876 sourceFile.delete(); 8877 } 8878 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 8879 final File publicSourceFile = new File(publicSourceDir); 8880 if (!publicSourceFile.exists()) { 8881 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 8882 } 8883 if (publicSourceFile.exists()) { 8884 publicSourceFile.delete(); 8885 } 8886 } 8887 8888 if (libraryPath != null) { 8889 File nativeLibraryFile = new File(libraryPath); 8890 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 8891 if (!nativeLibraryFile.delete()) { 8892 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath); 8893 } 8894 } 8895 8896 return ret; 8897 } 8898 8899 void cleanUpResourcesLI() { 8900 String sourceDir = getCodePath(); 8901 if (cleanUp()) { 8902 if (instructionSet == null) { 8903 throw new IllegalStateException("instructionSet == null"); 8904 } 8905 int retCode = mInstaller.rmdex(sourceDir, instructionSet); 8906 if (retCode < 0) { 8907 Slog.w(TAG, "Couldn't remove dex file for package: " 8908 + " at location " 8909 + sourceDir + ", retcode=" + retCode); 8910 // we don't consider this to be a failure of the core package deletion 8911 } 8912 } 8913 } 8914 8915 private boolean setPermissions() { 8916 // TODO Do this in a more elegant way later on. for now just a hack 8917 if (!isFwdLocked()) { 8918 final int filePermissions = 8919 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 8920 |FileUtils.S_IROTH; 8921 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 8922 if (retCode != 0) { 8923 Slog.e(TAG, "Couldn't set new package file permissions for " + 8924 getCodePath() 8925 + ". The return code was: " + retCode); 8926 // TODO Define new internal error 8927 return false; 8928 } 8929 return true; 8930 } 8931 return true; 8932 } 8933 8934 boolean doPostDeleteLI(boolean delete) { 8935 // XXX err, shouldn't we respect the delete flag? 8936 cleanUpResourcesLI(); 8937 return true; 8938 } 8939 } 8940 8941 private boolean isAsecExternal(String cid) { 8942 final String asecPath = PackageHelper.getSdFilesystem(cid); 8943 return !asecPath.startsWith(mAsecInternalPath); 8944 } 8945 8946 /** 8947 * Extract the MountService "container ID" from the full code path of an 8948 * .apk. 8949 */ 8950 static String cidFromCodePath(String fullCodePath) { 8951 int eidx = fullCodePath.lastIndexOf("/"); 8952 String subStr1 = fullCodePath.substring(0, eidx); 8953 int sidx = subStr1.lastIndexOf("/"); 8954 return subStr1.substring(sidx+1, eidx); 8955 } 8956 8957 class AsecInstallArgs extends InstallArgs { 8958 static final String RES_FILE_NAME = "pkg.apk"; 8959 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 8960 8961 String cid; 8962 String packagePath; 8963 String resourcePath; 8964 String libraryPath; 8965 8966 AsecInstallArgs(InstallParams params) { 8967 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 8968 params.installerPackageName, params.getManifestDigest(), 8969 params.getUser(), null /* instruction set */); 8970 } 8971 8972 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 8973 String instructionSet, boolean isExternal, boolean isForwardLocked) { 8974 super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 8975 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 8976 null, null, null, instructionSet); 8977 // Extract cid from fullCodePath 8978 int eidx = fullCodePath.lastIndexOf("/"); 8979 String subStr1 = fullCodePath.substring(0, eidx); 8980 int sidx = subStr1.lastIndexOf("/"); 8981 cid = subStr1.substring(sidx+1, eidx); 8982 setCachePath(subStr1); 8983 } 8984 8985 AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) { 8986 super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 8987 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 8988 null, null, null, instructionSet); 8989 this.cid = cid; 8990 setCachePath(PackageHelper.getSdDir(cid)); 8991 } 8992 8993 AsecInstallArgs(Uri packageURI, String cid, String instructionSet, 8994 boolean isExternal, boolean isForwardLocked) { 8995 super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 8996 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 8997 null, null, null, instructionSet); 8998 this.cid = cid; 8999 } 9000 9001 void createCopyFile() { 9002 cid = getTempContainerId(); 9003 } 9004 9005 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9006 try { 9007 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9008 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9009 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked()); 9010 } finally { 9011 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9012 } 9013 } 9014 9015 private final boolean isExternal() { 9016 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9017 } 9018 9019 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9020 if (temp) { 9021 createCopyFile(); 9022 } else { 9023 /* 9024 * Pre-emptively destroy the container since it's destroyed if 9025 * copying fails due to it existing anyway. 9026 */ 9027 PackageHelper.destroySdDir(cid); 9028 } 9029 9030 final String newCachePath; 9031 try { 9032 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9033 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9034 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(), 9035 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked()); 9036 } finally { 9037 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9038 } 9039 9040 if (newCachePath != null) { 9041 setCachePath(newCachePath); 9042 return PackageManager.INSTALL_SUCCEEDED; 9043 } else { 9044 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9045 } 9046 } 9047 9048 @Override 9049 String getCodePath() { 9050 return packagePath; 9051 } 9052 9053 @Override 9054 String getResourcePath() { 9055 return resourcePath; 9056 } 9057 9058 @Override 9059 String getNativeLibraryPath() { 9060 return libraryPath; 9061 } 9062 9063 int doPreInstall(int status) { 9064 if (status != PackageManager.INSTALL_SUCCEEDED) { 9065 // Destroy container 9066 PackageHelper.destroySdDir(cid); 9067 } else { 9068 boolean mounted = PackageHelper.isContainerMounted(cid); 9069 if (!mounted) { 9070 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9071 Process.SYSTEM_UID); 9072 if (newCachePath != null) { 9073 setCachePath(newCachePath); 9074 } else { 9075 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9076 } 9077 } 9078 } 9079 return status; 9080 } 9081 9082 boolean doRename(int status, final String pkgName, 9083 String oldCodePath) { 9084 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 9085 String newCachePath = null; 9086 if (PackageHelper.isContainerMounted(cid)) { 9087 // Unmount the container 9088 if (!PackageHelper.unMountSdDir(cid)) { 9089 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9090 return false; 9091 } 9092 } 9093 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9094 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9095 " which might be stale. Will try to clean up."); 9096 // Clean up the stale container and proceed to recreate. 9097 if (!PackageHelper.destroySdDir(newCacheId)) { 9098 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9099 return false; 9100 } 9101 // Successfully cleaned up stale container. Try to rename again. 9102 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9103 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9104 + " inspite of cleaning it up."); 9105 return false; 9106 } 9107 } 9108 if (!PackageHelper.isContainerMounted(newCacheId)) { 9109 Slog.w(TAG, "Mounting container " + newCacheId); 9110 newCachePath = PackageHelper.mountSdDir(newCacheId, 9111 getEncryptKey(), Process.SYSTEM_UID); 9112 } else { 9113 newCachePath = PackageHelper.getSdDir(newCacheId); 9114 } 9115 if (newCachePath == null) { 9116 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9117 return false; 9118 } 9119 Log.i(TAG, "Succesfully renamed " + cid + 9120 " to " + newCacheId + 9121 " at new path: " + newCachePath); 9122 cid = newCacheId; 9123 setCachePath(newCachePath); 9124 return true; 9125 } 9126 9127 private void setCachePath(String newCachePath) { 9128 File cachePath = new File(newCachePath); 9129 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 9130 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9131 9132 if (isFwdLocked()) { 9133 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9134 } else { 9135 resourcePath = packagePath; 9136 } 9137 } 9138 9139 int doPostInstall(int status, int uid) { 9140 if (status != PackageManager.INSTALL_SUCCEEDED) { 9141 cleanUp(); 9142 } else { 9143 final int groupOwner; 9144 final String protectedFile; 9145 if (isFwdLocked()) { 9146 groupOwner = UserHandle.getSharedAppGid(uid); 9147 protectedFile = RES_FILE_NAME; 9148 } else { 9149 groupOwner = -1; 9150 protectedFile = null; 9151 } 9152 9153 if (uid < Process.FIRST_APPLICATION_UID 9154 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9155 Slog.e(TAG, "Failed to finalize " + cid); 9156 PackageHelper.destroySdDir(cid); 9157 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9158 } 9159 9160 boolean mounted = PackageHelper.isContainerMounted(cid); 9161 if (!mounted) { 9162 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9163 } 9164 } 9165 return status; 9166 } 9167 9168 private void cleanUp() { 9169 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9170 9171 // Destroy secure container 9172 PackageHelper.destroySdDir(cid); 9173 } 9174 9175 void cleanUpResourcesLI() { 9176 String sourceFile = getCodePath(); 9177 // Remove dex file 9178 if (instructionSet == null) { 9179 throw new IllegalStateException("instructionSet == null"); 9180 } 9181 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9182 if (retCode < 0) { 9183 Slog.w(TAG, "Couldn't remove dex file for package: " 9184 + " at location " 9185 + sourceFile.toString() + ", retcode=" + retCode); 9186 // we don't consider this to be a failure of the core package deletion 9187 } 9188 cleanUp(); 9189 } 9190 9191 boolean matchContainer(String app) { 9192 if (cid.startsWith(app)) { 9193 return true; 9194 } 9195 return false; 9196 } 9197 9198 String getPackageName() { 9199 return getAsecPackageName(cid); 9200 } 9201 9202 boolean doPostDeleteLI(boolean delete) { 9203 boolean ret = false; 9204 boolean mounted = PackageHelper.isContainerMounted(cid); 9205 if (mounted) { 9206 // Unmount first 9207 ret = PackageHelper.unMountSdDir(cid); 9208 } 9209 if (ret && delete) { 9210 cleanUpResourcesLI(); 9211 } 9212 return ret; 9213 } 9214 9215 @Override 9216 int doPreCopy() { 9217 if (isFwdLocked()) { 9218 if (!PackageHelper.fixSdPermissions(cid, 9219 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9220 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9221 } 9222 } 9223 9224 return PackageManager.INSTALL_SUCCEEDED; 9225 } 9226 9227 @Override 9228 int doPostCopy(int uid) { 9229 if (isFwdLocked()) { 9230 if (uid < Process.FIRST_APPLICATION_UID 9231 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9232 RES_FILE_NAME)) { 9233 Slog.e(TAG, "Failed to finalize " + cid); 9234 PackageHelper.destroySdDir(cid); 9235 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9236 } 9237 } 9238 9239 return PackageManager.INSTALL_SUCCEEDED; 9240 } 9241 }; 9242 9243 static String getAsecPackageName(String packageCid) { 9244 int idx = packageCid.lastIndexOf("-"); 9245 if (idx == -1) { 9246 return packageCid; 9247 } 9248 return packageCid.substring(0, idx); 9249 } 9250 9251 // Utility method used to create code paths based on package name and available index. 9252 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9253 String idxStr = ""; 9254 int idx = 1; 9255 // Fall back to default value of idx=1 if prefix is not 9256 // part of oldCodePath 9257 if (oldCodePath != null) { 9258 String subStr = oldCodePath; 9259 // Drop the suffix right away 9260 if (subStr.endsWith(suffix)) { 9261 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9262 } 9263 // If oldCodePath already contains prefix find out the 9264 // ending index to either increment or decrement. 9265 int sidx = subStr.lastIndexOf(prefix); 9266 if (sidx != -1) { 9267 subStr = subStr.substring(sidx + prefix.length()); 9268 if (subStr != null) { 9269 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9270 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9271 } 9272 try { 9273 idx = Integer.parseInt(subStr); 9274 if (idx <= 1) { 9275 idx++; 9276 } else { 9277 idx--; 9278 } 9279 } catch(NumberFormatException e) { 9280 } 9281 } 9282 } 9283 } 9284 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9285 return prefix + idxStr; 9286 } 9287 9288 // Utility method used to ignore ADD/REMOVE events 9289 // by directory observer. 9290 private static boolean ignoreCodePath(String fullPathStr) { 9291 String apkName = getApkName(fullPathStr); 9292 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9293 if (idx != -1 && ((idx+1) < apkName.length())) { 9294 // Make sure the package ends with a numeral 9295 String version = apkName.substring(idx+1); 9296 try { 9297 Integer.parseInt(version); 9298 return true; 9299 } catch (NumberFormatException e) {} 9300 } 9301 return false; 9302 } 9303 9304 // Utility method that returns the relative package path with respect 9305 // to the installation directory. Like say for /data/data/com.test-1.apk 9306 // string com.test-1 is returned. 9307 static String getApkName(String codePath) { 9308 if (codePath == null) { 9309 return null; 9310 } 9311 int sidx = codePath.lastIndexOf("/"); 9312 int eidx = codePath.lastIndexOf("."); 9313 if (eidx == -1) { 9314 eidx = codePath.length(); 9315 } else if (eidx == 0) { 9316 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 9317 return null; 9318 } 9319 return codePath.substring(sidx+1, eidx); 9320 } 9321 9322 class PackageInstalledInfo { 9323 String name; 9324 int uid; 9325 // The set of users that originally had this package installed. 9326 int[] origUsers; 9327 // The set of users that now have this package installed. 9328 int[] newUsers; 9329 PackageParser.Package pkg; 9330 int returnCode; 9331 PackageRemovedInfo removedInfo; 9332 9333 // In some error cases we want to convey more info back to the observer 9334 String origPackage; 9335 String origPermission; 9336 } 9337 9338 /* 9339 * Install a non-existing package. 9340 */ 9341 private void installNewPackageLI(PackageParser.Package pkg, 9342 int parseFlags, int scanMode, UserHandle user, 9343 String installerPackageName, PackageInstalledInfo res) { 9344 // Remember this for later, in case we need to rollback this install 9345 String pkgName = pkg.packageName; 9346 9347 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9348 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9349 synchronized(mPackages) { 9350 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9351 // A package with the same name is already installed, though 9352 // it has been renamed to an older name. The package we 9353 // are trying to install should be installed as an update to 9354 // the existing one, but that has not been requested, so bail. 9355 Slog.w(TAG, "Attempt to re-install " + pkgName 9356 + " without first uninstalling package running as " 9357 + mSettings.mRenamedPackages.get(pkgName)); 9358 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9359 return; 9360 } 9361 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) { 9362 // Don't allow installation over an existing package with the same name. 9363 Slog.w(TAG, "Attempt to re-install " + pkgName 9364 + " without first uninstalling."); 9365 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9366 return; 9367 } 9368 } 9369 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9370 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9371 System.currentTimeMillis(), user); 9372 if (newPackage == null) { 9373 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9374 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9375 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9376 } 9377 } else { 9378 updateSettingsLI(newPackage, 9379 installerPackageName, 9380 null, null, 9381 res); 9382 // delete the partially installed application. the data directory will have to be 9383 // restored if it was already existing 9384 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9385 // remove package from internal structures. Note that we want deletePackageX to 9386 // delete the package data and cache directories that it created in 9387 // scanPackageLocked, unless those directories existed before we even tried to 9388 // install. 9389 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9390 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9391 res.removedInfo, true); 9392 } 9393 } 9394 } 9395 9396 private void replacePackageLI(PackageParser.Package pkg, 9397 int parseFlags, int scanMode, UserHandle user, 9398 String installerPackageName, PackageInstalledInfo res) { 9399 9400 PackageParser.Package oldPackage; 9401 String pkgName = pkg.packageName; 9402 int[] allUsers; 9403 boolean[] perUserInstalled; 9404 9405 // First find the old package info and check signatures 9406 synchronized(mPackages) { 9407 oldPackage = mPackages.get(pkgName); 9408 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9409 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9410 != PackageManager.SIGNATURE_MATCH) { 9411 Slog.w(TAG, "New package has a different signature: " + pkgName); 9412 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9413 return; 9414 } 9415 9416 // In case of rollback, remember per-user/profile install state 9417 PackageSetting ps = mSettings.mPackages.get(pkgName); 9418 allUsers = sUserManager.getUserIds(); 9419 perUserInstalled = new boolean[allUsers.length]; 9420 for (int i = 0; i < allUsers.length; i++) { 9421 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9422 } 9423 } 9424 boolean sysPkg = (isSystemApp(oldPackage)); 9425 if (sysPkg) { 9426 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9427 user, allUsers, perUserInstalled, installerPackageName, res); 9428 } else { 9429 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9430 user, allUsers, perUserInstalled, installerPackageName, res); 9431 } 9432 } 9433 9434 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9435 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9436 int[] allUsers, boolean[] perUserInstalled, 9437 String installerPackageName, PackageInstalledInfo res) { 9438 PackageParser.Package newPackage = null; 9439 String pkgName = deletedPackage.packageName; 9440 boolean deletedPkg = true; 9441 boolean updatedSettings = false; 9442 9443 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9444 + deletedPackage); 9445 long origUpdateTime; 9446 if (pkg.mExtras != null) { 9447 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9448 } else { 9449 origUpdateTime = 0; 9450 } 9451 9452 // First delete the existing package while retaining the data directory 9453 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9454 res.removedInfo, true)) { 9455 // If the existing package wasn't successfully deleted 9456 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9457 deletedPkg = false; 9458 } else { 9459 // Successfully deleted the old package. Now proceed with re-installation 9460 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9461 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9462 System.currentTimeMillis(), user); 9463 if (newPackage == null) { 9464 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9465 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9466 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9467 } 9468 } else { 9469 updateSettingsLI(newPackage, 9470 installerPackageName, 9471 allUsers, perUserInstalled, 9472 res); 9473 updatedSettings = true; 9474 } 9475 } 9476 9477 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9478 // remove package from internal structures. Note that we want deletePackageX to 9479 // delete the package data and cache directories that it created in 9480 // scanPackageLocked, unless those directories existed before we even tried to 9481 // install. 9482 if(updatedSettings) { 9483 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9484 deletePackageLI( 9485 pkgName, null, true, allUsers, perUserInstalled, 9486 PackageManager.DELETE_KEEP_DATA, 9487 res.removedInfo, true); 9488 } 9489 // Since we failed to install the new package we need to restore the old 9490 // package that we deleted. 9491 if(deletedPkg) { 9492 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9493 File restoreFile = new File(deletedPackage.mPath); 9494 // Parse old package 9495 boolean oldOnSd = isExternal(deletedPackage); 9496 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9497 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9498 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9499 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 9500 | SCAN_UPDATE_TIME; 9501 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 9502 origUpdateTime, null) == null) { 9503 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 9504 return; 9505 } 9506 // Restore of old package succeeded. Update permissions. 9507 // writer 9508 synchronized (mPackages) { 9509 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9510 UPDATE_PERMISSIONS_ALL); 9511 // can downgrade to reader 9512 mSettings.writeLPr(); 9513 } 9514 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9515 } 9516 } 9517 } 9518 9519 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9520 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9521 int[] allUsers, boolean[] perUserInstalled, 9522 String installerPackageName, PackageInstalledInfo res) { 9523 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9524 + ", old=" + deletedPackage); 9525 PackageParser.Package newPackage = null; 9526 boolean updatedSettings = false; 9527 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 9528 PackageParser.PARSE_IS_SYSTEM; 9529 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9530 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9531 } 9532 String packageName = deletedPackage.packageName; 9533 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9534 if (packageName == null) { 9535 Slog.w(TAG, "Attempt to delete null packageName."); 9536 return; 9537 } 9538 PackageParser.Package oldPkg; 9539 PackageSetting oldPkgSetting; 9540 // reader 9541 synchronized (mPackages) { 9542 oldPkg = mPackages.get(packageName); 9543 oldPkgSetting = mSettings.mPackages.get(packageName); 9544 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 9545 (oldPkgSetting == null)) { 9546 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 9547 return; 9548 } 9549 } 9550 9551 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 9552 9553 res.removedInfo.uid = oldPkg.applicationInfo.uid; 9554 res.removedInfo.removedPackage = packageName; 9555 // Remove existing system package 9556 removePackageLI(oldPkgSetting, true); 9557 // writer 9558 synchronized (mPackages) { 9559 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 9560 // We didn't need to disable the .apk as a current system package, 9561 // which means we are replacing another update that is already 9562 // installed. We need to make sure to delete the older one's .apk. 9563 res.removedInfo.args = createInstallArgs(0, 9564 deletedPackage.applicationInfo.sourceDir, 9565 deletedPackage.applicationInfo.publicSourceDir, 9566 deletedPackage.applicationInfo.nativeLibraryDir, 9567 getAppInstructionSet(deletedPackage.applicationInfo)); 9568 } else { 9569 res.removedInfo.args = null; 9570 } 9571 } 9572 9573 // Successfully disabled the old package. Now proceed with re-installation 9574 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9575 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9576 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user); 9577 if (newPackage == null) { 9578 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9579 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9580 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9581 } 9582 } else { 9583 if (newPackage.mExtras != null) { 9584 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 9585 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 9586 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 9587 9588 // is the update attempting to change shared user? that isn't going to work... 9589 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 9590 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 9591 + " to " + newPkgSetting.sharedUser); 9592 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 9593 updatedSettings = true; 9594 } 9595 } 9596 9597 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9598 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9599 updatedSettings = true; 9600 } 9601 } 9602 9603 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9604 // Re installation failed. Restore old information 9605 // Remove new pkg information 9606 if (newPackage != null) { 9607 removeInstalledPackageLI(newPackage, true); 9608 } 9609 // Add back the old system package 9610 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user); 9611 // Restore the old system information in Settings 9612 synchronized(mPackages) { 9613 if (updatedSettings) { 9614 mSettings.enableSystemPackageLPw(packageName); 9615 mSettings.setInstallerPackageName(packageName, 9616 oldPkgSetting.installerPackageName); 9617 } 9618 mSettings.writeLPr(); 9619 } 9620 } 9621 } 9622 9623 // Utility method used to move dex files during install. 9624 private int moveDexFilesLI(PackageParser.Package newPackage) { 9625 int retCode; 9626 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 9627 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath, 9628 getAppInstructionSet(newPackage.applicationInfo)); 9629 if (retCode != 0) { 9630 if (mNoDexOpt) { 9631 /* 9632 * If we're in an engineering build, programs are lazily run 9633 * through dexopt. If the .dex file doesn't exist yet, it 9634 * will be created when the program is run next. 9635 */ 9636 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath); 9637 } else { 9638 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath); 9639 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9640 } 9641 } 9642 } 9643 return PackageManager.INSTALL_SUCCEEDED; 9644 } 9645 9646 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 9647 int[] allUsers, boolean[] perUserInstalled, 9648 PackageInstalledInfo res) { 9649 String pkgName = newPackage.packageName; 9650 synchronized (mPackages) { 9651 //write settings. the installStatus will be incomplete at this stage. 9652 //note that the new package setting would have already been 9653 //added to mPackages. It hasn't been persisted yet. 9654 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 9655 mSettings.writeLPr(); 9656 } 9657 9658 if ((res.returnCode = moveDexFilesLI(newPackage)) 9659 != PackageManager.INSTALL_SUCCEEDED) { 9660 // Discontinue if moving dex files failed. 9661 return; 9662 } 9663 9664 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath); 9665 9666 synchronized (mPackages) { 9667 updatePermissionsLPw(newPackage.packageName, newPackage, 9668 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 9669 ? UPDATE_PERMISSIONS_ALL : 0)); 9670 // For system-bundled packages, we assume that installing an upgraded version 9671 // of the package implies that the user actually wants to run that new code, 9672 // so we enable the package. 9673 if (isSystemApp(newPackage)) { 9674 // NB: implicit assumption that system package upgrades apply to all users 9675 if (DEBUG_INSTALL) { 9676 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 9677 } 9678 PackageSetting ps = mSettings.mPackages.get(pkgName); 9679 if (ps != null) { 9680 if (res.origUsers != null) { 9681 for (int userHandle : res.origUsers) { 9682 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 9683 userHandle, installerPackageName); 9684 } 9685 } 9686 // Also convey the prior install/uninstall state 9687 if (allUsers != null && perUserInstalled != null) { 9688 for (int i = 0; i < allUsers.length; i++) { 9689 if (DEBUG_INSTALL) { 9690 Slog.d(TAG, " user " + allUsers[i] 9691 + " => " + perUserInstalled[i]); 9692 } 9693 ps.setInstalled(perUserInstalled[i], allUsers[i]); 9694 } 9695 // these install state changes will be persisted in the 9696 // upcoming call to mSettings.writeLPr(). 9697 } 9698 } 9699 } 9700 res.name = pkgName; 9701 res.uid = newPackage.applicationInfo.uid; 9702 res.pkg = newPackage; 9703 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 9704 mSettings.setInstallerPackageName(pkgName, installerPackageName); 9705 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 9706 //to update install status 9707 mSettings.writeLPr(); 9708 } 9709 } 9710 9711 private void installPackageLI(InstallArgs args, 9712 boolean newInstall, PackageInstalledInfo res) { 9713 int pFlags = args.flags; 9714 String installerPackageName = args.installerPackageName; 9715 File tmpPackageFile = new File(args.getCodePath()); 9716 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 9717 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 9718 boolean replace = false; 9719 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 9720 | (newInstall ? SCAN_NEW_INSTALL : 0); 9721 // Result object to be returned 9722 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 9723 9724 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 9725 // Retrieve PackageSettings and parse package 9726 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 9727 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 9728 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 9729 PackageParser pp = new PackageParser(tmpPackageFile.getPath()); 9730 pp.setSeparateProcesses(mSeparateProcesses); 9731 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile, 9732 null, mMetrics, parseFlags); 9733 if (pkg == null) { 9734 res.returnCode = pp.getParseError(); 9735 return; 9736 } 9737 String pkgName = res.name = pkg.packageName; 9738 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 9739 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 9740 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 9741 return; 9742 } 9743 } 9744 if (!pp.collectCertificates(pkg, parseFlags)) { 9745 res.returnCode = pp.getParseError(); 9746 return; 9747 } 9748 9749 /* If the installer passed in a manifest digest, compare it now. */ 9750 if (args.manifestDigest != null) { 9751 if (DEBUG_INSTALL) { 9752 final String parsedManifest = pkg.manifestDigest == null ? "null" 9753 : pkg.manifestDigest.toString(); 9754 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 9755 + parsedManifest); 9756 } 9757 9758 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 9759 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 9760 return; 9761 } 9762 } else if (DEBUG_INSTALL) { 9763 final String parsedManifest = pkg.manifestDigest == null 9764 ? "null" : pkg.manifestDigest.toString(); 9765 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 9766 } 9767 9768 // Get rid of all references to package scan path via parser. 9769 pp = null; 9770 String oldCodePath = null; 9771 boolean systemApp = false; 9772 synchronized (mPackages) { 9773 // Check whether the newly-scanned package wants to define an already-defined perm 9774 int N = pkg.permissions.size(); 9775 for (int i = 0; i < N; i++) { 9776 PackageParser.Permission perm = pkg.permissions.get(i); 9777 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 9778 if (bp != null) { 9779 // If the defining package is signed with our cert, it's okay. This 9780 // also includes the "updating the same package" case, of course. 9781 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 9782 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9783 Slog.w(TAG, "Package " + pkg.packageName 9784 + " attempting to redeclare permission " + perm.info.name 9785 + " already owned by " + bp.sourcePackage); 9786 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 9787 res.origPermission = perm.info.name; 9788 res.origPackage = bp.sourcePackage; 9789 return; 9790 } 9791 } 9792 } 9793 9794 // Check if installing already existing package 9795 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9796 String oldName = mSettings.mRenamedPackages.get(pkgName); 9797 if (pkg.mOriginalPackages != null 9798 && pkg.mOriginalPackages.contains(oldName) 9799 && mPackages.containsKey(oldName)) { 9800 // This package is derived from an original package, 9801 // and this device has been updating from that original 9802 // name. We must continue using the original name, so 9803 // rename the new package here. 9804 pkg.setPackageName(oldName); 9805 pkgName = pkg.packageName; 9806 replace = true; 9807 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 9808 + oldName + " pkgName=" + pkgName); 9809 } else if (mPackages.containsKey(pkgName)) { 9810 // This package, under its official name, already exists 9811 // on the device; we should replace it. 9812 replace = true; 9813 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 9814 } 9815 } 9816 PackageSetting ps = mSettings.mPackages.get(pkgName); 9817 if (ps != null) { 9818 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 9819 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 9820 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 9821 systemApp = (ps.pkg.applicationInfo.flags & 9822 ApplicationInfo.FLAG_SYSTEM) != 0; 9823 } 9824 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 9825 } 9826 } 9827 9828 if (systemApp && onSd) { 9829 // Disable updates to system apps on sdcard 9830 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 9831 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9832 return; 9833 } 9834 9835 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 9836 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9837 return; 9838 } 9839 // Set application objects path explicitly after the rename 9840 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath()); 9841 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 9842 if (replace) { 9843 replacePackageLI(pkg, parseFlags, scanMode, args.user, 9844 installerPackageName, res); 9845 } else { 9846 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 9847 installerPackageName, res); 9848 } 9849 synchronized (mPackages) { 9850 final PackageSetting ps = mSettings.mPackages.get(pkgName); 9851 if (ps != null) { 9852 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 9853 } 9854 } 9855 } 9856 9857 private static boolean isForwardLocked(PackageParser.Package pkg) { 9858 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 9859 } 9860 9861 9862 private boolean isForwardLocked(PackageSetting ps) { 9863 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 9864 } 9865 9866 private static boolean isExternal(PackageParser.Package pkg) { 9867 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 9868 } 9869 9870 private static boolean isExternal(PackageSetting ps) { 9871 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 9872 } 9873 9874 private static boolean isSystemApp(PackageParser.Package pkg) { 9875 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9876 } 9877 9878 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 9879 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 9880 } 9881 9882 private static boolean isSystemApp(ApplicationInfo info) { 9883 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9884 } 9885 9886 private static boolean isSystemApp(PackageSetting ps) { 9887 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 9888 } 9889 9890 private static boolean isUpdatedSystemApp(PackageSetting ps) { 9891 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 9892 } 9893 9894 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 9895 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 9896 } 9897 9898 private int packageFlagsToInstallFlags(PackageSetting ps) { 9899 int installFlags = 0; 9900 if (isExternal(ps)) { 9901 installFlags |= PackageManager.INSTALL_EXTERNAL; 9902 } 9903 if (isForwardLocked(ps)) { 9904 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 9905 } 9906 return installFlags; 9907 } 9908 9909 private void deleteTempPackageFiles() { 9910 final FilenameFilter filter = new FilenameFilter() { 9911 public boolean accept(File dir, String name) { 9912 return name.startsWith("vmdl") && name.endsWith(".tmp"); 9913 } 9914 }; 9915 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 9916 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 9917 } 9918 9919 private static final void deleteTempPackageFilesInDirectory(File directory, 9920 FilenameFilter filter) { 9921 final String[] tmpFilesList = directory.list(filter); 9922 if (tmpFilesList == null) { 9923 return; 9924 } 9925 for (int i = 0; i < tmpFilesList.length; i++) { 9926 final File tmpFile = new File(directory, tmpFilesList[i]); 9927 tmpFile.delete(); 9928 } 9929 } 9930 9931 private File createTempPackageFile(File installDir) { 9932 File tmpPackageFile; 9933 try { 9934 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 9935 } catch (IOException e) { 9936 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 9937 return null; 9938 } 9939 try { 9940 FileUtils.setPermissions( 9941 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 9942 -1, -1); 9943 if (!SELinux.restorecon(tmpPackageFile)) { 9944 return null; 9945 } 9946 } catch (IOException e) { 9947 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 9948 return null; 9949 } 9950 return tmpPackageFile; 9951 } 9952 9953 @Override 9954 public void deletePackageAsUser(final String packageName, 9955 final IPackageDeleteObserver observer, 9956 final int userId, final int flags) { 9957 mContext.enforceCallingOrSelfPermission( 9958 android.Manifest.permission.DELETE_PACKAGES, null); 9959 final int uid = Binder.getCallingUid(); 9960 if (UserHandle.getUserId(uid) != userId) { 9961 mContext.enforceCallingPermission( 9962 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 9963 "deletePackage for user " + userId); 9964 } 9965 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 9966 try { 9967 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 9968 } catch (RemoteException re) { 9969 } 9970 return; 9971 } 9972 9973 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 9974 // Queue up an async operation since the package deletion may take a little while. 9975 mHandler.post(new Runnable() { 9976 public void run() { 9977 mHandler.removeCallbacks(this); 9978 final int returnCode = deletePackageX(packageName, userId, flags); 9979 if (observer != null) { 9980 try { 9981 observer.packageDeleted(packageName, returnCode); 9982 } catch (RemoteException e) { 9983 Log.i(TAG, "Observer no longer exists."); 9984 } //end catch 9985 } //end if 9986 } //end run 9987 }); 9988 } 9989 9990 private boolean isPackageDeviceAdmin(String packageName, int userId) { 9991 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 9992 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 9993 try { 9994 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 9995 || dpm.isDeviceOwner(packageName))) { 9996 return true; 9997 } 9998 } catch (RemoteException e) { 9999 } 10000 return false; 10001 } 10002 10003 /** 10004 * This method is an internal method that could be get invoked either 10005 * to delete an installed package or to clean up a failed installation. 10006 * After deleting an installed package, a broadcast is sent to notify any 10007 * listeners that the package has been installed. For cleaning up a failed 10008 * installation, the broadcast is not necessary since the package's 10009 * installation wouldn't have sent the initial broadcast either 10010 * The key steps in deleting a package are 10011 * deleting the package information in internal structures like mPackages, 10012 * deleting the packages base directories through installd 10013 * updating mSettings to reflect current status 10014 * persisting settings for later use 10015 * sending a broadcast if necessary 10016 */ 10017 private int deletePackageX(String packageName, int userId, int flags) { 10018 final PackageRemovedInfo info = new PackageRemovedInfo(); 10019 final boolean res; 10020 10021 if (isPackageDeviceAdmin(packageName, userId)) { 10022 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10023 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10024 } 10025 10026 boolean removedForAllUsers = false; 10027 boolean systemUpdate = false; 10028 10029 // for the uninstall-updates case and restricted profiles, remember the per- 10030 // userhandle installed state 10031 int[] allUsers; 10032 boolean[] perUserInstalled; 10033 synchronized (mPackages) { 10034 PackageSetting ps = mSettings.mPackages.get(packageName); 10035 allUsers = sUserManager.getUserIds(); 10036 perUserInstalled = new boolean[allUsers.length]; 10037 for (int i = 0; i < allUsers.length; i++) { 10038 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10039 } 10040 } 10041 10042 synchronized (mInstallLock) { 10043 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10044 res = deletePackageLI(packageName, 10045 (flags & PackageManager.DELETE_ALL_USERS) != 0 10046 ? UserHandle.ALL : new UserHandle(userId), 10047 true, allUsers, perUserInstalled, 10048 flags | REMOVE_CHATTY, info, true); 10049 systemUpdate = info.isRemovedPackageSystemUpdate; 10050 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10051 removedForAllUsers = true; 10052 } 10053 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10054 + " removedForAllUsers=" + removedForAllUsers); 10055 } 10056 10057 if (res) { 10058 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10059 10060 // If the removed package was a system update, the old system package 10061 // was re-enabled; we need to broadcast this information 10062 if (systemUpdate) { 10063 Bundle extras = new Bundle(1); 10064 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10065 ? info.removedAppId : info.uid); 10066 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10067 10068 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10069 extras, null, null, null); 10070 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10071 extras, null, null, null); 10072 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10073 null, packageName, null, null); 10074 } 10075 } 10076 // Force a gc here. 10077 Runtime.getRuntime().gc(); 10078 // Delete the resources here after sending the broadcast to let 10079 // other processes clean up before deleting resources. 10080 if (info.args != null) { 10081 synchronized (mInstallLock) { 10082 info.args.doPostDeleteLI(true); 10083 } 10084 } 10085 10086 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10087 } 10088 10089 static class PackageRemovedInfo { 10090 String removedPackage; 10091 int uid = -1; 10092 int removedAppId = -1; 10093 int[] removedUsers = null; 10094 boolean isRemovedPackageSystemUpdate = false; 10095 // Clean up resources deleted packages. 10096 InstallArgs args = null; 10097 10098 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10099 Bundle extras = new Bundle(1); 10100 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10101 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10102 if (replacing) { 10103 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10104 } 10105 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10106 if (removedPackage != null) { 10107 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10108 extras, null, null, removedUsers); 10109 if (fullRemove && !replacing) { 10110 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10111 extras, null, null, removedUsers); 10112 } 10113 } 10114 if (removedAppId >= 0) { 10115 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10116 removedUsers); 10117 } 10118 } 10119 } 10120 10121 /* 10122 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10123 * flag is not set, the data directory is removed as well. 10124 * make sure this flag is set for partially installed apps. If not its meaningless to 10125 * delete a partially installed application. 10126 */ 10127 private void removePackageDataLI(PackageSetting ps, 10128 int[] allUserHandles, boolean[] perUserInstalled, 10129 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10130 String packageName = ps.name; 10131 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10132 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10133 // Retrieve object to delete permissions for shared user later on 10134 final PackageSetting deletedPs; 10135 // reader 10136 synchronized (mPackages) { 10137 deletedPs = mSettings.mPackages.get(packageName); 10138 if (outInfo != null) { 10139 outInfo.removedPackage = packageName; 10140 outInfo.removedUsers = deletedPs != null 10141 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10142 : null; 10143 } 10144 } 10145 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10146 removeDataDirsLI(packageName); 10147 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10148 } 10149 // writer 10150 synchronized (mPackages) { 10151 if (deletedPs != null) { 10152 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10153 if (outInfo != null) { 10154 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10155 } 10156 if (deletedPs != null) { 10157 updatePermissionsLPw(deletedPs.name, null, 0); 10158 if (deletedPs.sharedUser != null) { 10159 // remove permissions associated with package 10160 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10161 } 10162 } 10163 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10164 } 10165 // make sure to preserve per-user disabled state if this removal was just 10166 // a downgrade of a system app to the factory package 10167 if (allUserHandles != null && perUserInstalled != null) { 10168 if (DEBUG_REMOVE) { 10169 Slog.d(TAG, "Propagating install state across downgrade"); 10170 } 10171 for (int i = 0; i < allUserHandles.length; i++) { 10172 if (DEBUG_REMOVE) { 10173 Slog.d(TAG, " user " + allUserHandles[i] 10174 + " => " + perUserInstalled[i]); 10175 } 10176 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10177 } 10178 } 10179 } 10180 // can downgrade to reader 10181 if (writeSettings) { 10182 // Save settings now 10183 mSettings.writeLPr(); 10184 } 10185 } 10186 if (outInfo != null) { 10187 // A user ID was deleted here. Go through all users and remove it 10188 // from KeyStore. 10189 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10190 } 10191 } 10192 10193 static boolean locationIsPrivileged(File path) { 10194 try { 10195 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10196 .getCanonicalPath(); 10197 return path.getCanonicalPath().startsWith(privilegedAppDir); 10198 } catch (IOException e) { 10199 Slog.e(TAG, "Unable to access code path " + path); 10200 } 10201 return false; 10202 } 10203 10204 /* 10205 * Tries to delete system package. 10206 */ 10207 private boolean deleteSystemPackageLI(PackageSetting newPs, 10208 int[] allUserHandles, boolean[] perUserInstalled, 10209 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10210 final boolean applyUserRestrictions 10211 = (allUserHandles != null) && (perUserInstalled != null); 10212 PackageSetting disabledPs = null; 10213 // Confirm if the system package has been updated 10214 // An updated system app can be deleted. This will also have to restore 10215 // the system pkg from system partition 10216 // reader 10217 synchronized (mPackages) { 10218 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10219 } 10220 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10221 + " disabledPs=" + disabledPs); 10222 if (disabledPs == null) { 10223 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10224 return false; 10225 } else if (DEBUG_REMOVE) { 10226 Slog.d(TAG, "Deleting system pkg from data partition"); 10227 } 10228 if (DEBUG_REMOVE) { 10229 if (applyUserRestrictions) { 10230 Slog.d(TAG, "Remembering install states:"); 10231 for (int i = 0; i < allUserHandles.length; i++) { 10232 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10233 } 10234 } 10235 } 10236 // Delete the updated package 10237 outInfo.isRemovedPackageSystemUpdate = true; 10238 if (disabledPs.versionCode < newPs.versionCode) { 10239 // Delete data for downgrades 10240 flags &= ~PackageManager.DELETE_KEEP_DATA; 10241 } else { 10242 // Preserve data by setting flag 10243 flags |= PackageManager.DELETE_KEEP_DATA; 10244 } 10245 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10246 allUserHandles, perUserInstalled, outInfo, writeSettings); 10247 if (!ret) { 10248 return false; 10249 } 10250 // writer 10251 synchronized (mPackages) { 10252 // Reinstate the old system package 10253 mSettings.enableSystemPackageLPw(newPs.name); 10254 // Remove any native libraries from the upgraded package. 10255 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 10256 } 10257 // Install the system package 10258 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10259 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10260 if (locationIsPrivileged(disabledPs.codePath)) { 10261 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10262 } 10263 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10264 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null); 10265 10266 if (newPkg == null) { 10267 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10268 + " with error:" + mLastScanError); 10269 return false; 10270 } 10271 // writer 10272 synchronized (mPackages) { 10273 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10274 setInternalAppNativeLibraryPath(newPkg, ps); 10275 updatePermissionsLPw(newPkg.packageName, newPkg, 10276 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10277 if (applyUserRestrictions) { 10278 if (DEBUG_REMOVE) { 10279 Slog.d(TAG, "Propagating install state across reinstall"); 10280 } 10281 for (int i = 0; i < allUserHandles.length; i++) { 10282 if (DEBUG_REMOVE) { 10283 Slog.d(TAG, " user " + allUserHandles[i] 10284 + " => " + perUserInstalled[i]); 10285 } 10286 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10287 } 10288 // Regardless of writeSettings we need to ensure that this restriction 10289 // state propagation is persisted 10290 mSettings.writeAllUsersPackageRestrictionsLPr(); 10291 } 10292 // can downgrade to reader here 10293 if (writeSettings) { 10294 mSettings.writeLPr(); 10295 } 10296 } 10297 return true; 10298 } 10299 10300 private boolean deleteInstalledPackageLI(PackageSetting ps, 10301 boolean deleteCodeAndResources, int flags, 10302 int[] allUserHandles, boolean[] perUserInstalled, 10303 PackageRemovedInfo outInfo, boolean writeSettings) { 10304 if (outInfo != null) { 10305 outInfo.uid = ps.appId; 10306 } 10307 10308 // Delete package data from internal structures and also remove data if flag is set 10309 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10310 10311 // Delete application code and resources 10312 if (deleteCodeAndResources && (outInfo != null)) { 10313 outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString, 10314 ps.resourcePathString, ps.nativeLibraryPathString, 10315 getAppInstructionSetFromSettings(ps)); 10316 } 10317 return true; 10318 } 10319 10320 /* 10321 * This method handles package deletion in general 10322 */ 10323 private boolean deletePackageLI(String packageName, UserHandle user, 10324 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10325 int flags, PackageRemovedInfo outInfo, 10326 boolean writeSettings) { 10327 if (packageName == null) { 10328 Slog.w(TAG, "Attempt to delete null packageName."); 10329 return false; 10330 } 10331 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10332 PackageSetting ps; 10333 boolean dataOnly = false; 10334 int removeUser = -1; 10335 int appId = -1; 10336 synchronized (mPackages) { 10337 ps = mSettings.mPackages.get(packageName); 10338 if (ps == null) { 10339 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10340 return false; 10341 } 10342 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10343 && user.getIdentifier() != UserHandle.USER_ALL) { 10344 // The caller is asking that the package only be deleted for a single 10345 // user. To do this, we just mark its uninstalled state and delete 10346 // its data. If this is a system app, we only allow this to happen if 10347 // they have set the special DELETE_SYSTEM_APP which requests different 10348 // semantics than normal for uninstalling system apps. 10349 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10350 ps.setUserState(user.getIdentifier(), 10351 COMPONENT_ENABLED_STATE_DEFAULT, 10352 false, //installed 10353 true, //stopped 10354 true, //notLaunched 10355 false, //blocked 10356 null, null, null); 10357 if (!isSystemApp(ps)) { 10358 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10359 // Other user still have this package installed, so all 10360 // we need to do is clear this user's data and save that 10361 // it is uninstalled. 10362 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10363 removeUser = user.getIdentifier(); 10364 appId = ps.appId; 10365 mSettings.writePackageRestrictionsLPr(removeUser); 10366 } else { 10367 // We need to set it back to 'installed' so the uninstall 10368 // broadcasts will be sent correctly. 10369 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10370 ps.setInstalled(true, user.getIdentifier()); 10371 } 10372 } else { 10373 // This is a system app, so we assume that the 10374 // other users still have this package installed, so all 10375 // we need to do is clear this user's data and save that 10376 // it is uninstalled. 10377 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10378 removeUser = user.getIdentifier(); 10379 appId = ps.appId; 10380 mSettings.writePackageRestrictionsLPr(removeUser); 10381 } 10382 } 10383 } 10384 10385 if (removeUser >= 0) { 10386 // From above, we determined that we are deleting this only 10387 // for a single user. Continue the work here. 10388 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10389 if (outInfo != null) { 10390 outInfo.removedPackage = packageName; 10391 outInfo.removedAppId = appId; 10392 outInfo.removedUsers = new int[] {removeUser}; 10393 } 10394 mInstaller.clearUserData(packageName, removeUser); 10395 removeKeystoreDataIfNeeded(removeUser, appId); 10396 schedulePackageCleaning(packageName, removeUser, false); 10397 return true; 10398 } 10399 10400 if (dataOnly) { 10401 // Delete application data first 10402 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10403 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10404 return true; 10405 } 10406 10407 boolean ret = false; 10408 mSettings.mKeySetManager.removeAppKeySetData(packageName); 10409 if (isSystemApp(ps)) { 10410 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10411 // When an updated system application is deleted we delete the existing resources as well and 10412 // fall back to existing code in system partition 10413 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10414 flags, outInfo, writeSettings); 10415 } else { 10416 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10417 // Kill application pre-emptively especially for apps on sd. 10418 killApplication(packageName, ps.appId, "uninstall pkg"); 10419 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10420 allUserHandles, perUserInstalled, 10421 outInfo, writeSettings); 10422 } 10423 10424 return ret; 10425 } 10426 10427 private final class ClearStorageConnection implements ServiceConnection { 10428 IMediaContainerService mContainerService; 10429 10430 @Override 10431 public void onServiceConnected(ComponentName name, IBinder service) { 10432 synchronized (this) { 10433 mContainerService = IMediaContainerService.Stub.asInterface(service); 10434 notifyAll(); 10435 } 10436 } 10437 10438 @Override 10439 public void onServiceDisconnected(ComponentName name) { 10440 } 10441 } 10442 10443 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10444 final boolean mounted; 10445 if (Environment.isExternalStorageEmulated()) { 10446 mounted = true; 10447 } else { 10448 final String status = Environment.getExternalStorageState(); 10449 10450 mounted = status.equals(Environment.MEDIA_MOUNTED) 10451 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10452 } 10453 10454 if (!mounted) { 10455 return; 10456 } 10457 10458 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10459 int[] users; 10460 if (userId == UserHandle.USER_ALL) { 10461 users = sUserManager.getUserIds(); 10462 } else { 10463 users = new int[] { userId }; 10464 } 10465 final ClearStorageConnection conn = new ClearStorageConnection(); 10466 if (mContext.bindServiceAsUser( 10467 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10468 try { 10469 for (int curUser : users) { 10470 long timeout = SystemClock.uptimeMillis() + 5000; 10471 synchronized (conn) { 10472 long now = SystemClock.uptimeMillis(); 10473 while (conn.mContainerService == null && now < timeout) { 10474 try { 10475 conn.wait(timeout - now); 10476 } catch (InterruptedException e) { 10477 } 10478 } 10479 } 10480 if (conn.mContainerService == null) { 10481 return; 10482 } 10483 10484 final UserEnvironment userEnv = new UserEnvironment(curUser); 10485 clearDirectory(conn.mContainerService, 10486 userEnv.buildExternalStorageAppCacheDirs(packageName)); 10487 if (allData) { 10488 clearDirectory(conn.mContainerService, 10489 userEnv.buildExternalStorageAppDataDirs(packageName)); 10490 clearDirectory(conn.mContainerService, 10491 userEnv.buildExternalStorageAppMediaDirs(packageName)); 10492 } 10493 } 10494 } finally { 10495 mContext.unbindService(conn); 10496 } 10497 } 10498 } 10499 10500 @Override 10501 public void clearApplicationUserData(final String packageName, 10502 final IPackageDataObserver observer, final int userId) { 10503 mContext.enforceCallingOrSelfPermission( 10504 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 10505 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 10506 // Queue up an async operation since the package deletion may take a little while. 10507 mHandler.post(new Runnable() { 10508 public void run() { 10509 mHandler.removeCallbacks(this); 10510 final boolean succeeded; 10511 synchronized (mInstallLock) { 10512 succeeded = clearApplicationUserDataLI(packageName, userId); 10513 } 10514 clearExternalStorageDataSync(packageName, userId, true); 10515 if (succeeded) { 10516 // invoke DeviceStorageMonitor's update method to clear any notifications 10517 DeviceStorageMonitorInternal 10518 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 10519 if (dsm != null) { 10520 dsm.checkMemory(); 10521 } 10522 } 10523 if(observer != null) { 10524 try { 10525 observer.onRemoveCompleted(packageName, succeeded); 10526 } catch (RemoteException e) { 10527 Log.i(TAG, "Observer no longer exists."); 10528 } 10529 } //end if observer 10530 } //end run 10531 }); 10532 } 10533 10534 private boolean clearApplicationUserDataLI(String packageName, int userId) { 10535 if (packageName == null) { 10536 Slog.w(TAG, "Attempt to delete null packageName."); 10537 return false; 10538 } 10539 PackageParser.Package p; 10540 boolean dataOnly = false; 10541 final int appId; 10542 synchronized (mPackages) { 10543 p = mPackages.get(packageName); 10544 if (p == null) { 10545 dataOnly = true; 10546 PackageSetting ps = mSettings.mPackages.get(packageName); 10547 if ((ps == null) || (ps.pkg == null)) { 10548 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10549 return false; 10550 } 10551 p = ps.pkg; 10552 } 10553 if (!dataOnly) { 10554 // need to check this only for fully installed applications 10555 if (p == null) { 10556 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10557 return false; 10558 } 10559 final ApplicationInfo applicationInfo = p.applicationInfo; 10560 if (applicationInfo == null) { 10561 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10562 return false; 10563 } 10564 } 10565 if (p != null && p.applicationInfo != null) { 10566 appId = p.applicationInfo.uid; 10567 } else { 10568 appId = -1; 10569 } 10570 } 10571 int retCode = mInstaller.clearUserData(packageName, userId); 10572 if (retCode < 0) { 10573 Slog.w(TAG, "Couldn't remove cache files for package: " 10574 + packageName); 10575 return false; 10576 } 10577 removeKeystoreDataIfNeeded(userId, appId); 10578 return true; 10579 } 10580 10581 /** 10582 * Remove entries from the keystore daemon. Will only remove it if the 10583 * {@code appId} is valid. 10584 */ 10585 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 10586 if (appId < 0) { 10587 return; 10588 } 10589 10590 final KeyStore keyStore = KeyStore.getInstance(); 10591 if (keyStore != null) { 10592 if (userId == UserHandle.USER_ALL) { 10593 for (final int individual : sUserManager.getUserIds()) { 10594 keyStore.clearUid(UserHandle.getUid(individual, appId)); 10595 } 10596 } else { 10597 keyStore.clearUid(UserHandle.getUid(userId, appId)); 10598 } 10599 } else { 10600 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 10601 } 10602 } 10603 10604 public void deleteApplicationCacheFiles(final String packageName, 10605 final IPackageDataObserver observer) { 10606 mContext.enforceCallingOrSelfPermission( 10607 android.Manifest.permission.DELETE_CACHE_FILES, null); 10608 // Queue up an async operation since the package deletion may take a little while. 10609 final int userId = UserHandle.getCallingUserId(); 10610 mHandler.post(new Runnable() { 10611 public void run() { 10612 mHandler.removeCallbacks(this); 10613 final boolean succeded; 10614 synchronized (mInstallLock) { 10615 succeded = deleteApplicationCacheFilesLI(packageName, userId); 10616 } 10617 clearExternalStorageDataSync(packageName, userId, false); 10618 if(observer != null) { 10619 try { 10620 observer.onRemoveCompleted(packageName, succeded); 10621 } catch (RemoteException e) { 10622 Log.i(TAG, "Observer no longer exists."); 10623 } 10624 } //end if observer 10625 } //end run 10626 }); 10627 } 10628 10629 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 10630 if (packageName == null) { 10631 Slog.w(TAG, "Attempt to delete null packageName."); 10632 return false; 10633 } 10634 PackageParser.Package p; 10635 synchronized (mPackages) { 10636 p = mPackages.get(packageName); 10637 } 10638 if (p == null) { 10639 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 10640 return false; 10641 } 10642 final ApplicationInfo applicationInfo = p.applicationInfo; 10643 if (applicationInfo == null) { 10644 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10645 return false; 10646 } 10647 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 10648 if (retCode < 0) { 10649 Slog.w(TAG, "Couldn't remove cache files for package: " 10650 + packageName + " u" + userId); 10651 return false; 10652 } 10653 return true; 10654 } 10655 10656 public void getPackageSizeInfo(final String packageName, int userHandle, 10657 final IPackageStatsObserver observer) { 10658 mContext.enforceCallingOrSelfPermission( 10659 android.Manifest.permission.GET_PACKAGE_SIZE, null); 10660 if (packageName == null) { 10661 throw new IllegalArgumentException("Attempt to get size of null packageName"); 10662 } 10663 10664 PackageStats stats = new PackageStats(packageName, userHandle); 10665 10666 /* 10667 * Queue up an async operation since the package measurement may take a 10668 * little while. 10669 */ 10670 Message msg = mHandler.obtainMessage(INIT_COPY); 10671 msg.obj = new MeasureParams(stats, observer); 10672 mHandler.sendMessage(msg); 10673 } 10674 10675 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 10676 PackageStats pStats) { 10677 if (packageName == null) { 10678 Slog.w(TAG, "Attempt to get size of null packageName."); 10679 return false; 10680 } 10681 PackageParser.Package p; 10682 boolean dataOnly = false; 10683 String libDirPath = null; 10684 String asecPath = null; 10685 PackageSetting ps = null; 10686 synchronized (mPackages) { 10687 p = mPackages.get(packageName); 10688 ps = mSettings.mPackages.get(packageName); 10689 if(p == null) { 10690 dataOnly = true; 10691 if((ps == null) || (ps.pkg == null)) { 10692 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 10693 return false; 10694 } 10695 p = ps.pkg; 10696 } 10697 if (ps != null) { 10698 libDirPath = ps.nativeLibraryPathString; 10699 } 10700 if (p != null && (isExternal(p) || isForwardLocked(p))) { 10701 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 10702 if (secureContainerId != null) { 10703 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 10704 } 10705 } 10706 } 10707 String publicSrcDir = null; 10708 if(!dataOnly) { 10709 final ApplicationInfo applicationInfo = p.applicationInfo; 10710 if (applicationInfo == null) { 10711 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10712 return false; 10713 } 10714 if (isForwardLocked(p)) { 10715 publicSrcDir = applicationInfo.publicSourceDir; 10716 } 10717 } 10718 int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath, 10719 publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps), 10720 pStats); 10721 if (res < 0) { 10722 return false; 10723 } 10724 10725 // Fix-up for forward-locked applications in ASEC containers. 10726 if (!isExternal(p)) { 10727 pStats.codeSize += pStats.externalCodeSize; 10728 pStats.externalCodeSize = 0L; 10729 } 10730 10731 return true; 10732 } 10733 10734 10735 public void addPackageToPreferred(String packageName) { 10736 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 10737 } 10738 10739 public void removePackageFromPreferred(String packageName) { 10740 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 10741 } 10742 10743 public List<PackageInfo> getPreferredPackages(int flags) { 10744 return new ArrayList<PackageInfo>(); 10745 } 10746 10747 private int getUidTargetSdkVersionLockedLPr(int uid) { 10748 Object obj = mSettings.getUserIdLPr(uid); 10749 if (obj instanceof SharedUserSetting) { 10750 final SharedUserSetting sus = (SharedUserSetting) obj; 10751 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 10752 final Iterator<PackageSetting> it = sus.packages.iterator(); 10753 while (it.hasNext()) { 10754 final PackageSetting ps = it.next(); 10755 if (ps.pkg != null) { 10756 int v = ps.pkg.applicationInfo.targetSdkVersion; 10757 if (v < vers) vers = v; 10758 } 10759 } 10760 return vers; 10761 } else if (obj instanceof PackageSetting) { 10762 final PackageSetting ps = (PackageSetting) obj; 10763 if (ps.pkg != null) { 10764 return ps.pkg.applicationInfo.targetSdkVersion; 10765 } 10766 } 10767 return Build.VERSION_CODES.CUR_DEVELOPMENT; 10768 } 10769 10770 public void addPreferredActivity(IntentFilter filter, int match, 10771 ComponentName[] set, ComponentName activity, int userId) { 10772 addPreferredActivityInternal(filter, match, set, activity, true, userId); 10773 } 10774 10775 private void addPreferredActivityInternal(IntentFilter filter, int match, 10776 ComponentName[] set, ComponentName activity, boolean always, int userId) { 10777 // writer 10778 int callingUid = Binder.getCallingUid(); 10779 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 10780 if (filter.countActions() == 0) { 10781 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 10782 return; 10783 } 10784 synchronized (mPackages) { 10785 if (mContext.checkCallingOrSelfPermission( 10786 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10787 != PackageManager.PERMISSION_GRANTED) { 10788 if (getUidTargetSdkVersionLockedLPr(callingUid) 10789 < Build.VERSION_CODES.FROYO) { 10790 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 10791 + callingUid); 10792 return; 10793 } 10794 mContext.enforceCallingOrSelfPermission( 10795 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10796 } 10797 10798 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 10799 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10800 mSettings.editPreferredActivitiesLPw(userId).addFilter( 10801 new PreferredActivity(filter, match, set, activity, always)); 10802 mSettings.writePackageRestrictionsLPr(userId); 10803 } 10804 } 10805 10806 public void replacePreferredActivity(IntentFilter filter, int match, 10807 ComponentName[] set, ComponentName activity) { 10808 if (filter.countActions() != 1) { 10809 throw new IllegalArgumentException( 10810 "replacePreferredActivity expects filter to have only 1 action."); 10811 } 10812 if (filter.countDataAuthorities() != 0 10813 || filter.countDataPaths() != 0 10814 || filter.countDataSchemes() > 1 10815 || filter.countDataTypes() != 0) { 10816 throw new IllegalArgumentException( 10817 "replacePreferredActivity expects filter to have no data authorities, " + 10818 "paths, or types; and at most one scheme."); 10819 } 10820 synchronized (mPackages) { 10821 if (mContext.checkCallingOrSelfPermission( 10822 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10823 != PackageManager.PERMISSION_GRANTED) { 10824 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 10825 < Build.VERSION_CODES.FROYO) { 10826 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 10827 + Binder.getCallingUid()); 10828 return; 10829 } 10830 mContext.enforceCallingOrSelfPermission( 10831 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10832 } 10833 10834 final int callingUserId = UserHandle.getCallingUserId(); 10835 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 10836 if (pir != null) { 10837 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 10838 if (filter.countDataSchemes() == 1) { 10839 Uri.Builder builder = new Uri.Builder(); 10840 builder.scheme(filter.getDataScheme(0)); 10841 intent.setData(builder.build()); 10842 } 10843 List<PreferredActivity> matches = pir.queryIntent( 10844 intent, null, true, callingUserId); 10845 if (DEBUG_PREFERRED) { 10846 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 10847 } 10848 for (int i = 0; i < matches.size(); i++) { 10849 PreferredActivity pa = matches.get(i); 10850 if (DEBUG_PREFERRED) { 10851 Slog.i(TAG, "Removing preferred activity " 10852 + pa.mPref.mComponent + ":"); 10853 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10854 } 10855 pir.removeFilter(pa); 10856 } 10857 } 10858 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 10859 } 10860 } 10861 10862 public void clearPackagePreferredActivities(String packageName) { 10863 final int uid = Binder.getCallingUid(); 10864 // writer 10865 synchronized (mPackages) { 10866 PackageParser.Package pkg = mPackages.get(packageName); 10867 if (pkg == null || pkg.applicationInfo.uid != uid) { 10868 if (mContext.checkCallingOrSelfPermission( 10869 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10870 != PackageManager.PERMISSION_GRANTED) { 10871 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 10872 < Build.VERSION_CODES.FROYO) { 10873 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 10874 + Binder.getCallingUid()); 10875 return; 10876 } 10877 mContext.enforceCallingOrSelfPermission( 10878 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10879 } 10880 } 10881 10882 int user = UserHandle.getCallingUserId(); 10883 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 10884 mSettings.writePackageRestrictionsLPr(user); 10885 scheduleWriteSettingsLocked(); 10886 } 10887 } 10888 } 10889 10890 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 10891 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 10892 ArrayList<PreferredActivity> removed = null; 10893 boolean changed = false; 10894 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 10895 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 10896 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 10897 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 10898 continue; 10899 } 10900 Iterator<PreferredActivity> it = pir.filterIterator(); 10901 while (it.hasNext()) { 10902 PreferredActivity pa = it.next(); 10903 // Mark entry for removal only if it matches the package name 10904 // and the entry is of type "always". 10905 if (packageName == null || 10906 (pa.mPref.mComponent.getPackageName().equals(packageName) 10907 && pa.mPref.mAlways)) { 10908 if (removed == null) { 10909 removed = new ArrayList<PreferredActivity>(); 10910 } 10911 removed.add(pa); 10912 } 10913 } 10914 if (removed != null) { 10915 for (int j=0; j<removed.size(); j++) { 10916 PreferredActivity pa = removed.get(j); 10917 pir.removeFilter(pa); 10918 } 10919 changed = true; 10920 } 10921 } 10922 return changed; 10923 } 10924 10925 public void resetPreferredActivities(int userId) { 10926 mContext.enforceCallingOrSelfPermission( 10927 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10928 // writer 10929 synchronized (mPackages) { 10930 int user = UserHandle.getCallingUserId(); 10931 clearPackagePreferredActivitiesLPw(null, user); 10932 mSettings.readDefaultPreferredAppsLPw(this, user); 10933 mSettings.writePackageRestrictionsLPr(user); 10934 scheduleWriteSettingsLocked(); 10935 } 10936 } 10937 10938 public int getPreferredActivities(List<IntentFilter> outFilters, 10939 List<ComponentName> outActivities, String packageName) { 10940 10941 int num = 0; 10942 final int userId = UserHandle.getCallingUserId(); 10943 // reader 10944 synchronized (mPackages) { 10945 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 10946 if (pir != null) { 10947 final Iterator<PreferredActivity> it = pir.filterIterator(); 10948 while (it.hasNext()) { 10949 final PreferredActivity pa = it.next(); 10950 if (packageName == null 10951 || (pa.mPref.mComponent.getPackageName().equals(packageName) 10952 && pa.mPref.mAlways)) { 10953 if (outFilters != null) { 10954 outFilters.add(new IntentFilter(pa)); 10955 } 10956 if (outActivities != null) { 10957 outActivities.add(pa.mPref.mComponent); 10958 } 10959 } 10960 } 10961 } 10962 } 10963 10964 return num; 10965 } 10966 10967 @Override 10968 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 10969 int userId) { 10970 int callingUid = Binder.getCallingUid(); 10971 if (callingUid != Process.SYSTEM_UID) { 10972 throw new SecurityException( 10973 "addPersistentPreferredActivity can only be run by the system"); 10974 } 10975 if (filter.countActions() == 0) { 10976 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 10977 return; 10978 } 10979 synchronized (mPackages) { 10980 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 10981 " :"); 10982 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10983 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 10984 new PersistentPreferredActivity(filter, activity)); 10985 mSettings.writePackageRestrictionsLPr(userId); 10986 } 10987 } 10988 10989 @Override 10990 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 10991 int callingUid = Binder.getCallingUid(); 10992 if (callingUid != Process.SYSTEM_UID) { 10993 throw new SecurityException( 10994 "clearPackagePersistentPreferredActivities can only be run by the system"); 10995 } 10996 ArrayList<PersistentPreferredActivity> removed = null; 10997 boolean changed = false; 10998 synchronized (mPackages) { 10999 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11000 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11001 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11002 .valueAt(i); 11003 if (userId != thisUserId) { 11004 continue; 11005 } 11006 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11007 while (it.hasNext()) { 11008 PersistentPreferredActivity ppa = it.next(); 11009 // Mark entry for removal only if it matches the package name. 11010 if (ppa.mComponent.getPackageName().equals(packageName)) { 11011 if (removed == null) { 11012 removed = new ArrayList<PersistentPreferredActivity>(); 11013 } 11014 removed.add(ppa); 11015 } 11016 } 11017 if (removed != null) { 11018 for (int j=0; j<removed.size(); j++) { 11019 PersistentPreferredActivity ppa = removed.get(j); 11020 ppir.removeFilter(ppa); 11021 } 11022 changed = true; 11023 } 11024 } 11025 11026 if (changed) { 11027 mSettings.writePackageRestrictionsLPr(userId); 11028 } 11029 } 11030 } 11031 11032 @Override 11033 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11034 Intent intent = new Intent(Intent.ACTION_MAIN); 11035 intent.addCategory(Intent.CATEGORY_HOME); 11036 11037 final int callingUserId = UserHandle.getCallingUserId(); 11038 List<ResolveInfo> list = queryIntentActivities(intent, null, 11039 PackageManager.GET_META_DATA, callingUserId); 11040 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11041 true, false, false, callingUserId); 11042 11043 allHomeCandidates.clear(); 11044 if (list != null) { 11045 for (ResolveInfo ri : list) { 11046 allHomeCandidates.add(ri); 11047 } 11048 } 11049 return (preferred == null || preferred.activityInfo == null) 11050 ? null 11051 : new ComponentName(preferred.activityInfo.packageName, 11052 preferred.activityInfo.name); 11053 } 11054 11055 @Override 11056 public void setApplicationEnabledSetting(String appPackageName, 11057 int newState, int flags, int userId, String callingPackage) { 11058 if (!sUserManager.exists(userId)) return; 11059 if (callingPackage == null) { 11060 callingPackage = Integer.toString(Binder.getCallingUid()); 11061 } 11062 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11063 } 11064 11065 @Override 11066 public void setComponentEnabledSetting(ComponentName componentName, 11067 int newState, int flags, int userId) { 11068 if (!sUserManager.exists(userId)) return; 11069 setEnabledSetting(componentName.getPackageName(), 11070 componentName.getClassName(), newState, flags, userId, null); 11071 } 11072 11073 private void setEnabledSetting(final String packageName, String className, int newState, 11074 final int flags, int userId, String callingPackage) { 11075 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11076 || newState == COMPONENT_ENABLED_STATE_ENABLED 11077 || newState == COMPONENT_ENABLED_STATE_DISABLED 11078 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11079 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11080 throw new IllegalArgumentException("Invalid new component state: " 11081 + newState); 11082 } 11083 PackageSetting pkgSetting; 11084 final int uid = Binder.getCallingUid(); 11085 final int permission = mContext.checkCallingOrSelfPermission( 11086 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11087 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11088 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11089 boolean sendNow = false; 11090 boolean isApp = (className == null); 11091 String componentName = isApp ? packageName : className; 11092 int packageUid = -1; 11093 ArrayList<String> components; 11094 11095 // writer 11096 synchronized (mPackages) { 11097 pkgSetting = mSettings.mPackages.get(packageName); 11098 if (pkgSetting == null) { 11099 if (className == null) { 11100 throw new IllegalArgumentException( 11101 "Unknown package: " + packageName); 11102 } 11103 throw new IllegalArgumentException( 11104 "Unknown component: " + packageName 11105 + "/" + className); 11106 } 11107 // Allow root and verify that userId is not being specified by a different user 11108 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11109 throw new SecurityException( 11110 "Permission Denial: attempt to change component state from pid=" 11111 + Binder.getCallingPid() 11112 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11113 } 11114 if (className == null) { 11115 // We're dealing with an application/package level state change 11116 if (pkgSetting.getEnabled(userId) == newState) { 11117 // Nothing to do 11118 return; 11119 } 11120 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11121 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11122 // Don't care about who enables an app. 11123 callingPackage = null; 11124 } 11125 pkgSetting.setEnabled(newState, userId, callingPackage); 11126 // pkgSetting.pkg.mSetEnabled = newState; 11127 } else { 11128 // We're dealing with a component level state change 11129 // First, verify that this is a valid class name. 11130 PackageParser.Package pkg = pkgSetting.pkg; 11131 if (pkg == null || !pkg.hasComponentClassName(className)) { 11132 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11133 throw new IllegalArgumentException("Component class " + className 11134 + " does not exist in " + packageName); 11135 } else { 11136 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11137 + className + " does not exist in " + packageName); 11138 } 11139 } 11140 switch (newState) { 11141 case COMPONENT_ENABLED_STATE_ENABLED: 11142 if (!pkgSetting.enableComponentLPw(className, userId)) { 11143 return; 11144 } 11145 break; 11146 case COMPONENT_ENABLED_STATE_DISABLED: 11147 if (!pkgSetting.disableComponentLPw(className, userId)) { 11148 return; 11149 } 11150 break; 11151 case COMPONENT_ENABLED_STATE_DEFAULT: 11152 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11153 return; 11154 } 11155 break; 11156 default: 11157 Slog.e(TAG, "Invalid new component state: " + newState); 11158 return; 11159 } 11160 } 11161 mSettings.writePackageRestrictionsLPr(userId); 11162 components = mPendingBroadcasts.get(userId, packageName); 11163 final boolean newPackage = components == null; 11164 if (newPackage) { 11165 components = new ArrayList<String>(); 11166 } 11167 if (!components.contains(componentName)) { 11168 components.add(componentName); 11169 } 11170 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11171 sendNow = true; 11172 // Purge entry from pending broadcast list if another one exists already 11173 // since we are sending one right away. 11174 mPendingBroadcasts.remove(userId, packageName); 11175 } else { 11176 if (newPackage) { 11177 mPendingBroadcasts.put(userId, packageName, components); 11178 } 11179 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11180 // Schedule a message 11181 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11182 } 11183 } 11184 } 11185 11186 long callingId = Binder.clearCallingIdentity(); 11187 try { 11188 if (sendNow) { 11189 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11190 sendPackageChangedBroadcast(packageName, 11191 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11192 } 11193 } finally { 11194 Binder.restoreCallingIdentity(callingId); 11195 } 11196 } 11197 11198 private void sendPackageChangedBroadcast(String packageName, 11199 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11200 if (DEBUG_INSTALL) 11201 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11202 + componentNames); 11203 Bundle extras = new Bundle(4); 11204 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11205 String nameList[] = new String[componentNames.size()]; 11206 componentNames.toArray(nameList); 11207 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11208 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11209 extras.putInt(Intent.EXTRA_UID, packageUid); 11210 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11211 new int[] {UserHandle.getUserId(packageUid)}); 11212 } 11213 11214 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11215 if (!sUserManager.exists(userId)) return; 11216 final int uid = Binder.getCallingUid(); 11217 final int permission = mContext.checkCallingOrSelfPermission( 11218 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11219 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11220 enforceCrossUserPermission(uid, userId, true, "stop package"); 11221 // writer 11222 synchronized (mPackages) { 11223 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11224 uid, userId)) { 11225 scheduleWritePackageRestrictionsLocked(userId); 11226 } 11227 } 11228 } 11229 11230 public String getInstallerPackageName(String packageName) { 11231 // reader 11232 synchronized (mPackages) { 11233 return mSettings.getInstallerPackageNameLPr(packageName); 11234 } 11235 } 11236 11237 @Override 11238 public int getApplicationEnabledSetting(String packageName, int userId) { 11239 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11240 int uid = Binder.getCallingUid(); 11241 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11242 // reader 11243 synchronized (mPackages) { 11244 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11245 } 11246 } 11247 11248 @Override 11249 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11250 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11251 int uid = Binder.getCallingUid(); 11252 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11253 // reader 11254 synchronized (mPackages) { 11255 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11256 } 11257 } 11258 11259 public void enterSafeMode() { 11260 enforceSystemOrRoot("Only the system can request entering safe mode"); 11261 11262 if (!mSystemReady) { 11263 mSafeMode = true; 11264 } 11265 } 11266 11267 public void systemReady() { 11268 mSystemReady = true; 11269 11270 // Read the compatibilty setting when the system is ready. 11271 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11272 mContext.getContentResolver(), 11273 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11274 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11275 if (DEBUG_SETTINGS) { 11276 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11277 } 11278 11279 synchronized (mPackages) { 11280 // Verify that all of the preferred activity components actually 11281 // exist. It is possible for applications to be updated and at 11282 // that point remove a previously declared activity component that 11283 // had been set as a preferred activity. We try to clean this up 11284 // the next time we encounter that preferred activity, but it is 11285 // possible for the user flow to never be able to return to that 11286 // situation so here we do a sanity check to make sure we haven't 11287 // left any junk around. 11288 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11289 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11290 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11291 removed.clear(); 11292 for (PreferredActivity pa : pir.filterSet()) { 11293 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11294 removed.add(pa); 11295 } 11296 } 11297 if (removed.size() > 0) { 11298 for (int j=0; j<removed.size(); j++) { 11299 PreferredActivity pa = removed.get(i); 11300 Slog.w(TAG, "Removing dangling preferred activity: " 11301 + pa.mPref.mComponent); 11302 pir.removeFilter(pa); 11303 } 11304 mSettings.writePackageRestrictionsLPr( 11305 mSettings.mPreferredActivities.keyAt(i)); 11306 } 11307 } 11308 } 11309 sUserManager.systemReady(); 11310 } 11311 11312 public boolean isSafeMode() { 11313 return mSafeMode; 11314 } 11315 11316 public boolean hasSystemUidErrors() { 11317 return mHasSystemUidErrors; 11318 } 11319 11320 static String arrayToString(int[] array) { 11321 StringBuffer buf = new StringBuffer(128); 11322 buf.append('['); 11323 if (array != null) { 11324 for (int i=0; i<array.length; i++) { 11325 if (i > 0) buf.append(", "); 11326 buf.append(array[i]); 11327 } 11328 } 11329 buf.append(']'); 11330 return buf.toString(); 11331 } 11332 11333 static class DumpState { 11334 public static final int DUMP_LIBS = 1 << 0; 11335 11336 public static final int DUMP_FEATURES = 1 << 1; 11337 11338 public static final int DUMP_RESOLVERS = 1 << 2; 11339 11340 public static final int DUMP_PERMISSIONS = 1 << 3; 11341 11342 public static final int DUMP_PACKAGES = 1 << 4; 11343 11344 public static final int DUMP_SHARED_USERS = 1 << 5; 11345 11346 public static final int DUMP_MESSAGES = 1 << 6; 11347 11348 public static final int DUMP_PROVIDERS = 1 << 7; 11349 11350 public static final int DUMP_VERIFIERS = 1 << 8; 11351 11352 public static final int DUMP_PREFERRED = 1 << 9; 11353 11354 public static final int DUMP_PREFERRED_XML = 1 << 10; 11355 11356 public static final int DUMP_KEYSETS = 1 << 11; 11357 11358 public static final int DUMP_VERSION = 1 << 12; 11359 11360 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11361 11362 private int mTypes; 11363 11364 private int mOptions; 11365 11366 private boolean mTitlePrinted; 11367 11368 private SharedUserSetting mSharedUser; 11369 11370 public boolean isDumping(int type) { 11371 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11372 return true; 11373 } 11374 11375 return (mTypes & type) != 0; 11376 } 11377 11378 public void setDump(int type) { 11379 mTypes |= type; 11380 } 11381 11382 public boolean isOptionEnabled(int option) { 11383 return (mOptions & option) != 0; 11384 } 11385 11386 public void setOptionEnabled(int option) { 11387 mOptions |= option; 11388 } 11389 11390 public boolean onTitlePrinted() { 11391 final boolean printed = mTitlePrinted; 11392 mTitlePrinted = true; 11393 return printed; 11394 } 11395 11396 public boolean getTitlePrinted() { 11397 return mTitlePrinted; 11398 } 11399 11400 public void setTitlePrinted(boolean enabled) { 11401 mTitlePrinted = enabled; 11402 } 11403 11404 public SharedUserSetting getSharedUser() { 11405 return mSharedUser; 11406 } 11407 11408 public void setSharedUser(SharedUserSetting user) { 11409 mSharedUser = user; 11410 } 11411 } 11412 11413 @Override 11414 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 11415 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 11416 != PackageManager.PERMISSION_GRANTED) { 11417 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 11418 + Binder.getCallingPid() 11419 + ", uid=" + Binder.getCallingUid() 11420 + " without permission " 11421 + android.Manifest.permission.DUMP); 11422 return; 11423 } 11424 11425 DumpState dumpState = new DumpState(); 11426 boolean fullPreferred = false; 11427 boolean checkin = false; 11428 11429 String packageName = null; 11430 11431 int opti = 0; 11432 while (opti < args.length) { 11433 String opt = args[opti]; 11434 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 11435 break; 11436 } 11437 opti++; 11438 if ("-a".equals(opt)) { 11439 // Right now we only know how to print all. 11440 } else if ("-h".equals(opt)) { 11441 pw.println("Package manager dump options:"); 11442 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 11443 pw.println(" --checkin: dump for a checkin"); 11444 pw.println(" -f: print details of intent filters"); 11445 pw.println(" -h: print this help"); 11446 pw.println(" cmd may be one of:"); 11447 pw.println(" l[ibraries]: list known shared libraries"); 11448 pw.println(" f[ibraries]: list device features"); 11449 pw.println(" r[esolvers]: dump intent resolvers"); 11450 pw.println(" perm[issions]: dump permissions"); 11451 pw.println(" pref[erred]: print preferred package settings"); 11452 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 11453 pw.println(" prov[iders]: dump content providers"); 11454 pw.println(" p[ackages]: dump installed packages"); 11455 pw.println(" s[hared-users]: dump shared user IDs"); 11456 pw.println(" m[essages]: print collected runtime messages"); 11457 pw.println(" v[erifiers]: print package verifier info"); 11458 pw.println(" version: print database version info"); 11459 pw.println(" <package.name>: info about given package"); 11460 pw.println(" k[eysets]: print known keysets"); 11461 return; 11462 } else if ("--checkin".equals(opt)) { 11463 checkin = true; 11464 } else if ("-f".equals(opt)) { 11465 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11466 } else { 11467 pw.println("Unknown argument: " + opt + "; use -h for help"); 11468 } 11469 } 11470 11471 // Is the caller requesting to dump a particular piece of data? 11472 if (opti < args.length) { 11473 String cmd = args[opti]; 11474 opti++; 11475 // Is this a package name? 11476 if ("android".equals(cmd) || cmd.contains(".")) { 11477 packageName = cmd; 11478 // When dumping a single package, we always dump all of its 11479 // filter information since the amount of data will be reasonable. 11480 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11481 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 11482 dumpState.setDump(DumpState.DUMP_LIBS); 11483 } else if ("f".equals(cmd) || "features".equals(cmd)) { 11484 dumpState.setDump(DumpState.DUMP_FEATURES); 11485 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 11486 dumpState.setDump(DumpState.DUMP_RESOLVERS); 11487 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 11488 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 11489 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 11490 dumpState.setDump(DumpState.DUMP_PREFERRED); 11491 } else if ("preferred-xml".equals(cmd)) { 11492 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 11493 if (opti < args.length && "--full".equals(args[opti])) { 11494 fullPreferred = true; 11495 opti++; 11496 } 11497 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 11498 dumpState.setDump(DumpState.DUMP_PACKAGES); 11499 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 11500 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 11501 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 11502 dumpState.setDump(DumpState.DUMP_PROVIDERS); 11503 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 11504 dumpState.setDump(DumpState.DUMP_MESSAGES); 11505 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 11506 dumpState.setDump(DumpState.DUMP_VERIFIERS); 11507 } else if ("version".equals(cmd)) { 11508 dumpState.setDump(DumpState.DUMP_VERSION); 11509 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 11510 dumpState.setDump(DumpState.DUMP_KEYSETS); 11511 } 11512 } 11513 11514 if (checkin) { 11515 pw.println("vers,1"); 11516 } 11517 11518 // reader 11519 synchronized (mPackages) { 11520 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 11521 if (!checkin) { 11522 if (dumpState.onTitlePrinted()) 11523 pw.println(); 11524 pw.println("Database versions:"); 11525 pw.print(" SDK Version:"); 11526 pw.print(" internal="); 11527 pw.print(mSettings.mInternalSdkPlatform); 11528 pw.print(" external="); 11529 pw.println(mSettings.mExternalSdkPlatform); 11530 pw.print(" DB Version:"); 11531 pw.print(" internal="); 11532 pw.print(mSettings.mInternalDatabaseVersion); 11533 pw.print(" external="); 11534 pw.println(mSettings.mExternalDatabaseVersion); 11535 } 11536 } 11537 11538 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 11539 if (!checkin) { 11540 if (dumpState.onTitlePrinted()) 11541 pw.println(); 11542 pw.println("Verifiers:"); 11543 pw.print(" Required: "); 11544 pw.print(mRequiredVerifierPackage); 11545 pw.print(" (uid="); 11546 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 11547 pw.println(")"); 11548 } else if (mRequiredVerifierPackage != null) { 11549 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 11550 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 11551 } 11552 } 11553 11554 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 11555 boolean printedHeader = false; 11556 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 11557 while (it.hasNext()) { 11558 String name = it.next(); 11559 SharedLibraryEntry ent = mSharedLibraries.get(name); 11560 if (!checkin) { 11561 if (!printedHeader) { 11562 if (dumpState.onTitlePrinted()) 11563 pw.println(); 11564 pw.println("Libraries:"); 11565 printedHeader = true; 11566 } 11567 pw.print(" "); 11568 } else { 11569 pw.print("lib,"); 11570 } 11571 pw.print(name); 11572 if (!checkin) { 11573 pw.print(" -> "); 11574 } 11575 if (ent.path != null) { 11576 if (!checkin) { 11577 pw.print("(jar) "); 11578 pw.print(ent.path); 11579 } else { 11580 pw.print(",jar,"); 11581 pw.print(ent.path); 11582 } 11583 } else { 11584 if (!checkin) { 11585 pw.print("(apk) "); 11586 pw.print(ent.apk); 11587 } else { 11588 pw.print(",apk,"); 11589 pw.print(ent.apk); 11590 } 11591 } 11592 pw.println(); 11593 } 11594 } 11595 11596 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 11597 if (dumpState.onTitlePrinted()) 11598 pw.println(); 11599 if (!checkin) { 11600 pw.println("Features:"); 11601 } 11602 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 11603 while (it.hasNext()) { 11604 String name = it.next(); 11605 if (!checkin) { 11606 pw.print(" "); 11607 } else { 11608 pw.print("feat,"); 11609 } 11610 pw.println(name); 11611 } 11612 } 11613 11614 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 11615 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 11616 : "Activity Resolver Table:", " ", packageName, 11617 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11618 dumpState.setTitlePrinted(true); 11619 } 11620 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 11621 : "Receiver Resolver Table:", " ", packageName, 11622 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11623 dumpState.setTitlePrinted(true); 11624 } 11625 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 11626 : "Service Resolver Table:", " ", packageName, 11627 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11628 dumpState.setTitlePrinted(true); 11629 } 11630 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 11631 : "Provider Resolver Table:", " ", packageName, 11632 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11633 dumpState.setTitlePrinted(true); 11634 } 11635 } 11636 11637 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 11638 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11639 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11640 int user = mSettings.mPreferredActivities.keyAt(i); 11641 if (pir.dump(pw, 11642 dumpState.getTitlePrinted() 11643 ? "\nPreferred Activities User " + user + ":" 11644 : "Preferred Activities User " + user + ":", " ", 11645 packageName, true)) { 11646 dumpState.setTitlePrinted(true); 11647 } 11648 } 11649 } 11650 11651 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 11652 pw.flush(); 11653 FileOutputStream fout = new FileOutputStream(fd); 11654 BufferedOutputStream str = new BufferedOutputStream(fout); 11655 XmlSerializer serializer = new FastXmlSerializer(); 11656 try { 11657 serializer.setOutput(str, "utf-8"); 11658 serializer.startDocument(null, true); 11659 serializer.setFeature( 11660 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 11661 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 11662 serializer.endDocument(); 11663 serializer.flush(); 11664 } catch (IllegalArgumentException e) { 11665 pw.println("Failed writing: " + e); 11666 } catch (IllegalStateException e) { 11667 pw.println("Failed writing: " + e); 11668 } catch (IOException e) { 11669 pw.println("Failed writing: " + e); 11670 } 11671 } 11672 11673 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 11674 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 11675 } 11676 11677 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 11678 boolean printedSomething = false; 11679 for (PackageParser.Provider p : mProviders.mProviders.values()) { 11680 if (packageName != null && !packageName.equals(p.info.packageName)) { 11681 continue; 11682 } 11683 if (!printedSomething) { 11684 if (dumpState.onTitlePrinted()) 11685 pw.println(); 11686 pw.println("Registered ContentProviders:"); 11687 printedSomething = true; 11688 } 11689 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 11690 pw.print(" "); pw.println(p.toString()); 11691 } 11692 printedSomething = false; 11693 for (Map.Entry<String, PackageParser.Provider> entry : 11694 mProvidersByAuthority.entrySet()) { 11695 PackageParser.Provider p = entry.getValue(); 11696 if (packageName != null && !packageName.equals(p.info.packageName)) { 11697 continue; 11698 } 11699 if (!printedSomething) { 11700 if (dumpState.onTitlePrinted()) 11701 pw.println(); 11702 pw.println("ContentProvider Authorities:"); 11703 printedSomething = true; 11704 } 11705 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 11706 pw.print(" "); pw.println(p.toString()); 11707 if (p.info != null && p.info.applicationInfo != null) { 11708 final String appInfo = p.info.applicationInfo.toString(); 11709 pw.print(" applicationInfo="); pw.println(appInfo); 11710 } 11711 } 11712 } 11713 11714 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 11715 mSettings.mKeySetManager.dump(pw, packageName, dumpState); 11716 } 11717 11718 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 11719 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 11720 } 11721 11722 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 11723 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 11724 } 11725 11726 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 11727 if (dumpState.onTitlePrinted()) 11728 pw.println(); 11729 mSettings.dumpReadMessagesLPr(pw, dumpState); 11730 11731 pw.println(); 11732 pw.println("Package warning messages:"); 11733 final File fname = getSettingsProblemFile(); 11734 FileInputStream in = null; 11735 try { 11736 in = new FileInputStream(fname); 11737 final int avail = in.available(); 11738 final byte[] data = new byte[avail]; 11739 in.read(data); 11740 pw.print(new String(data)); 11741 } catch (FileNotFoundException e) { 11742 } catch (IOException e) { 11743 } finally { 11744 if (in != null) { 11745 try { 11746 in.close(); 11747 } catch (IOException e) { 11748 } 11749 } 11750 } 11751 } 11752 } 11753 } 11754 11755 // ------- apps on sdcard specific code ------- 11756 static final boolean DEBUG_SD_INSTALL = false; 11757 11758 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 11759 11760 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 11761 11762 private boolean mMediaMounted = false; 11763 11764 private String getEncryptKey() { 11765 try { 11766 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 11767 SD_ENCRYPTION_KEYSTORE_NAME); 11768 if (sdEncKey == null) { 11769 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 11770 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 11771 if (sdEncKey == null) { 11772 Slog.e(TAG, "Failed to create encryption keys"); 11773 return null; 11774 } 11775 } 11776 return sdEncKey; 11777 } catch (NoSuchAlgorithmException nsae) { 11778 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 11779 return null; 11780 } catch (IOException ioe) { 11781 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 11782 return null; 11783 } 11784 11785 } 11786 11787 /* package */static String getTempContainerId() { 11788 int tmpIdx = 1; 11789 String list[] = PackageHelper.getSecureContainerList(); 11790 if (list != null) { 11791 for (final String name : list) { 11792 // Ignore null and non-temporary container entries 11793 if (name == null || !name.startsWith(mTempContainerPrefix)) { 11794 continue; 11795 } 11796 11797 String subStr = name.substring(mTempContainerPrefix.length()); 11798 try { 11799 int cid = Integer.parseInt(subStr); 11800 if (cid >= tmpIdx) { 11801 tmpIdx = cid + 1; 11802 } 11803 } catch (NumberFormatException e) { 11804 } 11805 } 11806 } 11807 return mTempContainerPrefix + tmpIdx; 11808 } 11809 11810 /* 11811 * Update media status on PackageManager. 11812 */ 11813 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 11814 int callingUid = Binder.getCallingUid(); 11815 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 11816 throw new SecurityException("Media status can only be updated by the system"); 11817 } 11818 // reader; this apparently protects mMediaMounted, but should probably 11819 // be a different lock in that case. 11820 synchronized (mPackages) { 11821 Log.i(TAG, "Updating external media status from " 11822 + (mMediaMounted ? "mounted" : "unmounted") + " to " 11823 + (mediaStatus ? "mounted" : "unmounted")); 11824 if (DEBUG_SD_INSTALL) 11825 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 11826 + ", mMediaMounted=" + mMediaMounted); 11827 if (mediaStatus == mMediaMounted) { 11828 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 11829 : 0, -1); 11830 mHandler.sendMessage(msg); 11831 return; 11832 } 11833 mMediaMounted = mediaStatus; 11834 } 11835 // Queue up an async operation since the package installation may take a 11836 // little while. 11837 mHandler.post(new Runnable() { 11838 public void run() { 11839 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 11840 } 11841 }); 11842 } 11843 11844 /** 11845 * Called by MountService when the initial ASECs to scan are available. 11846 * Should block until all the ASEC containers are finished being scanned. 11847 */ 11848 public void scanAvailableAsecs() { 11849 updateExternalMediaStatusInner(true, false, false); 11850 if (mShouldRestoreconData) { 11851 SELinuxMMAC.setRestoreconDone(); 11852 mShouldRestoreconData = false; 11853 } 11854 } 11855 11856 /* 11857 * Collect information of applications on external media, map them against 11858 * existing containers and update information based on current mount status. 11859 * Please note that we always have to report status if reportStatus has been 11860 * set to true especially when unloading packages. 11861 */ 11862 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 11863 boolean externalStorage) { 11864 // Collection of uids 11865 int uidArr[] = null; 11866 // Collection of stale containers 11867 HashSet<String> removeCids = new HashSet<String>(); 11868 // Collection of packages on external media with valid containers. 11869 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 11870 // Get list of secure containers. 11871 final String list[] = PackageHelper.getSecureContainerList(); 11872 if (list == null || list.length == 0) { 11873 Log.i(TAG, "No secure containers on sdcard"); 11874 } else { 11875 // Process list of secure containers and categorize them 11876 // as active or stale based on their package internal state. 11877 int uidList[] = new int[list.length]; 11878 int num = 0; 11879 // reader 11880 synchronized (mPackages) { 11881 for (String cid : list) { 11882 if (DEBUG_SD_INSTALL) 11883 Log.i(TAG, "Processing container " + cid); 11884 String pkgName = getAsecPackageName(cid); 11885 if (pkgName == null) { 11886 if (DEBUG_SD_INSTALL) 11887 Log.i(TAG, "Container : " + cid + " stale"); 11888 removeCids.add(cid); 11889 continue; 11890 } 11891 if (DEBUG_SD_INSTALL) 11892 Log.i(TAG, "Looking for pkg : " + pkgName); 11893 11894 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11895 if (ps == null) { 11896 Log.i(TAG, "Deleting container with no matching settings " + cid); 11897 removeCids.add(cid); 11898 continue; 11899 } 11900 11901 /* 11902 * Skip packages that are not external if we're unmounting 11903 * external storage. 11904 */ 11905 if (externalStorage && !isMounted && !isExternal(ps)) { 11906 continue; 11907 } 11908 11909 final AsecInstallArgs args = new AsecInstallArgs(cid, 11910 getAppInstructionSetFromSettings(ps), 11911 isForwardLocked(ps)); 11912 // The package status is changed only if the code path 11913 // matches between settings and the container id. 11914 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 11915 if (DEBUG_SD_INSTALL) { 11916 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 11917 + " at code path: " + ps.codePathString); 11918 } 11919 11920 // We do have a valid package installed on sdcard 11921 processCids.put(args, ps.codePathString); 11922 final int uid = ps.appId; 11923 if (uid != -1) { 11924 uidList[num++] = uid; 11925 } 11926 } else { 11927 Log.i(TAG, "Deleting stale container for " + cid); 11928 removeCids.add(cid); 11929 } 11930 } 11931 } 11932 11933 if (num > 0) { 11934 // Sort uid list 11935 Arrays.sort(uidList, 0, num); 11936 // Throw away duplicates 11937 uidArr = new int[num]; 11938 uidArr[0] = uidList[0]; 11939 int di = 0; 11940 for (int i = 1; i < num; i++) { 11941 if (uidList[i - 1] != uidList[i]) { 11942 uidArr[di++] = uidList[i]; 11943 } 11944 } 11945 } 11946 } 11947 // Process packages with valid entries. 11948 if (isMounted) { 11949 if (DEBUG_SD_INSTALL) 11950 Log.i(TAG, "Loading packages"); 11951 loadMediaPackages(processCids, uidArr, removeCids); 11952 startCleaningPackages(); 11953 } else { 11954 if (DEBUG_SD_INSTALL) 11955 Log.i(TAG, "Unloading packages"); 11956 unloadMediaPackages(processCids, uidArr, reportStatus); 11957 } 11958 } 11959 11960 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 11961 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 11962 int size = pkgList.size(); 11963 if (size > 0) { 11964 // Send broadcasts here 11965 Bundle extras = new Bundle(); 11966 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 11967 .toArray(new String[size])); 11968 if (uidArr != null) { 11969 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 11970 } 11971 if (replacing) { 11972 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 11973 } 11974 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 11975 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 11976 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 11977 } 11978 } 11979 11980 /* 11981 * Look at potentially valid container ids from processCids If package 11982 * information doesn't match the one on record or package scanning fails, 11983 * the cid is added to list of removeCids. We currently don't delete stale 11984 * containers. 11985 */ 11986 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 11987 HashSet<String> removeCids) { 11988 ArrayList<String> pkgList = new ArrayList<String>(); 11989 Set<AsecInstallArgs> keys = processCids.keySet(); 11990 boolean doGc = false; 11991 for (AsecInstallArgs args : keys) { 11992 String codePath = processCids.get(args); 11993 if (DEBUG_SD_INSTALL) 11994 Log.i(TAG, "Loading container : " + args.cid); 11995 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11996 try { 11997 // Make sure there are no container errors first. 11998 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 11999 Slog.e(TAG, "Failed to mount cid : " + args.cid 12000 + " when installing from sdcard"); 12001 continue; 12002 } 12003 // Check code path here. 12004 if (codePath == null || !codePath.equals(args.getCodePath())) { 12005 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12006 + " does not match one in settings " + codePath); 12007 continue; 12008 } 12009 // Parse package 12010 int parseFlags = mDefParseFlags; 12011 if (args.isExternal()) { 12012 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12013 } 12014 if (args.isFwdLocked()) { 12015 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12016 } 12017 12018 doGc = true; 12019 synchronized (mInstallLock) { 12020 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 12021 0, 0, null); 12022 // Scan the package 12023 if (pkg != null) { 12024 /* 12025 * TODO why is the lock being held? doPostInstall is 12026 * called in other places without the lock. This needs 12027 * to be straightened out. 12028 */ 12029 // writer 12030 synchronized (mPackages) { 12031 retCode = PackageManager.INSTALL_SUCCEEDED; 12032 pkgList.add(pkg.packageName); 12033 // Post process args 12034 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12035 pkg.applicationInfo.uid); 12036 } 12037 } else { 12038 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12039 } 12040 } 12041 12042 } finally { 12043 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12044 // Don't destroy container here. Wait till gc clears things 12045 // up. 12046 removeCids.add(args.cid); 12047 } 12048 } 12049 } 12050 // writer 12051 synchronized (mPackages) { 12052 // If the platform SDK has changed since the last time we booted, 12053 // we need to re-grant app permission to catch any new ones that 12054 // appear. This is really a hack, and means that apps can in some 12055 // cases get permissions that the user didn't initially explicitly 12056 // allow... it would be nice to have some better way to handle 12057 // this situation. 12058 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12059 if (regrantPermissions) 12060 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12061 + mSdkVersion + "; regranting permissions for external storage"); 12062 mSettings.mExternalSdkPlatform = mSdkVersion; 12063 12064 // Make sure group IDs have been assigned, and any permission 12065 // changes in other apps are accounted for 12066 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12067 | (regrantPermissions 12068 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12069 : 0)); 12070 12071 mSettings.updateExternalDatabaseVersion(); 12072 12073 // can downgrade to reader 12074 // Persist settings 12075 mSettings.writeLPr(); 12076 } 12077 // Send a broadcast to let everyone know we are done processing 12078 if (pkgList.size() > 0) { 12079 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12080 } 12081 // Force gc to avoid any stale parser references that we might have. 12082 if (doGc) { 12083 Runtime.getRuntime().gc(); 12084 } 12085 // List stale containers and destroy stale temporary containers. 12086 if (removeCids != null) { 12087 for (String cid : removeCids) { 12088 if (cid.startsWith(mTempContainerPrefix)) { 12089 Log.i(TAG, "Destroying stale temporary container " + cid); 12090 PackageHelper.destroySdDir(cid); 12091 } else { 12092 Log.w(TAG, "Container " + cid + " is stale"); 12093 } 12094 } 12095 } 12096 } 12097 12098 /* 12099 * Utility method to unload a list of specified containers 12100 */ 12101 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12102 // Just unmount all valid containers. 12103 for (AsecInstallArgs arg : cidArgs) { 12104 synchronized (mInstallLock) { 12105 arg.doPostDeleteLI(false); 12106 } 12107 } 12108 } 12109 12110 /* 12111 * Unload packages mounted on external media. This involves deleting package 12112 * data from internal structures, sending broadcasts about diabled packages, 12113 * gc'ing to free up references, unmounting all secure containers 12114 * corresponding to packages on external media, and posting a 12115 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12116 * that we always have to post this message if status has been requested no 12117 * matter what. 12118 */ 12119 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12120 final boolean reportStatus) { 12121 if (DEBUG_SD_INSTALL) 12122 Log.i(TAG, "unloading media packages"); 12123 ArrayList<String> pkgList = new ArrayList<String>(); 12124 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12125 final Set<AsecInstallArgs> keys = processCids.keySet(); 12126 for (AsecInstallArgs args : keys) { 12127 String pkgName = args.getPackageName(); 12128 if (DEBUG_SD_INSTALL) 12129 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12130 // Delete package internally 12131 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12132 synchronized (mInstallLock) { 12133 boolean res = deletePackageLI(pkgName, null, false, null, null, 12134 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12135 if (res) { 12136 pkgList.add(pkgName); 12137 } else { 12138 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12139 failedList.add(args); 12140 } 12141 } 12142 } 12143 12144 // reader 12145 synchronized (mPackages) { 12146 // We didn't update the settings after removing each package; 12147 // write them now for all packages. 12148 mSettings.writeLPr(); 12149 } 12150 12151 // We have to absolutely send UPDATED_MEDIA_STATUS only 12152 // after confirming that all the receivers processed the ordered 12153 // broadcast when packages get disabled, force a gc to clean things up. 12154 // and unload all the containers. 12155 if (pkgList.size() > 0) { 12156 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12157 new IIntentReceiver.Stub() { 12158 public void performReceive(Intent intent, int resultCode, String data, 12159 Bundle extras, boolean ordered, boolean sticky, 12160 int sendingUser) throws RemoteException { 12161 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12162 reportStatus ? 1 : 0, 1, keys); 12163 mHandler.sendMessage(msg); 12164 } 12165 }); 12166 } else { 12167 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12168 keys); 12169 mHandler.sendMessage(msg); 12170 } 12171 } 12172 12173 /** Binder call */ 12174 @Override 12175 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12176 final int flags) { 12177 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12178 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12179 int returnCode = PackageManager.MOVE_SUCCEEDED; 12180 int currFlags = 0; 12181 int newFlags = 0; 12182 // reader 12183 synchronized (mPackages) { 12184 PackageParser.Package pkg = mPackages.get(packageName); 12185 if (pkg == null) { 12186 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12187 } else { 12188 // Disable moving fwd locked apps and system packages 12189 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12190 Slog.w(TAG, "Cannot move system application"); 12191 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12192 } else if (pkg.mOperationPending) { 12193 Slog.w(TAG, "Attempt to move package which has pending operations"); 12194 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12195 } else { 12196 // Find install location first 12197 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12198 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12199 Slog.w(TAG, "Ambigous flags specified for move location."); 12200 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12201 } else { 12202 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12203 : PackageManager.INSTALL_INTERNAL; 12204 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12205 : PackageManager.INSTALL_INTERNAL; 12206 12207 if (newFlags == currFlags) { 12208 Slog.w(TAG, "No move required. Trying to move to same location"); 12209 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12210 } else { 12211 if (isForwardLocked(pkg)) { 12212 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12213 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12214 } 12215 } 12216 } 12217 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12218 pkg.mOperationPending = true; 12219 } 12220 } 12221 } 12222 12223 /* 12224 * TODO this next block probably shouldn't be inside the lock. We 12225 * can't guarantee these won't change after this is fired off 12226 * anyway. 12227 */ 12228 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12229 processPendingMove(new MoveParams(null, observer, 0, packageName, null, 12230 null, -1, user), 12231 returnCode); 12232 } else { 12233 Message msg = mHandler.obtainMessage(INIT_COPY); 12234 final String instructionSet = getAppInstructionSet(pkg.applicationInfo); 12235 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir, 12236 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir, 12237 instructionSet); 12238 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12239 pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user); 12240 msg.obj = mp; 12241 mHandler.sendMessage(msg); 12242 } 12243 } 12244 } 12245 12246 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12247 // Queue up an async operation since the package deletion may take a 12248 // little while. 12249 mHandler.post(new Runnable() { 12250 public void run() { 12251 // TODO fix this; this does nothing. 12252 mHandler.removeCallbacks(this); 12253 int returnCode = currentStatus; 12254 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12255 int uidArr[] = null; 12256 ArrayList<String> pkgList = null; 12257 synchronized (mPackages) { 12258 PackageParser.Package pkg = mPackages.get(mp.packageName); 12259 if (pkg == null) { 12260 Slog.w(TAG, " Package " + mp.packageName 12261 + " doesn't exist. Aborting move"); 12262 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12263 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 12264 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12265 + mp.srcArgs.getCodePath() + " to " 12266 + pkg.applicationInfo.sourceDir 12267 + " Aborting move and returning error"); 12268 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12269 } else { 12270 uidArr = new int[] { 12271 pkg.applicationInfo.uid 12272 }; 12273 pkgList = new ArrayList<String>(); 12274 pkgList.add(mp.packageName); 12275 } 12276 } 12277 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12278 // Send resources unavailable broadcast 12279 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12280 // Update package code and resource paths 12281 synchronized (mInstallLock) { 12282 synchronized (mPackages) { 12283 PackageParser.Package pkg = mPackages.get(mp.packageName); 12284 // Recheck for package again. 12285 if (pkg == null) { 12286 Slog.w(TAG, " Package " + mp.packageName 12287 + " doesn't exist. Aborting move"); 12288 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12289 } else if (!mp.srcArgs.getCodePath().equals( 12290 pkg.applicationInfo.sourceDir)) { 12291 Slog.w(TAG, "Package " + mp.packageName 12292 + " code path changed from " + mp.srcArgs.getCodePath() 12293 + " to " + pkg.applicationInfo.sourceDir 12294 + " Aborting move and returning error"); 12295 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12296 } else { 12297 final String oldCodePath = pkg.mPath; 12298 final String newCodePath = mp.targetArgs.getCodePath(); 12299 final String newResPath = mp.targetArgs.getResourcePath(); 12300 final String newNativePath = mp.targetArgs 12301 .getNativeLibraryPath(); 12302 12303 final File newNativeDir = new File(newNativePath); 12304 12305 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12306 // NOTE: We do not report any errors from the APK scan and library 12307 // copy at this point. 12308 NativeLibraryHelper.ApkHandle handle = 12309 new NativeLibraryHelper.ApkHandle(newCodePath); 12310 final int abi = NativeLibraryHelper.findSupportedAbi( 12311 handle, Build.SUPPORTED_ABIS); 12312 if (abi >= 0) { 12313 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12314 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12315 } 12316 handle.close(); 12317 } 12318 final int[] users = sUserManager.getUserIds(); 12319 for (int user : users) { 12320 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 12321 newNativePath, user) < 0) { 12322 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12323 } 12324 } 12325 12326 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12327 pkg.mPath = newCodePath; 12328 // Move dex files around 12329 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) { 12330 // Moving of dex files failed. Set 12331 // error code and abort move. 12332 pkg.mPath = pkg.mScanPath; 12333 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12334 } 12335 } 12336 12337 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12338 pkg.mScanPath = newCodePath; 12339 pkg.applicationInfo.sourceDir = newCodePath; 12340 pkg.applicationInfo.publicSourceDir = newResPath; 12341 pkg.applicationInfo.nativeLibraryDir = newNativePath; 12342 PackageSetting ps = (PackageSetting) pkg.mExtras; 12343 ps.codePath = new File(pkg.applicationInfo.sourceDir); 12344 ps.codePathString = ps.codePath.getPath(); 12345 ps.resourcePath = new File( 12346 pkg.applicationInfo.publicSourceDir); 12347 ps.resourcePathString = ps.resourcePath.getPath(); 12348 ps.nativeLibraryPathString = newNativePath; 12349 // Set the application info flag 12350 // correctly. 12351 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 12352 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12353 } else { 12354 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12355 } 12356 ps.setFlags(pkg.applicationInfo.flags); 12357 mAppDirs.remove(oldCodePath); 12358 mAppDirs.put(newCodePath, pkg); 12359 // Persist settings 12360 mSettings.writeLPr(); 12361 } 12362 } 12363 } 12364 } 12365 // Send resources available broadcast 12366 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12367 } 12368 } 12369 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12370 // Clean up failed installation 12371 if (mp.targetArgs != null) { 12372 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 12373 -1); 12374 } 12375 } else { 12376 // Force a gc to clear things up. 12377 Runtime.getRuntime().gc(); 12378 // Delete older code 12379 synchronized (mInstallLock) { 12380 mp.srcArgs.doPostDeleteLI(true); 12381 } 12382 } 12383 12384 // Allow more operations on this file if we didn't fail because 12385 // an operation was already pending for this package. 12386 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 12387 synchronized (mPackages) { 12388 PackageParser.Package pkg = mPackages.get(mp.packageName); 12389 if (pkg != null) { 12390 pkg.mOperationPending = false; 12391 } 12392 } 12393 } 12394 12395 IPackageMoveObserver observer = mp.observer; 12396 if (observer != null) { 12397 try { 12398 observer.packageMoved(mp.packageName, returnCode); 12399 } catch (RemoteException e) { 12400 Log.i(TAG, "Observer no longer exists."); 12401 } 12402 } 12403 } 12404 }); 12405 } 12406 12407 public boolean setInstallLocation(int loc) { 12408 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12409 null); 12410 if (getInstallLocation() == loc) { 12411 return true; 12412 } 12413 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12414 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12415 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12416 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12417 return true; 12418 } 12419 return false; 12420 } 12421 12422 public int getInstallLocation() { 12423 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12424 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12425 PackageHelper.APP_INSTALL_AUTO); 12426 } 12427 12428 /** Called by UserManagerService */ 12429 void cleanUpUserLILPw(int userHandle) { 12430 mDirtyUsers.remove(userHandle); 12431 mSettings.removeUserLPr(userHandle); 12432 mPendingBroadcasts.remove(userHandle); 12433 if (mInstaller != null) { 12434 // Technically, we shouldn't be doing this with the package lock 12435 // held. However, this is very rare, and there is already so much 12436 // other disk I/O going on, that we'll let it slide for now. 12437 mInstaller.removeUserDataDirs(userHandle); 12438 } 12439 } 12440 12441 /** Called by UserManagerService */ 12442 void createNewUserLILPw(int userHandle, File path) { 12443 if (mInstaller != null) { 12444 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 12445 } 12446 } 12447 12448 @Override 12449 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 12450 mContext.enforceCallingOrSelfPermission( 12451 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12452 "Only package verification agents can read the verifier device identity"); 12453 12454 synchronized (mPackages) { 12455 return mSettings.getVerifierDeviceIdentityLPw(); 12456 } 12457 } 12458 12459 @Override 12460 public void setPermissionEnforced(String permission, boolean enforced) { 12461 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 12462 if (READ_EXTERNAL_STORAGE.equals(permission)) { 12463 synchronized (mPackages) { 12464 if (mSettings.mReadExternalStorageEnforced == null 12465 || mSettings.mReadExternalStorageEnforced != enforced) { 12466 mSettings.mReadExternalStorageEnforced = enforced; 12467 mSettings.writeLPr(); 12468 } 12469 } 12470 // kill any non-foreground processes so we restart them and 12471 // grant/revoke the GID. 12472 final IActivityManager am = ActivityManagerNative.getDefault(); 12473 if (am != null) { 12474 final long token = Binder.clearCallingIdentity(); 12475 try { 12476 am.killProcessesBelowForeground("setPermissionEnforcement"); 12477 } catch (RemoteException e) { 12478 } finally { 12479 Binder.restoreCallingIdentity(token); 12480 } 12481 } 12482 } else { 12483 throw new IllegalArgumentException("No selective enforcement for " + permission); 12484 } 12485 } 12486 12487 @Override 12488 @Deprecated 12489 public boolean isPermissionEnforced(String permission) { 12490 return true; 12491 } 12492 12493 @Override 12494 public boolean isStorageLow() { 12495 final long token = Binder.clearCallingIdentity(); 12496 try { 12497 final DeviceStorageMonitorInternal 12498 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12499 if (dsm != null) { 12500 return dsm.isMemoryLow(); 12501 } else { 12502 return false; 12503 } 12504 } finally { 12505 Binder.restoreCallingIdentity(token); 12506 } 12507 } 12508} 12509