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