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