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