PackageManagerService.java revision dd3d95f182a634acdcc1b1e8e4954234d048eb54
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, false, 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.isDexOptNeeded(lib)) { 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.isDexOptNeeded(path)) { 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 static int compareSignatures(Signature[] s1, Signature[] s2) { 2580 if (s1 == null) { 2581 return s2 == null 2582 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2583 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2584 } 2585 if (s2 == null) { 2586 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2587 } 2588 HashSet<Signature> set1 = new HashSet<Signature>(); 2589 for (Signature sig : s1) { 2590 set1.add(sig); 2591 } 2592 HashSet<Signature> set2 = new HashSet<Signature>(); 2593 for (Signature sig : s2) { 2594 set2.add(sig); 2595 } 2596 // Make sure s2 contains all signatures in s1. 2597 if (set1.equals(set2)) { 2598 return PackageManager.SIGNATURE_MATCH; 2599 } 2600 return PackageManager.SIGNATURE_NO_MATCH; 2601 } 2602 2603 public String[] getPackagesForUid(int uid) { 2604 uid = UserHandle.getAppId(uid); 2605 // reader 2606 synchronized (mPackages) { 2607 Object obj = mSettings.getUserIdLPr(uid); 2608 if (obj instanceof SharedUserSetting) { 2609 final SharedUserSetting sus = (SharedUserSetting) obj; 2610 final int N = sus.packages.size(); 2611 final String[] res = new String[N]; 2612 final Iterator<PackageSetting> it = sus.packages.iterator(); 2613 int i = 0; 2614 while (it.hasNext()) { 2615 res[i++] = it.next().name; 2616 } 2617 return res; 2618 } else if (obj instanceof PackageSetting) { 2619 final PackageSetting ps = (PackageSetting) obj; 2620 return new String[] { ps.name }; 2621 } 2622 } 2623 return null; 2624 } 2625 2626 public String getNameForUid(int uid) { 2627 // reader 2628 synchronized (mPackages) { 2629 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2630 if (obj instanceof SharedUserSetting) { 2631 final SharedUserSetting sus = (SharedUserSetting) obj; 2632 return sus.name + ":" + sus.userId; 2633 } else if (obj instanceof PackageSetting) { 2634 final PackageSetting ps = (PackageSetting) obj; 2635 return ps.name; 2636 } 2637 } 2638 return null; 2639 } 2640 2641 public int getUidForSharedUser(String sharedUserName) { 2642 if(sharedUserName == null) { 2643 return -1; 2644 } 2645 // reader 2646 synchronized (mPackages) { 2647 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2648 if (suid == null) { 2649 return -1; 2650 } 2651 return suid.userId; 2652 } 2653 } 2654 2655 public int getFlagsForUid(int uid) { 2656 synchronized (mPackages) { 2657 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2658 if (obj instanceof SharedUserSetting) { 2659 final SharedUserSetting sus = (SharedUserSetting) obj; 2660 return sus.pkgFlags; 2661 } else if (obj instanceof PackageSetting) { 2662 final PackageSetting ps = (PackageSetting) obj; 2663 return ps.pkgFlags; 2664 } 2665 } 2666 return 0; 2667 } 2668 2669 @Override 2670 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2671 int flags, int userId) { 2672 if (!sUserManager.exists(userId)) return null; 2673 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2674 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2675 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2676 } 2677 2678 @Override 2679 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2680 IntentFilter filter, int match, ComponentName activity) { 2681 final int userId = UserHandle.getCallingUserId(); 2682 if (DEBUG_PREFERRED) { 2683 Log.v(TAG, "setLastChosenActivity intent=" + intent 2684 + " resolvedType=" + resolvedType 2685 + " flags=" + flags 2686 + " filter=" + filter 2687 + " match=" + match 2688 + " activity=" + activity); 2689 filter.dump(new PrintStreamPrinter(System.out), " "); 2690 } 2691 intent.setComponent(null); 2692 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2693 // Find any earlier preferred or last chosen entries and nuke them 2694 findPreferredActivity(intent, resolvedType, 2695 flags, query, 0, false, true, false, userId); 2696 // Add the new activity as the last chosen for this filter 2697 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2698 } 2699 2700 @Override 2701 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2702 final int userId = UserHandle.getCallingUserId(); 2703 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2704 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2705 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2706 false, false, false, userId); 2707 } 2708 2709 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2710 int flags, List<ResolveInfo> query, int userId) { 2711 if (query != null) { 2712 final int N = query.size(); 2713 if (N == 1) { 2714 return query.get(0); 2715 } else if (N > 1) { 2716 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2717 // If there is more than one activity with the same priority, 2718 // then let the user decide between them. 2719 ResolveInfo r0 = query.get(0); 2720 ResolveInfo r1 = query.get(1); 2721 if (DEBUG_INTENT_MATCHING || debug) { 2722 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2723 + r1.activityInfo.name + "=" + r1.priority); 2724 } 2725 // If the first activity has a higher priority, or a different 2726 // default, then it is always desireable to pick it. 2727 if (r0.priority != r1.priority 2728 || r0.preferredOrder != r1.preferredOrder 2729 || r0.isDefault != r1.isDefault) { 2730 return query.get(0); 2731 } 2732 // If we have saved a preference for a preferred activity for 2733 // this Intent, use that. 2734 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2735 flags, query, r0.priority, true, false, debug, userId); 2736 if (ri != null) { 2737 return ri; 2738 } 2739 if (userId != 0) { 2740 ri = new ResolveInfo(mResolveInfo); 2741 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2742 ri.activityInfo.applicationInfo = new ApplicationInfo( 2743 ri.activityInfo.applicationInfo); 2744 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2745 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2746 return ri; 2747 } 2748 return mResolveInfo; 2749 } 2750 } 2751 return null; 2752 } 2753 2754 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 2755 List<ResolveInfo> query, int priority, boolean always, 2756 boolean removeMatches, boolean debug, int userId) { 2757 if (!sUserManager.exists(userId)) return null; 2758 // writer 2759 synchronized (mPackages) { 2760 if (intent.getSelector() != null) { 2761 intent = intent.getSelector(); 2762 } 2763 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 2764 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 2765 // Get the list of preferred activities that handle the intent 2766 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 2767 List<PreferredActivity> prefs = pir != null 2768 ? pir.queryIntent(intent, resolvedType, 2769 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2770 : null; 2771 if (prefs != null && prefs.size() > 0) { 2772 // First figure out how good the original match set is. 2773 // We will only allow preferred activities that came 2774 // from the same match quality. 2775 int match = 0; 2776 2777 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 2778 2779 final int N = query.size(); 2780 for (int j=0; j<N; j++) { 2781 final ResolveInfo ri = query.get(j); 2782 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 2783 + ": 0x" + Integer.toHexString(match)); 2784 if (ri.match > match) { 2785 match = ri.match; 2786 } 2787 } 2788 2789 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 2790 + Integer.toHexString(match)); 2791 2792 match &= IntentFilter.MATCH_CATEGORY_MASK; 2793 final int M = prefs.size(); 2794 for (int i=0; i<M; i++) { 2795 final PreferredActivity pa = prefs.get(i); 2796 if (DEBUG_PREFERRED || debug) { 2797 Slog.v(TAG, "Checking PreferredActivity ds=" 2798 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 2799 + "\n component=" + pa.mPref.mComponent); 2800 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2801 } 2802 if (pa.mPref.mMatch != match) { 2803 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 2804 + Integer.toHexString(pa.mPref.mMatch)); 2805 continue; 2806 } 2807 // If it's not an "always" type preferred activity and that's what we're 2808 // looking for, skip it. 2809 if (always && !pa.mPref.mAlways) { 2810 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 2811 continue; 2812 } 2813 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 2814 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2815 if (DEBUG_PREFERRED || debug) { 2816 Slog.v(TAG, "Found preferred activity:"); 2817 if (ai != null) { 2818 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2819 } else { 2820 Slog.v(TAG, " null"); 2821 } 2822 } 2823 if (ai == null) { 2824 // This previously registered preferred activity 2825 // component is no longer known. Most likely an update 2826 // to the app was installed and in the new version this 2827 // component no longer exists. Clean it up by removing 2828 // it from the preferred activities list, and skip it. 2829 Slog.w(TAG, "Removing dangling preferred activity: " 2830 + pa.mPref.mComponent); 2831 pir.removeFilter(pa); 2832 continue; 2833 } 2834 for (int j=0; j<N; j++) { 2835 final ResolveInfo ri = query.get(j); 2836 if (!ri.activityInfo.applicationInfo.packageName 2837 .equals(ai.applicationInfo.packageName)) { 2838 continue; 2839 } 2840 if (!ri.activityInfo.name.equals(ai.name)) { 2841 continue; 2842 } 2843 2844 if (removeMatches) { 2845 pir.removeFilter(pa); 2846 if (DEBUG_PREFERRED) { 2847 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 2848 } 2849 break; 2850 } 2851 2852 // Okay we found a previously set preferred or last chosen app. 2853 // If the result set is different from when this 2854 // was created, we need to clear it and re-ask the 2855 // user their preference, if we're looking for an "always" type entry. 2856 if (always && !pa.mPref.sameSet(query, priority)) { 2857 Slog.i(TAG, "Result set changed, dropping preferred activity for " 2858 + intent + " type " + resolvedType); 2859 if (DEBUG_PREFERRED) { 2860 Slog.v(TAG, "Removing preferred activity since set changed " 2861 + pa.mPref.mComponent); 2862 } 2863 pir.removeFilter(pa); 2864 // Re-add the filter as a "last chosen" entry (!always) 2865 PreferredActivity lastChosen = new PreferredActivity( 2866 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 2867 pir.addFilter(lastChosen); 2868 mSettings.writePackageRestrictionsLPr(userId); 2869 return null; 2870 } 2871 2872 // Yay! Either the set matched or we're looking for the last chosen 2873 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 2874 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 2875 mSettings.writePackageRestrictionsLPr(userId); 2876 return ri; 2877 } 2878 } 2879 } 2880 mSettings.writePackageRestrictionsLPr(userId); 2881 } 2882 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 2883 return null; 2884 } 2885 2886 @Override 2887 public List<ResolveInfo> queryIntentActivities(Intent intent, 2888 String resolvedType, int flags, int userId) { 2889 if (!sUserManager.exists(userId)) return Collections.emptyList(); 2890 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 2891 ComponentName comp = intent.getComponent(); 2892 if (comp == null) { 2893 if (intent.getSelector() != null) { 2894 intent = intent.getSelector(); 2895 comp = intent.getComponent(); 2896 } 2897 } 2898 2899 if (comp != null) { 2900 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 2901 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 2902 if (ai != null) { 2903 final ResolveInfo ri = new ResolveInfo(); 2904 ri.activityInfo = ai; 2905 list.add(ri); 2906 } 2907 return list; 2908 } 2909 2910 // reader 2911 synchronized (mPackages) { 2912 final String pkgName = intent.getPackage(); 2913 if (pkgName == null) { 2914 return mActivities.queryIntent(intent, resolvedType, flags, userId); 2915 } 2916 final PackageParser.Package pkg = mPackages.get(pkgName); 2917 if (pkg != null) { 2918 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 2919 pkg.activities, userId); 2920 } 2921 return new ArrayList<ResolveInfo>(); 2922 } 2923 } 2924 2925 @Override 2926 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 2927 Intent[] specifics, String[] specificTypes, Intent intent, 2928 String resolvedType, int flags, int userId) { 2929 if (!sUserManager.exists(userId)) return Collections.emptyList(); 2930 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 2931 "query intent activity options"); 2932 final String resultsAction = intent.getAction(); 2933 2934 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 2935 | PackageManager.GET_RESOLVED_FILTER, userId); 2936 2937 if (DEBUG_INTENT_MATCHING) { 2938 Log.v(TAG, "Query " + intent + ": " + results); 2939 } 2940 2941 int specificsPos = 0; 2942 int N; 2943 2944 // todo: note that the algorithm used here is O(N^2). This 2945 // isn't a problem in our current environment, but if we start running 2946 // into situations where we have more than 5 or 10 matches then this 2947 // should probably be changed to something smarter... 2948 2949 // First we go through and resolve each of the specific items 2950 // that were supplied, taking care of removing any corresponding 2951 // duplicate items in the generic resolve list. 2952 if (specifics != null) { 2953 for (int i=0; i<specifics.length; i++) { 2954 final Intent sintent = specifics[i]; 2955 if (sintent == null) { 2956 continue; 2957 } 2958 2959 if (DEBUG_INTENT_MATCHING) { 2960 Log.v(TAG, "Specific #" + i + ": " + sintent); 2961 } 2962 2963 String action = sintent.getAction(); 2964 if (resultsAction != null && resultsAction.equals(action)) { 2965 // If this action was explicitly requested, then don't 2966 // remove things that have it. 2967 action = null; 2968 } 2969 2970 ResolveInfo ri = null; 2971 ActivityInfo ai = null; 2972 2973 ComponentName comp = sintent.getComponent(); 2974 if (comp == null) { 2975 ri = resolveIntent( 2976 sintent, 2977 specificTypes != null ? specificTypes[i] : null, 2978 flags, userId); 2979 if (ri == null) { 2980 continue; 2981 } 2982 if (ri == mResolveInfo) { 2983 // ACK! Must do something better with this. 2984 } 2985 ai = ri.activityInfo; 2986 comp = new ComponentName(ai.applicationInfo.packageName, 2987 ai.name); 2988 } else { 2989 ai = getActivityInfo(comp, flags, userId); 2990 if (ai == null) { 2991 continue; 2992 } 2993 } 2994 2995 // Look for any generic query activities that are duplicates 2996 // of this specific one, and remove them from the results. 2997 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 2998 N = results.size(); 2999 int j; 3000 for (j=specificsPos; j<N; j++) { 3001 ResolveInfo sri = results.get(j); 3002 if ((sri.activityInfo.name.equals(comp.getClassName()) 3003 && sri.activityInfo.applicationInfo.packageName.equals( 3004 comp.getPackageName())) 3005 || (action != null && sri.filter.matchAction(action))) { 3006 results.remove(j); 3007 if (DEBUG_INTENT_MATCHING) Log.v( 3008 TAG, "Removing duplicate item from " + j 3009 + " due to specific " + specificsPos); 3010 if (ri == null) { 3011 ri = sri; 3012 } 3013 j--; 3014 N--; 3015 } 3016 } 3017 3018 // Add this specific item to its proper place. 3019 if (ri == null) { 3020 ri = new ResolveInfo(); 3021 ri.activityInfo = ai; 3022 } 3023 results.add(specificsPos, ri); 3024 ri.specificIndex = i; 3025 specificsPos++; 3026 } 3027 } 3028 3029 // Now we go through the remaining generic results and remove any 3030 // duplicate actions that are found here. 3031 N = results.size(); 3032 for (int i=specificsPos; i<N-1; i++) { 3033 final ResolveInfo rii = results.get(i); 3034 if (rii.filter == null) { 3035 continue; 3036 } 3037 3038 // Iterate over all of the actions of this result's intent 3039 // filter... typically this should be just one. 3040 final Iterator<String> it = rii.filter.actionsIterator(); 3041 if (it == null) { 3042 continue; 3043 } 3044 while (it.hasNext()) { 3045 final String action = it.next(); 3046 if (resultsAction != null && resultsAction.equals(action)) { 3047 // If this action was explicitly requested, then don't 3048 // remove things that have it. 3049 continue; 3050 } 3051 for (int j=i+1; j<N; j++) { 3052 final ResolveInfo rij = results.get(j); 3053 if (rij.filter != null && rij.filter.hasAction(action)) { 3054 results.remove(j); 3055 if (DEBUG_INTENT_MATCHING) Log.v( 3056 TAG, "Removing duplicate item from " + j 3057 + " due to action " + action + " at " + i); 3058 j--; 3059 N--; 3060 } 3061 } 3062 } 3063 3064 // If the caller didn't request filter information, drop it now 3065 // so we don't have to marshall/unmarshall it. 3066 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3067 rii.filter = null; 3068 } 3069 } 3070 3071 // Filter out the caller activity if so requested. 3072 if (caller != null) { 3073 N = results.size(); 3074 for (int i=0; i<N; i++) { 3075 ActivityInfo ainfo = results.get(i).activityInfo; 3076 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3077 && caller.getClassName().equals(ainfo.name)) { 3078 results.remove(i); 3079 break; 3080 } 3081 } 3082 } 3083 3084 // If the caller didn't request filter information, 3085 // drop them now so we don't have to 3086 // marshall/unmarshall it. 3087 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3088 N = results.size(); 3089 for (int i=0; i<N; i++) { 3090 results.get(i).filter = null; 3091 } 3092 } 3093 3094 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3095 return results; 3096 } 3097 3098 @Override 3099 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3100 int userId) { 3101 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3102 ComponentName comp = intent.getComponent(); 3103 if (comp == null) { 3104 if (intent.getSelector() != null) { 3105 intent = intent.getSelector(); 3106 comp = intent.getComponent(); 3107 } 3108 } 3109 if (comp != null) { 3110 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3111 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3112 if (ai != null) { 3113 ResolveInfo ri = new ResolveInfo(); 3114 ri.activityInfo = ai; 3115 list.add(ri); 3116 } 3117 return list; 3118 } 3119 3120 // reader 3121 synchronized (mPackages) { 3122 String pkgName = intent.getPackage(); 3123 if (pkgName == null) { 3124 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3125 } 3126 final PackageParser.Package pkg = mPackages.get(pkgName); 3127 if (pkg != null) { 3128 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3129 userId); 3130 } 3131 return null; 3132 } 3133 } 3134 3135 @Override 3136 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3137 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3138 if (!sUserManager.exists(userId)) return null; 3139 if (query != null) { 3140 if (query.size() >= 1) { 3141 // If there is more than one service with the same priority, 3142 // just arbitrarily pick the first one. 3143 return query.get(0); 3144 } 3145 } 3146 return null; 3147 } 3148 3149 @Override 3150 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3151 int userId) { 3152 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3153 ComponentName comp = intent.getComponent(); 3154 if (comp == null) { 3155 if (intent.getSelector() != null) { 3156 intent = intent.getSelector(); 3157 comp = intent.getComponent(); 3158 } 3159 } 3160 if (comp != null) { 3161 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3162 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3163 if (si != null) { 3164 final ResolveInfo ri = new ResolveInfo(); 3165 ri.serviceInfo = si; 3166 list.add(ri); 3167 } 3168 return list; 3169 } 3170 3171 // reader 3172 synchronized (mPackages) { 3173 String pkgName = intent.getPackage(); 3174 if (pkgName == null) { 3175 return mServices.queryIntent(intent, resolvedType, flags, userId); 3176 } 3177 final PackageParser.Package pkg = mPackages.get(pkgName); 3178 if (pkg != null) { 3179 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3180 userId); 3181 } 3182 return null; 3183 } 3184 } 3185 3186 @Override 3187 public List<ResolveInfo> queryIntentContentProviders( 3188 Intent intent, String resolvedType, int flags, int userId) { 3189 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3190 ComponentName comp = intent.getComponent(); 3191 if (comp == null) { 3192 if (intent.getSelector() != null) { 3193 intent = intent.getSelector(); 3194 comp = intent.getComponent(); 3195 } 3196 } 3197 if (comp != null) { 3198 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3199 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3200 if (pi != null) { 3201 final ResolveInfo ri = new ResolveInfo(); 3202 ri.providerInfo = pi; 3203 list.add(ri); 3204 } 3205 return list; 3206 } 3207 3208 // reader 3209 synchronized (mPackages) { 3210 String pkgName = intent.getPackage(); 3211 if (pkgName == null) { 3212 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3213 } 3214 final PackageParser.Package pkg = mPackages.get(pkgName); 3215 if (pkg != null) { 3216 return mProviders.queryIntentForPackage( 3217 intent, resolvedType, flags, pkg.providers, userId); 3218 } 3219 return null; 3220 } 3221 } 3222 3223 @Override 3224 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3225 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3226 3227 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3228 3229 // writer 3230 synchronized (mPackages) { 3231 ArrayList<PackageInfo> list; 3232 if (listUninstalled) { 3233 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3234 for (PackageSetting ps : mSettings.mPackages.values()) { 3235 PackageInfo pi; 3236 if (ps.pkg != null) { 3237 pi = generatePackageInfo(ps.pkg, flags, userId); 3238 } else { 3239 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3240 } 3241 if (pi != null) { 3242 list.add(pi); 3243 } 3244 } 3245 } else { 3246 list = new ArrayList<PackageInfo>(mPackages.size()); 3247 for (PackageParser.Package p : mPackages.values()) { 3248 PackageInfo pi = generatePackageInfo(p, flags, userId); 3249 if (pi != null) { 3250 list.add(pi); 3251 } 3252 } 3253 } 3254 3255 return new ParceledListSlice<PackageInfo>(list); 3256 } 3257 } 3258 3259 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3260 String[] permissions, boolean[] tmp, int flags, int userId) { 3261 int numMatch = 0; 3262 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3263 for (int i=0; i<permissions.length; i++) { 3264 if (gp.grantedPermissions.contains(permissions[i])) { 3265 tmp[i] = true; 3266 numMatch++; 3267 } else { 3268 tmp[i] = false; 3269 } 3270 } 3271 if (numMatch == 0) { 3272 return; 3273 } 3274 PackageInfo pi; 3275 if (ps.pkg != null) { 3276 pi = generatePackageInfo(ps.pkg, flags, userId); 3277 } else { 3278 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3279 } 3280 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3281 if (numMatch == permissions.length) { 3282 pi.requestedPermissions = permissions; 3283 } else { 3284 pi.requestedPermissions = new String[numMatch]; 3285 numMatch = 0; 3286 for (int i=0; i<permissions.length; i++) { 3287 if (tmp[i]) { 3288 pi.requestedPermissions[numMatch] = permissions[i]; 3289 numMatch++; 3290 } 3291 } 3292 } 3293 } 3294 list.add(pi); 3295 } 3296 3297 @Override 3298 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3299 String[] permissions, int flags, int userId) { 3300 if (!sUserManager.exists(userId)) return null; 3301 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3302 3303 // writer 3304 synchronized (mPackages) { 3305 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3306 boolean[] tmpBools = new boolean[permissions.length]; 3307 if (listUninstalled) { 3308 for (PackageSetting ps : mSettings.mPackages.values()) { 3309 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3310 } 3311 } else { 3312 for (PackageParser.Package pkg : mPackages.values()) { 3313 PackageSetting ps = (PackageSetting)pkg.mExtras; 3314 if (ps != null) { 3315 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3316 userId); 3317 } 3318 } 3319 } 3320 3321 return new ParceledListSlice<PackageInfo>(list); 3322 } 3323 } 3324 3325 @Override 3326 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3327 if (!sUserManager.exists(userId)) return null; 3328 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3329 3330 // writer 3331 synchronized (mPackages) { 3332 ArrayList<ApplicationInfo> list; 3333 if (listUninstalled) { 3334 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3335 for (PackageSetting ps : mSettings.mPackages.values()) { 3336 ApplicationInfo ai; 3337 if (ps.pkg != null) { 3338 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3339 ps.readUserState(userId), userId); 3340 } else { 3341 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3342 } 3343 if (ai != null) { 3344 list.add(ai); 3345 } 3346 } 3347 } else { 3348 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3349 for (PackageParser.Package p : mPackages.values()) { 3350 if (p.mExtras != null) { 3351 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3352 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3353 if (ai != null) { 3354 list.add(ai); 3355 } 3356 } 3357 } 3358 } 3359 3360 return new ParceledListSlice<ApplicationInfo>(list); 3361 } 3362 } 3363 3364 public List<ApplicationInfo> getPersistentApplications(int flags) { 3365 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3366 3367 // reader 3368 synchronized (mPackages) { 3369 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3370 final int userId = UserHandle.getCallingUserId(); 3371 while (i.hasNext()) { 3372 final PackageParser.Package p = i.next(); 3373 if (p.applicationInfo != null 3374 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3375 && (!mSafeMode || isSystemApp(p))) { 3376 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3377 if (ps != null) { 3378 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3379 ps.readUserState(userId), userId); 3380 if (ai != null) { 3381 finalList.add(ai); 3382 } 3383 } 3384 } 3385 } 3386 } 3387 3388 return finalList; 3389 } 3390 3391 @Override 3392 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3393 if (!sUserManager.exists(userId)) return null; 3394 // reader 3395 synchronized (mPackages) { 3396 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3397 PackageSetting ps = provider != null 3398 ? mSettings.mPackages.get(provider.owner.packageName) 3399 : null; 3400 return ps != null 3401 && mSettings.isEnabledLPr(provider.info, flags, userId) 3402 && (!mSafeMode || (provider.info.applicationInfo.flags 3403 &ApplicationInfo.FLAG_SYSTEM) != 0) 3404 ? PackageParser.generateProviderInfo(provider, flags, 3405 ps.readUserState(userId), userId) 3406 : null; 3407 } 3408 } 3409 3410 /** 3411 * @deprecated 3412 */ 3413 @Deprecated 3414 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3415 // reader 3416 synchronized (mPackages) { 3417 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3418 .entrySet().iterator(); 3419 final int userId = UserHandle.getCallingUserId(); 3420 while (i.hasNext()) { 3421 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3422 PackageParser.Provider p = entry.getValue(); 3423 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3424 3425 if (ps != null && p.syncable 3426 && (!mSafeMode || (p.info.applicationInfo.flags 3427 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3428 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3429 ps.readUserState(userId), userId); 3430 if (info != null) { 3431 outNames.add(entry.getKey()); 3432 outInfo.add(info); 3433 } 3434 } 3435 } 3436 } 3437 } 3438 3439 public List<ProviderInfo> queryContentProviders(String processName, 3440 int uid, int flags) { 3441 ArrayList<ProviderInfo> finalList = null; 3442 // reader 3443 synchronized (mPackages) { 3444 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3445 final int userId = processName != null ? 3446 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3447 while (i.hasNext()) { 3448 final PackageParser.Provider p = i.next(); 3449 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3450 if (ps != null && p.info.authority != null 3451 && (processName == null 3452 || (p.info.processName.equals(processName) 3453 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3454 && mSettings.isEnabledLPr(p.info, flags, userId) 3455 && (!mSafeMode 3456 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3457 if (finalList == null) { 3458 finalList = new ArrayList<ProviderInfo>(3); 3459 } 3460 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3461 ps.readUserState(userId), userId); 3462 if (info != null) { 3463 finalList.add(info); 3464 } 3465 } 3466 } 3467 } 3468 3469 if (finalList != null) { 3470 Collections.sort(finalList, mProviderInitOrderSorter); 3471 } 3472 3473 return finalList; 3474 } 3475 3476 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3477 int flags) { 3478 // reader 3479 synchronized (mPackages) { 3480 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3481 return PackageParser.generateInstrumentationInfo(i, flags); 3482 } 3483 } 3484 3485 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3486 int flags) { 3487 ArrayList<InstrumentationInfo> finalList = 3488 new ArrayList<InstrumentationInfo>(); 3489 3490 // reader 3491 synchronized (mPackages) { 3492 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3493 while (i.hasNext()) { 3494 final PackageParser.Instrumentation p = i.next(); 3495 if (targetPackage == null 3496 || targetPackage.equals(p.info.targetPackage)) { 3497 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3498 flags); 3499 if (ii != null) { 3500 finalList.add(ii); 3501 } 3502 } 3503 } 3504 } 3505 3506 return finalList; 3507 } 3508 3509 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 3510 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 3511 if (overlays == null) { 3512 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 3513 return; 3514 } 3515 for (PackageParser.Package opkg : overlays.values()) { 3516 // Not much to do if idmap fails: we already logged the error 3517 // and we certainly don't want to abort installation of pkg simply 3518 // because an overlay didn't fit properly. For these reasons, 3519 // ignore the return value of createIdmapForPackagePairLI. 3520 createIdmapForPackagePairLI(pkg, opkg); 3521 } 3522 } 3523 3524 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 3525 PackageParser.Package opkg) { 3526 if (!opkg.mTrustedOverlay) { 3527 Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " + 3528 opkg.mScanPath + ": overlay not trusted"); 3529 return false; 3530 } 3531 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 3532 if (overlaySet == null) { 3533 Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " + 3534 opkg.mScanPath + " but target package has no known overlays"); 3535 return false; 3536 } 3537 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 3538 if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) { 3539 Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath); 3540 return false; 3541 } 3542 PackageParser.Package[] overlayArray = 3543 overlaySet.values().toArray(new PackageParser.Package[0]); 3544 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 3545 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 3546 return p1.mOverlayPriority - p2.mOverlayPriority; 3547 } 3548 }; 3549 Arrays.sort(overlayArray, cmp); 3550 3551 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 3552 int i = 0; 3553 for (PackageParser.Package p : overlayArray) { 3554 pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir; 3555 } 3556 return true; 3557 } 3558 3559 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 3560 String[] files = dir.list(); 3561 if (files == null) { 3562 Log.d(TAG, "No files in app dir " + dir); 3563 return; 3564 } 3565 3566 if (DEBUG_PACKAGE_SCANNING) { 3567 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 3568 + " flags=0x" + Integer.toHexString(flags)); 3569 } 3570 3571 int i; 3572 for (i=0; i<files.length; i++) { 3573 File file = new File(dir, files[i]); 3574 if (!isPackageFilename(files[i])) { 3575 // Ignore entries which are not apk's 3576 continue; 3577 } 3578 PackageParser.Package pkg = scanPackageLI(file, 3579 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null); 3580 // Don't mess around with apps in system partition. 3581 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 3582 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 3583 // Delete the apk 3584 Slog.w(TAG, "Cleaning up failed install of " + file); 3585 file.delete(); 3586 } 3587 } 3588 } 3589 3590 private static File getSettingsProblemFile() { 3591 File dataDir = Environment.getDataDirectory(); 3592 File systemDir = new File(dataDir, "system"); 3593 File fname = new File(systemDir, "uiderrors.txt"); 3594 return fname; 3595 } 3596 3597 static void reportSettingsProblem(int priority, String msg) { 3598 try { 3599 File fname = getSettingsProblemFile(); 3600 FileOutputStream out = new FileOutputStream(fname, true); 3601 PrintWriter pw = new FastPrintWriter(out); 3602 SimpleDateFormat formatter = new SimpleDateFormat(); 3603 String dateString = formatter.format(new Date(System.currentTimeMillis())); 3604 pw.println(dateString + ": " + msg); 3605 pw.close(); 3606 FileUtils.setPermissions( 3607 fname.toString(), 3608 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 3609 -1, -1); 3610 } catch (java.io.IOException e) { 3611 } 3612 Slog.println(priority, TAG, msg); 3613 } 3614 3615 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 3616 PackageParser.Package pkg, File srcFile, int parseFlags) { 3617 if (GET_CERTIFICATES) { 3618 if (ps != null 3619 && ps.codePath.equals(srcFile) 3620 && ps.timeStamp == srcFile.lastModified()) { 3621 if (ps.signatures.mSignatures != null 3622 && ps.signatures.mSignatures.length != 0) { 3623 // Optimization: reuse the existing cached certificates 3624 // if the package appears to be unchanged. 3625 pkg.mSignatures = ps.signatures.mSignatures; 3626 return true; 3627 } 3628 3629 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 3630 } else { 3631 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 3632 } 3633 3634 if (!pp.collectCertificates(pkg, parseFlags)) { 3635 mLastScanError = pp.getParseError(); 3636 return false; 3637 } 3638 } 3639 return true; 3640 } 3641 3642 /* 3643 * Scan a package and return the newly parsed package. 3644 * Returns null in case of errors and the error code is stored in mLastScanError 3645 */ 3646 private PackageParser.Package scanPackageLI(File scanFile, 3647 int parseFlags, int scanMode, long currentTime, UserHandle user) { 3648 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 3649 String scanPath = scanFile.getPath(); 3650 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath); 3651 parseFlags |= mDefParseFlags; 3652 PackageParser pp = new PackageParser(scanPath); 3653 pp.setSeparateProcesses(mSeparateProcesses); 3654 pp.setOnlyCoreApps(mOnlyCore); 3655 final PackageParser.Package pkg = pp.parsePackage(scanFile, 3656 scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0); 3657 3658 if (pkg == null) { 3659 mLastScanError = pp.getParseError(); 3660 return null; 3661 } 3662 3663 PackageSetting ps = null; 3664 PackageSetting updatedPkg; 3665 // reader 3666 synchronized (mPackages) { 3667 // Look to see if we already know about this package. 3668 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 3669 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 3670 // This package has been renamed to its original name. Let's 3671 // use that. 3672 ps = mSettings.peekPackageLPr(oldName); 3673 } 3674 // If there was no original package, see one for the real package name. 3675 if (ps == null) { 3676 ps = mSettings.peekPackageLPr(pkg.packageName); 3677 } 3678 // Check to see if this package could be hiding/updating a system 3679 // package. Must look for it either under the original or real 3680 // package name depending on our state. 3681 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 3682 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 3683 } 3684 // First check if this is a system package that may involve an update 3685 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 3686 if (ps != null && !ps.codePath.equals(scanFile)) { 3687 // The path has changed from what was last scanned... check the 3688 // version of the new path against what we have stored to determine 3689 // what to do. 3690 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 3691 if (pkg.mVersionCode < ps.versionCode) { 3692 // The system package has been updated and the code path does not match 3693 // Ignore entry. Skip it. 3694 Log.i(TAG, "Package " + ps.name + " at " + scanFile 3695 + " ignored: updated version " + ps.versionCode 3696 + " better than this " + pkg.mVersionCode); 3697 if (!updatedPkg.codePath.equals(scanFile)) { 3698 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 3699 + ps.name + " changing from " + updatedPkg.codePathString 3700 + " to " + scanFile); 3701 updatedPkg.codePath = scanFile; 3702 updatedPkg.codePathString = scanFile.toString(); 3703 // This is the point at which we know that the system-disk APK 3704 // for this package has moved during a reboot (e.g. due to an OTA), 3705 // so we need to reevaluate it for privilege policy. 3706 if (locationIsPrivileged(scanFile)) { 3707 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 3708 } 3709 } 3710 updatedPkg.pkg = pkg; 3711 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 3712 return null; 3713 } else { 3714 // The current app on the system partion is better than 3715 // what we have updated to on the data partition; switch 3716 // back to the system partition version. 3717 // At this point, its safely assumed that package installation for 3718 // apps in system partition will go through. If not there won't be a working 3719 // version of the app 3720 // writer 3721 synchronized (mPackages) { 3722 // Just remove the loaded entries from package lists. 3723 mPackages.remove(ps.name); 3724 } 3725 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 3726 + "reverting from " + ps.codePathString 3727 + ": new version " + pkg.mVersionCode 3728 + " better than installed " + ps.versionCode); 3729 3730 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 3731 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString); 3732 synchronized (mInstallLock) { 3733 args.cleanUpResourcesLI(); 3734 } 3735 synchronized (mPackages) { 3736 mSettings.enableSystemPackageLPw(ps.name); 3737 } 3738 } 3739 } 3740 } 3741 3742 if (updatedPkg != null) { 3743 // An updated system app will not have the PARSE_IS_SYSTEM flag set 3744 // initially 3745 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 3746 3747 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 3748 // flag set initially 3749 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 3750 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 3751 } 3752 } 3753 // Verify certificates against what was last scanned 3754 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 3755 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 3756 return null; 3757 } 3758 3759 /* 3760 * A new system app appeared, but we already had a non-system one of the 3761 * same name installed earlier. 3762 */ 3763 boolean shouldHideSystemApp = false; 3764 if (updatedPkg == null && ps != null 3765 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 3766 /* 3767 * Check to make sure the signatures match first. If they don't, 3768 * wipe the installed application and its data. 3769 */ 3770 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 3771 != PackageManager.SIGNATURE_MATCH) { 3772 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 3773 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 3774 ps = null; 3775 } else { 3776 /* 3777 * If the newly-added system app is an older version than the 3778 * already installed version, hide it. It will be scanned later 3779 * and re-added like an update. 3780 */ 3781 if (pkg.mVersionCode < ps.versionCode) { 3782 shouldHideSystemApp = true; 3783 } else { 3784 /* 3785 * The newly found system app is a newer version that the 3786 * one previously installed. Simply remove the 3787 * already-installed application and replace it with our own 3788 * while keeping the application data. 3789 */ 3790 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 3791 + ps.codePathString + ": new version " + pkg.mVersionCode 3792 + " better than installed " + ps.versionCode); 3793 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 3794 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString); 3795 synchronized (mInstallLock) { 3796 args.cleanUpResourcesLI(); 3797 } 3798 } 3799 } 3800 } 3801 3802 // The apk is forward locked (not public) if its code and resources 3803 // are kept in different files. (except for app in either system or 3804 // vendor path). 3805 // TODO grab this value from PackageSettings 3806 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 3807 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 3808 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 3809 } 3810 } 3811 3812 String codePath = null; 3813 String resPath = null; 3814 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) { 3815 if (ps != null && ps.resourcePathString != null) { 3816 resPath = ps.resourcePathString; 3817 } else { 3818 // Should not happen at all. Just log an error. 3819 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 3820 } 3821 } else { 3822 resPath = pkg.mScanPath; 3823 } 3824 3825 codePath = pkg.mScanPath; 3826 // Set application objects path explicitly. 3827 setApplicationInfoPaths(pkg, codePath, resPath); 3828 // Note that we invoke the following method only if we are about to unpack an application 3829 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 3830 | SCAN_UPDATE_SIGNATURE, currentTime, user); 3831 3832 /* 3833 * If the system app should be overridden by a previously installed 3834 * data, hide the system app now and let the /data/app scan pick it up 3835 * again. 3836 */ 3837 if (shouldHideSystemApp) { 3838 synchronized (mPackages) { 3839 /* 3840 * We have to grant systems permissions before we hide, because 3841 * grantPermissions will assume the package update is trying to 3842 * expand its permissions. 3843 */ 3844 grantPermissionsLPw(pkg, true); 3845 mSettings.disableSystemPackageLPw(pkg.packageName); 3846 } 3847 } 3848 3849 return scannedPkg; 3850 } 3851 3852 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath, 3853 String destResPath) { 3854 pkg.mPath = pkg.mScanPath = destCodePath; 3855 pkg.applicationInfo.sourceDir = destCodePath; 3856 pkg.applicationInfo.publicSourceDir = destResPath; 3857 } 3858 3859 private static String fixProcessName(String defProcessName, 3860 String processName, int uid) { 3861 if (processName == null) { 3862 return defProcessName; 3863 } 3864 return processName; 3865 } 3866 3867 private boolean verifySignaturesLP(PackageSetting pkgSetting, 3868 PackageParser.Package pkg) { 3869 if (pkgSetting.signatures.mSignatures != null) { 3870 // Already existing package. Make sure signatures match 3871 if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) != 3872 PackageManager.SIGNATURE_MATCH) { 3873 Slog.e(TAG, "Package " + pkg.packageName 3874 + " signatures do not match the previously installed version; ignoring!"); 3875 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 3876 return false; 3877 } 3878 } 3879 // Check for shared user signatures 3880 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 3881 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 3882 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 3883 Slog.e(TAG, "Package " + pkg.packageName 3884 + " has no signatures that match those in shared user " 3885 + pkgSetting.sharedUser.name + "; ignoring!"); 3886 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 3887 return false; 3888 } 3889 } 3890 return true; 3891 } 3892 3893 /** 3894 * Enforces that only the system UID or root's UID can call a method exposed 3895 * via Binder. 3896 * 3897 * @param message used as message if SecurityException is thrown 3898 * @throws SecurityException if the caller is not system or root 3899 */ 3900 private static final void enforceSystemOrRoot(String message) { 3901 final int uid = Binder.getCallingUid(); 3902 if (uid != Process.SYSTEM_UID && uid != 0) { 3903 throw new SecurityException(message); 3904 } 3905 } 3906 3907 public void performBootDexOpt() { 3908 HashSet<PackageParser.Package> pkgs = null; 3909 synchronized (mPackages) { 3910 pkgs = mDeferredDexOpt; 3911 mDeferredDexOpt = null; 3912 } 3913 if (pkgs != null) { 3914 int i = 0; 3915 for (PackageParser.Package pkg : pkgs) { 3916 if (!isFirstBoot()) { 3917 i++; 3918 try { 3919 ActivityManagerNative.getDefault().showBootMessage( 3920 mContext.getResources().getString( 3921 com.android.internal.R.string.android_upgrading_apk, 3922 i, pkgs.size()), true); 3923 } catch (RemoteException e) { 3924 } 3925 } 3926 PackageParser.Package p = pkg; 3927 synchronized (mInstallLock) { 3928 if (!p.mDidDexOpt) { 3929 performDexOptLI(p, false, false, true); 3930 } 3931 } 3932 } 3933 } 3934 } 3935 3936 public boolean performDexOpt(String packageName) { 3937 enforceSystemOrRoot("Only the system can request dexopt be performed"); 3938 3939 if (!mNoDexOpt) { 3940 return false; 3941 } 3942 3943 PackageParser.Package p; 3944 synchronized (mPackages) { 3945 p = mPackages.get(packageName); 3946 if (p == null || p.mDidDexOpt) { 3947 return false; 3948 } 3949 } 3950 synchronized (mInstallLock) { 3951 return performDexOptLI(p, false, false, true) == DEX_OPT_PERFORMED; 3952 } 3953 } 3954 3955 private void performDexOptLibsLI(ArrayList<String> libs, boolean forceDex, boolean defer, 3956 HashSet<String> done) { 3957 for (int i=0; i<libs.size(); i++) { 3958 PackageParser.Package libPkg; 3959 String libName; 3960 synchronized (mPackages) { 3961 libName = libs.get(i); 3962 SharedLibraryEntry lib = mSharedLibraries.get(libName); 3963 if (lib != null && lib.apk != null) { 3964 libPkg = mPackages.get(lib.apk); 3965 } else { 3966 libPkg = null; 3967 } 3968 } 3969 if (libPkg != null && !done.contains(libName)) { 3970 performDexOptLI(libPkg, forceDex, defer, done); 3971 } 3972 } 3973 } 3974 3975 static final int DEX_OPT_SKIPPED = 0; 3976 static final int DEX_OPT_PERFORMED = 1; 3977 static final int DEX_OPT_DEFERRED = 2; 3978 static final int DEX_OPT_FAILED = -1; 3979 3980 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 3981 HashSet<String> done) { 3982 boolean performed = false; 3983 if (done != null) { 3984 done.add(pkg.packageName); 3985 if (pkg.usesLibraries != null) { 3986 performDexOptLibsLI(pkg.usesLibraries, forceDex, defer, done); 3987 } 3988 if (pkg.usesOptionalLibraries != null) { 3989 performDexOptLibsLI(pkg.usesOptionalLibraries, forceDex, defer, done); 3990 } 3991 } 3992 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 3993 String path = pkg.mScanPath; 3994 int ret = 0; 3995 try { 3996 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) { 3997 if (!forceDex && defer) { 3998 if (mDeferredDexOpt == null) { 3999 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4000 } 4001 mDeferredDexOpt.add(pkg); 4002 return DEX_OPT_DEFERRED; 4003 } else { 4004 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName); 4005 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4006 ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg)); 4007 pkg.mDidDexOpt = true; 4008 performed = true; 4009 } 4010 } 4011 } catch (FileNotFoundException e) { 4012 Slog.w(TAG, "Apk not found for dexopt: " + path); 4013 ret = -1; 4014 } catch (IOException e) { 4015 Slog.w(TAG, "IOException reading apk: " + path, e); 4016 ret = -1; 4017 } catch (dalvik.system.StaleDexCacheError e) { 4018 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4019 ret = -1; 4020 } catch (Exception e) { 4021 Slog.w(TAG, "Exception when doing dexopt : ", e); 4022 ret = -1; 4023 } 4024 if (ret < 0) { 4025 //error from installer 4026 return DEX_OPT_FAILED; 4027 } 4028 } 4029 4030 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4031 } 4032 4033 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4034 boolean inclDependencies) { 4035 HashSet<String> done; 4036 boolean performed = false; 4037 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4038 done = new HashSet<String>(); 4039 done.add(pkg.packageName); 4040 } else { 4041 done = null; 4042 } 4043 return performDexOptLI(pkg, forceDex, defer, done); 4044 } 4045 4046 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4047 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4048 Slog.w(TAG, "Unable to update from " + oldPkg.name 4049 + " to " + newPkg.packageName 4050 + ": old package not in system partition"); 4051 return false; 4052 } else if (mPackages.get(oldPkg.name) != null) { 4053 Slog.w(TAG, "Unable to update from " + oldPkg.name 4054 + " to " + newPkg.packageName 4055 + ": old package still exists"); 4056 return false; 4057 } 4058 return true; 4059 } 4060 4061 File getDataPathForUser(int userId) { 4062 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4063 } 4064 4065 private File getDataPathForPackage(String packageName, int userId) { 4066 /* 4067 * Until we fully support multiple users, return the directory we 4068 * previously would have. The PackageManagerTests will need to be 4069 * revised when this is changed back.. 4070 */ 4071 if (userId == 0) { 4072 return new File(mAppDataDir, packageName); 4073 } else { 4074 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4075 + File.separator + packageName); 4076 } 4077 } 4078 4079 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4080 int[] users = sUserManager.getUserIds(); 4081 int res = mInstaller.install(packageName, uid, uid, seinfo); 4082 if (res < 0) { 4083 return res; 4084 } 4085 for (int user : users) { 4086 if (user != 0) { 4087 res = mInstaller.createUserData(packageName, 4088 UserHandle.getUid(user, uid), user, seinfo); 4089 if (res < 0) { 4090 return res; 4091 } 4092 } 4093 } 4094 return res; 4095 } 4096 4097 private int removeDataDirsLI(String packageName) { 4098 int[] users = sUserManager.getUserIds(); 4099 int res = 0; 4100 for (int user : users) { 4101 int resInner = mInstaller.remove(packageName, user); 4102 if (resInner < 0) { 4103 res = resInner; 4104 } 4105 } 4106 4107 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4108 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4109 if (!nativeLibraryFile.delete()) { 4110 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4111 } 4112 4113 return res; 4114 } 4115 4116 private int addSharedLibraryLPw(final SharedLibraryEntry file, int num, 4117 PackageParser.Package changingLib) { 4118 if (file.path != null) { 4119 mTmpSharedLibraries[num] = file.path; 4120 return num+1; 4121 } 4122 PackageParser.Package p = mPackages.get(file.apk); 4123 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4124 // If we are doing this while in the middle of updating a library apk, 4125 // then we need to make sure to use that new apk for determining the 4126 // dependencies here. (We haven't yet finished committing the new apk 4127 // to the package manager state.) 4128 if (p == null || p.packageName.equals(changingLib.packageName)) { 4129 p = changingLib; 4130 } 4131 } 4132 if (p != null) { 4133 String path = p.mPath; 4134 for (int i=0; i<num; i++) { 4135 if (mTmpSharedLibraries[i].equals(path)) { 4136 return num; 4137 } 4138 } 4139 mTmpSharedLibraries[num] = p.mPath; 4140 return num+1; 4141 } 4142 return num; 4143 } 4144 4145 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4146 PackageParser.Package changingLib) { 4147 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4148 if (mTmpSharedLibraries == null || 4149 mTmpSharedLibraries.length < mSharedLibraries.size()) { 4150 mTmpSharedLibraries = new String[mSharedLibraries.size()]; 4151 } 4152 int num = 0; 4153 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4154 for (int i=0; i<N; i++) { 4155 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4156 if (file == null) { 4157 Slog.e(TAG, "Package " + pkg.packageName 4158 + " requires unavailable shared library " 4159 + pkg.usesLibraries.get(i) + "; failing!"); 4160 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4161 return false; 4162 } 4163 num = addSharedLibraryLPw(file, num, changingLib); 4164 } 4165 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4166 for (int i=0; i<N; i++) { 4167 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4168 if (file == null) { 4169 Slog.w(TAG, "Package " + pkg.packageName 4170 + " desires unavailable shared library " 4171 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4172 } else { 4173 num = addSharedLibraryLPw(file, num, changingLib); 4174 } 4175 } 4176 if (num > 0) { 4177 pkg.usesLibraryFiles = new String[num]; 4178 System.arraycopy(mTmpSharedLibraries, 0, 4179 pkg.usesLibraryFiles, 0, num); 4180 } else { 4181 pkg.usesLibraryFiles = null; 4182 } 4183 } 4184 return true; 4185 } 4186 4187 private static boolean hasString(List<String> list, List<String> which) { 4188 if (list == null) { 4189 return false; 4190 } 4191 for (int i=list.size()-1; i>=0; i--) { 4192 for (int j=which.size()-1; j>=0; j--) { 4193 if (which.get(j).equals(list.get(i))) { 4194 return true; 4195 } 4196 } 4197 } 4198 return false; 4199 } 4200 4201 private void updateAllSharedLibrariesLPw() { 4202 for (PackageParser.Package pkg : mPackages.values()) { 4203 updateSharedLibrariesLPw(pkg, null); 4204 } 4205 } 4206 4207 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4208 PackageParser.Package changingPkg) { 4209 ArrayList<PackageParser.Package> res = null; 4210 for (PackageParser.Package pkg : mPackages.values()) { 4211 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4212 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4213 if (res == null) { 4214 res = new ArrayList<PackageParser.Package>(); 4215 } 4216 res.add(pkg); 4217 updateSharedLibrariesLPw(pkg, changingPkg); 4218 } 4219 } 4220 return res; 4221 } 4222 4223 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4224 int parseFlags, int scanMode, long currentTime, UserHandle user) { 4225 File scanFile = new File(pkg.mScanPath); 4226 if (scanFile == null || pkg.applicationInfo.sourceDir == null || 4227 pkg.applicationInfo.publicSourceDir == null) { 4228 // Bail out. The resource and code paths haven't been set. 4229 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4230 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4231 return null; 4232 } 4233 mScanningPath = scanFile; 4234 4235 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4236 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4237 } 4238 4239 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4240 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4241 } 4242 4243 if (mCustomResolverComponentName != null && 4244 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4245 setUpCustomResolverActivity(pkg); 4246 } 4247 4248 if (pkg.packageName.equals("android")) { 4249 synchronized (mPackages) { 4250 if (mAndroidApplication != null) { 4251 Slog.w(TAG, "*************************************************"); 4252 Slog.w(TAG, "Core android package being redefined. Skipping."); 4253 Slog.w(TAG, " file=" + mScanningPath); 4254 Slog.w(TAG, "*************************************************"); 4255 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4256 return null; 4257 } 4258 4259 // Set up information for our fall-back user intent resolution activity. 4260 mPlatformPackage = pkg; 4261 pkg.mVersionCode = mSdkVersion; 4262 mAndroidApplication = pkg.applicationInfo; 4263 4264 if (!mResolverReplaced) { 4265 mResolveActivity.applicationInfo = mAndroidApplication; 4266 mResolveActivity.name = ResolverActivity.class.getName(); 4267 mResolveActivity.packageName = mAndroidApplication.packageName; 4268 mResolveActivity.processName = "system:ui"; 4269 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4270 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4271 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert; 4272 mResolveActivity.exported = true; 4273 mResolveActivity.enabled = true; 4274 mResolveInfo.activityInfo = mResolveActivity; 4275 mResolveInfo.priority = 0; 4276 mResolveInfo.preferredOrder = 0; 4277 mResolveInfo.match = 0; 4278 mResolveComponentName = new ComponentName( 4279 mAndroidApplication.packageName, mResolveActivity.name); 4280 } 4281 } 4282 } 4283 4284 if (DEBUG_PACKAGE_SCANNING) { 4285 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4286 Log.d(TAG, "Scanning package " + pkg.packageName); 4287 } 4288 4289 if (mPackages.containsKey(pkg.packageName) 4290 || mSharedLibraries.containsKey(pkg.packageName)) { 4291 Slog.w(TAG, "Application package " + pkg.packageName 4292 + " already installed. Skipping duplicate."); 4293 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4294 return null; 4295 } 4296 4297 // Initialize package source and resource directories 4298 File destCodeFile = new File(pkg.applicationInfo.sourceDir); 4299 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir); 4300 4301 SharedUserSetting suid = null; 4302 PackageSetting pkgSetting = null; 4303 4304 if (!isSystemApp(pkg)) { 4305 // Only system apps can use these features. 4306 pkg.mOriginalPackages = null; 4307 pkg.mRealPackage = null; 4308 pkg.mAdoptPermissions = null; 4309 } 4310 4311 // writer 4312 synchronized (mPackages) { 4313 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4314 // Check all shared libraries and map to their actual file path. 4315 // We only do this here for apps not on a system dir, because those 4316 // are the only ones that can fail an install due to this. We 4317 // will take care of the system apps by updating all of their 4318 // library paths after the scan is done. 4319 if (!updateSharedLibrariesLPw(pkg, null)) { 4320 return null; 4321 } 4322 } 4323 4324 if (pkg.mSharedUserId != null) { 4325 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 4326 if (suid == null) { 4327 Slog.w(TAG, "Creating application package " + pkg.packageName 4328 + " for shared user failed"); 4329 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4330 return null; 4331 } 4332 if (DEBUG_PACKAGE_SCANNING) { 4333 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4334 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 4335 + "): packages=" + suid.packages); 4336 } 4337 } 4338 4339 // Check if we are renaming from an original package name. 4340 PackageSetting origPackage = null; 4341 String realName = null; 4342 if (pkg.mOriginalPackages != null) { 4343 // This package may need to be renamed to a previously 4344 // installed name. Let's check on that... 4345 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 4346 if (pkg.mOriginalPackages.contains(renamed)) { 4347 // This package had originally been installed as the 4348 // original name, and we have already taken care of 4349 // transitioning to the new one. Just update the new 4350 // one to continue using the old name. 4351 realName = pkg.mRealPackage; 4352 if (!pkg.packageName.equals(renamed)) { 4353 // Callers into this function may have already taken 4354 // care of renaming the package; only do it here if 4355 // it is not already done. 4356 pkg.setPackageName(renamed); 4357 } 4358 4359 } else { 4360 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 4361 if ((origPackage = mSettings.peekPackageLPr( 4362 pkg.mOriginalPackages.get(i))) != null) { 4363 // We do have the package already installed under its 4364 // original name... should we use it? 4365 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 4366 // New package is not compatible with original. 4367 origPackage = null; 4368 continue; 4369 } else if (origPackage.sharedUser != null) { 4370 // Make sure uid is compatible between packages. 4371 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 4372 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 4373 + " to " + pkg.packageName + ": old uid " 4374 + origPackage.sharedUser.name 4375 + " differs from " + pkg.mSharedUserId); 4376 origPackage = null; 4377 continue; 4378 } 4379 } else { 4380 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 4381 + pkg.packageName + " to old name " + origPackage.name); 4382 } 4383 break; 4384 } 4385 } 4386 } 4387 } 4388 4389 if (mTransferedPackages.contains(pkg.packageName)) { 4390 Slog.w(TAG, "Package " + pkg.packageName 4391 + " was transferred to another, but its .apk remains"); 4392 } 4393 4394 // Just create the setting, don't add it yet. For already existing packages 4395 // the PkgSetting exists already and doesn't have to be created. 4396 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 4397 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 4398 pkg.applicationInfo.flags, user, false); 4399 if (pkgSetting == null) { 4400 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 4401 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4402 return null; 4403 } 4404 4405 if (pkgSetting.origPackage != null) { 4406 // If we are first transitioning from an original package, 4407 // fix up the new package's name now. We need to do this after 4408 // looking up the package under its new name, so getPackageLP 4409 // can take care of fiddling things correctly. 4410 pkg.setPackageName(origPackage.name); 4411 4412 // File a report about this. 4413 String msg = "New package " + pkgSetting.realName 4414 + " renamed to replace old package " + pkgSetting.name; 4415 reportSettingsProblem(Log.WARN, msg); 4416 4417 // Make a note of it. 4418 mTransferedPackages.add(origPackage.name); 4419 4420 // No longer need to retain this. 4421 pkgSetting.origPackage = null; 4422 } 4423 4424 if (realName != null) { 4425 // Make a note of it. 4426 mTransferedPackages.add(pkg.packageName); 4427 } 4428 4429 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 4430 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 4431 } 4432 4433 if (mFoundPolicyFile) { 4434 SELinuxMMAC.assignSeinfoValue(pkg); 4435 } 4436 4437 pkg.applicationInfo.uid = pkgSetting.appId; 4438 pkg.mExtras = pkgSetting; 4439 4440 if (!verifySignaturesLP(pkgSetting, pkg)) { 4441 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4442 return null; 4443 } 4444 // The signature has changed, but this package is in the system 4445 // image... let's recover! 4446 pkgSetting.signatures.mSignatures = pkg.mSignatures; 4447 // However... if this package is part of a shared user, but it 4448 // doesn't match the signature of the shared user, let's fail. 4449 // What this means is that you can't change the signatures 4450 // associated with an overall shared user, which doesn't seem all 4451 // that unreasonable. 4452 if (pkgSetting.sharedUser != null) { 4453 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4454 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 4455 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 4456 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 4457 return null; 4458 } 4459 } 4460 // File a report about this. 4461 String msg = "System package " + pkg.packageName 4462 + " signature changed; retaining data."; 4463 reportSettingsProblem(Log.WARN, msg); 4464 } 4465 4466 // Verify that this new package doesn't have any content providers 4467 // that conflict with existing packages. Only do this if the 4468 // package isn't already installed, since we don't want to break 4469 // things that are installed. 4470 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 4471 final int N = pkg.providers.size(); 4472 int i; 4473 for (i=0; i<N; i++) { 4474 PackageParser.Provider p = pkg.providers.get(i); 4475 if (p.info.authority != null) { 4476 String names[] = p.info.authority.split(";"); 4477 for (int j = 0; j < names.length; j++) { 4478 if (mProvidersByAuthority.containsKey(names[j])) { 4479 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 4480 Slog.w(TAG, "Can't install because provider name " + names[j] + 4481 " (in package " + pkg.applicationInfo.packageName + 4482 ") is already used by " 4483 + ((other != null && other.getComponentName() != null) 4484 ? other.getComponentName().getPackageName() : "?")); 4485 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 4486 return null; 4487 } 4488 } 4489 } 4490 } 4491 } 4492 4493 if (pkg.mAdoptPermissions != null) { 4494 // This package wants to adopt ownership of permissions from 4495 // another package. 4496 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 4497 final String origName = pkg.mAdoptPermissions.get(i); 4498 final PackageSetting orig = mSettings.peekPackageLPr(origName); 4499 if (orig != null) { 4500 if (verifyPackageUpdateLPr(orig, pkg)) { 4501 Slog.i(TAG, "Adopting permissions from " + origName + " to " 4502 + pkg.packageName); 4503 mSettings.transferPermissionsLPw(origName, pkg.packageName); 4504 } 4505 } 4506 } 4507 } 4508 } 4509 4510 final String pkgName = pkg.packageName; 4511 4512 final long scanFileTime = scanFile.lastModified(); 4513 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 4514 pkg.applicationInfo.processName = fixProcessName( 4515 pkg.applicationInfo.packageName, 4516 pkg.applicationInfo.processName, 4517 pkg.applicationInfo.uid); 4518 4519 File dataPath; 4520 if (mPlatformPackage == pkg) { 4521 // The system package is special. 4522 dataPath = new File (Environment.getDataDirectory(), "system"); 4523 pkg.applicationInfo.dataDir = dataPath.getPath(); 4524 } else { 4525 // This is a normal package, need to make its data directory. 4526 dataPath = getDataPathForPackage(pkg.packageName, 0); 4527 4528 boolean uidError = false; 4529 4530 if (dataPath.exists()) { 4531 int currentUid = 0; 4532 try { 4533 StructStat stat = Libcore.os.stat(dataPath.getPath()); 4534 currentUid = stat.st_uid; 4535 } catch (ErrnoException e) { 4536 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 4537 } 4538 4539 // If we have mismatched owners for the data path, we have a problem. 4540 if (currentUid != pkg.applicationInfo.uid) { 4541 boolean recovered = false; 4542 if (currentUid == 0) { 4543 // The directory somehow became owned by root. Wow. 4544 // This is probably because the system was stopped while 4545 // installd was in the middle of messing with its libs 4546 // directory. Ask installd to fix that. 4547 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 4548 pkg.applicationInfo.uid); 4549 if (ret >= 0) { 4550 recovered = true; 4551 String msg = "Package " + pkg.packageName 4552 + " unexpectedly changed to uid 0; recovered to " + 4553 + pkg.applicationInfo.uid; 4554 reportSettingsProblem(Log.WARN, msg); 4555 } 4556 } 4557 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 4558 || (scanMode&SCAN_BOOTING) != 0)) { 4559 // If this is a system app, we can at least delete its 4560 // current data so the application will still work. 4561 int ret = removeDataDirsLI(pkgName); 4562 if (ret >= 0) { 4563 // TODO: Kill the processes first 4564 // Old data gone! 4565 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 4566 ? "System package " : "Third party package "; 4567 String msg = prefix + pkg.packageName 4568 + " has changed from uid: " 4569 + currentUid + " to " 4570 + pkg.applicationInfo.uid + "; old data erased"; 4571 reportSettingsProblem(Log.WARN, msg); 4572 recovered = true; 4573 4574 // And now re-install the app. 4575 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 4576 pkg.applicationInfo.seinfo); 4577 if (ret == -1) { 4578 // Ack should not happen! 4579 msg = prefix + pkg.packageName 4580 + " could not have data directory re-created after delete."; 4581 reportSettingsProblem(Log.WARN, msg); 4582 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4583 return null; 4584 } 4585 } 4586 if (!recovered) { 4587 mHasSystemUidErrors = true; 4588 } 4589 } else if (!recovered) { 4590 // If we allow this install to proceed, we will be broken. 4591 // Abort, abort! 4592 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 4593 return null; 4594 } 4595 if (!recovered) { 4596 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 4597 + pkg.applicationInfo.uid + "/fs_" 4598 + currentUid; 4599 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 4600 String msg = "Package " + pkg.packageName 4601 + " has mismatched uid: " 4602 + currentUid + " on disk, " 4603 + pkg.applicationInfo.uid + " in settings"; 4604 // writer 4605 synchronized (mPackages) { 4606 mSettings.mReadMessages.append(msg); 4607 mSettings.mReadMessages.append('\n'); 4608 uidError = true; 4609 if (!pkgSetting.uidError) { 4610 reportSettingsProblem(Log.ERROR, msg); 4611 } 4612 } 4613 } 4614 } 4615 pkg.applicationInfo.dataDir = dataPath.getPath(); 4616 } else { 4617 if (DEBUG_PACKAGE_SCANNING) { 4618 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4619 Log.v(TAG, "Want this data dir: " + dataPath); 4620 } 4621 //invoke installer to do the actual installation 4622 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 4623 pkg.applicationInfo.seinfo); 4624 if (ret < 0) { 4625 // Error from installer 4626 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4627 return null; 4628 } 4629 4630 if (dataPath.exists()) { 4631 pkg.applicationInfo.dataDir = dataPath.getPath(); 4632 } else { 4633 Slog.w(TAG, "Unable to create data directory: " + dataPath); 4634 pkg.applicationInfo.dataDir = null; 4635 } 4636 } 4637 4638 /* 4639 * Set the data dir to the default "/data/data/<package name>/lib" 4640 * if we got here without anyone telling us different (e.g., apps 4641 * stored on SD card have their native libraries stored in the ASEC 4642 * container with the APK). 4643 * 4644 * This happens during an upgrade from a package settings file that 4645 * doesn't have a native library path attribute at all. 4646 */ 4647 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 4648 if (pkgSetting.nativeLibraryPathString == null) { 4649 setInternalAppNativeLibraryPath(pkg, pkgSetting); 4650 } else { 4651 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 4652 } 4653 } 4654 4655 pkgSetting.uidError = uidError; 4656 } 4657 4658 String path = scanFile.getPath(); 4659 /* Note: We don't want to unpack the native binaries for 4660 * system applications, unless they have been updated 4661 * (the binaries are already under /system/lib). 4662 * Also, don't unpack libs for apps on the external card 4663 * since they should have their libraries in the ASEC 4664 * container already. 4665 * 4666 * In other words, we're going to unpack the binaries 4667 * only for non-system apps and system app upgrades. 4668 */ 4669 if (pkg.applicationInfo.nativeLibraryDir != null) { 4670 try { 4671 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 4672 final String dataPathString = dataPath.getCanonicalPath(); 4673 4674 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 4675 /* 4676 * Upgrading from a previous version of the OS sometimes 4677 * leaves native libraries in the /data/data/<app>/lib 4678 * directory for system apps even when they shouldn't be. 4679 * Recent changes in the JNI library search path 4680 * necessitates we remove those to match previous behavior. 4681 */ 4682 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 4683 Log.i(TAG, "removed obsolete native libraries for system package " 4684 + path); 4685 } 4686 } else { 4687 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 4688 /* 4689 * Update native library dir if it starts with 4690 * /data/data 4691 */ 4692 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 4693 setInternalAppNativeLibraryPath(pkg, pkgSetting); 4694 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 4695 } 4696 4697 try { 4698 if (copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir) != PackageManager.INSTALL_SUCCEEDED) { 4699 Slog.e(TAG, "Unable to copy native libraries"); 4700 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 4701 return null; 4702 } 4703 } catch (IOException e) { 4704 Slog.e(TAG, "Unable to copy native libraries", e); 4705 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 4706 return null; 4707 } 4708 } 4709 4710 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 4711 final int[] userIds = sUserManager.getUserIds(); 4712 synchronized (mInstallLock) { 4713 for (int userId : userIds) { 4714 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 4715 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 4716 Slog.w(TAG, "Failed linking native library dir (user=" + userId 4717 + ")"); 4718 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 4719 return null; 4720 } 4721 } 4722 } 4723 } 4724 } catch (IOException ioe) { 4725 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 4726 } 4727 } 4728 pkg.mScanPath = path; 4729 4730 if ((scanMode&SCAN_NO_DEX) == 0) { 4731 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 4732 == DEX_OPT_FAILED) { 4733 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 4734 return null; 4735 } 4736 } 4737 4738 if (mFactoryTest && pkg.requestedPermissions.contains( 4739 android.Manifest.permission.FACTORY_TEST)) { 4740 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 4741 } 4742 4743 ArrayList<PackageParser.Package> clientLibPkgs = null; 4744 4745 // writer 4746 synchronized (mPackages) { 4747 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 4748 // Only system apps can add new shared libraries. 4749 if (pkg.libraryNames != null) { 4750 for (int i=0; i<pkg.libraryNames.size(); i++) { 4751 String name = pkg.libraryNames.get(i); 4752 boolean allowed = false; 4753 if (isUpdatedSystemApp(pkg)) { 4754 // New library entries can only be added through the 4755 // system image. This is important to get rid of a lot 4756 // of nasty edge cases: for example if we allowed a non- 4757 // system update of the app to add a library, then uninstalling 4758 // the update would make the library go away, and assumptions 4759 // we made such as through app install filtering would now 4760 // have allowed apps on the device which aren't compatible 4761 // with it. Better to just have the restriction here, be 4762 // conservative, and create many fewer cases that can negatively 4763 // impact the user experience. 4764 final PackageSetting sysPs = mSettings 4765 .getDisabledSystemPkgLPr(pkg.packageName); 4766 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 4767 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 4768 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 4769 allowed = true; 4770 allowed = true; 4771 break; 4772 } 4773 } 4774 } 4775 } else { 4776 allowed = true; 4777 } 4778 if (allowed) { 4779 if (!mSharedLibraries.containsKey(name)) { 4780 mSharedLibraries.put(name, new SharedLibraryEntry(null, 4781 pkg.packageName)); 4782 } else if (!name.equals(pkg.packageName)) { 4783 Slog.w(TAG, "Package " + pkg.packageName + " library " 4784 + name + " already exists; skipping"); 4785 } 4786 } else { 4787 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 4788 + name + " that is not declared on system image; skipping"); 4789 } 4790 } 4791 if ((scanMode&SCAN_BOOTING) == 0) { 4792 // If we are not booting, we need to update any applications 4793 // that are clients of our shared library. If we are booting, 4794 // this will all be done once the scan is complete. 4795 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 4796 } 4797 } 4798 } 4799 } 4800 4801 // We also need to dexopt any apps that are dependent on this library. Note that 4802 // if these fail, we should abort the install since installing the library will 4803 // result in some apps being broken. 4804 if (clientLibPkgs != null) { 4805 if ((scanMode&SCAN_NO_DEX) == 0) { 4806 for (int i=0; i<clientLibPkgs.size(); i++) { 4807 PackageParser.Package clientPkg = clientLibPkgs.get(i); 4808 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 4809 == DEX_OPT_FAILED) { 4810 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 4811 return null; 4812 } 4813 } 4814 } 4815 } 4816 4817 // Request the ActivityManager to kill the process(only for existing packages) 4818 // so that we do not end up in a confused state while the user is still using the older 4819 // version of the application while the new one gets installed. 4820 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 4821 // If the package lives in an asec, tell everyone that the container is going 4822 // away so they can clean up any references to its resources (which would prevent 4823 // vold from being able to unmount the asec) 4824 if (isForwardLocked(pkg) || isExternal(pkg)) { 4825 if (DEBUG_INSTALL) { 4826 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 4827 } 4828 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 4829 final ArrayList<String> pkgList = new ArrayList<String>(1); 4830 pkgList.add(pkg.applicationInfo.packageName); 4831 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 4832 } 4833 4834 // Post the request that it be killed now that the going-away broadcast is en route 4835 killApplication(pkg.applicationInfo.packageName, 4836 pkg.applicationInfo.uid, "update pkg"); 4837 } 4838 4839 // Also need to kill any apps that are dependent on the library. 4840 if (clientLibPkgs != null) { 4841 for (int i=0; i<clientLibPkgs.size(); i++) { 4842 PackageParser.Package clientPkg = clientLibPkgs.get(i); 4843 killApplication(clientPkg.applicationInfo.packageName, 4844 clientPkg.applicationInfo.uid, "update lib"); 4845 } 4846 } 4847 4848 // writer 4849 synchronized (mPackages) { 4850 // We don't expect installation to fail beyond this point, 4851 if ((scanMode&SCAN_MONITOR) != 0) { 4852 mAppDirs.put(pkg.mPath, pkg); 4853 } 4854 // Add the new setting to mSettings 4855 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 4856 // Add the new setting to mPackages 4857 mPackages.put(pkg.applicationInfo.packageName, pkg); 4858 // Make sure we don't accidentally delete its data. 4859 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 4860 while (iter.hasNext()) { 4861 PackageCleanItem item = iter.next(); 4862 if (pkgName.equals(item.packageName)) { 4863 iter.remove(); 4864 } 4865 } 4866 4867 // Take care of first install / last update times. 4868 if (currentTime != 0) { 4869 if (pkgSetting.firstInstallTime == 0) { 4870 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 4871 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 4872 pkgSetting.lastUpdateTime = currentTime; 4873 } 4874 } else if (pkgSetting.firstInstallTime == 0) { 4875 // We need *something*. Take time time stamp of the file. 4876 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 4877 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 4878 if (scanFileTime != pkgSetting.timeStamp) { 4879 // A package on the system image has changed; consider this 4880 // to be an update. 4881 pkgSetting.lastUpdateTime = scanFileTime; 4882 } 4883 } 4884 4885 // Add the package's KeySets to the global KeySetManager 4886 KeySetManager ksm = mSettings.mKeySetManager; 4887 try { 4888 ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 4889 if (pkg.mKeySetMapping != null) { 4890 for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) { 4891 if (entry.getValue() != null) { 4892 ksm.addDefinedKeySetToPackage(pkg.packageName, 4893 entry.getValue(), entry.getKey()); 4894 } 4895 } 4896 } 4897 } catch (NullPointerException e) { 4898 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 4899 } catch (IllegalArgumentException e) { 4900 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 4901 } 4902 4903 int N = pkg.providers.size(); 4904 StringBuilder r = null; 4905 int i; 4906 for (i=0; i<N; i++) { 4907 PackageParser.Provider p = pkg.providers.get(i); 4908 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 4909 p.info.processName, pkg.applicationInfo.uid); 4910 mProviders.addProvider(p); 4911 p.syncable = p.info.isSyncable; 4912 if (p.info.authority != null) { 4913 String names[] = p.info.authority.split(";"); 4914 p.info.authority = null; 4915 for (int j = 0; j < names.length; j++) { 4916 if (j == 1 && p.syncable) { 4917 // We only want the first authority for a provider to possibly be 4918 // syncable, so if we already added this provider using a different 4919 // authority clear the syncable flag. We copy the provider before 4920 // changing it because the mProviders object contains a reference 4921 // to a provider that we don't want to change. 4922 // Only do this for the second authority since the resulting provider 4923 // object can be the same for all future authorities for this provider. 4924 p = new PackageParser.Provider(p); 4925 p.syncable = false; 4926 } 4927 if (!mProvidersByAuthority.containsKey(names[j])) { 4928 mProvidersByAuthority.put(names[j], p); 4929 if (p.info.authority == null) { 4930 p.info.authority = names[j]; 4931 } else { 4932 p.info.authority = p.info.authority + ";" + names[j]; 4933 } 4934 if (DEBUG_PACKAGE_SCANNING) { 4935 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4936 Log.d(TAG, "Registered content provider: " + names[j] 4937 + ", className = " + p.info.name + ", isSyncable = " 4938 + p.info.isSyncable); 4939 } 4940 } else { 4941 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 4942 Slog.w(TAG, "Skipping provider name " + names[j] + 4943 " (in package " + pkg.applicationInfo.packageName + 4944 "): name already used by " 4945 + ((other != null && other.getComponentName() != null) 4946 ? other.getComponentName().getPackageName() : "?")); 4947 } 4948 } 4949 } 4950 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4951 if (r == null) { 4952 r = new StringBuilder(256); 4953 } else { 4954 r.append(' '); 4955 } 4956 r.append(p.info.name); 4957 } 4958 } 4959 if (r != null) { 4960 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 4961 } 4962 4963 N = pkg.services.size(); 4964 r = null; 4965 for (i=0; i<N; i++) { 4966 PackageParser.Service s = pkg.services.get(i); 4967 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 4968 s.info.processName, pkg.applicationInfo.uid); 4969 mServices.addService(s); 4970 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4971 if (r == null) { 4972 r = new StringBuilder(256); 4973 } else { 4974 r.append(' '); 4975 } 4976 r.append(s.info.name); 4977 } 4978 } 4979 if (r != null) { 4980 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 4981 } 4982 4983 N = pkg.receivers.size(); 4984 r = null; 4985 for (i=0; i<N; i++) { 4986 PackageParser.Activity a = pkg.receivers.get(i); 4987 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 4988 a.info.processName, pkg.applicationInfo.uid); 4989 mReceivers.addActivity(a, "receiver"); 4990 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4991 if (r == null) { 4992 r = new StringBuilder(256); 4993 } else { 4994 r.append(' '); 4995 } 4996 r.append(a.info.name); 4997 } 4998 } 4999 if (r != null) { 5000 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5001 } 5002 5003 N = pkg.activities.size(); 5004 r = null; 5005 for (i=0; i<N; i++) { 5006 PackageParser.Activity a = pkg.activities.get(i); 5007 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5008 a.info.processName, pkg.applicationInfo.uid); 5009 mActivities.addActivity(a, "activity"); 5010 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5011 if (r == null) { 5012 r = new StringBuilder(256); 5013 } else { 5014 r.append(' '); 5015 } 5016 r.append(a.info.name); 5017 } 5018 } 5019 if (r != null) { 5020 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5021 } 5022 5023 N = pkg.permissionGroups.size(); 5024 r = null; 5025 for (i=0; i<N; i++) { 5026 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5027 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5028 if (cur == null) { 5029 mPermissionGroups.put(pg.info.name, pg); 5030 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5031 if (r == null) { 5032 r = new StringBuilder(256); 5033 } else { 5034 r.append(' '); 5035 } 5036 r.append(pg.info.name); 5037 } 5038 } else { 5039 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5040 + pg.info.packageName + " ignored: original from " 5041 + cur.info.packageName); 5042 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5043 if (r == null) { 5044 r = new StringBuilder(256); 5045 } else { 5046 r.append(' '); 5047 } 5048 r.append("DUP:"); 5049 r.append(pg.info.name); 5050 } 5051 } 5052 } 5053 if (r != null) { 5054 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5055 } 5056 5057 N = pkg.permissions.size(); 5058 r = null; 5059 for (i=0; i<N; i++) { 5060 PackageParser.Permission p = pkg.permissions.get(i); 5061 HashMap<String, BasePermission> permissionMap = 5062 p.tree ? mSettings.mPermissionTrees 5063 : mSettings.mPermissions; 5064 p.group = mPermissionGroups.get(p.info.group); 5065 if (p.info.group == null || p.group != null) { 5066 BasePermission bp = permissionMap.get(p.info.name); 5067 if (bp == null) { 5068 bp = new BasePermission(p.info.name, p.info.packageName, 5069 BasePermission.TYPE_NORMAL); 5070 permissionMap.put(p.info.name, bp); 5071 } 5072 if (bp.perm == null) { 5073 if (bp.sourcePackage != null 5074 && !bp.sourcePackage.equals(p.info.packageName)) { 5075 // If this is a permission that was formerly defined by a non-system 5076 // app, but is now defined by a system app (following an upgrade), 5077 // discard the previous declaration and consider the system's to be 5078 // canonical. 5079 if (isSystemApp(p.owner)) { 5080 Slog.i(TAG, "New decl " + p.owner + " of permission " 5081 + p.info.name + " is system"); 5082 bp.sourcePackage = null; 5083 } 5084 } 5085 if (bp.sourcePackage == null 5086 || bp.sourcePackage.equals(p.info.packageName)) { 5087 BasePermission tree = findPermissionTreeLP(p.info.name); 5088 if (tree == null 5089 || tree.sourcePackage.equals(p.info.packageName)) { 5090 bp.packageSetting = pkgSetting; 5091 bp.perm = p; 5092 bp.uid = pkg.applicationInfo.uid; 5093 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5094 if (r == null) { 5095 r = new StringBuilder(256); 5096 } else { 5097 r.append(' '); 5098 } 5099 r.append(p.info.name); 5100 } 5101 } else { 5102 Slog.w(TAG, "Permission " + p.info.name + " from package " 5103 + p.info.packageName + " ignored: base tree " 5104 + tree.name + " is from package " 5105 + tree.sourcePackage); 5106 } 5107 } else { 5108 Slog.w(TAG, "Permission " + p.info.name + " from package " 5109 + p.info.packageName + " ignored: original from " 5110 + bp.sourcePackage); 5111 } 5112 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5113 if (r == null) { 5114 r = new StringBuilder(256); 5115 } else { 5116 r.append(' '); 5117 } 5118 r.append("DUP:"); 5119 r.append(p.info.name); 5120 } 5121 if (bp.perm == p) { 5122 bp.protectionLevel = p.info.protectionLevel; 5123 } 5124 } else { 5125 Slog.w(TAG, "Permission " + p.info.name + " from package " 5126 + p.info.packageName + " ignored: no group " 5127 + p.group); 5128 } 5129 } 5130 if (r != null) { 5131 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5132 } 5133 5134 N = pkg.instrumentation.size(); 5135 r = null; 5136 for (i=0; i<N; i++) { 5137 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5138 a.info.packageName = pkg.applicationInfo.packageName; 5139 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5140 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5141 a.info.dataDir = pkg.applicationInfo.dataDir; 5142 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5143 mInstrumentation.put(a.getComponentName(), a); 5144 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5145 if (r == null) { 5146 r = new StringBuilder(256); 5147 } else { 5148 r.append(' '); 5149 } 5150 r.append(a.info.name); 5151 } 5152 } 5153 if (r != null) { 5154 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5155 } 5156 5157 if (pkg.protectedBroadcasts != null) { 5158 N = pkg.protectedBroadcasts.size(); 5159 for (i=0; i<N; i++) { 5160 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5161 } 5162 } 5163 5164 pkgSetting.setTimeStamp(scanFileTime); 5165 5166 // Create idmap files for pairs of (packages, overlay packages). 5167 // Note: "android", ie framework-res.apk, is handled by native layers. 5168 if (pkg.mOverlayTarget != null) { 5169 // This is an overlay package. 5170 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 5171 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 5172 mOverlays.put(pkg.mOverlayTarget, 5173 new HashMap<String, PackageParser.Package>()); 5174 } 5175 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 5176 map.put(pkg.packageName, pkg); 5177 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 5178 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 5179 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5180 return null; 5181 } 5182 } 5183 } else if (mOverlays.containsKey(pkg.packageName) && 5184 !pkg.packageName.equals("android")) { 5185 // This is a regular package, with one or more known overlay packages. 5186 createIdmapsForPackageLI(pkg); 5187 } 5188 } 5189 5190 return pkg; 5191 } 5192 5193 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 5194 synchronized (mPackages) { 5195 mResolverReplaced = true; 5196 // Set up information for custom user intent resolution activity. 5197 mResolveActivity.applicationInfo = pkg.applicationInfo; 5198 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 5199 mResolveActivity.packageName = pkg.applicationInfo.packageName; 5200 mResolveActivity.processName = null; 5201 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5202 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 5203 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 5204 mResolveActivity.theme = 0; 5205 mResolveActivity.exported = true; 5206 mResolveActivity.enabled = true; 5207 mResolveInfo.activityInfo = mResolveActivity; 5208 mResolveInfo.priority = 0; 5209 mResolveInfo.preferredOrder = 0; 5210 mResolveInfo.match = 0; 5211 mResolveComponentName = mCustomResolverComponentName; 5212 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 5213 mResolveComponentName); 5214 } 5215 } 5216 5217 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 5218 PackageSetting pkgSetting) { 5219 final String apkLibPath = getApkName(pkgSetting.codePathString); 5220 final String nativeLibraryPath = new File(mAppLibInstallDir, apkLibPath).getPath(); 5221 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 5222 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 5223 } 5224 5225 private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir) 5226 throws IOException { 5227 if (!nativeLibraryDir.isDirectory()) { 5228 nativeLibraryDir.delete(); 5229 5230 if (!nativeLibraryDir.mkdir()) { 5231 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 5232 } 5233 5234 try { 5235 Libcore.os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH 5236 | S_IXOTH); 5237 } catch (ErrnoException e) { 5238 throw new IOException("Cannot chmod native library directory " 5239 + nativeLibraryDir.getPath(), e); 5240 } 5241 } else if (!SELinux.restorecon(nativeLibraryDir)) { 5242 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 5243 } 5244 5245 /* 5246 * If this is an internal application or our nativeLibraryPath points to 5247 * the app-lib directory, unpack the libraries if necessary. 5248 */ 5249 return NativeLibraryHelper.copyNativeBinariesIfNeededLI(scanFile, nativeLibraryDir); 5250 } 5251 5252 private void killApplication(String pkgName, int appId, String reason) { 5253 // Request the ActivityManager to kill the process(only for existing packages) 5254 // so that we do not end up in a confused state while the user is still using the older 5255 // version of the application while the new one gets installed. 5256 IActivityManager am = ActivityManagerNative.getDefault(); 5257 if (am != null) { 5258 try { 5259 am.killApplicationWithAppId(pkgName, appId, reason); 5260 } catch (RemoteException e) { 5261 } 5262 } 5263 } 5264 5265 void removePackageLI(PackageSetting ps, boolean chatty) { 5266 if (DEBUG_INSTALL) { 5267 if (chatty) 5268 Log.d(TAG, "Removing package " + ps.name); 5269 } 5270 5271 // writer 5272 synchronized (mPackages) { 5273 mPackages.remove(ps.name); 5274 if (ps.codePathString != null) { 5275 mAppDirs.remove(ps.codePathString); 5276 } 5277 5278 final PackageParser.Package pkg = ps.pkg; 5279 if (pkg != null) { 5280 cleanPackageDataStructuresLILPw(pkg, chatty); 5281 } 5282 } 5283 } 5284 5285 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 5286 if (DEBUG_INSTALL) { 5287 if (chatty) 5288 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 5289 } 5290 5291 // writer 5292 synchronized (mPackages) { 5293 mPackages.remove(pkg.applicationInfo.packageName); 5294 if (pkg.mPath != null) { 5295 mAppDirs.remove(pkg.mPath); 5296 } 5297 cleanPackageDataStructuresLILPw(pkg, chatty); 5298 } 5299 } 5300 5301 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 5302 int N = pkg.providers.size(); 5303 StringBuilder r = null; 5304 int i; 5305 for (i=0; i<N; i++) { 5306 PackageParser.Provider p = pkg.providers.get(i); 5307 mProviders.removeProvider(p); 5308 if (p.info.authority == null) { 5309 5310 /* There was another ContentProvider with this authority when 5311 * this app was installed so this authority is null, 5312 * Ignore it as we don't have to unregister the provider. 5313 */ 5314 continue; 5315 } 5316 String names[] = p.info.authority.split(";"); 5317 for (int j = 0; j < names.length; j++) { 5318 if (mProvidersByAuthority.get(names[j]) == p) { 5319 mProvidersByAuthority.remove(names[j]); 5320 if (DEBUG_REMOVE) { 5321 if (chatty) 5322 Log.d(TAG, "Unregistered content provider: " + names[j] 5323 + ", className = " + p.info.name + ", isSyncable = " 5324 + p.info.isSyncable); 5325 } 5326 } 5327 } 5328 if (DEBUG_REMOVE && chatty) { 5329 if (r == null) { 5330 r = new StringBuilder(256); 5331 } else { 5332 r.append(' '); 5333 } 5334 r.append(p.info.name); 5335 } 5336 } 5337 if (r != null) { 5338 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 5339 } 5340 5341 N = pkg.services.size(); 5342 r = null; 5343 for (i=0; i<N; i++) { 5344 PackageParser.Service s = pkg.services.get(i); 5345 mServices.removeService(s); 5346 if (chatty) { 5347 if (r == null) { 5348 r = new StringBuilder(256); 5349 } else { 5350 r.append(' '); 5351 } 5352 r.append(s.info.name); 5353 } 5354 } 5355 if (r != null) { 5356 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 5357 } 5358 5359 N = pkg.receivers.size(); 5360 r = null; 5361 for (i=0; i<N; i++) { 5362 PackageParser.Activity a = pkg.receivers.get(i); 5363 mReceivers.removeActivity(a, "receiver"); 5364 if (DEBUG_REMOVE && chatty) { 5365 if (r == null) { 5366 r = new StringBuilder(256); 5367 } else { 5368 r.append(' '); 5369 } 5370 r.append(a.info.name); 5371 } 5372 } 5373 if (r != null) { 5374 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 5375 } 5376 5377 N = pkg.activities.size(); 5378 r = null; 5379 for (i=0; i<N; i++) { 5380 PackageParser.Activity a = pkg.activities.get(i); 5381 mActivities.removeActivity(a, "activity"); 5382 if (DEBUG_REMOVE && chatty) { 5383 if (r == null) { 5384 r = new StringBuilder(256); 5385 } else { 5386 r.append(' '); 5387 } 5388 r.append(a.info.name); 5389 } 5390 } 5391 if (r != null) { 5392 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 5393 } 5394 5395 N = pkg.permissions.size(); 5396 r = null; 5397 for (i=0; i<N; i++) { 5398 PackageParser.Permission p = pkg.permissions.get(i); 5399 BasePermission bp = mSettings.mPermissions.get(p.info.name); 5400 if (bp == null) { 5401 bp = mSettings.mPermissionTrees.get(p.info.name); 5402 } 5403 if (bp != null && bp.perm == p) { 5404 bp.perm = null; 5405 if (DEBUG_REMOVE && chatty) { 5406 if (r == null) { 5407 r = new StringBuilder(256); 5408 } else { 5409 r.append(' '); 5410 } 5411 r.append(p.info.name); 5412 } 5413 } 5414 } 5415 if (r != null) { 5416 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 5417 } 5418 5419 N = pkg.instrumentation.size(); 5420 r = null; 5421 for (i=0; i<N; i++) { 5422 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5423 mInstrumentation.remove(a.getComponentName()); 5424 if (DEBUG_REMOVE && chatty) { 5425 if (r == null) { 5426 r = new StringBuilder(256); 5427 } else { 5428 r.append(' '); 5429 } 5430 r.append(a.info.name); 5431 } 5432 } 5433 if (r != null) { 5434 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 5435 } 5436 5437 r = null; 5438 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5439 // Only system apps can hold shared libraries. 5440 if (pkg.libraryNames != null) { 5441 for (i=0; i<pkg.libraryNames.size(); i++) { 5442 String name = pkg.libraryNames.get(i); 5443 SharedLibraryEntry cur = mSharedLibraries.get(name); 5444 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 5445 mSharedLibraries.remove(name); 5446 if (DEBUG_REMOVE && chatty) { 5447 if (r == null) { 5448 r = new StringBuilder(256); 5449 } else { 5450 r.append(' '); 5451 } 5452 r.append(name); 5453 } 5454 } 5455 } 5456 } 5457 } 5458 if (r != null) { 5459 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 5460 } 5461 } 5462 5463 private static final boolean isPackageFilename(String name) { 5464 return name != null && name.endsWith(".apk"); 5465 } 5466 5467 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 5468 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 5469 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 5470 return true; 5471 } 5472 } 5473 return false; 5474 } 5475 5476 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 5477 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 5478 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 5479 5480 private void updatePermissionsLPw(String changingPkg, 5481 PackageParser.Package pkgInfo, int flags) { 5482 // Make sure there are no dangling permission trees. 5483 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 5484 while (it.hasNext()) { 5485 final BasePermission bp = it.next(); 5486 if (bp.packageSetting == null) { 5487 // We may not yet have parsed the package, so just see if 5488 // we still know about its settings. 5489 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 5490 } 5491 if (bp.packageSetting == null) { 5492 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 5493 + " from package " + bp.sourcePackage); 5494 it.remove(); 5495 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 5496 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 5497 Slog.i(TAG, "Removing old permission tree: " + bp.name 5498 + " from package " + bp.sourcePackage); 5499 flags |= UPDATE_PERMISSIONS_ALL; 5500 it.remove(); 5501 } 5502 } 5503 } 5504 5505 // Make sure all dynamic permissions have been assigned to a package, 5506 // and make sure there are no dangling permissions. 5507 it = mSettings.mPermissions.values().iterator(); 5508 while (it.hasNext()) { 5509 final BasePermission bp = it.next(); 5510 if (bp.type == BasePermission.TYPE_DYNAMIC) { 5511 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 5512 + bp.name + " pkg=" + bp.sourcePackage 5513 + " info=" + bp.pendingInfo); 5514 if (bp.packageSetting == null && bp.pendingInfo != null) { 5515 final BasePermission tree = findPermissionTreeLP(bp.name); 5516 if (tree != null && tree.perm != null) { 5517 bp.packageSetting = tree.packageSetting; 5518 bp.perm = new PackageParser.Permission(tree.perm.owner, 5519 new PermissionInfo(bp.pendingInfo)); 5520 bp.perm.info.packageName = tree.perm.info.packageName; 5521 bp.perm.info.name = bp.name; 5522 bp.uid = tree.uid; 5523 } 5524 } 5525 } 5526 if (bp.packageSetting == null) { 5527 // We may not yet have parsed the package, so just see if 5528 // we still know about its settings. 5529 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 5530 } 5531 if (bp.packageSetting == null) { 5532 Slog.w(TAG, "Removing dangling permission: " + bp.name 5533 + " from package " + bp.sourcePackage); 5534 it.remove(); 5535 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 5536 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 5537 Slog.i(TAG, "Removing old permission: " + bp.name 5538 + " from package " + bp.sourcePackage); 5539 flags |= UPDATE_PERMISSIONS_ALL; 5540 it.remove(); 5541 } 5542 } 5543 } 5544 5545 // Now update the permissions for all packages, in particular 5546 // replace the granted permissions of the system packages. 5547 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 5548 for (PackageParser.Package pkg : mPackages.values()) { 5549 if (pkg != pkgInfo) { 5550 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 5551 } 5552 } 5553 } 5554 5555 if (pkgInfo != null) { 5556 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 5557 } 5558 } 5559 5560 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 5561 final PackageSetting ps = (PackageSetting) pkg.mExtras; 5562 if (ps == null) { 5563 return; 5564 } 5565 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 5566 HashSet<String> origPermissions = gp.grantedPermissions; 5567 boolean changedPermission = false; 5568 5569 if (replace) { 5570 ps.permissionsFixed = false; 5571 if (gp == ps) { 5572 origPermissions = new HashSet<String>(gp.grantedPermissions); 5573 gp.grantedPermissions.clear(); 5574 gp.gids = mGlobalGids; 5575 } 5576 } 5577 5578 if (gp.gids == null) { 5579 gp.gids = mGlobalGids; 5580 } 5581 5582 final int N = pkg.requestedPermissions.size(); 5583 for (int i=0; i<N; i++) { 5584 final String name = pkg.requestedPermissions.get(i); 5585 final boolean required = pkg.requestedPermissionsRequired.get(i); 5586 final BasePermission bp = mSettings.mPermissions.get(name); 5587 if (DEBUG_INSTALL) { 5588 if (gp != ps) { 5589 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 5590 } 5591 } 5592 5593 if (bp == null || bp.packageSetting == null) { 5594 Slog.w(TAG, "Unknown permission " + name 5595 + " in package " + pkg.packageName); 5596 continue; 5597 } 5598 5599 final String perm = bp.name; 5600 boolean allowed; 5601 boolean allowedSig = false; 5602 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 5603 if (level == PermissionInfo.PROTECTION_NORMAL 5604 || level == PermissionInfo.PROTECTION_DANGEROUS) { 5605 // We grant a normal or dangerous permission if any of the following 5606 // are true: 5607 // 1) The permission is required 5608 // 2) The permission is optional, but was granted in the past 5609 // 3) The permission is optional, but was requested by an 5610 // app in /system (not /data) 5611 // 5612 // Otherwise, reject the permission. 5613 allowed = (required || origPermissions.contains(perm) 5614 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 5615 } else if (bp.packageSetting == null) { 5616 // This permission is invalid; skip it. 5617 allowed = false; 5618 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 5619 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 5620 if (allowed) { 5621 allowedSig = true; 5622 } 5623 } else { 5624 allowed = false; 5625 } 5626 if (DEBUG_INSTALL) { 5627 if (gp != ps) { 5628 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 5629 } 5630 } 5631 if (allowed) { 5632 if (!isSystemApp(ps) && ps.permissionsFixed) { 5633 // If this is an existing, non-system package, then 5634 // we can't add any new permissions to it. 5635 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 5636 // Except... if this is a permission that was added 5637 // to the platform (note: need to only do this when 5638 // updating the platform). 5639 allowed = isNewPlatformPermissionForPackage(perm, pkg); 5640 } 5641 } 5642 if (allowed) { 5643 if (!gp.grantedPermissions.contains(perm)) { 5644 changedPermission = true; 5645 gp.grantedPermissions.add(perm); 5646 gp.gids = appendInts(gp.gids, bp.gids); 5647 } else if (!ps.haveGids) { 5648 gp.gids = appendInts(gp.gids, bp.gids); 5649 } 5650 } else { 5651 Slog.w(TAG, "Not granting permission " + perm 5652 + " to package " + pkg.packageName 5653 + " because it was previously installed without"); 5654 } 5655 } else { 5656 if (gp.grantedPermissions.remove(perm)) { 5657 changedPermission = true; 5658 gp.gids = removeInts(gp.gids, bp.gids); 5659 Slog.i(TAG, "Un-granting permission " + perm 5660 + " from package " + pkg.packageName 5661 + " (protectionLevel=" + bp.protectionLevel 5662 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 5663 + ")"); 5664 } else { 5665 Slog.w(TAG, "Not granting permission " + perm 5666 + " to package " + pkg.packageName 5667 + " (protectionLevel=" + bp.protectionLevel 5668 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 5669 + ")"); 5670 } 5671 } 5672 } 5673 5674 if ((changedPermission || replace) && !ps.permissionsFixed && 5675 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 5676 // This is the first that we have heard about this package, so the 5677 // permissions we have now selected are fixed until explicitly 5678 // changed. 5679 ps.permissionsFixed = true; 5680 } 5681 ps.haveGids = true; 5682 } 5683 5684 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 5685 boolean allowed = false; 5686 final int NP = PackageParser.NEW_PERMISSIONS.length; 5687 for (int ip=0; ip<NP; ip++) { 5688 final PackageParser.NewPermissionInfo npi 5689 = PackageParser.NEW_PERMISSIONS[ip]; 5690 if (npi.name.equals(perm) 5691 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 5692 allowed = true; 5693 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 5694 + pkg.packageName); 5695 break; 5696 } 5697 } 5698 return allowed; 5699 } 5700 5701 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 5702 BasePermission bp, HashSet<String> origPermissions) { 5703 boolean allowed; 5704 allowed = (compareSignatures( 5705 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 5706 == PackageManager.SIGNATURE_MATCH) 5707 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 5708 == PackageManager.SIGNATURE_MATCH); 5709 if (!allowed && (bp.protectionLevel 5710 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 5711 if (isSystemApp(pkg)) { 5712 // For updated system applications, a system permission 5713 // is granted only if it had been defined by the original application. 5714 if (isUpdatedSystemApp(pkg)) { 5715 final PackageSetting sysPs = mSettings 5716 .getDisabledSystemPkgLPr(pkg.packageName); 5717 final GrantedPermissions origGp = sysPs.sharedUser != null 5718 ? sysPs.sharedUser : sysPs; 5719 5720 if (origGp.grantedPermissions.contains(perm)) { 5721 // If the original was granted this permission, we take 5722 // that grant decision as read and propagate it to the 5723 // update. 5724 allowed = true; 5725 } else { 5726 // The system apk may have been updated with an older 5727 // version of the one on the data partition, but which 5728 // granted a new system permission that it didn't have 5729 // before. In this case we do want to allow the app to 5730 // now get the new permission if the ancestral apk is 5731 // privileged to get it. 5732 if (sysPs.pkg != null && sysPs.isPrivileged()) { 5733 for (int j=0; 5734 j<sysPs.pkg.requestedPermissions.size(); j++) { 5735 if (perm.equals( 5736 sysPs.pkg.requestedPermissions.get(j))) { 5737 allowed = true; 5738 break; 5739 } 5740 } 5741 } 5742 } 5743 } else { 5744 allowed = isPrivilegedApp(pkg); 5745 } 5746 } 5747 } 5748 if (!allowed && (bp.protectionLevel 5749 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 5750 // For development permissions, a development permission 5751 // is granted only if it was already granted. 5752 allowed = origPermissions.contains(perm); 5753 } 5754 return allowed; 5755 } 5756 5757 final class ActivityIntentResolver 5758 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 5759 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 5760 boolean defaultOnly, int userId) { 5761 if (!sUserManager.exists(userId)) return null; 5762 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 5763 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 5764 } 5765 5766 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 5767 int userId) { 5768 if (!sUserManager.exists(userId)) return null; 5769 mFlags = flags; 5770 return super.queryIntent(intent, resolvedType, 5771 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 5772 } 5773 5774 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 5775 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 5776 if (!sUserManager.exists(userId)) return null; 5777 if (packageActivities == null) { 5778 return null; 5779 } 5780 mFlags = flags; 5781 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 5782 final int N = packageActivities.size(); 5783 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 5784 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 5785 5786 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 5787 for (int i = 0; i < N; ++i) { 5788 intentFilters = packageActivities.get(i).intents; 5789 if (intentFilters != null && intentFilters.size() > 0) { 5790 PackageParser.ActivityIntentInfo[] array = 5791 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 5792 intentFilters.toArray(array); 5793 listCut.add(array); 5794 } 5795 } 5796 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 5797 } 5798 5799 public final void addActivity(PackageParser.Activity a, String type) { 5800 final boolean systemApp = isSystemApp(a.info.applicationInfo); 5801 mActivities.put(a.getComponentName(), a); 5802 if (DEBUG_SHOW_INFO) 5803 Log.v( 5804 TAG, " " + type + " " + 5805 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 5806 if (DEBUG_SHOW_INFO) 5807 Log.v(TAG, " Class=" + a.info.name); 5808 final int NI = a.intents.size(); 5809 for (int j=0; j<NI; j++) { 5810 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 5811 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 5812 intent.setPriority(0); 5813 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 5814 + a.className + " with priority > 0, forcing to 0"); 5815 } 5816 if (DEBUG_SHOW_INFO) { 5817 Log.v(TAG, " IntentFilter:"); 5818 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 5819 } 5820 if (!intent.debugCheck()) { 5821 Log.w(TAG, "==> For Activity " + a.info.name); 5822 } 5823 addFilter(intent); 5824 } 5825 } 5826 5827 public final void removeActivity(PackageParser.Activity a, String type) { 5828 mActivities.remove(a.getComponentName()); 5829 if (DEBUG_SHOW_INFO) { 5830 Log.v(TAG, " " + type + " " 5831 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 5832 : a.info.name) + ":"); 5833 Log.v(TAG, " Class=" + a.info.name); 5834 } 5835 final int NI = a.intents.size(); 5836 for (int j=0; j<NI; j++) { 5837 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 5838 if (DEBUG_SHOW_INFO) { 5839 Log.v(TAG, " IntentFilter:"); 5840 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 5841 } 5842 removeFilter(intent); 5843 } 5844 } 5845 5846 @Override 5847 protected boolean allowFilterResult( 5848 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 5849 ActivityInfo filterAi = filter.activity.info; 5850 for (int i=dest.size()-1; i>=0; i--) { 5851 ActivityInfo destAi = dest.get(i).activityInfo; 5852 if (destAi.name == filterAi.name 5853 && destAi.packageName == filterAi.packageName) { 5854 return false; 5855 } 5856 } 5857 return true; 5858 } 5859 5860 @Override 5861 protected ActivityIntentInfo[] newArray(int size) { 5862 return new ActivityIntentInfo[size]; 5863 } 5864 5865 @Override 5866 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 5867 if (!sUserManager.exists(userId)) return true; 5868 PackageParser.Package p = filter.activity.owner; 5869 if (p != null) { 5870 PackageSetting ps = (PackageSetting)p.mExtras; 5871 if (ps != null) { 5872 // System apps are never considered stopped for purposes of 5873 // filtering, because there may be no way for the user to 5874 // actually re-launch them. 5875 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 5876 && ps.getStopped(userId); 5877 } 5878 } 5879 return false; 5880 } 5881 5882 @Override 5883 protected boolean isPackageForFilter(String packageName, 5884 PackageParser.ActivityIntentInfo info) { 5885 return packageName.equals(info.activity.owner.packageName); 5886 } 5887 5888 @Override 5889 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 5890 int match, int userId) { 5891 if (!sUserManager.exists(userId)) return null; 5892 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 5893 return null; 5894 } 5895 final PackageParser.Activity activity = info.activity; 5896 if (mSafeMode && (activity.info.applicationInfo.flags 5897 &ApplicationInfo.FLAG_SYSTEM) == 0) { 5898 return null; 5899 } 5900 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 5901 if (ps == null) { 5902 return null; 5903 } 5904 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 5905 ps.readUserState(userId), userId); 5906 if (ai == null) { 5907 return null; 5908 } 5909 final ResolveInfo res = new ResolveInfo(); 5910 res.activityInfo = ai; 5911 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 5912 res.filter = info; 5913 } 5914 res.priority = info.getPriority(); 5915 res.preferredOrder = activity.owner.mPreferredOrder; 5916 //System.out.println("Result: " + res.activityInfo.className + 5917 // " = " + res.priority); 5918 res.match = match; 5919 res.isDefault = info.hasDefault; 5920 res.labelRes = info.labelRes; 5921 res.nonLocalizedLabel = info.nonLocalizedLabel; 5922 res.icon = info.icon; 5923 res.system = isSystemApp(res.activityInfo.applicationInfo); 5924 return res; 5925 } 5926 5927 @Override 5928 protected void sortResults(List<ResolveInfo> results) { 5929 Collections.sort(results, mResolvePrioritySorter); 5930 } 5931 5932 @Override 5933 protected void dumpFilter(PrintWriter out, String prefix, 5934 PackageParser.ActivityIntentInfo filter) { 5935 out.print(prefix); out.print( 5936 Integer.toHexString(System.identityHashCode(filter.activity))); 5937 out.print(' '); 5938 filter.activity.printComponentShortName(out); 5939 out.print(" filter "); 5940 out.println(Integer.toHexString(System.identityHashCode(filter))); 5941 } 5942 5943// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 5944// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 5945// final List<ResolveInfo> retList = Lists.newArrayList(); 5946// while (i.hasNext()) { 5947// final ResolveInfo resolveInfo = i.next(); 5948// if (isEnabledLP(resolveInfo.activityInfo)) { 5949// retList.add(resolveInfo); 5950// } 5951// } 5952// return retList; 5953// } 5954 5955 // Keys are String (activity class name), values are Activity. 5956 private final HashMap<ComponentName, PackageParser.Activity> mActivities 5957 = new HashMap<ComponentName, PackageParser.Activity>(); 5958 private int mFlags; 5959 } 5960 5961 private final class ServiceIntentResolver 5962 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 5963 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 5964 boolean defaultOnly, int userId) { 5965 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 5966 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 5967 } 5968 5969 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 5970 int userId) { 5971 if (!sUserManager.exists(userId)) return null; 5972 mFlags = flags; 5973 return super.queryIntent(intent, resolvedType, 5974 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 5975 } 5976 5977 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 5978 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 5979 if (!sUserManager.exists(userId)) return null; 5980 if (packageServices == null) { 5981 return null; 5982 } 5983 mFlags = flags; 5984 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 5985 final int N = packageServices.size(); 5986 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 5987 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 5988 5989 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 5990 for (int i = 0; i < N; ++i) { 5991 intentFilters = packageServices.get(i).intents; 5992 if (intentFilters != null && intentFilters.size() > 0) { 5993 PackageParser.ServiceIntentInfo[] array = 5994 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 5995 intentFilters.toArray(array); 5996 listCut.add(array); 5997 } 5998 } 5999 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6000 } 6001 6002 public final void addService(PackageParser.Service s) { 6003 mServices.put(s.getComponentName(), s); 6004 if (DEBUG_SHOW_INFO) { 6005 Log.v(TAG, " " 6006 + (s.info.nonLocalizedLabel != null 6007 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6008 Log.v(TAG, " Class=" + s.info.name); 6009 } 6010 final int NI = s.intents.size(); 6011 int j; 6012 for (j=0; j<NI; j++) { 6013 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6014 if (DEBUG_SHOW_INFO) { 6015 Log.v(TAG, " IntentFilter:"); 6016 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6017 } 6018 if (!intent.debugCheck()) { 6019 Log.w(TAG, "==> For Service " + s.info.name); 6020 } 6021 addFilter(intent); 6022 } 6023 } 6024 6025 public final void removeService(PackageParser.Service s) { 6026 mServices.remove(s.getComponentName()); 6027 if (DEBUG_SHOW_INFO) { 6028 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 6029 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6030 Log.v(TAG, " Class=" + s.info.name); 6031 } 6032 final int NI = s.intents.size(); 6033 int j; 6034 for (j=0; j<NI; j++) { 6035 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6036 if (DEBUG_SHOW_INFO) { 6037 Log.v(TAG, " IntentFilter:"); 6038 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6039 } 6040 removeFilter(intent); 6041 } 6042 } 6043 6044 @Override 6045 protected boolean allowFilterResult( 6046 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 6047 ServiceInfo filterSi = filter.service.info; 6048 for (int i=dest.size()-1; i>=0; i--) { 6049 ServiceInfo destAi = dest.get(i).serviceInfo; 6050 if (destAi.name == filterSi.name 6051 && destAi.packageName == filterSi.packageName) { 6052 return false; 6053 } 6054 } 6055 return true; 6056 } 6057 6058 @Override 6059 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 6060 return new PackageParser.ServiceIntentInfo[size]; 6061 } 6062 6063 @Override 6064 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 6065 if (!sUserManager.exists(userId)) return true; 6066 PackageParser.Package p = filter.service.owner; 6067 if (p != null) { 6068 PackageSetting ps = (PackageSetting)p.mExtras; 6069 if (ps != null) { 6070 // System apps are never considered stopped for purposes of 6071 // filtering, because there may be no way for the user to 6072 // actually re-launch them. 6073 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 6074 && ps.getStopped(userId); 6075 } 6076 } 6077 return false; 6078 } 6079 6080 @Override 6081 protected boolean isPackageForFilter(String packageName, 6082 PackageParser.ServiceIntentInfo info) { 6083 return packageName.equals(info.service.owner.packageName); 6084 } 6085 6086 @Override 6087 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 6088 int match, int userId) { 6089 if (!sUserManager.exists(userId)) return null; 6090 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 6091 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 6092 return null; 6093 } 6094 final PackageParser.Service service = info.service; 6095 if (mSafeMode && (service.info.applicationInfo.flags 6096 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6097 return null; 6098 } 6099 PackageSetting ps = (PackageSetting) service.owner.mExtras; 6100 if (ps == null) { 6101 return null; 6102 } 6103 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 6104 ps.readUserState(userId), userId); 6105 if (si == null) { 6106 return null; 6107 } 6108 final ResolveInfo res = new ResolveInfo(); 6109 res.serviceInfo = si; 6110 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6111 res.filter = filter; 6112 } 6113 res.priority = info.getPriority(); 6114 res.preferredOrder = service.owner.mPreferredOrder; 6115 //System.out.println("Result: " + res.activityInfo.className + 6116 // " = " + res.priority); 6117 res.match = match; 6118 res.isDefault = info.hasDefault; 6119 res.labelRes = info.labelRes; 6120 res.nonLocalizedLabel = info.nonLocalizedLabel; 6121 res.icon = info.icon; 6122 res.system = isSystemApp(res.serviceInfo.applicationInfo); 6123 return res; 6124 } 6125 6126 @Override 6127 protected void sortResults(List<ResolveInfo> results) { 6128 Collections.sort(results, mResolvePrioritySorter); 6129 } 6130 6131 @Override 6132 protected void dumpFilter(PrintWriter out, String prefix, 6133 PackageParser.ServiceIntentInfo filter) { 6134 out.print(prefix); out.print( 6135 Integer.toHexString(System.identityHashCode(filter.service))); 6136 out.print(' '); 6137 filter.service.printComponentShortName(out); 6138 out.print(" filter "); 6139 out.println(Integer.toHexString(System.identityHashCode(filter))); 6140 } 6141 6142// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6143// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6144// final List<ResolveInfo> retList = Lists.newArrayList(); 6145// while (i.hasNext()) { 6146// final ResolveInfo resolveInfo = (ResolveInfo) i; 6147// if (isEnabledLP(resolveInfo.serviceInfo)) { 6148// retList.add(resolveInfo); 6149// } 6150// } 6151// return retList; 6152// } 6153 6154 // Keys are String (activity class name), values are Activity. 6155 private final HashMap<ComponentName, PackageParser.Service> mServices 6156 = new HashMap<ComponentName, PackageParser.Service>(); 6157 private int mFlags; 6158 }; 6159 6160 private final class ProviderIntentResolver 6161 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 6162 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6163 boolean defaultOnly, int userId) { 6164 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6165 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6166 } 6167 6168 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6169 int userId) { 6170 if (!sUserManager.exists(userId)) 6171 return null; 6172 mFlags = flags; 6173 return super.queryIntent(intent, resolvedType, 6174 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6175 } 6176 6177 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6178 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 6179 if (!sUserManager.exists(userId)) 6180 return null; 6181 if (packageProviders == null) { 6182 return null; 6183 } 6184 mFlags = flags; 6185 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 6186 final int N = packageProviders.size(); 6187 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 6188 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 6189 6190 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 6191 for (int i = 0; i < N; ++i) { 6192 intentFilters = packageProviders.get(i).intents; 6193 if (intentFilters != null && intentFilters.size() > 0) { 6194 PackageParser.ProviderIntentInfo[] array = 6195 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 6196 intentFilters.toArray(array); 6197 listCut.add(array); 6198 } 6199 } 6200 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6201 } 6202 6203 public final void addProvider(PackageParser.Provider p) { 6204 mProviders.put(p.getComponentName(), p); 6205 if (DEBUG_SHOW_INFO) { 6206 Log.v(TAG, " " 6207 + (p.info.nonLocalizedLabel != null 6208 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 6209 Log.v(TAG, " Class=" + p.info.name); 6210 } 6211 final int NI = p.intents.size(); 6212 int j; 6213 for (j = 0; j < NI; j++) { 6214 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 6215 if (DEBUG_SHOW_INFO) { 6216 Log.v(TAG, " IntentFilter:"); 6217 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6218 } 6219 if (!intent.debugCheck()) { 6220 Log.w(TAG, "==> For Provider " + p.info.name); 6221 } 6222 addFilter(intent); 6223 } 6224 } 6225 6226 public final void removeProvider(PackageParser.Provider p) { 6227 mProviders.remove(p.getComponentName()); 6228 if (DEBUG_SHOW_INFO) { 6229 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 6230 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 6231 Log.v(TAG, " Class=" + p.info.name); 6232 } 6233 final int NI = p.intents.size(); 6234 int j; 6235 for (j = 0; j < NI; j++) { 6236 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 6237 if (DEBUG_SHOW_INFO) { 6238 Log.v(TAG, " IntentFilter:"); 6239 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6240 } 6241 removeFilter(intent); 6242 } 6243 } 6244 6245 @Override 6246 protected boolean allowFilterResult( 6247 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 6248 ProviderInfo filterPi = filter.provider.info; 6249 for (int i = dest.size() - 1; i >= 0; i--) { 6250 ProviderInfo destPi = dest.get(i).providerInfo; 6251 if (destPi.name == filterPi.name 6252 && destPi.packageName == filterPi.packageName) { 6253 return false; 6254 } 6255 } 6256 return true; 6257 } 6258 6259 @Override 6260 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 6261 return new PackageParser.ProviderIntentInfo[size]; 6262 } 6263 6264 @Override 6265 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 6266 if (!sUserManager.exists(userId)) 6267 return true; 6268 PackageParser.Package p = filter.provider.owner; 6269 if (p != null) { 6270 PackageSetting ps = (PackageSetting) p.mExtras; 6271 if (ps != null) { 6272 // System apps are never considered stopped for purposes of 6273 // filtering, because there may be no way for the user to 6274 // actually re-launch them. 6275 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 6276 && ps.getStopped(userId); 6277 } 6278 } 6279 return false; 6280 } 6281 6282 @Override 6283 protected boolean isPackageForFilter(String packageName, 6284 PackageParser.ProviderIntentInfo info) { 6285 return packageName.equals(info.provider.owner.packageName); 6286 } 6287 6288 @Override 6289 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 6290 int match, int userId) { 6291 if (!sUserManager.exists(userId)) 6292 return null; 6293 final PackageParser.ProviderIntentInfo info = filter; 6294 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 6295 return null; 6296 } 6297 final PackageParser.Provider provider = info.provider; 6298 if (mSafeMode && (provider.info.applicationInfo.flags 6299 & ApplicationInfo.FLAG_SYSTEM) == 0) { 6300 return null; 6301 } 6302 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 6303 if (ps == null) { 6304 return null; 6305 } 6306 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 6307 ps.readUserState(userId), userId); 6308 if (pi == null) { 6309 return null; 6310 } 6311 final ResolveInfo res = new ResolveInfo(); 6312 res.providerInfo = pi; 6313 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 6314 res.filter = filter; 6315 } 6316 res.priority = info.getPriority(); 6317 res.preferredOrder = provider.owner.mPreferredOrder; 6318 res.match = match; 6319 res.isDefault = info.hasDefault; 6320 res.labelRes = info.labelRes; 6321 res.nonLocalizedLabel = info.nonLocalizedLabel; 6322 res.icon = info.icon; 6323 res.system = isSystemApp(res.providerInfo.applicationInfo); 6324 return res; 6325 } 6326 6327 @Override 6328 protected void sortResults(List<ResolveInfo> results) { 6329 Collections.sort(results, mResolvePrioritySorter); 6330 } 6331 6332 @Override 6333 protected void dumpFilter(PrintWriter out, String prefix, 6334 PackageParser.ProviderIntentInfo filter) { 6335 out.print(prefix); 6336 out.print( 6337 Integer.toHexString(System.identityHashCode(filter.provider))); 6338 out.print(' '); 6339 filter.provider.printComponentShortName(out); 6340 out.print(" filter "); 6341 out.println(Integer.toHexString(System.identityHashCode(filter))); 6342 } 6343 6344 private final HashMap<ComponentName, PackageParser.Provider> mProviders 6345 = new HashMap<ComponentName, PackageParser.Provider>(); 6346 private int mFlags; 6347 }; 6348 6349 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 6350 new Comparator<ResolveInfo>() { 6351 public int compare(ResolveInfo r1, ResolveInfo r2) { 6352 int v1 = r1.priority; 6353 int v2 = r2.priority; 6354 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 6355 if (v1 != v2) { 6356 return (v1 > v2) ? -1 : 1; 6357 } 6358 v1 = r1.preferredOrder; 6359 v2 = r2.preferredOrder; 6360 if (v1 != v2) { 6361 return (v1 > v2) ? -1 : 1; 6362 } 6363 if (r1.isDefault != r2.isDefault) { 6364 return r1.isDefault ? -1 : 1; 6365 } 6366 v1 = r1.match; 6367 v2 = r2.match; 6368 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 6369 if (v1 != v2) { 6370 return (v1 > v2) ? -1 : 1; 6371 } 6372 if (r1.system != r2.system) { 6373 return r1.system ? -1 : 1; 6374 } 6375 return 0; 6376 } 6377 }; 6378 6379 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 6380 new Comparator<ProviderInfo>() { 6381 public int compare(ProviderInfo p1, ProviderInfo p2) { 6382 final int v1 = p1.initOrder; 6383 final int v2 = p2.initOrder; 6384 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 6385 } 6386 }; 6387 6388 static final void sendPackageBroadcast(String action, String pkg, 6389 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 6390 int[] userIds) { 6391 IActivityManager am = ActivityManagerNative.getDefault(); 6392 if (am != null) { 6393 try { 6394 if (userIds == null) { 6395 userIds = am.getRunningUserIds(); 6396 } 6397 for (int id : userIds) { 6398 final Intent intent = new Intent(action, 6399 pkg != null ? Uri.fromParts("package", pkg, null) : null); 6400 if (extras != null) { 6401 intent.putExtras(extras); 6402 } 6403 if (targetPkg != null) { 6404 intent.setPackage(targetPkg); 6405 } 6406 // Modify the UID when posting to other users 6407 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 6408 if (uid > 0 && UserHandle.getUserId(uid) != id) { 6409 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 6410 intent.putExtra(Intent.EXTRA_UID, uid); 6411 } 6412 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 6413 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 6414 if (DEBUG_BROADCASTS) { 6415 RuntimeException here = new RuntimeException("here"); 6416 here.fillInStackTrace(); 6417 Slog.d(TAG, "Sending to user " + id + ": " 6418 + intent.toShortString(false, true, false, false) 6419 + " " + intent.getExtras(), here); 6420 } 6421 am.broadcastIntent(null, intent, null, finishedReceiver, 6422 0, null, null, null, android.app.AppOpsManager.OP_NONE, 6423 finishedReceiver != null, false, id); 6424 } 6425 } catch (RemoteException ex) { 6426 } 6427 } 6428 } 6429 6430 /** 6431 * Check if the external storage media is available. This is true if there 6432 * is a mounted external storage medium or if the external storage is 6433 * emulated. 6434 */ 6435 private boolean isExternalMediaAvailable() { 6436 return mMediaMounted || Environment.isExternalStorageEmulated(); 6437 } 6438 6439 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 6440 // writer 6441 synchronized (mPackages) { 6442 if (!isExternalMediaAvailable()) { 6443 // If the external storage is no longer mounted at this point, 6444 // the caller may not have been able to delete all of this 6445 // packages files and can not delete any more. Bail. 6446 return null; 6447 } 6448 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 6449 if (lastPackage != null) { 6450 pkgs.remove(lastPackage); 6451 } 6452 if (pkgs.size() > 0) { 6453 return pkgs.get(0); 6454 } 6455 } 6456 return null; 6457 } 6458 6459 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 6460 if (false) { 6461 RuntimeException here = new RuntimeException("here"); 6462 here.fillInStackTrace(); 6463 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 6464 + " andCode=" + andCode, here); 6465 } 6466 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 6467 userId, andCode ? 1 : 0, packageName)); 6468 } 6469 6470 void startCleaningPackages() { 6471 // reader 6472 synchronized (mPackages) { 6473 if (!isExternalMediaAvailable()) { 6474 return; 6475 } 6476 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 6477 return; 6478 } 6479 } 6480 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 6481 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 6482 IActivityManager am = ActivityManagerNative.getDefault(); 6483 if (am != null) { 6484 try { 6485 am.startService(null, intent, null, UserHandle.USER_OWNER); 6486 } catch (RemoteException e) { 6487 } 6488 } 6489 } 6490 6491 private final class AppDirObserver extends FileObserver { 6492 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 6493 super(path, mask); 6494 mRootDir = path; 6495 mIsRom = isrom; 6496 mIsPrivileged = isPrivileged; 6497 } 6498 6499 public void onEvent(int event, String path) { 6500 String removedPackage = null; 6501 int removedAppId = -1; 6502 int[] removedUsers = null; 6503 String addedPackage = null; 6504 int addedAppId = -1; 6505 int[] addedUsers = null; 6506 6507 // TODO post a message to the handler to obtain serial ordering 6508 synchronized (mInstallLock) { 6509 String fullPathStr = null; 6510 File fullPath = null; 6511 if (path != null) { 6512 fullPath = new File(mRootDir, path); 6513 fullPathStr = fullPath.getPath(); 6514 } 6515 6516 if (DEBUG_APP_DIR_OBSERVER) 6517 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 6518 6519 if (!isPackageFilename(path)) { 6520 if (DEBUG_APP_DIR_OBSERVER) 6521 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 6522 return; 6523 } 6524 6525 // Ignore packages that are being installed or 6526 // have just been installed. 6527 if (ignoreCodePath(fullPathStr)) { 6528 return; 6529 } 6530 PackageParser.Package p = null; 6531 PackageSetting ps = null; 6532 // reader 6533 synchronized (mPackages) { 6534 p = mAppDirs.get(fullPathStr); 6535 if (p != null) { 6536 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 6537 if (ps != null) { 6538 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 6539 } else { 6540 removedUsers = sUserManager.getUserIds(); 6541 } 6542 } 6543 addedUsers = sUserManager.getUserIds(); 6544 } 6545 if ((event&REMOVE_EVENTS) != 0) { 6546 if (ps != null) { 6547 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 6548 removePackageLI(ps, true); 6549 removedPackage = ps.name; 6550 removedAppId = ps.appId; 6551 } 6552 } 6553 6554 if ((event&ADD_EVENTS) != 0) { 6555 if (p == null) { 6556 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 6557 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 6558 if (mIsRom) { 6559 flags |= PackageParser.PARSE_IS_SYSTEM 6560 | PackageParser.PARSE_IS_SYSTEM_DIR; 6561 if (mIsPrivileged) { 6562 flags |= PackageParser.PARSE_IS_PRIVILEGED; 6563 } 6564 } 6565 p = scanPackageLI(fullPath, flags, 6566 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 6567 System.currentTimeMillis(), UserHandle.ALL); 6568 if (p != null) { 6569 /* 6570 * TODO this seems dangerous as the package may have 6571 * changed since we last acquired the mPackages 6572 * lock. 6573 */ 6574 // writer 6575 synchronized (mPackages) { 6576 updatePermissionsLPw(p.packageName, p, 6577 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 6578 } 6579 addedPackage = p.applicationInfo.packageName; 6580 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 6581 } 6582 } 6583 } 6584 6585 // reader 6586 synchronized (mPackages) { 6587 mSettings.writeLPr(); 6588 } 6589 } 6590 6591 if (removedPackage != null) { 6592 Bundle extras = new Bundle(1); 6593 extras.putInt(Intent.EXTRA_UID, removedAppId); 6594 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 6595 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 6596 extras, null, null, removedUsers); 6597 } 6598 if (addedPackage != null) { 6599 Bundle extras = new Bundle(1); 6600 extras.putInt(Intent.EXTRA_UID, addedAppId); 6601 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 6602 extras, null, null, addedUsers); 6603 } 6604 } 6605 6606 private final String mRootDir; 6607 private final boolean mIsRom; 6608 private final boolean mIsPrivileged; 6609 } 6610 6611 /* Called when a downloaded package installation has been confirmed by the user */ 6612 public void installPackage( 6613 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 6614 installPackage(packageURI, observer, flags, null); 6615 } 6616 6617 /* Called when a downloaded package installation has been confirmed by the user */ 6618 public void installPackage( 6619 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 6620 final String installerPackageName) { 6621 installPackageWithVerification(packageURI, observer, flags, installerPackageName, null, 6622 null, null); 6623 } 6624 6625 @Override 6626 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 6627 int flags, String installerPackageName, Uri verificationURI, 6628 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 6629 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 6630 VerificationParams.NO_UID, manifestDigest); 6631 installPackageWithVerificationAndEncryption(packageURI, observer, flags, 6632 installerPackageName, verificationParams, encryptionParams); 6633 } 6634 6635 public void installPackageWithVerificationAndEncryption(Uri packageURI, 6636 IPackageInstallObserver observer, int flags, String installerPackageName, 6637 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 6638 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 6639 null); 6640 6641 final int uid = Binder.getCallingUid(); 6642 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 6643 try { 6644 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 6645 } catch (RemoteException re) { 6646 } 6647 return; 6648 } 6649 6650 UserHandle user; 6651 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 6652 user = UserHandle.ALL; 6653 } else { 6654 user = new UserHandle(UserHandle.getUserId(uid)); 6655 } 6656 6657 final int filteredFlags; 6658 6659 if (uid == Process.SHELL_UID || uid == 0) { 6660 if (DEBUG_INSTALL) { 6661 Slog.v(TAG, "Install from ADB"); 6662 } 6663 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 6664 } else { 6665 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 6666 } 6667 6668 verificationParams.setInstallerUid(uid); 6669 6670 final Message msg = mHandler.obtainMessage(INIT_COPY); 6671 msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName, 6672 verificationParams, encryptionParams, user); 6673 mHandler.sendMessage(msg); 6674 } 6675 6676 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 6677 Bundle extras = new Bundle(1); 6678 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 6679 6680 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 6681 packageName, extras, null, null, new int[] {userId}); 6682 try { 6683 IActivityManager am = ActivityManagerNative.getDefault(); 6684 final boolean isSystem = 6685 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 6686 if (isSystem && am.isUserRunning(userId, false)) { 6687 // The just-installed/enabled app is bundled on the system, so presumed 6688 // to be able to run automatically without needing an explicit launch. 6689 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 6690 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 6691 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 6692 .setPackage(packageName); 6693 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 6694 android.app.AppOpsManager.OP_NONE, false, false, userId); 6695 } 6696 } catch (RemoteException e) { 6697 // shouldn't happen 6698 Slog.w(TAG, "Unable to bootstrap installed package", e); 6699 } 6700 } 6701 6702 @Override 6703 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 6704 int userId) { 6705 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 6706 PackageSetting pkgSetting; 6707 final int uid = Binder.getCallingUid(); 6708 if (UserHandle.getUserId(uid) != userId) { 6709 mContext.enforceCallingOrSelfPermission( 6710 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 6711 "setApplicationBlockedSetting for user " + userId); 6712 } 6713 6714 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 6715 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 6716 return false; 6717 } 6718 6719 long callingId = Binder.clearCallingIdentity(); 6720 try { 6721 boolean sendAdded = false; 6722 boolean sendRemoved = false; 6723 // writer 6724 synchronized (mPackages) { 6725 pkgSetting = mSettings.mPackages.get(packageName); 6726 if (pkgSetting == null) { 6727 return false; 6728 } 6729 if (pkgSetting.getBlocked(userId) != blocked) { 6730 pkgSetting.setBlocked(blocked, userId); 6731 mSettings.writePackageRestrictionsLPr(userId); 6732 if (blocked) { 6733 sendRemoved = true; 6734 } else { 6735 sendAdded = true; 6736 } 6737 } 6738 } 6739 if (sendAdded) { 6740 sendPackageAddedForUser(packageName, pkgSetting, userId); 6741 return true; 6742 } 6743 if (sendRemoved) { 6744 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 6745 "blocking pkg"); 6746 sendPackageBlockedForUser(packageName, pkgSetting, userId); 6747 } 6748 } finally { 6749 Binder.restoreCallingIdentity(callingId); 6750 } 6751 return false; 6752 } 6753 6754 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 6755 int userId) { 6756 final PackageRemovedInfo info = new PackageRemovedInfo(); 6757 info.removedPackage = packageName; 6758 info.removedUsers = new int[] {userId}; 6759 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 6760 info.sendBroadcast(false, false, false); 6761 } 6762 6763 /** 6764 * Returns true if application is not found or there was an error. Otherwise it returns 6765 * the blocked state of the package for the given user. 6766 */ 6767 @Override 6768 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 6769 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 6770 PackageSetting pkgSetting; 6771 final int uid = Binder.getCallingUid(); 6772 if (UserHandle.getUserId(uid) != userId) { 6773 mContext.enforceCallingPermission( 6774 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 6775 "getApplicationBlocked for user " + userId); 6776 } 6777 long callingId = Binder.clearCallingIdentity(); 6778 try { 6779 // writer 6780 synchronized (mPackages) { 6781 pkgSetting = mSettings.mPackages.get(packageName); 6782 if (pkgSetting == null) { 6783 return true; 6784 } 6785 return pkgSetting.getBlocked(userId); 6786 } 6787 } finally { 6788 Binder.restoreCallingIdentity(callingId); 6789 } 6790 } 6791 6792 /** 6793 * @hide 6794 */ 6795 @Override 6796 public int installExistingPackageAsUser(String packageName, int userId) { 6797 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 6798 null); 6799 PackageSetting pkgSetting; 6800 final int uid = Binder.getCallingUid(); 6801 if (UserHandle.getUserId(uid) != userId) { 6802 mContext.enforceCallingPermission( 6803 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 6804 "installExistingPackage for user " + userId); 6805 } 6806 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 6807 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 6808 } 6809 6810 long callingId = Binder.clearCallingIdentity(); 6811 try { 6812 boolean sendAdded = false; 6813 Bundle extras = new Bundle(1); 6814 6815 // writer 6816 synchronized (mPackages) { 6817 pkgSetting = mSettings.mPackages.get(packageName); 6818 if (pkgSetting == null) { 6819 return PackageManager.INSTALL_FAILED_INVALID_URI; 6820 } 6821 if (!pkgSetting.getInstalled(userId)) { 6822 pkgSetting.setInstalled(true, userId); 6823 pkgSetting.setBlocked(false, userId); 6824 mSettings.writePackageRestrictionsLPr(userId); 6825 sendAdded = true; 6826 } 6827 } 6828 6829 if (sendAdded) { 6830 sendPackageAddedForUser(packageName, pkgSetting, userId); 6831 } 6832 } finally { 6833 Binder.restoreCallingIdentity(callingId); 6834 } 6835 6836 return PackageManager.INSTALL_SUCCEEDED; 6837 } 6838 6839 private boolean isUserRestricted(int userId, String restrictionKey) { 6840 Bundle restrictions = sUserManager.getUserRestrictions(userId); 6841 if (restrictions.getBoolean(restrictionKey, false)) { 6842 Log.w(TAG, "User is restricted: " + restrictionKey); 6843 return true; 6844 } 6845 return false; 6846 } 6847 6848 @Override 6849 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 6850 mContext.enforceCallingOrSelfPermission( 6851 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 6852 "Only package verification agents can verify applications"); 6853 6854 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 6855 final PackageVerificationResponse response = new PackageVerificationResponse( 6856 verificationCode, Binder.getCallingUid()); 6857 msg.arg1 = id; 6858 msg.obj = response; 6859 mHandler.sendMessage(msg); 6860 } 6861 6862 @Override 6863 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 6864 long millisecondsToDelay) { 6865 mContext.enforceCallingOrSelfPermission( 6866 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 6867 "Only package verification agents can extend verification timeouts"); 6868 6869 final PackageVerificationState state = mPendingVerification.get(id); 6870 final PackageVerificationResponse response = new PackageVerificationResponse( 6871 verificationCodeAtTimeout, Binder.getCallingUid()); 6872 6873 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 6874 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 6875 } 6876 if (millisecondsToDelay < 0) { 6877 millisecondsToDelay = 0; 6878 } 6879 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 6880 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 6881 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 6882 } 6883 6884 if ((state != null) && !state.timeoutExtended()) { 6885 state.extendTimeout(); 6886 6887 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 6888 msg.arg1 = id; 6889 msg.obj = response; 6890 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 6891 } 6892 } 6893 6894 private void broadcastPackageVerified(int verificationId, Uri packageUri, 6895 int verificationCode, UserHandle user) { 6896 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 6897 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 6898 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 6899 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 6900 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 6901 6902 mContext.sendBroadcastAsUser(intent, user, 6903 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 6904 } 6905 6906 private ComponentName matchComponentForVerifier(String packageName, 6907 List<ResolveInfo> receivers) { 6908 ActivityInfo targetReceiver = null; 6909 6910 final int NR = receivers.size(); 6911 for (int i = 0; i < NR; i++) { 6912 final ResolveInfo info = receivers.get(i); 6913 if (info.activityInfo == null) { 6914 continue; 6915 } 6916 6917 if (packageName.equals(info.activityInfo.packageName)) { 6918 targetReceiver = info.activityInfo; 6919 break; 6920 } 6921 } 6922 6923 if (targetReceiver == null) { 6924 return null; 6925 } 6926 6927 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 6928 } 6929 6930 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 6931 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 6932 if (pkgInfo.verifiers.length == 0) { 6933 return null; 6934 } 6935 6936 final int N = pkgInfo.verifiers.length; 6937 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 6938 for (int i = 0; i < N; i++) { 6939 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 6940 6941 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 6942 receivers); 6943 if (comp == null) { 6944 continue; 6945 } 6946 6947 final int verifierUid = getUidForVerifier(verifierInfo); 6948 if (verifierUid == -1) { 6949 continue; 6950 } 6951 6952 if (DEBUG_VERIFY) { 6953 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 6954 + " with the correct signature"); 6955 } 6956 sufficientVerifiers.add(comp); 6957 verificationState.addSufficientVerifier(verifierUid); 6958 } 6959 6960 return sufficientVerifiers; 6961 } 6962 6963 private int getUidForVerifier(VerifierInfo verifierInfo) { 6964 synchronized (mPackages) { 6965 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 6966 if (pkg == null) { 6967 return -1; 6968 } else if (pkg.mSignatures.length != 1) { 6969 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 6970 + " has more than one signature; ignoring"); 6971 return -1; 6972 } 6973 6974 /* 6975 * If the public key of the package's signature does not match 6976 * our expected public key, then this is a different package and 6977 * we should skip. 6978 */ 6979 6980 final byte[] expectedPublicKey; 6981 try { 6982 final Signature verifierSig = pkg.mSignatures[0]; 6983 final PublicKey publicKey = verifierSig.getPublicKey(); 6984 expectedPublicKey = publicKey.getEncoded(); 6985 } catch (CertificateException e) { 6986 return -1; 6987 } 6988 6989 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 6990 6991 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 6992 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 6993 + " does not have the expected public key; ignoring"); 6994 return -1; 6995 } 6996 6997 return pkg.applicationInfo.uid; 6998 } 6999 } 7000 7001 public void finishPackageInstall(int token) { 7002 enforceSystemOrRoot("Only the system is allowed to finish installs"); 7003 7004 if (DEBUG_INSTALL) { 7005 Slog.v(TAG, "BM finishing package install for " + token); 7006 } 7007 7008 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 7009 mHandler.sendMessage(msg); 7010 } 7011 7012 /** 7013 * Get the verification agent timeout. 7014 * 7015 * @return verification timeout in milliseconds 7016 */ 7017 private long getVerificationTimeout() { 7018 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 7019 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 7020 DEFAULT_VERIFICATION_TIMEOUT); 7021 } 7022 7023 /** 7024 * Get the default verification agent response code. 7025 * 7026 * @return default verification response code 7027 */ 7028 private int getDefaultVerificationResponse() { 7029 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7030 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 7031 DEFAULT_VERIFICATION_RESPONSE); 7032 } 7033 7034 /** 7035 * Check whether or not package verification has been enabled. 7036 * 7037 * @return true if verification should be performed 7038 */ 7039 private boolean isVerificationEnabled(int flags) { 7040 if (!DEFAULT_VERIFY_ENABLE) { 7041 return false; 7042 } 7043 7044 // Check if installing from ADB 7045 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 7046 // Do not run verification in a test harness environment 7047 if (ActivityManager.isRunningInTestHarness()) { 7048 return false; 7049 } 7050 // Check if the developer does not want package verification for ADB installs 7051 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7052 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 7053 return false; 7054 } 7055 } 7056 7057 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7058 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 7059 } 7060 7061 /** 7062 * Get the "allow unknown sources" setting. 7063 * 7064 * @return the current "allow unknown sources" setting 7065 */ 7066 private int getUnknownSourcesSettings() { 7067 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7068 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 7069 -1); 7070 } 7071 7072 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 7073 final int uid = Binder.getCallingUid(); 7074 // writer 7075 synchronized (mPackages) { 7076 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 7077 if (targetPackageSetting == null) { 7078 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 7079 } 7080 7081 PackageSetting installerPackageSetting; 7082 if (installerPackageName != null) { 7083 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 7084 if (installerPackageSetting == null) { 7085 throw new IllegalArgumentException("Unknown installer package: " 7086 + installerPackageName); 7087 } 7088 } else { 7089 installerPackageSetting = null; 7090 } 7091 7092 Signature[] callerSignature; 7093 Object obj = mSettings.getUserIdLPr(uid); 7094 if (obj != null) { 7095 if (obj instanceof SharedUserSetting) { 7096 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 7097 } else if (obj instanceof PackageSetting) { 7098 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 7099 } else { 7100 throw new SecurityException("Bad object " + obj + " for uid " + uid); 7101 } 7102 } else { 7103 throw new SecurityException("Unknown calling uid " + uid); 7104 } 7105 7106 // Verify: can't set installerPackageName to a package that is 7107 // not signed with the same cert as the caller. 7108 if (installerPackageSetting != null) { 7109 if (compareSignatures(callerSignature, 7110 installerPackageSetting.signatures.mSignatures) 7111 != PackageManager.SIGNATURE_MATCH) { 7112 throw new SecurityException( 7113 "Caller does not have same cert as new installer package " 7114 + installerPackageName); 7115 } 7116 } 7117 7118 // Verify: if target already has an installer package, it must 7119 // be signed with the same cert as the caller. 7120 if (targetPackageSetting.installerPackageName != null) { 7121 PackageSetting setting = mSettings.mPackages.get( 7122 targetPackageSetting.installerPackageName); 7123 // If the currently set package isn't valid, then it's always 7124 // okay to change it. 7125 if (setting != null) { 7126 if (compareSignatures(callerSignature, 7127 setting.signatures.mSignatures) 7128 != PackageManager.SIGNATURE_MATCH) { 7129 throw new SecurityException( 7130 "Caller does not have same cert as old installer package " 7131 + targetPackageSetting.installerPackageName); 7132 } 7133 } 7134 } 7135 7136 // Okay! 7137 targetPackageSetting.installerPackageName = installerPackageName; 7138 scheduleWriteSettingsLocked(); 7139 } 7140 } 7141 7142 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 7143 // Queue up an async operation since the package installation may take a little while. 7144 mHandler.post(new Runnable() { 7145 public void run() { 7146 mHandler.removeCallbacks(this); 7147 // Result object to be returned 7148 PackageInstalledInfo res = new PackageInstalledInfo(); 7149 res.returnCode = currentStatus; 7150 res.uid = -1; 7151 res.pkg = null; 7152 res.removedInfo = new PackageRemovedInfo(); 7153 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 7154 args.doPreInstall(res.returnCode); 7155 synchronized (mInstallLock) { 7156 installPackageLI(args, true, res); 7157 } 7158 args.doPostInstall(res.returnCode, res.uid); 7159 } 7160 7161 // A restore should be performed at this point if (a) the install 7162 // succeeded, (b) the operation is not an update, and (c) the new 7163 // package has a backupAgent defined. 7164 final boolean update = res.removedInfo.removedPackage != null; 7165 boolean doRestore = (!update 7166 && res.pkg != null 7167 && res.pkg.applicationInfo.backupAgentName != null); 7168 7169 // Set up the post-install work request bookkeeping. This will be used 7170 // and cleaned up by the post-install event handling regardless of whether 7171 // there's a restore pass performed. Token values are >= 1. 7172 int token; 7173 if (mNextInstallToken < 0) mNextInstallToken = 1; 7174 token = mNextInstallToken++; 7175 7176 PostInstallData data = new PostInstallData(args, res); 7177 mRunningInstalls.put(token, data); 7178 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 7179 7180 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 7181 // Pass responsibility to the Backup Manager. It will perform a 7182 // restore if appropriate, then pass responsibility back to the 7183 // Package Manager to run the post-install observer callbacks 7184 // and broadcasts. 7185 IBackupManager bm = IBackupManager.Stub.asInterface( 7186 ServiceManager.getService(Context.BACKUP_SERVICE)); 7187 if (bm != null) { 7188 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 7189 + " to BM for possible restore"); 7190 try { 7191 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 7192 } catch (RemoteException e) { 7193 // can't happen; the backup manager is local 7194 } catch (Exception e) { 7195 Slog.e(TAG, "Exception trying to enqueue restore", e); 7196 doRestore = false; 7197 } 7198 } else { 7199 Slog.e(TAG, "Backup Manager not found!"); 7200 doRestore = false; 7201 } 7202 } 7203 7204 if (!doRestore) { 7205 // No restore possible, or the Backup Manager was mysteriously not 7206 // available -- just fire the post-install work request directly. 7207 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 7208 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 7209 mHandler.sendMessage(msg); 7210 } 7211 } 7212 }); 7213 } 7214 7215 private abstract class HandlerParams { 7216 private static final int MAX_RETRIES = 4; 7217 7218 /** 7219 * Number of times startCopy() has been attempted and had a non-fatal 7220 * error. 7221 */ 7222 private int mRetries = 0; 7223 7224 /** User handle for the user requesting the information or installation. */ 7225 private final UserHandle mUser; 7226 7227 HandlerParams(UserHandle user) { 7228 mUser = user; 7229 } 7230 7231 UserHandle getUser() { 7232 return mUser; 7233 } 7234 7235 final boolean startCopy() { 7236 boolean res; 7237 try { 7238 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 7239 7240 if (++mRetries > MAX_RETRIES) { 7241 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 7242 mHandler.sendEmptyMessage(MCS_GIVE_UP); 7243 handleServiceError(); 7244 return false; 7245 } else { 7246 handleStartCopy(); 7247 res = true; 7248 } 7249 } catch (RemoteException e) { 7250 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 7251 mHandler.sendEmptyMessage(MCS_RECONNECT); 7252 res = false; 7253 } 7254 handleReturnCode(); 7255 return res; 7256 } 7257 7258 final void serviceError() { 7259 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 7260 handleServiceError(); 7261 handleReturnCode(); 7262 } 7263 7264 abstract void handleStartCopy() throws RemoteException; 7265 abstract void handleServiceError(); 7266 abstract void handleReturnCode(); 7267 } 7268 7269 class MeasureParams extends HandlerParams { 7270 private final PackageStats mStats; 7271 private boolean mSuccess; 7272 7273 private final IPackageStatsObserver mObserver; 7274 7275 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 7276 super(new UserHandle(stats.userHandle)); 7277 mObserver = observer; 7278 mStats = stats; 7279 } 7280 7281 @Override 7282 public String toString() { 7283 return "MeasureParams{" 7284 + Integer.toHexString(System.identityHashCode(this)) 7285 + " " + mStats.packageName + "}"; 7286 } 7287 7288 @Override 7289 void handleStartCopy() throws RemoteException { 7290 synchronized (mInstallLock) { 7291 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 7292 } 7293 7294 final boolean mounted; 7295 if (Environment.isExternalStorageEmulated()) { 7296 mounted = true; 7297 } else { 7298 final String status = Environment.getExternalStorageState(); 7299 mounted = (Environment.MEDIA_MOUNTED.equals(status) 7300 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 7301 } 7302 7303 if (mounted) { 7304 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 7305 7306 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 7307 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 7308 7309 mStats.externalDataSize = calculateDirectorySize(mContainerService, 7310 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 7311 7312 // Always subtract cache size, since it's a subdirectory 7313 mStats.externalDataSize -= mStats.externalCacheSize; 7314 7315 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 7316 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 7317 7318 mStats.externalObbSize = calculateDirectorySize(mContainerService, 7319 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 7320 } 7321 } 7322 7323 @Override 7324 void handleReturnCode() { 7325 if (mObserver != null) { 7326 try { 7327 mObserver.onGetStatsCompleted(mStats, mSuccess); 7328 } catch (RemoteException e) { 7329 Slog.i(TAG, "Observer no longer exists."); 7330 } 7331 } 7332 } 7333 7334 @Override 7335 void handleServiceError() { 7336 Slog.e(TAG, "Could not measure application " + mStats.packageName 7337 + " external storage"); 7338 } 7339 } 7340 7341 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 7342 throws RemoteException { 7343 long result = 0; 7344 for (File path : paths) { 7345 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 7346 } 7347 return result; 7348 } 7349 7350 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 7351 for (File path : paths) { 7352 try { 7353 mcs.clearDirectory(path.getAbsolutePath()); 7354 } catch (RemoteException e) { 7355 } 7356 } 7357 } 7358 7359 class InstallParams extends HandlerParams { 7360 final IPackageInstallObserver observer; 7361 int flags; 7362 7363 private final Uri mPackageURI; 7364 final String installerPackageName; 7365 final VerificationParams verificationParams; 7366 private InstallArgs mArgs; 7367 private int mRet; 7368 private File mTempPackage; 7369 final ContainerEncryptionParams encryptionParams; 7370 7371 InstallParams(Uri packageURI, 7372 IPackageInstallObserver observer, int flags, 7373 String installerPackageName, VerificationParams verificationParams, 7374 ContainerEncryptionParams encryptionParams, UserHandle user) { 7375 super(user); 7376 this.mPackageURI = packageURI; 7377 this.flags = flags; 7378 this.observer = observer; 7379 this.installerPackageName = installerPackageName; 7380 this.verificationParams = verificationParams; 7381 this.encryptionParams = encryptionParams; 7382 } 7383 7384 @Override 7385 public String toString() { 7386 return "InstallParams{" 7387 + Integer.toHexString(System.identityHashCode(this)) 7388 + " " + mPackageURI + "}"; 7389 } 7390 7391 public ManifestDigest getManifestDigest() { 7392 if (verificationParams == null) { 7393 return null; 7394 } 7395 return verificationParams.getManifestDigest(); 7396 } 7397 7398 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 7399 String packageName = pkgLite.packageName; 7400 int installLocation = pkgLite.installLocation; 7401 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 7402 // reader 7403 synchronized (mPackages) { 7404 PackageParser.Package pkg = mPackages.get(packageName); 7405 if (pkg != null) { 7406 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 7407 // Check for downgrading. 7408 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 7409 if (pkgLite.versionCode < pkg.mVersionCode) { 7410 Slog.w(TAG, "Can't install update of " + packageName 7411 + " update version " + pkgLite.versionCode 7412 + " is older than installed version " 7413 + pkg.mVersionCode); 7414 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 7415 } 7416 } 7417 // Check for updated system application. 7418 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 7419 if (onSd) { 7420 Slog.w(TAG, "Cannot install update to system app on sdcard"); 7421 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 7422 } 7423 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 7424 } else { 7425 if (onSd) { 7426 // Install flag overrides everything. 7427 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 7428 } 7429 // If current upgrade specifies particular preference 7430 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 7431 // Application explicitly specified internal. 7432 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 7433 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 7434 // App explictly prefers external. Let policy decide 7435 } else { 7436 // Prefer previous location 7437 if (isExternal(pkg)) { 7438 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 7439 } 7440 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 7441 } 7442 } 7443 } else { 7444 // Invalid install. Return error code 7445 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 7446 } 7447 } 7448 } 7449 // All the special cases have been taken care of. 7450 // Return result based on recommended install location. 7451 if (onSd) { 7452 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 7453 } 7454 return pkgLite.recommendedInstallLocation; 7455 } 7456 7457 private long getMemoryLowThreshold() { 7458 final DeviceStorageMonitorInternal 7459 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 7460 if (dsm == null) { 7461 return 0L; 7462 } 7463 return dsm.getMemoryLowThreshold(); 7464 } 7465 7466 /* 7467 * Invoke remote method to get package information and install 7468 * location values. Override install location based on default 7469 * policy if needed and then create install arguments based 7470 * on the install location. 7471 */ 7472 public void handleStartCopy() throws RemoteException { 7473 int ret = PackageManager.INSTALL_SUCCEEDED; 7474 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 7475 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 7476 PackageInfoLite pkgLite = null; 7477 7478 if (onInt && onSd) { 7479 // Check if both bits are set. 7480 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 7481 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 7482 } else { 7483 final long lowThreshold = getMemoryLowThreshold(); 7484 if (lowThreshold == 0L) { 7485 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 7486 } 7487 7488 try { 7489 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI, 7490 Intent.FLAG_GRANT_READ_URI_PERMISSION); 7491 7492 final File packageFile; 7493 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) { 7494 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir); 7495 if (mTempPackage != null) { 7496 ParcelFileDescriptor out; 7497 try { 7498 out = ParcelFileDescriptor.open(mTempPackage, 7499 ParcelFileDescriptor.MODE_READ_WRITE); 7500 } catch (FileNotFoundException e) { 7501 out = null; 7502 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI); 7503 } 7504 7505 // Make a temporary file for decryption. 7506 ret = mContainerService 7507 .copyResource(mPackageURI, encryptionParams, out); 7508 IoUtils.closeQuietly(out); 7509 7510 packageFile = mTempPackage; 7511 7512 FileUtils.setPermissions(packageFile.getAbsolutePath(), 7513 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP 7514 | FileUtils.S_IROTH, 7515 -1, -1); 7516 } else { 7517 packageFile = null; 7518 } 7519 } else { 7520 packageFile = new File(mPackageURI.getPath()); 7521 } 7522 7523 if (packageFile != null) { 7524 // Remote call to find out default install location 7525 final String packageFilePath = packageFile.getAbsolutePath(); 7526 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags, 7527 lowThreshold); 7528 7529 /* 7530 * If we have too little free space, try to free cache 7531 * before giving up. 7532 */ 7533 if (pkgLite.recommendedInstallLocation 7534 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 7535 final long size = mContainerService.calculateInstalledSize( 7536 packageFilePath, isForwardLocked()); 7537 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 7538 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, 7539 flags, lowThreshold); 7540 } 7541 /* 7542 * The cache free must have deleted the file we 7543 * downloaded to install. 7544 * 7545 * TODO: fix the "freeCache" call to not delete 7546 * the file we care about. 7547 */ 7548 if (pkgLite.recommendedInstallLocation 7549 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 7550 pkgLite.recommendedInstallLocation 7551 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 7552 } 7553 } 7554 } 7555 } finally { 7556 mContext.revokeUriPermission(mPackageURI, 7557 Intent.FLAG_GRANT_READ_URI_PERMISSION); 7558 } 7559 } 7560 7561 if (ret == PackageManager.INSTALL_SUCCEEDED) { 7562 int loc = pkgLite.recommendedInstallLocation; 7563 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 7564 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 7565 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 7566 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 7567 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 7568 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 7569 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 7570 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 7571 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 7572 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 7573 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 7574 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 7575 } else { 7576 // Override with defaults if needed. 7577 loc = installLocationPolicy(pkgLite, flags); 7578 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 7579 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 7580 } else if (!onSd && !onInt) { 7581 // Override install location with flags 7582 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 7583 // Set the flag to install on external media. 7584 flags |= PackageManager.INSTALL_EXTERNAL; 7585 flags &= ~PackageManager.INSTALL_INTERNAL; 7586 } else { 7587 // Make sure the flag for installing on external 7588 // media is unset 7589 flags |= PackageManager.INSTALL_INTERNAL; 7590 flags &= ~PackageManager.INSTALL_EXTERNAL; 7591 } 7592 } 7593 } 7594 } 7595 7596 final InstallArgs args = createInstallArgs(this); 7597 mArgs = args; 7598 7599 if (ret == PackageManager.INSTALL_SUCCEEDED) { 7600 /* 7601 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 7602 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 7603 */ 7604 int userIdentifier = getUser().getIdentifier(); 7605 if (userIdentifier == UserHandle.USER_ALL 7606 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 7607 userIdentifier = UserHandle.USER_OWNER; 7608 } 7609 7610 /* 7611 * Determine if we have any installed package verifiers. If we 7612 * do, then we'll defer to them to verify the packages. 7613 */ 7614 final int requiredUid = mRequiredVerifierPackage == null ? -1 7615 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 7616 if (requiredUid != -1 && isVerificationEnabled(flags)) { 7617 final Intent verification = new Intent( 7618 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 7619 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE); 7620 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7621 7622 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 7623 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 7624 0 /* TODO: Which userId? */); 7625 7626 if (DEBUG_VERIFY) { 7627 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 7628 + verification.toString() + " with " + pkgLite.verifiers.length 7629 + " optional verifiers"); 7630 } 7631 7632 final int verificationId = mPendingVerificationToken++; 7633 7634 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7635 7636 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 7637 installerPackageName); 7638 7639 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 7640 7641 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 7642 pkgLite.packageName); 7643 7644 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 7645 pkgLite.versionCode); 7646 7647 if (verificationParams != null) { 7648 if (verificationParams.getVerificationURI() != null) { 7649 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 7650 verificationParams.getVerificationURI()); 7651 } 7652 if (verificationParams.getOriginatingURI() != null) { 7653 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 7654 verificationParams.getOriginatingURI()); 7655 } 7656 if (verificationParams.getReferrer() != null) { 7657 verification.putExtra(Intent.EXTRA_REFERRER, 7658 verificationParams.getReferrer()); 7659 } 7660 if (verificationParams.getOriginatingUid() >= 0) { 7661 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 7662 verificationParams.getOriginatingUid()); 7663 } 7664 if (verificationParams.getInstallerUid() >= 0) { 7665 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 7666 verificationParams.getInstallerUid()); 7667 } 7668 } 7669 7670 final PackageVerificationState verificationState = new PackageVerificationState( 7671 requiredUid, args); 7672 7673 mPendingVerification.append(verificationId, verificationState); 7674 7675 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 7676 receivers, verificationState); 7677 7678 /* 7679 * If any sufficient verifiers were listed in the package 7680 * manifest, attempt to ask them. 7681 */ 7682 if (sufficientVerifiers != null) { 7683 final int N = sufficientVerifiers.size(); 7684 if (N == 0) { 7685 Slog.i(TAG, "Additional verifiers required, but none installed."); 7686 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 7687 } else { 7688 for (int i = 0; i < N; i++) { 7689 final ComponentName verifierComponent = sufficientVerifiers.get(i); 7690 7691 final Intent sufficientIntent = new Intent(verification); 7692 sufficientIntent.setComponent(verifierComponent); 7693 7694 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 7695 } 7696 } 7697 } 7698 7699 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 7700 mRequiredVerifierPackage, receivers); 7701 if (ret == PackageManager.INSTALL_SUCCEEDED 7702 && mRequiredVerifierPackage != null) { 7703 /* 7704 * Send the intent to the required verification agent, 7705 * but only start the verification timeout after the 7706 * target BroadcastReceivers have run. 7707 */ 7708 verification.setComponent(requiredVerifierComponent); 7709 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 7710 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7711 new BroadcastReceiver() { 7712 @Override 7713 public void onReceive(Context context, Intent intent) { 7714 final Message msg = mHandler 7715 .obtainMessage(CHECK_PENDING_VERIFICATION); 7716 msg.arg1 = verificationId; 7717 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 7718 } 7719 }, null, 0, null, null); 7720 7721 /* 7722 * We don't want the copy to proceed until verification 7723 * succeeds, so null out this field. 7724 */ 7725 mArgs = null; 7726 } 7727 } else { 7728 /* 7729 * No package verification is enabled, so immediately start 7730 * the remote call to initiate copy using temporary file. 7731 */ 7732 ret = args.copyApk(mContainerService, true); 7733 } 7734 } 7735 7736 mRet = ret; 7737 } 7738 7739 @Override 7740 void handleReturnCode() { 7741 // If mArgs is null, then MCS couldn't be reached. When it 7742 // reconnects, it will try again to install. At that point, this 7743 // will succeed. 7744 if (mArgs != null) { 7745 processPendingInstall(mArgs, mRet); 7746 7747 if (mTempPackage != null) { 7748 if (!mTempPackage.delete()) { 7749 Slog.w(TAG, "Couldn't delete temporary file: " + 7750 mTempPackage.getAbsolutePath()); 7751 } 7752 } 7753 } 7754 } 7755 7756 @Override 7757 void handleServiceError() { 7758 mArgs = createInstallArgs(this); 7759 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 7760 } 7761 7762 public boolean isForwardLocked() { 7763 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 7764 } 7765 7766 public Uri getPackageUri() { 7767 if (mTempPackage != null) { 7768 return Uri.fromFile(mTempPackage); 7769 } else { 7770 return mPackageURI; 7771 } 7772 } 7773 } 7774 7775 /* 7776 * Utility class used in movePackage api. 7777 * srcArgs and targetArgs are not set for invalid flags and make 7778 * sure to do null checks when invoking methods on them. 7779 * We probably want to return ErrorPrams for both failed installs 7780 * and moves. 7781 */ 7782 class MoveParams extends HandlerParams { 7783 final IPackageMoveObserver observer; 7784 final int flags; 7785 final String packageName; 7786 final InstallArgs srcArgs; 7787 final InstallArgs targetArgs; 7788 int uid; 7789 int mRet; 7790 7791 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 7792 String packageName, String dataDir, int uid, UserHandle user) { 7793 super(user); 7794 this.srcArgs = srcArgs; 7795 this.observer = observer; 7796 this.flags = flags; 7797 this.packageName = packageName; 7798 this.uid = uid; 7799 if (srcArgs != null) { 7800 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath())); 7801 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir); 7802 } else { 7803 targetArgs = null; 7804 } 7805 } 7806 7807 @Override 7808 public String toString() { 7809 return "MoveParams{" 7810 + Integer.toHexString(System.identityHashCode(this)) 7811 + " " + packageName + "}"; 7812 } 7813 7814 public void handleStartCopy() throws RemoteException { 7815 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 7816 // Check for storage space on target medium 7817 if (!targetArgs.checkFreeStorage(mContainerService)) { 7818 Log.w(TAG, "Insufficient storage to install"); 7819 return; 7820 } 7821 7822 mRet = srcArgs.doPreCopy(); 7823 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 7824 return; 7825 } 7826 7827 mRet = targetArgs.copyApk(mContainerService, false); 7828 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 7829 srcArgs.doPostCopy(uid); 7830 return; 7831 } 7832 7833 mRet = srcArgs.doPostCopy(uid); 7834 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 7835 return; 7836 } 7837 7838 mRet = targetArgs.doPreInstall(mRet); 7839 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 7840 return; 7841 } 7842 7843 if (DEBUG_SD_INSTALL) { 7844 StringBuilder builder = new StringBuilder(); 7845 if (srcArgs != null) { 7846 builder.append("src: "); 7847 builder.append(srcArgs.getCodePath()); 7848 } 7849 if (targetArgs != null) { 7850 builder.append(" target : "); 7851 builder.append(targetArgs.getCodePath()); 7852 } 7853 Log.i(TAG, builder.toString()); 7854 } 7855 } 7856 7857 @Override 7858 void handleReturnCode() { 7859 targetArgs.doPostInstall(mRet, uid); 7860 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 7861 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 7862 currentStatus = PackageManager.MOVE_SUCCEEDED; 7863 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 7864 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 7865 } 7866 processPendingMove(this, currentStatus); 7867 } 7868 7869 @Override 7870 void handleServiceError() { 7871 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 7872 } 7873 } 7874 7875 /** 7876 * Used during creation of InstallArgs 7877 * 7878 * @param flags package installation flags 7879 * @return true if should be installed on external storage 7880 */ 7881 private static boolean installOnSd(int flags) { 7882 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 7883 return false; 7884 } 7885 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 7886 return true; 7887 } 7888 return false; 7889 } 7890 7891 /** 7892 * Used during creation of InstallArgs 7893 * 7894 * @param flags package installation flags 7895 * @return true if should be installed as forward locked 7896 */ 7897 private static boolean installForwardLocked(int flags) { 7898 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 7899 } 7900 7901 private InstallArgs createInstallArgs(InstallParams params) { 7902 if (installOnSd(params.flags) || params.isForwardLocked()) { 7903 return new AsecInstallArgs(params); 7904 } else { 7905 return new FileInstallArgs(params); 7906 } 7907 } 7908 7909 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath, 7910 String nativeLibraryPath) { 7911 final boolean isInAsec; 7912 if (installOnSd(flags)) { 7913 /* Apps on SD card are always in ASEC containers. */ 7914 isInAsec = true; 7915 } else if (installForwardLocked(flags) 7916 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 7917 /* 7918 * Forward-locked apps are only in ASEC containers if they're the 7919 * new style 7920 */ 7921 isInAsec = true; 7922 } else { 7923 isInAsec = false; 7924 } 7925 7926 if (isInAsec) { 7927 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 7928 installOnSd(flags), installForwardLocked(flags)); 7929 } else { 7930 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath); 7931 } 7932 } 7933 7934 // Used by package mover 7935 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) { 7936 if (installOnSd(flags) || installForwardLocked(flags)) { 7937 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/" 7938 + AsecInstallArgs.RES_FILE_NAME); 7939 return new AsecInstallArgs(packageURI, cid, installOnSd(flags), 7940 installForwardLocked(flags)); 7941 } else { 7942 return new FileInstallArgs(packageURI, pkgName, dataDir); 7943 } 7944 } 7945 7946 static abstract class InstallArgs { 7947 final IPackageInstallObserver observer; 7948 // Always refers to PackageManager flags only 7949 final int flags; 7950 final Uri packageURI; 7951 final String installerPackageName; 7952 final ManifestDigest manifestDigest; 7953 final UserHandle user; 7954 7955 InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags, 7956 String installerPackageName, ManifestDigest manifestDigest, 7957 UserHandle user) { 7958 this.packageURI = packageURI; 7959 this.flags = flags; 7960 this.observer = observer; 7961 this.installerPackageName = installerPackageName; 7962 this.manifestDigest = manifestDigest; 7963 this.user = user; 7964 } 7965 7966 abstract void createCopyFile(); 7967 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 7968 abstract int doPreInstall(int status); 7969 abstract boolean doRename(int status, String pkgName, String oldCodePath); 7970 7971 abstract int doPostInstall(int status, int uid); 7972 abstract String getCodePath(); 7973 abstract String getResourcePath(); 7974 abstract String getNativeLibraryPath(); 7975 // Need installer lock especially for dex file removal. 7976 abstract void cleanUpResourcesLI(); 7977 abstract boolean doPostDeleteLI(boolean delete); 7978 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 7979 7980 /** 7981 * Called before the source arguments are copied. This is used mostly 7982 * for MoveParams when it needs to read the source file to put it in the 7983 * destination. 7984 */ 7985 int doPreCopy() { 7986 return PackageManager.INSTALL_SUCCEEDED; 7987 } 7988 7989 /** 7990 * Called after the source arguments are copied. This is used mostly for 7991 * MoveParams when it needs to read the source file to put it in the 7992 * destination. 7993 * 7994 * @return 7995 */ 7996 int doPostCopy(int uid) { 7997 return PackageManager.INSTALL_SUCCEEDED; 7998 } 7999 8000 protected boolean isFwdLocked() { 8001 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8002 } 8003 8004 UserHandle getUser() { 8005 return user; 8006 } 8007 } 8008 8009 class FileInstallArgs extends InstallArgs { 8010 File installDir; 8011 String codeFileName; 8012 String resourceFileName; 8013 String libraryPath; 8014 boolean created = false; 8015 8016 FileInstallArgs(InstallParams params) { 8017 super(params.getPackageUri(), params.observer, params.flags, 8018 params.installerPackageName, params.getManifestDigest(), 8019 params.getUser()); 8020 } 8021 8022 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) { 8023 super(null, null, 0, null, null, null); 8024 File codeFile = new File(fullCodePath); 8025 installDir = codeFile.getParentFile(); 8026 codeFileName = fullCodePath; 8027 resourceFileName = fullResourcePath; 8028 libraryPath = nativeLibraryPath; 8029 } 8030 8031 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) { 8032 super(packageURI, null, 0, null, null, null); 8033 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 8034 String apkName = getNextCodePath(null, pkgName, ".apk"); 8035 codeFileName = new File(installDir, apkName + ".apk").getPath(); 8036 resourceFileName = getResourcePathFromCodePath(); 8037 libraryPath = new File(mAppLibInstallDir, pkgName).getPath(); 8038 } 8039 8040 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 8041 final long lowThreshold; 8042 8043 final DeviceStorageMonitorInternal 8044 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8045 if (dsm == null) { 8046 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8047 lowThreshold = 0L; 8048 } else { 8049 if (dsm.isMemoryLow()) { 8050 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 8051 return false; 8052 } 8053 8054 lowThreshold = dsm.getMemoryLowThreshold(); 8055 } 8056 8057 try { 8058 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8059 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8060 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold); 8061 } finally { 8062 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8063 } 8064 } 8065 8066 String getCodePath() { 8067 return codeFileName; 8068 } 8069 8070 void createCopyFile() { 8071 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 8072 codeFileName = createTempPackageFile(installDir).getPath(); 8073 resourceFileName = getResourcePathFromCodePath(); 8074 libraryPath = getLibraryPathFromCodePath(); 8075 created = true; 8076 } 8077 8078 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 8079 if (temp) { 8080 // Generate temp file name 8081 createCopyFile(); 8082 } 8083 // Get a ParcelFileDescriptor to write to the output file 8084 File codeFile = new File(codeFileName); 8085 if (!created) { 8086 try { 8087 codeFile.createNewFile(); 8088 // Set permissions 8089 if (!setPermissions()) { 8090 // Failed setting permissions. 8091 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8092 } 8093 } catch (IOException e) { 8094 Slog.w(TAG, "Failed to create file " + codeFile); 8095 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8096 } 8097 } 8098 ParcelFileDescriptor out = null; 8099 try { 8100 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 8101 } catch (FileNotFoundException e) { 8102 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 8103 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8104 } 8105 // Copy the resource now 8106 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8107 try { 8108 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8109 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8110 ret = imcs.copyResource(packageURI, null, out); 8111 } finally { 8112 IoUtils.closeQuietly(out); 8113 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8114 } 8115 8116 if (isFwdLocked()) { 8117 final File destResourceFile = new File(getResourcePath()); 8118 8119 // Copy the public files 8120 try { 8121 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 8122 } catch (IOException e) { 8123 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 8124 + " forward-locked app."); 8125 destResourceFile.delete(); 8126 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8127 } 8128 } 8129 8130 final File nativeLibraryFile = new File(getNativeLibraryPath()); 8131 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath()); 8132 if (nativeLibraryFile.exists()) { 8133 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 8134 nativeLibraryFile.delete(); 8135 } 8136 try { 8137 int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile); 8138 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 8139 return copyRet; 8140 } 8141 } catch (IOException e) { 8142 Slog.e(TAG, "Copying native libraries failed", e); 8143 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8144 } 8145 8146 return ret; 8147 } 8148 8149 int doPreInstall(int status) { 8150 if (status != PackageManager.INSTALL_SUCCEEDED) { 8151 cleanUp(); 8152 } 8153 return status; 8154 } 8155 8156 boolean doRename(int status, final String pkgName, String oldCodePath) { 8157 if (status != PackageManager.INSTALL_SUCCEEDED) { 8158 cleanUp(); 8159 return false; 8160 } else { 8161 final File oldCodeFile = new File(getCodePath()); 8162 final File oldResourceFile = new File(getResourcePath()); 8163 final File oldLibraryFile = new File(getNativeLibraryPath()); 8164 8165 // Rename APK file based on packageName 8166 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 8167 final File newCodeFile = new File(installDir, apkName + ".apk"); 8168 if (!oldCodeFile.renameTo(newCodeFile)) { 8169 return false; 8170 } 8171 codeFileName = newCodeFile.getPath(); 8172 8173 // Rename public resource file if it's forward-locked. 8174 final File newResFile = new File(getResourcePathFromCodePath()); 8175 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 8176 return false; 8177 } 8178 resourceFileName = newResFile.getPath(); 8179 8180 // Rename library path 8181 final File newLibraryFile = new File(getLibraryPathFromCodePath()); 8182 if (newLibraryFile.exists()) { 8183 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile); 8184 newLibraryFile.delete(); 8185 } 8186 if (!oldLibraryFile.renameTo(newLibraryFile)) { 8187 Slog.e(TAG, "Cannot rename native library directory " 8188 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath()); 8189 return false; 8190 } 8191 libraryPath = newLibraryFile.getPath(); 8192 8193 // Attempt to set permissions 8194 if (!setPermissions()) { 8195 return false; 8196 } 8197 8198 if (!SELinux.restorecon(newCodeFile)) { 8199 return false; 8200 } 8201 8202 return true; 8203 } 8204 } 8205 8206 int doPostInstall(int status, int uid) { 8207 if (status != PackageManager.INSTALL_SUCCEEDED) { 8208 cleanUp(); 8209 } 8210 return status; 8211 } 8212 8213 String getResourcePath() { 8214 return resourceFileName; 8215 } 8216 8217 private String getResourcePathFromCodePath() { 8218 final String codePath = getCodePath(); 8219 if (isFwdLocked()) { 8220 final StringBuilder sb = new StringBuilder(); 8221 8222 sb.append(mAppInstallDir.getPath()); 8223 sb.append('/'); 8224 sb.append(getApkName(codePath)); 8225 sb.append(".zip"); 8226 8227 /* 8228 * If our APK is a temporary file, mark the resource as a 8229 * temporary file as well so it can be cleaned up after 8230 * catastrophic failure. 8231 */ 8232 if (codePath.endsWith(".tmp")) { 8233 sb.append(".tmp"); 8234 } 8235 8236 return sb.toString(); 8237 } else { 8238 return codePath; 8239 } 8240 } 8241 8242 private String getLibraryPathFromCodePath() { 8243 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath(); 8244 } 8245 8246 @Override 8247 String getNativeLibraryPath() { 8248 if (libraryPath == null) { 8249 libraryPath = getLibraryPathFromCodePath(); 8250 } 8251 return libraryPath; 8252 } 8253 8254 private boolean cleanUp() { 8255 boolean ret = true; 8256 String sourceDir = getCodePath(); 8257 String publicSourceDir = getResourcePath(); 8258 if (sourceDir != null) { 8259 File sourceFile = new File(sourceDir); 8260 if (!sourceFile.exists()) { 8261 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 8262 ret = false; 8263 } 8264 // Delete application's code and resources 8265 sourceFile.delete(); 8266 } 8267 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 8268 final File publicSourceFile = new File(publicSourceDir); 8269 if (!publicSourceFile.exists()) { 8270 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 8271 } 8272 if (publicSourceFile.exists()) { 8273 publicSourceFile.delete(); 8274 } 8275 } 8276 8277 if (libraryPath != null) { 8278 File nativeLibraryFile = new File(libraryPath); 8279 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 8280 if (!nativeLibraryFile.delete()) { 8281 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath); 8282 } 8283 } 8284 8285 return ret; 8286 } 8287 8288 void cleanUpResourcesLI() { 8289 String sourceDir = getCodePath(); 8290 if (cleanUp()) { 8291 int retCode = mInstaller.rmdex(sourceDir); 8292 if (retCode < 0) { 8293 Slog.w(TAG, "Couldn't remove dex file for package: " 8294 + " at location " 8295 + sourceDir + ", retcode=" + retCode); 8296 // we don't consider this to be a failure of the core package deletion 8297 } 8298 } 8299 } 8300 8301 private boolean setPermissions() { 8302 // TODO Do this in a more elegant way later on. for now just a hack 8303 if (!isFwdLocked()) { 8304 final int filePermissions = 8305 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 8306 |FileUtils.S_IROTH; 8307 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 8308 if (retCode != 0) { 8309 Slog.e(TAG, "Couldn't set new package file permissions for " + 8310 getCodePath() 8311 + ". The return code was: " + retCode); 8312 // TODO Define new internal error 8313 return false; 8314 } 8315 return true; 8316 } 8317 return true; 8318 } 8319 8320 boolean doPostDeleteLI(boolean delete) { 8321 // XXX err, shouldn't we respect the delete flag? 8322 cleanUpResourcesLI(); 8323 return true; 8324 } 8325 } 8326 8327 private boolean isAsecExternal(String cid) { 8328 final String asecPath = PackageHelper.getSdFilesystem(cid); 8329 return !asecPath.startsWith(mAsecInternalPath); 8330 } 8331 8332 /** 8333 * Extract the MountService "container ID" from the full code path of an 8334 * .apk. 8335 */ 8336 static String cidFromCodePath(String fullCodePath) { 8337 int eidx = fullCodePath.lastIndexOf("/"); 8338 String subStr1 = fullCodePath.substring(0, eidx); 8339 int sidx = subStr1.lastIndexOf("/"); 8340 return subStr1.substring(sidx+1, eidx); 8341 } 8342 8343 class AsecInstallArgs extends InstallArgs { 8344 static final String RES_FILE_NAME = "pkg.apk"; 8345 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 8346 8347 String cid; 8348 String packagePath; 8349 String resourcePath; 8350 String libraryPath; 8351 8352 AsecInstallArgs(InstallParams params) { 8353 super(params.getPackageUri(), params.observer, params.flags, 8354 params.installerPackageName, params.getManifestDigest(), 8355 params.getUser()); 8356 } 8357 8358 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 8359 boolean isExternal, boolean isForwardLocked) { 8360 super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 8361 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 8362 null, null, null); 8363 // Extract cid from fullCodePath 8364 int eidx = fullCodePath.lastIndexOf("/"); 8365 String subStr1 = fullCodePath.substring(0, eidx); 8366 int sidx = subStr1.lastIndexOf("/"); 8367 cid = subStr1.substring(sidx+1, eidx); 8368 setCachePath(subStr1); 8369 } 8370 8371 AsecInstallArgs(String cid, boolean isForwardLocked) { 8372 super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 8373 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 8374 null, null, null); 8375 this.cid = cid; 8376 setCachePath(PackageHelper.getSdDir(cid)); 8377 } 8378 8379 AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) { 8380 super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 8381 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 8382 null, null, null); 8383 this.cid = cid; 8384 } 8385 8386 void createCopyFile() { 8387 cid = getTempContainerId(); 8388 } 8389 8390 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 8391 try { 8392 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8393 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8394 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked()); 8395 } finally { 8396 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8397 } 8398 } 8399 8400 private final boolean isExternal() { 8401 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8402 } 8403 8404 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 8405 if (temp) { 8406 createCopyFile(); 8407 } else { 8408 /* 8409 * Pre-emptively destroy the container since it's destroyed if 8410 * copying fails due to it existing anyway. 8411 */ 8412 PackageHelper.destroySdDir(cid); 8413 } 8414 8415 final String newCachePath; 8416 try { 8417 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8418 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8419 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(), 8420 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked()); 8421 } finally { 8422 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8423 } 8424 8425 if (newCachePath != null) { 8426 setCachePath(newCachePath); 8427 return PackageManager.INSTALL_SUCCEEDED; 8428 } else { 8429 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 8430 } 8431 } 8432 8433 @Override 8434 String getCodePath() { 8435 return packagePath; 8436 } 8437 8438 @Override 8439 String getResourcePath() { 8440 return resourcePath; 8441 } 8442 8443 @Override 8444 String getNativeLibraryPath() { 8445 return libraryPath; 8446 } 8447 8448 int doPreInstall(int status) { 8449 if (status != PackageManager.INSTALL_SUCCEEDED) { 8450 // Destroy container 8451 PackageHelper.destroySdDir(cid); 8452 } else { 8453 boolean mounted = PackageHelper.isContainerMounted(cid); 8454 if (!mounted) { 8455 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 8456 Process.SYSTEM_UID); 8457 if (newCachePath != null) { 8458 setCachePath(newCachePath); 8459 } else { 8460 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 8461 } 8462 } 8463 } 8464 return status; 8465 } 8466 8467 boolean doRename(int status, final String pkgName, 8468 String oldCodePath) { 8469 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 8470 String newCachePath = null; 8471 if (PackageHelper.isContainerMounted(cid)) { 8472 // Unmount the container 8473 if (!PackageHelper.unMountSdDir(cid)) { 8474 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 8475 return false; 8476 } 8477 } 8478 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 8479 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 8480 " which might be stale. Will try to clean up."); 8481 // Clean up the stale container and proceed to recreate. 8482 if (!PackageHelper.destroySdDir(newCacheId)) { 8483 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 8484 return false; 8485 } 8486 // Successfully cleaned up stale container. Try to rename again. 8487 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 8488 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 8489 + " inspite of cleaning it up."); 8490 return false; 8491 } 8492 } 8493 if (!PackageHelper.isContainerMounted(newCacheId)) { 8494 Slog.w(TAG, "Mounting container " + newCacheId); 8495 newCachePath = PackageHelper.mountSdDir(newCacheId, 8496 getEncryptKey(), Process.SYSTEM_UID); 8497 } else { 8498 newCachePath = PackageHelper.getSdDir(newCacheId); 8499 } 8500 if (newCachePath == null) { 8501 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 8502 return false; 8503 } 8504 Log.i(TAG, "Succesfully renamed " + cid + 8505 " to " + newCacheId + 8506 " at new path: " + newCachePath); 8507 cid = newCacheId; 8508 setCachePath(newCachePath); 8509 return true; 8510 } 8511 8512 private void setCachePath(String newCachePath) { 8513 File cachePath = new File(newCachePath); 8514 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 8515 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 8516 8517 if (isFwdLocked()) { 8518 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 8519 } else { 8520 resourcePath = packagePath; 8521 } 8522 } 8523 8524 int doPostInstall(int status, int uid) { 8525 if (status != PackageManager.INSTALL_SUCCEEDED) { 8526 cleanUp(); 8527 } else { 8528 final int groupOwner; 8529 final String protectedFile; 8530 if (isFwdLocked()) { 8531 groupOwner = UserHandle.getSharedAppGid(uid); 8532 protectedFile = RES_FILE_NAME; 8533 } else { 8534 groupOwner = -1; 8535 protectedFile = null; 8536 } 8537 8538 if (uid < Process.FIRST_APPLICATION_UID 8539 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 8540 Slog.e(TAG, "Failed to finalize " + cid); 8541 PackageHelper.destroySdDir(cid); 8542 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 8543 } 8544 8545 boolean mounted = PackageHelper.isContainerMounted(cid); 8546 if (!mounted) { 8547 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 8548 } 8549 } 8550 return status; 8551 } 8552 8553 private void cleanUp() { 8554 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 8555 8556 // Destroy secure container 8557 PackageHelper.destroySdDir(cid); 8558 } 8559 8560 void cleanUpResourcesLI() { 8561 String sourceFile = getCodePath(); 8562 // Remove dex file 8563 int retCode = mInstaller.rmdex(sourceFile); 8564 if (retCode < 0) { 8565 Slog.w(TAG, "Couldn't remove dex file for package: " 8566 + " at location " 8567 + sourceFile.toString() + ", retcode=" + retCode); 8568 // we don't consider this to be a failure of the core package deletion 8569 } 8570 cleanUp(); 8571 } 8572 8573 boolean matchContainer(String app) { 8574 if (cid.startsWith(app)) { 8575 return true; 8576 } 8577 return false; 8578 } 8579 8580 String getPackageName() { 8581 return getAsecPackageName(cid); 8582 } 8583 8584 boolean doPostDeleteLI(boolean delete) { 8585 boolean ret = false; 8586 boolean mounted = PackageHelper.isContainerMounted(cid); 8587 if (mounted) { 8588 // Unmount first 8589 ret = PackageHelper.unMountSdDir(cid); 8590 } 8591 if (ret && delete) { 8592 cleanUpResourcesLI(); 8593 } 8594 return ret; 8595 } 8596 8597 @Override 8598 int doPreCopy() { 8599 if (isFwdLocked()) { 8600 if (!PackageHelper.fixSdPermissions(cid, 8601 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 8602 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 8603 } 8604 } 8605 8606 return PackageManager.INSTALL_SUCCEEDED; 8607 } 8608 8609 @Override 8610 int doPostCopy(int uid) { 8611 if (isFwdLocked()) { 8612 if (uid < Process.FIRST_APPLICATION_UID 8613 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 8614 RES_FILE_NAME)) { 8615 Slog.e(TAG, "Failed to finalize " + cid); 8616 PackageHelper.destroySdDir(cid); 8617 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 8618 } 8619 } 8620 8621 return PackageManager.INSTALL_SUCCEEDED; 8622 } 8623 }; 8624 8625 static String getAsecPackageName(String packageCid) { 8626 int idx = packageCid.lastIndexOf("-"); 8627 if (idx == -1) { 8628 return packageCid; 8629 } 8630 return packageCid.substring(0, idx); 8631 } 8632 8633 // Utility method used to create code paths based on package name and available index. 8634 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 8635 String idxStr = ""; 8636 int idx = 1; 8637 // Fall back to default value of idx=1 if prefix is not 8638 // part of oldCodePath 8639 if (oldCodePath != null) { 8640 String subStr = oldCodePath; 8641 // Drop the suffix right away 8642 if (subStr.endsWith(suffix)) { 8643 subStr = subStr.substring(0, subStr.length() - suffix.length()); 8644 } 8645 // If oldCodePath already contains prefix find out the 8646 // ending index to either increment or decrement. 8647 int sidx = subStr.lastIndexOf(prefix); 8648 if (sidx != -1) { 8649 subStr = subStr.substring(sidx + prefix.length()); 8650 if (subStr != null) { 8651 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 8652 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 8653 } 8654 try { 8655 idx = Integer.parseInt(subStr); 8656 if (idx <= 1) { 8657 idx++; 8658 } else { 8659 idx--; 8660 } 8661 } catch(NumberFormatException e) { 8662 } 8663 } 8664 } 8665 } 8666 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 8667 return prefix + idxStr; 8668 } 8669 8670 // Utility method used to ignore ADD/REMOVE events 8671 // by directory observer. 8672 private static boolean ignoreCodePath(String fullPathStr) { 8673 String apkName = getApkName(fullPathStr); 8674 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 8675 if (idx != -1 && ((idx+1) < apkName.length())) { 8676 // Make sure the package ends with a numeral 8677 String version = apkName.substring(idx+1); 8678 try { 8679 Integer.parseInt(version); 8680 return true; 8681 } catch (NumberFormatException e) {} 8682 } 8683 return false; 8684 } 8685 8686 // Utility method that returns the relative package path with respect 8687 // to the installation directory. Like say for /data/data/com.test-1.apk 8688 // string com.test-1 is returned. 8689 static String getApkName(String codePath) { 8690 if (codePath == null) { 8691 return null; 8692 } 8693 int sidx = codePath.lastIndexOf("/"); 8694 int eidx = codePath.lastIndexOf("."); 8695 if (eidx == -1) { 8696 eidx = codePath.length(); 8697 } else if (eidx == 0) { 8698 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 8699 return null; 8700 } 8701 return codePath.substring(sidx+1, eidx); 8702 } 8703 8704 class PackageInstalledInfo { 8705 String name; 8706 int uid; 8707 // The set of users that originally had this package installed. 8708 int[] origUsers; 8709 // The set of users that now have this package installed. 8710 int[] newUsers; 8711 PackageParser.Package pkg; 8712 int returnCode; 8713 PackageRemovedInfo removedInfo; 8714 } 8715 8716 /* 8717 * Install a non-existing package. 8718 */ 8719 private void installNewPackageLI(PackageParser.Package pkg, 8720 int parseFlags, int scanMode, UserHandle user, 8721 String installerPackageName, PackageInstalledInfo res) { 8722 // Remember this for later, in case we need to rollback this install 8723 String pkgName = pkg.packageName; 8724 8725 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 8726 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 8727 synchronized(mPackages) { 8728 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 8729 // A package with the same name is already installed, though 8730 // it has been renamed to an older name. The package we 8731 // are trying to install should be installed as an update to 8732 // the existing one, but that has not been requested, so bail. 8733 Slog.w(TAG, "Attempt to re-install " + pkgName 8734 + " without first uninstalling package running as " 8735 + mSettings.mRenamedPackages.get(pkgName)); 8736 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8737 return; 8738 } 8739 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) { 8740 // Don't allow installation over an existing package with the same name. 8741 Slog.w(TAG, "Attempt to re-install " + pkgName 8742 + " without first uninstalling."); 8743 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8744 return; 8745 } 8746 } 8747 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 8748 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 8749 System.currentTimeMillis(), user); 8750 if (newPackage == null) { 8751 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 8752 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 8753 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 8754 } 8755 } else { 8756 updateSettingsLI(newPackage, 8757 installerPackageName, 8758 null, null, 8759 res); 8760 // delete the partially installed application. the data directory will have to be 8761 // restored if it was already existing 8762 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 8763 // remove package from internal structures. Note that we want deletePackageX to 8764 // delete the package data and cache directories that it created in 8765 // scanPackageLocked, unless those directories existed before we even tried to 8766 // install. 8767 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 8768 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 8769 res.removedInfo, true); 8770 } 8771 } 8772 } 8773 8774 private void replacePackageLI(PackageParser.Package pkg, 8775 int parseFlags, int scanMode, UserHandle user, 8776 String installerPackageName, PackageInstalledInfo res) { 8777 8778 PackageParser.Package oldPackage; 8779 String pkgName = pkg.packageName; 8780 int[] allUsers; 8781 boolean[] perUserInstalled; 8782 8783 // First find the old package info and check signatures 8784 synchronized(mPackages) { 8785 oldPackage = mPackages.get(pkgName); 8786 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 8787 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 8788 != PackageManager.SIGNATURE_MATCH) { 8789 Slog.w(TAG, "New package has a different signature: " + pkgName); 8790 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 8791 return; 8792 } 8793 8794 // In case of rollback, remember per-user/profile install state 8795 PackageSetting ps = mSettings.mPackages.get(pkgName); 8796 allUsers = sUserManager.getUserIds(); 8797 perUserInstalled = new boolean[allUsers.length]; 8798 for (int i = 0; i < allUsers.length; i++) { 8799 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 8800 } 8801 } 8802 boolean sysPkg = (isSystemApp(oldPackage)); 8803 if (sysPkg) { 8804 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 8805 user, allUsers, perUserInstalled, installerPackageName, res); 8806 } else { 8807 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 8808 user, allUsers, perUserInstalled, installerPackageName, res); 8809 } 8810 } 8811 8812 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 8813 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 8814 int[] allUsers, boolean[] perUserInstalled, 8815 String installerPackageName, PackageInstalledInfo res) { 8816 PackageParser.Package newPackage = null; 8817 String pkgName = deletedPackage.packageName; 8818 boolean deletedPkg = true; 8819 boolean updatedSettings = false; 8820 8821 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 8822 + deletedPackage); 8823 long origUpdateTime; 8824 if (pkg.mExtras != null) { 8825 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 8826 } else { 8827 origUpdateTime = 0; 8828 } 8829 8830 // First delete the existing package while retaining the data directory 8831 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 8832 res.removedInfo, true)) { 8833 // If the existing package wasn't successfully deleted 8834 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 8835 deletedPkg = false; 8836 } else { 8837 // Successfully deleted the old package. Now proceed with re-installation 8838 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 8839 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 8840 System.currentTimeMillis(), user); 8841 if (newPackage == null) { 8842 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 8843 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 8844 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 8845 } 8846 } else { 8847 updateSettingsLI(newPackage, 8848 installerPackageName, 8849 allUsers, perUserInstalled, 8850 res); 8851 updatedSettings = true; 8852 } 8853 } 8854 8855 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 8856 // remove package from internal structures. Note that we want deletePackageX to 8857 // delete the package data and cache directories that it created in 8858 // scanPackageLocked, unless those directories existed before we even tried to 8859 // install. 8860 if(updatedSettings) { 8861 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 8862 deletePackageLI( 8863 pkgName, null, true, allUsers, perUserInstalled, 8864 PackageManager.DELETE_KEEP_DATA, 8865 res.removedInfo, true); 8866 } 8867 // Since we failed to install the new package we need to restore the old 8868 // package that we deleted. 8869 if(deletedPkg) { 8870 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 8871 File restoreFile = new File(deletedPackage.mPath); 8872 // Parse old package 8873 boolean oldOnSd = isExternal(deletedPackage); 8874 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 8875 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 8876 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 8877 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 8878 | SCAN_UPDATE_TIME; 8879 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 8880 origUpdateTime, null) == null) { 8881 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 8882 return; 8883 } 8884 // Restore of old package succeeded. Update permissions. 8885 // writer 8886 synchronized (mPackages) { 8887 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 8888 UPDATE_PERMISSIONS_ALL); 8889 // can downgrade to reader 8890 mSettings.writeLPr(); 8891 } 8892 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 8893 } 8894 } 8895 } 8896 8897 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 8898 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 8899 int[] allUsers, boolean[] perUserInstalled, 8900 String installerPackageName, PackageInstalledInfo res) { 8901 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 8902 + ", old=" + deletedPackage); 8903 PackageParser.Package newPackage = null; 8904 boolean updatedSettings = false; 8905 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 8906 PackageParser.PARSE_IS_SYSTEM; 8907 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 8908 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 8909 } 8910 String packageName = deletedPackage.packageName; 8911 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 8912 if (packageName == null) { 8913 Slog.w(TAG, "Attempt to delete null packageName."); 8914 return; 8915 } 8916 PackageParser.Package oldPkg; 8917 PackageSetting oldPkgSetting; 8918 // reader 8919 synchronized (mPackages) { 8920 oldPkg = mPackages.get(packageName); 8921 oldPkgSetting = mSettings.mPackages.get(packageName); 8922 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 8923 (oldPkgSetting == null)) { 8924 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 8925 return; 8926 } 8927 } 8928 8929 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 8930 8931 res.removedInfo.uid = oldPkg.applicationInfo.uid; 8932 res.removedInfo.removedPackage = packageName; 8933 // Remove existing system package 8934 removePackageLI(oldPkgSetting, true); 8935 // writer 8936 synchronized (mPackages) { 8937 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 8938 // We didn't need to disable the .apk as a current system package, 8939 // which means we are replacing another update that is already 8940 // installed. We need to make sure to delete the older one's .apk. 8941 res.removedInfo.args = createInstallArgs(0, 8942 deletedPackage.applicationInfo.sourceDir, 8943 deletedPackage.applicationInfo.publicSourceDir, 8944 deletedPackage.applicationInfo.nativeLibraryDir); 8945 } else { 8946 res.removedInfo.args = null; 8947 } 8948 } 8949 8950 // Successfully disabled the old package. Now proceed with re-installation 8951 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 8952 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8953 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user); 8954 if (newPackage == null) { 8955 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 8956 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 8957 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 8958 } 8959 } else { 8960 if (newPackage.mExtras != null) { 8961 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 8962 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 8963 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 8964 } 8965 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 8966 updatedSettings = true; 8967 } 8968 8969 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 8970 // Re installation failed. Restore old information 8971 // Remove new pkg information 8972 if (newPackage != null) { 8973 removeInstalledPackageLI(newPackage, true); 8974 } 8975 // Add back the old system package 8976 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user); 8977 // Restore the old system information in Settings 8978 synchronized(mPackages) { 8979 if (updatedSettings) { 8980 mSettings.enableSystemPackageLPw(packageName); 8981 mSettings.setInstallerPackageName(packageName, 8982 oldPkgSetting.installerPackageName); 8983 } 8984 mSettings.writeLPr(); 8985 } 8986 } 8987 } 8988 8989 // Utility method used to move dex files during install. 8990 private int moveDexFilesLI(PackageParser.Package newPackage) { 8991 int retCode; 8992 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 8993 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath); 8994 if (retCode != 0) { 8995 if (mNoDexOpt) { 8996 /* 8997 * If we're in an engineering build, programs are lazily run 8998 * through dexopt. If the .dex file doesn't exist yet, it 8999 * will be created when the program is run next. 9000 */ 9001 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath); 9002 } else { 9003 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath); 9004 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9005 } 9006 } 9007 } 9008 return PackageManager.INSTALL_SUCCEEDED; 9009 } 9010 9011 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 9012 int[] allUsers, boolean[] perUserInstalled, 9013 PackageInstalledInfo res) { 9014 String pkgName = newPackage.packageName; 9015 synchronized (mPackages) { 9016 //write settings. the installStatus will be incomplete at this stage. 9017 //note that the new package setting would have already been 9018 //added to mPackages. It hasn't been persisted yet. 9019 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 9020 mSettings.writeLPr(); 9021 } 9022 9023 if ((res.returnCode = moveDexFilesLI(newPackage)) 9024 != PackageManager.INSTALL_SUCCEEDED) { 9025 // Discontinue if moving dex files failed. 9026 return; 9027 } 9028 9029 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath); 9030 9031 synchronized (mPackages) { 9032 updatePermissionsLPw(newPackage.packageName, newPackage, 9033 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 9034 ? UPDATE_PERMISSIONS_ALL : 0)); 9035 // For system-bundled packages, we assume that installing an upgraded version 9036 // of the package implies that the user actually wants to run that new code, 9037 // so we enable the package. 9038 if (isSystemApp(newPackage)) { 9039 // NB: implicit assumption that system package upgrades apply to all users 9040 if (DEBUG_INSTALL) { 9041 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 9042 } 9043 PackageSetting ps = mSettings.mPackages.get(pkgName); 9044 if (ps != null) { 9045 if (res.origUsers != null) { 9046 for (int userHandle : res.origUsers) { 9047 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 9048 userHandle, installerPackageName); 9049 } 9050 } 9051 // Also convey the prior install/uninstall state 9052 if (allUsers != null && perUserInstalled != null) { 9053 for (int i = 0; i < allUsers.length; i++) { 9054 if (DEBUG_INSTALL) { 9055 Slog.d(TAG, " user " + allUsers[i] 9056 + " => " + perUserInstalled[i]); 9057 } 9058 ps.setInstalled(perUserInstalled[i], allUsers[i]); 9059 } 9060 // these install state changes will be persisted in the 9061 // upcoming call to mSettings.writeLPr(). 9062 } 9063 } 9064 } 9065 res.name = pkgName; 9066 res.uid = newPackage.applicationInfo.uid; 9067 res.pkg = newPackage; 9068 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 9069 mSettings.setInstallerPackageName(pkgName, installerPackageName); 9070 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 9071 //to update install status 9072 mSettings.writeLPr(); 9073 } 9074 } 9075 9076 private void installPackageLI(InstallArgs args, 9077 boolean newInstall, PackageInstalledInfo res) { 9078 int pFlags = args.flags; 9079 String installerPackageName = args.installerPackageName; 9080 File tmpPackageFile = new File(args.getCodePath()); 9081 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 9082 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 9083 boolean replace = false; 9084 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 9085 | (newInstall ? SCAN_NEW_INSTALL : 0); 9086 // Result object to be returned 9087 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 9088 9089 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 9090 // Retrieve PackageSettings and parse package 9091 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 9092 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 9093 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 9094 PackageParser pp = new PackageParser(tmpPackageFile.getPath()); 9095 pp.setSeparateProcesses(mSeparateProcesses); 9096 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile, 9097 null, mMetrics, parseFlags); 9098 if (pkg == null) { 9099 res.returnCode = pp.getParseError(); 9100 return; 9101 } 9102 String pkgName = res.name = pkg.packageName; 9103 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 9104 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 9105 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 9106 return; 9107 } 9108 } 9109 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) { 9110 res.returnCode = pp.getParseError(); 9111 return; 9112 } 9113 9114 /* If the installer passed in a manifest digest, compare it now. */ 9115 if (args.manifestDigest != null) { 9116 if (DEBUG_INSTALL) { 9117 final String parsedManifest = pkg.manifestDigest == null ? "null" 9118 : pkg.manifestDigest.toString(); 9119 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 9120 + parsedManifest); 9121 } 9122 9123 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 9124 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 9125 return; 9126 } 9127 } else if (DEBUG_INSTALL) { 9128 final String parsedManifest = pkg.manifestDigest == null 9129 ? "null" : pkg.manifestDigest.toString(); 9130 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 9131 } 9132 9133 // Get rid of all references to package scan path via parser. 9134 pp = null; 9135 String oldCodePath = null; 9136 boolean systemApp = false; 9137 synchronized (mPackages) { 9138 // Check if installing already existing package 9139 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9140 String oldName = mSettings.mRenamedPackages.get(pkgName); 9141 if (pkg.mOriginalPackages != null 9142 && pkg.mOriginalPackages.contains(oldName) 9143 && mPackages.containsKey(oldName)) { 9144 // This package is derived from an original package, 9145 // and this device has been updating from that original 9146 // name. We must continue using the original name, so 9147 // rename the new package here. 9148 pkg.setPackageName(oldName); 9149 pkgName = pkg.packageName; 9150 replace = true; 9151 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 9152 + oldName + " pkgName=" + pkgName); 9153 } else if (mPackages.containsKey(pkgName)) { 9154 // This package, under its official name, already exists 9155 // on the device; we should replace it. 9156 replace = true; 9157 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 9158 } 9159 } 9160 PackageSetting ps = mSettings.mPackages.get(pkgName); 9161 if (ps != null) { 9162 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 9163 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 9164 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 9165 systemApp = (ps.pkg.applicationInfo.flags & 9166 ApplicationInfo.FLAG_SYSTEM) != 0; 9167 } 9168 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 9169 } 9170 } 9171 9172 if (systemApp && onSd) { 9173 // Disable updates to system apps on sdcard 9174 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 9175 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9176 return; 9177 } 9178 9179 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 9180 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9181 return; 9182 } 9183 // Set application objects path explicitly after the rename 9184 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath()); 9185 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 9186 if (replace) { 9187 replacePackageLI(pkg, parseFlags, scanMode, args.user, 9188 installerPackageName, res); 9189 } else { 9190 installNewPackageLI(pkg, parseFlags, scanMode, args.user, 9191 installerPackageName, res); 9192 } 9193 synchronized (mPackages) { 9194 final PackageSetting ps = mSettings.mPackages.get(pkgName); 9195 if (ps != null) { 9196 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 9197 } 9198 } 9199 } 9200 9201 private static boolean isForwardLocked(PackageParser.Package pkg) { 9202 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 9203 } 9204 9205 9206 private boolean isForwardLocked(PackageSetting ps) { 9207 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 9208 } 9209 9210 private static boolean isExternal(PackageParser.Package pkg) { 9211 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 9212 } 9213 9214 private static boolean isExternal(PackageSetting ps) { 9215 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 9216 } 9217 9218 private static boolean isSystemApp(PackageParser.Package pkg) { 9219 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9220 } 9221 9222 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 9223 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 9224 } 9225 9226 private static boolean isSystemApp(ApplicationInfo info) { 9227 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9228 } 9229 9230 private static boolean isSystemApp(PackageSetting ps) { 9231 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 9232 } 9233 9234 private static boolean isUpdatedSystemApp(PackageSetting ps) { 9235 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 9236 } 9237 9238 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 9239 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 9240 } 9241 9242 private int packageFlagsToInstallFlags(PackageSetting ps) { 9243 int installFlags = 0; 9244 if (isExternal(ps)) { 9245 installFlags |= PackageManager.INSTALL_EXTERNAL; 9246 } 9247 if (isForwardLocked(ps)) { 9248 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 9249 } 9250 return installFlags; 9251 } 9252 9253 private void deleteTempPackageFiles() { 9254 final FilenameFilter filter = new FilenameFilter() { 9255 public boolean accept(File dir, String name) { 9256 return name.startsWith("vmdl") && name.endsWith(".tmp"); 9257 } 9258 }; 9259 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 9260 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 9261 } 9262 9263 private static final void deleteTempPackageFilesInDirectory(File directory, 9264 FilenameFilter filter) { 9265 final String[] tmpFilesList = directory.list(filter); 9266 if (tmpFilesList == null) { 9267 return; 9268 } 9269 for (int i = 0; i < tmpFilesList.length; i++) { 9270 final File tmpFile = new File(directory, tmpFilesList[i]); 9271 tmpFile.delete(); 9272 } 9273 } 9274 9275 private File createTempPackageFile(File installDir) { 9276 File tmpPackageFile; 9277 try { 9278 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 9279 } catch (IOException e) { 9280 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 9281 return null; 9282 } 9283 try { 9284 FileUtils.setPermissions( 9285 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 9286 -1, -1); 9287 if (!SELinux.restorecon(tmpPackageFile)) { 9288 return null; 9289 } 9290 } catch (IOException e) { 9291 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 9292 return null; 9293 } 9294 return tmpPackageFile; 9295 } 9296 9297 @Override 9298 public void deletePackageAsUser(final String packageName, 9299 final IPackageDeleteObserver observer, 9300 final int userId, final int flags) { 9301 mContext.enforceCallingOrSelfPermission( 9302 android.Manifest.permission.DELETE_PACKAGES, null); 9303 final int uid = Binder.getCallingUid(); 9304 if (UserHandle.getUserId(uid) != userId) { 9305 mContext.enforceCallingPermission( 9306 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 9307 "deletePackage for user " + userId); 9308 } 9309 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 9310 try { 9311 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 9312 } catch (RemoteException re) { 9313 } 9314 return; 9315 } 9316 9317 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 9318 // Queue up an async operation since the package deletion may take a little while. 9319 mHandler.post(new Runnable() { 9320 public void run() { 9321 mHandler.removeCallbacks(this); 9322 final int returnCode = deletePackageX(packageName, userId, flags); 9323 if (observer != null) { 9324 try { 9325 observer.packageDeleted(packageName, returnCode); 9326 } catch (RemoteException e) { 9327 Log.i(TAG, "Observer no longer exists."); 9328 } //end catch 9329 } //end if 9330 } //end run 9331 }); 9332 } 9333 9334 private boolean isPackageDeviceAdmin(String packageName, int userId) { 9335 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 9336 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 9337 try { 9338 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 9339 || dpm.isDeviceOwner(packageName))) { 9340 return true; 9341 } 9342 } catch (RemoteException e) { 9343 } 9344 return false; 9345 } 9346 9347 /** 9348 * This method is an internal method that could be get invoked either 9349 * to delete an installed package or to clean up a failed installation. 9350 * After deleting an installed package, a broadcast is sent to notify any 9351 * listeners that the package has been installed. For cleaning up a failed 9352 * installation, the broadcast is not necessary since the package's 9353 * installation wouldn't have sent the initial broadcast either 9354 * The key steps in deleting a package are 9355 * deleting the package information in internal structures like mPackages, 9356 * deleting the packages base directories through installd 9357 * updating mSettings to reflect current status 9358 * persisting settings for later use 9359 * sending a broadcast if necessary 9360 */ 9361 private int deletePackageX(String packageName, int userId, int flags) { 9362 final PackageRemovedInfo info = new PackageRemovedInfo(); 9363 final boolean res; 9364 9365 if (isPackageDeviceAdmin(packageName, userId)) { 9366 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 9367 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 9368 } 9369 9370 boolean removedForAllUsers = false; 9371 boolean systemUpdate = false; 9372 9373 // for the uninstall-updates case and restricted profiles, remember the per- 9374 // userhandle installed state 9375 int[] allUsers; 9376 boolean[] perUserInstalled; 9377 synchronized (mPackages) { 9378 PackageSetting ps = mSettings.mPackages.get(packageName); 9379 allUsers = sUserManager.getUserIds(); 9380 perUserInstalled = new boolean[allUsers.length]; 9381 for (int i = 0; i < allUsers.length; i++) { 9382 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9383 } 9384 } 9385 9386 synchronized (mInstallLock) { 9387 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 9388 res = deletePackageLI(packageName, 9389 (flags & PackageManager.DELETE_ALL_USERS) != 0 9390 ? UserHandle.ALL : new UserHandle(userId), 9391 true, allUsers, perUserInstalled, 9392 flags | REMOVE_CHATTY, info, true); 9393 systemUpdate = info.isRemovedPackageSystemUpdate; 9394 if (res && !systemUpdate && mPackages.get(packageName) == null) { 9395 removedForAllUsers = true; 9396 } 9397 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 9398 + " removedForAllUsers=" + removedForAllUsers); 9399 } 9400 9401 if (res) { 9402 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 9403 9404 // If the removed package was a system update, the old system package 9405 // was re-enabled; we need to broadcast this information 9406 if (systemUpdate) { 9407 Bundle extras = new Bundle(1); 9408 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 9409 ? info.removedAppId : info.uid); 9410 extras.putBoolean(Intent.EXTRA_REPLACING, true); 9411 9412 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 9413 extras, null, null, null); 9414 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 9415 extras, null, null, null); 9416 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 9417 null, packageName, null, null); 9418 } 9419 } 9420 // Force a gc here. 9421 Runtime.getRuntime().gc(); 9422 // Delete the resources here after sending the broadcast to let 9423 // other processes clean up before deleting resources. 9424 if (info.args != null) { 9425 synchronized (mInstallLock) { 9426 info.args.doPostDeleteLI(true); 9427 } 9428 } 9429 9430 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 9431 } 9432 9433 static class PackageRemovedInfo { 9434 String removedPackage; 9435 int uid = -1; 9436 int removedAppId = -1; 9437 int[] removedUsers = null; 9438 boolean isRemovedPackageSystemUpdate = false; 9439 // Clean up resources deleted packages. 9440 InstallArgs args = null; 9441 9442 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 9443 Bundle extras = new Bundle(1); 9444 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 9445 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 9446 if (replacing) { 9447 extras.putBoolean(Intent.EXTRA_REPLACING, true); 9448 } 9449 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 9450 if (removedPackage != null) { 9451 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 9452 extras, null, null, removedUsers); 9453 if (fullRemove && !replacing) { 9454 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 9455 extras, null, null, removedUsers); 9456 } 9457 } 9458 if (removedAppId >= 0) { 9459 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 9460 removedUsers); 9461 } 9462 } 9463 } 9464 9465 /* 9466 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 9467 * flag is not set, the data directory is removed as well. 9468 * make sure this flag is set for partially installed apps. If not its meaningless to 9469 * delete a partially installed application. 9470 */ 9471 private void removePackageDataLI(PackageSetting ps, 9472 int[] allUserHandles, boolean[] perUserInstalled, 9473 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 9474 String packageName = ps.name; 9475 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 9476 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 9477 // Retrieve object to delete permissions for shared user later on 9478 final PackageSetting deletedPs; 9479 // reader 9480 synchronized (mPackages) { 9481 deletedPs = mSettings.mPackages.get(packageName); 9482 if (outInfo != null) { 9483 outInfo.removedPackage = packageName; 9484 outInfo.removedUsers = deletedPs != null 9485 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 9486 : null; 9487 } 9488 } 9489 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 9490 removeDataDirsLI(packageName); 9491 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 9492 } 9493 // writer 9494 synchronized (mPackages) { 9495 if (deletedPs != null) { 9496 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 9497 if (outInfo != null) { 9498 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 9499 } 9500 if (deletedPs != null) { 9501 updatePermissionsLPw(deletedPs.name, null, 0); 9502 if (deletedPs.sharedUser != null) { 9503 // remove permissions associated with package 9504 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 9505 } 9506 } 9507 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 9508 } 9509 // make sure to preserve per-user disabled state if this removal was just 9510 // a downgrade of a system app to the factory package 9511 if (allUserHandles != null && perUserInstalled != null) { 9512 if (DEBUG_REMOVE) { 9513 Slog.d(TAG, "Propagating install state across downgrade"); 9514 } 9515 for (int i = 0; i < allUserHandles.length; i++) { 9516 if (DEBUG_REMOVE) { 9517 Slog.d(TAG, " user " + allUserHandles[i] 9518 + " => " + perUserInstalled[i]); 9519 } 9520 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 9521 } 9522 } 9523 } 9524 // can downgrade to reader 9525 if (writeSettings) { 9526 // Save settings now 9527 mSettings.writeLPr(); 9528 } 9529 } 9530 if (outInfo != null) { 9531 // A user ID was deleted here. Go through all users and remove it 9532 // from KeyStore. 9533 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 9534 } 9535 } 9536 9537 static boolean locationIsPrivileged(File path) { 9538 try { 9539 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 9540 .getCanonicalPath(); 9541 return path.getCanonicalPath().startsWith(privilegedAppDir); 9542 } catch (IOException e) { 9543 Slog.e(TAG, "Unable to access code path " + path); 9544 } 9545 return false; 9546 } 9547 9548 /* 9549 * Tries to delete system package. 9550 */ 9551 private boolean deleteSystemPackageLI(PackageSetting newPs, 9552 int[] allUserHandles, boolean[] perUserInstalled, 9553 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 9554 final boolean applyUserRestrictions 9555 = (allUserHandles != null) && (perUserInstalled != null); 9556 PackageSetting disabledPs = null; 9557 // Confirm if the system package has been updated 9558 // An updated system app can be deleted. This will also have to restore 9559 // the system pkg from system partition 9560 // reader 9561 synchronized (mPackages) { 9562 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 9563 } 9564 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 9565 + " disabledPs=" + disabledPs); 9566 if (disabledPs == null) { 9567 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 9568 return false; 9569 } else if (DEBUG_REMOVE) { 9570 Slog.d(TAG, "Deleting system pkg from data partition"); 9571 } 9572 if (DEBUG_REMOVE) { 9573 if (applyUserRestrictions) { 9574 Slog.d(TAG, "Remembering install states:"); 9575 for (int i = 0; i < allUserHandles.length; i++) { 9576 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 9577 } 9578 } 9579 } 9580 // Delete the updated package 9581 outInfo.isRemovedPackageSystemUpdate = true; 9582 if (disabledPs.versionCode < newPs.versionCode) { 9583 // Delete data for downgrades 9584 flags &= ~PackageManager.DELETE_KEEP_DATA; 9585 } else { 9586 // Preserve data by setting flag 9587 flags |= PackageManager.DELETE_KEEP_DATA; 9588 } 9589 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 9590 allUserHandles, perUserInstalled, outInfo, writeSettings); 9591 if (!ret) { 9592 return false; 9593 } 9594 // writer 9595 synchronized (mPackages) { 9596 // Reinstate the old system package 9597 mSettings.enableSystemPackageLPw(newPs.name); 9598 // Remove any native libraries from the upgraded package. 9599 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 9600 } 9601 // Install the system package 9602 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 9603 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 9604 if (locationIsPrivileged(disabledPs.codePath)) { 9605 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9606 } 9607 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 9608 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null); 9609 9610 if (newPkg == null) { 9611 Slog.w(TAG, "Failed to restore system package:" + newPs.name 9612 + " with error:" + mLastScanError); 9613 return false; 9614 } 9615 // writer 9616 synchronized (mPackages) { 9617 updatePermissionsLPw(newPkg.packageName, newPkg, 9618 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 9619 if (applyUserRestrictions) { 9620 if (DEBUG_REMOVE) { 9621 Slog.d(TAG, "Propagating install state across reinstall"); 9622 } 9623 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 9624 for (int i = 0; i < allUserHandles.length; i++) { 9625 if (DEBUG_REMOVE) { 9626 Slog.d(TAG, " user " + allUserHandles[i] 9627 + " => " + perUserInstalled[i]); 9628 } 9629 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 9630 } 9631 // Regardless of writeSettings we need to ensure that this restriction 9632 // state propagation is persisted 9633 mSettings.writeAllUsersPackageRestrictionsLPr(); 9634 } 9635 // can downgrade to reader here 9636 if (writeSettings) { 9637 mSettings.writeLPr(); 9638 } 9639 } 9640 return true; 9641 } 9642 9643 private boolean deleteInstalledPackageLI(PackageSetting ps, 9644 boolean deleteCodeAndResources, int flags, 9645 int[] allUserHandles, boolean[] perUserInstalled, 9646 PackageRemovedInfo outInfo, boolean writeSettings) { 9647 if (outInfo != null) { 9648 outInfo.uid = ps.appId; 9649 } 9650 9651 // Delete package data from internal structures and also remove data if flag is set 9652 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 9653 9654 // Delete application code and resources 9655 if (deleteCodeAndResources && (outInfo != null)) { 9656 outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString, 9657 ps.resourcePathString, ps.nativeLibraryPathString); 9658 } 9659 return true; 9660 } 9661 9662 /* 9663 * This method handles package deletion in general 9664 */ 9665 private boolean deletePackageLI(String packageName, UserHandle user, 9666 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 9667 int flags, PackageRemovedInfo outInfo, 9668 boolean writeSettings) { 9669 if (packageName == null) { 9670 Slog.w(TAG, "Attempt to delete null packageName."); 9671 return false; 9672 } 9673 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 9674 PackageSetting ps; 9675 boolean dataOnly = false; 9676 int removeUser = -1; 9677 int appId = -1; 9678 synchronized (mPackages) { 9679 ps = mSettings.mPackages.get(packageName); 9680 if (ps == null) { 9681 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 9682 return false; 9683 } 9684 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 9685 && user.getIdentifier() != UserHandle.USER_ALL) { 9686 // The caller is asking that the package only be deleted for a single 9687 // user. To do this, we just mark its uninstalled state and delete 9688 // its data. If this is a system app, we only allow this to happen if 9689 // they have set the special DELETE_SYSTEM_APP which requests different 9690 // semantics than normal for uninstalling system apps. 9691 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 9692 ps.setUserState(user.getIdentifier(), 9693 COMPONENT_ENABLED_STATE_DEFAULT, 9694 false, //installed 9695 true, //stopped 9696 true, //notLaunched 9697 false, //blocked 9698 null, null, null); 9699 if (!isSystemApp(ps)) { 9700 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 9701 // Other user still have this package installed, so all 9702 // we need to do is clear this user's data and save that 9703 // it is uninstalled. 9704 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 9705 removeUser = user.getIdentifier(); 9706 appId = ps.appId; 9707 mSettings.writePackageRestrictionsLPr(removeUser); 9708 } else { 9709 // We need to set it back to 'installed' so the uninstall 9710 // broadcasts will be sent correctly. 9711 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 9712 ps.setInstalled(true, user.getIdentifier()); 9713 } 9714 } else { 9715 // This is a system app, so we assume that the 9716 // other users still have this package installed, so all 9717 // we need to do is clear this user's data and save that 9718 // it is uninstalled. 9719 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 9720 removeUser = user.getIdentifier(); 9721 appId = ps.appId; 9722 mSettings.writePackageRestrictionsLPr(removeUser); 9723 } 9724 } 9725 } 9726 9727 if (removeUser >= 0) { 9728 // From above, we determined that we are deleting this only 9729 // for a single user. Continue the work here. 9730 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 9731 if (outInfo != null) { 9732 outInfo.removedPackage = packageName; 9733 outInfo.removedAppId = appId; 9734 outInfo.removedUsers = new int[] {removeUser}; 9735 } 9736 mInstaller.clearUserData(packageName, removeUser); 9737 removeKeystoreDataIfNeeded(removeUser, appId); 9738 schedulePackageCleaning(packageName, removeUser, false); 9739 return true; 9740 } 9741 9742 if (dataOnly) { 9743 // Delete application data first 9744 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 9745 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 9746 return true; 9747 } 9748 9749 boolean ret = false; 9750 mSettings.mKeySetManager.removeAppKeySetData(packageName); 9751 if (isSystemApp(ps)) { 9752 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 9753 // When an updated system application is deleted we delete the existing resources as well and 9754 // fall back to existing code in system partition 9755 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 9756 flags, outInfo, writeSettings); 9757 } else { 9758 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 9759 // Kill application pre-emptively especially for apps on sd. 9760 killApplication(packageName, ps.appId, "uninstall pkg"); 9761 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 9762 allUserHandles, perUserInstalled, 9763 outInfo, writeSettings); 9764 } 9765 9766 return ret; 9767 } 9768 9769 private final class ClearStorageConnection implements ServiceConnection { 9770 IMediaContainerService mContainerService; 9771 9772 @Override 9773 public void onServiceConnected(ComponentName name, IBinder service) { 9774 synchronized (this) { 9775 mContainerService = IMediaContainerService.Stub.asInterface(service); 9776 notifyAll(); 9777 } 9778 } 9779 9780 @Override 9781 public void onServiceDisconnected(ComponentName name) { 9782 } 9783 } 9784 9785 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 9786 final boolean mounted; 9787 if (Environment.isExternalStorageEmulated()) { 9788 mounted = true; 9789 } else { 9790 final String status = Environment.getExternalStorageState(); 9791 9792 mounted = status.equals(Environment.MEDIA_MOUNTED) 9793 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 9794 } 9795 9796 if (!mounted) { 9797 return; 9798 } 9799 9800 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 9801 int[] users; 9802 if (userId == UserHandle.USER_ALL) { 9803 users = sUserManager.getUserIds(); 9804 } else { 9805 users = new int[] { userId }; 9806 } 9807 final ClearStorageConnection conn = new ClearStorageConnection(); 9808 if (mContext.bindServiceAsUser( 9809 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 9810 try { 9811 for (int curUser : users) { 9812 long timeout = SystemClock.uptimeMillis() + 5000; 9813 synchronized (conn) { 9814 long now = SystemClock.uptimeMillis(); 9815 while (conn.mContainerService == null && now < timeout) { 9816 try { 9817 conn.wait(timeout - now); 9818 } catch (InterruptedException e) { 9819 } 9820 } 9821 } 9822 if (conn.mContainerService == null) { 9823 return; 9824 } 9825 9826 final UserEnvironment userEnv = new UserEnvironment(curUser); 9827 clearDirectory(conn.mContainerService, 9828 userEnv.buildExternalStorageAppCacheDirs(packageName)); 9829 if (allData) { 9830 clearDirectory(conn.mContainerService, 9831 userEnv.buildExternalStorageAppDataDirs(packageName)); 9832 clearDirectory(conn.mContainerService, 9833 userEnv.buildExternalStorageAppMediaDirs(packageName)); 9834 } 9835 } 9836 } finally { 9837 mContext.unbindService(conn); 9838 } 9839 } 9840 } 9841 9842 @Override 9843 public void clearApplicationUserData(final String packageName, 9844 final IPackageDataObserver observer, final int userId) { 9845 mContext.enforceCallingOrSelfPermission( 9846 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 9847 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 9848 // Queue up an async operation since the package deletion may take a little while. 9849 mHandler.post(new Runnable() { 9850 public void run() { 9851 mHandler.removeCallbacks(this); 9852 final boolean succeeded; 9853 synchronized (mInstallLock) { 9854 succeeded = clearApplicationUserDataLI(packageName, userId); 9855 } 9856 clearExternalStorageDataSync(packageName, userId, true); 9857 if (succeeded) { 9858 // invoke DeviceStorageMonitor's update method to clear any notifications 9859 DeviceStorageMonitorInternal 9860 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9861 if (dsm != null) { 9862 dsm.checkMemory(); 9863 } 9864 } 9865 if(observer != null) { 9866 try { 9867 observer.onRemoveCompleted(packageName, succeeded); 9868 } catch (RemoteException e) { 9869 Log.i(TAG, "Observer no longer exists."); 9870 } 9871 } //end if observer 9872 } //end run 9873 }); 9874 } 9875 9876 private boolean clearApplicationUserDataLI(String packageName, int userId) { 9877 if (packageName == null) { 9878 Slog.w(TAG, "Attempt to delete null packageName."); 9879 return false; 9880 } 9881 PackageParser.Package p; 9882 boolean dataOnly = false; 9883 final int appId; 9884 synchronized (mPackages) { 9885 p = mPackages.get(packageName); 9886 if (p == null) { 9887 dataOnly = true; 9888 PackageSetting ps = mSettings.mPackages.get(packageName); 9889 if ((ps == null) || (ps.pkg == null)) { 9890 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 9891 return false; 9892 } 9893 p = ps.pkg; 9894 } 9895 if (!dataOnly) { 9896 // need to check this only for fully installed applications 9897 if (p == null) { 9898 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 9899 return false; 9900 } 9901 final ApplicationInfo applicationInfo = p.applicationInfo; 9902 if (applicationInfo == null) { 9903 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 9904 return false; 9905 } 9906 } 9907 if (p != null && p.applicationInfo != null) { 9908 appId = p.applicationInfo.uid; 9909 } else { 9910 appId = -1; 9911 } 9912 } 9913 int retCode = mInstaller.clearUserData(packageName, userId); 9914 if (retCode < 0) { 9915 Slog.w(TAG, "Couldn't remove cache files for package: " 9916 + packageName); 9917 return false; 9918 } 9919 removeKeystoreDataIfNeeded(userId, appId); 9920 return true; 9921 } 9922 9923 /** 9924 * Remove entries from the keystore daemon. Will only remove it if the 9925 * {@code appId} is valid. 9926 */ 9927 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 9928 if (appId < 0) { 9929 return; 9930 } 9931 9932 final KeyStore keyStore = KeyStore.getInstance(); 9933 if (keyStore != null) { 9934 if (userId == UserHandle.USER_ALL) { 9935 for (final int individual : sUserManager.getUserIds()) { 9936 keyStore.clearUid(UserHandle.getUid(individual, appId)); 9937 } 9938 } else { 9939 keyStore.clearUid(UserHandle.getUid(userId, appId)); 9940 } 9941 } else { 9942 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 9943 } 9944 } 9945 9946 public void deleteApplicationCacheFiles(final String packageName, 9947 final IPackageDataObserver observer) { 9948 mContext.enforceCallingOrSelfPermission( 9949 android.Manifest.permission.DELETE_CACHE_FILES, null); 9950 // Queue up an async operation since the package deletion may take a little while. 9951 final int userId = UserHandle.getCallingUserId(); 9952 mHandler.post(new Runnable() { 9953 public void run() { 9954 mHandler.removeCallbacks(this); 9955 final boolean succeded; 9956 synchronized (mInstallLock) { 9957 succeded = deleteApplicationCacheFilesLI(packageName, userId); 9958 } 9959 clearExternalStorageDataSync(packageName, userId, false); 9960 if(observer != null) { 9961 try { 9962 observer.onRemoveCompleted(packageName, succeded); 9963 } catch (RemoteException e) { 9964 Log.i(TAG, "Observer no longer exists."); 9965 } 9966 } //end if observer 9967 } //end run 9968 }); 9969 } 9970 9971 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 9972 if (packageName == null) { 9973 Slog.w(TAG, "Attempt to delete null packageName."); 9974 return false; 9975 } 9976 PackageParser.Package p; 9977 synchronized (mPackages) { 9978 p = mPackages.get(packageName); 9979 } 9980 if (p == null) { 9981 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 9982 return false; 9983 } 9984 final ApplicationInfo applicationInfo = p.applicationInfo; 9985 if (applicationInfo == null) { 9986 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 9987 return false; 9988 } 9989 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 9990 if (retCode < 0) { 9991 Slog.w(TAG, "Couldn't remove cache files for package: " 9992 + packageName + " u" + userId); 9993 return false; 9994 } 9995 return true; 9996 } 9997 9998 public void getPackageSizeInfo(final String packageName, int userHandle, 9999 final IPackageStatsObserver observer) { 10000 mContext.enforceCallingOrSelfPermission( 10001 android.Manifest.permission.GET_PACKAGE_SIZE, null); 10002 10003 PackageStats stats = new PackageStats(packageName, userHandle); 10004 10005 /* 10006 * Queue up an async operation since the package measurement may take a 10007 * little while. 10008 */ 10009 Message msg = mHandler.obtainMessage(INIT_COPY); 10010 msg.obj = new MeasureParams(stats, observer); 10011 mHandler.sendMessage(msg); 10012 } 10013 10014 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 10015 PackageStats pStats) { 10016 if (packageName == null) { 10017 Slog.w(TAG, "Attempt to get size of null packageName."); 10018 return false; 10019 } 10020 PackageParser.Package p; 10021 boolean dataOnly = false; 10022 String libDirPath = null; 10023 String asecPath = null; 10024 synchronized (mPackages) { 10025 p = mPackages.get(packageName); 10026 PackageSetting ps = mSettings.mPackages.get(packageName); 10027 if(p == null) { 10028 dataOnly = true; 10029 if((ps == null) || (ps.pkg == null)) { 10030 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 10031 return false; 10032 } 10033 p = ps.pkg; 10034 } 10035 if (ps != null) { 10036 libDirPath = ps.nativeLibraryPathString; 10037 } 10038 if (p != null && (isExternal(p) || isForwardLocked(p))) { 10039 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 10040 if (secureContainerId != null) { 10041 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 10042 } 10043 } 10044 } 10045 String publicSrcDir = null; 10046 if(!dataOnly) { 10047 final ApplicationInfo applicationInfo = p.applicationInfo; 10048 if (applicationInfo == null) { 10049 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10050 return false; 10051 } 10052 if (isForwardLocked(p)) { 10053 publicSrcDir = applicationInfo.publicSourceDir; 10054 } 10055 } 10056 int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath, 10057 publicSrcDir, asecPath, pStats); 10058 if (res < 0) { 10059 return false; 10060 } 10061 10062 // Fix-up for forward-locked applications in ASEC containers. 10063 if (!isExternal(p)) { 10064 pStats.codeSize += pStats.externalCodeSize; 10065 pStats.externalCodeSize = 0L; 10066 } 10067 10068 return true; 10069 } 10070 10071 10072 public void addPackageToPreferred(String packageName) { 10073 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 10074 } 10075 10076 public void removePackageFromPreferred(String packageName) { 10077 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 10078 } 10079 10080 public List<PackageInfo> getPreferredPackages(int flags) { 10081 return new ArrayList<PackageInfo>(); 10082 } 10083 10084 private int getUidTargetSdkVersionLockedLPr(int uid) { 10085 Object obj = mSettings.getUserIdLPr(uid); 10086 if (obj instanceof SharedUserSetting) { 10087 final SharedUserSetting sus = (SharedUserSetting) obj; 10088 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 10089 final Iterator<PackageSetting> it = sus.packages.iterator(); 10090 while (it.hasNext()) { 10091 final PackageSetting ps = it.next(); 10092 if (ps.pkg != null) { 10093 int v = ps.pkg.applicationInfo.targetSdkVersion; 10094 if (v < vers) vers = v; 10095 } 10096 } 10097 return vers; 10098 } else if (obj instanceof PackageSetting) { 10099 final PackageSetting ps = (PackageSetting) obj; 10100 if (ps.pkg != null) { 10101 return ps.pkg.applicationInfo.targetSdkVersion; 10102 } 10103 } 10104 return Build.VERSION_CODES.CUR_DEVELOPMENT; 10105 } 10106 10107 public void addPreferredActivity(IntentFilter filter, int match, 10108 ComponentName[] set, ComponentName activity, int userId) { 10109 addPreferredActivityInternal(filter, match, set, activity, true, userId); 10110 } 10111 10112 private void addPreferredActivityInternal(IntentFilter filter, int match, 10113 ComponentName[] set, ComponentName activity, boolean always, int userId) { 10114 // writer 10115 int callingUid = Binder.getCallingUid(); 10116 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 10117 if (filter.countActions() == 0) { 10118 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 10119 return; 10120 } 10121 synchronized (mPackages) { 10122 if (mContext.checkCallingOrSelfPermission( 10123 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10124 != PackageManager.PERMISSION_GRANTED) { 10125 if (getUidTargetSdkVersionLockedLPr(callingUid) 10126 < Build.VERSION_CODES.FROYO) { 10127 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 10128 + callingUid); 10129 return; 10130 } 10131 mContext.enforceCallingOrSelfPermission( 10132 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10133 } 10134 10135 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 10136 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10137 mSettings.editPreferredActivitiesLPw(userId).addFilter( 10138 new PreferredActivity(filter, match, set, activity, always)); 10139 mSettings.writePackageRestrictionsLPr(userId); 10140 } 10141 } 10142 10143 public void replacePreferredActivity(IntentFilter filter, int match, 10144 ComponentName[] set, ComponentName activity) { 10145 if (filter.countActions() != 1) { 10146 throw new IllegalArgumentException( 10147 "replacePreferredActivity expects filter to have only 1 action."); 10148 } 10149 if (filter.countDataAuthorities() != 0 10150 || filter.countDataPaths() != 0 10151 || filter.countDataSchemes() > 1 10152 || filter.countDataTypes() != 0) { 10153 throw new IllegalArgumentException( 10154 "replacePreferredActivity expects filter to have no data authorities, " + 10155 "paths, or types; and at most one scheme."); 10156 } 10157 synchronized (mPackages) { 10158 if (mContext.checkCallingOrSelfPermission( 10159 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10160 != PackageManager.PERMISSION_GRANTED) { 10161 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 10162 < Build.VERSION_CODES.FROYO) { 10163 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 10164 + Binder.getCallingUid()); 10165 return; 10166 } 10167 mContext.enforceCallingOrSelfPermission( 10168 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10169 } 10170 10171 final int callingUserId = UserHandle.getCallingUserId(); 10172 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 10173 if (pir != null) { 10174 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 10175 if (filter.countDataSchemes() == 1) { 10176 Uri.Builder builder = new Uri.Builder(); 10177 builder.scheme(filter.getDataScheme(0)); 10178 intent.setData(builder.build()); 10179 } 10180 List<PreferredActivity> matches = pir.queryIntent( 10181 intent, null, true, callingUserId); 10182 if (DEBUG_PREFERRED) { 10183 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 10184 } 10185 for (int i = 0; i < matches.size(); i++) { 10186 PreferredActivity pa = matches.get(i); 10187 if (DEBUG_PREFERRED) { 10188 Slog.i(TAG, "Removing preferred activity " 10189 + pa.mPref.mComponent + ":"); 10190 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10191 } 10192 pir.removeFilter(pa); 10193 } 10194 } 10195 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 10196 } 10197 } 10198 10199 public void clearPackagePreferredActivities(String packageName) { 10200 final int uid = Binder.getCallingUid(); 10201 // writer 10202 synchronized (mPackages) { 10203 PackageParser.Package pkg = mPackages.get(packageName); 10204 if (pkg == null || pkg.applicationInfo.uid != uid) { 10205 if (mContext.checkCallingOrSelfPermission( 10206 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10207 != PackageManager.PERMISSION_GRANTED) { 10208 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 10209 < Build.VERSION_CODES.FROYO) { 10210 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 10211 + Binder.getCallingUid()); 10212 return; 10213 } 10214 mContext.enforceCallingOrSelfPermission( 10215 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10216 } 10217 } 10218 10219 int user = UserHandle.getCallingUserId(); 10220 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 10221 mSettings.writePackageRestrictionsLPr(user); 10222 scheduleWriteSettingsLocked(); 10223 } 10224 } 10225 } 10226 10227 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 10228 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 10229 ArrayList<PreferredActivity> removed = null; 10230 boolean changed = false; 10231 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 10232 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 10233 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 10234 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 10235 continue; 10236 } 10237 Iterator<PreferredActivity> it = pir.filterIterator(); 10238 while (it.hasNext()) { 10239 PreferredActivity pa = it.next(); 10240 // Mark entry for removal only if it matches the package name 10241 // and the entry is of type "always". 10242 if (packageName == null || 10243 (pa.mPref.mComponent.getPackageName().equals(packageName) 10244 && pa.mPref.mAlways)) { 10245 if (removed == null) { 10246 removed = new ArrayList<PreferredActivity>(); 10247 } 10248 removed.add(pa); 10249 } 10250 } 10251 if (removed != null) { 10252 for (int j=0; j<removed.size(); j++) { 10253 PreferredActivity pa = removed.get(j); 10254 pir.removeFilter(pa); 10255 } 10256 changed = true; 10257 } 10258 } 10259 return changed; 10260 } 10261 10262 public void resetPreferredActivities(int userId) { 10263 mContext.enforceCallingOrSelfPermission( 10264 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10265 // writer 10266 synchronized (mPackages) { 10267 int user = UserHandle.getCallingUserId(); 10268 clearPackagePreferredActivitiesLPw(null, user); 10269 mSettings.readDefaultPreferredAppsLPw(this, user); 10270 mSettings.writePackageRestrictionsLPr(user); 10271 scheduleWriteSettingsLocked(); 10272 } 10273 } 10274 10275 public int getPreferredActivities(List<IntentFilter> outFilters, 10276 List<ComponentName> outActivities, String packageName) { 10277 10278 int num = 0; 10279 final int userId = UserHandle.getCallingUserId(); 10280 // reader 10281 synchronized (mPackages) { 10282 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 10283 if (pir != null) { 10284 final Iterator<PreferredActivity> it = pir.filterIterator(); 10285 while (it.hasNext()) { 10286 final PreferredActivity pa = it.next(); 10287 if (packageName == null 10288 || (pa.mPref.mComponent.getPackageName().equals(packageName) 10289 && pa.mPref.mAlways)) { 10290 if (outFilters != null) { 10291 outFilters.add(new IntentFilter(pa)); 10292 } 10293 if (outActivities != null) { 10294 outActivities.add(pa.mPref.mComponent); 10295 } 10296 } 10297 } 10298 } 10299 } 10300 10301 return num; 10302 } 10303 10304 @Override 10305 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 10306 Intent intent = new Intent(Intent.ACTION_MAIN); 10307 intent.addCategory(Intent.CATEGORY_HOME); 10308 10309 final int callingUserId = UserHandle.getCallingUserId(); 10310 List<ResolveInfo> list = queryIntentActivities(intent, null, 10311 PackageManager.GET_META_DATA, callingUserId); 10312 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 10313 true, false, false, callingUserId); 10314 10315 allHomeCandidates.clear(); 10316 if (list != null) { 10317 for (ResolveInfo ri : list) { 10318 allHomeCandidates.add(ri); 10319 } 10320 } 10321 return (preferred == null || preferred.activityInfo == null) 10322 ? null 10323 : new ComponentName(preferred.activityInfo.packageName, 10324 preferred.activityInfo.name); 10325 } 10326 10327 @Override 10328 public void setApplicationEnabledSetting(String appPackageName, 10329 int newState, int flags, int userId, String callingPackage) { 10330 if (!sUserManager.exists(userId)) return; 10331 if (callingPackage == null) { 10332 callingPackage = Integer.toString(Binder.getCallingUid()); 10333 } 10334 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 10335 } 10336 10337 @Override 10338 public void setComponentEnabledSetting(ComponentName componentName, 10339 int newState, int flags, int userId) { 10340 if (!sUserManager.exists(userId)) return; 10341 setEnabledSetting(componentName.getPackageName(), 10342 componentName.getClassName(), newState, flags, userId, null); 10343 } 10344 10345 private void setEnabledSetting(final String packageName, String className, int newState, 10346 final int flags, int userId, String callingPackage) { 10347 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 10348 || newState == COMPONENT_ENABLED_STATE_ENABLED 10349 || newState == COMPONENT_ENABLED_STATE_DISABLED 10350 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 10351 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 10352 throw new IllegalArgumentException("Invalid new component state: " 10353 + newState); 10354 } 10355 PackageSetting pkgSetting; 10356 final int uid = Binder.getCallingUid(); 10357 final int permission = mContext.checkCallingOrSelfPermission( 10358 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 10359 enforceCrossUserPermission(uid, userId, false, "set enabled"); 10360 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 10361 boolean sendNow = false; 10362 boolean isApp = (className == null); 10363 String componentName = isApp ? packageName : className; 10364 int packageUid = -1; 10365 ArrayList<String> components; 10366 10367 // writer 10368 synchronized (mPackages) { 10369 pkgSetting = mSettings.mPackages.get(packageName); 10370 if (pkgSetting == null) { 10371 if (className == null) { 10372 throw new IllegalArgumentException( 10373 "Unknown package: " + packageName); 10374 } 10375 throw new IllegalArgumentException( 10376 "Unknown component: " + packageName 10377 + "/" + className); 10378 } 10379 // Allow root and verify that userId is not being specified by a different user 10380 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 10381 throw new SecurityException( 10382 "Permission Denial: attempt to change component state from pid=" 10383 + Binder.getCallingPid() 10384 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 10385 } 10386 if (className == null) { 10387 // We're dealing with an application/package level state change 10388 if (pkgSetting.getEnabled(userId) == newState) { 10389 // Nothing to do 10390 return; 10391 } 10392 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 10393 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 10394 // Don't care about who enables an app. 10395 callingPackage = null; 10396 } 10397 pkgSetting.setEnabled(newState, userId, callingPackage); 10398 // pkgSetting.pkg.mSetEnabled = newState; 10399 } else { 10400 // We're dealing with a component level state change 10401 // First, verify that this is a valid class name. 10402 PackageParser.Package pkg = pkgSetting.pkg; 10403 if (pkg == null || !pkg.hasComponentClassName(className)) { 10404 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 10405 throw new IllegalArgumentException("Component class " + className 10406 + " does not exist in " + packageName); 10407 } else { 10408 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 10409 + className + " does not exist in " + packageName); 10410 } 10411 } 10412 switch (newState) { 10413 case COMPONENT_ENABLED_STATE_ENABLED: 10414 if (!pkgSetting.enableComponentLPw(className, userId)) { 10415 return; 10416 } 10417 break; 10418 case COMPONENT_ENABLED_STATE_DISABLED: 10419 if (!pkgSetting.disableComponentLPw(className, userId)) { 10420 return; 10421 } 10422 break; 10423 case COMPONENT_ENABLED_STATE_DEFAULT: 10424 if (!pkgSetting.restoreComponentLPw(className, userId)) { 10425 return; 10426 } 10427 break; 10428 default: 10429 Slog.e(TAG, "Invalid new component state: " + newState); 10430 return; 10431 } 10432 } 10433 mSettings.writePackageRestrictionsLPr(userId); 10434 components = mPendingBroadcasts.get(userId, packageName); 10435 final boolean newPackage = components == null; 10436 if (newPackage) { 10437 components = new ArrayList<String>(); 10438 } 10439 if (!components.contains(componentName)) { 10440 components.add(componentName); 10441 } 10442 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 10443 sendNow = true; 10444 // Purge entry from pending broadcast list if another one exists already 10445 // since we are sending one right away. 10446 mPendingBroadcasts.remove(userId, packageName); 10447 } else { 10448 if (newPackage) { 10449 mPendingBroadcasts.put(userId, packageName, components); 10450 } 10451 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 10452 // Schedule a message 10453 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 10454 } 10455 } 10456 } 10457 10458 long callingId = Binder.clearCallingIdentity(); 10459 try { 10460 if (sendNow) { 10461 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 10462 sendPackageChangedBroadcast(packageName, 10463 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 10464 } 10465 } finally { 10466 Binder.restoreCallingIdentity(callingId); 10467 } 10468 } 10469 10470 private void sendPackageChangedBroadcast(String packageName, 10471 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 10472 if (DEBUG_INSTALL) 10473 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 10474 + componentNames); 10475 Bundle extras = new Bundle(4); 10476 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 10477 String nameList[] = new String[componentNames.size()]; 10478 componentNames.toArray(nameList); 10479 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 10480 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 10481 extras.putInt(Intent.EXTRA_UID, packageUid); 10482 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 10483 new int[] {UserHandle.getUserId(packageUid)}); 10484 } 10485 10486 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 10487 if (!sUserManager.exists(userId)) return; 10488 final int uid = Binder.getCallingUid(); 10489 final int permission = mContext.checkCallingOrSelfPermission( 10490 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 10491 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 10492 enforceCrossUserPermission(uid, userId, true, "stop package"); 10493 // writer 10494 synchronized (mPackages) { 10495 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 10496 uid, userId)) { 10497 scheduleWritePackageRestrictionsLocked(userId); 10498 } 10499 } 10500 } 10501 10502 public String getInstallerPackageName(String packageName) { 10503 // reader 10504 synchronized (mPackages) { 10505 return mSettings.getInstallerPackageNameLPr(packageName); 10506 } 10507 } 10508 10509 @Override 10510 public int getApplicationEnabledSetting(String packageName, int userId) { 10511 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 10512 int uid = Binder.getCallingUid(); 10513 enforceCrossUserPermission(uid, userId, false, "get enabled"); 10514 // reader 10515 synchronized (mPackages) { 10516 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 10517 } 10518 } 10519 10520 @Override 10521 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 10522 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 10523 int uid = Binder.getCallingUid(); 10524 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 10525 // reader 10526 synchronized (mPackages) { 10527 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 10528 } 10529 } 10530 10531 public void enterSafeMode() { 10532 enforceSystemOrRoot("Only the system can request entering safe mode"); 10533 10534 if (!mSystemReady) { 10535 mSafeMode = true; 10536 } 10537 } 10538 10539 public void systemReady() { 10540 mSystemReady = true; 10541 10542 // Read the compatibilty setting when the system is ready. 10543 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 10544 mContext.getContentResolver(), 10545 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 10546 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 10547 if (DEBUG_SETTINGS) { 10548 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 10549 } 10550 10551 synchronized (mPackages) { 10552 // Verify that all of the preferred activity components actually 10553 // exist. It is possible for applications to be updated and at 10554 // that point remove a previously declared activity component that 10555 // had been set as a preferred activity. We try to clean this up 10556 // the next time we encounter that preferred activity, but it is 10557 // possible for the user flow to never be able to return to that 10558 // situation so here we do a sanity check to make sure we haven't 10559 // left any junk around. 10560 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 10561 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 10562 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 10563 removed.clear(); 10564 for (PreferredActivity pa : pir.filterSet()) { 10565 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 10566 removed.add(pa); 10567 } 10568 } 10569 if (removed.size() > 0) { 10570 for (int j=0; j<removed.size(); j++) { 10571 PreferredActivity pa = removed.get(i); 10572 Slog.w(TAG, "Removing dangling preferred activity: " 10573 + pa.mPref.mComponent); 10574 pir.removeFilter(pa); 10575 } 10576 mSettings.writePackageRestrictionsLPr( 10577 mSettings.mPreferredActivities.keyAt(i)); 10578 } 10579 } 10580 } 10581 sUserManager.systemReady(); 10582 } 10583 10584 public boolean isSafeMode() { 10585 return mSafeMode; 10586 } 10587 10588 public boolean hasSystemUidErrors() { 10589 return mHasSystemUidErrors; 10590 } 10591 10592 static String arrayToString(int[] array) { 10593 StringBuffer buf = new StringBuffer(128); 10594 buf.append('['); 10595 if (array != null) { 10596 for (int i=0; i<array.length; i++) { 10597 if (i > 0) buf.append(", "); 10598 buf.append(array[i]); 10599 } 10600 } 10601 buf.append(']'); 10602 return buf.toString(); 10603 } 10604 10605 static class DumpState { 10606 public static final int DUMP_LIBS = 1 << 0; 10607 10608 public static final int DUMP_FEATURES = 1 << 1; 10609 10610 public static final int DUMP_RESOLVERS = 1 << 2; 10611 10612 public static final int DUMP_PERMISSIONS = 1 << 3; 10613 10614 public static final int DUMP_PACKAGES = 1 << 4; 10615 10616 public static final int DUMP_SHARED_USERS = 1 << 5; 10617 10618 public static final int DUMP_MESSAGES = 1 << 6; 10619 10620 public static final int DUMP_PROVIDERS = 1 << 7; 10621 10622 public static final int DUMP_VERIFIERS = 1 << 8; 10623 10624 public static final int DUMP_PREFERRED = 1 << 9; 10625 10626 public static final int DUMP_PREFERRED_XML = 1 << 10; 10627 10628 public static final int DUMP_KEYSETS = 1 << 11; 10629 10630 public static final int OPTION_SHOW_FILTERS = 1 << 0; 10631 10632 private int mTypes; 10633 10634 private int mOptions; 10635 10636 private boolean mTitlePrinted; 10637 10638 private SharedUserSetting mSharedUser; 10639 10640 public boolean isDumping(int type) { 10641 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 10642 return true; 10643 } 10644 10645 return (mTypes & type) != 0; 10646 } 10647 10648 public void setDump(int type) { 10649 mTypes |= type; 10650 } 10651 10652 public boolean isOptionEnabled(int option) { 10653 return (mOptions & option) != 0; 10654 } 10655 10656 public void setOptionEnabled(int option) { 10657 mOptions |= option; 10658 } 10659 10660 public boolean onTitlePrinted() { 10661 final boolean printed = mTitlePrinted; 10662 mTitlePrinted = true; 10663 return printed; 10664 } 10665 10666 public boolean getTitlePrinted() { 10667 return mTitlePrinted; 10668 } 10669 10670 public void setTitlePrinted(boolean enabled) { 10671 mTitlePrinted = enabled; 10672 } 10673 10674 public SharedUserSetting getSharedUser() { 10675 return mSharedUser; 10676 } 10677 10678 public void setSharedUser(SharedUserSetting user) { 10679 mSharedUser = user; 10680 } 10681 } 10682 10683 @Override 10684 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 10685 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 10686 != PackageManager.PERMISSION_GRANTED) { 10687 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 10688 + Binder.getCallingPid() 10689 + ", uid=" + Binder.getCallingUid() 10690 + " without permission " 10691 + android.Manifest.permission.DUMP); 10692 return; 10693 } 10694 10695 DumpState dumpState = new DumpState(); 10696 boolean fullPreferred = false; 10697 10698 String packageName = null; 10699 10700 int opti = 0; 10701 while (opti < args.length) { 10702 String opt = args[opti]; 10703 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 10704 break; 10705 } 10706 opti++; 10707 if ("-a".equals(opt)) { 10708 // Right now we only know how to print all. 10709 } else if ("-h".equals(opt)) { 10710 pw.println("Package manager dump options:"); 10711 pw.println(" [-h] [-f] [cmd] ..."); 10712 pw.println(" -f: print details of intent filters"); 10713 pw.println(" -h: print this help"); 10714 pw.println(" cmd may be one of:"); 10715 pw.println(" l[ibraries]: list known shared libraries"); 10716 pw.println(" f[ibraries]: list device features"); 10717 pw.println(" r[esolvers]: dump intent resolvers"); 10718 pw.println(" perm[issions]: dump permissions"); 10719 pw.println(" pref[erred]: print preferred package settings"); 10720 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 10721 pw.println(" prov[iders]: dump content providers"); 10722 pw.println(" p[ackages]: dump installed packages"); 10723 pw.println(" s[hared-users]: dump shared user IDs"); 10724 pw.println(" m[essages]: print collected runtime messages"); 10725 pw.println(" v[erifiers]: print package verifier info"); 10726 pw.println(" <package.name>: info about given package"); 10727 pw.println(" k[eysets]: print known keysets"); 10728 return; 10729 } else if ("-f".equals(opt)) { 10730 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 10731 } else { 10732 pw.println("Unknown argument: " + opt + "; use -h for help"); 10733 } 10734 } 10735 10736 // Is the caller requesting to dump a particular piece of data? 10737 if (opti < args.length) { 10738 String cmd = args[opti]; 10739 opti++; 10740 // Is this a package name? 10741 if ("android".equals(cmd) || cmd.contains(".")) { 10742 packageName = cmd; 10743 // When dumping a single package, we always dump all of its 10744 // filter information since the amount of data will be reasonable. 10745 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 10746 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 10747 dumpState.setDump(DumpState.DUMP_LIBS); 10748 } else if ("f".equals(cmd) || "features".equals(cmd)) { 10749 dumpState.setDump(DumpState.DUMP_FEATURES); 10750 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 10751 dumpState.setDump(DumpState.DUMP_RESOLVERS); 10752 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 10753 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 10754 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 10755 dumpState.setDump(DumpState.DUMP_PREFERRED); 10756 } else if ("preferred-xml".equals(cmd)) { 10757 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 10758 if (opti < args.length && "--full".equals(args[opti])) { 10759 fullPreferred = true; 10760 opti++; 10761 } 10762 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 10763 dumpState.setDump(DumpState.DUMP_PACKAGES); 10764 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 10765 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 10766 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 10767 dumpState.setDump(DumpState.DUMP_PROVIDERS); 10768 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 10769 dumpState.setDump(DumpState.DUMP_MESSAGES); 10770 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 10771 dumpState.setDump(DumpState.DUMP_VERIFIERS); 10772 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 10773 dumpState.setDump(DumpState.DUMP_KEYSETS); 10774 } 10775 } 10776 10777 // reader 10778 synchronized (mPackages) { 10779 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 10780 if (dumpState.onTitlePrinted()) 10781 pw.println(); 10782 pw.println("Verifiers:"); 10783 pw.print(" Required: "); 10784 pw.print(mRequiredVerifierPackage); 10785 pw.print(" (uid="); 10786 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 10787 pw.println(")"); 10788 } 10789 10790 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 10791 boolean printedHeader = false; 10792 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 10793 while (it.hasNext()) { 10794 String name = it.next(); 10795 SharedLibraryEntry ent = mSharedLibraries.get(name); 10796 if (!printedHeader) { 10797 if (dumpState.onTitlePrinted()) 10798 pw.println(); 10799 pw.println("Libraries:"); 10800 printedHeader = true; 10801 } 10802 pw.print(" "); 10803 pw.print(name); 10804 pw.print(" -> "); 10805 if (ent.path != null) { 10806 pw.print("(jar) "); 10807 pw.print(ent.path); 10808 } else { 10809 pw.print("(apk) "); 10810 pw.print(ent.apk); 10811 } 10812 pw.println(); 10813 } 10814 } 10815 10816 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 10817 if (dumpState.onTitlePrinted()) 10818 pw.println(); 10819 pw.println("Features:"); 10820 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 10821 while (it.hasNext()) { 10822 String name = it.next(); 10823 pw.print(" "); 10824 pw.println(name); 10825 } 10826 } 10827 10828 if (dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 10829 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 10830 : "Activity Resolver Table:", " ", packageName, 10831 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 10832 dumpState.setTitlePrinted(true); 10833 } 10834 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 10835 : "Receiver Resolver Table:", " ", packageName, 10836 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 10837 dumpState.setTitlePrinted(true); 10838 } 10839 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 10840 : "Service Resolver Table:", " ", packageName, 10841 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 10842 dumpState.setTitlePrinted(true); 10843 } 10844 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 10845 : "Provider Resolver Table:", " ", packageName, 10846 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 10847 dumpState.setTitlePrinted(true); 10848 } 10849 } 10850 10851 if (dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 10852 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 10853 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 10854 int user = mSettings.mPreferredActivities.keyAt(i); 10855 if (pir.dump(pw, 10856 dumpState.getTitlePrinted() 10857 ? "\nPreferred Activities User " + user + ":" 10858 : "Preferred Activities User " + user + ":", " ", 10859 packageName, true)) { 10860 dumpState.setTitlePrinted(true); 10861 } 10862 } 10863 } 10864 10865 if (dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 10866 pw.flush(); 10867 FileOutputStream fout = new FileOutputStream(fd); 10868 BufferedOutputStream str = new BufferedOutputStream(fout); 10869 XmlSerializer serializer = new FastXmlSerializer(); 10870 try { 10871 serializer.setOutput(str, "utf-8"); 10872 serializer.startDocument(null, true); 10873 serializer.setFeature( 10874 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 10875 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 10876 serializer.endDocument(); 10877 serializer.flush(); 10878 } catch (IllegalArgumentException e) { 10879 pw.println("Failed writing: " + e); 10880 } catch (IllegalStateException e) { 10881 pw.println("Failed writing: " + e); 10882 } catch (IOException e) { 10883 pw.println("Failed writing: " + e); 10884 } 10885 } 10886 10887 if (dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 10888 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 10889 } 10890 10891 if (dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 10892 boolean printedSomething = false; 10893 for (PackageParser.Provider p : mProviders.mProviders.values()) { 10894 if (packageName != null && !packageName.equals(p.info.packageName)) { 10895 continue; 10896 } 10897 if (!printedSomething) { 10898 if (dumpState.onTitlePrinted()) 10899 pw.println(); 10900 pw.println("Registered ContentProviders:"); 10901 printedSomething = true; 10902 } 10903 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 10904 pw.print(" "); pw.println(p.toString()); 10905 } 10906 printedSomething = false; 10907 for (Map.Entry<String, PackageParser.Provider> entry : 10908 mProvidersByAuthority.entrySet()) { 10909 PackageParser.Provider p = entry.getValue(); 10910 if (packageName != null && !packageName.equals(p.info.packageName)) { 10911 continue; 10912 } 10913 if (!printedSomething) { 10914 if (dumpState.onTitlePrinted()) 10915 pw.println(); 10916 pw.println("ContentProvider Authorities:"); 10917 printedSomething = true; 10918 } 10919 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 10920 pw.print(" "); pw.println(p.toString()); 10921 if (p.info != null && p.info.applicationInfo != null) { 10922 final String appInfo = p.info.applicationInfo.toString(); 10923 pw.print(" applicationInfo="); pw.println(appInfo); 10924 } 10925 } 10926 } 10927 10928 if (dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 10929 mSettings.mKeySetManager.dump(pw, packageName, dumpState); 10930 } 10931 10932 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 10933 mSettings.dumpPackagesLPr(pw, packageName, dumpState); 10934 } 10935 10936 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 10937 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 10938 } 10939 10940 if (dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 10941 if (dumpState.onTitlePrinted()) 10942 pw.println(); 10943 mSettings.dumpReadMessagesLPr(pw, dumpState); 10944 10945 pw.println(); 10946 pw.println("Package warning messages:"); 10947 final File fname = getSettingsProblemFile(); 10948 FileInputStream in = null; 10949 try { 10950 in = new FileInputStream(fname); 10951 final int avail = in.available(); 10952 final byte[] data = new byte[avail]; 10953 in.read(data); 10954 pw.print(new String(data)); 10955 } catch (FileNotFoundException e) { 10956 } catch (IOException e) { 10957 } finally { 10958 if (in != null) { 10959 try { 10960 in.close(); 10961 } catch (IOException e) { 10962 } 10963 } 10964 } 10965 } 10966 } 10967 } 10968 10969 // ------- apps on sdcard specific code ------- 10970 static final boolean DEBUG_SD_INSTALL = false; 10971 10972 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 10973 10974 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 10975 10976 private boolean mMediaMounted = false; 10977 10978 private String getEncryptKey() { 10979 try { 10980 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 10981 SD_ENCRYPTION_KEYSTORE_NAME); 10982 if (sdEncKey == null) { 10983 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 10984 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 10985 if (sdEncKey == null) { 10986 Slog.e(TAG, "Failed to create encryption keys"); 10987 return null; 10988 } 10989 } 10990 return sdEncKey; 10991 } catch (NoSuchAlgorithmException nsae) { 10992 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 10993 return null; 10994 } catch (IOException ioe) { 10995 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 10996 return null; 10997 } 10998 10999 } 11000 11001 /* package */static String getTempContainerId() { 11002 int tmpIdx = 1; 11003 String list[] = PackageHelper.getSecureContainerList(); 11004 if (list != null) { 11005 for (final String name : list) { 11006 // Ignore null and non-temporary container entries 11007 if (name == null || !name.startsWith(mTempContainerPrefix)) { 11008 continue; 11009 } 11010 11011 String subStr = name.substring(mTempContainerPrefix.length()); 11012 try { 11013 int cid = Integer.parseInt(subStr); 11014 if (cid >= tmpIdx) { 11015 tmpIdx = cid + 1; 11016 } 11017 } catch (NumberFormatException e) { 11018 } 11019 } 11020 } 11021 return mTempContainerPrefix + tmpIdx; 11022 } 11023 11024 /* 11025 * Update media status on PackageManager. 11026 */ 11027 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 11028 int callingUid = Binder.getCallingUid(); 11029 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 11030 throw new SecurityException("Media status can only be updated by the system"); 11031 } 11032 // reader; this apparently protects mMediaMounted, but should probably 11033 // be a different lock in that case. 11034 synchronized (mPackages) { 11035 Log.i(TAG, "Updating external media status from " 11036 + (mMediaMounted ? "mounted" : "unmounted") + " to " 11037 + (mediaStatus ? "mounted" : "unmounted")); 11038 if (DEBUG_SD_INSTALL) 11039 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 11040 + ", mMediaMounted=" + mMediaMounted); 11041 if (mediaStatus == mMediaMounted) { 11042 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 11043 : 0, -1); 11044 mHandler.sendMessage(msg); 11045 return; 11046 } 11047 mMediaMounted = mediaStatus; 11048 } 11049 // Queue up an async operation since the package installation may take a 11050 // little while. 11051 mHandler.post(new Runnable() { 11052 public void run() { 11053 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 11054 } 11055 }); 11056 } 11057 11058 /** 11059 * Called by MountService when the initial ASECs to scan are available. 11060 * Should block until all the ASEC containers are finished being scanned. 11061 */ 11062 public void scanAvailableAsecs() { 11063 updateExternalMediaStatusInner(true, false, false); 11064 } 11065 11066 /* 11067 * Collect information of applications on external media, map them against 11068 * existing containers and update information based on current mount status. 11069 * Please note that we always have to report status if reportStatus has been 11070 * set to true especially when unloading packages. 11071 */ 11072 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 11073 boolean externalStorage) { 11074 // Collection of uids 11075 int uidArr[] = null; 11076 // Collection of stale containers 11077 HashSet<String> removeCids = new HashSet<String>(); 11078 // Collection of packages on external media with valid containers. 11079 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 11080 // Get list of secure containers. 11081 final String list[] = PackageHelper.getSecureContainerList(); 11082 if (list == null || list.length == 0) { 11083 Log.i(TAG, "No secure containers on sdcard"); 11084 } else { 11085 // Process list of secure containers and categorize them 11086 // as active or stale based on their package internal state. 11087 int uidList[] = new int[list.length]; 11088 int num = 0; 11089 // reader 11090 synchronized (mPackages) { 11091 for (String cid : list) { 11092 if (DEBUG_SD_INSTALL) 11093 Log.i(TAG, "Processing container " + cid); 11094 String pkgName = getAsecPackageName(cid); 11095 if (pkgName == null) { 11096 if (DEBUG_SD_INSTALL) 11097 Log.i(TAG, "Container : " + cid + " stale"); 11098 removeCids.add(cid); 11099 continue; 11100 } 11101 if (DEBUG_SD_INSTALL) 11102 Log.i(TAG, "Looking for pkg : " + pkgName); 11103 11104 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11105 if (ps == null) { 11106 Log.i(TAG, "Deleting container with no matching settings " + cid); 11107 removeCids.add(cid); 11108 continue; 11109 } 11110 11111 /* 11112 * Skip packages that are not external if we're unmounting 11113 * external storage. 11114 */ 11115 if (externalStorage && !isMounted && !isExternal(ps)) { 11116 continue; 11117 } 11118 11119 final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps)); 11120 // The package status is changed only if the code path 11121 // matches between settings and the container id. 11122 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 11123 if (DEBUG_SD_INSTALL) { 11124 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 11125 + " at code path: " + ps.codePathString); 11126 } 11127 11128 // We do have a valid package installed on sdcard 11129 processCids.put(args, ps.codePathString); 11130 final int uid = ps.appId; 11131 if (uid != -1) { 11132 uidList[num++] = uid; 11133 } 11134 } else { 11135 Log.i(TAG, "Deleting stale container for " + cid); 11136 removeCids.add(cid); 11137 } 11138 } 11139 } 11140 11141 if (num > 0) { 11142 // Sort uid list 11143 Arrays.sort(uidList, 0, num); 11144 // Throw away duplicates 11145 uidArr = new int[num]; 11146 uidArr[0] = uidList[0]; 11147 int di = 0; 11148 for (int i = 1; i < num; i++) { 11149 if (uidList[i - 1] != uidList[i]) { 11150 uidArr[di++] = uidList[i]; 11151 } 11152 } 11153 } 11154 } 11155 // Process packages with valid entries. 11156 if (isMounted) { 11157 if (DEBUG_SD_INSTALL) 11158 Log.i(TAG, "Loading packages"); 11159 loadMediaPackages(processCids, uidArr, removeCids); 11160 startCleaningPackages(); 11161 } else { 11162 if (DEBUG_SD_INSTALL) 11163 Log.i(TAG, "Unloading packages"); 11164 unloadMediaPackages(processCids, uidArr, reportStatus); 11165 } 11166 } 11167 11168 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 11169 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 11170 int size = pkgList.size(); 11171 if (size > 0) { 11172 // Send broadcasts here 11173 Bundle extras = new Bundle(); 11174 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 11175 .toArray(new String[size])); 11176 if (uidArr != null) { 11177 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 11178 } 11179 if (replacing && !mediaStatus) { 11180 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 11181 } 11182 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 11183 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 11184 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 11185 } 11186 } 11187 11188 /* 11189 * Look at potentially valid container ids from processCids If package 11190 * information doesn't match the one on record or package scanning fails, 11191 * the cid is added to list of removeCids. We currently don't delete stale 11192 * containers. 11193 */ 11194 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 11195 HashSet<String> removeCids) { 11196 ArrayList<String> pkgList = new ArrayList<String>(); 11197 Set<AsecInstallArgs> keys = processCids.keySet(); 11198 boolean doGc = false; 11199 for (AsecInstallArgs args : keys) { 11200 String codePath = processCids.get(args); 11201 if (DEBUG_SD_INSTALL) 11202 Log.i(TAG, "Loading container : " + args.cid); 11203 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11204 try { 11205 // Make sure there are no container errors first. 11206 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 11207 Slog.e(TAG, "Failed to mount cid : " + args.cid 11208 + " when installing from sdcard"); 11209 continue; 11210 } 11211 // Check code path here. 11212 if (codePath == null || !codePath.equals(args.getCodePath())) { 11213 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 11214 + " does not match one in settings " + codePath); 11215 continue; 11216 } 11217 // Parse package 11218 int parseFlags = mDefParseFlags; 11219 if (args.isExternal()) { 11220 parseFlags |= PackageParser.PARSE_ON_SDCARD; 11221 } 11222 if (args.isFwdLocked()) { 11223 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 11224 } 11225 11226 doGc = true; 11227 synchronized (mInstallLock) { 11228 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 11229 0, 0, null); 11230 // Scan the package 11231 if (pkg != null) { 11232 /* 11233 * TODO why is the lock being held? doPostInstall is 11234 * called in other places without the lock. This needs 11235 * to be straightened out. 11236 */ 11237 // writer 11238 synchronized (mPackages) { 11239 retCode = PackageManager.INSTALL_SUCCEEDED; 11240 pkgList.add(pkg.packageName); 11241 // Post process args 11242 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 11243 pkg.applicationInfo.uid); 11244 } 11245 } else { 11246 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 11247 } 11248 } 11249 11250 } finally { 11251 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 11252 // Don't destroy container here. Wait till gc clears things 11253 // up. 11254 removeCids.add(args.cid); 11255 } 11256 } 11257 } 11258 // writer 11259 synchronized (mPackages) { 11260 // If the platform SDK has changed since the last time we booted, 11261 // we need to re-grant app permission to catch any new ones that 11262 // appear. This is really a hack, and means that apps can in some 11263 // cases get permissions that the user didn't initially explicitly 11264 // allow... it would be nice to have some better way to handle 11265 // this situation. 11266 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 11267 if (regrantPermissions) 11268 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 11269 + mSdkVersion + "; regranting permissions for external storage"); 11270 mSettings.mExternalSdkPlatform = mSdkVersion; 11271 11272 // Make sure group IDs have been assigned, and any permission 11273 // changes in other apps are accounted for 11274 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 11275 | (regrantPermissions 11276 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 11277 : 0)); 11278 // can downgrade to reader 11279 // Persist settings 11280 mSettings.writeLPr(); 11281 } 11282 // Send a broadcast to let everyone know we are done processing 11283 if (pkgList.size() > 0) { 11284 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 11285 } 11286 // Force gc to avoid any stale parser references that we might have. 11287 if (doGc) { 11288 Runtime.getRuntime().gc(); 11289 } 11290 // List stale containers and destroy stale temporary containers. 11291 if (removeCids != null) { 11292 for (String cid : removeCids) { 11293 if (cid.startsWith(mTempContainerPrefix)) { 11294 Log.i(TAG, "Destroying stale temporary container " + cid); 11295 PackageHelper.destroySdDir(cid); 11296 } else { 11297 Log.w(TAG, "Container " + cid + " is stale"); 11298 } 11299 } 11300 } 11301 } 11302 11303 /* 11304 * Utility method to unload a list of specified containers 11305 */ 11306 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 11307 // Just unmount all valid containers. 11308 for (AsecInstallArgs arg : cidArgs) { 11309 synchronized (mInstallLock) { 11310 arg.doPostDeleteLI(false); 11311 } 11312 } 11313 } 11314 11315 /* 11316 * Unload packages mounted on external media. This involves deleting package 11317 * data from internal structures, sending broadcasts about diabled packages, 11318 * gc'ing to free up references, unmounting all secure containers 11319 * corresponding to packages on external media, and posting a 11320 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 11321 * that we always have to post this message if status has been requested no 11322 * matter what. 11323 */ 11324 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 11325 final boolean reportStatus) { 11326 if (DEBUG_SD_INSTALL) 11327 Log.i(TAG, "unloading media packages"); 11328 ArrayList<String> pkgList = new ArrayList<String>(); 11329 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 11330 final Set<AsecInstallArgs> keys = processCids.keySet(); 11331 for (AsecInstallArgs args : keys) { 11332 String pkgName = args.getPackageName(); 11333 if (DEBUG_SD_INSTALL) 11334 Log.i(TAG, "Trying to unload pkg : " + pkgName); 11335 // Delete package internally 11336 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 11337 synchronized (mInstallLock) { 11338 boolean res = deletePackageLI(pkgName, null, false, null, null, 11339 PackageManager.DELETE_KEEP_DATA, outInfo, false); 11340 if (res) { 11341 pkgList.add(pkgName); 11342 } else { 11343 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 11344 failedList.add(args); 11345 } 11346 } 11347 } 11348 11349 // reader 11350 synchronized (mPackages) { 11351 // We didn't update the settings after removing each package; 11352 // write them now for all packages. 11353 mSettings.writeLPr(); 11354 } 11355 11356 // We have to absolutely send UPDATED_MEDIA_STATUS only 11357 // after confirming that all the receivers processed the ordered 11358 // broadcast when packages get disabled, force a gc to clean things up. 11359 // and unload all the containers. 11360 if (pkgList.size() > 0) { 11361 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 11362 new IIntentReceiver.Stub() { 11363 public void performReceive(Intent intent, int resultCode, String data, 11364 Bundle extras, boolean ordered, boolean sticky, 11365 int sendingUser) throws RemoteException { 11366 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 11367 reportStatus ? 1 : 0, 1, keys); 11368 mHandler.sendMessage(msg); 11369 } 11370 }); 11371 } else { 11372 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 11373 keys); 11374 mHandler.sendMessage(msg); 11375 } 11376 } 11377 11378 /** Binder call */ 11379 @Override 11380 public void movePackage(final String packageName, final IPackageMoveObserver observer, 11381 final int flags) { 11382 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 11383 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 11384 int returnCode = PackageManager.MOVE_SUCCEEDED; 11385 int currFlags = 0; 11386 int newFlags = 0; 11387 // reader 11388 synchronized (mPackages) { 11389 PackageParser.Package pkg = mPackages.get(packageName); 11390 if (pkg == null) { 11391 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 11392 } else { 11393 // Disable moving fwd locked apps and system packages 11394 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 11395 Slog.w(TAG, "Cannot move system application"); 11396 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 11397 } else if (pkg.mOperationPending) { 11398 Slog.w(TAG, "Attempt to move package which has pending operations"); 11399 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 11400 } else { 11401 // Find install location first 11402 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 11403 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 11404 Slog.w(TAG, "Ambigous flags specified for move location."); 11405 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 11406 } else { 11407 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 11408 : PackageManager.INSTALL_INTERNAL; 11409 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 11410 : PackageManager.INSTALL_INTERNAL; 11411 11412 if (newFlags == currFlags) { 11413 Slog.w(TAG, "No move required. Trying to move to same location"); 11414 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 11415 } else { 11416 if (isForwardLocked(pkg)) { 11417 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11418 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11419 } 11420 } 11421 } 11422 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 11423 pkg.mOperationPending = true; 11424 } 11425 } 11426 } 11427 11428 /* 11429 * TODO this next block probably shouldn't be inside the lock. We 11430 * can't guarantee these won't change after this is fired off 11431 * anyway. 11432 */ 11433 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 11434 processPendingMove(new MoveParams(null, observer, 0, packageName, 11435 null, -1, user), 11436 returnCode); 11437 } else { 11438 Message msg = mHandler.obtainMessage(INIT_COPY); 11439 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir, 11440 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir); 11441 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 11442 pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user); 11443 msg.obj = mp; 11444 mHandler.sendMessage(msg); 11445 } 11446 } 11447 } 11448 11449 private void processPendingMove(final MoveParams mp, final int currentStatus) { 11450 // Queue up an async operation since the package deletion may take a 11451 // little while. 11452 mHandler.post(new Runnable() { 11453 public void run() { 11454 // TODO fix this; this does nothing. 11455 mHandler.removeCallbacks(this); 11456 int returnCode = currentStatus; 11457 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 11458 int uidArr[] = null; 11459 ArrayList<String> pkgList = null; 11460 synchronized (mPackages) { 11461 PackageParser.Package pkg = mPackages.get(mp.packageName); 11462 if (pkg == null) { 11463 Slog.w(TAG, " Package " + mp.packageName 11464 + " doesn't exist. Aborting move"); 11465 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 11466 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 11467 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 11468 + mp.srcArgs.getCodePath() + " to " 11469 + pkg.applicationInfo.sourceDir 11470 + " Aborting move and returning error"); 11471 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 11472 } else { 11473 uidArr = new int[] { 11474 pkg.applicationInfo.uid 11475 }; 11476 pkgList = new ArrayList<String>(); 11477 pkgList.add(mp.packageName); 11478 } 11479 } 11480 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 11481 // Send resources unavailable broadcast 11482 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 11483 // Update package code and resource paths 11484 synchronized (mInstallLock) { 11485 synchronized (mPackages) { 11486 PackageParser.Package pkg = mPackages.get(mp.packageName); 11487 // Recheck for package again. 11488 if (pkg == null) { 11489 Slog.w(TAG, " Package " + mp.packageName 11490 + " doesn't exist. Aborting move"); 11491 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 11492 } else if (!mp.srcArgs.getCodePath().equals( 11493 pkg.applicationInfo.sourceDir)) { 11494 Slog.w(TAG, "Package " + mp.packageName 11495 + " code path changed from " + mp.srcArgs.getCodePath() 11496 + " to " + pkg.applicationInfo.sourceDir 11497 + " Aborting move and returning error"); 11498 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 11499 } else { 11500 final String oldCodePath = pkg.mPath; 11501 final String newCodePath = mp.targetArgs.getCodePath(); 11502 final String newResPath = mp.targetArgs.getResourcePath(); 11503 final String newNativePath = mp.targetArgs 11504 .getNativeLibraryPath(); 11505 11506 final File newNativeDir = new File(newNativePath); 11507 11508 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 11509 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 11510 new File(newCodePath), newNativeDir); 11511 } 11512 final int[] users = sUserManager.getUserIds(); 11513 for (int user : users) { 11514 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 11515 newNativePath, user) < 0) { 11516 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 11517 } 11518 } 11519 11520 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 11521 pkg.mPath = newCodePath; 11522 // Move dex files around 11523 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) { 11524 // Moving of dex files failed. Set 11525 // error code and abort move. 11526 pkg.mPath = pkg.mScanPath; 11527 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 11528 } 11529 } 11530 11531 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 11532 pkg.mScanPath = newCodePath; 11533 pkg.applicationInfo.sourceDir = newCodePath; 11534 pkg.applicationInfo.publicSourceDir = newResPath; 11535 pkg.applicationInfo.nativeLibraryDir = newNativePath; 11536 PackageSetting ps = (PackageSetting) pkg.mExtras; 11537 ps.codePath = new File(pkg.applicationInfo.sourceDir); 11538 ps.codePathString = ps.codePath.getPath(); 11539 ps.resourcePath = new File( 11540 pkg.applicationInfo.publicSourceDir); 11541 ps.resourcePathString = ps.resourcePath.getPath(); 11542 ps.nativeLibraryPathString = newNativePath; 11543 // Set the application info flag 11544 // correctly. 11545 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 11546 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 11547 } else { 11548 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 11549 } 11550 ps.setFlags(pkg.applicationInfo.flags); 11551 mAppDirs.remove(oldCodePath); 11552 mAppDirs.put(newCodePath, pkg); 11553 // Persist settings 11554 mSettings.writeLPr(); 11555 } 11556 } 11557 } 11558 } 11559 // Send resources available broadcast 11560 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 11561 } 11562 } 11563 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 11564 // Clean up failed installation 11565 if (mp.targetArgs != null) { 11566 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 11567 -1); 11568 } 11569 } else { 11570 // Force a gc to clear things up. 11571 Runtime.getRuntime().gc(); 11572 // Delete older code 11573 synchronized (mInstallLock) { 11574 mp.srcArgs.doPostDeleteLI(true); 11575 } 11576 } 11577 11578 // Allow more operations on this file if we didn't fail because 11579 // an operation was already pending for this package. 11580 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 11581 synchronized (mPackages) { 11582 PackageParser.Package pkg = mPackages.get(mp.packageName); 11583 if (pkg != null) { 11584 pkg.mOperationPending = false; 11585 } 11586 } 11587 } 11588 11589 IPackageMoveObserver observer = mp.observer; 11590 if (observer != null) { 11591 try { 11592 observer.packageMoved(mp.packageName, returnCode); 11593 } catch (RemoteException e) { 11594 Log.i(TAG, "Observer no longer exists."); 11595 } 11596 } 11597 } 11598 }); 11599 } 11600 11601 public boolean setInstallLocation(int loc) { 11602 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 11603 null); 11604 if (getInstallLocation() == loc) { 11605 return true; 11606 } 11607 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 11608 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 11609 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 11610 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 11611 return true; 11612 } 11613 return false; 11614 } 11615 11616 public int getInstallLocation() { 11617 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11618 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 11619 PackageHelper.APP_INSTALL_AUTO); 11620 } 11621 11622 /** Called by UserManagerService */ 11623 void cleanUpUserLILPw(int userHandle) { 11624 mDirtyUsers.remove(userHandle); 11625 mSettings.removeUserLPr(userHandle); 11626 mPendingBroadcasts.remove(userHandle); 11627 if (mInstaller != null) { 11628 // Technically, we shouldn't be doing this with the package lock 11629 // held. However, this is very rare, and there is already so much 11630 // other disk I/O going on, that we'll let it slide for now. 11631 mInstaller.removeUserDataDirs(userHandle); 11632 } 11633 } 11634 11635 /** Called by UserManagerService */ 11636 void createNewUserLILPw(int userHandle, File path) { 11637 if (mInstaller != null) { 11638 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 11639 } 11640 } 11641 11642 @Override 11643 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 11644 mContext.enforceCallingOrSelfPermission( 11645 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11646 "Only package verification agents can read the verifier device identity"); 11647 11648 synchronized (mPackages) { 11649 return mSettings.getVerifierDeviceIdentityLPw(); 11650 } 11651 } 11652 11653 @Override 11654 public void setPermissionEnforced(String permission, boolean enforced) { 11655 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 11656 if (READ_EXTERNAL_STORAGE.equals(permission)) { 11657 synchronized (mPackages) { 11658 if (mSettings.mReadExternalStorageEnforced == null 11659 || mSettings.mReadExternalStorageEnforced != enforced) { 11660 mSettings.mReadExternalStorageEnforced = enforced; 11661 mSettings.writeLPr(); 11662 } 11663 } 11664 // kill any non-foreground processes so we restart them and 11665 // grant/revoke the GID. 11666 final IActivityManager am = ActivityManagerNative.getDefault(); 11667 if (am != null) { 11668 final long token = Binder.clearCallingIdentity(); 11669 try { 11670 am.killProcessesBelowForeground("setPermissionEnforcement"); 11671 } catch (RemoteException e) { 11672 } finally { 11673 Binder.restoreCallingIdentity(token); 11674 } 11675 } 11676 } else { 11677 throw new IllegalArgumentException("No selective enforcement for " + permission); 11678 } 11679 } 11680 11681 @Override 11682 @Deprecated 11683 public boolean isPermissionEnforced(String permission) { 11684 return true; 11685 } 11686 11687 @Override 11688 public boolean isStorageLow() { 11689 final long token = Binder.clearCallingIdentity(); 11690 try { 11691 final DeviceStorageMonitorInternal 11692 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11693 if (dsm != null) { 11694 return dsm.isMemoryLow(); 11695 } else { 11696 return false; 11697 } 11698 } finally { 11699 Binder.restoreCallingIdentity(token); 11700 } 11701 } 11702} 11703