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