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