PackageManagerService.java revision 740888f62eae158d5775be716620f0d56d87f587
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 com.android.internal.util.ArrayUtils.appendInt; 27import static com.android.internal.util.ArrayUtils.removeInt; 28import static libcore.io.OsConstants.S_IRWXU; 29import static libcore.io.OsConstants.S_IRGRP; 30import static libcore.io.OsConstants.S_IXGRP; 31import static libcore.io.OsConstants.S_IROTH; 32import static libcore.io.OsConstants.S_IXOTH; 33 34import com.android.internal.app.IMediaContainerService; 35import com.android.internal.app.ResolverActivity; 36import com.android.internal.content.NativeLibraryHelper; 37import com.android.internal.content.PackageHelper; 38import com.android.internal.util.FastPrintWriter; 39import com.android.internal.util.FastXmlSerializer; 40import com.android.internal.util.XmlUtils; 41import com.android.server.EventLogTags; 42import com.android.server.IntentResolver; 43import com.android.server.ServiceThread; 44 45import com.android.server.LocalServices; 46import com.android.server.Watchdog; 47import org.xmlpull.v1.XmlPullParser; 48import org.xmlpull.v1.XmlPullParserException; 49import org.xmlpull.v1.XmlSerializer; 50 51import android.app.ActivityManager; 52import android.app.ActivityManagerNative; 53import android.app.IActivityManager; 54import android.app.admin.IDevicePolicyManager; 55import android.app.backup.IBackupManager; 56import android.content.BroadcastReceiver; 57import android.content.ComponentName; 58import android.content.Context; 59import android.content.IIntentReceiver; 60import android.content.Intent; 61import android.content.IntentFilter; 62import android.content.IntentSender; 63import android.content.IntentSender.SendIntentException; 64import android.content.ServiceConnection; 65import android.content.pm.ActivityInfo; 66import android.content.pm.ApplicationInfo; 67import android.content.pm.ContainerEncryptionParams; 68import android.content.pm.FeatureInfo; 69import android.content.pm.IPackageDataObserver; 70import android.content.pm.IPackageDeleteObserver; 71import android.content.pm.IPackageInstallObserver; 72import android.content.pm.IPackageInstallObserver2; 73import android.content.pm.IPackageManager; 74import android.content.pm.IPackageMoveObserver; 75import android.content.pm.IPackageStatsObserver; 76import android.content.pm.InstrumentationInfo; 77import android.content.pm.ManifestDigest; 78import android.content.pm.PackageCleanItem; 79import android.content.pm.PackageInfo; 80import android.content.pm.PackageInfoLite; 81import android.content.pm.PackageManager; 82import android.content.pm.PackageParser; 83import android.content.pm.PackageParser.ActivityIntentInfo; 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.HandlerThread; 108import android.os.IBinder; 109import android.os.Looper; 110import android.os.Message; 111import android.os.Parcel; 112import android.os.ParcelFileDescriptor; 113import android.os.Process; 114import android.os.RemoteException; 115import android.os.SELinux; 116import android.os.ServiceManager; 117import android.os.SystemClock; 118import android.os.SystemProperties; 119import android.os.UserHandle; 120import android.os.UserManager; 121import android.security.KeyStore; 122import android.security.SystemKeyStore; 123import android.text.TextUtils; 124import android.util.DisplayMetrics; 125import android.util.EventLog; 126import android.util.Log; 127import android.util.LogPrinter; 128import android.util.PrintStreamPrinter; 129import android.util.Slog; 130import android.util.SparseArray; 131import android.util.Xml; 132import android.view.Display; 133 134import java.io.BufferedOutputStream; 135import java.io.File; 136import java.io.FileDescriptor; 137import java.io.FileInputStream; 138import java.io.FileNotFoundException; 139import java.io.FileOutputStream; 140import java.io.FileReader; 141import java.io.FilenameFilter; 142import java.io.IOException; 143import java.io.PrintWriter; 144import java.security.NoSuchAlgorithmException; 145import java.security.PublicKey; 146import java.security.cert.CertificateException; 147import java.text.SimpleDateFormat; 148import java.util.ArrayList; 149import java.util.Arrays; 150import java.util.Collection; 151import java.util.Collections; 152import java.util.Comparator; 153import java.util.Date; 154import java.util.HashMap; 155import java.util.HashSet; 156import java.util.Iterator; 157import java.util.List; 158import java.util.Map; 159import java.util.Set; 160 161import libcore.io.ErrnoException; 162import libcore.io.IoUtils; 163import libcore.io.Libcore; 164import libcore.io.StructStat; 165 166import com.android.internal.R; 167import com.android.server.storage.DeviceStorageMonitorInternal; 168 169/** 170 * Keep track of all those .apks everywhere. 171 * 172 * This is very central to the platform's security; please run the unit 173 * tests whenever making modifications here: 174 * 175mmm frameworks/base/tests/AndroidTests 176adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 177adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 178 * 179 * {@hide} 180 */ 181public class PackageManagerService extends IPackageManager.Stub { 182 static final String TAG = "PackageManager"; 183 static final boolean DEBUG_SETTINGS = false; 184 static final boolean DEBUG_PREFERRED = false; 185 static final boolean DEBUG_UPGRADE = false; 186 private static final boolean DEBUG_INSTALL = false; 187 private static final boolean DEBUG_REMOVE = false; 188 private static final boolean DEBUG_BROADCASTS = false; 189 private static final boolean DEBUG_SHOW_INFO = false; 190 private static final boolean DEBUG_PACKAGE_INFO = false; 191 private static final boolean DEBUG_INTENT_MATCHING = false; 192 private static final boolean DEBUG_PACKAGE_SCANNING = false; 193 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 194 private static final boolean DEBUG_VERIFY = false; 195 196 private static final int RADIO_UID = Process.PHONE_UID; 197 private static final int LOG_UID = Process.LOG_UID; 198 private static final int NFC_UID = Process.NFC_UID; 199 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 200 private static final int SHELL_UID = Process.SHELL_UID; 201 202 private static final boolean GET_CERTIFICATES = true; 203 204 // Cap the size of permission trees that 3rd party apps can define 205 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 206 207 private static final int REMOVE_EVENTS = 208 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 209 private static final int ADD_EVENTS = 210 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 211 212 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 213 // Suffix used during package installation when copying/moving 214 // package apks to install directory. 215 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 216 217 static final int SCAN_MONITOR = 1<<0; 218 static final int SCAN_NO_DEX = 1<<1; 219 static final int SCAN_FORCE_DEX = 1<<2; 220 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 221 static final int SCAN_NEW_INSTALL = 1<<4; 222 static final int SCAN_NO_PATHS = 1<<5; 223 static final int SCAN_UPDATE_TIME = 1<<6; 224 static final int SCAN_DEFER_DEX = 1<<7; 225 static final int SCAN_BOOTING = 1<<8; 226 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 227 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 228 229 static final int REMOVE_CHATTY = 1<<16; 230 231 /** 232 * Timeout (in milliseconds) after which the watchdog should declare that 233 * our handler thread is wedged. The usual default for such things is one 234 * minute but we sometimes do very lengthy I/O operations on this thread, 235 * such as installing multi-gigabyte applications, so ours needs to be longer. 236 */ 237 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 238 239 /** 240 * Whether verification is enabled by default. 241 */ 242 private static final boolean DEFAULT_VERIFY_ENABLE = true; 243 244 /** 245 * The default maximum time to wait for the verification agent to return in 246 * milliseconds. 247 */ 248 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 249 250 /** 251 * The default response for package verification timeout. 252 * 253 * This can be either PackageManager.VERIFICATION_ALLOW or 254 * PackageManager.VERIFICATION_REJECT. 255 */ 256 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 257 258 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 259 260 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 261 DEFAULT_CONTAINER_PACKAGE, 262 "com.android.defcontainer.DefaultContainerService"); 263 264 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 265 266 private static final String LIB_DIR_NAME = "lib"; 267 private static final String LIB64_DIR_NAME = "lib64"; 268 269 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 270 271 static final String mTempContainerPrefix = "smdl2tmp"; 272 273 final ServiceThread mHandlerThread; 274 275 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 276 private static final String IDMAP_SUFFIX = "@idmap"; 277 278 final PackageHandler mHandler; 279 280 final int mSdkVersion = Build.VERSION.SDK_INT; 281 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME) 282 ? null : Build.VERSION.CODENAME; 283 284 final Context mContext; 285 final boolean mFactoryTest; 286 final boolean mOnlyCore; 287 final boolean mNoDexOpt; 288 final DisplayMetrics mMetrics; 289 final int mDefParseFlags; 290 final String[] mSeparateProcesses; 291 292 // This is where all application persistent data goes. 293 final File mAppDataDir; 294 295 // This is where all application persistent data goes for secondary users. 296 final File mUserAppDataDir; 297 298 /** The location for ASEC container files on internal storage. */ 299 final String mAsecInternalPath; 300 301 // This is the object monitoring the framework dir. 302 final FileObserver mFrameworkInstallObserver; 303 304 // This is the object monitoring the system app dir. 305 final FileObserver mSystemInstallObserver; 306 307 // This is the object monitoring the privileged system app dir. 308 final FileObserver mPrivilegedInstallObserver; 309 310 // This is the object monitoring the vendor app dir. 311 final FileObserver mVendorInstallObserver; 312 313 // This is the object monitoring the vendor overlay package dir. 314 final FileObserver mVendorOverlayInstallObserver; 315 316 // This is the object monitoring the OEM app dir. 317 final FileObserver mOemInstallObserver; 318 319 // This is the object monitoring mAppInstallDir. 320 final FileObserver mAppInstallObserver; 321 322 // This is the object monitoring mDrmAppPrivateInstallDir. 323 final FileObserver mDrmAppInstallObserver; 324 325 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 326 // LOCK HELD. Can be called with mInstallLock held. 327 final Installer mInstaller; 328 329 final File mAppInstallDir; 330 331 /** 332 * Directory to which applications installed internally have native 333 * libraries copied. 334 */ 335 private File mAppLibInstallDir; 336 337 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 338 // apps. 339 final File mDrmAppPrivateInstallDir; 340 341 // ---------------------------------------------------------------- 342 343 // Lock for state used when installing and doing other long running 344 // operations. Methods that must be called with this lock held have 345 // the suffix "LI". 346 final Object mInstallLock = new Object(); 347 348 // These are the directories in the 3rd party applications installed dir 349 // that we have currently loaded packages from. Keys are the application's 350 // installed zip file (absolute codePath), and values are Package. 351 final HashMap<String, PackageParser.Package> mAppDirs = 352 new HashMap<String, PackageParser.Package>(); 353 354 // Information for the parser to write more useful error messages. 355 int mLastScanError; 356 357 // ---------------------------------------------------------------- 358 359 // Keys are String (package name), values are Package. This also serves 360 // as the lock for the global state. Methods that must be called with 361 // this lock held have the prefix "LP". 362 final HashMap<String, PackageParser.Package> mPackages = 363 new HashMap<String, PackageParser.Package>(); 364 365 // Tracks available target package names -> overlay package paths. 366 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 367 new HashMap<String, HashMap<String, PackageParser.Package>>(); 368 369 final Settings mSettings; 370 boolean mRestoredSettings; 371 372 // Group-ids that are given to all packages as read from etc/permissions/*.xml. 373 int[] mGlobalGids; 374 375 // These are the built-in uid -> permission mappings that were read from the 376 // etc/permissions.xml file. 377 final SparseArray<HashSet<String>> mSystemPermissions = 378 new SparseArray<HashSet<String>>(); 379 380 static final class SharedLibraryEntry { 381 final String path; 382 final String apk; 383 384 SharedLibraryEntry(String _path, String _apk) { 385 path = _path; 386 apk = _apk; 387 } 388 } 389 390 // These are the built-in shared libraries that were read from the 391 // etc/permissions.xml file. 392 final HashMap<String, SharedLibraryEntry> mSharedLibraries 393 = new HashMap<String, SharedLibraryEntry>(); 394 395 // Temporary for building the final shared libraries for an .apk. 396 String[] mTmpSharedLibraries = null; 397 398 // These are the features this devices supports that were read from the 399 // etc/permissions.xml file. 400 final HashMap<String, FeatureInfo> mAvailableFeatures = 401 new HashMap<String, FeatureInfo>(); 402 403 // If mac_permissions.xml was found for seinfo labeling. 404 boolean mFoundPolicyFile; 405 406 // If a recursive restorecon of /data/data/<pkg> is needed. 407 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 408 409 // All available activities, for your resolving pleasure. 410 final ActivityIntentResolver mActivities = 411 new ActivityIntentResolver(); 412 413 // All available receivers, for your resolving pleasure. 414 final ActivityIntentResolver mReceivers = 415 new ActivityIntentResolver(); 416 417 // All available services, for your resolving pleasure. 418 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 419 420 // All available providers, for your resolving pleasure. 421 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 422 423 // Mapping from provider base names (first directory in content URI codePath) 424 // to the provider information. 425 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 426 new HashMap<String, PackageParser.Provider>(); 427 428 // Mapping from instrumentation class names to info about them. 429 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 430 new HashMap<ComponentName, PackageParser.Instrumentation>(); 431 432 // Mapping from permission names to info about them. 433 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 434 new HashMap<String, PackageParser.PermissionGroup>(); 435 436 // Packages whose data we have transfered into another package, thus 437 // should no longer exist. 438 final HashSet<String> mTransferedPackages = new HashSet<String>(); 439 440 // Broadcast actions that are only available to the system. 441 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 442 443 /** List of packages waiting for verification. */ 444 final SparseArray<PackageVerificationState> mPendingVerification 445 = new SparseArray<PackageVerificationState>(); 446 447 HashSet<PackageParser.Package> mDeferredDexOpt = null; 448 449 /** Token for keys in mPendingVerification. */ 450 private int mPendingVerificationToken = 0; 451 452 boolean mSystemReady; 453 boolean mSafeMode; 454 boolean mHasSystemUidErrors; 455 456 ApplicationInfo mAndroidApplication; 457 final ActivityInfo mResolveActivity = new ActivityInfo(); 458 final ResolveInfo mResolveInfo = new ResolveInfo(); 459 ComponentName mResolveComponentName; 460 PackageParser.Package mPlatformPackage; 461 ComponentName mCustomResolverComponentName; 462 463 boolean mResolverReplaced = false; 464 465 // Set of pending broadcasts for aggregating enable/disable of components. 466 static class PendingPackageBroadcasts { 467 // for each user id, a map of <package name -> components within that package> 468 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 469 470 public PendingPackageBroadcasts() { 471 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 472 } 473 474 public ArrayList<String> get(int userId, String packageName) { 475 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 476 return packages.get(packageName); 477 } 478 479 public void put(int userId, String packageName, ArrayList<String> components) { 480 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 481 packages.put(packageName, components); 482 } 483 484 public void remove(int userId, String packageName) { 485 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 486 if (packages != null) { 487 packages.remove(packageName); 488 } 489 } 490 491 public void remove(int userId) { 492 mUidMap.remove(userId); 493 } 494 495 public int userIdCount() { 496 return mUidMap.size(); 497 } 498 499 public int userIdAt(int n) { 500 return mUidMap.keyAt(n); 501 } 502 503 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 504 return mUidMap.get(userId); 505 } 506 507 public int size() { 508 // total number of pending broadcast entries across all userIds 509 int num = 0; 510 for (int i = 0; i< mUidMap.size(); i++) { 511 num += mUidMap.valueAt(i).size(); 512 } 513 return num; 514 } 515 516 public void clear() { 517 mUidMap.clear(); 518 } 519 520 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 521 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 522 if (map == null) { 523 map = new HashMap<String, ArrayList<String>>(); 524 mUidMap.put(userId, map); 525 } 526 return map; 527 } 528 } 529 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 530 531 // Service Connection to remote media container service to copy 532 // package uri's from external media onto secure containers 533 // or internal storage. 534 private IMediaContainerService mContainerService = null; 535 536 static final int SEND_PENDING_BROADCAST = 1; 537 static final int MCS_BOUND = 3; 538 static final int END_COPY = 4; 539 static final int INIT_COPY = 5; 540 static final int MCS_UNBIND = 6; 541 static final int START_CLEANING_PACKAGE = 7; 542 static final int FIND_INSTALL_LOC = 8; 543 static final int POST_INSTALL = 9; 544 static final int MCS_RECONNECT = 10; 545 static final int MCS_GIVE_UP = 11; 546 static final int UPDATED_MEDIA_STATUS = 12; 547 static final int WRITE_SETTINGS = 13; 548 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 549 static final int PACKAGE_VERIFIED = 15; 550 static final int CHECK_PENDING_VERIFICATION = 16; 551 552 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 553 554 // Delay time in millisecs 555 static final int BROADCAST_DELAY = 10 * 1000; 556 557 static UserManagerService sUserManager; 558 559 // Stores a list of users whose package restrictions file needs to be updated 560 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 561 562 final private DefaultContainerConnection mDefContainerConn = 563 new DefaultContainerConnection(); 564 class DefaultContainerConnection implements ServiceConnection { 565 public void onServiceConnected(ComponentName name, IBinder service) { 566 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 567 IMediaContainerService imcs = 568 IMediaContainerService.Stub.asInterface(service); 569 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 570 } 571 572 public void onServiceDisconnected(ComponentName name) { 573 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 574 } 575 }; 576 577 // Recordkeeping of restore-after-install operations that are currently in flight 578 // between the Package Manager and the Backup Manager 579 class PostInstallData { 580 public InstallArgs args; 581 public PackageInstalledInfo res; 582 583 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 584 args = _a; 585 res = _r; 586 } 587 }; 588 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 589 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 590 591 private final String mRequiredVerifierPackage; 592 593 class PackageHandler extends Handler { 594 private boolean mBound = false; 595 final ArrayList<HandlerParams> mPendingInstalls = 596 new ArrayList<HandlerParams>(); 597 598 private boolean connectToService() { 599 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 600 " DefaultContainerService"); 601 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 602 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 603 if (mContext.bindServiceAsUser(service, mDefContainerConn, 604 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 605 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 606 mBound = true; 607 return true; 608 } 609 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 610 return false; 611 } 612 613 private void disconnectService() { 614 mContainerService = null; 615 mBound = false; 616 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 617 mContext.unbindService(mDefContainerConn); 618 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 619 } 620 621 PackageHandler(Looper looper) { 622 super(looper); 623 } 624 625 public void handleMessage(Message msg) { 626 try { 627 doHandleMessage(msg); 628 } finally { 629 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 630 } 631 } 632 633 void doHandleMessage(Message msg) { 634 switch (msg.what) { 635 case INIT_COPY: { 636 HandlerParams params = (HandlerParams) msg.obj; 637 int idx = mPendingInstalls.size(); 638 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 639 // If a bind was already initiated we dont really 640 // need to do anything. The pending install 641 // will be processed later on. 642 if (!mBound) { 643 // If this is the only one pending we might 644 // have to bind to the service again. 645 if (!connectToService()) { 646 Slog.e(TAG, "Failed to bind to media container service"); 647 params.serviceError(); 648 return; 649 } else { 650 // Once we bind to the service, the first 651 // pending request will be processed. 652 mPendingInstalls.add(idx, params); 653 } 654 } else { 655 mPendingInstalls.add(idx, params); 656 // Already bound to the service. Just make 657 // sure we trigger off processing the first request. 658 if (idx == 0) { 659 mHandler.sendEmptyMessage(MCS_BOUND); 660 } 661 } 662 break; 663 } 664 case MCS_BOUND: { 665 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 666 if (msg.obj != null) { 667 mContainerService = (IMediaContainerService) msg.obj; 668 } 669 if (mContainerService == null) { 670 // Something seriously wrong. Bail out 671 Slog.e(TAG, "Cannot bind to media container service"); 672 for (HandlerParams params : mPendingInstalls) { 673 // Indicate service bind error 674 params.serviceError(); 675 } 676 mPendingInstalls.clear(); 677 } else if (mPendingInstalls.size() > 0) { 678 HandlerParams params = mPendingInstalls.get(0); 679 if (params != null) { 680 if (params.startCopy()) { 681 // We are done... look for more work or to 682 // go idle. 683 if (DEBUG_SD_INSTALL) Log.i(TAG, 684 "Checking for more work or unbind..."); 685 // Delete pending install 686 if (mPendingInstalls.size() > 0) { 687 mPendingInstalls.remove(0); 688 } 689 if (mPendingInstalls.size() == 0) { 690 if (mBound) { 691 if (DEBUG_SD_INSTALL) Log.i(TAG, 692 "Posting delayed MCS_UNBIND"); 693 removeMessages(MCS_UNBIND); 694 Message ubmsg = obtainMessage(MCS_UNBIND); 695 // Unbind after a little delay, to avoid 696 // continual thrashing. 697 sendMessageDelayed(ubmsg, 10000); 698 } 699 } else { 700 // There are more pending requests in queue. 701 // Just post MCS_BOUND message to trigger processing 702 // of next pending install. 703 if (DEBUG_SD_INSTALL) Log.i(TAG, 704 "Posting MCS_BOUND for next work"); 705 mHandler.sendEmptyMessage(MCS_BOUND); 706 } 707 } 708 } 709 } else { 710 // Should never happen ideally. 711 Slog.w(TAG, "Empty queue"); 712 } 713 break; 714 } 715 case MCS_RECONNECT: { 716 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 717 if (mPendingInstalls.size() > 0) { 718 if (mBound) { 719 disconnectService(); 720 } 721 if (!connectToService()) { 722 Slog.e(TAG, "Failed to bind to media container service"); 723 for (HandlerParams params : mPendingInstalls) { 724 // Indicate service bind error 725 params.serviceError(); 726 } 727 mPendingInstalls.clear(); 728 } 729 } 730 break; 731 } 732 case MCS_UNBIND: { 733 // If there is no actual work left, then time to unbind. 734 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 735 736 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 737 if (mBound) { 738 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 739 740 disconnectService(); 741 } 742 } else if (mPendingInstalls.size() > 0) { 743 // There are more pending requests in queue. 744 // Just post MCS_BOUND message to trigger processing 745 // of next pending install. 746 mHandler.sendEmptyMessage(MCS_BOUND); 747 } 748 749 break; 750 } 751 case MCS_GIVE_UP: { 752 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 753 mPendingInstalls.remove(0); 754 break; 755 } 756 case SEND_PENDING_BROADCAST: { 757 String packages[]; 758 ArrayList<String> components[]; 759 int size = 0; 760 int uids[]; 761 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 762 synchronized (mPackages) { 763 if (mPendingBroadcasts == null) { 764 return; 765 } 766 size = mPendingBroadcasts.size(); 767 if (size <= 0) { 768 // Nothing to be done. Just return 769 return; 770 } 771 packages = new String[size]; 772 components = new ArrayList[size]; 773 uids = new int[size]; 774 int i = 0; // filling out the above arrays 775 776 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 777 int packageUserId = mPendingBroadcasts.userIdAt(n); 778 Iterator<Map.Entry<String, ArrayList<String>>> it 779 = mPendingBroadcasts.packagesForUserId(packageUserId) 780 .entrySet().iterator(); 781 while (it.hasNext() && i < size) { 782 Map.Entry<String, ArrayList<String>> ent = it.next(); 783 packages[i] = ent.getKey(); 784 components[i] = ent.getValue(); 785 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 786 uids[i] = (ps != null) 787 ? UserHandle.getUid(packageUserId, ps.appId) 788 : -1; 789 i++; 790 } 791 } 792 size = i; 793 mPendingBroadcasts.clear(); 794 } 795 // Send broadcasts 796 for (int i = 0; i < size; i++) { 797 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 798 } 799 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 800 break; 801 } 802 case START_CLEANING_PACKAGE: { 803 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 804 final String packageName = (String)msg.obj; 805 final int userId = msg.arg1; 806 final boolean andCode = msg.arg2 != 0; 807 synchronized (mPackages) { 808 if (userId == UserHandle.USER_ALL) { 809 int[] users = sUserManager.getUserIds(); 810 for (int user : users) { 811 mSettings.addPackageToCleanLPw( 812 new PackageCleanItem(user, packageName, andCode)); 813 } 814 } else { 815 mSettings.addPackageToCleanLPw( 816 new PackageCleanItem(userId, packageName, andCode)); 817 } 818 } 819 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 820 startCleaningPackages(); 821 } break; 822 case POST_INSTALL: { 823 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 824 PostInstallData data = mRunningInstalls.get(msg.arg1); 825 mRunningInstalls.delete(msg.arg1); 826 boolean deleteOld = false; 827 828 if (data != null) { 829 InstallArgs args = data.args; 830 PackageInstalledInfo res = data.res; 831 832 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 833 res.removedInfo.sendBroadcast(false, true, false); 834 Bundle extras = new Bundle(1); 835 extras.putInt(Intent.EXTRA_UID, res.uid); 836 // Determine the set of users who are adding this 837 // package for the first time vs. those who are seeing 838 // an update. 839 int[] firstUsers; 840 int[] updateUsers = new int[0]; 841 if (res.origUsers == null || res.origUsers.length == 0) { 842 firstUsers = res.newUsers; 843 } else { 844 firstUsers = new int[0]; 845 for (int i=0; i<res.newUsers.length; i++) { 846 int user = res.newUsers[i]; 847 boolean isNew = true; 848 for (int j=0; j<res.origUsers.length; j++) { 849 if (res.origUsers[j] == user) { 850 isNew = false; 851 break; 852 } 853 } 854 if (isNew) { 855 int[] newFirst = new int[firstUsers.length+1]; 856 System.arraycopy(firstUsers, 0, newFirst, 0, 857 firstUsers.length); 858 newFirst[firstUsers.length] = user; 859 firstUsers = newFirst; 860 } else { 861 int[] newUpdate = new int[updateUsers.length+1]; 862 System.arraycopy(updateUsers, 0, newUpdate, 0, 863 updateUsers.length); 864 newUpdate[updateUsers.length] = user; 865 updateUsers = newUpdate; 866 } 867 } 868 } 869 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 870 res.pkg.applicationInfo.packageName, 871 extras, null, null, firstUsers); 872 final boolean update = res.removedInfo.removedPackage != null; 873 if (update) { 874 extras.putBoolean(Intent.EXTRA_REPLACING, true); 875 } 876 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 877 res.pkg.applicationInfo.packageName, 878 extras, null, null, updateUsers); 879 if (update) { 880 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 881 res.pkg.applicationInfo.packageName, 882 extras, null, null, updateUsers); 883 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 884 null, null, 885 res.pkg.applicationInfo.packageName, null, updateUsers); 886 887 // treat asec-hosted packages like removable media on upgrade 888 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 889 if (DEBUG_INSTALL) { 890 Slog.i(TAG, "upgrading pkg " + res.pkg 891 + " is ASEC-hosted -> AVAILABLE"); 892 } 893 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 894 ArrayList<String> pkgList = new ArrayList<String>(1); 895 pkgList.add(res.pkg.applicationInfo.packageName); 896 sendResourcesChangedBroadcast(true, true, 897 pkgList,uidArray, null); 898 } 899 } 900 if (res.removedInfo.args != null) { 901 // Remove the replaced package's older resources safely now 902 deleteOld = true; 903 } 904 905 // Log current value of "unknown sources" setting 906 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 907 getUnknownSourcesSettings()); 908 } 909 // Force a gc to clear up things 910 Runtime.getRuntime().gc(); 911 // We delete after a gc for applications on sdcard. 912 if (deleteOld) { 913 synchronized (mInstallLock) { 914 res.removedInfo.args.doPostDeleteLI(true); 915 } 916 } 917 if (args.observer != null) { 918 try { 919 args.observer.packageInstalled(res.name, res.returnCode); 920 } catch (RemoteException e) { 921 Slog.i(TAG, "Observer no longer exists."); 922 } 923 } 924 if (args.observer2 != null) { 925 try { 926 Bundle extras = extrasForInstallResult(res); 927 args.observer2.packageInstalled(res.name, extras, res.returnCode); 928 } catch (RemoteException e) { 929 Slog.i(TAG, "Observer no longer exists."); 930 } 931 } 932 } else { 933 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 934 } 935 } break; 936 case UPDATED_MEDIA_STATUS: { 937 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 938 boolean reportStatus = msg.arg1 == 1; 939 boolean doGc = msg.arg2 == 1; 940 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 941 if (doGc) { 942 // Force a gc to clear up stale containers. 943 Runtime.getRuntime().gc(); 944 } 945 if (msg.obj != null) { 946 @SuppressWarnings("unchecked") 947 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 948 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 949 // Unload containers 950 unloadAllContainers(args); 951 } 952 if (reportStatus) { 953 try { 954 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 955 PackageHelper.getMountService().finishMediaUpdate(); 956 } catch (RemoteException e) { 957 Log.e(TAG, "MountService not running?"); 958 } 959 } 960 } break; 961 case WRITE_SETTINGS: { 962 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 963 synchronized (mPackages) { 964 removeMessages(WRITE_SETTINGS); 965 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 966 mSettings.writeLPr(); 967 mDirtyUsers.clear(); 968 } 969 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 970 } break; 971 case WRITE_PACKAGE_RESTRICTIONS: { 972 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 973 synchronized (mPackages) { 974 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 975 for (int userId : mDirtyUsers) { 976 mSettings.writePackageRestrictionsLPr(userId); 977 } 978 mDirtyUsers.clear(); 979 } 980 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 981 } break; 982 case CHECK_PENDING_VERIFICATION: { 983 final int verificationId = msg.arg1; 984 final PackageVerificationState state = mPendingVerification.get(verificationId); 985 986 if ((state != null) && !state.timeoutExtended()) { 987 final InstallArgs args = state.getInstallArgs(); 988 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString()); 989 mPendingVerification.remove(verificationId); 990 991 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 992 993 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 994 Slog.i(TAG, "Continuing with installation of " 995 + args.packageURI.toString()); 996 state.setVerifierResponse(Binder.getCallingUid(), 997 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 998 broadcastPackageVerified(verificationId, args.packageURI, 999 PackageManager.VERIFICATION_ALLOW, 1000 state.getInstallArgs().getUser()); 1001 try { 1002 ret = args.copyApk(mContainerService, true); 1003 } catch (RemoteException e) { 1004 Slog.e(TAG, "Could not contact the ContainerService"); 1005 } 1006 } else { 1007 broadcastPackageVerified(verificationId, args.packageURI, 1008 PackageManager.VERIFICATION_REJECT, 1009 state.getInstallArgs().getUser()); 1010 } 1011 1012 processPendingInstall(args, ret); 1013 mHandler.sendEmptyMessage(MCS_UNBIND); 1014 } 1015 break; 1016 } 1017 case PACKAGE_VERIFIED: { 1018 final int verificationId = msg.arg1; 1019 1020 final PackageVerificationState state = mPendingVerification.get(verificationId); 1021 if (state == null) { 1022 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1023 break; 1024 } 1025 1026 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1027 1028 state.setVerifierResponse(response.callerUid, response.code); 1029 1030 if (state.isVerificationComplete()) { 1031 mPendingVerification.remove(verificationId); 1032 1033 final InstallArgs args = state.getInstallArgs(); 1034 1035 int ret; 1036 if (state.isInstallAllowed()) { 1037 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1038 broadcastPackageVerified(verificationId, args.packageURI, 1039 response.code, state.getInstallArgs().getUser()); 1040 try { 1041 ret = args.copyApk(mContainerService, true); 1042 } catch (RemoteException e) { 1043 Slog.e(TAG, "Could not contact the ContainerService"); 1044 } 1045 } else { 1046 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1047 } 1048 1049 processPendingInstall(args, ret); 1050 1051 mHandler.sendEmptyMessage(MCS_UNBIND); 1052 } 1053 1054 break; 1055 } 1056 } 1057 } 1058 } 1059 1060 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1061 Bundle extras = null; 1062 switch (res.returnCode) { 1063 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1064 extras = new Bundle(); 1065 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1066 res.origPermission); 1067 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1068 res.origPackage); 1069 break; 1070 } 1071 } 1072 return extras; 1073 } 1074 1075 void scheduleWriteSettingsLocked() { 1076 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1077 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1078 } 1079 } 1080 1081 void scheduleWritePackageRestrictionsLocked(int userId) { 1082 if (!sUserManager.exists(userId)) return; 1083 mDirtyUsers.add(userId); 1084 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1085 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1086 } 1087 } 1088 1089 public static final IPackageManager main(Context context, Installer installer, 1090 boolean factoryTest, boolean onlyCore) { 1091 PackageManagerService m = new PackageManagerService(context, installer, 1092 factoryTest, onlyCore); 1093 ServiceManager.addService("package", m); 1094 return m; 1095 } 1096 1097 static String[] splitString(String str, char sep) { 1098 int count = 1; 1099 int i = 0; 1100 while ((i=str.indexOf(sep, i)) >= 0) { 1101 count++; 1102 i++; 1103 } 1104 1105 String[] res = new String[count]; 1106 i=0; 1107 count = 0; 1108 int lastI=0; 1109 while ((i=str.indexOf(sep, i)) >= 0) { 1110 res[count] = str.substring(lastI, i); 1111 count++; 1112 i++; 1113 lastI = i; 1114 } 1115 res[count] = str.substring(lastI, str.length()); 1116 return res; 1117 } 1118 1119 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1120 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1121 Context.DISPLAY_SERVICE); 1122 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1123 } 1124 1125 public PackageManagerService(Context context, Installer installer, 1126 boolean factoryTest, boolean onlyCore) { 1127 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1128 SystemClock.uptimeMillis()); 1129 1130 if (mSdkVersion <= 0) { 1131 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1132 } 1133 1134 mContext = context; 1135 mFactoryTest = factoryTest; 1136 mOnlyCore = onlyCore; 1137 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1138 mMetrics = new DisplayMetrics(); 1139 mSettings = new Settings(context); 1140 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1141 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1142 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1143 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1144 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1145 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1146 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1147 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1148 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1149 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1150 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1151 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1152 1153 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1154 if (separateProcesses != null && separateProcesses.length() > 0) { 1155 if ("*".equals(separateProcesses)) { 1156 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1157 mSeparateProcesses = null; 1158 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1159 } else { 1160 mDefParseFlags = 0; 1161 mSeparateProcesses = separateProcesses.split(","); 1162 Slog.w(TAG, "Running with debug.separate_processes: " 1163 + separateProcesses); 1164 } 1165 } else { 1166 mDefParseFlags = 0; 1167 mSeparateProcesses = null; 1168 } 1169 1170 mInstaller = installer; 1171 1172 getDefaultDisplayMetrics(context, mMetrics); 1173 1174 synchronized (mInstallLock) { 1175 // writer 1176 synchronized (mPackages) { 1177 mHandlerThread = new ServiceThread(TAG, 1178 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1179 mHandlerThread.start(); 1180 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1181 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1182 1183 File dataDir = Environment.getDataDirectory(); 1184 mAppDataDir = new File(dataDir, "data"); 1185 mAppInstallDir = new File(dataDir, "app"); 1186 mAppLibInstallDir = new File(dataDir, "app-lib"); 1187 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1188 mUserAppDataDir = new File(dataDir, "user"); 1189 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1190 1191 sUserManager = new UserManagerService(context, this, 1192 mInstallLock, mPackages); 1193 1194 // Read permissions and features from system 1195 readPermissions(Environment.buildPath( 1196 Environment.getRootDirectory(), "etc", "permissions"), false); 1197 // Only read features from OEM 1198 readPermissions(Environment.buildPath( 1199 Environment.getOemDirectory(), "etc", "permissions"), true); 1200 1201 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1202 1203 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1204 mSdkVersion, mOnlyCore); 1205 1206 String customResolverActivity = Resources.getSystem().getString( 1207 R.string.config_customResolverActivity); 1208 if (TextUtils.isEmpty(customResolverActivity)) { 1209 customResolverActivity = null; 1210 } else { 1211 mCustomResolverComponentName = ComponentName.unflattenFromString( 1212 customResolverActivity); 1213 } 1214 1215 long startTime = SystemClock.uptimeMillis(); 1216 1217 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1218 startTime); 1219 1220 // Set flag to monitor and not change apk file paths when 1221 // scanning install directories. 1222 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1223 if (mNoDexOpt) { 1224 Slog.w(TAG, "Running ENG build: no pre-dexopt!"); 1225 scanMode |= SCAN_NO_DEX; 1226 } 1227 1228 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1229 1230 /** 1231 * Add everything in the in the boot class path to the 1232 * list of process files because dexopt will have been run 1233 * if necessary during zygote startup. 1234 */ 1235 String bootClassPath = System.getProperty("java.boot.class.path"); 1236 if (bootClassPath != null) { 1237 String[] paths = splitString(bootClassPath, ':'); 1238 for (int i=0; i<paths.length; i++) { 1239 alreadyDexOpted.add(paths[i]); 1240 } 1241 } else { 1242 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1243 } 1244 1245 boolean didDexOpt = false; 1246 1247 /** 1248 * Ensure all external libraries have had dexopt run on them. 1249 */ 1250 if (mSharedLibraries.size() > 0) { 1251 Iterator<SharedLibraryEntry> libs = mSharedLibraries.values().iterator(); 1252 while (libs.hasNext()) { 1253 String lib = libs.next().path; 1254 if (lib == null) { 1255 continue; 1256 } 1257 try { 1258 if (dalvik.system.DexFile.isDexOptNeededInternal(lib, null, false)) { 1259 alreadyDexOpted.add(lib); 1260 mInstaller.dexopt(lib, Process.SYSTEM_UID, true); 1261 didDexOpt = true; 1262 } 1263 } catch (FileNotFoundException e) { 1264 Slog.w(TAG, "Library not found: " + lib); 1265 } catch (IOException e) { 1266 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1267 + e.getMessage()); 1268 } 1269 } 1270 } 1271 1272 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1273 1274 // Gross hack for now: we know this file doesn't contain any 1275 // code, so don't dexopt it to avoid the resulting log spew. 1276 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1277 1278 // Gross hack for now: we know this file is only part of 1279 // the boot class path for art, so don't dexopt it to 1280 // avoid the resulting log spew. 1281 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1282 1283 /** 1284 * And there are a number of commands implemented in Java, which 1285 * we currently need to do the dexopt on so that they can be 1286 * run from a non-root shell. 1287 */ 1288 String[] frameworkFiles = frameworkDir.list(); 1289 if (frameworkFiles != null) { 1290 for (int i=0; i<frameworkFiles.length; i++) { 1291 File libPath = new File(frameworkDir, frameworkFiles[i]); 1292 String path = libPath.getPath(); 1293 // Skip the file if we alrady did it. 1294 if (alreadyDexOpted.contains(path)) { 1295 continue; 1296 } 1297 // Skip the file if it is not a type we want to dexopt. 1298 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1299 continue; 1300 } 1301 try { 1302 if (dalvik.system.DexFile.isDexOptNeededInternal(path, null, false)) { 1303 mInstaller.dexopt(path, Process.SYSTEM_UID, true); 1304 didDexOpt = true; 1305 } 1306 } catch (FileNotFoundException e) { 1307 Slog.w(TAG, "Jar not found: " + path); 1308 } catch (IOException e) { 1309 Slog.w(TAG, "Exception reading jar: " + path, e); 1310 } 1311 } 1312 } 1313 1314 if (didDexOpt) { 1315 File dalvikCacheDir = new File(dataDir, "dalvik-cache"); 1316 1317 // If we had to do a dexopt of one of the previous 1318 // things, then something on the system has changed. 1319 // Consider this significant, and wipe away all other 1320 // existing dexopt files to ensure we don't leave any 1321 // dangling around. 1322 String[] files = dalvikCacheDir.list(); 1323 if (files != null) { 1324 for (int i=0; i<files.length; i++) { 1325 String fn = files[i]; 1326 if (fn.startsWith("data@app@") 1327 || fn.startsWith("data@app-private@")) { 1328 Slog.i(TAG, "Pruning dalvik file: " + fn); 1329 (new File(dalvikCacheDir, fn)).delete(); 1330 } 1331 } 1332 } 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 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1511 SystemClock.uptimeMillis()); 1512 Slog.i(TAG, "Time to scan packages: " 1513 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1514 + " seconds"); 1515 1516 // If the platform SDK has changed since the last time we booted, 1517 // we need to re-grant app permission to catch any new ones that 1518 // appear. This is really a hack, and means that apps can in some 1519 // cases get permissions that the user didn't initially explicitly 1520 // allow... it would be nice to have some better way to handle 1521 // this situation. 1522 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1523 != mSdkVersion; 1524 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1525 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1526 + "; regranting permissions for internal storage"); 1527 mSettings.mInternalSdkPlatform = mSdkVersion; 1528 1529 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1530 | (regrantPermissions 1531 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1532 : 0)); 1533 1534 // If this is the first boot, and it is a normal boot, then 1535 // we need to initialize the default preferred apps. 1536 if (!mRestoredSettings && !onlyCore) { 1537 mSettings.readDefaultPreferredAppsLPw(this, 0); 1538 } 1539 1540 // can downgrade to reader 1541 mSettings.writeLPr(); 1542 1543 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1544 SystemClock.uptimeMillis()); 1545 1546 // Now after opening every single application zip, make sure they 1547 // are all flushed. Not really needed, but keeps things nice and 1548 // tidy. 1549 Runtime.getRuntime().gc(); 1550 1551 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1552 } // synchronized (mPackages) 1553 } // synchronized (mInstallLock) 1554 } 1555 1556 public boolean isFirstBoot() { 1557 return !mRestoredSettings; 1558 } 1559 1560 public boolean isOnlyCoreApps() { 1561 return mOnlyCore; 1562 } 1563 1564 private String getRequiredVerifierLPr() { 1565 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1566 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1567 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1568 1569 String requiredVerifier = null; 1570 1571 final int N = receivers.size(); 1572 for (int i = 0; i < N; i++) { 1573 final ResolveInfo info = receivers.get(i); 1574 1575 if (info.activityInfo == null) { 1576 continue; 1577 } 1578 1579 final String packageName = info.activityInfo.packageName; 1580 1581 final PackageSetting ps = mSettings.mPackages.get(packageName); 1582 if (ps == null) { 1583 continue; 1584 } 1585 1586 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1587 if (!gp.grantedPermissions 1588 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1589 continue; 1590 } 1591 1592 if (requiredVerifier != null) { 1593 throw new RuntimeException("There can be only one required verifier"); 1594 } 1595 1596 requiredVerifier = packageName; 1597 } 1598 1599 return requiredVerifier; 1600 } 1601 1602 @Override 1603 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1604 throws RemoteException { 1605 try { 1606 return super.onTransact(code, data, reply, flags); 1607 } catch (RuntimeException e) { 1608 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1609 Slog.wtf(TAG, "Package Manager Crash", e); 1610 } 1611 throw e; 1612 } 1613 } 1614 1615 void cleanupInstallFailedPackage(PackageSetting ps) { 1616 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1617 removeDataDirsLI(ps.name); 1618 if (ps.codePath != null) { 1619 if (!ps.codePath.delete()) { 1620 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1621 } 1622 } 1623 if (ps.resourcePath != null) { 1624 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1625 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1626 } 1627 } 1628 mSettings.removePackageLPw(ps.name); 1629 } 1630 1631 void readPermissions(File libraryDir, boolean onlyFeatures) { 1632 // Read permissions from .../etc/permission directory. 1633 if (!libraryDir.exists() || !libraryDir.isDirectory()) { 1634 Slog.w(TAG, "No directory " + libraryDir + ", skipping"); 1635 return; 1636 } 1637 if (!libraryDir.canRead()) { 1638 Slog.w(TAG, "Directory " + libraryDir + " cannot be read"); 1639 return; 1640 } 1641 1642 // Iterate over the files in the directory and scan .xml files 1643 for (File f : libraryDir.listFiles()) { 1644 // We'll read platform.xml last 1645 if (f.getPath().endsWith("etc/permissions/platform.xml")) { 1646 continue; 1647 } 1648 1649 if (!f.getPath().endsWith(".xml")) { 1650 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring"); 1651 continue; 1652 } 1653 if (!f.canRead()) { 1654 Slog.w(TAG, "Permissions library file " + f + " cannot be read"); 1655 continue; 1656 } 1657 1658 readPermissionsFromXml(f, onlyFeatures); 1659 } 1660 1661 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence 1662 final File permFile = new File(Environment.getRootDirectory(), 1663 "etc/permissions/platform.xml"); 1664 readPermissionsFromXml(permFile, onlyFeatures); 1665 } 1666 1667 private void readPermissionsFromXml(File permFile, boolean onlyFeatures) { 1668 FileReader permReader = null; 1669 try { 1670 permReader = new FileReader(permFile); 1671 } catch (FileNotFoundException e) { 1672 Slog.w(TAG, "Couldn't find or open permissions file " + permFile); 1673 return; 1674 } 1675 1676 try { 1677 XmlPullParser parser = Xml.newPullParser(); 1678 parser.setInput(permReader); 1679 1680 XmlUtils.beginDocument(parser, "permissions"); 1681 1682 while (true) { 1683 XmlUtils.nextElement(parser); 1684 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) { 1685 break; 1686 } 1687 1688 String name = parser.getName(); 1689 if ("group".equals(name) && !onlyFeatures) { 1690 String gidStr = parser.getAttributeValue(null, "gid"); 1691 if (gidStr != null) { 1692 int gid = Process.getGidForName(gidStr); 1693 mGlobalGids = appendInt(mGlobalGids, gid); 1694 } else { 1695 Slog.w(TAG, "<group> without gid at " 1696 + parser.getPositionDescription()); 1697 } 1698 1699 XmlUtils.skipCurrentTag(parser); 1700 continue; 1701 } else if ("permission".equals(name) && !onlyFeatures) { 1702 String perm = parser.getAttributeValue(null, "name"); 1703 if (perm == null) { 1704 Slog.w(TAG, "<permission> without name at " 1705 + parser.getPositionDescription()); 1706 XmlUtils.skipCurrentTag(parser); 1707 continue; 1708 } 1709 perm = perm.intern(); 1710 readPermission(parser, perm); 1711 1712 } else if ("assign-permission".equals(name) && !onlyFeatures) { 1713 String perm = parser.getAttributeValue(null, "name"); 1714 if (perm == null) { 1715 Slog.w(TAG, "<assign-permission> without name at " 1716 + parser.getPositionDescription()); 1717 XmlUtils.skipCurrentTag(parser); 1718 continue; 1719 } 1720 String uidStr = parser.getAttributeValue(null, "uid"); 1721 if (uidStr == null) { 1722 Slog.w(TAG, "<assign-permission> without uid at " 1723 + parser.getPositionDescription()); 1724 XmlUtils.skipCurrentTag(parser); 1725 continue; 1726 } 1727 int uid = Process.getUidForName(uidStr); 1728 if (uid < 0) { 1729 Slog.w(TAG, "<assign-permission> with unknown uid \"" 1730 + uidStr + "\" at " 1731 + parser.getPositionDescription()); 1732 XmlUtils.skipCurrentTag(parser); 1733 continue; 1734 } 1735 perm = perm.intern(); 1736 HashSet<String> perms = mSystemPermissions.get(uid); 1737 if (perms == null) { 1738 perms = new HashSet<String>(); 1739 mSystemPermissions.put(uid, perms); 1740 } 1741 perms.add(perm); 1742 XmlUtils.skipCurrentTag(parser); 1743 1744 } else if ("library".equals(name) && !onlyFeatures) { 1745 String lname = parser.getAttributeValue(null, "name"); 1746 String lfile = parser.getAttributeValue(null, "file"); 1747 if (lname == null) { 1748 Slog.w(TAG, "<library> without name at " 1749 + parser.getPositionDescription()); 1750 } else if (lfile == null) { 1751 Slog.w(TAG, "<library> without file at " 1752 + parser.getPositionDescription()); 1753 } else { 1754 //Log.i(TAG, "Got library " + lname + " in " + lfile); 1755 mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null)); 1756 } 1757 XmlUtils.skipCurrentTag(parser); 1758 continue; 1759 1760 } else if ("feature".equals(name)) { 1761 String fname = parser.getAttributeValue(null, "name"); 1762 if (fname == null) { 1763 Slog.w(TAG, "<feature> without name at " 1764 + parser.getPositionDescription()); 1765 } else { 1766 //Log.i(TAG, "Got feature " + fname); 1767 FeatureInfo fi = new FeatureInfo(); 1768 fi.name = fname; 1769 mAvailableFeatures.put(fname, fi); 1770 } 1771 XmlUtils.skipCurrentTag(parser); 1772 continue; 1773 1774 } else { 1775 XmlUtils.skipCurrentTag(parser); 1776 continue; 1777 } 1778 1779 } 1780 permReader.close(); 1781 } catch (XmlPullParserException e) { 1782 Slog.w(TAG, "Got execption parsing permissions.", e); 1783 } catch (IOException e) { 1784 Slog.w(TAG, "Got execption parsing permissions.", e); 1785 } 1786 } 1787 1788 void readPermission(XmlPullParser parser, String name) 1789 throws IOException, XmlPullParserException { 1790 1791 name = name.intern(); 1792 1793 BasePermission bp = mSettings.mPermissions.get(name); 1794 if (bp == null) { 1795 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN); 1796 mSettings.mPermissions.put(name, bp); 1797 } 1798 int outerDepth = parser.getDepth(); 1799 int type; 1800 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 1801 && (type != XmlPullParser.END_TAG 1802 || parser.getDepth() > outerDepth)) { 1803 if (type == XmlPullParser.END_TAG 1804 || type == XmlPullParser.TEXT) { 1805 continue; 1806 } 1807 1808 String tagName = parser.getName(); 1809 if ("group".equals(tagName)) { 1810 String gidStr = parser.getAttributeValue(null, "gid"); 1811 if (gidStr != null) { 1812 int gid = Process.getGidForName(gidStr); 1813 bp.gids = appendInt(bp.gids, gid); 1814 } else { 1815 Slog.w(TAG, "<group> without gid at " 1816 + parser.getPositionDescription()); 1817 } 1818 } 1819 XmlUtils.skipCurrentTag(parser); 1820 } 1821 } 1822 1823 static int[] appendInts(int[] cur, int[] add) { 1824 if (add == null) return cur; 1825 if (cur == null) return add; 1826 final int N = add.length; 1827 for (int i=0; i<N; i++) { 1828 cur = appendInt(cur, add[i]); 1829 } 1830 return cur; 1831 } 1832 1833 static int[] removeInts(int[] cur, int[] rem) { 1834 if (rem == null) return cur; 1835 if (cur == null) return cur; 1836 final int N = rem.length; 1837 for (int i=0; i<N; i++) { 1838 cur = removeInt(cur, rem[i]); 1839 } 1840 return cur; 1841 } 1842 1843 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1844 if (!sUserManager.exists(userId)) return null; 1845 PackageInfo pi; 1846 final PackageSetting ps = (PackageSetting) p.mExtras; 1847 if (ps == null) { 1848 return null; 1849 } 1850 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1851 final PackageUserState state = ps.readUserState(userId); 1852 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1853 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1854 state, userId); 1855 } 1856 1857 public boolean isPackageAvailable(String packageName, int userId) { 1858 if (!sUserManager.exists(userId)) return false; 1859 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1860 synchronized (mPackages) { 1861 PackageParser.Package p = mPackages.get(packageName); 1862 if (p != null) { 1863 final PackageSetting ps = (PackageSetting) p.mExtras; 1864 if (ps != null) { 1865 final PackageUserState state = ps.readUserState(userId); 1866 if (state != null) { 1867 return PackageParser.isAvailable(state); 1868 } 1869 } 1870 } 1871 } 1872 return false; 1873 } 1874 1875 @Override 1876 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1877 if (!sUserManager.exists(userId)) return null; 1878 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1879 // reader 1880 synchronized (mPackages) { 1881 PackageParser.Package p = mPackages.get(packageName); 1882 if (DEBUG_PACKAGE_INFO) 1883 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1884 if (p != null) { 1885 return generatePackageInfo(p, flags, userId); 1886 } 1887 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1888 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1889 } 1890 } 1891 return null; 1892 } 1893 1894 public String[] currentToCanonicalPackageNames(String[] names) { 1895 String[] out = new String[names.length]; 1896 // reader 1897 synchronized (mPackages) { 1898 for (int i=names.length-1; i>=0; i--) { 1899 PackageSetting ps = mSettings.mPackages.get(names[i]); 1900 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1901 } 1902 } 1903 return out; 1904 } 1905 1906 public String[] canonicalToCurrentPackageNames(String[] names) { 1907 String[] out = new String[names.length]; 1908 // reader 1909 synchronized (mPackages) { 1910 for (int i=names.length-1; i>=0; i--) { 1911 String cur = mSettings.mRenamedPackages.get(names[i]); 1912 out[i] = cur != null ? cur : names[i]; 1913 } 1914 } 1915 return out; 1916 } 1917 1918 @Override 1919 public int getPackageUid(String packageName, int userId) { 1920 if (!sUserManager.exists(userId)) return -1; 1921 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1922 // reader 1923 synchronized (mPackages) { 1924 PackageParser.Package p = mPackages.get(packageName); 1925 if(p != null) { 1926 return UserHandle.getUid(userId, p.applicationInfo.uid); 1927 } 1928 PackageSetting ps = mSettings.mPackages.get(packageName); 1929 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1930 return -1; 1931 } 1932 p = ps.pkg; 1933 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1934 } 1935 } 1936 1937 @Override 1938 public int[] getPackageGids(String packageName) { 1939 // reader 1940 synchronized (mPackages) { 1941 PackageParser.Package p = mPackages.get(packageName); 1942 if (DEBUG_PACKAGE_INFO) 1943 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1944 if (p != null) { 1945 final PackageSetting ps = (PackageSetting)p.mExtras; 1946 return ps.getGids(); 1947 } 1948 } 1949 // stupid thing to indicate an error. 1950 return new int[0]; 1951 } 1952 1953 static final PermissionInfo generatePermissionInfo( 1954 BasePermission bp, int flags) { 1955 if (bp.perm != null) { 1956 return PackageParser.generatePermissionInfo(bp.perm, flags); 1957 } 1958 PermissionInfo pi = new PermissionInfo(); 1959 pi.name = bp.name; 1960 pi.packageName = bp.sourcePackage; 1961 pi.nonLocalizedLabel = bp.name; 1962 pi.protectionLevel = bp.protectionLevel; 1963 return pi; 1964 } 1965 1966 public PermissionInfo getPermissionInfo(String name, int flags) { 1967 // reader 1968 synchronized (mPackages) { 1969 final BasePermission p = mSettings.mPermissions.get(name); 1970 if (p != null) { 1971 return generatePermissionInfo(p, flags); 1972 } 1973 return null; 1974 } 1975 } 1976 1977 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1978 // reader 1979 synchronized (mPackages) { 1980 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1981 for (BasePermission p : mSettings.mPermissions.values()) { 1982 if (group == null) { 1983 if (p.perm == null || p.perm.info.group == null) { 1984 out.add(generatePermissionInfo(p, flags)); 1985 } 1986 } else { 1987 if (p.perm != null && group.equals(p.perm.info.group)) { 1988 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1989 } 1990 } 1991 } 1992 1993 if (out.size() > 0) { 1994 return out; 1995 } 1996 return mPermissionGroups.containsKey(group) ? out : null; 1997 } 1998 } 1999 2000 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2001 // reader 2002 synchronized (mPackages) { 2003 return PackageParser.generatePermissionGroupInfo( 2004 mPermissionGroups.get(name), flags); 2005 } 2006 } 2007 2008 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2009 // reader 2010 synchronized (mPackages) { 2011 final int N = mPermissionGroups.size(); 2012 ArrayList<PermissionGroupInfo> out 2013 = new ArrayList<PermissionGroupInfo>(N); 2014 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2015 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2016 } 2017 return out; 2018 } 2019 } 2020 2021 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2022 int userId) { 2023 if (!sUserManager.exists(userId)) return null; 2024 PackageSetting ps = mSettings.mPackages.get(packageName); 2025 if (ps != null) { 2026 if (ps.pkg == null) { 2027 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2028 flags, userId); 2029 if (pInfo != null) { 2030 return pInfo.applicationInfo; 2031 } 2032 return null; 2033 } 2034 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2035 ps.readUserState(userId), userId); 2036 } 2037 return null; 2038 } 2039 2040 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2041 int userId) { 2042 if (!sUserManager.exists(userId)) return null; 2043 PackageSetting ps = mSettings.mPackages.get(packageName); 2044 if (ps != null) { 2045 PackageParser.Package pkg = ps.pkg; 2046 if (pkg == null) { 2047 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2048 return null; 2049 } 2050 pkg = new PackageParser.Package(packageName); 2051 pkg.applicationInfo.packageName = packageName; 2052 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2053 pkg.applicationInfo.publicSourceDir = ps.resourcePathString; 2054 pkg.applicationInfo.sourceDir = ps.codePathString; 2055 pkg.applicationInfo.dataDir = 2056 getDataPathForPackage(packageName, 0).getPath(); 2057 pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString; 2058 pkg.applicationInfo.requiredCpuAbi = ps.requiredCpuAbiString; 2059 } 2060 return generatePackageInfo(pkg, flags, userId); 2061 } 2062 return null; 2063 } 2064 2065 @Override 2066 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2067 if (!sUserManager.exists(userId)) return null; 2068 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2069 // writer 2070 synchronized (mPackages) { 2071 PackageParser.Package p = mPackages.get(packageName); 2072 if (DEBUG_PACKAGE_INFO) Log.v( 2073 TAG, "getApplicationInfo " + packageName 2074 + ": " + p); 2075 if (p != null) { 2076 PackageSetting ps = mSettings.mPackages.get(packageName); 2077 if (ps == null) return null; 2078 // Note: isEnabledLP() does not apply here - always return info 2079 return PackageParser.generateApplicationInfo( 2080 p, flags, ps.readUserState(userId), userId); 2081 } 2082 if ("android".equals(packageName)||"system".equals(packageName)) { 2083 return mAndroidApplication; 2084 } 2085 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2086 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2087 } 2088 } 2089 return null; 2090 } 2091 2092 2093 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2094 mContext.enforceCallingOrSelfPermission( 2095 android.Manifest.permission.CLEAR_APP_CACHE, null); 2096 // Queue up an async operation since clearing cache may take a little while. 2097 mHandler.post(new Runnable() { 2098 public void run() { 2099 mHandler.removeCallbacks(this); 2100 int retCode = -1; 2101 synchronized (mInstallLock) { 2102 retCode = mInstaller.freeCache(freeStorageSize); 2103 if (retCode < 0) { 2104 Slog.w(TAG, "Couldn't clear application caches"); 2105 } 2106 } 2107 if (observer != null) { 2108 try { 2109 observer.onRemoveCompleted(null, (retCode >= 0)); 2110 } catch (RemoteException e) { 2111 Slog.w(TAG, "RemoveException when invoking call back"); 2112 } 2113 } 2114 } 2115 }); 2116 } 2117 2118 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2119 mContext.enforceCallingOrSelfPermission( 2120 android.Manifest.permission.CLEAR_APP_CACHE, null); 2121 // Queue up an async operation since clearing cache may take a little while. 2122 mHandler.post(new Runnable() { 2123 public void run() { 2124 mHandler.removeCallbacks(this); 2125 int retCode = -1; 2126 synchronized (mInstallLock) { 2127 retCode = mInstaller.freeCache(freeStorageSize); 2128 if (retCode < 0) { 2129 Slog.w(TAG, "Couldn't clear application caches"); 2130 } 2131 } 2132 if(pi != null) { 2133 try { 2134 // Callback via pending intent 2135 int code = (retCode >= 0) ? 1 : 0; 2136 pi.sendIntent(null, code, null, 2137 null, null); 2138 } catch (SendIntentException e1) { 2139 Slog.i(TAG, "Failed to send pending intent"); 2140 } 2141 } 2142 } 2143 }); 2144 } 2145 2146 @Override 2147 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2148 if (!sUserManager.exists(userId)) return null; 2149 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2150 synchronized (mPackages) { 2151 PackageParser.Activity a = mActivities.mActivities.get(component); 2152 2153 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2154 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2155 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2156 if (ps == null) return null; 2157 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2158 userId); 2159 } 2160 if (mResolveComponentName.equals(component)) { 2161 return mResolveActivity; 2162 } 2163 } 2164 return null; 2165 } 2166 2167 @Override 2168 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2169 if (!sUserManager.exists(userId)) return null; 2170 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2171 synchronized (mPackages) { 2172 PackageParser.Activity a = mReceivers.mActivities.get(component); 2173 if (DEBUG_PACKAGE_INFO) Log.v( 2174 TAG, "getReceiverInfo " + component + ": " + a); 2175 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2176 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2177 if (ps == null) return null; 2178 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2179 userId); 2180 } 2181 } 2182 return null; 2183 } 2184 2185 @Override 2186 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2187 if (!sUserManager.exists(userId)) return null; 2188 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2189 synchronized (mPackages) { 2190 PackageParser.Service s = mServices.mServices.get(component); 2191 if (DEBUG_PACKAGE_INFO) Log.v( 2192 TAG, "getServiceInfo " + component + ": " + s); 2193 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2194 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2195 if (ps == null) return null; 2196 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2197 userId); 2198 } 2199 } 2200 return null; 2201 } 2202 2203 @Override 2204 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2205 if (!sUserManager.exists(userId)) return null; 2206 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2207 synchronized (mPackages) { 2208 PackageParser.Provider p = mProviders.mProviders.get(component); 2209 if (DEBUG_PACKAGE_INFO) Log.v( 2210 TAG, "getProviderInfo " + component + ": " + p); 2211 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2212 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2213 if (ps == null) return null; 2214 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2215 userId); 2216 } 2217 } 2218 return null; 2219 } 2220 2221 public String[] getSystemSharedLibraryNames() { 2222 Set<String> libSet; 2223 synchronized (mPackages) { 2224 libSet = mSharedLibraries.keySet(); 2225 int size = libSet.size(); 2226 if (size > 0) { 2227 String[] libs = new String[size]; 2228 libSet.toArray(libs); 2229 return libs; 2230 } 2231 } 2232 return null; 2233 } 2234 2235 public FeatureInfo[] getSystemAvailableFeatures() { 2236 Collection<FeatureInfo> featSet; 2237 synchronized (mPackages) { 2238 featSet = mAvailableFeatures.values(); 2239 int size = featSet.size(); 2240 if (size > 0) { 2241 FeatureInfo[] features = new FeatureInfo[size+1]; 2242 featSet.toArray(features); 2243 FeatureInfo fi = new FeatureInfo(); 2244 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2245 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2246 features[size] = fi; 2247 return features; 2248 } 2249 } 2250 return null; 2251 } 2252 2253 public boolean hasSystemFeature(String name) { 2254 synchronized (mPackages) { 2255 return mAvailableFeatures.containsKey(name); 2256 } 2257 } 2258 2259 private void checkValidCaller(int uid, int userId) { 2260 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2261 return; 2262 2263 throw new SecurityException("Caller uid=" + uid 2264 + " is not privileged to communicate with user=" + userId); 2265 } 2266 2267 public int checkPermission(String permName, String pkgName) { 2268 synchronized (mPackages) { 2269 PackageParser.Package p = mPackages.get(pkgName); 2270 if (p != null && p.mExtras != null) { 2271 PackageSetting ps = (PackageSetting)p.mExtras; 2272 if (ps.sharedUser != null) { 2273 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2274 return PackageManager.PERMISSION_GRANTED; 2275 } 2276 } else if (ps.grantedPermissions.contains(permName)) { 2277 return PackageManager.PERMISSION_GRANTED; 2278 } 2279 } 2280 } 2281 return PackageManager.PERMISSION_DENIED; 2282 } 2283 2284 public int checkUidPermission(String permName, int uid) { 2285 synchronized (mPackages) { 2286 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2287 if (obj != null) { 2288 GrantedPermissions gp = (GrantedPermissions)obj; 2289 if (gp.grantedPermissions.contains(permName)) { 2290 return PackageManager.PERMISSION_GRANTED; 2291 } 2292 } else { 2293 HashSet<String> perms = mSystemPermissions.get(uid); 2294 if (perms != null && perms.contains(permName)) { 2295 return PackageManager.PERMISSION_GRANTED; 2296 } 2297 } 2298 } 2299 return PackageManager.PERMISSION_DENIED; 2300 } 2301 2302 /** 2303 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2304 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2305 * @param message the message to log on security exception 2306 * @return 2307 */ 2308 private void enforceCrossUserPermission(int callingUid, int userId, 2309 boolean requireFullPermission, String message) { 2310 if (userId < 0) { 2311 throw new IllegalArgumentException("Invalid userId " + userId); 2312 } 2313 if (userId == UserHandle.getUserId(callingUid)) return; 2314 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2315 if (requireFullPermission) { 2316 mContext.enforceCallingOrSelfPermission( 2317 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2318 } else { 2319 try { 2320 mContext.enforceCallingOrSelfPermission( 2321 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2322 } catch (SecurityException se) { 2323 mContext.enforceCallingOrSelfPermission( 2324 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2325 } 2326 } 2327 } 2328 } 2329 2330 private BasePermission findPermissionTreeLP(String permName) { 2331 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2332 if (permName.startsWith(bp.name) && 2333 permName.length() > bp.name.length() && 2334 permName.charAt(bp.name.length()) == '.') { 2335 return bp; 2336 } 2337 } 2338 return null; 2339 } 2340 2341 private BasePermission checkPermissionTreeLP(String permName) { 2342 if (permName != null) { 2343 BasePermission bp = findPermissionTreeLP(permName); 2344 if (bp != null) { 2345 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2346 return bp; 2347 } 2348 throw new SecurityException("Calling uid " 2349 + Binder.getCallingUid() 2350 + " is not allowed to add to permission tree " 2351 + bp.name + " owned by uid " + bp.uid); 2352 } 2353 } 2354 throw new SecurityException("No permission tree found for " + permName); 2355 } 2356 2357 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2358 if (s1 == null) { 2359 return s2 == null; 2360 } 2361 if (s2 == null) { 2362 return false; 2363 } 2364 if (s1.getClass() != s2.getClass()) { 2365 return false; 2366 } 2367 return s1.equals(s2); 2368 } 2369 2370 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2371 if (pi1.icon != pi2.icon) return false; 2372 if (pi1.logo != pi2.logo) return false; 2373 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2374 if (!compareStrings(pi1.name, pi2.name)) return false; 2375 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2376 // We'll take care of setting this one. 2377 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2378 // These are not currently stored in settings. 2379 //if (!compareStrings(pi1.group, pi2.group)) return false; 2380 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2381 //if (pi1.labelRes != pi2.labelRes) return false; 2382 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2383 return true; 2384 } 2385 2386 int permissionInfoFootprint(PermissionInfo info) { 2387 int size = info.name.length(); 2388 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2389 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2390 return size; 2391 } 2392 2393 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2394 int size = 0; 2395 for (BasePermission perm : mSettings.mPermissions.values()) { 2396 if (perm.uid == tree.uid) { 2397 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2398 } 2399 } 2400 return size; 2401 } 2402 2403 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2404 // We calculate the max size of permissions defined by this uid and throw 2405 // if that plus the size of 'info' would exceed our stated maximum. 2406 if (tree.uid != Process.SYSTEM_UID) { 2407 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2408 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2409 throw new SecurityException("Permission tree size cap exceeded"); 2410 } 2411 } 2412 } 2413 2414 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2415 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2416 throw new SecurityException("Label must be specified in permission"); 2417 } 2418 BasePermission tree = checkPermissionTreeLP(info.name); 2419 BasePermission bp = mSettings.mPermissions.get(info.name); 2420 boolean added = bp == null; 2421 boolean changed = true; 2422 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2423 if (added) { 2424 enforcePermissionCapLocked(info, tree); 2425 bp = new BasePermission(info.name, tree.sourcePackage, 2426 BasePermission.TYPE_DYNAMIC); 2427 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2428 throw new SecurityException( 2429 "Not allowed to modify non-dynamic permission " 2430 + info.name); 2431 } else { 2432 if (bp.protectionLevel == fixedLevel 2433 && bp.perm.owner.equals(tree.perm.owner) 2434 && bp.uid == tree.uid 2435 && comparePermissionInfos(bp.perm.info, info)) { 2436 changed = false; 2437 } 2438 } 2439 bp.protectionLevel = fixedLevel; 2440 info = new PermissionInfo(info); 2441 info.protectionLevel = fixedLevel; 2442 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2443 bp.perm.info.packageName = tree.perm.info.packageName; 2444 bp.uid = tree.uid; 2445 if (added) { 2446 mSettings.mPermissions.put(info.name, bp); 2447 } 2448 if (changed) { 2449 if (!async) { 2450 mSettings.writeLPr(); 2451 } else { 2452 scheduleWriteSettingsLocked(); 2453 } 2454 } 2455 return added; 2456 } 2457 2458 public boolean addPermission(PermissionInfo info) { 2459 synchronized (mPackages) { 2460 return addPermissionLocked(info, false); 2461 } 2462 } 2463 2464 public boolean addPermissionAsync(PermissionInfo info) { 2465 synchronized (mPackages) { 2466 return addPermissionLocked(info, true); 2467 } 2468 } 2469 2470 public void removePermission(String name) { 2471 synchronized (mPackages) { 2472 checkPermissionTreeLP(name); 2473 BasePermission bp = mSettings.mPermissions.get(name); 2474 if (bp != null) { 2475 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2476 throw new SecurityException( 2477 "Not allowed to modify non-dynamic permission " 2478 + name); 2479 } 2480 mSettings.mPermissions.remove(name); 2481 mSettings.writeLPr(); 2482 } 2483 } 2484 } 2485 2486 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2487 int index = pkg.requestedPermissions.indexOf(bp.name); 2488 if (index == -1) { 2489 throw new SecurityException("Package " + pkg.packageName 2490 + " has not requested permission " + bp.name); 2491 } 2492 boolean isNormal = 2493 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2494 == PermissionInfo.PROTECTION_NORMAL); 2495 boolean isDangerous = 2496 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2497 == PermissionInfo.PROTECTION_DANGEROUS); 2498 boolean isDevelopment = 2499 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2500 2501 if (!isNormal && !isDangerous && !isDevelopment) { 2502 throw new SecurityException("Permission " + bp.name 2503 + " is not a changeable permission type"); 2504 } 2505 2506 if (isNormal || isDangerous) { 2507 if (pkg.requestedPermissionsRequired.get(index)) { 2508 throw new SecurityException("Can't change " + bp.name 2509 + ". It is required by the application"); 2510 } 2511 } 2512 } 2513 2514 public void grantPermission(String packageName, String permissionName) { 2515 mContext.enforceCallingOrSelfPermission( 2516 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2517 synchronized (mPackages) { 2518 final PackageParser.Package pkg = mPackages.get(packageName); 2519 if (pkg == null) { 2520 throw new IllegalArgumentException("Unknown package: " + packageName); 2521 } 2522 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2523 if (bp == null) { 2524 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2525 } 2526 2527 checkGrantRevokePermissions(pkg, bp); 2528 2529 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2530 if (ps == null) { 2531 return; 2532 } 2533 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2534 if (gp.grantedPermissions.add(permissionName)) { 2535 if (ps.haveGids) { 2536 gp.gids = appendInts(gp.gids, bp.gids); 2537 } 2538 mSettings.writeLPr(); 2539 } 2540 } 2541 } 2542 2543 public void revokePermission(String packageName, String permissionName) { 2544 int changedAppId = -1; 2545 2546 synchronized (mPackages) { 2547 final PackageParser.Package pkg = mPackages.get(packageName); 2548 if (pkg == null) { 2549 throw new IllegalArgumentException("Unknown package: " + packageName); 2550 } 2551 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2552 mContext.enforceCallingOrSelfPermission( 2553 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2554 } 2555 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2556 if (bp == null) { 2557 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2558 } 2559 2560 checkGrantRevokePermissions(pkg, bp); 2561 2562 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2563 if (ps == null) { 2564 return; 2565 } 2566 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2567 if (gp.grantedPermissions.remove(permissionName)) { 2568 gp.grantedPermissions.remove(permissionName); 2569 if (ps.haveGids) { 2570 gp.gids = removeInts(gp.gids, bp.gids); 2571 } 2572 mSettings.writeLPr(); 2573 changedAppId = ps.appId; 2574 } 2575 } 2576 2577 if (changedAppId >= 0) { 2578 // We changed the perm on someone, kill its processes. 2579 IActivityManager am = ActivityManagerNative.getDefault(); 2580 if (am != null) { 2581 final int callingUserId = UserHandle.getCallingUserId(); 2582 final long ident = Binder.clearCallingIdentity(); 2583 try { 2584 //XXX we should only revoke for the calling user's app permissions, 2585 // but for now we impact all users. 2586 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2587 // "revoke " + permissionName); 2588 int[] users = sUserManager.getUserIds(); 2589 for (int user : users) { 2590 am.killUid(UserHandle.getUid(user, changedAppId), 2591 "revoke " + permissionName); 2592 } 2593 } catch (RemoteException e) { 2594 } finally { 2595 Binder.restoreCallingIdentity(ident); 2596 } 2597 } 2598 } 2599 } 2600 2601 public boolean isProtectedBroadcast(String actionName) { 2602 synchronized (mPackages) { 2603 return mProtectedBroadcasts.contains(actionName); 2604 } 2605 } 2606 2607 public int checkSignatures(String pkg1, String pkg2) { 2608 synchronized (mPackages) { 2609 final PackageParser.Package p1 = mPackages.get(pkg1); 2610 final PackageParser.Package p2 = mPackages.get(pkg2); 2611 if (p1 == null || p1.mExtras == null 2612 || p2 == null || p2.mExtras == null) { 2613 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2614 } 2615 return compareSignatures(p1.mSignatures, p2.mSignatures); 2616 } 2617 } 2618 2619 public int checkUidSignatures(int uid1, int uid2) { 2620 // Map to base uids. 2621 uid1 = UserHandle.getAppId(uid1); 2622 uid2 = UserHandle.getAppId(uid2); 2623 // reader 2624 synchronized (mPackages) { 2625 Signature[] s1; 2626 Signature[] s2; 2627 Object obj = mSettings.getUserIdLPr(uid1); 2628 if (obj != null) { 2629 if (obj instanceof SharedUserSetting) { 2630 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2631 } else if (obj instanceof PackageSetting) { 2632 s1 = ((PackageSetting)obj).signatures.mSignatures; 2633 } else { 2634 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2635 } 2636 } else { 2637 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2638 } 2639 obj = mSettings.getUserIdLPr(uid2); 2640 if (obj != null) { 2641 if (obj instanceof SharedUserSetting) { 2642 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2643 } else if (obj instanceof PackageSetting) { 2644 s2 = ((PackageSetting)obj).signatures.mSignatures; 2645 } else { 2646 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2647 } 2648 } else { 2649 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2650 } 2651 return compareSignatures(s1, s2); 2652 } 2653 } 2654 2655 /** 2656 * Compares two sets of signatures. Returns: 2657 * <br /> 2658 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2659 * <br /> 2660 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2661 * <br /> 2662 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2663 * <br /> 2664 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2665 * <br /> 2666 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2667 */ 2668 static int compareSignatures(Signature[] s1, Signature[] s2) { 2669 if (s1 == null) { 2670 return s2 == null 2671 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2672 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2673 } 2674 2675 if (s2 == null) { 2676 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2677 } 2678 2679 if (s1.length != s2.length) { 2680 return PackageManager.SIGNATURE_NO_MATCH; 2681 } 2682 2683 // Since both signature sets are of size 1, we can compare without HashSets. 2684 if (s1.length == 1) { 2685 return s1[0].equals(s2[0]) ? 2686 PackageManager.SIGNATURE_MATCH : 2687 PackageManager.SIGNATURE_NO_MATCH; 2688 } 2689 2690 HashSet<Signature> set1 = new HashSet<Signature>(); 2691 for (Signature sig : s1) { 2692 set1.add(sig); 2693 } 2694 HashSet<Signature> set2 = new HashSet<Signature>(); 2695 for (Signature sig : s2) { 2696 set2.add(sig); 2697 } 2698 // Make sure s2 contains all signatures in s1. 2699 if (set1.equals(set2)) { 2700 return PackageManager.SIGNATURE_MATCH; 2701 } 2702 return PackageManager.SIGNATURE_NO_MATCH; 2703 } 2704 2705 public String[] getPackagesForUid(int uid) { 2706 uid = UserHandle.getAppId(uid); 2707 // reader 2708 synchronized (mPackages) { 2709 Object obj = mSettings.getUserIdLPr(uid); 2710 if (obj instanceof SharedUserSetting) { 2711 final SharedUserSetting sus = (SharedUserSetting) obj; 2712 final int N = sus.packages.size(); 2713 final String[] res = new String[N]; 2714 final Iterator<PackageSetting> it = sus.packages.iterator(); 2715 int i = 0; 2716 while (it.hasNext()) { 2717 res[i++] = it.next().name; 2718 } 2719 return res; 2720 } else if (obj instanceof PackageSetting) { 2721 final PackageSetting ps = (PackageSetting) obj; 2722 return new String[] { ps.name }; 2723 } 2724 } 2725 return null; 2726 } 2727 2728 public String getNameForUid(int uid) { 2729 // reader 2730 synchronized (mPackages) { 2731 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2732 if (obj instanceof SharedUserSetting) { 2733 final SharedUserSetting sus = (SharedUserSetting) obj; 2734 return sus.name + ":" + sus.userId; 2735 } else if (obj instanceof PackageSetting) { 2736 final PackageSetting ps = (PackageSetting) obj; 2737 return ps.name; 2738 } 2739 } 2740 return null; 2741 } 2742 2743 public int getUidForSharedUser(String sharedUserName) { 2744 if(sharedUserName == null) { 2745 return -1; 2746 } 2747 // reader 2748 synchronized (mPackages) { 2749 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2750 if (suid == null) { 2751 return -1; 2752 } 2753 return suid.userId; 2754 } 2755 } 2756 2757 public int getFlagsForUid(int uid) { 2758 synchronized (mPackages) { 2759 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2760 if (obj instanceof SharedUserSetting) { 2761 final SharedUserSetting sus = (SharedUserSetting) obj; 2762 return sus.pkgFlags; 2763 } else if (obj instanceof PackageSetting) { 2764 final PackageSetting ps = (PackageSetting) obj; 2765 return ps.pkgFlags; 2766 } 2767 } 2768 return 0; 2769 } 2770 2771 @Override 2772 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2773 int flags, int userId) { 2774 if (!sUserManager.exists(userId)) return null; 2775 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2776 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2777 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2778 } 2779 2780 @Override 2781 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2782 IntentFilter filter, int match, ComponentName activity) { 2783 final int userId = UserHandle.getCallingUserId(); 2784 if (DEBUG_PREFERRED) { 2785 Log.v(TAG, "setLastChosenActivity intent=" + intent 2786 + " resolvedType=" + resolvedType 2787 + " flags=" + flags 2788 + " filter=" + filter 2789 + " match=" + match 2790 + " activity=" + activity); 2791 filter.dump(new PrintStreamPrinter(System.out), " "); 2792 } 2793 intent.setComponent(null); 2794 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2795 // Find any earlier preferred or last chosen entries and nuke them 2796 findPreferredActivity(intent, resolvedType, 2797 flags, query, 0, false, true, false, userId); 2798 // Add the new activity as the last chosen for this filter 2799 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2800 } 2801 2802 @Override 2803 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2804 final int userId = UserHandle.getCallingUserId(); 2805 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2806 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2807 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2808 false, false, false, userId); 2809 } 2810 2811 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2812 int flags, List<ResolveInfo> query, int userId) { 2813 if (query != null) { 2814 final int N = query.size(); 2815 if (N == 1) { 2816 return query.get(0); 2817 } else if (N > 1) { 2818 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2819 // If there is more than one activity with the same priority, 2820 // then let the user decide between them. 2821 ResolveInfo r0 = query.get(0); 2822 ResolveInfo r1 = query.get(1); 2823 if (DEBUG_INTENT_MATCHING || debug) { 2824 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2825 + r1.activityInfo.name + "=" + r1.priority); 2826 } 2827 // If the first activity has a higher priority, or a different 2828 // default, then it is always desireable to pick it. 2829 if (r0.priority != r1.priority 2830 || r0.preferredOrder != r1.preferredOrder 2831 || r0.isDefault != r1.isDefault) { 2832 return query.get(0); 2833 } 2834 // If we have saved a preference for a preferred activity for 2835 // this Intent, use that. 2836 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2837 flags, query, r0.priority, true, false, debug, userId); 2838 if (ri != null) { 2839 return ri; 2840 } 2841 if (userId != 0) { 2842 ri = new ResolveInfo(mResolveInfo); 2843 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2844 ri.activityInfo.applicationInfo = new ApplicationInfo( 2845 ri.activityInfo.applicationInfo); 2846 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2847 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2848 return ri; 2849 } 2850 return mResolveInfo; 2851 } 2852 } 2853 return null; 2854 } 2855 2856 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2857 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2858 final int N = query.size(); 2859 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2860 .get(userId); 2861 // Get the list of persistent preferred activities that handle the intent 2862 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2863 List<PersistentPreferredActivity> pprefs = ppir != null 2864 ? ppir.queryIntent(intent, resolvedType, 2865 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2866 : null; 2867 if (pprefs != null && pprefs.size() > 0) { 2868 final int M = pprefs.size(); 2869 for (int i=0; i<M; i++) { 2870 final PersistentPreferredActivity ppa = pprefs.get(i); 2871 if (DEBUG_PREFERRED || debug) { 2872 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2873 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2874 + "\n component=" + ppa.mComponent); 2875 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2876 } 2877 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2878 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2879 if (DEBUG_PREFERRED || debug) { 2880 Slog.v(TAG, "Found persistent preferred activity:"); 2881 if (ai != null) { 2882 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2883 } else { 2884 Slog.v(TAG, " null"); 2885 } 2886 } 2887 if (ai == null) { 2888 // This previously registered persistent preferred activity 2889 // component is no longer known. Ignore it and do NOT remove it. 2890 continue; 2891 } 2892 for (int j=0; j<N; j++) { 2893 final ResolveInfo ri = query.get(j); 2894 if (!ri.activityInfo.applicationInfo.packageName 2895 .equals(ai.applicationInfo.packageName)) { 2896 continue; 2897 } 2898 if (!ri.activityInfo.name.equals(ai.name)) { 2899 continue; 2900 } 2901 // Found a persistent preference that can handle the intent. 2902 if (DEBUG_PREFERRED || debug) { 2903 Slog.v(TAG, "Returning persistent preferred activity: " + 2904 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 2905 } 2906 return ri; 2907 } 2908 } 2909 } 2910 return null; 2911 } 2912 2913 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 2914 List<ResolveInfo> query, int priority, boolean always, 2915 boolean removeMatches, boolean debug, int userId) { 2916 if (!sUserManager.exists(userId)) return null; 2917 // writer 2918 synchronized (mPackages) { 2919 if (intent.getSelector() != null) { 2920 intent = intent.getSelector(); 2921 } 2922 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 2923 2924 // Try to find a matching persistent preferred activity. 2925 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 2926 debug, userId); 2927 2928 // If a persistent preferred activity matched, use it. 2929 if (pri != null) { 2930 return pri; 2931 } 2932 2933 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 2934 // Get the list of preferred activities that handle the intent 2935 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 2936 List<PreferredActivity> prefs = pir != null 2937 ? pir.queryIntent(intent, resolvedType, 2938 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2939 : null; 2940 if (prefs != null && prefs.size() > 0) { 2941 // First figure out how good the original match set is. 2942 // We will only allow preferred activities that came 2943 // from the same match quality. 2944 int match = 0; 2945 2946 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 2947 2948 final int N = query.size(); 2949 for (int j=0; j<N; j++) { 2950 final ResolveInfo ri = query.get(j); 2951 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 2952 + ": 0x" + Integer.toHexString(match)); 2953 if (ri.match > match) { 2954 match = ri.match; 2955 } 2956 } 2957 2958 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 2959 + Integer.toHexString(match)); 2960 2961 match &= IntentFilter.MATCH_CATEGORY_MASK; 2962 final int M = prefs.size(); 2963 for (int i=0; i<M; i++) { 2964 final PreferredActivity pa = prefs.get(i); 2965 if (DEBUG_PREFERRED || debug) { 2966 Slog.v(TAG, "Checking PreferredActivity ds=" 2967 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 2968 + "\n component=" + pa.mPref.mComponent); 2969 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2970 } 2971 if (pa.mPref.mMatch != match) { 2972 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 2973 + Integer.toHexString(pa.mPref.mMatch)); 2974 continue; 2975 } 2976 // If it's not an "always" type preferred activity and that's what we're 2977 // looking for, skip it. 2978 if (always && !pa.mPref.mAlways) { 2979 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 2980 continue; 2981 } 2982 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 2983 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2984 if (DEBUG_PREFERRED || debug) { 2985 Slog.v(TAG, "Found preferred activity:"); 2986 if (ai != null) { 2987 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2988 } else { 2989 Slog.v(TAG, " null"); 2990 } 2991 } 2992 if (ai == null) { 2993 // This previously registered preferred activity 2994 // component is no longer known. Most likely an update 2995 // to the app was installed and in the new version this 2996 // component no longer exists. Clean it up by removing 2997 // it from the preferred activities list, and skip it. 2998 Slog.w(TAG, "Removing dangling preferred activity: " 2999 + pa.mPref.mComponent); 3000 pir.removeFilter(pa); 3001 continue; 3002 } 3003 for (int j=0; j<N; j++) { 3004 final ResolveInfo ri = query.get(j); 3005 if (!ri.activityInfo.applicationInfo.packageName 3006 .equals(ai.applicationInfo.packageName)) { 3007 continue; 3008 } 3009 if (!ri.activityInfo.name.equals(ai.name)) { 3010 continue; 3011 } 3012 3013 if (removeMatches) { 3014 pir.removeFilter(pa); 3015 if (DEBUG_PREFERRED) { 3016 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3017 } 3018 break; 3019 } 3020 3021 // Okay we found a previously set preferred or last chosen app. 3022 // If the result set is different from when this 3023 // was created, we need to clear it and re-ask the 3024 // user their preference, if we're looking for an "always" type entry. 3025 if (always && !pa.mPref.sameSet(query, priority)) { 3026 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3027 + intent + " type " + resolvedType); 3028 if (DEBUG_PREFERRED) { 3029 Slog.v(TAG, "Removing preferred activity since set changed " 3030 + pa.mPref.mComponent); 3031 } 3032 pir.removeFilter(pa); 3033 // Re-add the filter as a "last chosen" entry (!always) 3034 PreferredActivity lastChosen = new PreferredActivity( 3035 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3036 pir.addFilter(lastChosen); 3037 mSettings.writePackageRestrictionsLPr(userId); 3038 return null; 3039 } 3040 3041 // Yay! Either the set matched or we're looking for the last chosen 3042 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3043 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3044 mSettings.writePackageRestrictionsLPr(userId); 3045 return ri; 3046 } 3047 } 3048 } 3049 mSettings.writePackageRestrictionsLPr(userId); 3050 } 3051 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3052 return null; 3053 } 3054 3055 @Override 3056 public List<ResolveInfo> queryIntentActivities(Intent intent, 3057 String resolvedType, int flags, int userId) { 3058 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3059 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3060 ComponentName comp = intent.getComponent(); 3061 if (comp == null) { 3062 if (intent.getSelector() != null) { 3063 intent = intent.getSelector(); 3064 comp = intent.getComponent(); 3065 } 3066 } 3067 3068 if (comp != null) { 3069 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3070 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3071 if (ai != null) { 3072 final ResolveInfo ri = new ResolveInfo(); 3073 ri.activityInfo = ai; 3074 list.add(ri); 3075 } 3076 return list; 3077 } 3078 3079 // reader 3080 synchronized (mPackages) { 3081 final String pkgName = intent.getPackage(); 3082 if (pkgName == null) { 3083 return mActivities.queryIntent(intent, resolvedType, flags, userId); 3084 } 3085 final PackageParser.Package pkg = mPackages.get(pkgName); 3086 if (pkg != null) { 3087 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3088 pkg.activities, userId); 3089 } 3090 return new ArrayList<ResolveInfo>(); 3091 } 3092 } 3093 3094 @Override 3095 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3096 Intent[] specifics, String[] specificTypes, Intent intent, 3097 String resolvedType, int flags, int userId) { 3098 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3099 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3100 "query intent activity options"); 3101 final String resultsAction = intent.getAction(); 3102 3103 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3104 | PackageManager.GET_RESOLVED_FILTER, userId); 3105 3106 if (DEBUG_INTENT_MATCHING) { 3107 Log.v(TAG, "Query " + intent + ": " + results); 3108 } 3109 3110 int specificsPos = 0; 3111 int N; 3112 3113 // todo: note that the algorithm used here is O(N^2). This 3114 // isn't a problem in our current environment, but if we start running 3115 // into situations where we have more than 5 or 10 matches then this 3116 // should probably be changed to something smarter... 3117 3118 // First we go through and resolve each of the specific items 3119 // that were supplied, taking care of removing any corresponding 3120 // duplicate items in the generic resolve list. 3121 if (specifics != null) { 3122 for (int i=0; i<specifics.length; i++) { 3123 final Intent sintent = specifics[i]; 3124 if (sintent == null) { 3125 continue; 3126 } 3127 3128 if (DEBUG_INTENT_MATCHING) { 3129 Log.v(TAG, "Specific #" + i + ": " + sintent); 3130 } 3131 3132 String action = sintent.getAction(); 3133 if (resultsAction != null && resultsAction.equals(action)) { 3134 // If this action was explicitly requested, then don't 3135 // remove things that have it. 3136 action = null; 3137 } 3138 3139 ResolveInfo ri = null; 3140 ActivityInfo ai = null; 3141 3142 ComponentName comp = sintent.getComponent(); 3143 if (comp == null) { 3144 ri = resolveIntent( 3145 sintent, 3146 specificTypes != null ? specificTypes[i] : null, 3147 flags, userId); 3148 if (ri == null) { 3149 continue; 3150 } 3151 if (ri == mResolveInfo) { 3152 // ACK! Must do something better with this. 3153 } 3154 ai = ri.activityInfo; 3155 comp = new ComponentName(ai.applicationInfo.packageName, 3156 ai.name); 3157 } else { 3158 ai = getActivityInfo(comp, flags, userId); 3159 if (ai == null) { 3160 continue; 3161 } 3162 } 3163 3164 // Look for any generic query activities that are duplicates 3165 // of this specific one, and remove them from the results. 3166 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3167 N = results.size(); 3168 int j; 3169 for (j=specificsPos; j<N; j++) { 3170 ResolveInfo sri = results.get(j); 3171 if ((sri.activityInfo.name.equals(comp.getClassName()) 3172 && sri.activityInfo.applicationInfo.packageName.equals( 3173 comp.getPackageName())) 3174 || (action != null && sri.filter.matchAction(action))) { 3175 results.remove(j); 3176 if (DEBUG_INTENT_MATCHING) Log.v( 3177 TAG, "Removing duplicate item from " + j 3178 + " due to specific " + specificsPos); 3179 if (ri == null) { 3180 ri = sri; 3181 } 3182 j--; 3183 N--; 3184 } 3185 } 3186 3187 // Add this specific item to its proper place. 3188 if (ri == null) { 3189 ri = new ResolveInfo(); 3190 ri.activityInfo = ai; 3191 } 3192 results.add(specificsPos, ri); 3193 ri.specificIndex = i; 3194 specificsPos++; 3195 } 3196 } 3197 3198 // Now we go through the remaining generic results and remove any 3199 // duplicate actions that are found here. 3200 N = results.size(); 3201 for (int i=specificsPos; i<N-1; i++) { 3202 final ResolveInfo rii = results.get(i); 3203 if (rii.filter == null) { 3204 continue; 3205 } 3206 3207 // Iterate over all of the actions of this result's intent 3208 // filter... typically this should be just one. 3209 final Iterator<String> it = rii.filter.actionsIterator(); 3210 if (it == null) { 3211 continue; 3212 } 3213 while (it.hasNext()) { 3214 final String action = it.next(); 3215 if (resultsAction != null && resultsAction.equals(action)) { 3216 // If this action was explicitly requested, then don't 3217 // remove things that have it. 3218 continue; 3219 } 3220 for (int j=i+1; j<N; j++) { 3221 final ResolveInfo rij = results.get(j); 3222 if (rij.filter != null && rij.filter.hasAction(action)) { 3223 results.remove(j); 3224 if (DEBUG_INTENT_MATCHING) Log.v( 3225 TAG, "Removing duplicate item from " + j 3226 + " due to action " + action + " at " + i); 3227 j--; 3228 N--; 3229 } 3230 } 3231 } 3232 3233 // If the caller didn't request filter information, drop it now 3234 // so we don't have to marshall/unmarshall it. 3235 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3236 rii.filter = null; 3237 } 3238 } 3239 3240 // Filter out the caller activity if so requested. 3241 if (caller != null) { 3242 N = results.size(); 3243 for (int i=0; i<N; i++) { 3244 ActivityInfo ainfo = results.get(i).activityInfo; 3245 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3246 && caller.getClassName().equals(ainfo.name)) { 3247 results.remove(i); 3248 break; 3249 } 3250 } 3251 } 3252 3253 // If the caller didn't request filter information, 3254 // drop them now so we don't have to 3255 // marshall/unmarshall it. 3256 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3257 N = results.size(); 3258 for (int i=0; i<N; i++) { 3259 results.get(i).filter = null; 3260 } 3261 } 3262 3263 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3264 return results; 3265 } 3266 3267 @Override 3268 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3269 int userId) { 3270 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3271 ComponentName comp = intent.getComponent(); 3272 if (comp == null) { 3273 if (intent.getSelector() != null) { 3274 intent = intent.getSelector(); 3275 comp = intent.getComponent(); 3276 } 3277 } 3278 if (comp != null) { 3279 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3280 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3281 if (ai != null) { 3282 ResolveInfo ri = new ResolveInfo(); 3283 ri.activityInfo = ai; 3284 list.add(ri); 3285 } 3286 return list; 3287 } 3288 3289 // reader 3290 synchronized (mPackages) { 3291 String pkgName = intent.getPackage(); 3292 if (pkgName == null) { 3293 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3294 } 3295 final PackageParser.Package pkg = mPackages.get(pkgName); 3296 if (pkg != null) { 3297 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3298 userId); 3299 } 3300 return null; 3301 } 3302 } 3303 3304 @Override 3305 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3306 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3307 if (!sUserManager.exists(userId)) return null; 3308 if (query != null) { 3309 if (query.size() >= 1) { 3310 // If there is more than one service with the same priority, 3311 // just arbitrarily pick the first one. 3312 return query.get(0); 3313 } 3314 } 3315 return null; 3316 } 3317 3318 @Override 3319 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3320 int userId) { 3321 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3322 ComponentName comp = intent.getComponent(); 3323 if (comp == null) { 3324 if (intent.getSelector() != null) { 3325 intent = intent.getSelector(); 3326 comp = intent.getComponent(); 3327 } 3328 } 3329 if (comp != null) { 3330 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3331 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3332 if (si != null) { 3333 final ResolveInfo ri = new ResolveInfo(); 3334 ri.serviceInfo = si; 3335 list.add(ri); 3336 } 3337 return list; 3338 } 3339 3340 // reader 3341 synchronized (mPackages) { 3342 String pkgName = intent.getPackage(); 3343 if (pkgName == null) { 3344 return mServices.queryIntent(intent, resolvedType, flags, userId); 3345 } 3346 final PackageParser.Package pkg = mPackages.get(pkgName); 3347 if (pkg != null) { 3348 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3349 userId); 3350 } 3351 return null; 3352 } 3353 } 3354 3355 @Override 3356 public List<ResolveInfo> queryIntentContentProviders( 3357 Intent intent, String resolvedType, int flags, int userId) { 3358 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3359 ComponentName comp = intent.getComponent(); 3360 if (comp == null) { 3361 if (intent.getSelector() != null) { 3362 intent = intent.getSelector(); 3363 comp = intent.getComponent(); 3364 } 3365 } 3366 if (comp != null) { 3367 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3368 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3369 if (pi != null) { 3370 final ResolveInfo ri = new ResolveInfo(); 3371 ri.providerInfo = pi; 3372 list.add(ri); 3373 } 3374 return list; 3375 } 3376 3377 // reader 3378 synchronized (mPackages) { 3379 String pkgName = intent.getPackage(); 3380 if (pkgName == null) { 3381 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3382 } 3383 final PackageParser.Package pkg = mPackages.get(pkgName); 3384 if (pkg != null) { 3385 return mProviders.queryIntentForPackage( 3386 intent, resolvedType, flags, pkg.providers, userId); 3387 } 3388 return null; 3389 } 3390 } 3391 3392 @Override 3393 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3394 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3395 3396 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3397 3398 // writer 3399 synchronized (mPackages) { 3400 ArrayList<PackageInfo> list; 3401 if (listUninstalled) { 3402 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3403 for (PackageSetting ps : mSettings.mPackages.values()) { 3404 PackageInfo pi; 3405 if (ps.pkg != null) { 3406 pi = generatePackageInfo(ps.pkg, flags, userId); 3407 } else { 3408 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3409 } 3410 if (pi != null) { 3411 list.add(pi); 3412 } 3413 } 3414 } else { 3415 list = new ArrayList<PackageInfo>(mPackages.size()); 3416 for (PackageParser.Package p : mPackages.values()) { 3417 PackageInfo pi = generatePackageInfo(p, flags, userId); 3418 if (pi != null) { 3419 list.add(pi); 3420 } 3421 } 3422 } 3423 3424 return new ParceledListSlice<PackageInfo>(list); 3425 } 3426 } 3427 3428 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3429 String[] permissions, boolean[] tmp, int flags, int userId) { 3430 int numMatch = 0; 3431 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3432 for (int i=0; i<permissions.length; i++) { 3433 if (gp.grantedPermissions.contains(permissions[i])) { 3434 tmp[i] = true; 3435 numMatch++; 3436 } else { 3437 tmp[i] = false; 3438 } 3439 } 3440 if (numMatch == 0) { 3441 return; 3442 } 3443 PackageInfo pi; 3444 if (ps.pkg != null) { 3445 pi = generatePackageInfo(ps.pkg, flags, userId); 3446 } else { 3447 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3448 } 3449 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3450 if (numMatch == permissions.length) { 3451 pi.requestedPermissions = permissions; 3452 } else { 3453 pi.requestedPermissions = new String[numMatch]; 3454 numMatch = 0; 3455 for (int i=0; i<permissions.length; i++) { 3456 if (tmp[i]) { 3457 pi.requestedPermissions[numMatch] = permissions[i]; 3458 numMatch++; 3459 } 3460 } 3461 } 3462 } 3463 list.add(pi); 3464 } 3465 3466 @Override 3467 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3468 String[] permissions, int flags, int userId) { 3469 if (!sUserManager.exists(userId)) return null; 3470 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3471 3472 // writer 3473 synchronized (mPackages) { 3474 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3475 boolean[] tmpBools = new boolean[permissions.length]; 3476 if (listUninstalled) { 3477 for (PackageSetting ps : mSettings.mPackages.values()) { 3478 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3479 } 3480 } else { 3481 for (PackageParser.Package pkg : mPackages.values()) { 3482 PackageSetting ps = (PackageSetting)pkg.mExtras; 3483 if (ps != null) { 3484 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3485 userId); 3486 } 3487 } 3488 } 3489 3490 return new ParceledListSlice<PackageInfo>(list); 3491 } 3492 } 3493 3494 @Override 3495 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3496 if (!sUserManager.exists(userId)) return null; 3497 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3498 3499 // writer 3500 synchronized (mPackages) { 3501 ArrayList<ApplicationInfo> list; 3502 if (listUninstalled) { 3503 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3504 for (PackageSetting ps : mSettings.mPackages.values()) { 3505 ApplicationInfo ai; 3506 if (ps.pkg != null) { 3507 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3508 ps.readUserState(userId), userId); 3509 } else { 3510 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3511 } 3512 if (ai != null) { 3513 list.add(ai); 3514 } 3515 } 3516 } else { 3517 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3518 for (PackageParser.Package p : mPackages.values()) { 3519 if (p.mExtras != null) { 3520 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3521 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3522 if (ai != null) { 3523 list.add(ai); 3524 } 3525 } 3526 } 3527 } 3528 3529 return new ParceledListSlice<ApplicationInfo>(list); 3530 } 3531 } 3532 3533 public List<ApplicationInfo> getPersistentApplications(int flags) { 3534 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3535 3536 // reader 3537 synchronized (mPackages) { 3538 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3539 final int userId = UserHandle.getCallingUserId(); 3540 while (i.hasNext()) { 3541 final PackageParser.Package p = i.next(); 3542 if (p.applicationInfo != null 3543 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3544 && (!mSafeMode || isSystemApp(p))) { 3545 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3546 if (ps != null) { 3547 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3548 ps.readUserState(userId), userId); 3549 if (ai != null) { 3550 finalList.add(ai); 3551 } 3552 } 3553 } 3554 } 3555 } 3556 3557 return finalList; 3558 } 3559 3560 @Override 3561 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3562 if (!sUserManager.exists(userId)) return null; 3563 // reader 3564 synchronized (mPackages) { 3565 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3566 PackageSetting ps = provider != null 3567 ? mSettings.mPackages.get(provider.owner.packageName) 3568 : null; 3569 return ps != null 3570 && mSettings.isEnabledLPr(provider.info, flags, userId) 3571 && (!mSafeMode || (provider.info.applicationInfo.flags 3572 &ApplicationInfo.FLAG_SYSTEM) != 0) 3573 ? PackageParser.generateProviderInfo(provider, flags, 3574 ps.readUserState(userId), userId) 3575 : null; 3576 } 3577 } 3578 3579 /** 3580 * @deprecated 3581 */ 3582 @Deprecated 3583 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3584 // reader 3585 synchronized (mPackages) { 3586 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3587 .entrySet().iterator(); 3588 final int userId = UserHandle.getCallingUserId(); 3589 while (i.hasNext()) { 3590 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3591 PackageParser.Provider p = entry.getValue(); 3592 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3593 3594 if (ps != null && p.syncable 3595 && (!mSafeMode || (p.info.applicationInfo.flags 3596 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3597 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3598 ps.readUserState(userId), userId); 3599 if (info != null) { 3600 outNames.add(entry.getKey()); 3601 outInfo.add(info); 3602 } 3603 } 3604 } 3605 } 3606 } 3607 3608 public List<ProviderInfo> queryContentProviders(String processName, 3609 int uid, int flags) { 3610 ArrayList<ProviderInfo> finalList = null; 3611 // reader 3612 synchronized (mPackages) { 3613 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3614 final int userId = processName != null ? 3615 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3616 while (i.hasNext()) { 3617 final PackageParser.Provider p = i.next(); 3618 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3619 if (ps != null && p.info.authority != null 3620 && (processName == null 3621 || (p.info.processName.equals(processName) 3622 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3623 && mSettings.isEnabledLPr(p.info, flags, userId) 3624 && (!mSafeMode 3625 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3626 if (finalList == null) { 3627 finalList = new ArrayList<ProviderInfo>(3); 3628 } 3629 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3630 ps.readUserState(userId), userId); 3631 if (info != null) { 3632 finalList.add(info); 3633 } 3634 } 3635 } 3636 } 3637 3638 if (finalList != null) { 3639 Collections.sort(finalList, mProviderInitOrderSorter); 3640 } 3641 3642 return finalList; 3643 } 3644 3645 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3646 int flags) { 3647 // reader 3648 synchronized (mPackages) { 3649 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3650 return PackageParser.generateInstrumentationInfo(i, flags); 3651 } 3652 } 3653 3654 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3655 int flags) { 3656 ArrayList<InstrumentationInfo> finalList = 3657 new ArrayList<InstrumentationInfo>(); 3658 3659 // reader 3660 synchronized (mPackages) { 3661 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3662 while (i.hasNext()) { 3663 final PackageParser.Instrumentation p = i.next(); 3664 if (targetPackage == null 3665 || targetPackage.equals(p.info.targetPackage)) { 3666 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3667 flags); 3668 if (ii != null) { 3669 finalList.add(ii); 3670 } 3671 } 3672 } 3673 } 3674 3675 return finalList; 3676 } 3677 3678 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 3679 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 3680 if (overlays == null) { 3681 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 3682 return; 3683 } 3684 for (PackageParser.Package opkg : overlays.values()) { 3685 // Not much to do if idmap fails: we already logged the error 3686 // and we certainly don't want to abort installation of pkg simply 3687 // because an overlay didn't fit properly. For these reasons, 3688 // ignore the return value of createIdmapForPackagePairLI. 3689 createIdmapForPackagePairLI(pkg, opkg); 3690 } 3691 } 3692 3693 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 3694 PackageParser.Package opkg) { 3695 if (!opkg.mTrustedOverlay) { 3696 Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " + 3697 opkg.mScanPath + ": overlay not trusted"); 3698 return false; 3699 } 3700 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 3701 if (overlaySet == null) { 3702 Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " + 3703 opkg.mScanPath + " but target package has no known overlays"); 3704 return false; 3705 } 3706 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 3707 if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) { 3708 Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath); 3709 return false; 3710 } 3711 PackageParser.Package[] overlayArray = 3712 overlaySet.values().toArray(new PackageParser.Package[0]); 3713 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 3714 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 3715 return p1.mOverlayPriority - p2.mOverlayPriority; 3716 } 3717 }; 3718 Arrays.sort(overlayArray, cmp); 3719 3720 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 3721 int i = 0; 3722 for (PackageParser.Package p : overlayArray) { 3723 pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir; 3724 } 3725 return true; 3726 } 3727 3728 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 3729 String[] files = dir.list(); 3730 if (files == null) { 3731 Log.d(TAG, "No files in app dir " + dir); 3732 return; 3733 } 3734 3735 if (DEBUG_PACKAGE_SCANNING) { 3736 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 3737 + " flags=0x" + Integer.toHexString(flags)); 3738 } 3739 3740 int i; 3741 for (i=0; i<files.length; i++) { 3742 File file = new File(dir, files[i]); 3743 if (!isPackageFilename(files[i])) { 3744 // Ignore entries which are not apk's 3745 continue; 3746 } 3747 PackageParser.Package pkg = scanPackageLI(file, 3748 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null); 3749 // Don't mess around with apps in system partition. 3750 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 3751 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 3752 // Delete the apk 3753 Slog.w(TAG, "Cleaning up failed install of " + file); 3754 file.delete(); 3755 } 3756 } 3757 } 3758 3759 private static File getSettingsProblemFile() { 3760 File dataDir = Environment.getDataDirectory(); 3761 File systemDir = new File(dataDir, "system"); 3762 File fname = new File(systemDir, "uiderrors.txt"); 3763 return fname; 3764 } 3765 3766 static void reportSettingsProblem(int priority, String msg) { 3767 try { 3768 File fname = getSettingsProblemFile(); 3769 FileOutputStream out = new FileOutputStream(fname, true); 3770 PrintWriter pw = new FastPrintWriter(out); 3771 SimpleDateFormat formatter = new SimpleDateFormat(); 3772 String dateString = formatter.format(new Date(System.currentTimeMillis())); 3773 pw.println(dateString + ": " + msg); 3774 pw.close(); 3775 FileUtils.setPermissions( 3776 fname.toString(), 3777 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 3778 -1, -1); 3779 } catch (java.io.IOException e) { 3780 } 3781 Slog.println(priority, TAG, msg); 3782 } 3783 3784 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 3785 PackageParser.Package pkg, File srcFile, int parseFlags) { 3786 if (GET_CERTIFICATES) { 3787 if (ps != null 3788 && ps.codePath.equals(srcFile) 3789 && ps.timeStamp == srcFile.lastModified()) { 3790 if (ps.signatures.mSignatures != null 3791 && ps.signatures.mSignatures.length != 0) { 3792 // Optimization: reuse the existing cached certificates 3793 // if the package appears to be unchanged. 3794 pkg.mSignatures = ps.signatures.mSignatures; 3795 return true; 3796 } 3797 3798 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 3799 } else { 3800 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 3801 } 3802 3803 if (!pp.collectCertificates(pkg, parseFlags)) { 3804 mLastScanError = pp.getParseError(); 3805 return false; 3806 } 3807 } 3808 return true; 3809 } 3810 3811 /* 3812 * Scan a package and return the newly parsed package. 3813 * Returns null in case of errors and the error code is stored in mLastScanError 3814 */ 3815 private PackageParser.Package scanPackageLI(File scanFile, 3816 int parseFlags, int scanMode, long currentTime, UserHandle user) { 3817 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 3818 String scanPath = scanFile.getPath(); 3819 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath); 3820 parseFlags |= mDefParseFlags; 3821 PackageParser pp = new PackageParser(scanPath); 3822 pp.setSeparateProcesses(mSeparateProcesses); 3823 pp.setOnlyCoreApps(mOnlyCore); 3824 final PackageParser.Package pkg = pp.parsePackage(scanFile, 3825 scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0); 3826 3827 if (pkg == null) { 3828 mLastScanError = pp.getParseError(); 3829 return null; 3830 } 3831 3832 PackageSetting ps = null; 3833 PackageSetting updatedPkg; 3834 // reader 3835 synchronized (mPackages) { 3836 // Look to see if we already know about this package. 3837 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 3838 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 3839 // This package has been renamed to its original name. Let's 3840 // use that. 3841 ps = mSettings.peekPackageLPr(oldName); 3842 } 3843 // If there was no original package, see one for the real package name. 3844 if (ps == null) { 3845 ps = mSettings.peekPackageLPr(pkg.packageName); 3846 } 3847 // Check to see if this package could be hiding/updating a system 3848 // package. Must look for it either under the original or real 3849 // package name depending on our state. 3850 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 3851 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 3852 } 3853 boolean updatedPkgBetter = false; 3854 // First check if this is a system package that may involve an update 3855 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 3856 if (ps != null && !ps.codePath.equals(scanFile)) { 3857 // The path has changed from what was last scanned... check the 3858 // version of the new path against what we have stored to determine 3859 // what to do. 3860 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 3861 if (pkg.mVersionCode < ps.versionCode) { 3862 // The system package has been updated and the code path does not match 3863 // Ignore entry. Skip it. 3864 Log.i(TAG, "Package " + ps.name + " at " + scanFile 3865 + " ignored: updated version " + ps.versionCode 3866 + " better than this " + pkg.mVersionCode); 3867 if (!updatedPkg.codePath.equals(scanFile)) { 3868 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 3869 + ps.name + " changing from " + updatedPkg.codePathString 3870 + " to " + scanFile); 3871 updatedPkg.codePath = scanFile; 3872 updatedPkg.codePathString = scanFile.toString(); 3873 // This is the point at which we know that the system-disk APK 3874 // for this package has moved during a reboot (e.g. due to an OTA), 3875 // so we need to reevaluate it for privilege policy. 3876 if (locationIsPrivileged(scanFile)) { 3877 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 3878 } 3879 } 3880 updatedPkg.pkg = pkg; 3881 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 3882 return null; 3883 } else { 3884 // The current app on the system partion is better than 3885 // what we have updated to on the data partition; switch 3886 // back to the system partition version. 3887 // At this point, its safely assumed that package installation for 3888 // apps in system partition will go through. If not there won't be a working 3889 // version of the app 3890 // writer 3891 synchronized (mPackages) { 3892 // Just remove the loaded entries from package lists. 3893 mPackages.remove(ps.name); 3894 } 3895 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 3896 + "reverting from " + ps.codePathString 3897 + ": new version " + pkg.mVersionCode 3898 + " better than installed " + ps.versionCode); 3899 3900 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 3901 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString); 3902 synchronized (mInstallLock) { 3903 args.cleanUpResourcesLI(); 3904 } 3905 synchronized (mPackages) { 3906 mSettings.enableSystemPackageLPw(ps.name); 3907 } 3908 updatedPkgBetter = true; 3909 } 3910 } 3911 } 3912 3913 if (updatedPkg != null) { 3914 // An updated system app will not have the PARSE_IS_SYSTEM flag set 3915 // initially 3916 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 3917 3918 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 3919 // flag set initially 3920 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 3921 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 3922 } 3923 } 3924 // Verify certificates against what was last scanned 3925 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 3926 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 3927 return null; 3928 } 3929 3930 /* 3931 * A new system app appeared, but we already had a non-system one of the 3932 * same name installed earlier. 3933 */ 3934 boolean shouldHideSystemApp = false; 3935 if (updatedPkg == null && ps != null 3936 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 3937 /* 3938 * Check to make sure the signatures match first. If they don't, 3939 * wipe the installed application and its data. 3940 */ 3941 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 3942 != PackageManager.SIGNATURE_MATCH) { 3943 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 3944 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 3945 ps = null; 3946 } else { 3947 /* 3948 * If the newly-added system app is an older version than the 3949 * already installed version, hide it. It will be scanned later 3950 * and re-added like an update. 3951 */ 3952 if (pkg.mVersionCode < ps.versionCode) { 3953 shouldHideSystemApp = true; 3954 } else { 3955 /* 3956 * The newly found system app is a newer version that the 3957 * one previously installed. Simply remove the 3958 * already-installed application and replace it with our own 3959 * while keeping the application data. 3960 */ 3961 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 3962 + ps.codePathString + ": new version " + pkg.mVersionCode 3963 + " better than installed " + ps.versionCode); 3964 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 3965 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString); 3966 synchronized (mInstallLock) { 3967 args.cleanUpResourcesLI(); 3968 } 3969 } 3970 } 3971 } 3972 3973 // The apk is forward locked (not public) if its code and resources 3974 // are kept in different files. (except for app in either system or 3975 // vendor path). 3976 // TODO grab this value from PackageSettings 3977 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 3978 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 3979 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 3980 } 3981 } 3982 3983 String codePath = null; 3984 String resPath = null; 3985 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 3986 if (ps != null && ps.resourcePathString != null) { 3987 resPath = ps.resourcePathString; 3988 } else { 3989 // Should not happen at all. Just log an error. 3990 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 3991 } 3992 } else { 3993 resPath = pkg.mScanPath; 3994 } 3995 3996 codePath = pkg.mScanPath; 3997 // Set application objects path explicitly. 3998 setApplicationInfoPaths(pkg, codePath, resPath); 3999 // Applications can run with the primary Cpu Abi unless otherwise is specified 4000 pkg.applicationInfo.requiredCpuAbi = null; 4001 // Note that we invoke the following method only if we are about to unpack an application 4002 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4003 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4004 4005 /* 4006 * If the system app should be overridden by a previously installed 4007 * data, hide the system app now and let the /data/app scan pick it up 4008 * again. 4009 */ 4010 if (shouldHideSystemApp) { 4011 synchronized (mPackages) { 4012 /* 4013 * We have to grant systems permissions before we hide, because 4014 * grantPermissions will assume the package update is trying to 4015 * expand its permissions. 4016 */ 4017 grantPermissionsLPw(pkg, true); 4018 mSettings.disableSystemPackageLPw(pkg.packageName); 4019 } 4020 } 4021 4022 return scannedPkg; 4023 } 4024 4025 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath, 4026 String destResPath) { 4027 pkg.mPath = pkg.mScanPath = destCodePath; 4028 pkg.applicationInfo.sourceDir = destCodePath; 4029 pkg.applicationInfo.publicSourceDir = destResPath; 4030 } 4031 4032 private static String fixProcessName(String defProcessName, 4033 String processName, int uid) { 4034 if (processName == null) { 4035 return defProcessName; 4036 } 4037 return processName; 4038 } 4039 4040 private boolean verifySignaturesLP(PackageSetting pkgSetting, 4041 PackageParser.Package pkg) { 4042 if (pkgSetting.signatures.mSignatures != null) { 4043 // Already existing package. Make sure signatures match 4044 if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) != 4045 PackageManager.SIGNATURE_MATCH) { 4046 Slog.e(TAG, "Package " + pkg.packageName 4047 + " signatures do not match the previously installed version; ignoring!"); 4048 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4049 return false; 4050 } 4051 } 4052 // Check for shared user signatures 4053 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4054 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4055 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 4056 Slog.e(TAG, "Package " + pkg.packageName 4057 + " has no signatures that match those in shared user " 4058 + pkgSetting.sharedUser.name + "; ignoring!"); 4059 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4060 return false; 4061 } 4062 } 4063 return true; 4064 } 4065 4066 /** 4067 * Enforces that only the system UID or root's UID can call a method exposed 4068 * via Binder. 4069 * 4070 * @param message used as message if SecurityException is thrown 4071 * @throws SecurityException if the caller is not system or root 4072 */ 4073 private static final void enforceSystemOrRoot(String message) { 4074 final int uid = Binder.getCallingUid(); 4075 if (uid != Process.SYSTEM_UID && uid != 0) { 4076 throw new SecurityException(message); 4077 } 4078 } 4079 4080 public void performBootDexOpt() { 4081 HashSet<PackageParser.Package> pkgs = null; 4082 synchronized (mPackages) { 4083 pkgs = mDeferredDexOpt; 4084 mDeferredDexOpt = null; 4085 } 4086 if (pkgs != null) { 4087 int i = 0; 4088 for (PackageParser.Package pkg : pkgs) { 4089 if (!isFirstBoot()) { 4090 i++; 4091 try { 4092 ActivityManagerNative.getDefault().showBootMessage( 4093 mContext.getResources().getString( 4094 com.android.internal.R.string.android_upgrading_apk, 4095 i, pkgs.size()), true); 4096 } catch (RemoteException e) { 4097 } 4098 } 4099 PackageParser.Package p = pkg; 4100 synchronized (mInstallLock) { 4101 if (!p.mDidDexOpt) { 4102 performDexOptLI(p, false, false, true); 4103 } 4104 } 4105 } 4106 } 4107 } 4108 4109 public boolean performDexOpt(String packageName) { 4110 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4111 4112 if (!mNoDexOpt) { 4113 return false; 4114 } 4115 4116 PackageParser.Package p; 4117 synchronized (mPackages) { 4118 p = mPackages.get(packageName); 4119 if (p == null || p.mDidDexOpt) { 4120 return false; 4121 } 4122 } 4123 synchronized (mInstallLock) { 4124 return performDexOptLI(p, false, false, true) == DEX_OPT_PERFORMED; 4125 } 4126 } 4127 4128 private void performDexOptLibsLI(ArrayList<String> libs, boolean forceDex, boolean defer, 4129 HashSet<String> done) { 4130 for (int i=0; i<libs.size(); i++) { 4131 PackageParser.Package libPkg; 4132 String libName; 4133 synchronized (mPackages) { 4134 libName = libs.get(i); 4135 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4136 if (lib != null && lib.apk != null) { 4137 libPkg = mPackages.get(lib.apk); 4138 } else { 4139 libPkg = null; 4140 } 4141 } 4142 if (libPkg != null && !done.contains(libName)) { 4143 performDexOptLI(libPkg, forceDex, defer, done); 4144 } 4145 } 4146 } 4147 4148 static final int DEX_OPT_SKIPPED = 0; 4149 static final int DEX_OPT_PERFORMED = 1; 4150 static final int DEX_OPT_DEFERRED = 2; 4151 static final int DEX_OPT_FAILED = -1; 4152 4153 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4154 HashSet<String> done) { 4155 boolean performed = false; 4156 if (done != null) { 4157 done.add(pkg.packageName); 4158 if (pkg.usesLibraries != null) { 4159 performDexOptLibsLI(pkg.usesLibraries, forceDex, defer, done); 4160 } 4161 if (pkg.usesOptionalLibraries != null) { 4162 performDexOptLibsLI(pkg.usesOptionalLibraries, forceDex, defer, done); 4163 } 4164 } 4165 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 4166 String path = pkg.mScanPath; 4167 int ret = 0; 4168 try { 4169 if (forceDex || dalvik.system.DexFile.isDexOptNeededInternal(path, pkg.packageName, 4170 defer)) { 4171 if (!forceDex && defer) { 4172 if (mDeferredDexOpt == null) { 4173 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4174 } 4175 mDeferredDexOpt.add(pkg); 4176 return DEX_OPT_DEFERRED; 4177 } else { 4178 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName); 4179 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4180 ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4181 pkg.packageName); 4182 pkg.mDidDexOpt = true; 4183 performed = true; 4184 } 4185 } 4186 } catch (FileNotFoundException e) { 4187 Slog.w(TAG, "Apk not found for dexopt: " + path); 4188 ret = -1; 4189 } catch (IOException e) { 4190 Slog.w(TAG, "IOException reading apk: " + path, e); 4191 ret = -1; 4192 } catch (dalvik.system.StaleDexCacheError e) { 4193 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4194 ret = -1; 4195 } catch (Exception e) { 4196 Slog.w(TAG, "Exception when doing dexopt : ", e); 4197 ret = -1; 4198 } 4199 if (ret < 0) { 4200 //error from installer 4201 return DEX_OPT_FAILED; 4202 } 4203 } 4204 4205 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4206 } 4207 4208 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4209 boolean inclDependencies) { 4210 HashSet<String> done; 4211 boolean performed = false; 4212 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4213 done = new HashSet<String>(); 4214 done.add(pkg.packageName); 4215 } else { 4216 done = null; 4217 } 4218 return performDexOptLI(pkg, forceDex, defer, done); 4219 } 4220 4221 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4222 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4223 Slog.w(TAG, "Unable to update from " + oldPkg.name 4224 + " to " + newPkg.packageName 4225 + ": old package not in system partition"); 4226 return false; 4227 } else if (mPackages.get(oldPkg.name) != null) { 4228 Slog.w(TAG, "Unable to update from " + oldPkg.name 4229 + " to " + newPkg.packageName 4230 + ": old package still exists"); 4231 return false; 4232 } 4233 return true; 4234 } 4235 4236 File getDataPathForUser(int userId) { 4237 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4238 } 4239 4240 private File getDataPathForPackage(String packageName, int userId) { 4241 /* 4242 * Until we fully support multiple users, return the directory we 4243 * previously would have. The PackageManagerTests will need to be 4244 * revised when this is changed back.. 4245 */ 4246 if (userId == 0) { 4247 return new File(mAppDataDir, packageName); 4248 } else { 4249 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4250 + File.separator + packageName); 4251 } 4252 } 4253 4254 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4255 int[] users = sUserManager.getUserIds(); 4256 int res = mInstaller.install(packageName, uid, uid, seinfo); 4257 if (res < 0) { 4258 return res; 4259 } 4260 for (int user : users) { 4261 if (user != 0) { 4262 res = mInstaller.createUserData(packageName, 4263 UserHandle.getUid(user, uid), user, seinfo); 4264 if (res < 0) { 4265 return res; 4266 } 4267 } 4268 } 4269 return res; 4270 } 4271 4272 private int removeDataDirsLI(String packageName) { 4273 int[] users = sUserManager.getUserIds(); 4274 int res = 0; 4275 for (int user : users) { 4276 int resInner = mInstaller.remove(packageName, user); 4277 if (resInner < 0) { 4278 res = resInner; 4279 } 4280 } 4281 4282 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4283 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4284 if (!nativeLibraryFile.delete()) { 4285 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4286 } 4287 4288 return res; 4289 } 4290 4291 private int addSharedLibraryLPw(final SharedLibraryEntry file, int num, 4292 PackageParser.Package changingLib) { 4293 if (file.path != null) { 4294 mTmpSharedLibraries[num] = file.path; 4295 return num+1; 4296 } 4297 PackageParser.Package p = mPackages.get(file.apk); 4298 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4299 // If we are doing this while in the middle of updating a library apk, 4300 // then we need to make sure to use that new apk for determining the 4301 // dependencies here. (We haven't yet finished committing the new apk 4302 // to the package manager state.) 4303 if (p == null || p.packageName.equals(changingLib.packageName)) { 4304 p = changingLib; 4305 } 4306 } 4307 if (p != null) { 4308 String path = p.mPath; 4309 for (int i=0; i<num; i++) { 4310 if (mTmpSharedLibraries[i].equals(path)) { 4311 return num; 4312 } 4313 } 4314 mTmpSharedLibraries[num] = p.mPath; 4315 return num+1; 4316 } 4317 return num; 4318 } 4319 4320 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4321 PackageParser.Package changingLib) { 4322 // We might be upgrading from a version of the platform that did not 4323 // provide per-package native library directories for system apps. 4324 // Fix that up here. 4325 if (isSystemApp(pkg)) { 4326 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4327 setInternalAppNativeLibraryPath(pkg, ps); 4328 } 4329 4330 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4331 if (mTmpSharedLibraries == null || 4332 mTmpSharedLibraries.length < mSharedLibraries.size()) { 4333 mTmpSharedLibraries = new String[mSharedLibraries.size()]; 4334 } 4335 int num = 0; 4336 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4337 for (int i=0; i<N; i++) { 4338 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4339 if (file == null) { 4340 Slog.e(TAG, "Package " + pkg.packageName 4341 + " requires unavailable shared library " 4342 + pkg.usesLibraries.get(i) + "; failing!"); 4343 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4344 return false; 4345 } 4346 num = addSharedLibraryLPw(file, num, changingLib); 4347 } 4348 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4349 for (int i=0; i<N; i++) { 4350 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4351 if (file == null) { 4352 Slog.w(TAG, "Package " + pkg.packageName 4353 + " desires unavailable shared library " 4354 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4355 } else { 4356 num = addSharedLibraryLPw(file, num, changingLib); 4357 } 4358 } 4359 if (num > 0) { 4360 pkg.usesLibraryFiles = new String[num]; 4361 System.arraycopy(mTmpSharedLibraries, 0, 4362 pkg.usesLibraryFiles, 0, num); 4363 } else { 4364 pkg.usesLibraryFiles = null; 4365 } 4366 } 4367 return true; 4368 } 4369 4370 private static boolean hasString(List<String> list, List<String> which) { 4371 if (list == null) { 4372 return false; 4373 } 4374 for (int i=list.size()-1; i>=0; i--) { 4375 for (int j=which.size()-1; j>=0; j--) { 4376 if (which.get(j).equals(list.get(i))) { 4377 return true; 4378 } 4379 } 4380 } 4381 return false; 4382 } 4383 4384 private void updateAllSharedLibrariesLPw() { 4385 for (PackageParser.Package pkg : mPackages.values()) { 4386 updateSharedLibrariesLPw(pkg, null); 4387 } 4388 } 4389 4390 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4391 PackageParser.Package changingPkg) { 4392 ArrayList<PackageParser.Package> res = null; 4393 for (PackageParser.Package pkg : mPackages.values()) { 4394 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4395 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4396 if (res == null) { 4397 res = new ArrayList<PackageParser.Package>(); 4398 } 4399 res.add(pkg); 4400 updateSharedLibrariesLPw(pkg, changingPkg); 4401 } 4402 } 4403 return res; 4404 } 4405 4406 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4407 int parseFlags, int scanMode, long currentTime, UserHandle user) { 4408 File scanFile = new File(pkg.mScanPath); 4409 if (scanFile == null || pkg.applicationInfo.sourceDir == null || 4410 pkg.applicationInfo.publicSourceDir == null) { 4411 // Bail out. The resource and code paths haven't been set. 4412 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4413 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4414 return null; 4415 } 4416 4417 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4418 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4419 } 4420 4421 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4422 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4423 } 4424 4425 if (mCustomResolverComponentName != null && 4426 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4427 setUpCustomResolverActivity(pkg); 4428 } 4429 4430 if (pkg.packageName.equals("android")) { 4431 synchronized (mPackages) { 4432 if (mAndroidApplication != null) { 4433 Slog.w(TAG, "*************************************************"); 4434 Slog.w(TAG, "Core android package being redefined. Skipping."); 4435 Slog.w(TAG, " file=" + scanFile); 4436 Slog.w(TAG, "*************************************************"); 4437 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4438 return null; 4439 } 4440 4441 // Set up information for our fall-back user intent resolution activity. 4442 mPlatformPackage = pkg; 4443 pkg.mVersionCode = mSdkVersion; 4444 mAndroidApplication = pkg.applicationInfo; 4445 4446 if (!mResolverReplaced) { 4447 mResolveActivity.applicationInfo = mAndroidApplication; 4448 mResolveActivity.name = ResolverActivity.class.getName(); 4449 mResolveActivity.packageName = mAndroidApplication.packageName; 4450 mResolveActivity.processName = "system:ui"; 4451 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4452 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4453 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert; 4454 mResolveActivity.exported = true; 4455 mResolveActivity.enabled = true; 4456 mResolveInfo.activityInfo = mResolveActivity; 4457 mResolveInfo.priority = 0; 4458 mResolveInfo.preferredOrder = 0; 4459 mResolveInfo.match = 0; 4460 mResolveComponentName = new ComponentName( 4461 mAndroidApplication.packageName, mResolveActivity.name); 4462 } 4463 } 4464 } 4465 4466 if (DEBUG_PACKAGE_SCANNING) { 4467 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4468 Log.d(TAG, "Scanning package " + pkg.packageName); 4469 } 4470 4471 if (mPackages.containsKey(pkg.packageName) 4472 || mSharedLibraries.containsKey(pkg.packageName)) { 4473 Slog.w(TAG, "Application package " + pkg.packageName 4474 + " already installed. Skipping duplicate."); 4475 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4476 return null; 4477 } 4478 4479 // Initialize package source and resource directories 4480 File destCodeFile = new File(pkg.applicationInfo.sourceDir); 4481 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir); 4482 4483 SharedUserSetting suid = null; 4484 PackageSetting pkgSetting = null; 4485 4486 if (!isSystemApp(pkg)) { 4487 // Only system apps can use these features. 4488 pkg.mOriginalPackages = null; 4489 pkg.mRealPackage = null; 4490 pkg.mAdoptPermissions = null; 4491 } 4492 4493 // writer 4494 synchronized (mPackages) { 4495 if (pkg.mSharedUserId != null) { 4496 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 4497 if (suid == null) { 4498 Slog.w(TAG, "Creating application package " + pkg.packageName 4499 + " for shared user failed"); 4500 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4501 return null; 4502 } 4503 if (DEBUG_PACKAGE_SCANNING) { 4504 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4505 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 4506 + "): packages=" + suid.packages); 4507 } 4508 } 4509 4510 // Check if we are renaming from an original package name. 4511 PackageSetting origPackage = null; 4512 String realName = null; 4513 if (pkg.mOriginalPackages != null) { 4514 // This package may need to be renamed to a previously 4515 // installed name. Let's check on that... 4516 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 4517 if (pkg.mOriginalPackages.contains(renamed)) { 4518 // This package had originally been installed as the 4519 // original name, and we have already taken care of 4520 // transitioning to the new one. Just update the new 4521 // one to continue using the old name. 4522 realName = pkg.mRealPackage; 4523 if (!pkg.packageName.equals(renamed)) { 4524 // Callers into this function may have already taken 4525 // care of renaming the package; only do it here if 4526 // it is not already done. 4527 pkg.setPackageName(renamed); 4528 } 4529 4530 } else { 4531 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 4532 if ((origPackage = mSettings.peekPackageLPr( 4533 pkg.mOriginalPackages.get(i))) != null) { 4534 // We do have the package already installed under its 4535 // original name... should we use it? 4536 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 4537 // New package is not compatible with original. 4538 origPackage = null; 4539 continue; 4540 } else if (origPackage.sharedUser != null) { 4541 // Make sure uid is compatible between packages. 4542 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 4543 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 4544 + " to " + pkg.packageName + ": old uid " 4545 + origPackage.sharedUser.name 4546 + " differs from " + pkg.mSharedUserId); 4547 origPackage = null; 4548 continue; 4549 } 4550 } else { 4551 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 4552 + pkg.packageName + " to old name " + origPackage.name); 4553 } 4554 break; 4555 } 4556 } 4557 } 4558 } 4559 4560 if (mTransferedPackages.contains(pkg.packageName)) { 4561 Slog.w(TAG, "Package " + pkg.packageName 4562 + " was transferred to another, but its .apk remains"); 4563 } 4564 4565 // Just create the setting, don't add it yet. For already existing packages 4566 // the PkgSetting exists already and doesn't have to be created. 4567 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 4568 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 4569 pkg.applicationInfo.requiredCpuAbi, 4570 pkg.applicationInfo.flags, user, false); 4571 if (pkgSetting == null) { 4572 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 4573 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4574 return null; 4575 } 4576 4577 if (pkgSetting.origPackage != null) { 4578 // If we are first transitioning from an original package, 4579 // fix up the new package's name now. We need to do this after 4580 // looking up the package under its new name, so getPackageLP 4581 // can take care of fiddling things correctly. 4582 pkg.setPackageName(origPackage.name); 4583 4584 // File a report about this. 4585 String msg = "New package " + pkgSetting.realName 4586 + " renamed to replace old package " + pkgSetting.name; 4587 reportSettingsProblem(Log.WARN, msg); 4588 4589 // Make a note of it. 4590 mTransferedPackages.add(origPackage.name); 4591 4592 // No longer need to retain this. 4593 pkgSetting.origPackage = null; 4594 } 4595 4596 if (realName != null) { 4597 // Make a note of it. 4598 mTransferedPackages.add(pkg.packageName); 4599 } 4600 4601 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 4602 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 4603 } 4604 4605 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4606 // Check all shared libraries and map to their actual file path. 4607 // We only do this here for apps not on a system dir, because those 4608 // are the only ones that can fail an install due to this. We 4609 // will take care of the system apps by updating all of their 4610 // library paths after the scan is done. 4611 if (!updateSharedLibrariesLPw(pkg, null)) { 4612 return null; 4613 } 4614 } 4615 4616 if (mFoundPolicyFile) { 4617 SELinuxMMAC.assignSeinfoValue(pkg); 4618 } 4619 4620 pkg.applicationInfo.uid = pkgSetting.appId; 4621 pkg.mExtras = pkgSetting; 4622 4623 if (!verifySignaturesLP(pkgSetting, pkg)) { 4624 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4625 return null; 4626 } 4627 // The signature has changed, but this package is in the system 4628 // image... let's recover! 4629 pkgSetting.signatures.mSignatures = pkg.mSignatures; 4630 // However... if this package is part of a shared user, but it 4631 // doesn't match the signature of the shared user, let's fail. 4632 // What this means is that you can't change the signatures 4633 // associated with an overall shared user, which doesn't seem all 4634 // that unreasonable. 4635 if (pkgSetting.sharedUser != null) { 4636 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4637 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 4638 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 4639 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 4640 return null; 4641 } 4642 } 4643 // File a report about this. 4644 String msg = "System package " + pkg.packageName 4645 + " signature changed; retaining data."; 4646 reportSettingsProblem(Log.WARN, msg); 4647 } 4648 4649 // Verify that this new package doesn't have any content providers 4650 // that conflict with existing packages. Only do this if the 4651 // package isn't already installed, since we don't want to break 4652 // things that are installed. 4653 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 4654 final int N = pkg.providers.size(); 4655 int i; 4656 for (i=0; i<N; i++) { 4657 PackageParser.Provider p = pkg.providers.get(i); 4658 if (p.info.authority != null) { 4659 String names[] = p.info.authority.split(";"); 4660 for (int j = 0; j < names.length; j++) { 4661 if (mProvidersByAuthority.containsKey(names[j])) { 4662 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 4663 Slog.w(TAG, "Can't install because provider name " + names[j] + 4664 " (in package " + pkg.applicationInfo.packageName + 4665 ") is already used by " 4666 + ((other != null && other.getComponentName() != null) 4667 ? other.getComponentName().getPackageName() : "?")); 4668 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 4669 return null; 4670 } 4671 } 4672 } 4673 } 4674 } 4675 4676 if (pkg.mAdoptPermissions != null) { 4677 // This package wants to adopt ownership of permissions from 4678 // another package. 4679 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 4680 final String origName = pkg.mAdoptPermissions.get(i); 4681 final PackageSetting orig = mSettings.peekPackageLPr(origName); 4682 if (orig != null) { 4683 if (verifyPackageUpdateLPr(orig, pkg)) { 4684 Slog.i(TAG, "Adopting permissions from " + origName + " to " 4685 + pkg.packageName); 4686 mSettings.transferPermissionsLPw(origName, pkg.packageName); 4687 } 4688 } 4689 } 4690 } 4691 } 4692 4693 final String pkgName = pkg.packageName; 4694 4695 final long scanFileTime = scanFile.lastModified(); 4696 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 4697 pkg.applicationInfo.processName = fixProcessName( 4698 pkg.applicationInfo.packageName, 4699 pkg.applicationInfo.processName, 4700 pkg.applicationInfo.uid); 4701 4702 File dataPath; 4703 if (mPlatformPackage == pkg) { 4704 // The system package is special. 4705 dataPath = new File (Environment.getDataDirectory(), "system"); 4706 pkg.applicationInfo.dataDir = dataPath.getPath(); 4707 } else { 4708 // This is a normal package, need to make its data directory. 4709 dataPath = getDataPathForPackage(pkg.packageName, 0); 4710 4711 boolean uidError = false; 4712 4713 if (dataPath.exists()) { 4714 int currentUid = 0; 4715 try { 4716 StructStat stat = Libcore.os.stat(dataPath.getPath()); 4717 currentUid = stat.st_uid; 4718 } catch (ErrnoException e) { 4719 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 4720 } 4721 4722 // If we have mismatched owners for the data path, we have a problem. 4723 if (currentUid != pkg.applicationInfo.uid) { 4724 boolean recovered = false; 4725 if (currentUid == 0) { 4726 // The directory somehow became owned by root. Wow. 4727 // This is probably because the system was stopped while 4728 // installd was in the middle of messing with its libs 4729 // directory. Ask installd to fix that. 4730 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 4731 pkg.applicationInfo.uid); 4732 if (ret >= 0) { 4733 recovered = true; 4734 String msg = "Package " + pkg.packageName 4735 + " unexpectedly changed to uid 0; recovered to " + 4736 + pkg.applicationInfo.uid; 4737 reportSettingsProblem(Log.WARN, msg); 4738 } 4739 } 4740 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 4741 || (scanMode&SCAN_BOOTING) != 0)) { 4742 // If this is a system app, we can at least delete its 4743 // current data so the application will still work. 4744 int ret = removeDataDirsLI(pkgName); 4745 if (ret >= 0) { 4746 // TODO: Kill the processes first 4747 // Old data gone! 4748 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 4749 ? "System package " : "Third party package "; 4750 String msg = prefix + pkg.packageName 4751 + " has changed from uid: " 4752 + currentUid + " to " 4753 + pkg.applicationInfo.uid + "; old data erased"; 4754 reportSettingsProblem(Log.WARN, msg); 4755 recovered = true; 4756 4757 // And now re-install the app. 4758 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 4759 pkg.applicationInfo.seinfo); 4760 if (ret == -1) { 4761 // Ack should not happen! 4762 msg = prefix + pkg.packageName 4763 + " could not have data directory re-created after delete."; 4764 reportSettingsProblem(Log.WARN, msg); 4765 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4766 return null; 4767 } 4768 } 4769 if (!recovered) { 4770 mHasSystemUidErrors = true; 4771 } 4772 } else if (!recovered) { 4773 // If we allow this install to proceed, we will be broken. 4774 // Abort, abort! 4775 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 4776 return null; 4777 } 4778 if (!recovered) { 4779 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 4780 + pkg.applicationInfo.uid + "/fs_" 4781 + currentUid; 4782 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 4783 String msg = "Package " + pkg.packageName 4784 + " has mismatched uid: " 4785 + currentUid + " on disk, " 4786 + pkg.applicationInfo.uid + " in settings"; 4787 // writer 4788 synchronized (mPackages) { 4789 mSettings.mReadMessages.append(msg); 4790 mSettings.mReadMessages.append('\n'); 4791 uidError = true; 4792 if (!pkgSetting.uidError) { 4793 reportSettingsProblem(Log.ERROR, msg); 4794 } 4795 } 4796 } 4797 } 4798 pkg.applicationInfo.dataDir = dataPath.getPath(); 4799 if (mShouldRestoreconData) { 4800 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 4801 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 4802 pkg.applicationInfo.uid); 4803 } 4804 } else { 4805 if (DEBUG_PACKAGE_SCANNING) { 4806 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4807 Log.v(TAG, "Want this data dir: " + dataPath); 4808 } 4809 //invoke installer to do the actual installation 4810 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 4811 pkg.applicationInfo.seinfo); 4812 if (ret < 0) { 4813 // Error from installer 4814 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4815 return null; 4816 } 4817 4818 if (dataPath.exists()) { 4819 pkg.applicationInfo.dataDir = dataPath.getPath(); 4820 } else { 4821 Slog.w(TAG, "Unable to create data directory: " + dataPath); 4822 pkg.applicationInfo.dataDir = null; 4823 } 4824 } 4825 4826 /* 4827 * Set the data dir to the default "/data/data/<package name>/lib" 4828 * if we got here without anyone telling us different (e.g., apps 4829 * stored on SD card have their native libraries stored in the ASEC 4830 * container with the APK). 4831 * 4832 * This happens during an upgrade from a package settings file that 4833 * doesn't have a native library path attribute at all. 4834 */ 4835 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 4836 if (pkgSetting.nativeLibraryPathString == null) { 4837 setInternalAppNativeLibraryPath(pkg, pkgSetting); 4838 } else { 4839 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 4840 } 4841 } 4842 4843 pkgSetting.uidError = uidError; 4844 } 4845 4846 String path = scanFile.getPath(); 4847 /* Note: We don't want to unpack the native binaries for 4848 * system applications, unless they have been updated 4849 * (the binaries are already under /system/lib). 4850 * Also, don't unpack libs for apps on the external card 4851 * since they should have their libraries in the ASEC 4852 * container already. 4853 * 4854 * In other words, we're going to unpack the binaries 4855 * only for non-system apps and system app upgrades. 4856 */ 4857 if (pkg.applicationInfo.nativeLibraryDir != null) { 4858 try { 4859 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 4860 final String dataPathString = dataPath.getCanonicalPath(); 4861 4862 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 4863 /* 4864 * Upgrading from a previous version of the OS sometimes 4865 * leaves native libraries in the /data/data/<app>/lib 4866 * directory for system apps even when they shouldn't be. 4867 * Recent changes in the JNI library search path 4868 * necessitates we remove those to match previous behavior. 4869 */ 4870 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 4871 Log.i(TAG, "removed obsolete native libraries for system package " 4872 + path); 4873 } 4874 } else { 4875 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 4876 /* 4877 * Update native library dir if it starts with 4878 * /data/data 4879 */ 4880 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 4881 setInternalAppNativeLibraryPath(pkg, pkgSetting); 4882 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 4883 } 4884 4885 try { 4886 int copyRet = copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir); 4887 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 4888 Slog.e(TAG, "Unable to copy native libraries"); 4889 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 4890 return null; 4891 } 4892 4893 // We've successfully copied native libraries across, so we make a 4894 // note of what ABI we're using 4895 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 4896 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[copyRet]; 4897 } else { 4898 pkg.applicationInfo.requiredCpuAbi = null; 4899 } 4900 } catch (IOException e) { 4901 Slog.e(TAG, "Unable to copy native libraries", e); 4902 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 4903 return null; 4904 } 4905 } 4906 4907 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 4908 final int[] userIds = sUserManager.getUserIds(); 4909 synchronized (mInstallLock) { 4910 for (int userId : userIds) { 4911 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 4912 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 4913 Slog.w(TAG, "Failed linking native library dir (user=" + userId 4914 + ")"); 4915 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 4916 return null; 4917 } 4918 } 4919 } 4920 } 4921 } catch (IOException ioe) { 4922 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 4923 } 4924 } 4925 pkg.mScanPath = path; 4926 4927 if ((scanMode&SCAN_NO_DEX) == 0) { 4928 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 4929 == DEX_OPT_FAILED) { 4930 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 4931 removeDataDirsLI(pkg.packageName); 4932 } 4933 4934 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 4935 return null; 4936 } 4937 } 4938 4939 if (mFactoryTest && pkg.requestedPermissions.contains( 4940 android.Manifest.permission.FACTORY_TEST)) { 4941 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 4942 } 4943 4944 ArrayList<PackageParser.Package> clientLibPkgs = null; 4945 4946 // writer 4947 synchronized (mPackages) { 4948 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 4949 // Only system apps can add new shared libraries. 4950 if (pkg.libraryNames != null) { 4951 for (int i=0; i<pkg.libraryNames.size(); i++) { 4952 String name = pkg.libraryNames.get(i); 4953 boolean allowed = false; 4954 if (isUpdatedSystemApp(pkg)) { 4955 // New library entries can only be added through the 4956 // system image. This is important to get rid of a lot 4957 // of nasty edge cases: for example if we allowed a non- 4958 // system update of the app to add a library, then uninstalling 4959 // the update would make the library go away, and assumptions 4960 // we made such as through app install filtering would now 4961 // have allowed apps on the device which aren't compatible 4962 // with it. Better to just have the restriction here, be 4963 // conservative, and create many fewer cases that can negatively 4964 // impact the user experience. 4965 final PackageSetting sysPs = mSettings 4966 .getDisabledSystemPkgLPr(pkg.packageName); 4967 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 4968 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 4969 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 4970 allowed = true; 4971 allowed = true; 4972 break; 4973 } 4974 } 4975 } 4976 } else { 4977 allowed = true; 4978 } 4979 if (allowed) { 4980 if (!mSharedLibraries.containsKey(name)) { 4981 mSharedLibraries.put(name, new SharedLibraryEntry(null, 4982 pkg.packageName)); 4983 } else if (!name.equals(pkg.packageName)) { 4984 Slog.w(TAG, "Package " + pkg.packageName + " library " 4985 + name + " already exists; skipping"); 4986 } 4987 } else { 4988 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 4989 + name + " that is not declared on system image; skipping"); 4990 } 4991 } 4992 if ((scanMode&SCAN_BOOTING) == 0) { 4993 // If we are not booting, we need to update any applications 4994 // that are clients of our shared library. If we are booting, 4995 // this will all be done once the scan is complete. 4996 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 4997 } 4998 } 4999 } 5000 } 5001 5002 // We also need to dexopt any apps that are dependent on this library. Note that 5003 // if these fail, we should abort the install since installing the library will 5004 // result in some apps being broken. 5005 if (clientLibPkgs != null) { 5006 if ((scanMode&SCAN_NO_DEX) == 0) { 5007 for (int i=0; i<clientLibPkgs.size(); i++) { 5008 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5009 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5010 == DEX_OPT_FAILED) { 5011 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5012 removeDataDirsLI(pkg.packageName); 5013 } 5014 5015 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5016 return null; 5017 } 5018 } 5019 } 5020 } 5021 5022 // Request the ActivityManager to kill the process(only for existing packages) 5023 // so that we do not end up in a confused state while the user is still using the older 5024 // version of the application while the new one gets installed. 5025 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5026 // If the package lives in an asec, tell everyone that the container is going 5027 // away so they can clean up any references to its resources (which would prevent 5028 // vold from being able to unmount the asec) 5029 if (isForwardLocked(pkg) || isExternal(pkg)) { 5030 if (DEBUG_INSTALL) { 5031 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5032 } 5033 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5034 final ArrayList<String> pkgList = new ArrayList<String>(1); 5035 pkgList.add(pkg.applicationInfo.packageName); 5036 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5037 } 5038 5039 // Post the request that it be killed now that the going-away broadcast is en route 5040 killApplication(pkg.applicationInfo.packageName, 5041 pkg.applicationInfo.uid, "update pkg"); 5042 } 5043 5044 // Also need to kill any apps that are dependent on the library. 5045 if (clientLibPkgs != null) { 5046 for (int i=0; i<clientLibPkgs.size(); i++) { 5047 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5048 killApplication(clientPkg.applicationInfo.packageName, 5049 clientPkg.applicationInfo.uid, "update lib"); 5050 } 5051 } 5052 5053 // writer 5054 synchronized (mPackages) { 5055 // We don't expect installation to fail beyond this point, 5056 if ((scanMode&SCAN_MONITOR) != 0) { 5057 mAppDirs.put(pkg.mPath, pkg); 5058 } 5059 // Add the new setting to mSettings 5060 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5061 // Add the new setting to mPackages 5062 mPackages.put(pkg.applicationInfo.packageName, pkg); 5063 // Make sure we don't accidentally delete its data. 5064 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5065 while (iter.hasNext()) { 5066 PackageCleanItem item = iter.next(); 5067 if (pkgName.equals(item.packageName)) { 5068 iter.remove(); 5069 } 5070 } 5071 5072 // Take care of first install / last update times. 5073 if (currentTime != 0) { 5074 if (pkgSetting.firstInstallTime == 0) { 5075 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5076 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5077 pkgSetting.lastUpdateTime = currentTime; 5078 } 5079 } else if (pkgSetting.firstInstallTime == 0) { 5080 // We need *something*. Take time time stamp of the file. 5081 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5082 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5083 if (scanFileTime != pkgSetting.timeStamp) { 5084 // A package on the system image has changed; consider this 5085 // to be an update. 5086 pkgSetting.lastUpdateTime = scanFileTime; 5087 } 5088 } 5089 5090 // Add the package's KeySets to the global KeySetManager 5091 KeySetManager ksm = mSettings.mKeySetManager; 5092 try { 5093 ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5094 if (pkg.mKeySetMapping != null) { 5095 for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) { 5096 if (entry.getValue() != null) { 5097 ksm.addDefinedKeySetToPackage(pkg.packageName, 5098 entry.getValue(), entry.getKey()); 5099 } 5100 } 5101 } 5102 } catch (NullPointerException e) { 5103 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5104 } catch (IllegalArgumentException e) { 5105 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5106 } 5107 5108 int N = pkg.providers.size(); 5109 StringBuilder r = null; 5110 int i; 5111 for (i=0; i<N; i++) { 5112 PackageParser.Provider p = pkg.providers.get(i); 5113 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5114 p.info.processName, pkg.applicationInfo.uid); 5115 mProviders.addProvider(p); 5116 p.syncable = p.info.isSyncable; 5117 if (p.info.authority != null) { 5118 String names[] = p.info.authority.split(";"); 5119 p.info.authority = null; 5120 for (int j = 0; j < names.length; j++) { 5121 if (j == 1 && p.syncable) { 5122 // We only want the first authority for a provider to possibly be 5123 // syncable, so if we already added this provider using a different 5124 // authority clear the syncable flag. We copy the provider before 5125 // changing it because the mProviders object contains a reference 5126 // to a provider that we don't want to change. 5127 // Only do this for the second authority since the resulting provider 5128 // object can be the same for all future authorities for this provider. 5129 p = new PackageParser.Provider(p); 5130 p.syncable = false; 5131 } 5132 if (!mProvidersByAuthority.containsKey(names[j])) { 5133 mProvidersByAuthority.put(names[j], p); 5134 if (p.info.authority == null) { 5135 p.info.authority = names[j]; 5136 } else { 5137 p.info.authority = p.info.authority + ";" + names[j]; 5138 } 5139 if (DEBUG_PACKAGE_SCANNING) { 5140 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5141 Log.d(TAG, "Registered content provider: " + names[j] 5142 + ", className = " + p.info.name + ", isSyncable = " 5143 + p.info.isSyncable); 5144 } 5145 } else { 5146 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5147 Slog.w(TAG, "Skipping provider name " + names[j] + 5148 " (in package " + pkg.applicationInfo.packageName + 5149 "): name already used by " 5150 + ((other != null && other.getComponentName() != null) 5151 ? other.getComponentName().getPackageName() : "?")); 5152 } 5153 } 5154 } 5155 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5156 if (r == null) { 5157 r = new StringBuilder(256); 5158 } else { 5159 r.append(' '); 5160 } 5161 r.append(p.info.name); 5162 } 5163 } 5164 if (r != null) { 5165 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5166 } 5167 5168 N = pkg.services.size(); 5169 r = null; 5170 for (i=0; i<N; i++) { 5171 PackageParser.Service s = pkg.services.get(i); 5172 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5173 s.info.processName, pkg.applicationInfo.uid); 5174 mServices.addService(s); 5175 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5176 if (r == null) { 5177 r = new StringBuilder(256); 5178 } else { 5179 r.append(' '); 5180 } 5181 r.append(s.info.name); 5182 } 5183 } 5184 if (r != null) { 5185 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5186 } 5187 5188 N = pkg.receivers.size(); 5189 r = null; 5190 for (i=0; i<N; i++) { 5191 PackageParser.Activity a = pkg.receivers.get(i); 5192 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5193 a.info.processName, pkg.applicationInfo.uid); 5194 mReceivers.addActivity(a, "receiver"); 5195 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5196 if (r == null) { 5197 r = new StringBuilder(256); 5198 } else { 5199 r.append(' '); 5200 } 5201 r.append(a.info.name); 5202 } 5203 } 5204 if (r != null) { 5205 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5206 } 5207 5208 N = pkg.activities.size(); 5209 r = null; 5210 for (i=0; i<N; i++) { 5211 PackageParser.Activity a = pkg.activities.get(i); 5212 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5213 a.info.processName, pkg.applicationInfo.uid); 5214 mActivities.addActivity(a, "activity"); 5215 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5216 if (r == null) { 5217 r = new StringBuilder(256); 5218 } else { 5219 r.append(' '); 5220 } 5221 r.append(a.info.name); 5222 } 5223 } 5224 if (r != null) { 5225 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5226 } 5227 5228 N = pkg.permissionGroups.size(); 5229 r = null; 5230 for (i=0; i<N; i++) { 5231 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5232 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5233 if (cur == null) { 5234 mPermissionGroups.put(pg.info.name, pg); 5235 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5236 if (r == null) { 5237 r = new StringBuilder(256); 5238 } else { 5239 r.append(' '); 5240 } 5241 r.append(pg.info.name); 5242 } 5243 } else { 5244 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5245 + pg.info.packageName + " ignored: original from " 5246 + cur.info.packageName); 5247 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5248 if (r == null) { 5249 r = new StringBuilder(256); 5250 } else { 5251 r.append(' '); 5252 } 5253 r.append("DUP:"); 5254 r.append(pg.info.name); 5255 } 5256 } 5257 } 5258 if (r != null) { 5259 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5260 } 5261 5262 N = pkg.permissions.size(); 5263 r = null; 5264 for (i=0; i<N; i++) { 5265 PackageParser.Permission p = pkg.permissions.get(i); 5266 HashMap<String, BasePermission> permissionMap = 5267 p.tree ? mSettings.mPermissionTrees 5268 : mSettings.mPermissions; 5269 p.group = mPermissionGroups.get(p.info.group); 5270 if (p.info.group == null || p.group != null) { 5271 BasePermission bp = permissionMap.get(p.info.name); 5272 if (bp == null) { 5273 bp = new BasePermission(p.info.name, p.info.packageName, 5274 BasePermission.TYPE_NORMAL); 5275 permissionMap.put(p.info.name, bp); 5276 } 5277 if (bp.perm == null) { 5278 if (bp.sourcePackage != null 5279 && !bp.sourcePackage.equals(p.info.packageName)) { 5280 // If this is a permission that was formerly defined by a non-system 5281 // app, but is now defined by a system app (following an upgrade), 5282 // discard the previous declaration and consider the system's to be 5283 // canonical. 5284 if (isSystemApp(p.owner)) { 5285 String msg = "New decl " + p.owner + " of permission " 5286 + p.info.name + " is system"; 5287 reportSettingsProblem(Log.WARN, msg); 5288 bp.sourcePackage = null; 5289 } 5290 } 5291 if (bp.sourcePackage == null 5292 || bp.sourcePackage.equals(p.info.packageName)) { 5293 BasePermission tree = findPermissionTreeLP(p.info.name); 5294 if (tree == null 5295 || tree.sourcePackage.equals(p.info.packageName)) { 5296 bp.packageSetting = pkgSetting; 5297 bp.perm = p; 5298 bp.uid = pkg.applicationInfo.uid; 5299 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5300 if (r == null) { 5301 r = new StringBuilder(256); 5302 } else { 5303 r.append(' '); 5304 } 5305 r.append(p.info.name); 5306 } 5307 } else { 5308 Slog.w(TAG, "Permission " + p.info.name + " from package " 5309 + p.info.packageName + " ignored: base tree " 5310 + tree.name + " is from package " 5311 + tree.sourcePackage); 5312 } 5313 } else { 5314 Slog.w(TAG, "Permission " + p.info.name + " from package " 5315 + p.info.packageName + " ignored: original from " 5316 + bp.sourcePackage); 5317 } 5318 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5319 if (r == null) { 5320 r = new StringBuilder(256); 5321 } else { 5322 r.append(' '); 5323 } 5324 r.append("DUP:"); 5325 r.append(p.info.name); 5326 } 5327 if (bp.perm == p) { 5328 bp.protectionLevel = p.info.protectionLevel; 5329 } 5330 } else { 5331 Slog.w(TAG, "Permission " + p.info.name + " from package " 5332 + p.info.packageName + " ignored: no group " 5333 + p.group); 5334 } 5335 } 5336 if (r != null) { 5337 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5338 } 5339 5340 N = pkg.instrumentation.size(); 5341 r = null; 5342 for (i=0; i<N; i++) { 5343 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5344 a.info.packageName = pkg.applicationInfo.packageName; 5345 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5346 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5347 a.info.dataDir = pkg.applicationInfo.dataDir; 5348 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5349 mInstrumentation.put(a.getComponentName(), a); 5350 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5351 if (r == null) { 5352 r = new StringBuilder(256); 5353 } else { 5354 r.append(' '); 5355 } 5356 r.append(a.info.name); 5357 } 5358 } 5359 if (r != null) { 5360 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5361 } 5362 5363 if (pkg.protectedBroadcasts != null) { 5364 N = pkg.protectedBroadcasts.size(); 5365 for (i=0; i<N; i++) { 5366 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5367 } 5368 } 5369 5370 pkgSetting.setTimeStamp(scanFileTime); 5371 5372 // Create idmap files for pairs of (packages, overlay packages). 5373 // Note: "android", ie framework-res.apk, is handled by native layers. 5374 if (pkg.mOverlayTarget != null) { 5375 // This is an overlay package. 5376 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 5377 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 5378 mOverlays.put(pkg.mOverlayTarget, 5379 new HashMap<String, PackageParser.Package>()); 5380 } 5381 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 5382 map.put(pkg.packageName, pkg); 5383 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 5384 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 5385 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5386 return null; 5387 } 5388 } 5389 } else if (mOverlays.containsKey(pkg.packageName) && 5390 !pkg.packageName.equals("android")) { 5391 // This is a regular package, with one or more known overlay packages. 5392 createIdmapsForPackageLI(pkg); 5393 } 5394 } 5395 5396 return pkg; 5397 } 5398 5399 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 5400 synchronized (mPackages) { 5401 mResolverReplaced = true; 5402 // Set up information for custom user intent resolution activity. 5403 mResolveActivity.applicationInfo = pkg.applicationInfo; 5404 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 5405 mResolveActivity.packageName = pkg.applicationInfo.packageName; 5406 mResolveActivity.processName = null; 5407 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5408 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 5409 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 5410 mResolveActivity.theme = 0; 5411 mResolveActivity.exported = true; 5412 mResolveActivity.enabled = true; 5413 mResolveInfo.activityInfo = mResolveActivity; 5414 mResolveInfo.priority = 0; 5415 mResolveInfo.preferredOrder = 0; 5416 mResolveInfo.match = 0; 5417 mResolveComponentName = mCustomResolverComponentName; 5418 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 5419 mResolveComponentName); 5420 } 5421 } 5422 5423 private String calculateApkRoot(final File codePath) { 5424 final File codeRoot; 5425 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 5426 codeRoot = Environment.getRootDirectory(); 5427 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 5428 codeRoot = Environment.getRootDirectory(); 5429 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 5430 codeRoot = Environment.getVendorDirectory(); 5431 } else { 5432 // Unrecognized code path; take its top real segment as the apk root: 5433 // e.g. /something/app/blah.apk => /something 5434 try { 5435 File f = codePath.getCanonicalFile(); 5436 File parent = f.getParentFile(); // non-null because codePath is a file 5437 File tmp; 5438 while ((tmp = parent.getParentFile()) != null) { 5439 f = parent; 5440 parent = tmp; 5441 } 5442 codeRoot = f; 5443 Slog.w(TAG, "Unrecognized code path " 5444 + codePath + " - using " + codeRoot); 5445 } catch (IOException e) { 5446 // Can't canonicalize the lib path -- shenanigans? 5447 Slog.w(TAG, "Can't canonicalize code path " + codePath); 5448 return Environment.getRootDirectory().getPath(); 5449 } 5450 } 5451 return codeRoot.getPath(); 5452 } 5453 5454 // This is the initial scan-time determination of how to handle a given 5455 // package for purposes of native library location. 5456 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 5457 PackageSetting pkgSetting) { 5458 // "bundled" here means system-installed with no overriding update 5459 final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg); 5460 final String apkName = getApkName(pkgSetting.codePathString); 5461 final File libDir; 5462 if (bundledApk) { 5463 // If "/system/lib64/apkname" exists, assume that is the per-package 5464 // native library directory to use; otherwise use "/system/lib/apkname". 5465 String apkRoot = calculateApkRoot(pkgSetting.codePath); 5466 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 5467 File packLib64 = new File(lib64, apkName); 5468 libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 5469 } else { 5470 libDir = mAppLibInstallDir; 5471 } 5472 final String nativeLibraryPath = (new File(libDir, apkName)).getPath(); 5473 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 5474 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 5475 } 5476 5477 private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir) 5478 throws IOException { 5479 if (!nativeLibraryDir.isDirectory()) { 5480 nativeLibraryDir.delete(); 5481 5482 if (!nativeLibraryDir.mkdir()) { 5483 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 5484 } 5485 5486 try { 5487 Libcore.os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH 5488 | S_IXOTH); 5489 } catch (ErrnoException e) { 5490 throw new IOException("Cannot chmod native library directory " 5491 + nativeLibraryDir.getPath(), e); 5492 } 5493 } else if (!SELinux.restorecon(nativeLibraryDir)) { 5494 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 5495 } 5496 5497 /* 5498 * If this is an internal application or our nativeLibraryPath points to 5499 * the app-lib directory, unpack the libraries if necessary. 5500 */ 5501 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile); 5502 try { 5503 int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS); 5504 if (abi >= 0) { 5505 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 5506 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 5507 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 5508 return copyRet; 5509 } 5510 } 5511 5512 return abi; 5513 } finally { 5514 handle.close(); 5515 } 5516 } 5517 5518 private void killApplication(String pkgName, int appId, String reason) { 5519 // Request the ActivityManager to kill the process(only for existing packages) 5520 // so that we do not end up in a confused state while the user is still using the older 5521 // version of the application while the new one gets installed. 5522 IActivityManager am = ActivityManagerNative.getDefault(); 5523 if (am != null) { 5524 try { 5525 am.killApplicationWithAppId(pkgName, appId, reason); 5526 } catch (RemoteException e) { 5527 } 5528 } 5529 } 5530 5531 void removePackageLI(PackageSetting ps, boolean chatty) { 5532 if (DEBUG_INSTALL) { 5533 if (chatty) 5534 Log.d(TAG, "Removing package " + ps.name); 5535 } 5536 5537 // writer 5538 synchronized (mPackages) { 5539 mPackages.remove(ps.name); 5540 if (ps.codePathString != null) { 5541 mAppDirs.remove(ps.codePathString); 5542 } 5543 5544 final PackageParser.Package pkg = ps.pkg; 5545 if (pkg != null) { 5546 cleanPackageDataStructuresLILPw(pkg, chatty); 5547 } 5548 } 5549 } 5550 5551 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 5552 if (DEBUG_INSTALL) { 5553 if (chatty) 5554 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 5555 } 5556 5557 // writer 5558 synchronized (mPackages) { 5559 mPackages.remove(pkg.applicationInfo.packageName); 5560 if (pkg.mPath != null) { 5561 mAppDirs.remove(pkg.mPath); 5562 } 5563 cleanPackageDataStructuresLILPw(pkg, chatty); 5564 } 5565 } 5566 5567 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 5568 int N = pkg.providers.size(); 5569 StringBuilder r = null; 5570 int i; 5571 for (i=0; i<N; i++) { 5572 PackageParser.Provider p = pkg.providers.get(i); 5573 mProviders.removeProvider(p); 5574 if (p.info.authority == null) { 5575 5576 /* There was another ContentProvider with this authority when 5577 * this app was installed so this authority is null, 5578 * Ignore it as we don't have to unregister the provider. 5579 */ 5580 continue; 5581 } 5582 String names[] = p.info.authority.split(";"); 5583 for (int j = 0; j < names.length; j++) { 5584 if (mProvidersByAuthority.get(names[j]) == p) { 5585 mProvidersByAuthority.remove(names[j]); 5586 if (DEBUG_REMOVE) { 5587 if (chatty) 5588 Log.d(TAG, "Unregistered content provider: " + names[j] 5589 + ", className = " + p.info.name + ", isSyncable = " 5590 + p.info.isSyncable); 5591 } 5592 } 5593 } 5594 if (DEBUG_REMOVE && chatty) { 5595 if (r == null) { 5596 r = new StringBuilder(256); 5597 } else { 5598 r.append(' '); 5599 } 5600 r.append(p.info.name); 5601 } 5602 } 5603 if (r != null) { 5604 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 5605 } 5606 5607 N = pkg.services.size(); 5608 r = null; 5609 for (i=0; i<N; i++) { 5610 PackageParser.Service s = pkg.services.get(i); 5611 mServices.removeService(s); 5612 if (chatty) { 5613 if (r == null) { 5614 r = new StringBuilder(256); 5615 } else { 5616 r.append(' '); 5617 } 5618 r.append(s.info.name); 5619 } 5620 } 5621 if (r != null) { 5622 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 5623 } 5624 5625 N = pkg.receivers.size(); 5626 r = null; 5627 for (i=0; i<N; i++) { 5628 PackageParser.Activity a = pkg.receivers.get(i); 5629 mReceivers.removeActivity(a, "receiver"); 5630 if (DEBUG_REMOVE && chatty) { 5631 if (r == null) { 5632 r = new StringBuilder(256); 5633 } else { 5634 r.append(' '); 5635 } 5636 r.append(a.info.name); 5637 } 5638 } 5639 if (r != null) { 5640 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 5641 } 5642 5643 N = pkg.activities.size(); 5644 r = null; 5645 for (i=0; i<N; i++) { 5646 PackageParser.Activity a = pkg.activities.get(i); 5647 mActivities.removeActivity(a, "activity"); 5648 if (DEBUG_REMOVE && chatty) { 5649 if (r == null) { 5650 r = new StringBuilder(256); 5651 } else { 5652 r.append(' '); 5653 } 5654 r.append(a.info.name); 5655 } 5656 } 5657 if (r != null) { 5658 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 5659 } 5660 5661 N = pkg.permissions.size(); 5662 r = null; 5663 for (i=0; i<N; i++) { 5664 PackageParser.Permission p = pkg.permissions.get(i); 5665 BasePermission bp = mSettings.mPermissions.get(p.info.name); 5666 if (bp == null) { 5667 bp = mSettings.mPermissionTrees.get(p.info.name); 5668 } 5669 if (bp != null && bp.perm == p) { 5670 bp.perm = null; 5671 if (DEBUG_REMOVE && chatty) { 5672 if (r == null) { 5673 r = new StringBuilder(256); 5674 } else { 5675 r.append(' '); 5676 } 5677 r.append(p.info.name); 5678 } 5679 } 5680 } 5681 if (r != null) { 5682 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 5683 } 5684 5685 N = pkg.instrumentation.size(); 5686 r = null; 5687 for (i=0; i<N; i++) { 5688 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5689 mInstrumentation.remove(a.getComponentName()); 5690 if (DEBUG_REMOVE && chatty) { 5691 if (r == null) { 5692 r = new StringBuilder(256); 5693 } else { 5694 r.append(' '); 5695 } 5696 r.append(a.info.name); 5697 } 5698 } 5699 if (r != null) { 5700 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 5701 } 5702 5703 r = null; 5704 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5705 // Only system apps can hold shared libraries. 5706 if (pkg.libraryNames != null) { 5707 for (i=0; i<pkg.libraryNames.size(); i++) { 5708 String name = pkg.libraryNames.get(i); 5709 SharedLibraryEntry cur = mSharedLibraries.get(name); 5710 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 5711 mSharedLibraries.remove(name); 5712 if (DEBUG_REMOVE && chatty) { 5713 if (r == null) { 5714 r = new StringBuilder(256); 5715 } else { 5716 r.append(' '); 5717 } 5718 r.append(name); 5719 } 5720 } 5721 } 5722 } 5723 } 5724 if (r != null) { 5725 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 5726 } 5727 } 5728 5729 private static final boolean isPackageFilename(String name) { 5730 return name != null && name.endsWith(".apk"); 5731 } 5732 5733 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 5734 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 5735 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 5736 return true; 5737 } 5738 } 5739 return false; 5740 } 5741 5742 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 5743 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 5744 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 5745 5746 private void updatePermissionsLPw(String changingPkg, 5747 PackageParser.Package pkgInfo, int flags) { 5748 // Make sure there are no dangling permission trees. 5749 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 5750 while (it.hasNext()) { 5751 final BasePermission bp = it.next(); 5752 if (bp.packageSetting == null) { 5753 // We may not yet have parsed the package, so just see if 5754 // we still know about its settings. 5755 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 5756 } 5757 if (bp.packageSetting == null) { 5758 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 5759 + " from package " + bp.sourcePackage); 5760 it.remove(); 5761 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 5762 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 5763 Slog.i(TAG, "Removing old permission tree: " + bp.name 5764 + " from package " + bp.sourcePackage); 5765 flags |= UPDATE_PERMISSIONS_ALL; 5766 it.remove(); 5767 } 5768 } 5769 } 5770 5771 // Make sure all dynamic permissions have been assigned to a package, 5772 // and make sure there are no dangling permissions. 5773 it = mSettings.mPermissions.values().iterator(); 5774 while (it.hasNext()) { 5775 final BasePermission bp = it.next(); 5776 if (bp.type == BasePermission.TYPE_DYNAMIC) { 5777 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 5778 + bp.name + " pkg=" + bp.sourcePackage 5779 + " info=" + bp.pendingInfo); 5780 if (bp.packageSetting == null && bp.pendingInfo != null) { 5781 final BasePermission tree = findPermissionTreeLP(bp.name); 5782 if (tree != null && tree.perm != null) { 5783 bp.packageSetting = tree.packageSetting; 5784 bp.perm = new PackageParser.Permission(tree.perm.owner, 5785 new PermissionInfo(bp.pendingInfo)); 5786 bp.perm.info.packageName = tree.perm.info.packageName; 5787 bp.perm.info.name = bp.name; 5788 bp.uid = tree.uid; 5789 } 5790 } 5791 } 5792 if (bp.packageSetting == null) { 5793 // We may not yet have parsed the package, so just see if 5794 // we still know about its settings. 5795 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 5796 } 5797 if (bp.packageSetting == null) { 5798 Slog.w(TAG, "Removing dangling permission: " + bp.name 5799 + " from package " + bp.sourcePackage); 5800 it.remove(); 5801 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 5802 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 5803 Slog.i(TAG, "Removing old permission: " + bp.name 5804 + " from package " + bp.sourcePackage); 5805 flags |= UPDATE_PERMISSIONS_ALL; 5806 it.remove(); 5807 } 5808 } 5809 } 5810 5811 // Now update the permissions for all packages, in particular 5812 // replace the granted permissions of the system packages. 5813 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 5814 for (PackageParser.Package pkg : mPackages.values()) { 5815 if (pkg != pkgInfo) { 5816 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 5817 } 5818 } 5819 } 5820 5821 if (pkgInfo != null) { 5822 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 5823 } 5824 } 5825 5826 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 5827 final PackageSetting ps = (PackageSetting) pkg.mExtras; 5828 if (ps == null) { 5829 return; 5830 } 5831 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 5832 HashSet<String> origPermissions = gp.grantedPermissions; 5833 boolean changedPermission = false; 5834 5835 if (replace) { 5836 ps.permissionsFixed = false; 5837 if (gp == ps) { 5838 origPermissions = new HashSet<String>(gp.grantedPermissions); 5839 gp.grantedPermissions.clear(); 5840 gp.gids = mGlobalGids; 5841 } 5842 } 5843 5844 if (gp.gids == null) { 5845 gp.gids = mGlobalGids; 5846 } 5847 5848 final int N = pkg.requestedPermissions.size(); 5849 for (int i=0; i<N; i++) { 5850 final String name = pkg.requestedPermissions.get(i); 5851 final boolean required = pkg.requestedPermissionsRequired.get(i); 5852 final BasePermission bp = mSettings.mPermissions.get(name); 5853 if (DEBUG_INSTALL) { 5854 if (gp != ps) { 5855 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 5856 } 5857 } 5858 5859 if (bp == null || bp.packageSetting == null) { 5860 Slog.w(TAG, "Unknown permission " + name 5861 + " in package " + pkg.packageName); 5862 continue; 5863 } 5864 5865 final String perm = bp.name; 5866 boolean allowed; 5867 boolean allowedSig = false; 5868 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 5869 if (level == PermissionInfo.PROTECTION_NORMAL 5870 || level == PermissionInfo.PROTECTION_DANGEROUS) { 5871 // We grant a normal or dangerous permission if any of the following 5872 // are true: 5873 // 1) The permission is required 5874 // 2) The permission is optional, but was granted in the past 5875 // 3) The permission is optional, but was requested by an 5876 // app in /system (not /data) 5877 // 5878 // Otherwise, reject the permission. 5879 allowed = (required || origPermissions.contains(perm) 5880 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 5881 } else if (bp.packageSetting == null) { 5882 // This permission is invalid; skip it. 5883 allowed = false; 5884 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 5885 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 5886 if (allowed) { 5887 allowedSig = true; 5888 } 5889 } else { 5890 allowed = false; 5891 } 5892 if (DEBUG_INSTALL) { 5893 if (gp != ps) { 5894 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 5895 } 5896 } 5897 if (allowed) { 5898 if (!isSystemApp(ps) && ps.permissionsFixed) { 5899 // If this is an existing, non-system package, then 5900 // we can't add any new permissions to it. 5901 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 5902 // Except... if this is a permission that was added 5903 // to the platform (note: need to only do this when 5904 // updating the platform). 5905 allowed = isNewPlatformPermissionForPackage(perm, pkg); 5906 } 5907 } 5908 if (allowed) { 5909 if (!gp.grantedPermissions.contains(perm)) { 5910 changedPermission = true; 5911 gp.grantedPermissions.add(perm); 5912 gp.gids = appendInts(gp.gids, bp.gids); 5913 } else if (!ps.haveGids) { 5914 gp.gids = appendInts(gp.gids, bp.gids); 5915 } 5916 } else { 5917 Slog.w(TAG, "Not granting permission " + perm 5918 + " to package " + pkg.packageName 5919 + " because it was previously installed without"); 5920 } 5921 } else { 5922 if (gp.grantedPermissions.remove(perm)) { 5923 changedPermission = true; 5924 gp.gids = removeInts(gp.gids, bp.gids); 5925 Slog.i(TAG, "Un-granting permission " + perm 5926 + " from package " + pkg.packageName 5927 + " (protectionLevel=" + bp.protectionLevel 5928 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 5929 + ")"); 5930 } else { 5931 Slog.w(TAG, "Not granting permission " + perm 5932 + " to package " + pkg.packageName 5933 + " (protectionLevel=" + bp.protectionLevel 5934 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 5935 + ")"); 5936 } 5937 } 5938 } 5939 5940 if ((changedPermission || replace) && !ps.permissionsFixed && 5941 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 5942 // This is the first that we have heard about this package, so the 5943 // permissions we have now selected are fixed until explicitly 5944 // changed. 5945 ps.permissionsFixed = true; 5946 } 5947 ps.haveGids = true; 5948 } 5949 5950 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 5951 boolean allowed = false; 5952 final int NP = PackageParser.NEW_PERMISSIONS.length; 5953 for (int ip=0; ip<NP; ip++) { 5954 final PackageParser.NewPermissionInfo npi 5955 = PackageParser.NEW_PERMISSIONS[ip]; 5956 if (npi.name.equals(perm) 5957 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 5958 allowed = true; 5959 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 5960 + pkg.packageName); 5961 break; 5962 } 5963 } 5964 return allowed; 5965 } 5966 5967 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 5968 BasePermission bp, HashSet<String> origPermissions) { 5969 boolean allowed; 5970 allowed = (compareSignatures( 5971 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 5972 == PackageManager.SIGNATURE_MATCH) 5973 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 5974 == PackageManager.SIGNATURE_MATCH); 5975 if (!allowed && (bp.protectionLevel 5976 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 5977 if (isSystemApp(pkg)) { 5978 // For updated system applications, a system permission 5979 // is granted only if it had been defined by the original application. 5980 if (isUpdatedSystemApp(pkg)) { 5981 final PackageSetting sysPs = mSettings 5982 .getDisabledSystemPkgLPr(pkg.packageName); 5983 final GrantedPermissions origGp = sysPs.sharedUser != null 5984 ? sysPs.sharedUser : sysPs; 5985 5986 if (origGp.grantedPermissions.contains(perm)) { 5987 // If the original was granted this permission, we take 5988 // that grant decision as read and propagate it to the 5989 // update. 5990 allowed = true; 5991 } else { 5992 // The system apk may have been updated with an older 5993 // version of the one on the data partition, but which 5994 // granted a new system permission that it didn't have 5995 // before. In this case we do want to allow the app to 5996 // now get the new permission if the ancestral apk is 5997 // privileged to get it. 5998 if (sysPs.pkg != null && sysPs.isPrivileged()) { 5999 for (int j=0; 6000 j<sysPs.pkg.requestedPermissions.size(); j++) { 6001 if (perm.equals( 6002 sysPs.pkg.requestedPermissions.get(j))) { 6003 allowed = true; 6004 break; 6005 } 6006 } 6007 } 6008 } 6009 } else { 6010 allowed = isPrivilegedApp(pkg); 6011 } 6012 } 6013 } 6014 if (!allowed && (bp.protectionLevel 6015 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6016 // For development permissions, a development permission 6017 // is granted only if it was already granted. 6018 allowed = origPermissions.contains(perm); 6019 } 6020 return allowed; 6021 } 6022 6023 final class ActivityIntentResolver 6024 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6025 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6026 boolean defaultOnly, int userId) { 6027 if (!sUserManager.exists(userId)) return null; 6028 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6029 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6030 } 6031 6032 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6033 int userId) { 6034 if (!sUserManager.exists(userId)) return null; 6035 mFlags = flags; 6036 return super.queryIntent(intent, resolvedType, 6037 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6038 } 6039 6040 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6041 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6042 if (!sUserManager.exists(userId)) return null; 6043 if (packageActivities == null) { 6044 return null; 6045 } 6046 mFlags = flags; 6047 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6048 final int N = packageActivities.size(); 6049 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6050 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6051 6052 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6053 for (int i = 0; i < N; ++i) { 6054 intentFilters = packageActivities.get(i).intents; 6055 if (intentFilters != null && intentFilters.size() > 0) { 6056 PackageParser.ActivityIntentInfo[] array = 6057 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6058 intentFilters.toArray(array); 6059 listCut.add(array); 6060 } 6061 } 6062 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6063 } 6064 6065 public final void addActivity(PackageParser.Activity a, String type) { 6066 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6067 mActivities.put(a.getComponentName(), a); 6068 if (DEBUG_SHOW_INFO) 6069 Log.v( 6070 TAG, " " + type + " " + 6071 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6072 if (DEBUG_SHOW_INFO) 6073 Log.v(TAG, " Class=" + a.info.name); 6074 final int NI = a.intents.size(); 6075 for (int j=0; j<NI; j++) { 6076 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6077 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6078 intent.setPriority(0); 6079 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6080 + a.className + " with priority > 0, forcing to 0"); 6081 } 6082 if (DEBUG_SHOW_INFO) { 6083 Log.v(TAG, " IntentFilter:"); 6084 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6085 } 6086 if (!intent.debugCheck()) { 6087 Log.w(TAG, "==> For Activity " + a.info.name); 6088 } 6089 addFilter(intent); 6090 } 6091 } 6092 6093 public final void removeActivity(PackageParser.Activity a, String type) { 6094 mActivities.remove(a.getComponentName()); 6095 if (DEBUG_SHOW_INFO) { 6096 Log.v(TAG, " " + type + " " 6097 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6098 : a.info.name) + ":"); 6099 Log.v(TAG, " Class=" + a.info.name); 6100 } 6101 final int NI = a.intents.size(); 6102 for (int j=0; j<NI; j++) { 6103 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6104 if (DEBUG_SHOW_INFO) { 6105 Log.v(TAG, " IntentFilter:"); 6106 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6107 } 6108 removeFilter(intent); 6109 } 6110 } 6111 6112 @Override 6113 protected boolean allowFilterResult( 6114 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6115 ActivityInfo filterAi = filter.activity.info; 6116 for (int i=dest.size()-1; i>=0; i--) { 6117 ActivityInfo destAi = dest.get(i).activityInfo; 6118 if (destAi.name == filterAi.name 6119 && destAi.packageName == filterAi.packageName) { 6120 return false; 6121 } 6122 } 6123 return true; 6124 } 6125 6126 @Override 6127 protected ActivityIntentInfo[] newArray(int size) { 6128 return new ActivityIntentInfo[size]; 6129 } 6130 6131 @Override 6132 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6133 if (!sUserManager.exists(userId)) return true; 6134 PackageParser.Package p = filter.activity.owner; 6135 if (p != null) { 6136 PackageSetting ps = (PackageSetting)p.mExtras; 6137 if (ps != null) { 6138 // System apps are never considered stopped for purposes of 6139 // filtering, because there may be no way for the user to 6140 // actually re-launch them. 6141 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6142 && ps.getStopped(userId); 6143 } 6144 } 6145 return false; 6146 } 6147 6148 @Override 6149 protected boolean isPackageForFilter(String packageName, 6150 PackageParser.ActivityIntentInfo info) { 6151 return packageName.equals(info.activity.owner.packageName); 6152 } 6153 6154 @Override 6155 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6156 int match, int userId) { 6157 if (!sUserManager.exists(userId)) return null; 6158 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6159 return null; 6160 } 6161 final PackageParser.Activity activity = info.activity; 6162 if (mSafeMode && (activity.info.applicationInfo.flags 6163 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6164 return null; 6165 } 6166 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6167 if (ps == null) { 6168 return null; 6169 } 6170 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6171 ps.readUserState(userId), userId); 6172 if (ai == null) { 6173 return null; 6174 } 6175 final ResolveInfo res = new ResolveInfo(); 6176 res.activityInfo = ai; 6177 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6178 res.filter = info; 6179 } 6180 res.priority = info.getPriority(); 6181 res.preferredOrder = activity.owner.mPreferredOrder; 6182 //System.out.println("Result: " + res.activityInfo.className + 6183 // " = " + res.priority); 6184 res.match = match; 6185 res.isDefault = info.hasDefault; 6186 res.labelRes = info.labelRes; 6187 res.nonLocalizedLabel = info.nonLocalizedLabel; 6188 res.icon = info.icon; 6189 res.system = isSystemApp(res.activityInfo.applicationInfo); 6190 return res; 6191 } 6192 6193 @Override 6194 protected void sortResults(List<ResolveInfo> results) { 6195 Collections.sort(results, mResolvePrioritySorter); 6196 } 6197 6198 @Override 6199 protected void dumpFilter(PrintWriter out, String prefix, 6200 PackageParser.ActivityIntentInfo filter) { 6201 out.print(prefix); out.print( 6202 Integer.toHexString(System.identityHashCode(filter.activity))); 6203 out.print(' '); 6204 filter.activity.printComponentShortName(out); 6205 out.print(" filter "); 6206 out.println(Integer.toHexString(System.identityHashCode(filter))); 6207 } 6208 6209// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6210// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6211// final List<ResolveInfo> retList = Lists.newArrayList(); 6212// while (i.hasNext()) { 6213// final ResolveInfo resolveInfo = i.next(); 6214// if (isEnabledLP(resolveInfo.activityInfo)) { 6215// retList.add(resolveInfo); 6216// } 6217// } 6218// return retList; 6219// } 6220 6221 // Keys are String (activity class name), values are Activity. 6222 private final HashMap<ComponentName, PackageParser.Activity> mActivities 6223 = new HashMap<ComponentName, PackageParser.Activity>(); 6224 private int mFlags; 6225 } 6226 6227 private final class ServiceIntentResolver 6228 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 6229 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6230 boolean defaultOnly, int userId) { 6231 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6232 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6233 } 6234 6235 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6236 int userId) { 6237 if (!sUserManager.exists(userId)) return null; 6238 mFlags = flags; 6239 return super.queryIntent(intent, resolvedType, 6240 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6241 } 6242 6243 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6244 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 6245 if (!sUserManager.exists(userId)) return null; 6246 if (packageServices == null) { 6247 return null; 6248 } 6249 mFlags = flags; 6250 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6251 final int N = packageServices.size(); 6252 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 6253 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 6254 6255 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 6256 for (int i = 0; i < N; ++i) { 6257 intentFilters = packageServices.get(i).intents; 6258 if (intentFilters != null && intentFilters.size() > 0) { 6259 PackageParser.ServiceIntentInfo[] array = 6260 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 6261 intentFilters.toArray(array); 6262 listCut.add(array); 6263 } 6264 } 6265 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6266 } 6267 6268 public final void addService(PackageParser.Service s) { 6269 mServices.put(s.getComponentName(), s); 6270 if (DEBUG_SHOW_INFO) { 6271 Log.v(TAG, " " 6272 + (s.info.nonLocalizedLabel != null 6273 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6274 Log.v(TAG, " Class=" + s.info.name); 6275 } 6276 final int NI = s.intents.size(); 6277 int j; 6278 for (j=0; j<NI; j++) { 6279 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6280 if (DEBUG_SHOW_INFO) { 6281 Log.v(TAG, " IntentFilter:"); 6282 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6283 } 6284 if (!intent.debugCheck()) { 6285 Log.w(TAG, "==> For Service " + s.info.name); 6286 } 6287 addFilter(intent); 6288 } 6289 } 6290 6291 public final void removeService(PackageParser.Service s) { 6292 mServices.remove(s.getComponentName()); 6293 if (DEBUG_SHOW_INFO) { 6294 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 6295 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6296 Log.v(TAG, " Class=" + s.info.name); 6297 } 6298 final int NI = s.intents.size(); 6299 int j; 6300 for (j=0; j<NI; j++) { 6301 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6302 if (DEBUG_SHOW_INFO) { 6303 Log.v(TAG, " IntentFilter:"); 6304 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6305 } 6306 removeFilter(intent); 6307 } 6308 } 6309 6310 @Override 6311 protected boolean allowFilterResult( 6312 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 6313 ServiceInfo filterSi = filter.service.info; 6314 for (int i=dest.size()-1; i>=0; i--) { 6315 ServiceInfo destAi = dest.get(i).serviceInfo; 6316 if (destAi.name == filterSi.name 6317 && destAi.packageName == filterSi.packageName) { 6318 return false; 6319 } 6320 } 6321 return true; 6322 } 6323 6324 @Override 6325 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 6326 return new PackageParser.ServiceIntentInfo[size]; 6327 } 6328 6329 @Override 6330 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 6331 if (!sUserManager.exists(userId)) return true; 6332 PackageParser.Package p = filter.service.owner; 6333 if (p != null) { 6334 PackageSetting ps = (PackageSetting)p.mExtras; 6335 if (ps != null) { 6336 // System apps are never considered stopped for purposes of 6337 // filtering, because there may be no way for the user to 6338 // actually re-launch them. 6339 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 6340 && ps.getStopped(userId); 6341 } 6342 } 6343 return false; 6344 } 6345 6346 @Override 6347 protected boolean isPackageForFilter(String packageName, 6348 PackageParser.ServiceIntentInfo info) { 6349 return packageName.equals(info.service.owner.packageName); 6350 } 6351 6352 @Override 6353 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 6354 int match, int userId) { 6355 if (!sUserManager.exists(userId)) return null; 6356 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 6357 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 6358 return null; 6359 } 6360 final PackageParser.Service service = info.service; 6361 if (mSafeMode && (service.info.applicationInfo.flags 6362 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6363 return null; 6364 } 6365 PackageSetting ps = (PackageSetting) service.owner.mExtras; 6366 if (ps == null) { 6367 return null; 6368 } 6369 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 6370 ps.readUserState(userId), userId); 6371 if (si == null) { 6372 return null; 6373 } 6374 final ResolveInfo res = new ResolveInfo(); 6375 res.serviceInfo = si; 6376 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6377 res.filter = filter; 6378 } 6379 res.priority = info.getPriority(); 6380 res.preferredOrder = service.owner.mPreferredOrder; 6381 //System.out.println("Result: " + res.activityInfo.className + 6382 // " = " + res.priority); 6383 res.match = match; 6384 res.isDefault = info.hasDefault; 6385 res.labelRes = info.labelRes; 6386 res.nonLocalizedLabel = info.nonLocalizedLabel; 6387 res.icon = info.icon; 6388 res.system = isSystemApp(res.serviceInfo.applicationInfo); 6389 return res; 6390 } 6391 6392 @Override 6393 protected void sortResults(List<ResolveInfo> results) { 6394 Collections.sort(results, mResolvePrioritySorter); 6395 } 6396 6397 @Override 6398 protected void dumpFilter(PrintWriter out, String prefix, 6399 PackageParser.ServiceIntentInfo filter) { 6400 out.print(prefix); out.print( 6401 Integer.toHexString(System.identityHashCode(filter.service))); 6402 out.print(' '); 6403 filter.service.printComponentShortName(out); 6404 out.print(" filter "); 6405 out.println(Integer.toHexString(System.identityHashCode(filter))); 6406 } 6407 6408// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6409// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6410// final List<ResolveInfo> retList = Lists.newArrayList(); 6411// while (i.hasNext()) { 6412// final ResolveInfo resolveInfo = (ResolveInfo) i; 6413// if (isEnabledLP(resolveInfo.serviceInfo)) { 6414// retList.add(resolveInfo); 6415// } 6416// } 6417// return retList; 6418// } 6419 6420 // Keys are String (activity class name), values are Activity. 6421 private final HashMap<ComponentName, PackageParser.Service> mServices 6422 = new HashMap<ComponentName, PackageParser.Service>(); 6423 private int mFlags; 6424 }; 6425 6426 private final class ProviderIntentResolver 6427 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 6428 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6429 boolean defaultOnly, int userId) { 6430 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6431 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6432 } 6433 6434 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6435 int userId) { 6436 if (!sUserManager.exists(userId)) 6437 return null; 6438 mFlags = flags; 6439 return super.queryIntent(intent, resolvedType, 6440 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6441 } 6442 6443 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6444 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 6445 if (!sUserManager.exists(userId)) 6446 return null; 6447 if (packageProviders == null) { 6448 return null; 6449 } 6450 mFlags = flags; 6451 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 6452 final int N = packageProviders.size(); 6453 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 6454 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 6455 6456 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 6457 for (int i = 0; i < N; ++i) { 6458 intentFilters = packageProviders.get(i).intents; 6459 if (intentFilters != null && intentFilters.size() > 0) { 6460 PackageParser.ProviderIntentInfo[] array = 6461 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 6462 intentFilters.toArray(array); 6463 listCut.add(array); 6464 } 6465 } 6466 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6467 } 6468 6469 public final void addProvider(PackageParser.Provider p) { 6470 if (mProviders.containsKey(p.getComponentName())) { 6471 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 6472 return; 6473 } 6474 6475 mProviders.put(p.getComponentName(), p); 6476 if (DEBUG_SHOW_INFO) { 6477 Log.v(TAG, " " 6478 + (p.info.nonLocalizedLabel != null 6479 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 6480 Log.v(TAG, " Class=" + p.info.name); 6481 } 6482 final int NI = p.intents.size(); 6483 int j; 6484 for (j = 0; j < NI; j++) { 6485 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 6486 if (DEBUG_SHOW_INFO) { 6487 Log.v(TAG, " IntentFilter:"); 6488 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6489 } 6490 if (!intent.debugCheck()) { 6491 Log.w(TAG, "==> For Provider " + p.info.name); 6492 } 6493 addFilter(intent); 6494 } 6495 } 6496 6497 public final void removeProvider(PackageParser.Provider p) { 6498 mProviders.remove(p.getComponentName()); 6499 if (DEBUG_SHOW_INFO) { 6500 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 6501 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 6502 Log.v(TAG, " Class=" + p.info.name); 6503 } 6504 final int NI = p.intents.size(); 6505 int j; 6506 for (j = 0; j < NI; j++) { 6507 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 6508 if (DEBUG_SHOW_INFO) { 6509 Log.v(TAG, " IntentFilter:"); 6510 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6511 } 6512 removeFilter(intent); 6513 } 6514 } 6515 6516 @Override 6517 protected boolean allowFilterResult( 6518 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 6519 ProviderInfo filterPi = filter.provider.info; 6520 for (int i = dest.size() - 1; i >= 0; i--) { 6521 ProviderInfo destPi = dest.get(i).providerInfo; 6522 if (destPi.name == filterPi.name 6523 && destPi.packageName == filterPi.packageName) { 6524 return false; 6525 } 6526 } 6527 return true; 6528 } 6529 6530 @Override 6531 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 6532 return new PackageParser.ProviderIntentInfo[size]; 6533 } 6534 6535 @Override 6536 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 6537 if (!sUserManager.exists(userId)) 6538 return true; 6539 PackageParser.Package p = filter.provider.owner; 6540 if (p != null) { 6541 PackageSetting ps = (PackageSetting) p.mExtras; 6542 if (ps != null) { 6543 // System apps are never considered stopped for purposes of 6544 // filtering, because there may be no way for the user to 6545 // actually re-launch them. 6546 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 6547 && ps.getStopped(userId); 6548 } 6549 } 6550 return false; 6551 } 6552 6553 @Override 6554 protected boolean isPackageForFilter(String packageName, 6555 PackageParser.ProviderIntentInfo info) { 6556 return packageName.equals(info.provider.owner.packageName); 6557 } 6558 6559 @Override 6560 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 6561 int match, int userId) { 6562 if (!sUserManager.exists(userId)) 6563 return null; 6564 final PackageParser.ProviderIntentInfo info = filter; 6565 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 6566 return null; 6567 } 6568 final PackageParser.Provider provider = info.provider; 6569 if (mSafeMode && (provider.info.applicationInfo.flags 6570 & ApplicationInfo.FLAG_SYSTEM) == 0) { 6571 return null; 6572 } 6573 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 6574 if (ps == null) { 6575 return null; 6576 } 6577 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 6578 ps.readUserState(userId), userId); 6579 if (pi == null) { 6580 return null; 6581 } 6582 final ResolveInfo res = new ResolveInfo(); 6583 res.providerInfo = pi; 6584 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 6585 res.filter = filter; 6586 } 6587 res.priority = info.getPriority(); 6588 res.preferredOrder = provider.owner.mPreferredOrder; 6589 res.match = match; 6590 res.isDefault = info.hasDefault; 6591 res.labelRes = info.labelRes; 6592 res.nonLocalizedLabel = info.nonLocalizedLabel; 6593 res.icon = info.icon; 6594 res.system = isSystemApp(res.providerInfo.applicationInfo); 6595 return res; 6596 } 6597 6598 @Override 6599 protected void sortResults(List<ResolveInfo> results) { 6600 Collections.sort(results, mResolvePrioritySorter); 6601 } 6602 6603 @Override 6604 protected void dumpFilter(PrintWriter out, String prefix, 6605 PackageParser.ProviderIntentInfo filter) { 6606 out.print(prefix); 6607 out.print( 6608 Integer.toHexString(System.identityHashCode(filter.provider))); 6609 out.print(' '); 6610 filter.provider.printComponentShortName(out); 6611 out.print(" filter "); 6612 out.println(Integer.toHexString(System.identityHashCode(filter))); 6613 } 6614 6615 private final HashMap<ComponentName, PackageParser.Provider> mProviders 6616 = new HashMap<ComponentName, PackageParser.Provider>(); 6617 private int mFlags; 6618 }; 6619 6620 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 6621 new Comparator<ResolveInfo>() { 6622 public int compare(ResolveInfo r1, ResolveInfo r2) { 6623 int v1 = r1.priority; 6624 int v2 = r2.priority; 6625 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 6626 if (v1 != v2) { 6627 return (v1 > v2) ? -1 : 1; 6628 } 6629 v1 = r1.preferredOrder; 6630 v2 = r2.preferredOrder; 6631 if (v1 != v2) { 6632 return (v1 > v2) ? -1 : 1; 6633 } 6634 if (r1.isDefault != r2.isDefault) { 6635 return r1.isDefault ? -1 : 1; 6636 } 6637 v1 = r1.match; 6638 v2 = r2.match; 6639 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 6640 if (v1 != v2) { 6641 return (v1 > v2) ? -1 : 1; 6642 } 6643 if (r1.system != r2.system) { 6644 return r1.system ? -1 : 1; 6645 } 6646 return 0; 6647 } 6648 }; 6649 6650 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 6651 new Comparator<ProviderInfo>() { 6652 public int compare(ProviderInfo p1, ProviderInfo p2) { 6653 final int v1 = p1.initOrder; 6654 final int v2 = p2.initOrder; 6655 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 6656 } 6657 }; 6658 6659 static final void sendPackageBroadcast(String action, String pkg, 6660 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 6661 int[] userIds) { 6662 IActivityManager am = ActivityManagerNative.getDefault(); 6663 if (am != null) { 6664 try { 6665 if (userIds == null) { 6666 userIds = am.getRunningUserIds(); 6667 } 6668 for (int id : userIds) { 6669 final Intent intent = new Intent(action, 6670 pkg != null ? Uri.fromParts("package", pkg, null) : null); 6671 if (extras != null) { 6672 intent.putExtras(extras); 6673 } 6674 if (targetPkg != null) { 6675 intent.setPackage(targetPkg); 6676 } 6677 // Modify the UID when posting to other users 6678 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 6679 if (uid > 0 && UserHandle.getUserId(uid) != id) { 6680 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 6681 intent.putExtra(Intent.EXTRA_UID, uid); 6682 } 6683 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 6684 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 6685 if (DEBUG_BROADCASTS) { 6686 RuntimeException here = new RuntimeException("here"); 6687 here.fillInStackTrace(); 6688 Slog.d(TAG, "Sending to user " + id + ": " 6689 + intent.toShortString(false, true, false, false) 6690 + " " + intent.getExtras(), here); 6691 } 6692 am.broadcastIntent(null, intent, null, finishedReceiver, 6693 0, null, null, null, android.app.AppOpsManager.OP_NONE, 6694 finishedReceiver != null, false, id); 6695 } 6696 } catch (RemoteException ex) { 6697 } 6698 } 6699 } 6700 6701 /** 6702 * Check if the external storage media is available. This is true if there 6703 * is a mounted external storage medium or if the external storage is 6704 * emulated. 6705 */ 6706 private boolean isExternalMediaAvailable() { 6707 return mMediaMounted || Environment.isExternalStorageEmulated(); 6708 } 6709 6710 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 6711 // writer 6712 synchronized (mPackages) { 6713 if (!isExternalMediaAvailable()) { 6714 // If the external storage is no longer mounted at this point, 6715 // the caller may not have been able to delete all of this 6716 // packages files and can not delete any more. Bail. 6717 return null; 6718 } 6719 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 6720 if (lastPackage != null) { 6721 pkgs.remove(lastPackage); 6722 } 6723 if (pkgs.size() > 0) { 6724 return pkgs.get(0); 6725 } 6726 } 6727 return null; 6728 } 6729 6730 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 6731 if (false) { 6732 RuntimeException here = new RuntimeException("here"); 6733 here.fillInStackTrace(); 6734 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 6735 + " andCode=" + andCode, here); 6736 } 6737 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 6738 userId, andCode ? 1 : 0, packageName)); 6739 } 6740 6741 void startCleaningPackages() { 6742 // reader 6743 synchronized (mPackages) { 6744 if (!isExternalMediaAvailable()) { 6745 return; 6746 } 6747 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 6748 return; 6749 } 6750 } 6751 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 6752 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 6753 IActivityManager am = ActivityManagerNative.getDefault(); 6754 if (am != null) { 6755 try { 6756 am.startService(null, intent, null, UserHandle.USER_OWNER); 6757 } catch (RemoteException e) { 6758 } 6759 } 6760 } 6761 6762 private final class AppDirObserver extends FileObserver { 6763 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 6764 super(path, mask); 6765 mRootDir = path; 6766 mIsRom = isrom; 6767 mIsPrivileged = isPrivileged; 6768 } 6769 6770 public void onEvent(int event, String path) { 6771 String removedPackage = null; 6772 int removedAppId = -1; 6773 int[] removedUsers = null; 6774 String addedPackage = null; 6775 int addedAppId = -1; 6776 int[] addedUsers = null; 6777 6778 // TODO post a message to the handler to obtain serial ordering 6779 synchronized (mInstallLock) { 6780 String fullPathStr = null; 6781 File fullPath = null; 6782 if (path != null) { 6783 fullPath = new File(mRootDir, path); 6784 fullPathStr = fullPath.getPath(); 6785 } 6786 6787 if (DEBUG_APP_DIR_OBSERVER) 6788 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 6789 6790 if (!isPackageFilename(path)) { 6791 if (DEBUG_APP_DIR_OBSERVER) 6792 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 6793 return; 6794 } 6795 6796 // Ignore packages that are being installed or 6797 // have just been installed. 6798 if (ignoreCodePath(fullPathStr)) { 6799 return; 6800 } 6801 PackageParser.Package p = null; 6802 PackageSetting ps = null; 6803 // reader 6804 synchronized (mPackages) { 6805 p = mAppDirs.get(fullPathStr); 6806 if (p != null) { 6807 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 6808 if (ps != null) { 6809 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 6810 } else { 6811 removedUsers = sUserManager.getUserIds(); 6812 } 6813 } 6814 addedUsers = sUserManager.getUserIds(); 6815 } 6816 if ((event&REMOVE_EVENTS) != 0) { 6817 if (ps != null) { 6818 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 6819 removePackageLI(ps, true); 6820 removedPackage = ps.name; 6821 removedAppId = ps.appId; 6822 } 6823 } 6824 6825 if ((event&ADD_EVENTS) != 0) { 6826 if (p == null) { 6827 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 6828 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 6829 if (mIsRom) { 6830 flags |= PackageParser.PARSE_IS_SYSTEM 6831 | PackageParser.PARSE_IS_SYSTEM_DIR; 6832 if (mIsPrivileged) { 6833 flags |= PackageParser.PARSE_IS_PRIVILEGED; 6834 } 6835 } 6836 p = scanPackageLI(fullPath, flags, 6837 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 6838 System.currentTimeMillis(), UserHandle.ALL); 6839 if (p != null) { 6840 /* 6841 * TODO this seems dangerous as the package may have 6842 * changed since we last acquired the mPackages 6843 * lock. 6844 */ 6845 // writer 6846 synchronized (mPackages) { 6847 updatePermissionsLPw(p.packageName, p, 6848 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 6849 } 6850 addedPackage = p.applicationInfo.packageName; 6851 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 6852 } 6853 } 6854 } 6855 6856 // reader 6857 synchronized (mPackages) { 6858 mSettings.writeLPr(); 6859 } 6860 } 6861 6862 if (removedPackage != null) { 6863 Bundle extras = new Bundle(1); 6864 extras.putInt(Intent.EXTRA_UID, removedAppId); 6865 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 6866 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 6867 extras, null, null, removedUsers); 6868 } 6869 if (addedPackage != null) { 6870 Bundle extras = new Bundle(1); 6871 extras.putInt(Intent.EXTRA_UID, addedAppId); 6872 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 6873 extras, null, null, addedUsers); 6874 } 6875 } 6876 6877 private final String mRootDir; 6878 private final boolean mIsRom; 6879 private final boolean mIsPrivileged; 6880 } 6881 6882 /* 6883 * The old-style observer methods all just trampoline to the newer signature with 6884 * expanded install observer API. The older API continues to work but does not 6885 * supply the additional details of the Observer2 API. 6886 */ 6887 6888 /* Called when a downloaded package installation has been confirmed by the user */ 6889 public void installPackage( 6890 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 6891 installPackageEtc(packageURI, observer, null, flags, null); 6892 } 6893 6894 /* Called when a downloaded package installation has been confirmed by the user */ 6895 public void installPackage( 6896 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 6897 final String installerPackageName) { 6898 installPackageWithVerificationEtc(packageURI, observer, null, flags, 6899 installerPackageName, null, null, null); 6900 } 6901 6902 @Override 6903 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 6904 int flags, String installerPackageName, Uri verificationURI, 6905 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 6906 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 6907 VerificationParams.NO_UID, manifestDigest); 6908 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 6909 installerPackageName, verificationParams, encryptionParams); 6910 } 6911 6912 public void installPackageWithVerificationAndEncryption(Uri packageURI, 6913 IPackageInstallObserver observer, int flags, String installerPackageName, 6914 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 6915 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 6916 installerPackageName, verificationParams, encryptionParams); 6917 } 6918 6919 /* 6920 * And here are the "live" versions that take both observer arguments 6921 */ 6922 public void installPackageEtc( 6923 final Uri packageURI, final IPackageInstallObserver observer, 6924 IPackageInstallObserver2 observer2, final int flags) { 6925 installPackageEtc(packageURI, observer, observer2, flags, null); 6926 } 6927 6928 public void installPackageEtc( 6929 final Uri packageURI, final IPackageInstallObserver observer, 6930 final IPackageInstallObserver2 observer2, final int flags, 6931 final String installerPackageName) { 6932 installPackageWithVerificationEtc(packageURI, observer, observer2, flags, 6933 installerPackageName, null, null, null); 6934 } 6935 6936 @Override 6937 public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer, 6938 IPackageInstallObserver2 observer2, 6939 int flags, String installerPackageName, Uri verificationURI, 6940 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 6941 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 6942 VerificationParams.NO_UID, manifestDigest); 6943 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags, 6944 installerPackageName, verificationParams, encryptionParams); 6945 } 6946 6947 /* 6948 * All of the installPackage...*() methods redirect to this one for the master implementation 6949 */ 6950 public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI, 6951 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 6952 int flags, String installerPackageName, 6953 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 6954 if (observer == null && observer2 == null) { 6955 throw new IllegalArgumentException("No install observer supplied"); 6956 } 6957 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 6958 null); 6959 6960 final int uid = Binder.getCallingUid(); 6961 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 6962 try { 6963 if (observer != null) { 6964 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 6965 } 6966 if (observer2 != null) { 6967 observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED); 6968 } 6969 } catch (RemoteException re) { 6970 } 6971 return; 6972 } 6973 6974 UserHandle user; 6975 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 6976 user = UserHandle.ALL; 6977 } else { 6978 user = new UserHandle(UserHandle.getUserId(uid)); 6979 } 6980 6981 final int filteredFlags; 6982 6983 if (uid == Process.SHELL_UID || uid == 0) { 6984 if (DEBUG_INSTALL) { 6985 Slog.v(TAG, "Install from ADB"); 6986 } 6987 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 6988 } else { 6989 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 6990 } 6991 6992 verificationParams.setInstallerUid(uid); 6993 6994 final Message msg = mHandler.obtainMessage(INIT_COPY); 6995 msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags, 6996 installerPackageName, verificationParams, encryptionParams, user); 6997 mHandler.sendMessage(msg); 6998 } 6999 7000 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7001 Bundle extras = new Bundle(1); 7002 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7003 7004 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7005 packageName, extras, null, null, new int[] {userId}); 7006 try { 7007 IActivityManager am = ActivityManagerNative.getDefault(); 7008 final boolean isSystem = 7009 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7010 if (isSystem && am.isUserRunning(userId, false)) { 7011 // The just-installed/enabled app is bundled on the system, so presumed 7012 // to be able to run automatically without needing an explicit launch. 7013 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7014 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7015 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7016 .setPackage(packageName); 7017 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7018 android.app.AppOpsManager.OP_NONE, false, false, userId); 7019 } 7020 } catch (RemoteException e) { 7021 // shouldn't happen 7022 Slog.w(TAG, "Unable to bootstrap installed package", e); 7023 } 7024 } 7025 7026 @Override 7027 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7028 int userId) { 7029 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7030 PackageSetting pkgSetting; 7031 final int uid = Binder.getCallingUid(); 7032 if (UserHandle.getUserId(uid) != userId) { 7033 mContext.enforceCallingOrSelfPermission( 7034 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7035 "setApplicationBlockedSetting for user " + userId); 7036 } 7037 7038 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7039 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7040 return false; 7041 } 7042 7043 long callingId = Binder.clearCallingIdentity(); 7044 try { 7045 boolean sendAdded = false; 7046 boolean sendRemoved = false; 7047 // writer 7048 synchronized (mPackages) { 7049 pkgSetting = mSettings.mPackages.get(packageName); 7050 if (pkgSetting == null) { 7051 return false; 7052 } 7053 if (pkgSetting.getBlocked(userId) != blocked) { 7054 pkgSetting.setBlocked(blocked, userId); 7055 mSettings.writePackageRestrictionsLPr(userId); 7056 if (blocked) { 7057 sendRemoved = true; 7058 } else { 7059 sendAdded = true; 7060 } 7061 } 7062 } 7063 if (sendAdded) { 7064 sendPackageAddedForUser(packageName, pkgSetting, userId); 7065 return true; 7066 } 7067 if (sendRemoved) { 7068 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7069 "blocking pkg"); 7070 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7071 } 7072 } finally { 7073 Binder.restoreCallingIdentity(callingId); 7074 } 7075 return false; 7076 } 7077 7078 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7079 int userId) { 7080 final PackageRemovedInfo info = new PackageRemovedInfo(); 7081 info.removedPackage = packageName; 7082 info.removedUsers = new int[] {userId}; 7083 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7084 info.sendBroadcast(false, false, false); 7085 } 7086 7087 /** 7088 * Returns true if application is not found or there was an error. Otherwise it returns 7089 * the blocked state of the package for the given user. 7090 */ 7091 @Override 7092 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7093 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7094 PackageSetting pkgSetting; 7095 final int uid = Binder.getCallingUid(); 7096 if (UserHandle.getUserId(uid) != userId) { 7097 mContext.enforceCallingPermission( 7098 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7099 "getApplicationBlocked for user " + userId); 7100 } 7101 long callingId = Binder.clearCallingIdentity(); 7102 try { 7103 // writer 7104 synchronized (mPackages) { 7105 pkgSetting = mSettings.mPackages.get(packageName); 7106 if (pkgSetting == null) { 7107 return true; 7108 } 7109 return pkgSetting.getBlocked(userId); 7110 } 7111 } finally { 7112 Binder.restoreCallingIdentity(callingId); 7113 } 7114 } 7115 7116 /** 7117 * @hide 7118 */ 7119 @Override 7120 public int installExistingPackageAsUser(String packageName, int userId) { 7121 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7122 null); 7123 PackageSetting pkgSetting; 7124 final int uid = Binder.getCallingUid(); 7125 if (UserHandle.getUserId(uid) != userId) { 7126 mContext.enforceCallingPermission( 7127 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7128 "installExistingPackage for user " + userId); 7129 } 7130 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7131 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7132 } 7133 7134 long callingId = Binder.clearCallingIdentity(); 7135 try { 7136 boolean sendAdded = false; 7137 Bundle extras = new Bundle(1); 7138 7139 // writer 7140 synchronized (mPackages) { 7141 pkgSetting = mSettings.mPackages.get(packageName); 7142 if (pkgSetting == null) { 7143 return PackageManager.INSTALL_FAILED_INVALID_URI; 7144 } 7145 if (!pkgSetting.getInstalled(userId)) { 7146 pkgSetting.setInstalled(true, userId); 7147 pkgSetting.setBlocked(false, userId); 7148 mSettings.writePackageRestrictionsLPr(userId); 7149 sendAdded = true; 7150 } 7151 } 7152 7153 if (sendAdded) { 7154 sendPackageAddedForUser(packageName, pkgSetting, userId); 7155 } 7156 } finally { 7157 Binder.restoreCallingIdentity(callingId); 7158 } 7159 7160 return PackageManager.INSTALL_SUCCEEDED; 7161 } 7162 7163 private boolean isUserRestricted(int userId, String restrictionKey) { 7164 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7165 if (restrictions.getBoolean(restrictionKey, false)) { 7166 Log.w(TAG, "User is restricted: " + restrictionKey); 7167 return true; 7168 } 7169 return false; 7170 } 7171 7172 @Override 7173 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7174 mContext.enforceCallingOrSelfPermission( 7175 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7176 "Only package verification agents can verify applications"); 7177 7178 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7179 final PackageVerificationResponse response = new PackageVerificationResponse( 7180 verificationCode, Binder.getCallingUid()); 7181 msg.arg1 = id; 7182 msg.obj = response; 7183 mHandler.sendMessage(msg); 7184 } 7185 7186 @Override 7187 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7188 long millisecondsToDelay) { 7189 mContext.enforceCallingOrSelfPermission( 7190 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7191 "Only package verification agents can extend verification timeouts"); 7192 7193 final PackageVerificationState state = mPendingVerification.get(id); 7194 final PackageVerificationResponse response = new PackageVerificationResponse( 7195 verificationCodeAtTimeout, Binder.getCallingUid()); 7196 7197 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7198 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7199 } 7200 if (millisecondsToDelay < 0) { 7201 millisecondsToDelay = 0; 7202 } 7203 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7204 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7205 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7206 } 7207 7208 if ((state != null) && !state.timeoutExtended()) { 7209 state.extendTimeout(); 7210 7211 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7212 msg.arg1 = id; 7213 msg.obj = response; 7214 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7215 } 7216 } 7217 7218 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7219 int verificationCode, UserHandle user) { 7220 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7221 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7222 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7223 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7224 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7225 7226 mContext.sendBroadcastAsUser(intent, user, 7227 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7228 } 7229 7230 private ComponentName matchComponentForVerifier(String packageName, 7231 List<ResolveInfo> receivers) { 7232 ActivityInfo targetReceiver = null; 7233 7234 final int NR = receivers.size(); 7235 for (int i = 0; i < NR; i++) { 7236 final ResolveInfo info = receivers.get(i); 7237 if (info.activityInfo == null) { 7238 continue; 7239 } 7240 7241 if (packageName.equals(info.activityInfo.packageName)) { 7242 targetReceiver = info.activityInfo; 7243 break; 7244 } 7245 } 7246 7247 if (targetReceiver == null) { 7248 return null; 7249 } 7250 7251 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 7252 } 7253 7254 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 7255 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 7256 if (pkgInfo.verifiers.length == 0) { 7257 return null; 7258 } 7259 7260 final int N = pkgInfo.verifiers.length; 7261 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 7262 for (int i = 0; i < N; i++) { 7263 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 7264 7265 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 7266 receivers); 7267 if (comp == null) { 7268 continue; 7269 } 7270 7271 final int verifierUid = getUidForVerifier(verifierInfo); 7272 if (verifierUid == -1) { 7273 continue; 7274 } 7275 7276 if (DEBUG_VERIFY) { 7277 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 7278 + " with the correct signature"); 7279 } 7280 sufficientVerifiers.add(comp); 7281 verificationState.addSufficientVerifier(verifierUid); 7282 } 7283 7284 return sufficientVerifiers; 7285 } 7286 7287 private int getUidForVerifier(VerifierInfo verifierInfo) { 7288 synchronized (mPackages) { 7289 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 7290 if (pkg == null) { 7291 return -1; 7292 } else if (pkg.mSignatures.length != 1) { 7293 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7294 + " has more than one signature; ignoring"); 7295 return -1; 7296 } 7297 7298 /* 7299 * If the public key of the package's signature does not match 7300 * our expected public key, then this is a different package and 7301 * we should skip. 7302 */ 7303 7304 final byte[] expectedPublicKey; 7305 try { 7306 final Signature verifierSig = pkg.mSignatures[0]; 7307 final PublicKey publicKey = verifierSig.getPublicKey(); 7308 expectedPublicKey = publicKey.getEncoded(); 7309 } catch (CertificateException e) { 7310 return -1; 7311 } 7312 7313 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 7314 7315 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 7316 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7317 + " does not have the expected public key; ignoring"); 7318 return -1; 7319 } 7320 7321 return pkg.applicationInfo.uid; 7322 } 7323 } 7324 7325 public void finishPackageInstall(int token) { 7326 enforceSystemOrRoot("Only the system is allowed to finish installs"); 7327 7328 if (DEBUG_INSTALL) { 7329 Slog.v(TAG, "BM finishing package install for " + token); 7330 } 7331 7332 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 7333 mHandler.sendMessage(msg); 7334 } 7335 7336 /** 7337 * Get the verification agent timeout. 7338 * 7339 * @return verification timeout in milliseconds 7340 */ 7341 private long getVerificationTimeout() { 7342 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 7343 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 7344 DEFAULT_VERIFICATION_TIMEOUT); 7345 } 7346 7347 /** 7348 * Get the default verification agent response code. 7349 * 7350 * @return default verification response code 7351 */ 7352 private int getDefaultVerificationResponse() { 7353 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7354 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 7355 DEFAULT_VERIFICATION_RESPONSE); 7356 } 7357 7358 /** 7359 * Check whether or not package verification has been enabled. 7360 * 7361 * @return true if verification should be performed 7362 */ 7363 private boolean isVerificationEnabled(int flags) { 7364 if (!DEFAULT_VERIFY_ENABLE) { 7365 return false; 7366 } 7367 7368 // Check if installing from ADB 7369 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 7370 // Do not run verification in a test harness environment 7371 if (ActivityManager.isRunningInTestHarness()) { 7372 return false; 7373 } 7374 // Check if the developer does not want package verification for ADB installs 7375 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7376 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 7377 return false; 7378 } 7379 } 7380 7381 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7382 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 7383 } 7384 7385 /** 7386 * Get the "allow unknown sources" setting. 7387 * 7388 * @return the current "allow unknown sources" setting 7389 */ 7390 private int getUnknownSourcesSettings() { 7391 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7392 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 7393 -1); 7394 } 7395 7396 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 7397 final int uid = Binder.getCallingUid(); 7398 // writer 7399 synchronized (mPackages) { 7400 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 7401 if (targetPackageSetting == null) { 7402 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 7403 } 7404 7405 PackageSetting installerPackageSetting; 7406 if (installerPackageName != null) { 7407 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 7408 if (installerPackageSetting == null) { 7409 throw new IllegalArgumentException("Unknown installer package: " 7410 + installerPackageName); 7411 } 7412 } else { 7413 installerPackageSetting = null; 7414 } 7415 7416 Signature[] callerSignature; 7417 Object obj = mSettings.getUserIdLPr(uid); 7418 if (obj != null) { 7419 if (obj instanceof SharedUserSetting) { 7420 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 7421 } else if (obj instanceof PackageSetting) { 7422 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 7423 } else { 7424 throw new SecurityException("Bad object " + obj + " for uid " + uid); 7425 } 7426 } else { 7427 throw new SecurityException("Unknown calling uid " + uid); 7428 } 7429 7430 // Verify: can't set installerPackageName to a package that is 7431 // not signed with the same cert as the caller. 7432 if (installerPackageSetting != null) { 7433 if (compareSignatures(callerSignature, 7434 installerPackageSetting.signatures.mSignatures) 7435 != PackageManager.SIGNATURE_MATCH) { 7436 throw new SecurityException( 7437 "Caller does not have same cert as new installer package " 7438 + installerPackageName); 7439 } 7440 } 7441 7442 // Verify: if target already has an installer package, it must 7443 // be signed with the same cert as the caller. 7444 if (targetPackageSetting.installerPackageName != null) { 7445 PackageSetting setting = mSettings.mPackages.get( 7446 targetPackageSetting.installerPackageName); 7447 // If the currently set package isn't valid, then it's always 7448 // okay to change it. 7449 if (setting != null) { 7450 if (compareSignatures(callerSignature, 7451 setting.signatures.mSignatures) 7452 != PackageManager.SIGNATURE_MATCH) { 7453 throw new SecurityException( 7454 "Caller does not have same cert as old installer package " 7455 + targetPackageSetting.installerPackageName); 7456 } 7457 } 7458 } 7459 7460 // Okay! 7461 targetPackageSetting.installerPackageName = installerPackageName; 7462 scheduleWriteSettingsLocked(); 7463 } 7464 } 7465 7466 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 7467 // Queue up an async operation since the package installation may take a little while. 7468 mHandler.post(new Runnable() { 7469 public void run() { 7470 mHandler.removeCallbacks(this); 7471 // Result object to be returned 7472 PackageInstalledInfo res = new PackageInstalledInfo(); 7473 res.returnCode = currentStatus; 7474 res.uid = -1; 7475 res.pkg = null; 7476 res.removedInfo = new PackageRemovedInfo(); 7477 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 7478 args.doPreInstall(res.returnCode); 7479 synchronized (mInstallLock) { 7480 installPackageLI(args, true, res); 7481 } 7482 args.doPostInstall(res.returnCode, res.uid); 7483 } 7484 7485 // A restore should be performed at this point if (a) the install 7486 // succeeded, (b) the operation is not an update, and (c) the new 7487 // package has a backupAgent defined. 7488 final boolean update = res.removedInfo.removedPackage != null; 7489 boolean doRestore = (!update 7490 && res.pkg != null 7491 && res.pkg.applicationInfo.backupAgentName != null); 7492 7493 // Set up the post-install work request bookkeeping. This will be used 7494 // and cleaned up by the post-install event handling regardless of whether 7495 // there's a restore pass performed. Token values are >= 1. 7496 int token; 7497 if (mNextInstallToken < 0) mNextInstallToken = 1; 7498 token = mNextInstallToken++; 7499 7500 PostInstallData data = new PostInstallData(args, res); 7501 mRunningInstalls.put(token, data); 7502 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 7503 7504 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 7505 // Pass responsibility to the Backup Manager. It will perform a 7506 // restore if appropriate, then pass responsibility back to the 7507 // Package Manager to run the post-install observer callbacks 7508 // and broadcasts. 7509 IBackupManager bm = IBackupManager.Stub.asInterface( 7510 ServiceManager.getService(Context.BACKUP_SERVICE)); 7511 if (bm != null) { 7512 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 7513 + " to BM for possible restore"); 7514 try { 7515 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 7516 } catch (RemoteException e) { 7517 // can't happen; the backup manager is local 7518 } catch (Exception e) { 7519 Slog.e(TAG, "Exception trying to enqueue restore", e); 7520 doRestore = false; 7521 } 7522 } else { 7523 Slog.e(TAG, "Backup Manager not found!"); 7524 doRestore = false; 7525 } 7526 } 7527 7528 if (!doRestore) { 7529 // No restore possible, or the Backup Manager was mysteriously not 7530 // available -- just fire the post-install work request directly. 7531 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 7532 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 7533 mHandler.sendMessage(msg); 7534 } 7535 } 7536 }); 7537 } 7538 7539 private abstract class HandlerParams { 7540 private static final int MAX_RETRIES = 4; 7541 7542 /** 7543 * Number of times startCopy() has been attempted and had a non-fatal 7544 * error. 7545 */ 7546 private int mRetries = 0; 7547 7548 /** User handle for the user requesting the information or installation. */ 7549 private final UserHandle mUser; 7550 7551 HandlerParams(UserHandle user) { 7552 mUser = user; 7553 } 7554 7555 UserHandle getUser() { 7556 return mUser; 7557 } 7558 7559 final boolean startCopy() { 7560 boolean res; 7561 try { 7562 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 7563 7564 if (++mRetries > MAX_RETRIES) { 7565 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 7566 mHandler.sendEmptyMessage(MCS_GIVE_UP); 7567 handleServiceError(); 7568 return false; 7569 } else { 7570 handleStartCopy(); 7571 res = true; 7572 } 7573 } catch (RemoteException e) { 7574 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 7575 mHandler.sendEmptyMessage(MCS_RECONNECT); 7576 res = false; 7577 } 7578 handleReturnCode(); 7579 return res; 7580 } 7581 7582 final void serviceError() { 7583 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 7584 handleServiceError(); 7585 handleReturnCode(); 7586 } 7587 7588 abstract void handleStartCopy() throws RemoteException; 7589 abstract void handleServiceError(); 7590 abstract void handleReturnCode(); 7591 } 7592 7593 class MeasureParams extends HandlerParams { 7594 private final PackageStats mStats; 7595 private boolean mSuccess; 7596 7597 private final IPackageStatsObserver mObserver; 7598 7599 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 7600 super(new UserHandle(stats.userHandle)); 7601 mObserver = observer; 7602 mStats = stats; 7603 } 7604 7605 @Override 7606 public String toString() { 7607 return "MeasureParams{" 7608 + Integer.toHexString(System.identityHashCode(this)) 7609 + " " + mStats.packageName + "}"; 7610 } 7611 7612 @Override 7613 void handleStartCopy() throws RemoteException { 7614 synchronized (mInstallLock) { 7615 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 7616 } 7617 7618 if (mSuccess) { 7619 final boolean mounted; 7620 if (Environment.isExternalStorageEmulated()) { 7621 mounted = true; 7622 } else { 7623 final String status = Environment.getExternalStorageState(); 7624 mounted = (Environment.MEDIA_MOUNTED.equals(status) 7625 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 7626 } 7627 7628 if (mounted) { 7629 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 7630 7631 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 7632 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 7633 7634 mStats.externalDataSize = calculateDirectorySize(mContainerService, 7635 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 7636 7637 // Always subtract cache size, since it's a subdirectory 7638 mStats.externalDataSize -= mStats.externalCacheSize; 7639 7640 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 7641 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 7642 7643 mStats.externalObbSize = calculateDirectorySize(mContainerService, 7644 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 7645 } 7646 } 7647 } 7648 7649 @Override 7650 void handleReturnCode() { 7651 if (mObserver != null) { 7652 try { 7653 mObserver.onGetStatsCompleted(mStats, mSuccess); 7654 } catch (RemoteException e) { 7655 Slog.i(TAG, "Observer no longer exists."); 7656 } 7657 } 7658 } 7659 7660 @Override 7661 void handleServiceError() { 7662 Slog.e(TAG, "Could not measure application " + mStats.packageName 7663 + " external storage"); 7664 } 7665 } 7666 7667 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 7668 throws RemoteException { 7669 long result = 0; 7670 for (File path : paths) { 7671 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 7672 } 7673 return result; 7674 } 7675 7676 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 7677 for (File path : paths) { 7678 try { 7679 mcs.clearDirectory(path.getAbsolutePath()); 7680 } catch (RemoteException e) { 7681 } 7682 } 7683 } 7684 7685 class InstallParams extends HandlerParams { 7686 final IPackageInstallObserver observer; 7687 final IPackageInstallObserver2 observer2; 7688 int flags; 7689 7690 private final Uri mPackageURI; 7691 final String installerPackageName; 7692 final VerificationParams verificationParams; 7693 private InstallArgs mArgs; 7694 private int mRet; 7695 private File mTempPackage; 7696 final ContainerEncryptionParams encryptionParams; 7697 7698 InstallParams(Uri packageURI, 7699 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7700 int flags, String installerPackageName, VerificationParams verificationParams, 7701 ContainerEncryptionParams encryptionParams, UserHandle user) { 7702 super(user); 7703 this.mPackageURI = packageURI; 7704 this.flags = flags; 7705 this.observer = observer; 7706 this.observer2 = observer2; 7707 this.installerPackageName = installerPackageName; 7708 this.verificationParams = verificationParams; 7709 this.encryptionParams = encryptionParams; 7710 } 7711 7712 @Override 7713 public String toString() { 7714 return "InstallParams{" 7715 + Integer.toHexString(System.identityHashCode(this)) 7716 + " " + mPackageURI + "}"; 7717 } 7718 7719 public ManifestDigest getManifestDigest() { 7720 if (verificationParams == null) { 7721 return null; 7722 } 7723 return verificationParams.getManifestDigest(); 7724 } 7725 7726 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 7727 String packageName = pkgLite.packageName; 7728 int installLocation = pkgLite.installLocation; 7729 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 7730 // reader 7731 synchronized (mPackages) { 7732 PackageParser.Package pkg = mPackages.get(packageName); 7733 if (pkg != null) { 7734 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 7735 // Check for downgrading. 7736 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 7737 if (pkgLite.versionCode < pkg.mVersionCode) { 7738 Slog.w(TAG, "Can't install update of " + packageName 7739 + " update version " + pkgLite.versionCode 7740 + " is older than installed version " 7741 + pkg.mVersionCode); 7742 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 7743 } 7744 } 7745 // Check for updated system application. 7746 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 7747 if (onSd) { 7748 Slog.w(TAG, "Cannot install update to system app on sdcard"); 7749 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 7750 } 7751 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 7752 } else { 7753 if (onSd) { 7754 // Install flag overrides everything. 7755 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 7756 } 7757 // If current upgrade specifies particular preference 7758 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 7759 // Application explicitly specified internal. 7760 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 7761 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 7762 // App explictly prefers external. Let policy decide 7763 } else { 7764 // Prefer previous location 7765 if (isExternal(pkg)) { 7766 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 7767 } 7768 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 7769 } 7770 } 7771 } else { 7772 // Invalid install. Return error code 7773 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 7774 } 7775 } 7776 } 7777 // All the special cases have been taken care of. 7778 // Return result based on recommended install location. 7779 if (onSd) { 7780 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 7781 } 7782 return pkgLite.recommendedInstallLocation; 7783 } 7784 7785 private long getMemoryLowThreshold() { 7786 final DeviceStorageMonitorInternal 7787 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 7788 if (dsm == null) { 7789 return 0L; 7790 } 7791 return dsm.getMemoryLowThreshold(); 7792 } 7793 7794 /* 7795 * Invoke remote method to get package information and install 7796 * location values. Override install location based on default 7797 * policy if needed and then create install arguments based 7798 * on the install location. 7799 */ 7800 public void handleStartCopy() throws RemoteException { 7801 int ret = PackageManager.INSTALL_SUCCEEDED; 7802 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 7803 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 7804 PackageInfoLite pkgLite = null; 7805 7806 if (onInt && onSd) { 7807 // Check if both bits are set. 7808 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 7809 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 7810 } else { 7811 final long lowThreshold = getMemoryLowThreshold(); 7812 if (lowThreshold == 0L) { 7813 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 7814 } 7815 7816 try { 7817 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI, 7818 Intent.FLAG_GRANT_READ_URI_PERMISSION); 7819 7820 final File packageFile; 7821 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) { 7822 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir); 7823 if (mTempPackage != null) { 7824 ParcelFileDescriptor out; 7825 try { 7826 out = ParcelFileDescriptor.open(mTempPackage, 7827 ParcelFileDescriptor.MODE_READ_WRITE); 7828 } catch (FileNotFoundException e) { 7829 out = null; 7830 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI); 7831 } 7832 7833 // Make a temporary file for decryption. 7834 ret = mContainerService 7835 .copyResource(mPackageURI, encryptionParams, out); 7836 IoUtils.closeQuietly(out); 7837 7838 packageFile = mTempPackage; 7839 7840 FileUtils.setPermissions(packageFile.getAbsolutePath(), 7841 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP 7842 | FileUtils.S_IROTH, 7843 -1, -1); 7844 } else { 7845 packageFile = null; 7846 } 7847 } else { 7848 packageFile = new File(mPackageURI.getPath()); 7849 } 7850 7851 if (packageFile != null) { 7852 // Remote call to find out default install location 7853 final String packageFilePath = packageFile.getAbsolutePath(); 7854 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags, 7855 lowThreshold); 7856 7857 /* 7858 * If we have too little free space, try to free cache 7859 * before giving up. 7860 */ 7861 if (pkgLite.recommendedInstallLocation 7862 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 7863 final long size = mContainerService.calculateInstalledSize( 7864 packageFilePath, isForwardLocked()); 7865 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 7866 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, 7867 flags, lowThreshold); 7868 } 7869 /* 7870 * The cache free must have deleted the file we 7871 * downloaded to install. 7872 * 7873 * TODO: fix the "freeCache" call to not delete 7874 * the file we care about. 7875 */ 7876 if (pkgLite.recommendedInstallLocation 7877 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 7878 pkgLite.recommendedInstallLocation 7879 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 7880 } 7881 } 7882 } 7883 } finally { 7884 mContext.revokeUriPermission(mPackageURI, 7885 Intent.FLAG_GRANT_READ_URI_PERMISSION); 7886 } 7887 } 7888 7889 if (ret == PackageManager.INSTALL_SUCCEEDED) { 7890 int loc = pkgLite.recommendedInstallLocation; 7891 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 7892 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 7893 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 7894 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 7895 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 7896 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 7897 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 7898 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 7899 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 7900 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 7901 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 7902 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 7903 } else { 7904 // Override with defaults if needed. 7905 loc = installLocationPolicy(pkgLite, flags); 7906 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 7907 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 7908 } else if (!onSd && !onInt) { 7909 // Override install location with flags 7910 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 7911 // Set the flag to install on external media. 7912 flags |= PackageManager.INSTALL_EXTERNAL; 7913 flags &= ~PackageManager.INSTALL_INTERNAL; 7914 } else { 7915 // Make sure the flag for installing on external 7916 // media is unset 7917 flags |= PackageManager.INSTALL_INTERNAL; 7918 flags &= ~PackageManager.INSTALL_EXTERNAL; 7919 } 7920 } 7921 } 7922 } 7923 7924 final InstallArgs args = createInstallArgs(this); 7925 mArgs = args; 7926 7927 if (ret == PackageManager.INSTALL_SUCCEEDED) { 7928 /* 7929 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 7930 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 7931 */ 7932 int userIdentifier = getUser().getIdentifier(); 7933 if (userIdentifier == UserHandle.USER_ALL 7934 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 7935 userIdentifier = UserHandle.USER_OWNER; 7936 } 7937 7938 /* 7939 * Determine if we have any installed package verifiers. If we 7940 * do, then we'll defer to them to verify the packages. 7941 */ 7942 final int requiredUid = mRequiredVerifierPackage == null ? -1 7943 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 7944 if (requiredUid != -1 && isVerificationEnabled(flags)) { 7945 final Intent verification = new Intent( 7946 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 7947 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE); 7948 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7949 7950 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 7951 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 7952 0 /* TODO: Which userId? */); 7953 7954 if (DEBUG_VERIFY) { 7955 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 7956 + verification.toString() + " with " + pkgLite.verifiers.length 7957 + " optional verifiers"); 7958 } 7959 7960 final int verificationId = mPendingVerificationToken++; 7961 7962 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7963 7964 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 7965 installerPackageName); 7966 7967 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 7968 7969 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 7970 pkgLite.packageName); 7971 7972 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 7973 pkgLite.versionCode); 7974 7975 if (verificationParams != null) { 7976 if (verificationParams.getVerificationURI() != null) { 7977 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 7978 verificationParams.getVerificationURI()); 7979 } 7980 if (verificationParams.getOriginatingURI() != null) { 7981 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 7982 verificationParams.getOriginatingURI()); 7983 } 7984 if (verificationParams.getReferrer() != null) { 7985 verification.putExtra(Intent.EXTRA_REFERRER, 7986 verificationParams.getReferrer()); 7987 } 7988 if (verificationParams.getOriginatingUid() >= 0) { 7989 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 7990 verificationParams.getOriginatingUid()); 7991 } 7992 if (verificationParams.getInstallerUid() >= 0) { 7993 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 7994 verificationParams.getInstallerUid()); 7995 } 7996 } 7997 7998 final PackageVerificationState verificationState = new PackageVerificationState( 7999 requiredUid, args); 8000 8001 mPendingVerification.append(verificationId, verificationState); 8002 8003 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8004 receivers, verificationState); 8005 8006 /* 8007 * If any sufficient verifiers were listed in the package 8008 * manifest, attempt to ask them. 8009 */ 8010 if (sufficientVerifiers != null) { 8011 final int N = sufficientVerifiers.size(); 8012 if (N == 0) { 8013 Slog.i(TAG, "Additional verifiers required, but none installed."); 8014 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8015 } else { 8016 for (int i = 0; i < N; i++) { 8017 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8018 8019 final Intent sufficientIntent = new Intent(verification); 8020 sufficientIntent.setComponent(verifierComponent); 8021 8022 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8023 } 8024 } 8025 } 8026 8027 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8028 mRequiredVerifierPackage, receivers); 8029 if (ret == PackageManager.INSTALL_SUCCEEDED 8030 && mRequiredVerifierPackage != null) { 8031 /* 8032 * Send the intent to the required verification agent, 8033 * but only start the verification timeout after the 8034 * target BroadcastReceivers have run. 8035 */ 8036 verification.setComponent(requiredVerifierComponent); 8037 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8038 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8039 new BroadcastReceiver() { 8040 @Override 8041 public void onReceive(Context context, Intent intent) { 8042 final Message msg = mHandler 8043 .obtainMessage(CHECK_PENDING_VERIFICATION); 8044 msg.arg1 = verificationId; 8045 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8046 } 8047 }, null, 0, null, null); 8048 8049 /* 8050 * We don't want the copy to proceed until verification 8051 * succeeds, so null out this field. 8052 */ 8053 mArgs = null; 8054 } 8055 } else { 8056 /* 8057 * No package verification is enabled, so immediately start 8058 * the remote call to initiate copy using temporary file. 8059 */ 8060 ret = args.copyApk(mContainerService, true); 8061 } 8062 } 8063 8064 mRet = ret; 8065 } 8066 8067 @Override 8068 void handleReturnCode() { 8069 // If mArgs is null, then MCS couldn't be reached. When it 8070 // reconnects, it will try again to install. At that point, this 8071 // will succeed. 8072 if (mArgs != null) { 8073 processPendingInstall(mArgs, mRet); 8074 8075 if (mTempPackage != null) { 8076 if (!mTempPackage.delete()) { 8077 Slog.w(TAG, "Couldn't delete temporary file: " + 8078 mTempPackage.getAbsolutePath()); 8079 } 8080 } 8081 } 8082 } 8083 8084 @Override 8085 void handleServiceError() { 8086 mArgs = createInstallArgs(this); 8087 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8088 } 8089 8090 public boolean isForwardLocked() { 8091 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8092 } 8093 8094 public Uri getPackageUri() { 8095 if (mTempPackage != null) { 8096 return Uri.fromFile(mTempPackage); 8097 } else { 8098 return mPackageURI; 8099 } 8100 } 8101 } 8102 8103 /* 8104 * Utility class used in movePackage api. 8105 * srcArgs and targetArgs are not set for invalid flags and make 8106 * sure to do null checks when invoking methods on them. 8107 * We probably want to return ErrorPrams for both failed installs 8108 * and moves. 8109 */ 8110 class MoveParams extends HandlerParams { 8111 final IPackageMoveObserver observer; 8112 final int flags; 8113 final String packageName; 8114 final InstallArgs srcArgs; 8115 final InstallArgs targetArgs; 8116 int uid; 8117 int mRet; 8118 8119 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8120 String packageName, String dataDir, int uid, UserHandle user) { 8121 super(user); 8122 this.srcArgs = srcArgs; 8123 this.observer = observer; 8124 this.flags = flags; 8125 this.packageName = packageName; 8126 this.uid = uid; 8127 if (srcArgs != null) { 8128 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath())); 8129 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir); 8130 } else { 8131 targetArgs = null; 8132 } 8133 } 8134 8135 @Override 8136 public String toString() { 8137 return "MoveParams{" 8138 + Integer.toHexString(System.identityHashCode(this)) 8139 + " " + packageName + "}"; 8140 } 8141 8142 public void handleStartCopy() throws RemoteException { 8143 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8144 // Check for storage space on target medium 8145 if (!targetArgs.checkFreeStorage(mContainerService)) { 8146 Log.w(TAG, "Insufficient storage to install"); 8147 return; 8148 } 8149 8150 mRet = srcArgs.doPreCopy(); 8151 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8152 return; 8153 } 8154 8155 mRet = targetArgs.copyApk(mContainerService, false); 8156 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8157 srcArgs.doPostCopy(uid); 8158 return; 8159 } 8160 8161 mRet = srcArgs.doPostCopy(uid); 8162 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8163 return; 8164 } 8165 8166 mRet = targetArgs.doPreInstall(mRet); 8167 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8168 return; 8169 } 8170 8171 if (DEBUG_SD_INSTALL) { 8172 StringBuilder builder = new StringBuilder(); 8173 if (srcArgs != null) { 8174 builder.append("src: "); 8175 builder.append(srcArgs.getCodePath()); 8176 } 8177 if (targetArgs != null) { 8178 builder.append(" target : "); 8179 builder.append(targetArgs.getCodePath()); 8180 } 8181 Log.i(TAG, builder.toString()); 8182 } 8183 } 8184 8185 @Override 8186 void handleReturnCode() { 8187 targetArgs.doPostInstall(mRet, uid); 8188 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8189 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8190 currentStatus = PackageManager.MOVE_SUCCEEDED; 8191 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8192 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8193 } 8194 processPendingMove(this, currentStatus); 8195 } 8196 8197 @Override 8198 void handleServiceError() { 8199 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8200 } 8201 } 8202 8203 /** 8204 * Used during creation of InstallArgs 8205 * 8206 * @param flags package installation flags 8207 * @return true if should be installed on external storage 8208 */ 8209 private static boolean installOnSd(int flags) { 8210 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8211 return false; 8212 } 8213 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8214 return true; 8215 } 8216 return false; 8217 } 8218 8219 /** 8220 * Used during creation of InstallArgs 8221 * 8222 * @param flags package installation flags 8223 * @return true if should be installed as forward locked 8224 */ 8225 private static boolean installForwardLocked(int flags) { 8226 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8227 } 8228 8229 private InstallArgs createInstallArgs(InstallParams params) { 8230 if (installOnSd(params.flags) || params.isForwardLocked()) { 8231 return new AsecInstallArgs(params); 8232 } else { 8233 return new FileInstallArgs(params); 8234 } 8235 } 8236 8237 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath, 8238 String nativeLibraryPath) { 8239 final boolean isInAsec; 8240 if (installOnSd(flags)) { 8241 /* Apps on SD card are always in ASEC containers. */ 8242 isInAsec = true; 8243 } else if (installForwardLocked(flags) 8244 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8245 /* 8246 * Forward-locked apps are only in ASEC containers if they're the 8247 * new style 8248 */ 8249 isInAsec = true; 8250 } else { 8251 isInAsec = false; 8252 } 8253 8254 if (isInAsec) { 8255 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8256 installOnSd(flags), installForwardLocked(flags)); 8257 } else { 8258 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath); 8259 } 8260 } 8261 8262 // Used by package mover 8263 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) { 8264 if (installOnSd(flags) || installForwardLocked(flags)) { 8265 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/" 8266 + AsecInstallArgs.RES_FILE_NAME); 8267 return new AsecInstallArgs(packageURI, cid, installOnSd(flags), 8268 installForwardLocked(flags)); 8269 } else { 8270 return new FileInstallArgs(packageURI, pkgName, dataDir); 8271 } 8272 } 8273 8274 static abstract class InstallArgs { 8275 final IPackageInstallObserver observer; 8276 final IPackageInstallObserver2 observer2; 8277 // Always refers to PackageManager flags only 8278 final int flags; 8279 final Uri packageURI; 8280 final String installerPackageName; 8281 final ManifestDigest manifestDigest; 8282 final UserHandle user; 8283 8284 InstallArgs(Uri packageURI, 8285 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 8286 int flags, String installerPackageName, ManifestDigest manifestDigest, 8287 UserHandle user) { 8288 this.packageURI = packageURI; 8289 this.flags = flags; 8290 this.observer = observer; 8291 this.observer2 = observer2; 8292 this.installerPackageName = installerPackageName; 8293 this.manifestDigest = manifestDigest; 8294 this.user = user; 8295 } 8296 8297 abstract void createCopyFile(); 8298 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 8299 abstract int doPreInstall(int status); 8300 abstract boolean doRename(int status, String pkgName, String oldCodePath); 8301 8302 abstract int doPostInstall(int status, int uid); 8303 abstract String getCodePath(); 8304 abstract String getResourcePath(); 8305 abstract String getNativeLibraryPath(); 8306 // Need installer lock especially for dex file removal. 8307 abstract void cleanUpResourcesLI(); 8308 abstract boolean doPostDeleteLI(boolean delete); 8309 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 8310 8311 /** 8312 * Called before the source arguments are copied. This is used mostly 8313 * for MoveParams when it needs to read the source file to put it in the 8314 * destination. 8315 */ 8316 int doPreCopy() { 8317 return PackageManager.INSTALL_SUCCEEDED; 8318 } 8319 8320 /** 8321 * Called after the source arguments are copied. This is used mostly for 8322 * MoveParams when it needs to read the source file to put it in the 8323 * destination. 8324 * 8325 * @return 8326 */ 8327 int doPostCopy(int uid) { 8328 return PackageManager.INSTALL_SUCCEEDED; 8329 } 8330 8331 protected boolean isFwdLocked() { 8332 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8333 } 8334 8335 UserHandle getUser() { 8336 return user; 8337 } 8338 } 8339 8340 class FileInstallArgs extends InstallArgs { 8341 File installDir; 8342 String codeFileName; 8343 String resourceFileName; 8344 String libraryPath; 8345 boolean created = false; 8346 8347 FileInstallArgs(InstallParams params) { 8348 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 8349 params.installerPackageName, params.getManifestDigest(), 8350 params.getUser()); 8351 } 8352 8353 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) { 8354 super(null, null, null, 0, null, null, null); 8355 File codeFile = new File(fullCodePath); 8356 installDir = codeFile.getParentFile(); 8357 codeFileName = fullCodePath; 8358 resourceFileName = fullResourcePath; 8359 libraryPath = nativeLibraryPath; 8360 } 8361 8362 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) { 8363 super(packageURI, null, null, 0, null, null, null); 8364 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 8365 String apkName = getNextCodePath(null, pkgName, ".apk"); 8366 codeFileName = new File(installDir, apkName + ".apk").getPath(); 8367 resourceFileName = getResourcePathFromCodePath(); 8368 libraryPath = new File(mAppLibInstallDir, pkgName).getPath(); 8369 } 8370 8371 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 8372 final long lowThreshold; 8373 8374 final DeviceStorageMonitorInternal 8375 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8376 if (dsm == null) { 8377 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8378 lowThreshold = 0L; 8379 } else { 8380 if (dsm.isMemoryLow()) { 8381 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 8382 return false; 8383 } 8384 8385 lowThreshold = dsm.getMemoryLowThreshold(); 8386 } 8387 8388 try { 8389 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8390 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8391 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold); 8392 } finally { 8393 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8394 } 8395 } 8396 8397 String getCodePath() { 8398 return codeFileName; 8399 } 8400 8401 void createCopyFile() { 8402 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 8403 codeFileName = createTempPackageFile(installDir).getPath(); 8404 resourceFileName = getResourcePathFromCodePath(); 8405 libraryPath = getLibraryPathFromCodePath(); 8406 created = true; 8407 } 8408 8409 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 8410 if (temp) { 8411 // Generate temp file name 8412 createCopyFile(); 8413 } 8414 // Get a ParcelFileDescriptor to write to the output file 8415 File codeFile = new File(codeFileName); 8416 if (!created) { 8417 try { 8418 codeFile.createNewFile(); 8419 // Set permissions 8420 if (!setPermissions()) { 8421 // Failed setting permissions. 8422 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8423 } 8424 } catch (IOException e) { 8425 Slog.w(TAG, "Failed to create file " + codeFile); 8426 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8427 } 8428 } 8429 ParcelFileDescriptor out = null; 8430 try { 8431 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 8432 } catch (FileNotFoundException e) { 8433 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 8434 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8435 } 8436 // Copy the resource now 8437 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8438 try { 8439 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8440 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8441 ret = imcs.copyResource(packageURI, null, out); 8442 } finally { 8443 IoUtils.closeQuietly(out); 8444 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8445 } 8446 8447 if (isFwdLocked()) { 8448 final File destResourceFile = new File(getResourcePath()); 8449 8450 // Copy the public files 8451 try { 8452 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 8453 } catch (IOException e) { 8454 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 8455 + " forward-locked app."); 8456 destResourceFile.delete(); 8457 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8458 } 8459 } 8460 8461 final File nativeLibraryFile = new File(getNativeLibraryPath()); 8462 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath()); 8463 if (nativeLibraryFile.exists()) { 8464 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 8465 nativeLibraryFile.delete(); 8466 } 8467 try { 8468 int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile); 8469 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8470 return copyRet; 8471 } 8472 } catch (IOException e) { 8473 Slog.e(TAG, "Copying native libraries failed", e); 8474 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8475 } 8476 8477 return ret; 8478 } 8479 8480 int doPreInstall(int status) { 8481 if (status != PackageManager.INSTALL_SUCCEEDED) { 8482 cleanUp(); 8483 } 8484 return status; 8485 } 8486 8487 boolean doRename(int status, final String pkgName, String oldCodePath) { 8488 if (status != PackageManager.INSTALL_SUCCEEDED) { 8489 cleanUp(); 8490 return false; 8491 } else { 8492 final File oldCodeFile = new File(getCodePath()); 8493 final File oldResourceFile = new File(getResourcePath()); 8494 final File oldLibraryFile = new File(getNativeLibraryPath()); 8495 8496 // Rename APK file based on packageName 8497 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 8498 final File newCodeFile = new File(installDir, apkName + ".apk"); 8499 if (!oldCodeFile.renameTo(newCodeFile)) { 8500 return false; 8501 } 8502 codeFileName = newCodeFile.getPath(); 8503 8504 // Rename public resource file if it's forward-locked. 8505 final File newResFile = new File(getResourcePathFromCodePath()); 8506 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 8507 return false; 8508 } 8509 resourceFileName = newResFile.getPath(); 8510 8511 // Rename library path 8512 final File newLibraryFile = new File(getLibraryPathFromCodePath()); 8513 if (newLibraryFile.exists()) { 8514 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile); 8515 newLibraryFile.delete(); 8516 } 8517 if (!oldLibraryFile.renameTo(newLibraryFile)) { 8518 Slog.e(TAG, "Cannot rename native library directory " 8519 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath()); 8520 return false; 8521 } 8522 libraryPath = newLibraryFile.getPath(); 8523 8524 // Attempt to set permissions 8525 if (!setPermissions()) { 8526 return false; 8527 } 8528 8529 if (!SELinux.restorecon(newCodeFile)) { 8530 return false; 8531 } 8532 8533 return true; 8534 } 8535 } 8536 8537 int doPostInstall(int status, int uid) { 8538 if (status != PackageManager.INSTALL_SUCCEEDED) { 8539 cleanUp(); 8540 } 8541 return status; 8542 } 8543 8544 String getResourcePath() { 8545 return resourceFileName; 8546 } 8547 8548 private String getResourcePathFromCodePath() { 8549 final String codePath = getCodePath(); 8550 if (isFwdLocked()) { 8551 final StringBuilder sb = new StringBuilder(); 8552 8553 sb.append(mAppInstallDir.getPath()); 8554 sb.append('/'); 8555 sb.append(getApkName(codePath)); 8556 sb.append(".zip"); 8557 8558 /* 8559 * If our APK is a temporary file, mark the resource as a 8560 * temporary file as well so it can be cleaned up after 8561 * catastrophic failure. 8562 */ 8563 if (codePath.endsWith(".tmp")) { 8564 sb.append(".tmp"); 8565 } 8566 8567 return sb.toString(); 8568 } else { 8569 return codePath; 8570 } 8571 } 8572 8573 private String getLibraryPathFromCodePath() { 8574 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath(); 8575 } 8576 8577 @Override 8578 String getNativeLibraryPath() { 8579 if (libraryPath == null) { 8580 libraryPath = getLibraryPathFromCodePath(); 8581 } 8582 return libraryPath; 8583 } 8584 8585 private boolean cleanUp() { 8586 boolean ret = true; 8587 String sourceDir = getCodePath(); 8588 String publicSourceDir = getResourcePath(); 8589 if (sourceDir != null) { 8590 File sourceFile = new File(sourceDir); 8591 if (!sourceFile.exists()) { 8592 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 8593 ret = false; 8594 } 8595 // Delete application's code and resources 8596 sourceFile.delete(); 8597 } 8598 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 8599 final File publicSourceFile = new File(publicSourceDir); 8600 if (!publicSourceFile.exists()) { 8601 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 8602 } 8603 if (publicSourceFile.exists()) { 8604 publicSourceFile.delete(); 8605 } 8606 } 8607 8608 if (libraryPath != null) { 8609 File nativeLibraryFile = new File(libraryPath); 8610 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 8611 if (!nativeLibraryFile.delete()) { 8612 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath); 8613 } 8614 } 8615 8616 return ret; 8617 } 8618 8619 void cleanUpResourcesLI() { 8620 String sourceDir = getCodePath(); 8621 if (cleanUp()) { 8622 int retCode = mInstaller.rmdex(sourceDir); 8623 if (retCode < 0) { 8624 Slog.w(TAG, "Couldn't remove dex file for package: " 8625 + " at location " 8626 + sourceDir + ", retcode=" + retCode); 8627 // we don't consider this to be a failure of the core package deletion 8628 } 8629 } 8630 } 8631 8632 private boolean setPermissions() { 8633 // TODO Do this in a more elegant way later on. for now just a hack 8634 if (!isFwdLocked()) { 8635 final int filePermissions = 8636 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 8637 |FileUtils.S_IROTH; 8638 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 8639 if (retCode != 0) { 8640 Slog.e(TAG, "Couldn't set new package file permissions for " + 8641 getCodePath() 8642 + ". The return code was: " + retCode); 8643 // TODO Define new internal error 8644 return false; 8645 } 8646 return true; 8647 } 8648 return true; 8649 } 8650 8651 boolean doPostDeleteLI(boolean delete) { 8652 // XXX err, shouldn't we respect the delete flag? 8653 cleanUpResourcesLI(); 8654 return true; 8655 } 8656 } 8657 8658 private boolean isAsecExternal(String cid) { 8659 final String asecPath = PackageHelper.getSdFilesystem(cid); 8660 return !asecPath.startsWith(mAsecInternalPath); 8661 } 8662 8663 /** 8664 * Extract the MountService "container ID" from the full code path of an 8665 * .apk. 8666 */ 8667 static String cidFromCodePath(String fullCodePath) { 8668 int eidx = fullCodePath.lastIndexOf("/"); 8669 String subStr1 = fullCodePath.substring(0, eidx); 8670 int sidx = subStr1.lastIndexOf("/"); 8671 return subStr1.substring(sidx+1, eidx); 8672 } 8673 8674 class AsecInstallArgs extends InstallArgs { 8675 static final String RES_FILE_NAME = "pkg.apk"; 8676 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 8677 8678 String cid; 8679 String packagePath; 8680 String resourcePath; 8681 String libraryPath; 8682 8683 AsecInstallArgs(InstallParams params) { 8684 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 8685 params.installerPackageName, params.getManifestDigest(), 8686 params.getUser()); 8687 } 8688 8689 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 8690 boolean isExternal, boolean isForwardLocked) { 8691 super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 8692 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 8693 null, null, null); 8694 // Extract cid from fullCodePath 8695 int eidx = fullCodePath.lastIndexOf("/"); 8696 String subStr1 = fullCodePath.substring(0, eidx); 8697 int sidx = subStr1.lastIndexOf("/"); 8698 cid = subStr1.substring(sidx+1, eidx); 8699 setCachePath(subStr1); 8700 } 8701 8702 AsecInstallArgs(String cid, boolean isForwardLocked) { 8703 super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 8704 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 8705 null, null, null); 8706 this.cid = cid; 8707 setCachePath(PackageHelper.getSdDir(cid)); 8708 } 8709 8710 AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) { 8711 super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 8712 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 8713 null, null, null); 8714 this.cid = cid; 8715 } 8716 8717 void createCopyFile() { 8718 cid = getTempContainerId(); 8719 } 8720 8721 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 8722 try { 8723 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8724 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8725 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked()); 8726 } finally { 8727 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8728 } 8729 } 8730 8731 private final boolean isExternal() { 8732 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8733 } 8734 8735 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 8736 if (temp) { 8737 createCopyFile(); 8738 } else { 8739 /* 8740 * Pre-emptively destroy the container since it's destroyed if 8741 * copying fails due to it existing anyway. 8742 */ 8743 PackageHelper.destroySdDir(cid); 8744 } 8745 8746 final String newCachePath; 8747 try { 8748 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8749 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8750 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(), 8751 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked()); 8752 } finally { 8753 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8754 } 8755 8756 if (newCachePath != null) { 8757 setCachePath(newCachePath); 8758 return PackageManager.INSTALL_SUCCEEDED; 8759 } else { 8760 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 8761 } 8762 } 8763 8764 @Override 8765 String getCodePath() { 8766 return packagePath; 8767 } 8768 8769 @Override 8770 String getResourcePath() { 8771 return resourcePath; 8772 } 8773 8774 @Override 8775 String getNativeLibraryPath() { 8776 return libraryPath; 8777 } 8778 8779 int doPreInstall(int status) { 8780 if (status != PackageManager.INSTALL_SUCCEEDED) { 8781 // Destroy container 8782 PackageHelper.destroySdDir(cid); 8783 } else { 8784 boolean mounted = PackageHelper.isContainerMounted(cid); 8785 if (!mounted) { 8786 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 8787 Process.SYSTEM_UID); 8788 if (newCachePath != null) { 8789 setCachePath(newCachePath); 8790 } else { 8791 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 8792 } 8793 } 8794 } 8795 return status; 8796 } 8797 8798 boolean doRename(int status, final String pkgName, 8799 String oldCodePath) { 8800 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 8801 String newCachePath = null; 8802 if (PackageHelper.isContainerMounted(cid)) { 8803 // Unmount the container 8804 if (!PackageHelper.unMountSdDir(cid)) { 8805 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 8806 return false; 8807 } 8808 } 8809 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 8810 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 8811 " which might be stale. Will try to clean up."); 8812 // Clean up the stale container and proceed to recreate. 8813 if (!PackageHelper.destroySdDir(newCacheId)) { 8814 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 8815 return false; 8816 } 8817 // Successfully cleaned up stale container. Try to rename again. 8818 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 8819 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 8820 + " inspite of cleaning it up."); 8821 return false; 8822 } 8823 } 8824 if (!PackageHelper.isContainerMounted(newCacheId)) { 8825 Slog.w(TAG, "Mounting container " + newCacheId); 8826 newCachePath = PackageHelper.mountSdDir(newCacheId, 8827 getEncryptKey(), Process.SYSTEM_UID); 8828 } else { 8829 newCachePath = PackageHelper.getSdDir(newCacheId); 8830 } 8831 if (newCachePath == null) { 8832 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 8833 return false; 8834 } 8835 Log.i(TAG, "Succesfully renamed " + cid + 8836 " to " + newCacheId + 8837 " at new path: " + newCachePath); 8838 cid = newCacheId; 8839 setCachePath(newCachePath); 8840 return true; 8841 } 8842 8843 private void setCachePath(String newCachePath) { 8844 File cachePath = new File(newCachePath); 8845 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 8846 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 8847 8848 if (isFwdLocked()) { 8849 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 8850 } else { 8851 resourcePath = packagePath; 8852 } 8853 } 8854 8855 int doPostInstall(int status, int uid) { 8856 if (status != PackageManager.INSTALL_SUCCEEDED) { 8857 cleanUp(); 8858 } else { 8859 final int groupOwner; 8860 final String protectedFile; 8861 if (isFwdLocked()) { 8862 groupOwner = UserHandle.getSharedAppGid(uid); 8863 protectedFile = RES_FILE_NAME; 8864 } else { 8865 groupOwner = -1; 8866 protectedFile = null; 8867 } 8868 8869 if (uid < Process.FIRST_APPLICATION_UID 8870 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 8871 Slog.e(TAG, "Failed to finalize " + cid); 8872 PackageHelper.destroySdDir(cid); 8873 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 8874 } 8875 8876 boolean mounted = PackageHelper.isContainerMounted(cid); 8877 if (!mounted) { 8878 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 8879 } 8880 } 8881 return status; 8882 } 8883 8884 private void cleanUp() { 8885 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 8886 8887 // Destroy secure container 8888 PackageHelper.destroySdDir(cid); 8889 } 8890 8891 void cleanUpResourcesLI() { 8892 String sourceFile = getCodePath(); 8893 // Remove dex file 8894 int retCode = mInstaller.rmdex(sourceFile); 8895 if (retCode < 0) { 8896 Slog.w(TAG, "Couldn't remove dex file for package: " 8897 + " at location " 8898 + sourceFile.toString() + ", retcode=" + retCode); 8899 // we don't consider this to be a failure of the core package deletion 8900 } 8901 cleanUp(); 8902 } 8903 8904 boolean matchContainer(String app) { 8905 if (cid.startsWith(app)) { 8906 return true; 8907 } 8908 return false; 8909 } 8910 8911 String getPackageName() { 8912 return getAsecPackageName(cid); 8913 } 8914 8915 boolean doPostDeleteLI(boolean delete) { 8916 boolean ret = false; 8917 boolean mounted = PackageHelper.isContainerMounted(cid); 8918 if (mounted) { 8919 // Unmount first 8920 ret = PackageHelper.unMountSdDir(cid); 8921 } 8922 if (ret && delete) { 8923 cleanUpResourcesLI(); 8924 } 8925 return ret; 8926 } 8927 8928 @Override 8929 int doPreCopy() { 8930 if (isFwdLocked()) { 8931 if (!PackageHelper.fixSdPermissions(cid, 8932 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 8933 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 8934 } 8935 } 8936 8937 return PackageManager.INSTALL_SUCCEEDED; 8938 } 8939 8940 @Override 8941 int doPostCopy(int uid) { 8942 if (isFwdLocked()) { 8943 if (uid < Process.FIRST_APPLICATION_UID 8944 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 8945 RES_FILE_NAME)) { 8946 Slog.e(TAG, "Failed to finalize " + cid); 8947 PackageHelper.destroySdDir(cid); 8948 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 8949 } 8950 } 8951 8952 return PackageManager.INSTALL_SUCCEEDED; 8953 } 8954 }; 8955 8956 static String getAsecPackageName(String packageCid) { 8957 int idx = packageCid.lastIndexOf("-"); 8958 if (idx == -1) { 8959 return packageCid; 8960 } 8961 return packageCid.substring(0, idx); 8962 } 8963 8964 // Utility method used to create code paths based on package name and available index. 8965 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 8966 String idxStr = ""; 8967 int idx = 1; 8968 // Fall back to default value of idx=1 if prefix is not 8969 // part of oldCodePath 8970 if (oldCodePath != null) { 8971 String subStr = oldCodePath; 8972 // Drop the suffix right away 8973 if (subStr.endsWith(suffix)) { 8974 subStr = subStr.substring(0, subStr.length() - suffix.length()); 8975 } 8976 // If oldCodePath already contains prefix find out the 8977 // ending index to either increment or decrement. 8978 int sidx = subStr.lastIndexOf(prefix); 8979 if (sidx != -1) { 8980 subStr = subStr.substring(sidx + prefix.length()); 8981 if (subStr != null) { 8982 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 8983 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 8984 } 8985 try { 8986 idx = Integer.parseInt(subStr); 8987 if (idx <= 1) { 8988 idx++; 8989 } else { 8990 idx--; 8991 } 8992 } catch(NumberFormatException e) { 8993 } 8994 } 8995 } 8996 } 8997 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 8998 return prefix + idxStr; 8999 } 9000 9001 // Utility method used to ignore ADD/REMOVE events 9002 // by directory observer. 9003 private static boolean ignoreCodePath(String fullPathStr) { 9004 String apkName = getApkName(fullPathStr); 9005 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9006 if (idx != -1 && ((idx+1) < apkName.length())) { 9007 // Make sure the package ends with a numeral 9008 String version = apkName.substring(idx+1); 9009 try { 9010 Integer.parseInt(version); 9011 return true; 9012 } catch (NumberFormatException e) {} 9013 } 9014 return false; 9015 } 9016 9017 // Utility method that returns the relative package path with respect 9018 // to the installation directory. Like say for /data/data/com.test-1.apk 9019 // string com.test-1 is returned. 9020 static String getApkName(String codePath) { 9021 if (codePath == null) { 9022 return null; 9023 } 9024 int sidx = codePath.lastIndexOf("/"); 9025 int eidx = codePath.lastIndexOf("."); 9026 if (eidx == -1) { 9027 eidx = codePath.length(); 9028 } else if (eidx == 0) { 9029 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 9030 return null; 9031 } 9032 return codePath.substring(sidx+1, eidx); 9033 } 9034 9035 class PackageInstalledInfo { 9036 String name; 9037 int uid; 9038 // The set of users that originally had this package installed. 9039 int[] origUsers; 9040 // The set of users that now have this package installed. 9041 int[] newUsers; 9042 PackageParser.Package pkg; 9043 int returnCode; 9044 PackageRemovedInfo removedInfo; 9045 9046 // In some error cases we want to convey more info back to the observer 9047 String origPackage; 9048 String origPermission; 9049 } 9050 9051 /* 9052 * Install a non-existing package. 9053 */ 9054 private void installNewPackageLI(PackageParser.Package pkg, 9055 int parseFlags, int scanMode, UserHandle user, 9056 String installerPackageName, PackageInstalledInfo res) { 9057 // Remember this for later, in case we need to rollback this install 9058 String pkgName = pkg.packageName; 9059 9060 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9061 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9062 synchronized(mPackages) { 9063 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9064 // A package with the same name is already installed, though 9065 // it has been renamed to an older name. The package we 9066 // are trying to install should be installed as an update to 9067 // the existing one, but that has not been requested, so bail. 9068 Slog.w(TAG, "Attempt to re-install " + pkgName 9069 + " without first uninstalling package running as " 9070 + mSettings.mRenamedPackages.get(pkgName)); 9071 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9072 return; 9073 } 9074 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) { 9075 // Don't allow installation over an existing package with the same name. 9076 Slog.w(TAG, "Attempt to re-install " + pkgName 9077 + " without first uninstalling."); 9078 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9079 return; 9080 } 9081 } 9082 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9083 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9084 System.currentTimeMillis(), user); 9085 if (newPackage == null) { 9086 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9087 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9088 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9089 } 9090 } else { 9091 updateSettingsLI(newPackage, 9092 installerPackageName, 9093 null, null, 9094 res); 9095 // delete the partially installed application. the data directory will have to be 9096 // restored if it was already existing 9097 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9098 // remove package from internal structures. Note that we want deletePackageX to 9099 // delete the package data and cache directories that it created in 9100 // scanPackageLocked, unless those directories existed before we even tried to 9101 // install. 9102 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9103 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9104 res.removedInfo, true); 9105 } 9106 } 9107 } 9108 9109 private void replacePackageLI(PackageParser.Package pkg, 9110 int parseFlags, int scanMode, UserHandle user, 9111 String installerPackageName, PackageInstalledInfo res) { 9112 9113 PackageParser.Package oldPackage; 9114 String pkgName = pkg.packageName; 9115 int[] allUsers; 9116 boolean[] perUserInstalled; 9117 9118 // First find the old package info and check signatures 9119 synchronized(mPackages) { 9120 oldPackage = mPackages.get(pkgName); 9121 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9122 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9123 != PackageManager.SIGNATURE_MATCH) { 9124 Slog.w(TAG, "New package has a different signature: " + pkgName); 9125 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9126 return; 9127 } 9128 9129 // In case of rollback, remember per-user/profile install state 9130 PackageSetting ps = mSettings.mPackages.get(pkgName); 9131 allUsers = sUserManager.getUserIds(); 9132 perUserInstalled = new boolean[allUsers.length]; 9133 for (int i = 0; i < allUsers.length; i++) { 9134 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9135 } 9136 } 9137 boolean sysPkg = (isSystemApp(oldPackage)); 9138 if (sysPkg) { 9139 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9140 user, allUsers, perUserInstalled, installerPackageName, res); 9141 } else { 9142 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9143 user, allUsers, perUserInstalled, installerPackageName, res); 9144 } 9145 } 9146 9147 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9148 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9149 int[] allUsers, boolean[] perUserInstalled, 9150 String installerPackageName, PackageInstalledInfo res) { 9151 PackageParser.Package newPackage = null; 9152 String pkgName = deletedPackage.packageName; 9153 boolean deletedPkg = true; 9154 boolean updatedSettings = false; 9155 9156 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9157 + deletedPackage); 9158 long origUpdateTime; 9159 if (pkg.mExtras != null) { 9160 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9161 } else { 9162 origUpdateTime = 0; 9163 } 9164 9165 // First delete the existing package while retaining the data directory 9166 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9167 res.removedInfo, true)) { 9168 // If the existing package wasn't successfully deleted 9169 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9170 deletedPkg = false; 9171 } else { 9172 // Successfully deleted the old package. Now proceed with re-installation 9173 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9174 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9175 System.currentTimeMillis(), user); 9176 if (newPackage == null) { 9177 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9178 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9179 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9180 } 9181 } else { 9182 updateSettingsLI(newPackage, 9183 installerPackageName, 9184 allUsers, perUserInstalled, 9185 res); 9186 updatedSettings = true; 9187 } 9188 } 9189 9190 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9191 // remove package from internal structures. Note that we want deletePackageX to 9192 // delete the package data and cache directories that it created in 9193 // scanPackageLocked, unless those directories existed before we even tried to 9194 // install. 9195 if(updatedSettings) { 9196 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9197 deletePackageLI( 9198 pkgName, null, true, allUsers, perUserInstalled, 9199 PackageManager.DELETE_KEEP_DATA, 9200 res.removedInfo, true); 9201 } 9202 // Since we failed to install the new package we need to restore the old 9203 // package that we deleted. 9204 if(deletedPkg) { 9205 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9206 File restoreFile = new File(deletedPackage.mPath); 9207 // Parse old package 9208 boolean oldOnSd = isExternal(deletedPackage); 9209 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9210 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9211 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9212 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 9213 | SCAN_UPDATE_TIME; 9214 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 9215 origUpdateTime, null) == null) { 9216 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 9217 return; 9218 } 9219 // Restore of old package succeeded. Update permissions. 9220 // writer 9221 synchronized (mPackages) { 9222 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9223 UPDATE_PERMISSIONS_ALL); 9224 // can downgrade to reader 9225 mSettings.writeLPr(); 9226 } 9227 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9228 } 9229 } 9230 } 9231 9232 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9233 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9234 int[] allUsers, boolean[] perUserInstalled, 9235 String installerPackageName, PackageInstalledInfo res) { 9236 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9237 + ", old=" + deletedPackage); 9238 PackageParser.Package newPackage = null; 9239 boolean updatedSettings = false; 9240 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 9241 PackageParser.PARSE_IS_SYSTEM; 9242 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9243 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9244 } 9245 String packageName = deletedPackage.packageName; 9246 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9247 if (packageName == null) { 9248 Slog.w(TAG, "Attempt to delete null packageName."); 9249 return; 9250 } 9251 PackageParser.Package oldPkg; 9252 PackageSetting oldPkgSetting; 9253 // reader 9254 synchronized (mPackages) { 9255 oldPkg = mPackages.get(packageName); 9256 oldPkgSetting = mSettings.mPackages.get(packageName); 9257 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 9258 (oldPkgSetting == null)) { 9259 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 9260 return; 9261 } 9262 } 9263 9264 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 9265 9266 res.removedInfo.uid = oldPkg.applicationInfo.uid; 9267 res.removedInfo.removedPackage = packageName; 9268 // Remove existing system package 9269 removePackageLI(oldPkgSetting, true); 9270 // writer 9271 synchronized (mPackages) { 9272 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 9273 // We didn't need to disable the .apk as a current system package, 9274 // which means we are replacing another update that is already 9275 // installed. We need to make sure to delete the older one's .apk. 9276 res.removedInfo.args = createInstallArgs(0, 9277 deletedPackage.applicationInfo.sourceDir, 9278 deletedPackage.applicationInfo.publicSourceDir, 9279 deletedPackage.applicationInfo.nativeLibraryDir); 9280 } else { 9281 res.removedInfo.args = null; 9282 } 9283 } 9284 9285 // Successfully disabled the old package. Now proceed with re-installation 9286 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9287 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9288 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user); 9289 if (newPackage == null) { 9290 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9291 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9292 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9293 } 9294 } else { 9295 if (newPackage.mExtras != null) { 9296 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 9297 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 9298 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 9299 9300 // is the update attempting to change shared user? that isn't going to work... 9301 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 9302 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 9303 + " to " + newPkgSetting.sharedUser); 9304 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 9305 updatedSettings = true; 9306 } 9307 } 9308 9309 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9310 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9311 updatedSettings = true; 9312 } 9313 } 9314 9315 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9316 // Re installation failed. Restore old information 9317 // Remove new pkg information 9318 if (newPackage != null) { 9319 removeInstalledPackageLI(newPackage, true); 9320 } 9321 // Add back the old system package 9322 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user); 9323 // Restore the old system information in Settings 9324 synchronized(mPackages) { 9325 if (updatedSettings) { 9326 mSettings.enableSystemPackageLPw(packageName); 9327 mSettings.setInstallerPackageName(packageName, 9328 oldPkgSetting.installerPackageName); 9329 } 9330 mSettings.writeLPr(); 9331 } 9332 } 9333 } 9334 9335 // Utility method used to move dex files during install. 9336 private int moveDexFilesLI(PackageParser.Package newPackage) { 9337 int retCode; 9338 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 9339 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath); 9340 if (retCode != 0) { 9341 if (mNoDexOpt) { 9342 /* 9343 * If we're in an engineering build, programs are lazily run 9344 * through dexopt. If the .dex file doesn't exist yet, it 9345 * will be created when the program is run next. 9346 */ 9347 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath); 9348 } else { 9349 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath); 9350 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9351 } 9352 } 9353 } 9354 return PackageManager.INSTALL_SUCCEEDED; 9355 } 9356 9357 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 9358 int[] allUsers, boolean[] perUserInstalled, 9359 PackageInstalledInfo res) { 9360 String pkgName = newPackage.packageName; 9361 synchronized (mPackages) { 9362 //write settings. the installStatus will be incomplete at this stage. 9363 //note that the new package setting would have already been 9364 //added to mPackages. It hasn't been persisted yet. 9365 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 9366 mSettings.writeLPr(); 9367 } 9368 9369 if ((res.returnCode = moveDexFilesLI(newPackage)) 9370 != PackageManager.INSTALL_SUCCEEDED) { 9371 // Discontinue if moving dex files failed. 9372 return; 9373 } 9374 9375 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath); 9376 9377 synchronized (mPackages) { 9378 updatePermissionsLPw(newPackage.packageName, newPackage, 9379 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 9380 ? UPDATE_PERMISSIONS_ALL : 0)); 9381 // For system-bundled packages, we assume that installing an upgraded version 9382 // of the package implies that the user actually wants to run that new code, 9383 // so we enable the package. 9384 if (isSystemApp(newPackage)) { 9385 // NB: implicit assumption that system package upgrades apply to all users 9386 if (DEBUG_INSTALL) { 9387 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 9388 } 9389 PackageSetting ps = mSettings.mPackages.get(pkgName); 9390 if (ps != null) { 9391 if (res.origUsers != null) { 9392 for (int userHandle : res.origUsers) { 9393 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 9394 userHandle, installerPackageName); 9395 } 9396 } 9397 // Also convey the prior install/uninstall state 9398 if (allUsers != null && perUserInstalled != null) { 9399 for (int i = 0; i < allUsers.length; i++) { 9400 if (DEBUG_INSTALL) { 9401 Slog.d(TAG, " user " + allUsers[i] 9402 + " => " + perUserInstalled[i]); 9403 } 9404 ps.setInstalled(perUserInstalled[i], allUsers[i]); 9405 } 9406 // these install state changes will be persisted in the 9407 // upcoming call to mSettings.writeLPr(). 9408 } 9409 } 9410 } 9411 res.name = pkgName; 9412 res.uid = newPackage.applicationInfo.uid; 9413 res.pkg = newPackage; 9414 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 9415 mSettings.setInstallerPackageName(pkgName, installerPackageName); 9416 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 9417 //to update install status 9418 mSettings.writeLPr(); 9419 } 9420 } 9421 9422 private void installPackageLI(InstallArgs args, 9423 boolean newInstall, PackageInstalledInfo res) { 9424 int pFlags = args.flags; 9425 String installerPackageName = args.installerPackageName; 9426 File tmpPackageFile = new File(args.getCodePath()); 9427 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 9428 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 9429 boolean replace = false; 9430 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 9431 | (newInstall ? SCAN_NEW_INSTALL : 0); 9432 // Result object to be returned 9433 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 9434 9435 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 9436 // Retrieve PackageSettings and parse package 9437 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 9438 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 9439 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 9440 PackageParser pp = new PackageParser(tmpPackageFile.getPath()); 9441 pp.setSeparateProcesses(mSeparateProcesses); 9442 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile, 9443 null, mMetrics, parseFlags); 9444 if (pkg == null) { 9445 res.returnCode = pp.getParseError(); 9446 return; 9447 } 9448 String pkgName = res.name = pkg.packageName; 9449 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 9450 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 9451 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 9452 return; 9453 } 9454 } 9455 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) { 9456 res.returnCode = pp.getParseError(); 9457 return; 9458 } 9459 9460 /* If the installer passed in a manifest digest, compare it now. */ 9461 if (args.manifestDigest != null) { 9462 if (DEBUG_INSTALL) { 9463 final String parsedManifest = pkg.manifestDigest == null ? "null" 9464 : pkg.manifestDigest.toString(); 9465 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 9466 + parsedManifest); 9467 } 9468 9469 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 9470 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 9471 return; 9472 } 9473 } else if (DEBUG_INSTALL) { 9474 final String parsedManifest = pkg.manifestDigest == null 9475 ? "null" : pkg.manifestDigest.toString(); 9476 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 9477 } 9478 9479 // Get rid of all references to package scan path via parser. 9480 pp = null; 9481 String oldCodePath = null; 9482 boolean systemApp = false; 9483 synchronized (mPackages) { 9484 // Check whether the newly-scanned package wants to define an already-defined perm 9485 int N = pkg.permissions.size(); 9486 for (int i = 0; i < N; i++) { 9487 PackageParser.Permission perm = pkg.permissions.get(i); 9488 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 9489 if (bp != null) { 9490 // If the defining package is signed with our cert, it's okay. This 9491 // also includes the "updating the same package" case, of course. 9492 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 9493 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9494 Slog.w(TAG, "Package " + pkg.packageName 9495 + " attempting to redeclare permission " + perm.info.name 9496 + " already owned by " + bp.sourcePackage); 9497 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 9498 res.origPermission = perm.info.name; 9499 res.origPackage = bp.sourcePackage; 9500 return; 9501 } 9502 } 9503 } 9504 9505 // Check if installing already existing package 9506 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9507 String oldName = mSettings.mRenamedPackages.get(pkgName); 9508 if (pkg.mOriginalPackages != null 9509 && pkg.mOriginalPackages.contains(oldName) 9510 && mPackages.containsKey(oldName)) { 9511 // This package is derived from an original package, 9512 // and this device has been updating from that original 9513 // name. We must continue using the original name, so 9514 // rename the new package here. 9515 pkg.setPackageName(oldName); 9516 pkgName = pkg.packageName; 9517 replace = true; 9518 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 9519 + oldName + " pkgName=" + pkgName); 9520 } else if (mPackages.containsKey(pkgName)) { 9521 // This package, under its official name, already exists 9522 // on the device; we should replace it. 9523 replace = true; 9524 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 9525 } 9526 } 9527 PackageSetting ps = mSettings.mPackages.get(pkgName); 9528 if (ps != null) { 9529 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 9530 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 9531 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 9532 systemApp = (ps.pkg.applicationInfo.flags & 9533 ApplicationInfo.FLAG_SYSTEM) != 0; 9534 } 9535 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 9536 } 9537 } 9538 9539 if (systemApp && onSd) { 9540 // Disable updates to system apps on sdcard 9541 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 9542 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9543 return; 9544 } 9545 9546 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 9547 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9548 return; 9549 } 9550 // Set application objects path explicitly after the rename 9551 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath()); 9552 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 9553 if (replace) { 9554 replacePackageLI(pkg, parseFlags, scanMode, args.user, 9555 installerPackageName, res); 9556 } else { 9557 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 9558 installerPackageName, res); 9559 } 9560 synchronized (mPackages) { 9561 final PackageSetting ps = mSettings.mPackages.get(pkgName); 9562 if (ps != null) { 9563 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 9564 } 9565 } 9566 } 9567 9568 private static boolean isForwardLocked(PackageParser.Package pkg) { 9569 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 9570 } 9571 9572 9573 private boolean isForwardLocked(PackageSetting ps) { 9574 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 9575 } 9576 9577 private static boolean isExternal(PackageParser.Package pkg) { 9578 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 9579 } 9580 9581 private static boolean isExternal(PackageSetting ps) { 9582 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 9583 } 9584 9585 private static boolean isSystemApp(PackageParser.Package pkg) { 9586 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9587 } 9588 9589 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 9590 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 9591 } 9592 9593 private static boolean isSystemApp(ApplicationInfo info) { 9594 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9595 } 9596 9597 private static boolean isSystemApp(PackageSetting ps) { 9598 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 9599 } 9600 9601 private static boolean isUpdatedSystemApp(PackageSetting ps) { 9602 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 9603 } 9604 9605 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 9606 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 9607 } 9608 9609 private int packageFlagsToInstallFlags(PackageSetting ps) { 9610 int installFlags = 0; 9611 if (isExternal(ps)) { 9612 installFlags |= PackageManager.INSTALL_EXTERNAL; 9613 } 9614 if (isForwardLocked(ps)) { 9615 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 9616 } 9617 return installFlags; 9618 } 9619 9620 private void deleteTempPackageFiles() { 9621 final FilenameFilter filter = new FilenameFilter() { 9622 public boolean accept(File dir, String name) { 9623 return name.startsWith("vmdl") && name.endsWith(".tmp"); 9624 } 9625 }; 9626 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 9627 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 9628 } 9629 9630 private static final void deleteTempPackageFilesInDirectory(File directory, 9631 FilenameFilter filter) { 9632 final String[] tmpFilesList = directory.list(filter); 9633 if (tmpFilesList == null) { 9634 return; 9635 } 9636 for (int i = 0; i < tmpFilesList.length; i++) { 9637 final File tmpFile = new File(directory, tmpFilesList[i]); 9638 tmpFile.delete(); 9639 } 9640 } 9641 9642 private File createTempPackageFile(File installDir) { 9643 File tmpPackageFile; 9644 try { 9645 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 9646 } catch (IOException e) { 9647 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 9648 return null; 9649 } 9650 try { 9651 FileUtils.setPermissions( 9652 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 9653 -1, -1); 9654 if (!SELinux.restorecon(tmpPackageFile)) { 9655 return null; 9656 } 9657 } catch (IOException e) { 9658 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 9659 return null; 9660 } 9661 return tmpPackageFile; 9662 } 9663 9664 @Override 9665 public void deletePackageAsUser(final String packageName, 9666 final IPackageDeleteObserver observer, 9667 final int userId, final int flags) { 9668 mContext.enforceCallingOrSelfPermission( 9669 android.Manifest.permission.DELETE_PACKAGES, null); 9670 final int uid = Binder.getCallingUid(); 9671 if (UserHandle.getUserId(uid) != userId) { 9672 mContext.enforceCallingPermission( 9673 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 9674 "deletePackage for user " + userId); 9675 } 9676 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 9677 try { 9678 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 9679 } catch (RemoteException re) { 9680 } 9681 return; 9682 } 9683 9684 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 9685 // Queue up an async operation since the package deletion may take a little while. 9686 mHandler.post(new Runnable() { 9687 public void run() { 9688 mHandler.removeCallbacks(this); 9689 final int returnCode = deletePackageX(packageName, userId, flags); 9690 if (observer != null) { 9691 try { 9692 observer.packageDeleted(packageName, returnCode); 9693 } catch (RemoteException e) { 9694 Log.i(TAG, "Observer no longer exists."); 9695 } //end catch 9696 } //end if 9697 } //end run 9698 }); 9699 } 9700 9701 private boolean isPackageDeviceAdmin(String packageName, int userId) { 9702 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 9703 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 9704 try { 9705 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 9706 || dpm.isDeviceOwner(packageName))) { 9707 return true; 9708 } 9709 } catch (RemoteException e) { 9710 } 9711 return false; 9712 } 9713 9714 /** 9715 * This method is an internal method that could be get invoked either 9716 * to delete an installed package or to clean up a failed installation. 9717 * After deleting an installed package, a broadcast is sent to notify any 9718 * listeners that the package has been installed. For cleaning up a failed 9719 * installation, the broadcast is not necessary since the package's 9720 * installation wouldn't have sent the initial broadcast either 9721 * The key steps in deleting a package are 9722 * deleting the package information in internal structures like mPackages, 9723 * deleting the packages base directories through installd 9724 * updating mSettings to reflect current status 9725 * persisting settings for later use 9726 * sending a broadcast if necessary 9727 */ 9728 private int deletePackageX(String packageName, int userId, int flags) { 9729 final PackageRemovedInfo info = new PackageRemovedInfo(); 9730 final boolean res; 9731 9732 if (isPackageDeviceAdmin(packageName, userId)) { 9733 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 9734 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 9735 } 9736 9737 boolean removedForAllUsers = false; 9738 boolean systemUpdate = false; 9739 9740 // for the uninstall-updates case and restricted profiles, remember the per- 9741 // userhandle installed state 9742 int[] allUsers; 9743 boolean[] perUserInstalled; 9744 synchronized (mPackages) { 9745 PackageSetting ps = mSettings.mPackages.get(packageName); 9746 allUsers = sUserManager.getUserIds(); 9747 perUserInstalled = new boolean[allUsers.length]; 9748 for (int i = 0; i < allUsers.length; i++) { 9749 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9750 } 9751 } 9752 9753 synchronized (mInstallLock) { 9754 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 9755 res = deletePackageLI(packageName, 9756 (flags & PackageManager.DELETE_ALL_USERS) != 0 9757 ? UserHandle.ALL : new UserHandle(userId), 9758 true, allUsers, perUserInstalled, 9759 flags | REMOVE_CHATTY, info, true); 9760 systemUpdate = info.isRemovedPackageSystemUpdate; 9761 if (res && !systemUpdate && mPackages.get(packageName) == null) { 9762 removedForAllUsers = true; 9763 } 9764 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 9765 + " removedForAllUsers=" + removedForAllUsers); 9766 } 9767 9768 if (res) { 9769 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 9770 9771 // If the removed package was a system update, the old system package 9772 // was re-enabled; we need to broadcast this information 9773 if (systemUpdate) { 9774 Bundle extras = new Bundle(1); 9775 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 9776 ? info.removedAppId : info.uid); 9777 extras.putBoolean(Intent.EXTRA_REPLACING, true); 9778 9779 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 9780 extras, null, null, null); 9781 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 9782 extras, null, null, null); 9783 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 9784 null, packageName, null, null); 9785 } 9786 } 9787 // Force a gc here. 9788 Runtime.getRuntime().gc(); 9789 // Delete the resources here after sending the broadcast to let 9790 // other processes clean up before deleting resources. 9791 if (info.args != null) { 9792 synchronized (mInstallLock) { 9793 info.args.doPostDeleteLI(true); 9794 } 9795 } 9796 9797 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 9798 } 9799 9800 static class PackageRemovedInfo { 9801 String removedPackage; 9802 int uid = -1; 9803 int removedAppId = -1; 9804 int[] removedUsers = null; 9805 boolean isRemovedPackageSystemUpdate = false; 9806 // Clean up resources deleted packages. 9807 InstallArgs args = null; 9808 9809 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 9810 Bundle extras = new Bundle(1); 9811 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 9812 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 9813 if (replacing) { 9814 extras.putBoolean(Intent.EXTRA_REPLACING, true); 9815 } 9816 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 9817 if (removedPackage != null) { 9818 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 9819 extras, null, null, removedUsers); 9820 if (fullRemove && !replacing) { 9821 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 9822 extras, null, null, removedUsers); 9823 } 9824 } 9825 if (removedAppId >= 0) { 9826 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 9827 removedUsers); 9828 } 9829 } 9830 } 9831 9832 /* 9833 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 9834 * flag is not set, the data directory is removed as well. 9835 * make sure this flag is set for partially installed apps. If not its meaningless to 9836 * delete a partially installed application. 9837 */ 9838 private void removePackageDataLI(PackageSetting ps, 9839 int[] allUserHandles, boolean[] perUserInstalled, 9840 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 9841 String packageName = ps.name; 9842 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 9843 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 9844 // Retrieve object to delete permissions for shared user later on 9845 final PackageSetting deletedPs; 9846 // reader 9847 synchronized (mPackages) { 9848 deletedPs = mSettings.mPackages.get(packageName); 9849 if (outInfo != null) { 9850 outInfo.removedPackage = packageName; 9851 outInfo.removedUsers = deletedPs != null 9852 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 9853 : null; 9854 } 9855 } 9856 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 9857 removeDataDirsLI(packageName); 9858 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 9859 } 9860 // writer 9861 synchronized (mPackages) { 9862 if (deletedPs != null) { 9863 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 9864 if (outInfo != null) { 9865 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 9866 } 9867 if (deletedPs != null) { 9868 updatePermissionsLPw(deletedPs.name, null, 0); 9869 if (deletedPs.sharedUser != null) { 9870 // remove permissions associated with package 9871 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 9872 } 9873 } 9874 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 9875 } 9876 // make sure to preserve per-user disabled state if this removal was just 9877 // a downgrade of a system app to the factory package 9878 if (allUserHandles != null && perUserInstalled != null) { 9879 if (DEBUG_REMOVE) { 9880 Slog.d(TAG, "Propagating install state across downgrade"); 9881 } 9882 for (int i = 0; i < allUserHandles.length; i++) { 9883 if (DEBUG_REMOVE) { 9884 Slog.d(TAG, " user " + allUserHandles[i] 9885 + " => " + perUserInstalled[i]); 9886 } 9887 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 9888 } 9889 } 9890 } 9891 // can downgrade to reader 9892 if (writeSettings) { 9893 // Save settings now 9894 mSettings.writeLPr(); 9895 } 9896 } 9897 if (outInfo != null) { 9898 // A user ID was deleted here. Go through all users and remove it 9899 // from KeyStore. 9900 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 9901 } 9902 } 9903 9904 static boolean locationIsPrivileged(File path) { 9905 try { 9906 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 9907 .getCanonicalPath(); 9908 return path.getCanonicalPath().startsWith(privilegedAppDir); 9909 } catch (IOException e) { 9910 Slog.e(TAG, "Unable to access code path " + path); 9911 } 9912 return false; 9913 } 9914 9915 /* 9916 * Tries to delete system package. 9917 */ 9918 private boolean deleteSystemPackageLI(PackageSetting newPs, 9919 int[] allUserHandles, boolean[] perUserInstalled, 9920 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 9921 final boolean applyUserRestrictions 9922 = (allUserHandles != null) && (perUserInstalled != null); 9923 PackageSetting disabledPs = null; 9924 // Confirm if the system package has been updated 9925 // An updated system app can be deleted. This will also have to restore 9926 // the system pkg from system partition 9927 // reader 9928 synchronized (mPackages) { 9929 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 9930 } 9931 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 9932 + " disabledPs=" + disabledPs); 9933 if (disabledPs == null) { 9934 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 9935 return false; 9936 } else if (DEBUG_REMOVE) { 9937 Slog.d(TAG, "Deleting system pkg from data partition"); 9938 } 9939 if (DEBUG_REMOVE) { 9940 if (applyUserRestrictions) { 9941 Slog.d(TAG, "Remembering install states:"); 9942 for (int i = 0; i < allUserHandles.length; i++) { 9943 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 9944 } 9945 } 9946 } 9947 // Delete the updated package 9948 outInfo.isRemovedPackageSystemUpdate = true; 9949 if (disabledPs.versionCode < newPs.versionCode) { 9950 // Delete data for downgrades 9951 flags &= ~PackageManager.DELETE_KEEP_DATA; 9952 } else { 9953 // Preserve data by setting flag 9954 flags |= PackageManager.DELETE_KEEP_DATA; 9955 } 9956 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 9957 allUserHandles, perUserInstalled, outInfo, writeSettings); 9958 if (!ret) { 9959 return false; 9960 } 9961 // writer 9962 synchronized (mPackages) { 9963 // Reinstate the old system package 9964 mSettings.enableSystemPackageLPw(newPs.name); 9965 // Remove any native libraries from the upgraded package. 9966 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 9967 } 9968 // Install the system package 9969 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 9970 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 9971 if (locationIsPrivileged(disabledPs.codePath)) { 9972 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9973 } 9974 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 9975 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null); 9976 9977 if (newPkg == null) { 9978 Slog.w(TAG, "Failed to restore system package:" + newPs.name 9979 + " with error:" + mLastScanError); 9980 return false; 9981 } 9982 // writer 9983 synchronized (mPackages) { 9984 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 9985 setInternalAppNativeLibraryPath(newPkg, ps); 9986 updatePermissionsLPw(newPkg.packageName, newPkg, 9987 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 9988 if (applyUserRestrictions) { 9989 if (DEBUG_REMOVE) { 9990 Slog.d(TAG, "Propagating install state across reinstall"); 9991 } 9992 for (int i = 0; i < allUserHandles.length; i++) { 9993 if (DEBUG_REMOVE) { 9994 Slog.d(TAG, " user " + allUserHandles[i] 9995 + " => " + perUserInstalled[i]); 9996 } 9997 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 9998 } 9999 // Regardless of writeSettings we need to ensure that this restriction 10000 // state propagation is persisted 10001 mSettings.writeAllUsersPackageRestrictionsLPr(); 10002 } 10003 // can downgrade to reader here 10004 if (writeSettings) { 10005 mSettings.writeLPr(); 10006 } 10007 } 10008 return true; 10009 } 10010 10011 private boolean deleteInstalledPackageLI(PackageSetting ps, 10012 boolean deleteCodeAndResources, int flags, 10013 int[] allUserHandles, boolean[] perUserInstalled, 10014 PackageRemovedInfo outInfo, boolean writeSettings) { 10015 if (outInfo != null) { 10016 outInfo.uid = ps.appId; 10017 } 10018 10019 // Delete package data from internal structures and also remove data if flag is set 10020 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10021 10022 // Delete application code and resources 10023 if (deleteCodeAndResources && (outInfo != null)) { 10024 outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString, 10025 ps.resourcePathString, ps.nativeLibraryPathString); 10026 } 10027 return true; 10028 } 10029 10030 /* 10031 * This method handles package deletion in general 10032 */ 10033 private boolean deletePackageLI(String packageName, UserHandle user, 10034 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10035 int flags, PackageRemovedInfo outInfo, 10036 boolean writeSettings) { 10037 if (packageName == null) { 10038 Slog.w(TAG, "Attempt to delete null packageName."); 10039 return false; 10040 } 10041 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10042 PackageSetting ps; 10043 boolean dataOnly = false; 10044 int removeUser = -1; 10045 int appId = -1; 10046 synchronized (mPackages) { 10047 ps = mSettings.mPackages.get(packageName); 10048 if (ps == null) { 10049 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10050 return false; 10051 } 10052 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10053 && user.getIdentifier() != UserHandle.USER_ALL) { 10054 // The caller is asking that the package only be deleted for a single 10055 // user. To do this, we just mark its uninstalled state and delete 10056 // its data. If this is a system app, we only allow this to happen if 10057 // they have set the special DELETE_SYSTEM_APP which requests different 10058 // semantics than normal for uninstalling system apps. 10059 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10060 ps.setUserState(user.getIdentifier(), 10061 COMPONENT_ENABLED_STATE_DEFAULT, 10062 false, //installed 10063 true, //stopped 10064 true, //notLaunched 10065 false, //blocked 10066 null, null, null); 10067 if (!isSystemApp(ps)) { 10068 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10069 // Other user still have this package installed, so all 10070 // we need to do is clear this user's data and save that 10071 // it is uninstalled. 10072 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10073 removeUser = user.getIdentifier(); 10074 appId = ps.appId; 10075 mSettings.writePackageRestrictionsLPr(removeUser); 10076 } else { 10077 // We need to set it back to 'installed' so the uninstall 10078 // broadcasts will be sent correctly. 10079 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10080 ps.setInstalled(true, user.getIdentifier()); 10081 } 10082 } else { 10083 // This is a system app, so we assume that the 10084 // other users still have this package installed, so all 10085 // we need to do is clear this user's data and save that 10086 // it is uninstalled. 10087 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10088 removeUser = user.getIdentifier(); 10089 appId = ps.appId; 10090 mSettings.writePackageRestrictionsLPr(removeUser); 10091 } 10092 } 10093 } 10094 10095 if (removeUser >= 0) { 10096 // From above, we determined that we are deleting this only 10097 // for a single user. Continue the work here. 10098 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10099 if (outInfo != null) { 10100 outInfo.removedPackage = packageName; 10101 outInfo.removedAppId = appId; 10102 outInfo.removedUsers = new int[] {removeUser}; 10103 } 10104 mInstaller.clearUserData(packageName, removeUser); 10105 removeKeystoreDataIfNeeded(removeUser, appId); 10106 schedulePackageCleaning(packageName, removeUser, false); 10107 return true; 10108 } 10109 10110 if (dataOnly) { 10111 // Delete application data first 10112 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10113 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10114 return true; 10115 } 10116 10117 boolean ret = false; 10118 mSettings.mKeySetManager.removeAppKeySetData(packageName); 10119 if (isSystemApp(ps)) { 10120 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10121 // When an updated system application is deleted we delete the existing resources as well and 10122 // fall back to existing code in system partition 10123 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10124 flags, outInfo, writeSettings); 10125 } else { 10126 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10127 // Kill application pre-emptively especially for apps on sd. 10128 killApplication(packageName, ps.appId, "uninstall pkg"); 10129 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10130 allUserHandles, perUserInstalled, 10131 outInfo, writeSettings); 10132 } 10133 10134 return ret; 10135 } 10136 10137 private final class ClearStorageConnection implements ServiceConnection { 10138 IMediaContainerService mContainerService; 10139 10140 @Override 10141 public void onServiceConnected(ComponentName name, IBinder service) { 10142 synchronized (this) { 10143 mContainerService = IMediaContainerService.Stub.asInterface(service); 10144 notifyAll(); 10145 } 10146 } 10147 10148 @Override 10149 public void onServiceDisconnected(ComponentName name) { 10150 } 10151 } 10152 10153 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10154 final boolean mounted; 10155 if (Environment.isExternalStorageEmulated()) { 10156 mounted = true; 10157 } else { 10158 final String status = Environment.getExternalStorageState(); 10159 10160 mounted = status.equals(Environment.MEDIA_MOUNTED) 10161 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10162 } 10163 10164 if (!mounted) { 10165 return; 10166 } 10167 10168 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10169 int[] users; 10170 if (userId == UserHandle.USER_ALL) { 10171 users = sUserManager.getUserIds(); 10172 } else { 10173 users = new int[] { userId }; 10174 } 10175 final ClearStorageConnection conn = new ClearStorageConnection(); 10176 if (mContext.bindServiceAsUser( 10177 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10178 try { 10179 for (int curUser : users) { 10180 long timeout = SystemClock.uptimeMillis() + 5000; 10181 synchronized (conn) { 10182 long now = SystemClock.uptimeMillis(); 10183 while (conn.mContainerService == null && now < timeout) { 10184 try { 10185 conn.wait(timeout - now); 10186 } catch (InterruptedException e) { 10187 } 10188 } 10189 } 10190 if (conn.mContainerService == null) { 10191 return; 10192 } 10193 10194 final UserEnvironment userEnv = new UserEnvironment(curUser); 10195 clearDirectory(conn.mContainerService, 10196 userEnv.buildExternalStorageAppCacheDirs(packageName)); 10197 if (allData) { 10198 clearDirectory(conn.mContainerService, 10199 userEnv.buildExternalStorageAppDataDirs(packageName)); 10200 clearDirectory(conn.mContainerService, 10201 userEnv.buildExternalStorageAppMediaDirs(packageName)); 10202 } 10203 } 10204 } finally { 10205 mContext.unbindService(conn); 10206 } 10207 } 10208 } 10209 10210 @Override 10211 public void clearApplicationUserData(final String packageName, 10212 final IPackageDataObserver observer, final int userId) { 10213 mContext.enforceCallingOrSelfPermission( 10214 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 10215 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 10216 // Queue up an async operation since the package deletion may take a little while. 10217 mHandler.post(new Runnable() { 10218 public void run() { 10219 mHandler.removeCallbacks(this); 10220 final boolean succeeded; 10221 synchronized (mInstallLock) { 10222 succeeded = clearApplicationUserDataLI(packageName, userId); 10223 } 10224 clearExternalStorageDataSync(packageName, userId, true); 10225 if (succeeded) { 10226 // invoke DeviceStorageMonitor's update method to clear any notifications 10227 DeviceStorageMonitorInternal 10228 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 10229 if (dsm != null) { 10230 dsm.checkMemory(); 10231 } 10232 } 10233 if(observer != null) { 10234 try { 10235 observer.onRemoveCompleted(packageName, succeeded); 10236 } catch (RemoteException e) { 10237 Log.i(TAG, "Observer no longer exists."); 10238 } 10239 } //end if observer 10240 } //end run 10241 }); 10242 } 10243 10244 private boolean clearApplicationUserDataLI(String packageName, int userId) { 10245 if (packageName == null) { 10246 Slog.w(TAG, "Attempt to delete null packageName."); 10247 return false; 10248 } 10249 PackageParser.Package p; 10250 boolean dataOnly = false; 10251 final int appId; 10252 synchronized (mPackages) { 10253 p = mPackages.get(packageName); 10254 if (p == null) { 10255 dataOnly = true; 10256 PackageSetting ps = mSettings.mPackages.get(packageName); 10257 if ((ps == null) || (ps.pkg == null)) { 10258 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10259 return false; 10260 } 10261 p = ps.pkg; 10262 } 10263 if (!dataOnly) { 10264 // need to check this only for fully installed applications 10265 if (p == null) { 10266 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10267 return false; 10268 } 10269 final ApplicationInfo applicationInfo = p.applicationInfo; 10270 if (applicationInfo == null) { 10271 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10272 return false; 10273 } 10274 } 10275 if (p != null && p.applicationInfo != null) { 10276 appId = p.applicationInfo.uid; 10277 } else { 10278 appId = -1; 10279 } 10280 } 10281 int retCode = mInstaller.clearUserData(packageName, userId); 10282 if (retCode < 0) { 10283 Slog.w(TAG, "Couldn't remove cache files for package: " 10284 + packageName); 10285 return false; 10286 } 10287 removeKeystoreDataIfNeeded(userId, appId); 10288 return true; 10289 } 10290 10291 /** 10292 * Remove entries from the keystore daemon. Will only remove it if the 10293 * {@code appId} is valid. 10294 */ 10295 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 10296 if (appId < 0) { 10297 return; 10298 } 10299 10300 final KeyStore keyStore = KeyStore.getInstance(); 10301 if (keyStore != null) { 10302 if (userId == UserHandle.USER_ALL) { 10303 for (final int individual : sUserManager.getUserIds()) { 10304 keyStore.clearUid(UserHandle.getUid(individual, appId)); 10305 } 10306 } else { 10307 keyStore.clearUid(UserHandle.getUid(userId, appId)); 10308 } 10309 } else { 10310 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 10311 } 10312 } 10313 10314 public void deleteApplicationCacheFiles(final String packageName, 10315 final IPackageDataObserver observer) { 10316 mContext.enforceCallingOrSelfPermission( 10317 android.Manifest.permission.DELETE_CACHE_FILES, null); 10318 // Queue up an async operation since the package deletion may take a little while. 10319 final int userId = UserHandle.getCallingUserId(); 10320 mHandler.post(new Runnable() { 10321 public void run() { 10322 mHandler.removeCallbacks(this); 10323 final boolean succeded; 10324 synchronized (mInstallLock) { 10325 succeded = deleteApplicationCacheFilesLI(packageName, userId); 10326 } 10327 clearExternalStorageDataSync(packageName, userId, false); 10328 if(observer != null) { 10329 try { 10330 observer.onRemoveCompleted(packageName, succeded); 10331 } catch (RemoteException e) { 10332 Log.i(TAG, "Observer no longer exists."); 10333 } 10334 } //end if observer 10335 } //end run 10336 }); 10337 } 10338 10339 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 10340 if (packageName == null) { 10341 Slog.w(TAG, "Attempt to delete null packageName."); 10342 return false; 10343 } 10344 PackageParser.Package p; 10345 synchronized (mPackages) { 10346 p = mPackages.get(packageName); 10347 } 10348 if (p == null) { 10349 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 10350 return false; 10351 } 10352 final ApplicationInfo applicationInfo = p.applicationInfo; 10353 if (applicationInfo == null) { 10354 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10355 return false; 10356 } 10357 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 10358 if (retCode < 0) { 10359 Slog.w(TAG, "Couldn't remove cache files for package: " 10360 + packageName + " u" + userId); 10361 return false; 10362 } 10363 return true; 10364 } 10365 10366 public void getPackageSizeInfo(final String packageName, int userHandle, 10367 final IPackageStatsObserver observer) { 10368 mContext.enforceCallingOrSelfPermission( 10369 android.Manifest.permission.GET_PACKAGE_SIZE, null); 10370 if (packageName == null) { 10371 throw new IllegalArgumentException("Attempt to get size of null packageName"); 10372 } 10373 10374 PackageStats stats = new PackageStats(packageName, userHandle); 10375 10376 /* 10377 * Queue up an async operation since the package measurement may take a 10378 * little while. 10379 */ 10380 Message msg = mHandler.obtainMessage(INIT_COPY); 10381 msg.obj = new MeasureParams(stats, observer); 10382 mHandler.sendMessage(msg); 10383 } 10384 10385 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 10386 PackageStats pStats) { 10387 if (packageName == null) { 10388 Slog.w(TAG, "Attempt to get size of null packageName."); 10389 return false; 10390 } 10391 PackageParser.Package p; 10392 boolean dataOnly = false; 10393 String libDirPath = null; 10394 String asecPath = null; 10395 synchronized (mPackages) { 10396 p = mPackages.get(packageName); 10397 PackageSetting ps = mSettings.mPackages.get(packageName); 10398 if(p == null) { 10399 dataOnly = true; 10400 if((ps == null) || (ps.pkg == null)) { 10401 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 10402 return false; 10403 } 10404 p = ps.pkg; 10405 } 10406 if (ps != null) { 10407 libDirPath = ps.nativeLibraryPathString; 10408 } 10409 if (p != null && (isExternal(p) || isForwardLocked(p))) { 10410 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 10411 if (secureContainerId != null) { 10412 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 10413 } 10414 } 10415 } 10416 String publicSrcDir = null; 10417 if(!dataOnly) { 10418 final ApplicationInfo applicationInfo = p.applicationInfo; 10419 if (applicationInfo == null) { 10420 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10421 return false; 10422 } 10423 if (isForwardLocked(p)) { 10424 publicSrcDir = applicationInfo.publicSourceDir; 10425 } 10426 } 10427 int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath, 10428 publicSrcDir, asecPath, pStats); 10429 if (res < 0) { 10430 return false; 10431 } 10432 10433 // Fix-up for forward-locked applications in ASEC containers. 10434 if (!isExternal(p)) { 10435 pStats.codeSize += pStats.externalCodeSize; 10436 pStats.externalCodeSize = 0L; 10437 } 10438 10439 return true; 10440 } 10441 10442 10443 public void addPackageToPreferred(String packageName) { 10444 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 10445 } 10446 10447 public void removePackageFromPreferred(String packageName) { 10448 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 10449 } 10450 10451 public List<PackageInfo> getPreferredPackages(int flags) { 10452 return new ArrayList<PackageInfo>(); 10453 } 10454 10455 private int getUidTargetSdkVersionLockedLPr(int uid) { 10456 Object obj = mSettings.getUserIdLPr(uid); 10457 if (obj instanceof SharedUserSetting) { 10458 final SharedUserSetting sus = (SharedUserSetting) obj; 10459 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 10460 final Iterator<PackageSetting> it = sus.packages.iterator(); 10461 while (it.hasNext()) { 10462 final PackageSetting ps = it.next(); 10463 if (ps.pkg != null) { 10464 int v = ps.pkg.applicationInfo.targetSdkVersion; 10465 if (v < vers) vers = v; 10466 } 10467 } 10468 return vers; 10469 } else if (obj instanceof PackageSetting) { 10470 final PackageSetting ps = (PackageSetting) obj; 10471 if (ps.pkg != null) { 10472 return ps.pkg.applicationInfo.targetSdkVersion; 10473 } 10474 } 10475 return Build.VERSION_CODES.CUR_DEVELOPMENT; 10476 } 10477 10478 public void addPreferredActivity(IntentFilter filter, int match, 10479 ComponentName[] set, ComponentName activity, int userId) { 10480 addPreferredActivityInternal(filter, match, set, activity, true, userId); 10481 } 10482 10483 private void addPreferredActivityInternal(IntentFilter filter, int match, 10484 ComponentName[] set, ComponentName activity, boolean always, int userId) { 10485 // writer 10486 int callingUid = Binder.getCallingUid(); 10487 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 10488 if (filter.countActions() == 0) { 10489 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 10490 return; 10491 } 10492 synchronized (mPackages) { 10493 if (mContext.checkCallingOrSelfPermission( 10494 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10495 != PackageManager.PERMISSION_GRANTED) { 10496 if (getUidTargetSdkVersionLockedLPr(callingUid) 10497 < Build.VERSION_CODES.FROYO) { 10498 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 10499 + callingUid); 10500 return; 10501 } 10502 mContext.enforceCallingOrSelfPermission( 10503 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10504 } 10505 10506 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 10507 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10508 mSettings.editPreferredActivitiesLPw(userId).addFilter( 10509 new PreferredActivity(filter, match, set, activity, always)); 10510 mSettings.writePackageRestrictionsLPr(userId); 10511 } 10512 } 10513 10514 public void replacePreferredActivity(IntentFilter filter, int match, 10515 ComponentName[] set, ComponentName activity) { 10516 if (filter.countActions() != 1) { 10517 throw new IllegalArgumentException( 10518 "replacePreferredActivity expects filter to have only 1 action."); 10519 } 10520 if (filter.countDataAuthorities() != 0 10521 || filter.countDataPaths() != 0 10522 || filter.countDataSchemes() > 1 10523 || filter.countDataTypes() != 0) { 10524 throw new IllegalArgumentException( 10525 "replacePreferredActivity expects filter to have no data authorities, " + 10526 "paths, or types; and at most one scheme."); 10527 } 10528 synchronized (mPackages) { 10529 if (mContext.checkCallingOrSelfPermission( 10530 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10531 != PackageManager.PERMISSION_GRANTED) { 10532 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 10533 < Build.VERSION_CODES.FROYO) { 10534 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 10535 + Binder.getCallingUid()); 10536 return; 10537 } 10538 mContext.enforceCallingOrSelfPermission( 10539 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10540 } 10541 10542 final int callingUserId = UserHandle.getCallingUserId(); 10543 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 10544 if (pir != null) { 10545 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 10546 if (filter.countDataSchemes() == 1) { 10547 Uri.Builder builder = new Uri.Builder(); 10548 builder.scheme(filter.getDataScheme(0)); 10549 intent.setData(builder.build()); 10550 } 10551 List<PreferredActivity> matches = pir.queryIntent( 10552 intent, null, true, callingUserId); 10553 if (DEBUG_PREFERRED) { 10554 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 10555 } 10556 for (int i = 0; i < matches.size(); i++) { 10557 PreferredActivity pa = matches.get(i); 10558 if (DEBUG_PREFERRED) { 10559 Slog.i(TAG, "Removing preferred activity " 10560 + pa.mPref.mComponent + ":"); 10561 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10562 } 10563 pir.removeFilter(pa); 10564 } 10565 } 10566 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 10567 } 10568 } 10569 10570 public void clearPackagePreferredActivities(String packageName) { 10571 final int uid = Binder.getCallingUid(); 10572 // writer 10573 synchronized (mPackages) { 10574 PackageParser.Package pkg = mPackages.get(packageName); 10575 if (pkg == null || pkg.applicationInfo.uid != uid) { 10576 if (mContext.checkCallingOrSelfPermission( 10577 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10578 != PackageManager.PERMISSION_GRANTED) { 10579 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 10580 < Build.VERSION_CODES.FROYO) { 10581 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 10582 + Binder.getCallingUid()); 10583 return; 10584 } 10585 mContext.enforceCallingOrSelfPermission( 10586 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10587 } 10588 } 10589 10590 int user = UserHandle.getCallingUserId(); 10591 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 10592 mSettings.writePackageRestrictionsLPr(user); 10593 scheduleWriteSettingsLocked(); 10594 } 10595 } 10596 } 10597 10598 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 10599 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 10600 ArrayList<PreferredActivity> removed = null; 10601 boolean changed = false; 10602 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 10603 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 10604 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 10605 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 10606 continue; 10607 } 10608 Iterator<PreferredActivity> it = pir.filterIterator(); 10609 while (it.hasNext()) { 10610 PreferredActivity pa = it.next(); 10611 // Mark entry for removal only if it matches the package name 10612 // and the entry is of type "always". 10613 if (packageName == null || 10614 (pa.mPref.mComponent.getPackageName().equals(packageName) 10615 && pa.mPref.mAlways)) { 10616 if (removed == null) { 10617 removed = new ArrayList<PreferredActivity>(); 10618 } 10619 removed.add(pa); 10620 } 10621 } 10622 if (removed != null) { 10623 for (int j=0; j<removed.size(); j++) { 10624 PreferredActivity pa = removed.get(j); 10625 pir.removeFilter(pa); 10626 } 10627 changed = true; 10628 } 10629 } 10630 return changed; 10631 } 10632 10633 public void resetPreferredActivities(int userId) { 10634 mContext.enforceCallingOrSelfPermission( 10635 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10636 // writer 10637 synchronized (mPackages) { 10638 int user = UserHandle.getCallingUserId(); 10639 clearPackagePreferredActivitiesLPw(null, user); 10640 mSettings.readDefaultPreferredAppsLPw(this, user); 10641 mSettings.writePackageRestrictionsLPr(user); 10642 scheduleWriteSettingsLocked(); 10643 } 10644 } 10645 10646 public int getPreferredActivities(List<IntentFilter> outFilters, 10647 List<ComponentName> outActivities, String packageName) { 10648 10649 int num = 0; 10650 final int userId = UserHandle.getCallingUserId(); 10651 // reader 10652 synchronized (mPackages) { 10653 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 10654 if (pir != null) { 10655 final Iterator<PreferredActivity> it = pir.filterIterator(); 10656 while (it.hasNext()) { 10657 final PreferredActivity pa = it.next(); 10658 if (packageName == null 10659 || (pa.mPref.mComponent.getPackageName().equals(packageName) 10660 && pa.mPref.mAlways)) { 10661 if (outFilters != null) { 10662 outFilters.add(new IntentFilter(pa)); 10663 } 10664 if (outActivities != null) { 10665 outActivities.add(pa.mPref.mComponent); 10666 } 10667 } 10668 } 10669 } 10670 } 10671 10672 return num; 10673 } 10674 10675 @Override 10676 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 10677 int userId) { 10678 int callingUid = Binder.getCallingUid(); 10679 if (callingUid != Process.SYSTEM_UID) { 10680 throw new SecurityException( 10681 "addPersistentPreferredActivity can only be run by the system"); 10682 } 10683 if (filter.countActions() == 0) { 10684 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 10685 return; 10686 } 10687 synchronized (mPackages) { 10688 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 10689 " :"); 10690 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10691 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 10692 new PersistentPreferredActivity(filter, activity)); 10693 mSettings.writePackageRestrictionsLPr(userId); 10694 } 10695 } 10696 10697 @Override 10698 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 10699 int callingUid = Binder.getCallingUid(); 10700 if (callingUid != Process.SYSTEM_UID) { 10701 throw new SecurityException( 10702 "clearPackagePersistentPreferredActivities can only be run by the system"); 10703 } 10704 ArrayList<PersistentPreferredActivity> removed = null; 10705 boolean changed = false; 10706 synchronized (mPackages) { 10707 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 10708 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 10709 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 10710 .valueAt(i); 10711 if (userId != thisUserId) { 10712 continue; 10713 } 10714 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 10715 while (it.hasNext()) { 10716 PersistentPreferredActivity ppa = it.next(); 10717 // Mark entry for removal only if it matches the package name. 10718 if (ppa.mComponent.getPackageName().equals(packageName)) { 10719 if (removed == null) { 10720 removed = new ArrayList<PersistentPreferredActivity>(); 10721 } 10722 removed.add(ppa); 10723 } 10724 } 10725 if (removed != null) { 10726 for (int j=0; j<removed.size(); j++) { 10727 PersistentPreferredActivity ppa = removed.get(j); 10728 ppir.removeFilter(ppa); 10729 } 10730 changed = true; 10731 } 10732 } 10733 10734 if (changed) { 10735 mSettings.writePackageRestrictionsLPr(userId); 10736 } 10737 } 10738 } 10739 10740 @Override 10741 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 10742 Intent intent = new Intent(Intent.ACTION_MAIN); 10743 intent.addCategory(Intent.CATEGORY_HOME); 10744 10745 final int callingUserId = UserHandle.getCallingUserId(); 10746 List<ResolveInfo> list = queryIntentActivities(intent, null, 10747 PackageManager.GET_META_DATA, callingUserId); 10748 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 10749 true, false, false, callingUserId); 10750 10751 allHomeCandidates.clear(); 10752 if (list != null) { 10753 for (ResolveInfo ri : list) { 10754 allHomeCandidates.add(ri); 10755 } 10756 } 10757 return (preferred == null || preferred.activityInfo == null) 10758 ? null 10759 : new ComponentName(preferred.activityInfo.packageName, 10760 preferred.activityInfo.name); 10761 } 10762 10763 @Override 10764 public void setApplicationEnabledSetting(String appPackageName, 10765 int newState, int flags, int userId, String callingPackage) { 10766 if (!sUserManager.exists(userId)) return; 10767 if (callingPackage == null) { 10768 callingPackage = Integer.toString(Binder.getCallingUid()); 10769 } 10770 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 10771 } 10772 10773 @Override 10774 public void setComponentEnabledSetting(ComponentName componentName, 10775 int newState, int flags, int userId) { 10776 if (!sUserManager.exists(userId)) return; 10777 setEnabledSetting(componentName.getPackageName(), 10778 componentName.getClassName(), newState, flags, userId, null); 10779 } 10780 10781 private void setEnabledSetting(final String packageName, String className, int newState, 10782 final int flags, int userId, String callingPackage) { 10783 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 10784 || newState == COMPONENT_ENABLED_STATE_ENABLED 10785 || newState == COMPONENT_ENABLED_STATE_DISABLED 10786 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 10787 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 10788 throw new IllegalArgumentException("Invalid new component state: " 10789 + newState); 10790 } 10791 PackageSetting pkgSetting; 10792 final int uid = Binder.getCallingUid(); 10793 final int permission = mContext.checkCallingOrSelfPermission( 10794 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 10795 enforceCrossUserPermission(uid, userId, false, "set enabled"); 10796 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 10797 boolean sendNow = false; 10798 boolean isApp = (className == null); 10799 String componentName = isApp ? packageName : className; 10800 int packageUid = -1; 10801 ArrayList<String> components; 10802 10803 // writer 10804 synchronized (mPackages) { 10805 pkgSetting = mSettings.mPackages.get(packageName); 10806 if (pkgSetting == null) { 10807 if (className == null) { 10808 throw new IllegalArgumentException( 10809 "Unknown package: " + packageName); 10810 } 10811 throw new IllegalArgumentException( 10812 "Unknown component: " + packageName 10813 + "/" + className); 10814 } 10815 // Allow root and verify that userId is not being specified by a different user 10816 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 10817 throw new SecurityException( 10818 "Permission Denial: attempt to change component state from pid=" 10819 + Binder.getCallingPid() 10820 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 10821 } 10822 if (className == null) { 10823 // We're dealing with an application/package level state change 10824 if (pkgSetting.getEnabled(userId) == newState) { 10825 // Nothing to do 10826 return; 10827 } 10828 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 10829 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 10830 // Don't care about who enables an app. 10831 callingPackage = null; 10832 } 10833 pkgSetting.setEnabled(newState, userId, callingPackage); 10834 // pkgSetting.pkg.mSetEnabled = newState; 10835 } else { 10836 // We're dealing with a component level state change 10837 // First, verify that this is a valid class name. 10838 PackageParser.Package pkg = pkgSetting.pkg; 10839 if (pkg == null || !pkg.hasComponentClassName(className)) { 10840 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 10841 throw new IllegalArgumentException("Component class " + className 10842 + " does not exist in " + packageName); 10843 } else { 10844 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 10845 + className + " does not exist in " + packageName); 10846 } 10847 } 10848 switch (newState) { 10849 case COMPONENT_ENABLED_STATE_ENABLED: 10850 if (!pkgSetting.enableComponentLPw(className, userId)) { 10851 return; 10852 } 10853 break; 10854 case COMPONENT_ENABLED_STATE_DISABLED: 10855 if (!pkgSetting.disableComponentLPw(className, userId)) { 10856 return; 10857 } 10858 break; 10859 case COMPONENT_ENABLED_STATE_DEFAULT: 10860 if (!pkgSetting.restoreComponentLPw(className, userId)) { 10861 return; 10862 } 10863 break; 10864 default: 10865 Slog.e(TAG, "Invalid new component state: " + newState); 10866 return; 10867 } 10868 } 10869 mSettings.writePackageRestrictionsLPr(userId); 10870 components = mPendingBroadcasts.get(userId, packageName); 10871 final boolean newPackage = components == null; 10872 if (newPackage) { 10873 components = new ArrayList<String>(); 10874 } 10875 if (!components.contains(componentName)) { 10876 components.add(componentName); 10877 } 10878 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 10879 sendNow = true; 10880 // Purge entry from pending broadcast list if another one exists already 10881 // since we are sending one right away. 10882 mPendingBroadcasts.remove(userId, packageName); 10883 } else { 10884 if (newPackage) { 10885 mPendingBroadcasts.put(userId, packageName, components); 10886 } 10887 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 10888 // Schedule a message 10889 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 10890 } 10891 } 10892 } 10893 10894 long callingId = Binder.clearCallingIdentity(); 10895 try { 10896 if (sendNow) { 10897 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 10898 sendPackageChangedBroadcast(packageName, 10899 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 10900 } 10901 } finally { 10902 Binder.restoreCallingIdentity(callingId); 10903 } 10904 } 10905 10906 private void sendPackageChangedBroadcast(String packageName, 10907 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 10908 if (DEBUG_INSTALL) 10909 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 10910 + componentNames); 10911 Bundle extras = new Bundle(4); 10912 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 10913 String nameList[] = new String[componentNames.size()]; 10914 componentNames.toArray(nameList); 10915 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 10916 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 10917 extras.putInt(Intent.EXTRA_UID, packageUid); 10918 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 10919 new int[] {UserHandle.getUserId(packageUid)}); 10920 } 10921 10922 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 10923 if (!sUserManager.exists(userId)) return; 10924 final int uid = Binder.getCallingUid(); 10925 final int permission = mContext.checkCallingOrSelfPermission( 10926 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 10927 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 10928 enforceCrossUserPermission(uid, userId, true, "stop package"); 10929 // writer 10930 synchronized (mPackages) { 10931 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 10932 uid, userId)) { 10933 scheduleWritePackageRestrictionsLocked(userId); 10934 } 10935 } 10936 } 10937 10938 public String getInstallerPackageName(String packageName) { 10939 // reader 10940 synchronized (mPackages) { 10941 return mSettings.getInstallerPackageNameLPr(packageName); 10942 } 10943 } 10944 10945 @Override 10946 public int getApplicationEnabledSetting(String packageName, int userId) { 10947 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 10948 int uid = Binder.getCallingUid(); 10949 enforceCrossUserPermission(uid, userId, false, "get enabled"); 10950 // reader 10951 synchronized (mPackages) { 10952 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 10953 } 10954 } 10955 10956 @Override 10957 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 10958 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 10959 int uid = Binder.getCallingUid(); 10960 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 10961 // reader 10962 synchronized (mPackages) { 10963 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 10964 } 10965 } 10966 10967 public void enterSafeMode() { 10968 enforceSystemOrRoot("Only the system can request entering safe mode"); 10969 10970 if (!mSystemReady) { 10971 mSafeMode = true; 10972 } 10973 } 10974 10975 public void systemReady() { 10976 mSystemReady = true; 10977 10978 // Read the compatibilty setting when the system is ready. 10979 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 10980 mContext.getContentResolver(), 10981 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 10982 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 10983 if (DEBUG_SETTINGS) { 10984 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 10985 } 10986 10987 synchronized (mPackages) { 10988 // Verify that all of the preferred activity components actually 10989 // exist. It is possible for applications to be updated and at 10990 // that point remove a previously declared activity component that 10991 // had been set as a preferred activity. We try to clean this up 10992 // the next time we encounter that preferred activity, but it is 10993 // possible for the user flow to never be able to return to that 10994 // situation so here we do a sanity check to make sure we haven't 10995 // left any junk around. 10996 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 10997 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 10998 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 10999 removed.clear(); 11000 for (PreferredActivity pa : pir.filterSet()) { 11001 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11002 removed.add(pa); 11003 } 11004 } 11005 if (removed.size() > 0) { 11006 for (int j=0; j<removed.size(); j++) { 11007 PreferredActivity pa = removed.get(i); 11008 Slog.w(TAG, "Removing dangling preferred activity: " 11009 + pa.mPref.mComponent); 11010 pir.removeFilter(pa); 11011 } 11012 mSettings.writePackageRestrictionsLPr( 11013 mSettings.mPreferredActivities.keyAt(i)); 11014 } 11015 } 11016 } 11017 sUserManager.systemReady(); 11018 } 11019 11020 public boolean isSafeMode() { 11021 return mSafeMode; 11022 } 11023 11024 public boolean hasSystemUidErrors() { 11025 return mHasSystemUidErrors; 11026 } 11027 11028 static String arrayToString(int[] array) { 11029 StringBuffer buf = new StringBuffer(128); 11030 buf.append('['); 11031 if (array != null) { 11032 for (int i=0; i<array.length; i++) { 11033 if (i > 0) buf.append(", "); 11034 buf.append(array[i]); 11035 } 11036 } 11037 buf.append(']'); 11038 return buf.toString(); 11039 } 11040 11041 static class DumpState { 11042 public static final int DUMP_LIBS = 1 << 0; 11043 11044 public static final int DUMP_FEATURES = 1 << 1; 11045 11046 public static final int DUMP_RESOLVERS = 1 << 2; 11047 11048 public static final int DUMP_PERMISSIONS = 1 << 3; 11049 11050 public static final int DUMP_PACKAGES = 1 << 4; 11051 11052 public static final int DUMP_SHARED_USERS = 1 << 5; 11053 11054 public static final int DUMP_MESSAGES = 1 << 6; 11055 11056 public static final int DUMP_PROVIDERS = 1 << 7; 11057 11058 public static final int DUMP_VERIFIERS = 1 << 8; 11059 11060 public static final int DUMP_PREFERRED = 1 << 9; 11061 11062 public static final int DUMP_PREFERRED_XML = 1 << 10; 11063 11064 public static final int DUMP_KEYSETS = 1 << 11; 11065 11066 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11067 11068 private int mTypes; 11069 11070 private int mOptions; 11071 11072 private boolean mTitlePrinted; 11073 11074 private SharedUserSetting mSharedUser; 11075 11076 public boolean isDumping(int type) { 11077 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11078 return true; 11079 } 11080 11081 return (mTypes & type) != 0; 11082 } 11083 11084 public void setDump(int type) { 11085 mTypes |= type; 11086 } 11087 11088 public boolean isOptionEnabled(int option) { 11089 return (mOptions & option) != 0; 11090 } 11091 11092 public void setOptionEnabled(int option) { 11093 mOptions |= option; 11094 } 11095 11096 public boolean onTitlePrinted() { 11097 final boolean printed = mTitlePrinted; 11098 mTitlePrinted = true; 11099 return printed; 11100 } 11101 11102 public boolean getTitlePrinted() { 11103 return mTitlePrinted; 11104 } 11105 11106 public void setTitlePrinted(boolean enabled) { 11107 mTitlePrinted = enabled; 11108 } 11109 11110 public SharedUserSetting getSharedUser() { 11111 return mSharedUser; 11112 } 11113 11114 public void setSharedUser(SharedUserSetting user) { 11115 mSharedUser = user; 11116 } 11117 } 11118 11119 @Override 11120 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 11121 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 11122 != PackageManager.PERMISSION_GRANTED) { 11123 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 11124 + Binder.getCallingPid() 11125 + ", uid=" + Binder.getCallingUid() 11126 + " without permission " 11127 + android.Manifest.permission.DUMP); 11128 return; 11129 } 11130 11131 DumpState dumpState = new DumpState(); 11132 boolean fullPreferred = false; 11133 boolean checkin = false; 11134 11135 String packageName = null; 11136 11137 int opti = 0; 11138 while (opti < args.length) { 11139 String opt = args[opti]; 11140 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 11141 break; 11142 } 11143 opti++; 11144 if ("-a".equals(opt)) { 11145 // Right now we only know how to print all. 11146 } else if ("-h".equals(opt)) { 11147 pw.println("Package manager dump options:"); 11148 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 11149 pw.println(" --checkin: dump for a checkin"); 11150 pw.println(" -f: print details of intent filters"); 11151 pw.println(" -h: print this help"); 11152 pw.println(" cmd may be one of:"); 11153 pw.println(" l[ibraries]: list known shared libraries"); 11154 pw.println(" f[ibraries]: list device features"); 11155 pw.println(" r[esolvers]: dump intent resolvers"); 11156 pw.println(" perm[issions]: dump permissions"); 11157 pw.println(" pref[erred]: print preferred package settings"); 11158 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 11159 pw.println(" prov[iders]: dump content providers"); 11160 pw.println(" p[ackages]: dump installed packages"); 11161 pw.println(" s[hared-users]: dump shared user IDs"); 11162 pw.println(" m[essages]: print collected runtime messages"); 11163 pw.println(" v[erifiers]: print package verifier info"); 11164 pw.println(" <package.name>: info about given package"); 11165 pw.println(" k[eysets]: print known keysets"); 11166 return; 11167 } else if ("--checkin".equals(opt)) { 11168 checkin = true; 11169 } else if ("-f".equals(opt)) { 11170 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11171 } else { 11172 pw.println("Unknown argument: " + opt + "; use -h for help"); 11173 } 11174 } 11175 11176 // Is the caller requesting to dump a particular piece of data? 11177 if (opti < args.length) { 11178 String cmd = args[opti]; 11179 opti++; 11180 // Is this a package name? 11181 if ("android".equals(cmd) || cmd.contains(".")) { 11182 packageName = cmd; 11183 // When dumping a single package, we always dump all of its 11184 // filter information since the amount of data will be reasonable. 11185 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11186 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 11187 dumpState.setDump(DumpState.DUMP_LIBS); 11188 } else if ("f".equals(cmd) || "features".equals(cmd)) { 11189 dumpState.setDump(DumpState.DUMP_FEATURES); 11190 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 11191 dumpState.setDump(DumpState.DUMP_RESOLVERS); 11192 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 11193 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 11194 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 11195 dumpState.setDump(DumpState.DUMP_PREFERRED); 11196 } else if ("preferred-xml".equals(cmd)) { 11197 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 11198 if (opti < args.length && "--full".equals(args[opti])) { 11199 fullPreferred = true; 11200 opti++; 11201 } 11202 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 11203 dumpState.setDump(DumpState.DUMP_PACKAGES); 11204 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 11205 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 11206 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 11207 dumpState.setDump(DumpState.DUMP_PROVIDERS); 11208 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 11209 dumpState.setDump(DumpState.DUMP_MESSAGES); 11210 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 11211 dumpState.setDump(DumpState.DUMP_VERIFIERS); 11212 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 11213 dumpState.setDump(DumpState.DUMP_KEYSETS); 11214 } 11215 } 11216 11217 if (checkin) { 11218 pw.println("vers,1"); 11219 } 11220 11221 // reader 11222 synchronized (mPackages) { 11223 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 11224 if (!checkin) { 11225 if (dumpState.onTitlePrinted()) 11226 pw.println(); 11227 pw.println("Verifiers:"); 11228 pw.print(" Required: "); 11229 pw.print(mRequiredVerifierPackage); 11230 pw.print(" (uid="); 11231 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 11232 pw.println(")"); 11233 } else if (mRequiredVerifierPackage != null) { 11234 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 11235 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 11236 } 11237 } 11238 11239 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 11240 boolean printedHeader = false; 11241 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 11242 while (it.hasNext()) { 11243 String name = it.next(); 11244 SharedLibraryEntry ent = mSharedLibraries.get(name); 11245 if (!checkin) { 11246 if (!printedHeader) { 11247 if (dumpState.onTitlePrinted()) 11248 pw.println(); 11249 pw.println("Libraries:"); 11250 printedHeader = true; 11251 } 11252 pw.print(" "); 11253 } else { 11254 pw.print("lib,"); 11255 } 11256 pw.print(name); 11257 if (!checkin) { 11258 pw.print(" -> "); 11259 } 11260 if (ent.path != null) { 11261 if (!checkin) { 11262 pw.print("(jar) "); 11263 pw.print(ent.path); 11264 } else { 11265 pw.print(",jar,"); 11266 pw.print(ent.path); 11267 } 11268 } else { 11269 if (!checkin) { 11270 pw.print("(apk) "); 11271 pw.print(ent.apk); 11272 } else { 11273 pw.print(",apk,"); 11274 pw.print(ent.apk); 11275 } 11276 } 11277 pw.println(); 11278 } 11279 } 11280 11281 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 11282 if (dumpState.onTitlePrinted()) 11283 pw.println(); 11284 if (!checkin) { 11285 pw.println("Features:"); 11286 } 11287 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 11288 while (it.hasNext()) { 11289 String name = it.next(); 11290 if (!checkin) { 11291 pw.print(" "); 11292 } else { 11293 pw.print("feat,"); 11294 } 11295 pw.println(name); 11296 } 11297 } 11298 11299 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 11300 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 11301 : "Activity Resolver Table:", " ", packageName, 11302 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11303 dumpState.setTitlePrinted(true); 11304 } 11305 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 11306 : "Receiver Resolver Table:", " ", packageName, 11307 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11308 dumpState.setTitlePrinted(true); 11309 } 11310 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 11311 : "Service Resolver Table:", " ", packageName, 11312 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11313 dumpState.setTitlePrinted(true); 11314 } 11315 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 11316 : "Provider Resolver Table:", " ", packageName, 11317 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11318 dumpState.setTitlePrinted(true); 11319 } 11320 } 11321 11322 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 11323 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11324 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11325 int user = mSettings.mPreferredActivities.keyAt(i); 11326 if (pir.dump(pw, 11327 dumpState.getTitlePrinted() 11328 ? "\nPreferred Activities User " + user + ":" 11329 : "Preferred Activities User " + user + ":", " ", 11330 packageName, true)) { 11331 dumpState.setTitlePrinted(true); 11332 } 11333 } 11334 } 11335 11336 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 11337 pw.flush(); 11338 FileOutputStream fout = new FileOutputStream(fd); 11339 BufferedOutputStream str = new BufferedOutputStream(fout); 11340 XmlSerializer serializer = new FastXmlSerializer(); 11341 try { 11342 serializer.setOutput(str, "utf-8"); 11343 serializer.startDocument(null, true); 11344 serializer.setFeature( 11345 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 11346 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 11347 serializer.endDocument(); 11348 serializer.flush(); 11349 } catch (IllegalArgumentException e) { 11350 pw.println("Failed writing: " + e); 11351 } catch (IllegalStateException e) { 11352 pw.println("Failed writing: " + e); 11353 } catch (IOException e) { 11354 pw.println("Failed writing: " + e); 11355 } 11356 } 11357 11358 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 11359 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 11360 } 11361 11362 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 11363 boolean printedSomething = false; 11364 for (PackageParser.Provider p : mProviders.mProviders.values()) { 11365 if (packageName != null && !packageName.equals(p.info.packageName)) { 11366 continue; 11367 } 11368 if (!printedSomething) { 11369 if (dumpState.onTitlePrinted()) 11370 pw.println(); 11371 pw.println("Registered ContentProviders:"); 11372 printedSomething = true; 11373 } 11374 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 11375 pw.print(" "); pw.println(p.toString()); 11376 } 11377 printedSomething = false; 11378 for (Map.Entry<String, PackageParser.Provider> entry : 11379 mProvidersByAuthority.entrySet()) { 11380 PackageParser.Provider p = entry.getValue(); 11381 if (packageName != null && !packageName.equals(p.info.packageName)) { 11382 continue; 11383 } 11384 if (!printedSomething) { 11385 if (dumpState.onTitlePrinted()) 11386 pw.println(); 11387 pw.println("ContentProvider Authorities:"); 11388 printedSomething = true; 11389 } 11390 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 11391 pw.print(" "); pw.println(p.toString()); 11392 if (p.info != null && p.info.applicationInfo != null) { 11393 final String appInfo = p.info.applicationInfo.toString(); 11394 pw.print(" applicationInfo="); pw.println(appInfo); 11395 } 11396 } 11397 } 11398 11399 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 11400 mSettings.mKeySetManager.dump(pw, packageName, dumpState); 11401 } 11402 11403 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 11404 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 11405 } 11406 11407 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 11408 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 11409 } 11410 11411 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 11412 if (dumpState.onTitlePrinted()) 11413 pw.println(); 11414 mSettings.dumpReadMessagesLPr(pw, dumpState); 11415 11416 pw.println(); 11417 pw.println("Package warning messages:"); 11418 final File fname = getSettingsProblemFile(); 11419 FileInputStream in = null; 11420 try { 11421 in = new FileInputStream(fname); 11422 final int avail = in.available(); 11423 final byte[] data = new byte[avail]; 11424 in.read(data); 11425 pw.print(new String(data)); 11426 } catch (FileNotFoundException e) { 11427 } catch (IOException e) { 11428 } finally { 11429 if (in != null) { 11430 try { 11431 in.close(); 11432 } catch (IOException e) { 11433 } 11434 } 11435 } 11436 } 11437 } 11438 } 11439 11440 // ------- apps on sdcard specific code ------- 11441 static final boolean DEBUG_SD_INSTALL = false; 11442 11443 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 11444 11445 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 11446 11447 private boolean mMediaMounted = false; 11448 11449 private String getEncryptKey() { 11450 try { 11451 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 11452 SD_ENCRYPTION_KEYSTORE_NAME); 11453 if (sdEncKey == null) { 11454 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 11455 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 11456 if (sdEncKey == null) { 11457 Slog.e(TAG, "Failed to create encryption keys"); 11458 return null; 11459 } 11460 } 11461 return sdEncKey; 11462 } catch (NoSuchAlgorithmException nsae) { 11463 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 11464 return null; 11465 } catch (IOException ioe) { 11466 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 11467 return null; 11468 } 11469 11470 } 11471 11472 /* package */static String getTempContainerId() { 11473 int tmpIdx = 1; 11474 String list[] = PackageHelper.getSecureContainerList(); 11475 if (list != null) { 11476 for (final String name : list) { 11477 // Ignore null and non-temporary container entries 11478 if (name == null || !name.startsWith(mTempContainerPrefix)) { 11479 continue; 11480 } 11481 11482 String subStr = name.substring(mTempContainerPrefix.length()); 11483 try { 11484 int cid = Integer.parseInt(subStr); 11485 if (cid >= tmpIdx) { 11486 tmpIdx = cid + 1; 11487 } 11488 } catch (NumberFormatException e) { 11489 } 11490 } 11491 } 11492 return mTempContainerPrefix + tmpIdx; 11493 } 11494 11495 /* 11496 * Update media status on PackageManager. 11497 */ 11498 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 11499 int callingUid = Binder.getCallingUid(); 11500 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 11501 throw new SecurityException("Media status can only be updated by the system"); 11502 } 11503 // reader; this apparently protects mMediaMounted, but should probably 11504 // be a different lock in that case. 11505 synchronized (mPackages) { 11506 Log.i(TAG, "Updating external media status from " 11507 + (mMediaMounted ? "mounted" : "unmounted") + " to " 11508 + (mediaStatus ? "mounted" : "unmounted")); 11509 if (DEBUG_SD_INSTALL) 11510 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 11511 + ", mMediaMounted=" + mMediaMounted); 11512 if (mediaStatus == mMediaMounted) { 11513 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 11514 : 0, -1); 11515 mHandler.sendMessage(msg); 11516 return; 11517 } 11518 mMediaMounted = mediaStatus; 11519 } 11520 // Queue up an async operation since the package installation may take a 11521 // little while. 11522 mHandler.post(new Runnable() { 11523 public void run() { 11524 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 11525 } 11526 }); 11527 } 11528 11529 /** 11530 * Called by MountService when the initial ASECs to scan are available. 11531 * Should block until all the ASEC containers are finished being scanned. 11532 */ 11533 public void scanAvailableAsecs() { 11534 updateExternalMediaStatusInner(true, false, false); 11535 if (mShouldRestoreconData) { 11536 SELinuxMMAC.setRestoreconDone(); 11537 mShouldRestoreconData = false; 11538 } 11539 } 11540 11541 /* 11542 * Collect information of applications on external media, map them against 11543 * existing containers and update information based on current mount status. 11544 * Please note that we always have to report status if reportStatus has been 11545 * set to true especially when unloading packages. 11546 */ 11547 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 11548 boolean externalStorage) { 11549 // Collection of uids 11550 int uidArr[] = null; 11551 // Collection of stale containers 11552 HashSet<String> removeCids = new HashSet<String>(); 11553 // Collection of packages on external media with valid containers. 11554 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 11555 // Get list of secure containers. 11556 final String list[] = PackageHelper.getSecureContainerList(); 11557 if (list == null || list.length == 0) { 11558 Log.i(TAG, "No secure containers on sdcard"); 11559 } else { 11560 // Process list of secure containers and categorize them 11561 // as active or stale based on their package internal state. 11562 int uidList[] = new int[list.length]; 11563 int num = 0; 11564 // reader 11565 synchronized (mPackages) { 11566 for (String cid : list) { 11567 if (DEBUG_SD_INSTALL) 11568 Log.i(TAG, "Processing container " + cid); 11569 String pkgName = getAsecPackageName(cid); 11570 if (pkgName == null) { 11571 if (DEBUG_SD_INSTALL) 11572 Log.i(TAG, "Container : " + cid + " stale"); 11573 removeCids.add(cid); 11574 continue; 11575 } 11576 if (DEBUG_SD_INSTALL) 11577 Log.i(TAG, "Looking for pkg : " + pkgName); 11578 11579 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11580 if (ps == null) { 11581 Log.i(TAG, "Deleting container with no matching settings " + cid); 11582 removeCids.add(cid); 11583 continue; 11584 } 11585 11586 /* 11587 * Skip packages that are not external if we're unmounting 11588 * external storage. 11589 */ 11590 if (externalStorage && !isMounted && !isExternal(ps)) { 11591 continue; 11592 } 11593 11594 final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps)); 11595 // The package status is changed only if the code path 11596 // matches between settings and the container id. 11597 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 11598 if (DEBUG_SD_INSTALL) { 11599 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 11600 + " at code path: " + ps.codePathString); 11601 } 11602 11603 // We do have a valid package installed on sdcard 11604 processCids.put(args, ps.codePathString); 11605 final int uid = ps.appId; 11606 if (uid != -1) { 11607 uidList[num++] = uid; 11608 } 11609 } else { 11610 Log.i(TAG, "Deleting stale container for " + cid); 11611 removeCids.add(cid); 11612 } 11613 } 11614 } 11615 11616 if (num > 0) { 11617 // Sort uid list 11618 Arrays.sort(uidList, 0, num); 11619 // Throw away duplicates 11620 uidArr = new int[num]; 11621 uidArr[0] = uidList[0]; 11622 int di = 0; 11623 for (int i = 1; i < num; i++) { 11624 if (uidList[i - 1] != uidList[i]) { 11625 uidArr[di++] = uidList[i]; 11626 } 11627 } 11628 } 11629 } 11630 // Process packages with valid entries. 11631 if (isMounted) { 11632 if (DEBUG_SD_INSTALL) 11633 Log.i(TAG, "Loading packages"); 11634 loadMediaPackages(processCids, uidArr, removeCids); 11635 startCleaningPackages(); 11636 } else { 11637 if (DEBUG_SD_INSTALL) 11638 Log.i(TAG, "Unloading packages"); 11639 unloadMediaPackages(processCids, uidArr, reportStatus); 11640 } 11641 } 11642 11643 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 11644 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 11645 int size = pkgList.size(); 11646 if (size > 0) { 11647 // Send broadcasts here 11648 Bundle extras = new Bundle(); 11649 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 11650 .toArray(new String[size])); 11651 if (uidArr != null) { 11652 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 11653 } 11654 if (replacing) { 11655 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 11656 } 11657 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 11658 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 11659 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 11660 } 11661 } 11662 11663 /* 11664 * Look at potentially valid container ids from processCids If package 11665 * information doesn't match the one on record or package scanning fails, 11666 * the cid is added to list of removeCids. We currently don't delete stale 11667 * containers. 11668 */ 11669 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 11670 HashSet<String> removeCids) { 11671 ArrayList<String> pkgList = new ArrayList<String>(); 11672 Set<AsecInstallArgs> keys = processCids.keySet(); 11673 boolean doGc = false; 11674 for (AsecInstallArgs args : keys) { 11675 String codePath = processCids.get(args); 11676 if (DEBUG_SD_INSTALL) 11677 Log.i(TAG, "Loading container : " + args.cid); 11678 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11679 try { 11680 // Make sure there are no container errors first. 11681 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 11682 Slog.e(TAG, "Failed to mount cid : " + args.cid 11683 + " when installing from sdcard"); 11684 continue; 11685 } 11686 // Check code path here. 11687 if (codePath == null || !codePath.equals(args.getCodePath())) { 11688 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 11689 + " does not match one in settings " + codePath); 11690 continue; 11691 } 11692 // Parse package 11693 int parseFlags = mDefParseFlags; 11694 if (args.isExternal()) { 11695 parseFlags |= PackageParser.PARSE_ON_SDCARD; 11696 } 11697 if (args.isFwdLocked()) { 11698 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 11699 } 11700 11701 doGc = true; 11702 synchronized (mInstallLock) { 11703 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 11704 0, 0, null); 11705 // Scan the package 11706 if (pkg != null) { 11707 /* 11708 * TODO why is the lock being held? doPostInstall is 11709 * called in other places without the lock. This needs 11710 * to be straightened out. 11711 */ 11712 // writer 11713 synchronized (mPackages) { 11714 retCode = PackageManager.INSTALL_SUCCEEDED; 11715 pkgList.add(pkg.packageName); 11716 // Post process args 11717 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 11718 pkg.applicationInfo.uid); 11719 } 11720 } else { 11721 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 11722 } 11723 } 11724 11725 } finally { 11726 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 11727 // Don't destroy container here. Wait till gc clears things 11728 // up. 11729 removeCids.add(args.cid); 11730 } 11731 } 11732 } 11733 // writer 11734 synchronized (mPackages) { 11735 // If the platform SDK has changed since the last time we booted, 11736 // we need to re-grant app permission to catch any new ones that 11737 // appear. This is really a hack, and means that apps can in some 11738 // cases get permissions that the user didn't initially explicitly 11739 // allow... it would be nice to have some better way to handle 11740 // this situation. 11741 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 11742 if (regrantPermissions) 11743 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 11744 + mSdkVersion + "; regranting permissions for external storage"); 11745 mSettings.mExternalSdkPlatform = mSdkVersion; 11746 11747 // Make sure group IDs have been assigned, and any permission 11748 // changes in other apps are accounted for 11749 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 11750 | (regrantPermissions 11751 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 11752 : 0)); 11753 // can downgrade to reader 11754 // Persist settings 11755 mSettings.writeLPr(); 11756 } 11757 // Send a broadcast to let everyone know we are done processing 11758 if (pkgList.size() > 0) { 11759 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 11760 } 11761 // Force gc to avoid any stale parser references that we might have. 11762 if (doGc) { 11763 Runtime.getRuntime().gc(); 11764 } 11765 // List stale containers and destroy stale temporary containers. 11766 if (removeCids != null) { 11767 for (String cid : removeCids) { 11768 if (cid.startsWith(mTempContainerPrefix)) { 11769 Log.i(TAG, "Destroying stale temporary container " + cid); 11770 PackageHelper.destroySdDir(cid); 11771 } else { 11772 Log.w(TAG, "Container " + cid + " is stale"); 11773 } 11774 } 11775 } 11776 } 11777 11778 /* 11779 * Utility method to unload a list of specified containers 11780 */ 11781 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 11782 // Just unmount all valid containers. 11783 for (AsecInstallArgs arg : cidArgs) { 11784 synchronized (mInstallLock) { 11785 arg.doPostDeleteLI(false); 11786 } 11787 } 11788 } 11789 11790 /* 11791 * Unload packages mounted on external media. This involves deleting package 11792 * data from internal structures, sending broadcasts about diabled packages, 11793 * gc'ing to free up references, unmounting all secure containers 11794 * corresponding to packages on external media, and posting a 11795 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 11796 * that we always have to post this message if status has been requested no 11797 * matter what. 11798 */ 11799 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 11800 final boolean reportStatus) { 11801 if (DEBUG_SD_INSTALL) 11802 Log.i(TAG, "unloading media packages"); 11803 ArrayList<String> pkgList = new ArrayList<String>(); 11804 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 11805 final Set<AsecInstallArgs> keys = processCids.keySet(); 11806 for (AsecInstallArgs args : keys) { 11807 String pkgName = args.getPackageName(); 11808 if (DEBUG_SD_INSTALL) 11809 Log.i(TAG, "Trying to unload pkg : " + pkgName); 11810 // Delete package internally 11811 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 11812 synchronized (mInstallLock) { 11813 boolean res = deletePackageLI(pkgName, null, false, null, null, 11814 PackageManager.DELETE_KEEP_DATA, outInfo, false); 11815 if (res) { 11816 pkgList.add(pkgName); 11817 } else { 11818 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 11819 failedList.add(args); 11820 } 11821 } 11822 } 11823 11824 // reader 11825 synchronized (mPackages) { 11826 // We didn't update the settings after removing each package; 11827 // write them now for all packages. 11828 mSettings.writeLPr(); 11829 } 11830 11831 // We have to absolutely send UPDATED_MEDIA_STATUS only 11832 // after confirming that all the receivers processed the ordered 11833 // broadcast when packages get disabled, force a gc to clean things up. 11834 // and unload all the containers. 11835 if (pkgList.size() > 0) { 11836 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 11837 new IIntentReceiver.Stub() { 11838 public void performReceive(Intent intent, int resultCode, String data, 11839 Bundle extras, boolean ordered, boolean sticky, 11840 int sendingUser) throws RemoteException { 11841 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 11842 reportStatus ? 1 : 0, 1, keys); 11843 mHandler.sendMessage(msg); 11844 } 11845 }); 11846 } else { 11847 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 11848 keys); 11849 mHandler.sendMessage(msg); 11850 } 11851 } 11852 11853 /** Binder call */ 11854 @Override 11855 public void movePackage(final String packageName, final IPackageMoveObserver observer, 11856 final int flags) { 11857 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 11858 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 11859 int returnCode = PackageManager.MOVE_SUCCEEDED; 11860 int currFlags = 0; 11861 int newFlags = 0; 11862 // reader 11863 synchronized (mPackages) { 11864 PackageParser.Package pkg = mPackages.get(packageName); 11865 if (pkg == null) { 11866 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 11867 } else { 11868 // Disable moving fwd locked apps and system packages 11869 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 11870 Slog.w(TAG, "Cannot move system application"); 11871 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 11872 } else if (pkg.mOperationPending) { 11873 Slog.w(TAG, "Attempt to move package which has pending operations"); 11874 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 11875 } else { 11876 // Find install location first 11877 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 11878 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 11879 Slog.w(TAG, "Ambigous flags specified for move location."); 11880 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 11881 } else { 11882 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 11883 : PackageManager.INSTALL_INTERNAL; 11884 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 11885 : PackageManager.INSTALL_INTERNAL; 11886 11887 if (newFlags == currFlags) { 11888 Slog.w(TAG, "No move required. Trying to move to same location"); 11889 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 11890 } else { 11891 if (isForwardLocked(pkg)) { 11892 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11893 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11894 } 11895 } 11896 } 11897 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 11898 pkg.mOperationPending = true; 11899 } 11900 } 11901 } 11902 11903 /* 11904 * TODO this next block probably shouldn't be inside the lock. We 11905 * can't guarantee these won't change after this is fired off 11906 * anyway. 11907 */ 11908 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 11909 processPendingMove(new MoveParams(null, observer, 0, packageName, 11910 null, -1, user), 11911 returnCode); 11912 } else { 11913 Message msg = mHandler.obtainMessage(INIT_COPY); 11914 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir, 11915 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir); 11916 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 11917 pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user); 11918 msg.obj = mp; 11919 mHandler.sendMessage(msg); 11920 } 11921 } 11922 } 11923 11924 private void processPendingMove(final MoveParams mp, final int currentStatus) { 11925 // Queue up an async operation since the package deletion may take a 11926 // little while. 11927 mHandler.post(new Runnable() { 11928 public void run() { 11929 // TODO fix this; this does nothing. 11930 mHandler.removeCallbacks(this); 11931 int returnCode = currentStatus; 11932 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 11933 int uidArr[] = null; 11934 ArrayList<String> pkgList = null; 11935 synchronized (mPackages) { 11936 PackageParser.Package pkg = mPackages.get(mp.packageName); 11937 if (pkg == null) { 11938 Slog.w(TAG, " Package " + mp.packageName 11939 + " doesn't exist. Aborting move"); 11940 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 11941 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 11942 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 11943 + mp.srcArgs.getCodePath() + " to " 11944 + pkg.applicationInfo.sourceDir 11945 + " Aborting move and returning error"); 11946 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 11947 } else { 11948 uidArr = new int[] { 11949 pkg.applicationInfo.uid 11950 }; 11951 pkgList = new ArrayList<String>(); 11952 pkgList.add(mp.packageName); 11953 } 11954 } 11955 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 11956 // Send resources unavailable broadcast 11957 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 11958 // Update package code and resource paths 11959 synchronized (mInstallLock) { 11960 synchronized (mPackages) { 11961 PackageParser.Package pkg = mPackages.get(mp.packageName); 11962 // Recheck for package again. 11963 if (pkg == null) { 11964 Slog.w(TAG, " Package " + mp.packageName 11965 + " doesn't exist. Aborting move"); 11966 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 11967 } else if (!mp.srcArgs.getCodePath().equals( 11968 pkg.applicationInfo.sourceDir)) { 11969 Slog.w(TAG, "Package " + mp.packageName 11970 + " code path changed from " + mp.srcArgs.getCodePath() 11971 + " to " + pkg.applicationInfo.sourceDir 11972 + " Aborting move and returning error"); 11973 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 11974 } else { 11975 final String oldCodePath = pkg.mPath; 11976 final String newCodePath = mp.targetArgs.getCodePath(); 11977 final String newResPath = mp.targetArgs.getResourcePath(); 11978 final String newNativePath = mp.targetArgs 11979 .getNativeLibraryPath(); 11980 11981 final File newNativeDir = new File(newNativePath); 11982 11983 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 11984 // NOTE: We do not report any errors from the APK scan and library 11985 // copy at this point. 11986 NativeLibraryHelper.ApkHandle handle = 11987 new NativeLibraryHelper.ApkHandle(newCodePath); 11988 final int abi = NativeLibraryHelper.findSupportedAbi( 11989 handle, Build.SUPPORTED_ABIS); 11990 if (abi >= 0) { 11991 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 11992 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 11993 } 11994 handle.close(); 11995 } 11996 final int[] users = sUserManager.getUserIds(); 11997 for (int user : users) { 11998 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 11999 newNativePath, user) < 0) { 12000 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12001 } 12002 } 12003 12004 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12005 pkg.mPath = newCodePath; 12006 // Move dex files around 12007 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) { 12008 // Moving of dex files failed. Set 12009 // error code and abort move. 12010 pkg.mPath = pkg.mScanPath; 12011 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12012 } 12013 } 12014 12015 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12016 pkg.mScanPath = newCodePath; 12017 pkg.applicationInfo.sourceDir = newCodePath; 12018 pkg.applicationInfo.publicSourceDir = newResPath; 12019 pkg.applicationInfo.nativeLibraryDir = newNativePath; 12020 PackageSetting ps = (PackageSetting) pkg.mExtras; 12021 ps.codePath = new File(pkg.applicationInfo.sourceDir); 12022 ps.codePathString = ps.codePath.getPath(); 12023 ps.resourcePath = new File( 12024 pkg.applicationInfo.publicSourceDir); 12025 ps.resourcePathString = ps.resourcePath.getPath(); 12026 ps.nativeLibraryPathString = newNativePath; 12027 // Set the application info flag 12028 // correctly. 12029 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 12030 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12031 } else { 12032 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12033 } 12034 ps.setFlags(pkg.applicationInfo.flags); 12035 mAppDirs.remove(oldCodePath); 12036 mAppDirs.put(newCodePath, pkg); 12037 // Persist settings 12038 mSettings.writeLPr(); 12039 } 12040 } 12041 } 12042 } 12043 // Send resources available broadcast 12044 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12045 } 12046 } 12047 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12048 // Clean up failed installation 12049 if (mp.targetArgs != null) { 12050 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 12051 -1); 12052 } 12053 } else { 12054 // Force a gc to clear things up. 12055 Runtime.getRuntime().gc(); 12056 // Delete older code 12057 synchronized (mInstallLock) { 12058 mp.srcArgs.doPostDeleteLI(true); 12059 } 12060 } 12061 12062 // Allow more operations on this file if we didn't fail because 12063 // an operation was already pending for this package. 12064 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 12065 synchronized (mPackages) { 12066 PackageParser.Package pkg = mPackages.get(mp.packageName); 12067 if (pkg != null) { 12068 pkg.mOperationPending = false; 12069 } 12070 } 12071 } 12072 12073 IPackageMoveObserver observer = mp.observer; 12074 if (observer != null) { 12075 try { 12076 observer.packageMoved(mp.packageName, returnCode); 12077 } catch (RemoteException e) { 12078 Log.i(TAG, "Observer no longer exists."); 12079 } 12080 } 12081 } 12082 }); 12083 } 12084 12085 public boolean setInstallLocation(int loc) { 12086 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12087 null); 12088 if (getInstallLocation() == loc) { 12089 return true; 12090 } 12091 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12092 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12093 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12094 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12095 return true; 12096 } 12097 return false; 12098 } 12099 12100 public int getInstallLocation() { 12101 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12102 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12103 PackageHelper.APP_INSTALL_AUTO); 12104 } 12105 12106 /** Called by UserManagerService */ 12107 void cleanUpUserLILPw(int userHandle) { 12108 mDirtyUsers.remove(userHandle); 12109 mSettings.removeUserLPr(userHandle); 12110 mPendingBroadcasts.remove(userHandle); 12111 if (mInstaller != null) { 12112 // Technically, we shouldn't be doing this with the package lock 12113 // held. However, this is very rare, and there is already so much 12114 // other disk I/O going on, that we'll let it slide for now. 12115 mInstaller.removeUserDataDirs(userHandle); 12116 } 12117 } 12118 12119 /** Called by UserManagerService */ 12120 void createNewUserLILPw(int userHandle, File path) { 12121 if (mInstaller != null) { 12122 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 12123 } 12124 } 12125 12126 @Override 12127 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 12128 mContext.enforceCallingOrSelfPermission( 12129 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12130 "Only package verification agents can read the verifier device identity"); 12131 12132 synchronized (mPackages) { 12133 return mSettings.getVerifierDeviceIdentityLPw(); 12134 } 12135 } 12136 12137 @Override 12138 public void setPermissionEnforced(String permission, boolean enforced) { 12139 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 12140 if (READ_EXTERNAL_STORAGE.equals(permission)) { 12141 synchronized (mPackages) { 12142 if (mSettings.mReadExternalStorageEnforced == null 12143 || mSettings.mReadExternalStorageEnforced != enforced) { 12144 mSettings.mReadExternalStorageEnforced = enforced; 12145 mSettings.writeLPr(); 12146 } 12147 } 12148 // kill any non-foreground processes so we restart them and 12149 // grant/revoke the GID. 12150 final IActivityManager am = ActivityManagerNative.getDefault(); 12151 if (am != null) { 12152 final long token = Binder.clearCallingIdentity(); 12153 try { 12154 am.killProcessesBelowForeground("setPermissionEnforcement"); 12155 } catch (RemoteException e) { 12156 } finally { 12157 Binder.restoreCallingIdentity(token); 12158 } 12159 } 12160 } else { 12161 throw new IllegalArgumentException("No selective enforcement for " + permission); 12162 } 12163 } 12164 12165 @Override 12166 @Deprecated 12167 public boolean isPermissionEnforced(String permission) { 12168 return true; 12169 } 12170 12171 @Override 12172 public boolean isStorageLow() { 12173 final long token = Binder.clearCallingIdentity(); 12174 try { 12175 final DeviceStorageMonitorInternal 12176 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12177 if (dsm != null) { 12178 return dsm.isMemoryLow(); 12179 } else { 12180 return false; 12181 } 12182 } finally { 12183 Binder.restoreCallingIdentity(token); 12184 } 12185 } 12186} 12187