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