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