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