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