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