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