PackageManagerService.java revision ab45d1d6d296f4f61632a472cf7bd8626c8d5a06
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.system.OsConstants.S_IRWXU; 27import static android.system.OsConstants.S_IRGRP; 28import static android.system.OsConstants.S_IXGRP; 29import static android.system.OsConstants.S_IROTH; 30import static android.system.OsConstants.S_IXOTH; 31import static com.android.internal.util.ArrayUtils.appendInt; 32import static com.android.internal.util.ArrayUtils.removeInt; 33 34import android.content.pm.PackageParser.*; 35import com.android.internal.app.IMediaContainerService; 36import com.android.internal.app.ResolverActivity; 37import com.android.internal.content.NativeLibraryHelper; 38import com.android.internal.content.PackageHelper; 39import com.android.internal.util.FastPrintWriter; 40import com.android.internal.util.FastXmlSerializer; 41import com.android.internal.util.XmlUtils; 42import com.android.server.EventLogTags; 43import com.android.server.IntentResolver; 44import com.android.server.ServiceThread; 45 46import com.android.server.LocalServices; 47import com.android.server.Watchdog; 48import org.xmlpull.v1.XmlPullParser; 49import org.xmlpull.v1.XmlPullParserException; 50import org.xmlpull.v1.XmlSerializer; 51 52import android.app.ActivityManager; 53import android.app.ActivityManagerNative; 54import android.app.IActivityManager; 55import android.app.admin.IDevicePolicyManager; 56import android.app.backup.IBackupManager; 57import android.content.BroadcastReceiver; 58import android.content.ComponentName; 59import android.content.Context; 60import android.content.IIntentReceiver; 61import android.content.Intent; 62import android.content.IntentFilter; 63import android.content.IntentSender; 64import android.content.IntentSender.SendIntentException; 65import android.content.ServiceConnection; 66import android.content.pm.ActivityInfo; 67import android.content.pm.ApplicationInfo; 68import android.content.pm.ContainerEncryptionParams; 69import android.content.pm.FeatureInfo; 70import android.content.pm.IPackageDataObserver; 71import android.content.pm.IPackageDeleteObserver; 72import android.content.pm.IPackageInstallObserver; 73import android.content.pm.IPackageInstallObserver2; 74import android.content.pm.IPackageManager; 75import android.content.pm.IPackageMoveObserver; 76import android.content.pm.IPackageStatsObserver; 77import android.content.pm.InstrumentationInfo; 78import android.content.pm.ManifestDigest; 79import android.content.pm.PackageCleanItem; 80import android.content.pm.PackageInfo; 81import android.content.pm.PackageInfoLite; 82import android.content.pm.PackageManager; 83import android.content.pm.PackageParser; 84import android.content.pm.PackageStats; 85import android.content.pm.PackageUserState; 86import android.content.pm.ParceledListSlice; 87import android.content.pm.PermissionGroupInfo; 88import android.content.pm.PermissionInfo; 89import android.content.pm.ProviderInfo; 90import android.content.pm.ResolveInfo; 91import android.content.pm.ServiceInfo; 92import android.content.pm.Signature; 93import android.content.pm.VerificationParams; 94import android.content.pm.VerifierDeviceIdentity; 95import android.content.pm.VerifierInfo; 96import android.content.res.Resources; 97import android.hardware.display.DisplayManager; 98import android.net.Uri; 99import android.os.Binder; 100import android.os.Build; 101import android.os.Bundle; 102import android.os.Environment; 103import android.os.Environment.UserEnvironment; 104import android.os.FileObserver; 105import android.os.FileUtils; 106import android.os.Handler; 107import android.os.IBinder; 108import android.os.Looper; 109import android.os.Message; 110import android.os.Parcel; 111import android.os.ParcelFileDescriptor; 112import android.os.Process; 113import android.os.RemoteException; 114import android.os.SELinux; 115import android.os.ServiceManager; 116import android.os.SystemClock; 117import android.os.SystemProperties; 118import android.os.UserHandle; 119import android.os.UserManager; 120import android.security.KeyStore; 121import android.security.SystemKeyStore; 122import android.system.ErrnoException; 123import android.system.Os; 124import android.system.StructStat; 125import android.text.TextUtils; 126import android.util.DisplayMetrics; 127import android.util.EventLog; 128import android.util.Log; 129import android.util.LogPrinter; 130import android.util.PrintStreamPrinter; 131import android.util.Slog; 132import android.util.SparseArray; 133import android.util.Xml; 134import android.view.Display; 135 136import java.io.BufferedOutputStream; 137import java.io.File; 138import java.io.FileDescriptor; 139import java.io.FileInputStream; 140import java.io.FileNotFoundException; 141import java.io.FileOutputStream; 142import java.io.FileReader; 143import java.io.FilenameFilter; 144import java.io.IOException; 145import java.io.PrintWriter; 146import java.security.NoSuchAlgorithmException; 147import java.security.PublicKey; 148import java.security.cert.Certificate; 149import java.security.cert.CertificateEncodingException; 150import java.security.cert.CertificateException; 151import java.text.SimpleDateFormat; 152import java.util.ArrayList; 153import java.util.Arrays; 154import java.util.Collection; 155import java.util.Collections; 156import java.util.Comparator; 157import java.util.Date; 158import java.util.HashMap; 159import java.util.HashSet; 160import java.util.Iterator; 161import java.util.List; 162import java.util.Map; 163import java.util.Set; 164 165import dalvik.system.VMRuntime; 166import libcore.io.IoUtils; 167 168import com.android.internal.R; 169import com.android.server.pm.Settings.DatabaseVersion; 170import com.android.server.storage.DeviceStorageMonitorInternal; 171 172/** 173 * Keep track of all those .apks everywhere. 174 * 175 * This is very central to the platform's security; please run the unit 176 * tests whenever making modifications here: 177 * 178mmm frameworks/base/tests/AndroidTests 179adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 180adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 181 * 182 * {@hide} 183 */ 184public class PackageManagerService extends IPackageManager.Stub { 185 static final String TAG = "PackageManager"; 186 static final boolean DEBUG_SETTINGS = false; 187 static final boolean DEBUG_PREFERRED = false; 188 static final boolean DEBUG_UPGRADE = false; 189 private static final boolean DEBUG_INSTALL = false; 190 private static final boolean DEBUG_REMOVE = false; 191 private static final boolean DEBUG_BROADCASTS = false; 192 private static final boolean DEBUG_SHOW_INFO = false; 193 private static final boolean DEBUG_PACKAGE_INFO = false; 194 private static final boolean DEBUG_INTENT_MATCHING = false; 195 private static final boolean DEBUG_PACKAGE_SCANNING = false; 196 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 197 private static final boolean DEBUG_VERIFY = false; 198 199 private static final int RADIO_UID = Process.PHONE_UID; 200 private static final int LOG_UID = Process.LOG_UID; 201 private static final int NFC_UID = Process.NFC_UID; 202 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 203 private static final int SHELL_UID = Process.SHELL_UID; 204 205 // Cap the size of permission trees that 3rd party apps can define 206 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 207 208 private static final int REMOVE_EVENTS = 209 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 210 private static final int ADD_EVENTS = 211 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 212 213 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 214 // Suffix used during package installation when copying/moving 215 // package apks to install directory. 216 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 217 218 static final int SCAN_MONITOR = 1<<0; 219 static final int SCAN_NO_DEX = 1<<1; 220 static final int SCAN_FORCE_DEX = 1<<2; 221 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 222 static final int SCAN_NEW_INSTALL = 1<<4; 223 static final int SCAN_NO_PATHS = 1<<5; 224 static final int SCAN_UPDATE_TIME = 1<<6; 225 static final int SCAN_DEFER_DEX = 1<<7; 226 static final int SCAN_BOOTING = 1<<8; 227 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 228 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 229 230 static final int REMOVE_CHATTY = 1<<16; 231 232 /** 233 * Timeout (in milliseconds) after which the watchdog should declare that 234 * our handler thread is wedged. The usual default for such things is one 235 * minute but we sometimes do very lengthy I/O operations on this thread, 236 * such as installing multi-gigabyte applications, so ours needs to be longer. 237 */ 238 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 239 240 /** 241 * Whether verification is enabled by default. 242 */ 243 private static final boolean DEFAULT_VERIFY_ENABLE = true; 244 245 /** 246 * The default maximum time to wait for the verification agent to return in 247 * milliseconds. 248 */ 249 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 250 251 /** 252 * The default response for package verification timeout. 253 * 254 * This can be either PackageManager.VERIFICATION_ALLOW or 255 * PackageManager.VERIFICATION_REJECT. 256 */ 257 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 258 259 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 260 261 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 262 DEFAULT_CONTAINER_PACKAGE, 263 "com.android.defcontainer.DefaultContainerService"); 264 265 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 266 267 private static final String LIB_DIR_NAME = "lib"; 268 private static final String LIB64_DIR_NAME = "lib64"; 269 270 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 271 272 static final String mTempContainerPrefix = "smdl2tmp"; 273 274 private static String sPreferredInstructionSet; 275 276 final ServiceThread mHandlerThread; 277 278 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 279 private static final String IDMAP_SUFFIX = "@idmap"; 280 281 final PackageHandler mHandler; 282 283 final int mSdkVersion = Build.VERSION.SDK_INT; 284 285 final Context mContext; 286 final boolean mFactoryTest; 287 final boolean mOnlyCore; 288 final boolean mNoDexOpt; 289 final DisplayMetrics mMetrics; 290 final int mDefParseFlags; 291 final String[] mSeparateProcesses; 292 293 // This is where all application persistent data goes. 294 final File mAppDataDir; 295 296 // This is where all application persistent data goes for secondary users. 297 final File mUserAppDataDir; 298 299 /** The location for ASEC container files on internal storage. */ 300 final String mAsecInternalPath; 301 302 // This is the object monitoring the framework dir. 303 final FileObserver mFrameworkInstallObserver; 304 305 // This is the object monitoring the system app dir. 306 final FileObserver mSystemInstallObserver; 307 308 // This is the object monitoring the privileged system app dir. 309 final FileObserver mPrivilegedInstallObserver; 310 311 // This is the object monitoring the vendor app dir. 312 final FileObserver mVendorInstallObserver; 313 314 // This is the object monitoring the vendor overlay package dir. 315 final FileObserver mVendorOverlayInstallObserver; 316 317 // This is the object monitoring the OEM app dir. 318 final FileObserver mOemInstallObserver; 319 320 // This is the object monitoring mAppInstallDir. 321 final FileObserver mAppInstallObserver; 322 323 // This is the object monitoring mDrmAppPrivateInstallDir. 324 final FileObserver mDrmAppInstallObserver; 325 326 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 327 // LOCK HELD. Can be called with mInstallLock held. 328 final Installer mInstaller; 329 330 final File mAppInstallDir; 331 332 /** 333 * Directory to which applications installed internally have native 334 * libraries copied. 335 */ 336 private File mAppLibInstallDir; 337 338 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 339 // apps. 340 final File mDrmAppPrivateInstallDir; 341 342 // ---------------------------------------------------------------- 343 344 // Lock for state used when installing and doing other long running 345 // operations. Methods that must be called with this lock held have 346 // the suffix "LI". 347 final Object mInstallLock = new Object(); 348 349 // These are the directories in the 3rd party applications installed dir 350 // that we have currently loaded packages from. Keys are the application's 351 // installed zip file (absolute codePath), and values are Package. 352 final HashMap<String, PackageParser.Package> mAppDirs = 353 new HashMap<String, PackageParser.Package>(); 354 355 // Information for the parser to write more useful error messages. 356 int mLastScanError; 357 358 // ---------------------------------------------------------------- 359 360 // Keys are String (package name), values are Package. This also serves 361 // as the lock for the global state. Methods that must be called with 362 // this lock held have the prefix "LP". 363 final HashMap<String, PackageParser.Package> mPackages = 364 new HashMap<String, PackageParser.Package>(); 365 366 // Tracks available target package names -> overlay package paths. 367 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 368 new HashMap<String, HashMap<String, PackageParser.Package>>(); 369 370 final Settings mSettings; 371 boolean mRestoredSettings; 372 373 // Group-ids that are given to all packages as read from etc/permissions/*.xml. 374 int[] mGlobalGids; 375 376 // These are the built-in uid -> permission mappings that were read from the 377 // etc/permissions.xml file. 378 final SparseArray<HashSet<String>> mSystemPermissions = 379 new SparseArray<HashSet<String>>(); 380 381 static final class SharedLibraryEntry { 382 final String path; 383 final String apk; 384 385 SharedLibraryEntry(String _path, String _apk) { 386 path = _path; 387 apk = _apk; 388 } 389 } 390 391 // These are the built-in shared libraries that were read from the 392 // etc/permissions.xml file. 393 final HashMap<String, SharedLibraryEntry> mSharedLibraries 394 = new HashMap<String, SharedLibraryEntry>(); 395 396 // Temporary for building the final shared libraries for an .apk. 397 String[] mTmpSharedLibraries = null; 398 399 // These are the features this devices supports that were read from the 400 // etc/permissions.xml file. 401 final HashMap<String, FeatureInfo> mAvailableFeatures = 402 new HashMap<String, FeatureInfo>(); 403 404 // If mac_permissions.xml was found for seinfo labeling. 405 boolean mFoundPolicyFile; 406 407 // If a recursive restorecon of /data/data/<pkg> is needed. 408 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 409 410 // All available activities, for your resolving pleasure. 411 final ActivityIntentResolver mActivities = 412 new ActivityIntentResolver(); 413 414 // All available receivers, for your resolving pleasure. 415 final ActivityIntentResolver mReceivers = 416 new ActivityIntentResolver(); 417 418 // All available services, for your resolving pleasure. 419 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 420 421 // All available providers, for your resolving pleasure. 422 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 423 424 // Mapping from provider base names (first directory in content URI codePath) 425 // to the provider information. 426 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 427 new HashMap<String, PackageParser.Provider>(); 428 429 // Mapping from instrumentation class names to info about them. 430 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 431 new HashMap<ComponentName, PackageParser.Instrumentation>(); 432 433 // Mapping from permission names to info about them. 434 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 435 new HashMap<String, PackageParser.PermissionGroup>(); 436 437 // Packages whose data we have transfered into another package, thus 438 // should no longer exist. 439 final HashSet<String> mTransferedPackages = new HashSet<String>(); 440 441 // Broadcast actions that are only available to the system. 442 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 443 444 /** List of packages waiting for verification. */ 445 final SparseArray<PackageVerificationState> mPendingVerification 446 = new SparseArray<PackageVerificationState>(); 447 448 HashSet<PackageParser.Package> mDeferredDexOpt = null; 449 450 /** Token for keys in mPendingVerification. */ 451 private int mPendingVerificationToken = 0; 452 453 boolean mSystemReady; 454 boolean mSafeMode; 455 boolean mHasSystemUidErrors; 456 457 ApplicationInfo mAndroidApplication; 458 final ActivityInfo mResolveActivity = new ActivityInfo(); 459 final ResolveInfo mResolveInfo = new ResolveInfo(); 460 ComponentName mResolveComponentName; 461 PackageParser.Package mPlatformPackage; 462 ComponentName mCustomResolverComponentName; 463 464 boolean mResolverReplaced = false; 465 466 // Set of pending broadcasts for aggregating enable/disable of components. 467 static class PendingPackageBroadcasts { 468 // for each user id, a map of <package name -> components within that package> 469 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 470 471 public PendingPackageBroadcasts() { 472 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 473 } 474 475 public ArrayList<String> get(int userId, String packageName) { 476 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 477 return packages.get(packageName); 478 } 479 480 public void put(int userId, String packageName, ArrayList<String> components) { 481 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 482 packages.put(packageName, components); 483 } 484 485 public void remove(int userId, String packageName) { 486 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 487 if (packages != null) { 488 packages.remove(packageName); 489 } 490 } 491 492 public void remove(int userId) { 493 mUidMap.remove(userId); 494 } 495 496 public int userIdCount() { 497 return mUidMap.size(); 498 } 499 500 public int userIdAt(int n) { 501 return mUidMap.keyAt(n); 502 } 503 504 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 505 return mUidMap.get(userId); 506 } 507 508 public int size() { 509 // total number of pending broadcast entries across all userIds 510 int num = 0; 511 for (int i = 0; i< mUidMap.size(); i++) { 512 num += mUidMap.valueAt(i).size(); 513 } 514 return num; 515 } 516 517 public void clear() { 518 mUidMap.clear(); 519 } 520 521 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 522 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 523 if (map == null) { 524 map = new HashMap<String, ArrayList<String>>(); 525 mUidMap.put(userId, map); 526 } 527 return map; 528 } 529 } 530 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 531 532 // Service Connection to remote media container service to copy 533 // package uri's from external media onto secure containers 534 // or internal storage. 535 private IMediaContainerService mContainerService = null; 536 537 static final int SEND_PENDING_BROADCAST = 1; 538 static final int MCS_BOUND = 3; 539 static final int END_COPY = 4; 540 static final int INIT_COPY = 5; 541 static final int MCS_UNBIND = 6; 542 static final int START_CLEANING_PACKAGE = 7; 543 static final int FIND_INSTALL_LOC = 8; 544 static final int POST_INSTALL = 9; 545 static final int MCS_RECONNECT = 10; 546 static final int MCS_GIVE_UP = 11; 547 static final int UPDATED_MEDIA_STATUS = 12; 548 static final int WRITE_SETTINGS = 13; 549 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 550 static final int PACKAGE_VERIFIED = 15; 551 static final int CHECK_PENDING_VERIFICATION = 16; 552 553 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 554 555 // Delay time in millisecs 556 static final int BROADCAST_DELAY = 10 * 1000; 557 558 static UserManagerService sUserManager; 559 560 // Stores a list of users whose package restrictions file needs to be updated 561 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 562 563 final private DefaultContainerConnection mDefContainerConn = 564 new DefaultContainerConnection(); 565 class DefaultContainerConnection implements ServiceConnection { 566 public void onServiceConnected(ComponentName name, IBinder service) { 567 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 568 IMediaContainerService imcs = 569 IMediaContainerService.Stub.asInterface(service); 570 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 571 } 572 573 public void onServiceDisconnected(ComponentName name) { 574 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 575 } 576 }; 577 578 // Recordkeeping of restore-after-install operations that are currently in flight 579 // between the Package Manager and the Backup Manager 580 class PostInstallData { 581 public InstallArgs args; 582 public PackageInstalledInfo res; 583 584 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 585 args = _a; 586 res = _r; 587 } 588 }; 589 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 590 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 591 592 private final String mRequiredVerifierPackage; 593 594 class PackageHandler extends Handler { 595 private boolean mBound = false; 596 final ArrayList<HandlerParams> mPendingInstalls = 597 new ArrayList<HandlerParams>(); 598 599 private boolean connectToService() { 600 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 601 " DefaultContainerService"); 602 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 603 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 604 if (mContext.bindServiceAsUser(service, mDefContainerConn, 605 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 606 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 607 mBound = true; 608 return true; 609 } 610 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 611 return false; 612 } 613 614 private void disconnectService() { 615 mContainerService = null; 616 mBound = false; 617 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 618 mContext.unbindService(mDefContainerConn); 619 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 620 } 621 622 PackageHandler(Looper looper) { 623 super(looper); 624 } 625 626 public void handleMessage(Message msg) { 627 try { 628 doHandleMessage(msg); 629 } finally { 630 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 631 } 632 } 633 634 void doHandleMessage(Message msg) { 635 switch (msg.what) { 636 case INIT_COPY: { 637 HandlerParams params = (HandlerParams) msg.obj; 638 int idx = mPendingInstalls.size(); 639 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 640 // If a bind was already initiated we dont really 641 // need to do anything. The pending install 642 // will be processed later on. 643 if (!mBound) { 644 // If this is the only one pending we might 645 // have to bind to the service again. 646 if (!connectToService()) { 647 Slog.e(TAG, "Failed to bind to media container service"); 648 params.serviceError(); 649 return; 650 } else { 651 // Once we bind to the service, the first 652 // pending request will be processed. 653 mPendingInstalls.add(idx, params); 654 } 655 } else { 656 mPendingInstalls.add(idx, params); 657 // Already bound to the service. Just make 658 // sure we trigger off processing the first request. 659 if (idx == 0) { 660 mHandler.sendEmptyMessage(MCS_BOUND); 661 } 662 } 663 break; 664 } 665 case MCS_BOUND: { 666 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 667 if (msg.obj != null) { 668 mContainerService = (IMediaContainerService) msg.obj; 669 } 670 if (mContainerService == null) { 671 // Something seriously wrong. Bail out 672 Slog.e(TAG, "Cannot bind to media container service"); 673 for (HandlerParams params : mPendingInstalls) { 674 // Indicate service bind error 675 params.serviceError(); 676 } 677 mPendingInstalls.clear(); 678 } else if (mPendingInstalls.size() > 0) { 679 HandlerParams params = mPendingInstalls.get(0); 680 if (params != null) { 681 if (params.startCopy()) { 682 // We are done... look for more work or to 683 // go idle. 684 if (DEBUG_SD_INSTALL) Log.i(TAG, 685 "Checking for more work or unbind..."); 686 // Delete pending install 687 if (mPendingInstalls.size() > 0) { 688 mPendingInstalls.remove(0); 689 } 690 if (mPendingInstalls.size() == 0) { 691 if (mBound) { 692 if (DEBUG_SD_INSTALL) Log.i(TAG, 693 "Posting delayed MCS_UNBIND"); 694 removeMessages(MCS_UNBIND); 695 Message ubmsg = obtainMessage(MCS_UNBIND); 696 // Unbind after a little delay, to avoid 697 // continual thrashing. 698 sendMessageDelayed(ubmsg, 10000); 699 } 700 } else { 701 // There are more pending requests in queue. 702 // Just post MCS_BOUND message to trigger processing 703 // of next pending install. 704 if (DEBUG_SD_INSTALL) Log.i(TAG, 705 "Posting MCS_BOUND for next work"); 706 mHandler.sendEmptyMessage(MCS_BOUND); 707 } 708 } 709 } 710 } else { 711 // Should never happen ideally. 712 Slog.w(TAG, "Empty queue"); 713 } 714 break; 715 } 716 case MCS_RECONNECT: { 717 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 718 if (mPendingInstalls.size() > 0) { 719 if (mBound) { 720 disconnectService(); 721 } 722 if (!connectToService()) { 723 Slog.e(TAG, "Failed to bind to media container service"); 724 for (HandlerParams params : mPendingInstalls) { 725 // Indicate service bind error 726 params.serviceError(); 727 } 728 mPendingInstalls.clear(); 729 } 730 } 731 break; 732 } 733 case MCS_UNBIND: { 734 // If there is no actual work left, then time to unbind. 735 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 736 737 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 738 if (mBound) { 739 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 740 741 disconnectService(); 742 } 743 } else if (mPendingInstalls.size() > 0) { 744 // There are more pending requests in queue. 745 // Just post MCS_BOUND message to trigger processing 746 // of next pending install. 747 mHandler.sendEmptyMessage(MCS_BOUND); 748 } 749 750 break; 751 } 752 case MCS_GIVE_UP: { 753 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 754 mPendingInstalls.remove(0); 755 break; 756 } 757 case SEND_PENDING_BROADCAST: { 758 String packages[]; 759 ArrayList<String> components[]; 760 int size = 0; 761 int uids[]; 762 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 763 synchronized (mPackages) { 764 if (mPendingBroadcasts == null) { 765 return; 766 } 767 size = mPendingBroadcasts.size(); 768 if (size <= 0) { 769 // Nothing to be done. Just return 770 return; 771 } 772 packages = new String[size]; 773 components = new ArrayList[size]; 774 uids = new int[size]; 775 int i = 0; // filling out the above arrays 776 777 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 778 int packageUserId = mPendingBroadcasts.userIdAt(n); 779 Iterator<Map.Entry<String, ArrayList<String>>> it 780 = mPendingBroadcasts.packagesForUserId(packageUserId) 781 .entrySet().iterator(); 782 while (it.hasNext() && i < size) { 783 Map.Entry<String, ArrayList<String>> ent = it.next(); 784 packages[i] = ent.getKey(); 785 components[i] = ent.getValue(); 786 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 787 uids[i] = (ps != null) 788 ? UserHandle.getUid(packageUserId, ps.appId) 789 : -1; 790 i++; 791 } 792 } 793 size = i; 794 mPendingBroadcasts.clear(); 795 } 796 // Send broadcasts 797 for (int i = 0; i < size; i++) { 798 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 799 } 800 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 801 break; 802 } 803 case START_CLEANING_PACKAGE: { 804 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 805 final String packageName = (String)msg.obj; 806 final int userId = msg.arg1; 807 final boolean andCode = msg.arg2 != 0; 808 synchronized (mPackages) { 809 if (userId == UserHandle.USER_ALL) { 810 int[] users = sUserManager.getUserIds(); 811 for (int user : users) { 812 mSettings.addPackageToCleanLPw( 813 new PackageCleanItem(user, packageName, andCode)); 814 } 815 } else { 816 mSettings.addPackageToCleanLPw( 817 new PackageCleanItem(userId, packageName, andCode)); 818 } 819 } 820 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 821 startCleaningPackages(); 822 } break; 823 case POST_INSTALL: { 824 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 825 PostInstallData data = mRunningInstalls.get(msg.arg1); 826 mRunningInstalls.delete(msg.arg1); 827 boolean deleteOld = false; 828 829 if (data != null) { 830 InstallArgs args = data.args; 831 PackageInstalledInfo res = data.res; 832 833 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 834 res.removedInfo.sendBroadcast(false, true, false); 835 Bundle extras = new Bundle(1); 836 extras.putInt(Intent.EXTRA_UID, res.uid); 837 // Determine the set of users who are adding this 838 // package for the first time vs. those who are seeing 839 // an update. 840 int[] firstUsers; 841 int[] updateUsers = new int[0]; 842 if (res.origUsers == null || res.origUsers.length == 0) { 843 firstUsers = res.newUsers; 844 } else { 845 firstUsers = new int[0]; 846 for (int i=0; i<res.newUsers.length; i++) { 847 int user = res.newUsers[i]; 848 boolean isNew = true; 849 for (int j=0; j<res.origUsers.length; j++) { 850 if (res.origUsers[j] == user) { 851 isNew = false; 852 break; 853 } 854 } 855 if (isNew) { 856 int[] newFirst = new int[firstUsers.length+1]; 857 System.arraycopy(firstUsers, 0, newFirst, 0, 858 firstUsers.length); 859 newFirst[firstUsers.length] = user; 860 firstUsers = newFirst; 861 } else { 862 int[] newUpdate = new int[updateUsers.length+1]; 863 System.arraycopy(updateUsers, 0, newUpdate, 0, 864 updateUsers.length); 865 newUpdate[updateUsers.length] = user; 866 updateUsers = newUpdate; 867 } 868 } 869 } 870 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 871 res.pkg.applicationInfo.packageName, 872 extras, null, null, firstUsers); 873 final boolean update = res.removedInfo.removedPackage != null; 874 if (update) { 875 extras.putBoolean(Intent.EXTRA_REPLACING, true); 876 } 877 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 878 res.pkg.applicationInfo.packageName, 879 extras, null, null, updateUsers); 880 if (update) { 881 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 882 res.pkg.applicationInfo.packageName, 883 extras, null, null, updateUsers); 884 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 885 null, null, 886 res.pkg.applicationInfo.packageName, null, updateUsers); 887 888 // treat asec-hosted packages like removable media on upgrade 889 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 890 if (DEBUG_INSTALL) { 891 Slog.i(TAG, "upgrading pkg " + res.pkg 892 + " is ASEC-hosted -> AVAILABLE"); 893 } 894 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 895 ArrayList<String> pkgList = new ArrayList<String>(1); 896 pkgList.add(res.pkg.applicationInfo.packageName); 897 sendResourcesChangedBroadcast(true, true, 898 pkgList,uidArray, null); 899 } 900 } 901 if (res.removedInfo.args != null) { 902 // Remove the replaced package's older resources safely now 903 deleteOld = true; 904 } 905 906 // Log current value of "unknown sources" setting 907 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 908 getUnknownSourcesSettings()); 909 } 910 // Force a gc to clear up things 911 Runtime.getRuntime().gc(); 912 // We delete after a gc for applications on sdcard. 913 if (deleteOld) { 914 synchronized (mInstallLock) { 915 res.removedInfo.args.doPostDeleteLI(true); 916 } 917 } 918 if (args.observer != null) { 919 try { 920 args.observer.packageInstalled(res.name, res.returnCode); 921 } catch (RemoteException e) { 922 Slog.i(TAG, "Observer no longer exists."); 923 } 924 } 925 if (args.observer2 != null) { 926 try { 927 Bundle extras = extrasForInstallResult(res); 928 args.observer2.packageInstalled(res.name, extras, res.returnCode); 929 } catch (RemoteException e) { 930 Slog.i(TAG, "Observer no longer exists."); 931 } 932 } 933 } else { 934 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 935 } 936 } break; 937 case UPDATED_MEDIA_STATUS: { 938 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 939 boolean reportStatus = msg.arg1 == 1; 940 boolean doGc = msg.arg2 == 1; 941 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 942 if (doGc) { 943 // Force a gc to clear up stale containers. 944 Runtime.getRuntime().gc(); 945 } 946 if (msg.obj != null) { 947 @SuppressWarnings("unchecked") 948 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 949 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 950 // Unload containers 951 unloadAllContainers(args); 952 } 953 if (reportStatus) { 954 try { 955 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 956 PackageHelper.getMountService().finishMediaUpdate(); 957 } catch (RemoteException e) { 958 Log.e(TAG, "MountService not running?"); 959 } 960 } 961 } break; 962 case WRITE_SETTINGS: { 963 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 964 synchronized (mPackages) { 965 removeMessages(WRITE_SETTINGS); 966 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 967 mSettings.writeLPr(); 968 mDirtyUsers.clear(); 969 } 970 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 971 } break; 972 case WRITE_PACKAGE_RESTRICTIONS: { 973 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 974 synchronized (mPackages) { 975 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 976 for (int userId : mDirtyUsers) { 977 mSettings.writePackageRestrictionsLPr(userId); 978 } 979 mDirtyUsers.clear(); 980 } 981 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 982 } break; 983 case CHECK_PENDING_VERIFICATION: { 984 final int verificationId = msg.arg1; 985 final PackageVerificationState state = mPendingVerification.get(verificationId); 986 987 if ((state != null) && !state.timeoutExtended()) { 988 final InstallArgs args = state.getInstallArgs(); 989 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString()); 990 mPendingVerification.remove(verificationId); 991 992 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 993 994 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 995 Slog.i(TAG, "Continuing with installation of " 996 + args.packageURI.toString()); 997 state.setVerifierResponse(Binder.getCallingUid(), 998 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 999 broadcastPackageVerified(verificationId, args.packageURI, 1000 PackageManager.VERIFICATION_ALLOW, 1001 state.getInstallArgs().getUser()); 1002 try { 1003 ret = args.copyApk(mContainerService, true); 1004 } catch (RemoteException e) { 1005 Slog.e(TAG, "Could not contact the ContainerService"); 1006 } 1007 } else { 1008 broadcastPackageVerified(verificationId, args.packageURI, 1009 PackageManager.VERIFICATION_REJECT, 1010 state.getInstallArgs().getUser()); 1011 } 1012 1013 processPendingInstall(args, ret); 1014 mHandler.sendEmptyMessage(MCS_UNBIND); 1015 } 1016 break; 1017 } 1018 case PACKAGE_VERIFIED: { 1019 final int verificationId = msg.arg1; 1020 1021 final PackageVerificationState state = mPendingVerification.get(verificationId); 1022 if (state == null) { 1023 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1024 break; 1025 } 1026 1027 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1028 1029 state.setVerifierResponse(response.callerUid, response.code); 1030 1031 if (state.isVerificationComplete()) { 1032 mPendingVerification.remove(verificationId); 1033 1034 final InstallArgs args = state.getInstallArgs(); 1035 1036 int ret; 1037 if (state.isInstallAllowed()) { 1038 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1039 broadcastPackageVerified(verificationId, args.packageURI, 1040 response.code, state.getInstallArgs().getUser()); 1041 try { 1042 ret = args.copyApk(mContainerService, true); 1043 } catch (RemoteException e) { 1044 Slog.e(TAG, "Could not contact the ContainerService"); 1045 } 1046 } else { 1047 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1048 } 1049 1050 processPendingInstall(args, ret); 1051 1052 mHandler.sendEmptyMessage(MCS_UNBIND); 1053 } 1054 1055 break; 1056 } 1057 } 1058 } 1059 } 1060 1061 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1062 Bundle extras = null; 1063 switch (res.returnCode) { 1064 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1065 extras = new Bundle(); 1066 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1067 res.origPermission); 1068 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1069 res.origPackage); 1070 break; 1071 } 1072 } 1073 return extras; 1074 } 1075 1076 void scheduleWriteSettingsLocked() { 1077 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1078 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1079 } 1080 } 1081 1082 void scheduleWritePackageRestrictionsLocked(int userId) { 1083 if (!sUserManager.exists(userId)) return; 1084 mDirtyUsers.add(userId); 1085 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1086 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1087 } 1088 } 1089 1090 public static final IPackageManager main(Context context, Installer installer, 1091 boolean factoryTest, boolean onlyCore) { 1092 PackageManagerService m = new PackageManagerService(context, installer, 1093 factoryTest, onlyCore); 1094 ServiceManager.addService("package", m); 1095 return m; 1096 } 1097 1098 static String[] splitString(String str, char sep) { 1099 int count = 1; 1100 int i = 0; 1101 while ((i=str.indexOf(sep, i)) >= 0) { 1102 count++; 1103 i++; 1104 } 1105 1106 String[] res = new String[count]; 1107 i=0; 1108 count = 0; 1109 int lastI=0; 1110 while ((i=str.indexOf(sep, i)) >= 0) { 1111 res[count] = str.substring(lastI, i); 1112 count++; 1113 i++; 1114 lastI = i; 1115 } 1116 res[count] = str.substring(lastI, str.length()); 1117 return res; 1118 } 1119 1120 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1121 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1122 Context.DISPLAY_SERVICE); 1123 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1124 } 1125 1126 public PackageManagerService(Context context, Installer installer, 1127 boolean factoryTest, boolean onlyCore) { 1128 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1129 SystemClock.uptimeMillis()); 1130 1131 if (mSdkVersion <= 0) { 1132 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1133 } 1134 1135 mContext = context; 1136 mFactoryTest = factoryTest; 1137 mOnlyCore = onlyCore; 1138 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1139 mMetrics = new DisplayMetrics(); 1140 mSettings = new Settings(context); 1141 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1142 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1143 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1144 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1145 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1146 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1147 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1148 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1149 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1150 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1151 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1152 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1153 1154 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1155 if (separateProcesses != null && separateProcesses.length() > 0) { 1156 if ("*".equals(separateProcesses)) { 1157 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1158 mSeparateProcesses = null; 1159 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1160 } else { 1161 mDefParseFlags = 0; 1162 mSeparateProcesses = separateProcesses.split(","); 1163 Slog.w(TAG, "Running with debug.separate_processes: " 1164 + separateProcesses); 1165 } 1166 } else { 1167 mDefParseFlags = 0; 1168 mSeparateProcesses = null; 1169 } 1170 1171 mInstaller = installer; 1172 1173 getDefaultDisplayMetrics(context, mMetrics); 1174 1175 synchronized (mInstallLock) { 1176 // writer 1177 synchronized (mPackages) { 1178 mHandlerThread = new ServiceThread(TAG, 1179 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1180 mHandlerThread.start(); 1181 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1182 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1183 1184 File dataDir = Environment.getDataDirectory(); 1185 mAppDataDir = new File(dataDir, "data"); 1186 mAppInstallDir = new File(dataDir, "app"); 1187 mAppLibInstallDir = new File(dataDir, "app-lib"); 1188 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1189 mUserAppDataDir = new File(dataDir, "user"); 1190 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1191 1192 sUserManager = new UserManagerService(context, this, 1193 mInstallLock, mPackages); 1194 1195 // Read permissions and features from system 1196 readPermissions(Environment.buildPath( 1197 Environment.getRootDirectory(), "etc", "permissions"), false); 1198 // Only read features from OEM 1199 readPermissions(Environment.buildPath( 1200 Environment.getOemDirectory(), "etc", "permissions"), true); 1201 1202 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1203 1204 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1205 mSdkVersion, mOnlyCore); 1206 1207 String customResolverActivity = Resources.getSystem().getString( 1208 R.string.config_customResolverActivity); 1209 if (TextUtils.isEmpty(customResolverActivity)) { 1210 customResolverActivity = null; 1211 } else { 1212 mCustomResolverComponentName = ComponentName.unflattenFromString( 1213 customResolverActivity); 1214 } 1215 1216 long startTime = SystemClock.uptimeMillis(); 1217 1218 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1219 startTime); 1220 1221 // Set flag to monitor and not change apk file paths when 1222 // scanning install directories. 1223 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1224 if (mNoDexOpt) { 1225 Slog.w(TAG, "Running ENG build: no pre-dexopt!"); 1226 scanMode |= SCAN_NO_DEX; 1227 } 1228 1229 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1230 1231 /** 1232 * Add everything in the in the boot class path to the 1233 * list of process files because dexopt will have been run 1234 * if necessary during zygote startup. 1235 */ 1236 String bootClassPath = System.getProperty("java.boot.class.path"); 1237 if (bootClassPath != null) { 1238 String[] paths = splitString(bootClassPath, ':'); 1239 for (int i=0; i<paths.length; i++) { 1240 alreadyDexOpted.add(paths[i]); 1241 } 1242 } else { 1243 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1244 } 1245 1246 boolean didDexOpt = false; 1247 1248 final List<String> instructionSets = getAllInstructionSets(); 1249 1250 /** 1251 * Ensure all external libraries have had dexopt run on them. 1252 */ 1253 if (mSharedLibraries.size() > 0) { 1254 // NOTE: For now, we're compiling these system "shared libraries" 1255 // (and framework jars) into all available architectures. It's possible 1256 // to compile them only when we come across an app that uses them (there's 1257 // already logic for that in scanPackageLI) but that adds some complexity. 1258 for (String instructionSet : instructionSets) { 1259 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1260 final String lib = libEntry.path; 1261 if (lib == null) { 1262 continue; 1263 } 1264 1265 try { 1266 if (dalvik.system.DexFile.isDexOptNeededInternal( 1267 lib, null, instructionSet, false)) { 1268 alreadyDexOpted.add(lib); 1269 1270 // The list of "shared libraries" we have at this point is 1271 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1272 didDexOpt = true; 1273 } 1274 } catch (FileNotFoundException e) { 1275 Slog.w(TAG, "Library not found: " + lib); 1276 } catch (IOException e) { 1277 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1278 + e.getMessage()); 1279 } 1280 } 1281 } 1282 } 1283 1284 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1285 1286 // Gross hack for now: we know this file doesn't contain any 1287 // code, so don't dexopt it to avoid the resulting log spew. 1288 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1289 1290 // Gross hack for now: we know this file is only part of 1291 // the boot class path for art, so don't dexopt it to 1292 // avoid the resulting log spew. 1293 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1294 1295 /** 1296 * And there are a number of commands implemented in Java, which 1297 * we currently need to do the dexopt on so that they can be 1298 * run from a non-root shell. 1299 */ 1300 String[] frameworkFiles = frameworkDir.list(); 1301 if (frameworkFiles != null) { 1302 // TODO: We could compile these only for the most preferred ABI. We should 1303 // first double check that the dex files for these commands are not referenced 1304 // by other system apps. 1305 for (String instructionSet : instructionSets) { 1306 for (int i=0; i<frameworkFiles.length; i++) { 1307 File libPath = new File(frameworkDir, frameworkFiles[i]); 1308 String path = libPath.getPath(); 1309 // Skip the file if we already did it. 1310 if (alreadyDexOpted.contains(path)) { 1311 continue; 1312 } 1313 // Skip the file if it is not a type we want to dexopt. 1314 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1315 continue; 1316 } 1317 try { 1318 if (dalvik.system.DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1319 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1320 didDexOpt = true; 1321 } 1322 } catch (FileNotFoundException e) { 1323 Slog.w(TAG, "Jar not found: " + path); 1324 } catch (IOException e) { 1325 Slog.w(TAG, "Exception reading jar: " + path, e); 1326 } 1327 } 1328 } 1329 } 1330 1331 if (didDexOpt) { 1332 pruneDexFiles(new File(dataDir, "dalvik-cache")); 1333 } 1334 1335 // Collect vendor overlay packages. 1336 // (Do this before scanning any apps.) 1337 // For security and version matching reason, only consider 1338 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1339 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1340 mVendorOverlayInstallObserver = new AppDirObserver( 1341 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1342 mVendorOverlayInstallObserver.startWatching(); 1343 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1344 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1345 1346 // Find base frameworks (resource packages without code). 1347 mFrameworkInstallObserver = new AppDirObserver( 1348 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1349 mFrameworkInstallObserver.startWatching(); 1350 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1351 | PackageParser.PARSE_IS_SYSTEM_DIR 1352 | PackageParser.PARSE_IS_PRIVILEGED, 1353 scanMode | SCAN_NO_DEX, 0); 1354 1355 // Collected privileged system packages. 1356 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1357 mPrivilegedInstallObserver = new AppDirObserver( 1358 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1359 mPrivilegedInstallObserver.startWatching(); 1360 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1361 | PackageParser.PARSE_IS_SYSTEM_DIR 1362 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1363 1364 // Collect ordinary system packages. 1365 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1366 mSystemInstallObserver = new AppDirObserver( 1367 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1368 mSystemInstallObserver.startWatching(); 1369 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1370 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1371 1372 // Collect all vendor packages. 1373 File vendorAppDir = new File("/vendor/app"); 1374 try { 1375 vendorAppDir = vendorAppDir.getCanonicalFile(); 1376 } catch (IOException e) { 1377 // failed to look up canonical path, continue with original one 1378 } 1379 mVendorInstallObserver = new AppDirObserver( 1380 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1381 mVendorInstallObserver.startWatching(); 1382 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1383 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1384 1385 // Collect all OEM packages. 1386 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1387 mOemInstallObserver = new AppDirObserver( 1388 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1389 mOemInstallObserver.startWatching(); 1390 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1391 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1392 1393 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1394 mInstaller.moveFiles(); 1395 1396 // Prune any system packages that no longer exist. 1397 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1398 if (!mOnlyCore) { 1399 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1400 while (psit.hasNext()) { 1401 PackageSetting ps = psit.next(); 1402 1403 /* 1404 * If this is not a system app, it can't be a 1405 * disable system app. 1406 */ 1407 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1408 continue; 1409 } 1410 1411 /* 1412 * If the package is scanned, it's not erased. 1413 */ 1414 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1415 if (scannedPkg != null) { 1416 /* 1417 * If the system app is both scanned and in the 1418 * disabled packages list, then it must have been 1419 * added via OTA. Remove it from the currently 1420 * scanned package so the previously user-installed 1421 * application can be scanned. 1422 */ 1423 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1424 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1425 + "; removing system app"); 1426 removePackageLI(ps, true); 1427 } 1428 1429 continue; 1430 } 1431 1432 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1433 psit.remove(); 1434 String msg = "System package " + ps.name 1435 + " no longer exists; wiping its data"; 1436 reportSettingsProblem(Log.WARN, msg); 1437 removeDataDirsLI(ps.name); 1438 } else { 1439 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1440 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1441 possiblyDeletedUpdatedSystemApps.add(ps.name); 1442 } 1443 } 1444 } 1445 } 1446 1447 //look for any incomplete package installations 1448 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1449 //clean up list 1450 for(int i = 0; i < deletePkgsList.size(); i++) { 1451 //clean up here 1452 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1453 } 1454 //delete tmp files 1455 deleteTempPackageFiles(); 1456 1457 // Remove any shared userIDs that have no associated packages 1458 mSettings.pruneSharedUsersLPw(); 1459 1460 if (!mOnlyCore) { 1461 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1462 SystemClock.uptimeMillis()); 1463 mAppInstallObserver = new AppDirObserver( 1464 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1465 mAppInstallObserver.startWatching(); 1466 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1467 1468 mDrmAppInstallObserver = new AppDirObserver( 1469 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1470 mDrmAppInstallObserver.startWatching(); 1471 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1472 scanMode, 0); 1473 1474 /** 1475 * Remove disable package settings for any updated system 1476 * apps that were removed via an OTA. If they're not a 1477 * previously-updated app, remove them completely. 1478 * Otherwise, just revoke their system-level permissions. 1479 */ 1480 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1481 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1482 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1483 1484 String msg; 1485 if (deletedPkg == null) { 1486 msg = "Updated system package " + deletedAppName 1487 + " no longer exists; wiping its data"; 1488 removeDataDirsLI(deletedAppName); 1489 } else { 1490 msg = "Updated system app + " + deletedAppName 1491 + " no longer present; removing system privileges for " 1492 + deletedAppName; 1493 1494 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1495 1496 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1497 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1498 } 1499 reportSettingsProblem(Log.WARN, msg); 1500 } 1501 } else { 1502 mAppInstallObserver = null; 1503 mDrmAppInstallObserver = null; 1504 } 1505 1506 // Now that we know all of the shared libraries, update all clients to have 1507 // the correct library paths. 1508 updateAllSharedLibrariesLPw(); 1509 1510 1511 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1512 adjustCpuAbisForSharedUserLPw(setting.packages, true /* do dexopt */, 1513 false /* force dexopt */, false /* defer dexopt */); 1514 } 1515 1516 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1517 SystemClock.uptimeMillis()); 1518 Slog.i(TAG, "Time to scan packages: " 1519 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1520 + " seconds"); 1521 1522 // If the platform SDK has changed since the last time we booted, 1523 // we need to re-grant app permission to catch any new ones that 1524 // appear. This is really a hack, and means that apps can in some 1525 // cases get permissions that the user didn't initially explicitly 1526 // allow... it would be nice to have some better way to handle 1527 // this situation. 1528 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1529 != mSdkVersion; 1530 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1531 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1532 + "; regranting permissions for internal storage"); 1533 mSettings.mInternalSdkPlatform = mSdkVersion; 1534 1535 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1536 | (regrantPermissions 1537 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1538 : 0)); 1539 1540 // If this is the first boot, and it is a normal boot, then 1541 // we need to initialize the default preferred apps. 1542 if (!mRestoredSettings && !onlyCore) { 1543 mSettings.readDefaultPreferredAppsLPw(this, 0); 1544 } 1545 1546 // All the changes are done during package scanning. 1547 mSettings.updateInternalDatabaseVersion(); 1548 1549 // can downgrade to reader 1550 mSettings.writeLPr(); 1551 1552 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1553 SystemClock.uptimeMillis()); 1554 1555 // Now after opening every single application zip, make sure they 1556 // are all flushed. Not really needed, but keeps things nice and 1557 // tidy. 1558 Runtime.getRuntime().gc(); 1559 1560 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1561 } // synchronized (mPackages) 1562 } // synchronized (mInstallLock) 1563 } 1564 1565 private static void pruneDexFiles(File cacheDir) { 1566 // If we had to do a dexopt of one of the previous 1567 // things, then something on the system has changed. 1568 // Consider this significant, and wipe away all other 1569 // existing dexopt files to ensure we don't leave any 1570 // dangling around. 1571 // 1572 // Additionally, delete all dex files from the root directory 1573 // since there shouldn't be any there anyway. 1574 File[] files = cacheDir.listFiles(); 1575 if (files != null) { 1576 for (File file : files) { 1577 if (!file.isDirectory()) { 1578 Slog.i(TAG, "Pruning dalvik file: " + file.getAbsolutePath()); 1579 file.delete(); 1580 } else { 1581 File[] subDirList = file.listFiles(); 1582 if (subDirList != null) { 1583 for (File subDirFile : subDirList) { 1584 final String fn = subDirFile.getName(); 1585 if (fn.startsWith("data@app@") || fn.startsWith("data@app-private@")) { 1586 Slog.i(TAG, "Pruning dalvik file: " + fn); 1587 subDirFile.delete(); 1588 } 1589 } 1590 } 1591 } 1592 } 1593 } 1594 } 1595 1596 public boolean isFirstBoot() { 1597 return !mRestoredSettings; 1598 } 1599 1600 public boolean isOnlyCoreApps() { 1601 return mOnlyCore; 1602 } 1603 1604 private String getRequiredVerifierLPr() { 1605 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1606 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1607 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1608 1609 String requiredVerifier = null; 1610 1611 final int N = receivers.size(); 1612 for (int i = 0; i < N; i++) { 1613 final ResolveInfo info = receivers.get(i); 1614 1615 if (info.activityInfo == null) { 1616 continue; 1617 } 1618 1619 final String packageName = info.activityInfo.packageName; 1620 1621 final PackageSetting ps = mSettings.mPackages.get(packageName); 1622 if (ps == null) { 1623 continue; 1624 } 1625 1626 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1627 if (!gp.grantedPermissions 1628 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1629 continue; 1630 } 1631 1632 if (requiredVerifier != null) { 1633 throw new RuntimeException("There can be only one required verifier"); 1634 } 1635 1636 requiredVerifier = packageName; 1637 } 1638 1639 return requiredVerifier; 1640 } 1641 1642 @Override 1643 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1644 throws RemoteException { 1645 try { 1646 return super.onTransact(code, data, reply, flags); 1647 } catch (RuntimeException e) { 1648 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1649 Slog.wtf(TAG, "Package Manager Crash", e); 1650 } 1651 throw e; 1652 } 1653 } 1654 1655 void cleanupInstallFailedPackage(PackageSetting ps) { 1656 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1657 removeDataDirsLI(ps.name); 1658 if (ps.codePath != null) { 1659 if (!ps.codePath.delete()) { 1660 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1661 } 1662 } 1663 if (ps.resourcePath != null) { 1664 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1665 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1666 } 1667 } 1668 mSettings.removePackageLPw(ps.name); 1669 } 1670 1671 void readPermissions(File libraryDir, boolean onlyFeatures) { 1672 // Read permissions from .../etc/permission directory. 1673 if (!libraryDir.exists() || !libraryDir.isDirectory()) { 1674 Slog.w(TAG, "No directory " + libraryDir + ", skipping"); 1675 return; 1676 } 1677 if (!libraryDir.canRead()) { 1678 Slog.w(TAG, "Directory " + libraryDir + " cannot be read"); 1679 return; 1680 } 1681 1682 // Iterate over the files in the directory and scan .xml files 1683 for (File f : libraryDir.listFiles()) { 1684 // We'll read platform.xml last 1685 if (f.getPath().endsWith("etc/permissions/platform.xml")) { 1686 continue; 1687 } 1688 1689 if (!f.getPath().endsWith(".xml")) { 1690 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring"); 1691 continue; 1692 } 1693 if (!f.canRead()) { 1694 Slog.w(TAG, "Permissions library file " + f + " cannot be read"); 1695 continue; 1696 } 1697 1698 readPermissionsFromXml(f, onlyFeatures); 1699 } 1700 1701 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence 1702 final File permFile = new File(Environment.getRootDirectory(), 1703 "etc/permissions/platform.xml"); 1704 readPermissionsFromXml(permFile, onlyFeatures); 1705 } 1706 1707 private void readPermissionsFromXml(File permFile, boolean onlyFeatures) { 1708 FileReader permReader = null; 1709 try { 1710 permReader = new FileReader(permFile); 1711 } catch (FileNotFoundException e) { 1712 Slog.w(TAG, "Couldn't find or open permissions file " + permFile); 1713 return; 1714 } 1715 1716 try { 1717 XmlPullParser parser = Xml.newPullParser(); 1718 parser.setInput(permReader); 1719 1720 XmlUtils.beginDocument(parser, "permissions"); 1721 1722 while (true) { 1723 XmlUtils.nextElement(parser); 1724 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) { 1725 break; 1726 } 1727 1728 String name = parser.getName(); 1729 if ("group".equals(name) && !onlyFeatures) { 1730 String gidStr = parser.getAttributeValue(null, "gid"); 1731 if (gidStr != null) { 1732 int gid = Process.getGidForName(gidStr); 1733 mGlobalGids = appendInt(mGlobalGids, gid); 1734 } else { 1735 Slog.w(TAG, "<group> without gid at " 1736 + parser.getPositionDescription()); 1737 } 1738 1739 XmlUtils.skipCurrentTag(parser); 1740 continue; 1741 } else if ("permission".equals(name) && !onlyFeatures) { 1742 String perm = parser.getAttributeValue(null, "name"); 1743 if (perm == null) { 1744 Slog.w(TAG, "<permission> without name at " 1745 + parser.getPositionDescription()); 1746 XmlUtils.skipCurrentTag(parser); 1747 continue; 1748 } 1749 perm = perm.intern(); 1750 readPermission(parser, perm); 1751 1752 } else if ("assign-permission".equals(name) && !onlyFeatures) { 1753 String perm = parser.getAttributeValue(null, "name"); 1754 if (perm == null) { 1755 Slog.w(TAG, "<assign-permission> without name at " 1756 + parser.getPositionDescription()); 1757 XmlUtils.skipCurrentTag(parser); 1758 continue; 1759 } 1760 String uidStr = parser.getAttributeValue(null, "uid"); 1761 if (uidStr == null) { 1762 Slog.w(TAG, "<assign-permission> without uid at " 1763 + parser.getPositionDescription()); 1764 XmlUtils.skipCurrentTag(parser); 1765 continue; 1766 } 1767 int uid = Process.getUidForName(uidStr); 1768 if (uid < 0) { 1769 Slog.w(TAG, "<assign-permission> with unknown uid \"" 1770 + uidStr + "\" at " 1771 + parser.getPositionDescription()); 1772 XmlUtils.skipCurrentTag(parser); 1773 continue; 1774 } 1775 perm = perm.intern(); 1776 HashSet<String> perms = mSystemPermissions.get(uid); 1777 if (perms == null) { 1778 perms = new HashSet<String>(); 1779 mSystemPermissions.put(uid, perms); 1780 } 1781 perms.add(perm); 1782 XmlUtils.skipCurrentTag(parser); 1783 1784 } else if ("library".equals(name) && !onlyFeatures) { 1785 String lname = parser.getAttributeValue(null, "name"); 1786 String lfile = parser.getAttributeValue(null, "file"); 1787 if (lname == null) { 1788 Slog.w(TAG, "<library> without name at " 1789 + parser.getPositionDescription()); 1790 } else if (lfile == null) { 1791 Slog.w(TAG, "<library> without file at " 1792 + parser.getPositionDescription()); 1793 } else { 1794 //Log.i(TAG, "Got library " + lname + " in " + lfile); 1795 mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null)); 1796 } 1797 XmlUtils.skipCurrentTag(parser); 1798 continue; 1799 1800 } else if ("feature".equals(name)) { 1801 String fname = parser.getAttributeValue(null, "name"); 1802 if (fname == null) { 1803 Slog.w(TAG, "<feature> without name at " 1804 + parser.getPositionDescription()); 1805 } else { 1806 //Log.i(TAG, "Got feature " + fname); 1807 FeatureInfo fi = new FeatureInfo(); 1808 fi.name = fname; 1809 mAvailableFeatures.put(fname, fi); 1810 } 1811 XmlUtils.skipCurrentTag(parser); 1812 continue; 1813 1814 } else { 1815 XmlUtils.skipCurrentTag(parser); 1816 continue; 1817 } 1818 1819 } 1820 permReader.close(); 1821 } catch (XmlPullParserException e) { 1822 Slog.w(TAG, "Got execption parsing permissions.", e); 1823 } catch (IOException e) { 1824 Slog.w(TAG, "Got execption parsing permissions.", e); 1825 } 1826 } 1827 1828 void readPermission(XmlPullParser parser, String name) 1829 throws IOException, XmlPullParserException { 1830 1831 name = name.intern(); 1832 1833 BasePermission bp = mSettings.mPermissions.get(name); 1834 if (bp == null) { 1835 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN); 1836 mSettings.mPermissions.put(name, bp); 1837 } 1838 int outerDepth = parser.getDepth(); 1839 int type; 1840 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 1841 && (type != XmlPullParser.END_TAG 1842 || parser.getDepth() > outerDepth)) { 1843 if (type == XmlPullParser.END_TAG 1844 || type == XmlPullParser.TEXT) { 1845 continue; 1846 } 1847 1848 String tagName = parser.getName(); 1849 if ("group".equals(tagName)) { 1850 String gidStr = parser.getAttributeValue(null, "gid"); 1851 if (gidStr != null) { 1852 int gid = Process.getGidForName(gidStr); 1853 bp.gids = appendInt(bp.gids, gid); 1854 } else { 1855 Slog.w(TAG, "<group> without gid at " 1856 + parser.getPositionDescription()); 1857 } 1858 } 1859 XmlUtils.skipCurrentTag(parser); 1860 } 1861 } 1862 1863 static int[] appendInts(int[] cur, int[] add) { 1864 if (add == null) return cur; 1865 if (cur == null) return add; 1866 final int N = add.length; 1867 for (int i=0; i<N; i++) { 1868 cur = appendInt(cur, add[i]); 1869 } 1870 return cur; 1871 } 1872 1873 static int[] removeInts(int[] cur, int[] rem) { 1874 if (rem == null) return cur; 1875 if (cur == null) return cur; 1876 final int N = rem.length; 1877 for (int i=0; i<N; i++) { 1878 cur = removeInt(cur, rem[i]); 1879 } 1880 return cur; 1881 } 1882 1883 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1884 if (!sUserManager.exists(userId)) return null; 1885 final PackageSetting ps = (PackageSetting) p.mExtras; 1886 if (ps == null) { 1887 return null; 1888 } 1889 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1890 final PackageUserState state = ps.readUserState(userId); 1891 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1892 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1893 state, userId); 1894 } 1895 1896 public boolean isPackageAvailable(String packageName, int userId) { 1897 if (!sUserManager.exists(userId)) return false; 1898 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1899 synchronized (mPackages) { 1900 PackageParser.Package p = mPackages.get(packageName); 1901 if (p != null) { 1902 final PackageSetting ps = (PackageSetting) p.mExtras; 1903 if (ps != null) { 1904 final PackageUserState state = ps.readUserState(userId); 1905 if (state != null) { 1906 return PackageParser.isAvailable(state); 1907 } 1908 } 1909 } 1910 } 1911 return false; 1912 } 1913 1914 @Override 1915 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1916 if (!sUserManager.exists(userId)) return null; 1917 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1918 // reader 1919 synchronized (mPackages) { 1920 PackageParser.Package p = mPackages.get(packageName); 1921 if (DEBUG_PACKAGE_INFO) 1922 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1923 if (p != null) { 1924 return generatePackageInfo(p, flags, userId); 1925 } 1926 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1927 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1928 } 1929 } 1930 return null; 1931 } 1932 1933 public String[] currentToCanonicalPackageNames(String[] names) { 1934 String[] out = new String[names.length]; 1935 // reader 1936 synchronized (mPackages) { 1937 for (int i=names.length-1; i>=0; i--) { 1938 PackageSetting ps = mSettings.mPackages.get(names[i]); 1939 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1940 } 1941 } 1942 return out; 1943 } 1944 1945 public String[] canonicalToCurrentPackageNames(String[] names) { 1946 String[] out = new String[names.length]; 1947 // reader 1948 synchronized (mPackages) { 1949 for (int i=names.length-1; i>=0; i--) { 1950 String cur = mSettings.mRenamedPackages.get(names[i]); 1951 out[i] = cur != null ? cur : names[i]; 1952 } 1953 } 1954 return out; 1955 } 1956 1957 @Override 1958 public int getPackageUid(String packageName, int userId) { 1959 if (!sUserManager.exists(userId)) return -1; 1960 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1961 // reader 1962 synchronized (mPackages) { 1963 PackageParser.Package p = mPackages.get(packageName); 1964 if(p != null) { 1965 return UserHandle.getUid(userId, p.applicationInfo.uid); 1966 } 1967 PackageSetting ps = mSettings.mPackages.get(packageName); 1968 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1969 return -1; 1970 } 1971 p = ps.pkg; 1972 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1973 } 1974 } 1975 1976 @Override 1977 public int[] getPackageGids(String packageName) { 1978 // reader 1979 synchronized (mPackages) { 1980 PackageParser.Package p = mPackages.get(packageName); 1981 if (DEBUG_PACKAGE_INFO) 1982 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1983 if (p != null) { 1984 final PackageSetting ps = (PackageSetting)p.mExtras; 1985 return ps.getGids(); 1986 } 1987 } 1988 // stupid thing to indicate an error. 1989 return new int[0]; 1990 } 1991 1992 static final PermissionInfo generatePermissionInfo( 1993 BasePermission bp, int flags) { 1994 if (bp.perm != null) { 1995 return PackageParser.generatePermissionInfo(bp.perm, flags); 1996 } 1997 PermissionInfo pi = new PermissionInfo(); 1998 pi.name = bp.name; 1999 pi.packageName = bp.sourcePackage; 2000 pi.nonLocalizedLabel = bp.name; 2001 pi.protectionLevel = bp.protectionLevel; 2002 return pi; 2003 } 2004 2005 public PermissionInfo getPermissionInfo(String name, int flags) { 2006 // reader 2007 synchronized (mPackages) { 2008 final BasePermission p = mSettings.mPermissions.get(name); 2009 if (p != null) { 2010 return generatePermissionInfo(p, flags); 2011 } 2012 return null; 2013 } 2014 } 2015 2016 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2017 // reader 2018 synchronized (mPackages) { 2019 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2020 for (BasePermission p : mSettings.mPermissions.values()) { 2021 if (group == null) { 2022 if (p.perm == null || p.perm.info.group == null) { 2023 out.add(generatePermissionInfo(p, flags)); 2024 } 2025 } else { 2026 if (p.perm != null && group.equals(p.perm.info.group)) { 2027 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2028 } 2029 } 2030 } 2031 2032 if (out.size() > 0) { 2033 return out; 2034 } 2035 return mPermissionGroups.containsKey(group) ? out : null; 2036 } 2037 } 2038 2039 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2040 // reader 2041 synchronized (mPackages) { 2042 return PackageParser.generatePermissionGroupInfo( 2043 mPermissionGroups.get(name), flags); 2044 } 2045 } 2046 2047 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2048 // reader 2049 synchronized (mPackages) { 2050 final int N = mPermissionGroups.size(); 2051 ArrayList<PermissionGroupInfo> out 2052 = new ArrayList<PermissionGroupInfo>(N); 2053 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2054 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2055 } 2056 return out; 2057 } 2058 } 2059 2060 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2061 int userId) { 2062 if (!sUserManager.exists(userId)) return null; 2063 PackageSetting ps = mSettings.mPackages.get(packageName); 2064 if (ps != null) { 2065 if (ps.pkg == null) { 2066 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2067 flags, userId); 2068 if (pInfo != null) { 2069 return pInfo.applicationInfo; 2070 } 2071 return null; 2072 } 2073 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2074 ps.readUserState(userId), userId); 2075 } 2076 return null; 2077 } 2078 2079 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2080 int userId) { 2081 if (!sUserManager.exists(userId)) return null; 2082 PackageSetting ps = mSettings.mPackages.get(packageName); 2083 if (ps != null) { 2084 PackageParser.Package pkg = ps.pkg; 2085 if (pkg == null) { 2086 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2087 return null; 2088 } 2089 pkg = new PackageParser.Package(packageName); 2090 pkg.applicationInfo.packageName = packageName; 2091 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2092 pkg.applicationInfo.publicSourceDir = ps.resourcePathString; 2093 pkg.applicationInfo.sourceDir = ps.codePathString; 2094 pkg.applicationInfo.dataDir = 2095 getDataPathForPackage(packageName, 0).getPath(); 2096 pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString; 2097 pkg.applicationInfo.requiredCpuAbi = ps.requiredCpuAbiString; 2098 } 2099 return generatePackageInfo(pkg, flags, userId); 2100 } 2101 return null; 2102 } 2103 2104 @Override 2105 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2106 if (!sUserManager.exists(userId)) return null; 2107 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2108 // writer 2109 synchronized (mPackages) { 2110 PackageParser.Package p = mPackages.get(packageName); 2111 if (DEBUG_PACKAGE_INFO) Log.v( 2112 TAG, "getApplicationInfo " + packageName 2113 + ": " + p); 2114 if (p != null) { 2115 PackageSetting ps = mSettings.mPackages.get(packageName); 2116 if (ps == null) return null; 2117 // Note: isEnabledLP() does not apply here - always return info 2118 return PackageParser.generateApplicationInfo( 2119 p, flags, ps.readUserState(userId), userId); 2120 } 2121 if ("android".equals(packageName)||"system".equals(packageName)) { 2122 return mAndroidApplication; 2123 } 2124 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2125 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2126 } 2127 } 2128 return null; 2129 } 2130 2131 2132 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2133 mContext.enforceCallingOrSelfPermission( 2134 android.Manifest.permission.CLEAR_APP_CACHE, null); 2135 // Queue up an async operation since clearing cache may take a little while. 2136 mHandler.post(new Runnable() { 2137 public void run() { 2138 mHandler.removeCallbacks(this); 2139 int retCode = -1; 2140 synchronized (mInstallLock) { 2141 retCode = mInstaller.freeCache(freeStorageSize); 2142 if (retCode < 0) { 2143 Slog.w(TAG, "Couldn't clear application caches"); 2144 } 2145 } 2146 if (observer != null) { 2147 try { 2148 observer.onRemoveCompleted(null, (retCode >= 0)); 2149 } catch (RemoteException e) { 2150 Slog.w(TAG, "RemoveException when invoking call back"); 2151 } 2152 } 2153 } 2154 }); 2155 } 2156 2157 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2158 mContext.enforceCallingOrSelfPermission( 2159 android.Manifest.permission.CLEAR_APP_CACHE, null); 2160 // Queue up an async operation since clearing cache may take a little while. 2161 mHandler.post(new Runnable() { 2162 public void run() { 2163 mHandler.removeCallbacks(this); 2164 int retCode = -1; 2165 synchronized (mInstallLock) { 2166 retCode = mInstaller.freeCache(freeStorageSize); 2167 if (retCode < 0) { 2168 Slog.w(TAG, "Couldn't clear application caches"); 2169 } 2170 } 2171 if(pi != null) { 2172 try { 2173 // Callback via pending intent 2174 int code = (retCode >= 0) ? 1 : 0; 2175 pi.sendIntent(null, code, null, 2176 null, null); 2177 } catch (SendIntentException e1) { 2178 Slog.i(TAG, "Failed to send pending intent"); 2179 } 2180 } 2181 } 2182 }); 2183 } 2184 2185 @Override 2186 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2187 if (!sUserManager.exists(userId)) return null; 2188 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2189 synchronized (mPackages) { 2190 PackageParser.Activity a = mActivities.mActivities.get(component); 2191 2192 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2193 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2194 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2195 if (ps == null) return null; 2196 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2197 userId); 2198 } 2199 if (mResolveComponentName.equals(component)) { 2200 return mResolveActivity; 2201 } 2202 } 2203 return null; 2204 } 2205 2206 @Override 2207 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2208 String resolvedType) { 2209 synchronized (mPackages) { 2210 PackageParser.Activity a = mActivities.mActivities.get(component); 2211 if (a == null) { 2212 return false; 2213 } 2214 for (int i=0; i<a.intents.size(); i++) { 2215 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2216 intent.getData(), intent.getCategories(), TAG) >= 0) { 2217 return true; 2218 } 2219 } 2220 return false; 2221 } 2222 } 2223 2224 @Override 2225 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2226 if (!sUserManager.exists(userId)) return null; 2227 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2228 synchronized (mPackages) { 2229 PackageParser.Activity a = mReceivers.mActivities.get(component); 2230 if (DEBUG_PACKAGE_INFO) Log.v( 2231 TAG, "getReceiverInfo " + component + ": " + a); 2232 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2233 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2234 if (ps == null) return null; 2235 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2236 userId); 2237 } 2238 } 2239 return null; 2240 } 2241 2242 @Override 2243 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2244 if (!sUserManager.exists(userId)) return null; 2245 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2246 synchronized (mPackages) { 2247 PackageParser.Service s = mServices.mServices.get(component); 2248 if (DEBUG_PACKAGE_INFO) Log.v( 2249 TAG, "getServiceInfo " + component + ": " + s); 2250 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2251 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2252 if (ps == null) return null; 2253 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2254 userId); 2255 } 2256 } 2257 return null; 2258 } 2259 2260 @Override 2261 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2262 if (!sUserManager.exists(userId)) return null; 2263 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2264 synchronized (mPackages) { 2265 PackageParser.Provider p = mProviders.mProviders.get(component); 2266 if (DEBUG_PACKAGE_INFO) Log.v( 2267 TAG, "getProviderInfo " + component + ": " + p); 2268 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2269 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2270 if (ps == null) return null; 2271 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2272 userId); 2273 } 2274 } 2275 return null; 2276 } 2277 2278 public String[] getSystemSharedLibraryNames() { 2279 Set<String> libSet; 2280 synchronized (mPackages) { 2281 libSet = mSharedLibraries.keySet(); 2282 int size = libSet.size(); 2283 if (size > 0) { 2284 String[] libs = new String[size]; 2285 libSet.toArray(libs); 2286 return libs; 2287 } 2288 } 2289 return null; 2290 } 2291 2292 public FeatureInfo[] getSystemAvailableFeatures() { 2293 Collection<FeatureInfo> featSet; 2294 synchronized (mPackages) { 2295 featSet = mAvailableFeatures.values(); 2296 int size = featSet.size(); 2297 if (size > 0) { 2298 FeatureInfo[] features = new FeatureInfo[size+1]; 2299 featSet.toArray(features); 2300 FeatureInfo fi = new FeatureInfo(); 2301 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2302 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2303 features[size] = fi; 2304 return features; 2305 } 2306 } 2307 return null; 2308 } 2309 2310 public boolean hasSystemFeature(String name) { 2311 synchronized (mPackages) { 2312 return mAvailableFeatures.containsKey(name); 2313 } 2314 } 2315 2316 private void checkValidCaller(int uid, int userId) { 2317 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2318 return; 2319 2320 throw new SecurityException("Caller uid=" + uid 2321 + " is not privileged to communicate with user=" + userId); 2322 } 2323 2324 public int checkPermission(String permName, String pkgName) { 2325 synchronized (mPackages) { 2326 PackageParser.Package p = mPackages.get(pkgName); 2327 if (p != null && p.mExtras != null) { 2328 PackageSetting ps = (PackageSetting)p.mExtras; 2329 if (ps.sharedUser != null) { 2330 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2331 return PackageManager.PERMISSION_GRANTED; 2332 } 2333 } else if (ps.grantedPermissions.contains(permName)) { 2334 return PackageManager.PERMISSION_GRANTED; 2335 } 2336 } 2337 } 2338 return PackageManager.PERMISSION_DENIED; 2339 } 2340 2341 public int checkUidPermission(String permName, int uid) { 2342 synchronized (mPackages) { 2343 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2344 if (obj != null) { 2345 GrantedPermissions gp = (GrantedPermissions)obj; 2346 if (gp.grantedPermissions.contains(permName)) { 2347 return PackageManager.PERMISSION_GRANTED; 2348 } 2349 } else { 2350 HashSet<String> perms = mSystemPermissions.get(uid); 2351 if (perms != null && perms.contains(permName)) { 2352 return PackageManager.PERMISSION_GRANTED; 2353 } 2354 } 2355 } 2356 return PackageManager.PERMISSION_DENIED; 2357 } 2358 2359 /** 2360 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2361 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2362 * @param message the message to log on security exception 2363 * @return 2364 */ 2365 private void enforceCrossUserPermission(int callingUid, int userId, 2366 boolean requireFullPermission, String message) { 2367 if (userId < 0) { 2368 throw new IllegalArgumentException("Invalid userId " + userId); 2369 } 2370 if (userId == UserHandle.getUserId(callingUid)) return; 2371 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2372 if (requireFullPermission) { 2373 mContext.enforceCallingOrSelfPermission( 2374 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2375 } else { 2376 try { 2377 mContext.enforceCallingOrSelfPermission( 2378 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2379 } catch (SecurityException se) { 2380 mContext.enforceCallingOrSelfPermission( 2381 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2382 } 2383 } 2384 } 2385 } 2386 2387 private BasePermission findPermissionTreeLP(String permName) { 2388 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2389 if (permName.startsWith(bp.name) && 2390 permName.length() > bp.name.length() && 2391 permName.charAt(bp.name.length()) == '.') { 2392 return bp; 2393 } 2394 } 2395 return null; 2396 } 2397 2398 private BasePermission checkPermissionTreeLP(String permName) { 2399 if (permName != null) { 2400 BasePermission bp = findPermissionTreeLP(permName); 2401 if (bp != null) { 2402 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2403 return bp; 2404 } 2405 throw new SecurityException("Calling uid " 2406 + Binder.getCallingUid() 2407 + " is not allowed to add to permission tree " 2408 + bp.name + " owned by uid " + bp.uid); 2409 } 2410 } 2411 throw new SecurityException("No permission tree found for " + permName); 2412 } 2413 2414 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2415 if (s1 == null) { 2416 return s2 == null; 2417 } 2418 if (s2 == null) { 2419 return false; 2420 } 2421 if (s1.getClass() != s2.getClass()) { 2422 return false; 2423 } 2424 return s1.equals(s2); 2425 } 2426 2427 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2428 if (pi1.icon != pi2.icon) return false; 2429 if (pi1.logo != pi2.logo) return false; 2430 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2431 if (!compareStrings(pi1.name, pi2.name)) return false; 2432 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2433 // We'll take care of setting this one. 2434 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2435 // These are not currently stored in settings. 2436 //if (!compareStrings(pi1.group, pi2.group)) return false; 2437 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2438 //if (pi1.labelRes != pi2.labelRes) return false; 2439 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2440 return true; 2441 } 2442 2443 int permissionInfoFootprint(PermissionInfo info) { 2444 int size = info.name.length(); 2445 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2446 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2447 return size; 2448 } 2449 2450 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2451 int size = 0; 2452 for (BasePermission perm : mSettings.mPermissions.values()) { 2453 if (perm.uid == tree.uid) { 2454 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2455 } 2456 } 2457 return size; 2458 } 2459 2460 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2461 // We calculate the max size of permissions defined by this uid and throw 2462 // if that plus the size of 'info' would exceed our stated maximum. 2463 if (tree.uid != Process.SYSTEM_UID) { 2464 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2465 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2466 throw new SecurityException("Permission tree size cap exceeded"); 2467 } 2468 } 2469 } 2470 2471 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2472 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2473 throw new SecurityException("Label must be specified in permission"); 2474 } 2475 BasePermission tree = checkPermissionTreeLP(info.name); 2476 BasePermission bp = mSettings.mPermissions.get(info.name); 2477 boolean added = bp == null; 2478 boolean changed = true; 2479 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2480 if (added) { 2481 enforcePermissionCapLocked(info, tree); 2482 bp = new BasePermission(info.name, tree.sourcePackage, 2483 BasePermission.TYPE_DYNAMIC); 2484 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2485 throw new SecurityException( 2486 "Not allowed to modify non-dynamic permission " 2487 + info.name); 2488 } else { 2489 if (bp.protectionLevel == fixedLevel 2490 && bp.perm.owner.equals(tree.perm.owner) 2491 && bp.uid == tree.uid 2492 && comparePermissionInfos(bp.perm.info, info)) { 2493 changed = false; 2494 } 2495 } 2496 bp.protectionLevel = fixedLevel; 2497 info = new PermissionInfo(info); 2498 info.protectionLevel = fixedLevel; 2499 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2500 bp.perm.info.packageName = tree.perm.info.packageName; 2501 bp.uid = tree.uid; 2502 if (added) { 2503 mSettings.mPermissions.put(info.name, bp); 2504 } 2505 if (changed) { 2506 if (!async) { 2507 mSettings.writeLPr(); 2508 } else { 2509 scheduleWriteSettingsLocked(); 2510 } 2511 } 2512 return added; 2513 } 2514 2515 public boolean addPermission(PermissionInfo info) { 2516 synchronized (mPackages) { 2517 return addPermissionLocked(info, false); 2518 } 2519 } 2520 2521 public boolean addPermissionAsync(PermissionInfo info) { 2522 synchronized (mPackages) { 2523 return addPermissionLocked(info, true); 2524 } 2525 } 2526 2527 public void removePermission(String name) { 2528 synchronized (mPackages) { 2529 checkPermissionTreeLP(name); 2530 BasePermission bp = mSettings.mPermissions.get(name); 2531 if (bp != null) { 2532 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2533 throw new SecurityException( 2534 "Not allowed to modify non-dynamic permission " 2535 + name); 2536 } 2537 mSettings.mPermissions.remove(name); 2538 mSettings.writeLPr(); 2539 } 2540 } 2541 } 2542 2543 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2544 int index = pkg.requestedPermissions.indexOf(bp.name); 2545 if (index == -1) { 2546 throw new SecurityException("Package " + pkg.packageName 2547 + " has not requested permission " + bp.name); 2548 } 2549 boolean isNormal = 2550 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2551 == PermissionInfo.PROTECTION_NORMAL); 2552 boolean isDangerous = 2553 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2554 == PermissionInfo.PROTECTION_DANGEROUS); 2555 boolean isDevelopment = 2556 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2557 2558 if (!isNormal && !isDangerous && !isDevelopment) { 2559 throw new SecurityException("Permission " + bp.name 2560 + " is not a changeable permission type"); 2561 } 2562 2563 if (isNormal || isDangerous) { 2564 if (pkg.requestedPermissionsRequired.get(index)) { 2565 throw new SecurityException("Can't change " + bp.name 2566 + ". It is required by the application"); 2567 } 2568 } 2569 } 2570 2571 public void grantPermission(String packageName, String permissionName) { 2572 mContext.enforceCallingOrSelfPermission( 2573 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2574 synchronized (mPackages) { 2575 final PackageParser.Package pkg = mPackages.get(packageName); 2576 if (pkg == null) { 2577 throw new IllegalArgumentException("Unknown package: " + packageName); 2578 } 2579 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2580 if (bp == null) { 2581 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2582 } 2583 2584 checkGrantRevokePermissions(pkg, bp); 2585 2586 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2587 if (ps == null) { 2588 return; 2589 } 2590 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2591 if (gp.grantedPermissions.add(permissionName)) { 2592 if (ps.haveGids) { 2593 gp.gids = appendInts(gp.gids, bp.gids); 2594 } 2595 mSettings.writeLPr(); 2596 } 2597 } 2598 } 2599 2600 public void revokePermission(String packageName, String permissionName) { 2601 int changedAppId = -1; 2602 2603 synchronized (mPackages) { 2604 final PackageParser.Package pkg = mPackages.get(packageName); 2605 if (pkg == null) { 2606 throw new IllegalArgumentException("Unknown package: " + packageName); 2607 } 2608 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2609 mContext.enforceCallingOrSelfPermission( 2610 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2611 } 2612 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2613 if (bp == null) { 2614 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2615 } 2616 2617 checkGrantRevokePermissions(pkg, bp); 2618 2619 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2620 if (ps == null) { 2621 return; 2622 } 2623 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2624 if (gp.grantedPermissions.remove(permissionName)) { 2625 gp.grantedPermissions.remove(permissionName); 2626 if (ps.haveGids) { 2627 gp.gids = removeInts(gp.gids, bp.gids); 2628 } 2629 mSettings.writeLPr(); 2630 changedAppId = ps.appId; 2631 } 2632 } 2633 2634 if (changedAppId >= 0) { 2635 // We changed the perm on someone, kill its processes. 2636 IActivityManager am = ActivityManagerNative.getDefault(); 2637 if (am != null) { 2638 final int callingUserId = UserHandle.getCallingUserId(); 2639 final long ident = Binder.clearCallingIdentity(); 2640 try { 2641 //XXX we should only revoke for the calling user's app permissions, 2642 // but for now we impact all users. 2643 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2644 // "revoke " + permissionName); 2645 int[] users = sUserManager.getUserIds(); 2646 for (int user : users) { 2647 am.killUid(UserHandle.getUid(user, changedAppId), 2648 "revoke " + permissionName); 2649 } 2650 } catch (RemoteException e) { 2651 } finally { 2652 Binder.restoreCallingIdentity(ident); 2653 } 2654 } 2655 } 2656 } 2657 2658 public boolean isProtectedBroadcast(String actionName) { 2659 synchronized (mPackages) { 2660 return mProtectedBroadcasts.contains(actionName); 2661 } 2662 } 2663 2664 public int checkSignatures(String pkg1, String pkg2) { 2665 synchronized (mPackages) { 2666 final PackageParser.Package p1 = mPackages.get(pkg1); 2667 final PackageParser.Package p2 = mPackages.get(pkg2); 2668 if (p1 == null || p1.mExtras == null 2669 || p2 == null || p2.mExtras == null) { 2670 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2671 } 2672 return compareSignatures(p1.mSignatures, p2.mSignatures); 2673 } 2674 } 2675 2676 public int checkUidSignatures(int uid1, int uid2) { 2677 // Map to base uids. 2678 uid1 = UserHandle.getAppId(uid1); 2679 uid2 = UserHandle.getAppId(uid2); 2680 // reader 2681 synchronized (mPackages) { 2682 Signature[] s1; 2683 Signature[] s2; 2684 Object obj = mSettings.getUserIdLPr(uid1); 2685 if (obj != null) { 2686 if (obj instanceof SharedUserSetting) { 2687 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2688 } else if (obj instanceof PackageSetting) { 2689 s1 = ((PackageSetting)obj).signatures.mSignatures; 2690 } else { 2691 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2692 } 2693 } else { 2694 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2695 } 2696 obj = mSettings.getUserIdLPr(uid2); 2697 if (obj != null) { 2698 if (obj instanceof SharedUserSetting) { 2699 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2700 } else if (obj instanceof PackageSetting) { 2701 s2 = ((PackageSetting)obj).signatures.mSignatures; 2702 } else { 2703 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2704 } 2705 } else { 2706 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2707 } 2708 return compareSignatures(s1, s2); 2709 } 2710 } 2711 2712 /** 2713 * Compares two sets of signatures. Returns: 2714 * <br /> 2715 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2716 * <br /> 2717 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2718 * <br /> 2719 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2720 * <br /> 2721 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2722 * <br /> 2723 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2724 */ 2725 static int compareSignatures(Signature[] s1, Signature[] s2) { 2726 if (s1 == null) { 2727 return s2 == null 2728 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2729 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2730 } 2731 2732 if (s2 == null) { 2733 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2734 } 2735 2736 if (s1.length != s2.length) { 2737 return PackageManager.SIGNATURE_NO_MATCH; 2738 } 2739 2740 // Since both signature sets are of size 1, we can compare without HashSets. 2741 if (s1.length == 1) { 2742 return s1[0].equals(s2[0]) ? 2743 PackageManager.SIGNATURE_MATCH : 2744 PackageManager.SIGNATURE_NO_MATCH; 2745 } 2746 2747 HashSet<Signature> set1 = new HashSet<Signature>(); 2748 for (Signature sig : s1) { 2749 set1.add(sig); 2750 } 2751 HashSet<Signature> set2 = new HashSet<Signature>(); 2752 for (Signature sig : s2) { 2753 set2.add(sig); 2754 } 2755 // Make sure s2 contains all signatures in s1. 2756 if (set1.equals(set2)) { 2757 return PackageManager.SIGNATURE_MATCH; 2758 } 2759 return PackageManager.SIGNATURE_NO_MATCH; 2760 } 2761 2762 /** 2763 * If the database version for this type of package (internal storage or 2764 * external storage) is less than the version where package signatures 2765 * were updated, return true. 2766 */ 2767 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2768 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2769 DatabaseVersion.SIGNATURE_END_ENTITY)) 2770 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2771 DatabaseVersion.SIGNATURE_END_ENTITY)); 2772 } 2773 2774 /** 2775 * Used for backward compatibility to make sure any packages with 2776 * certificate chains get upgraded to the new style. {@code existingSigs} 2777 * will be in the old format (since they were stored on disk from before the 2778 * system upgrade) and {@code scannedSigs} will be in the newer format. 2779 */ 2780 private int compareSignaturesCompat(PackageSignatures existingSigs, 2781 PackageParser.Package scannedPkg) { 2782 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2783 return PackageManager.SIGNATURE_NO_MATCH; 2784 } 2785 2786 HashSet<Signature> existingSet = new HashSet<Signature>(); 2787 for (Signature sig : existingSigs.mSignatures) { 2788 existingSet.add(sig); 2789 } 2790 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2791 for (Signature sig : scannedPkg.mSignatures) { 2792 try { 2793 Signature[] chainSignatures = sig.getChainSignatures(); 2794 for (Signature chainSig : chainSignatures) { 2795 scannedCompatSet.add(chainSig); 2796 } 2797 } catch (CertificateEncodingException e) { 2798 scannedCompatSet.add(sig); 2799 } 2800 } 2801 /* 2802 * Make sure the expanded scanned set contains all signatures in the 2803 * existing one. 2804 */ 2805 if (scannedCompatSet.equals(existingSet)) { 2806 // Migrate the old signatures to the new scheme. 2807 existingSigs.assignSignatures(scannedPkg.mSignatures); 2808 // The new KeySets will be re-added later in the scanning process. 2809 mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName); 2810 return PackageManager.SIGNATURE_MATCH; 2811 } 2812 return PackageManager.SIGNATURE_NO_MATCH; 2813 } 2814 2815 public String[] getPackagesForUid(int uid) { 2816 uid = UserHandle.getAppId(uid); 2817 // reader 2818 synchronized (mPackages) { 2819 Object obj = mSettings.getUserIdLPr(uid); 2820 if (obj instanceof SharedUserSetting) { 2821 final SharedUserSetting sus = (SharedUserSetting) obj; 2822 final int N = sus.packages.size(); 2823 final String[] res = new String[N]; 2824 final Iterator<PackageSetting> it = sus.packages.iterator(); 2825 int i = 0; 2826 while (it.hasNext()) { 2827 res[i++] = it.next().name; 2828 } 2829 return res; 2830 } else if (obj instanceof PackageSetting) { 2831 final PackageSetting ps = (PackageSetting) obj; 2832 return new String[] { ps.name }; 2833 } 2834 } 2835 return null; 2836 } 2837 2838 public String getNameForUid(int uid) { 2839 // reader 2840 synchronized (mPackages) { 2841 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2842 if (obj instanceof SharedUserSetting) { 2843 final SharedUserSetting sus = (SharedUserSetting) obj; 2844 return sus.name + ":" + sus.userId; 2845 } else if (obj instanceof PackageSetting) { 2846 final PackageSetting ps = (PackageSetting) obj; 2847 return ps.name; 2848 } 2849 } 2850 return null; 2851 } 2852 2853 public int getUidForSharedUser(String sharedUserName) { 2854 if(sharedUserName == null) { 2855 return -1; 2856 } 2857 // reader 2858 synchronized (mPackages) { 2859 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2860 if (suid == null) { 2861 return -1; 2862 } 2863 return suid.userId; 2864 } 2865 } 2866 2867 public int getFlagsForUid(int uid) { 2868 synchronized (mPackages) { 2869 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2870 if (obj instanceof SharedUserSetting) { 2871 final SharedUserSetting sus = (SharedUserSetting) obj; 2872 return sus.pkgFlags; 2873 } else if (obj instanceof PackageSetting) { 2874 final PackageSetting ps = (PackageSetting) obj; 2875 return ps.pkgFlags; 2876 } 2877 } 2878 return 0; 2879 } 2880 2881 @Override 2882 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2883 int flags, int userId) { 2884 if (!sUserManager.exists(userId)) return null; 2885 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2886 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2887 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2888 } 2889 2890 @Override 2891 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2892 IntentFilter filter, int match, ComponentName activity) { 2893 final int userId = UserHandle.getCallingUserId(); 2894 if (DEBUG_PREFERRED) { 2895 Log.v(TAG, "setLastChosenActivity intent=" + intent 2896 + " resolvedType=" + resolvedType 2897 + " flags=" + flags 2898 + " filter=" + filter 2899 + " match=" + match 2900 + " activity=" + activity); 2901 filter.dump(new PrintStreamPrinter(System.out), " "); 2902 } 2903 intent.setComponent(null); 2904 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2905 // Find any earlier preferred or last chosen entries and nuke them 2906 findPreferredActivity(intent, resolvedType, 2907 flags, query, 0, false, true, false, userId); 2908 // Add the new activity as the last chosen for this filter 2909 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2910 } 2911 2912 @Override 2913 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2914 final int userId = UserHandle.getCallingUserId(); 2915 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2916 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2917 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2918 false, false, false, userId); 2919 } 2920 2921 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2922 int flags, List<ResolveInfo> query, int userId) { 2923 if (query != null) { 2924 final int N = query.size(); 2925 if (N == 1) { 2926 return query.get(0); 2927 } else if (N > 1) { 2928 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2929 // If there is more than one activity with the same priority, 2930 // then let the user decide between them. 2931 ResolveInfo r0 = query.get(0); 2932 ResolveInfo r1 = query.get(1); 2933 if (DEBUG_INTENT_MATCHING || debug) { 2934 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2935 + r1.activityInfo.name + "=" + r1.priority); 2936 } 2937 // If the first activity has a higher priority, or a different 2938 // default, then it is always desireable to pick it. 2939 if (r0.priority != r1.priority 2940 || r0.preferredOrder != r1.preferredOrder 2941 || r0.isDefault != r1.isDefault) { 2942 return query.get(0); 2943 } 2944 // If we have saved a preference for a preferred activity for 2945 // this Intent, use that. 2946 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2947 flags, query, r0.priority, true, false, debug, userId); 2948 if (ri != null) { 2949 return ri; 2950 } 2951 if (userId != 0) { 2952 ri = new ResolveInfo(mResolveInfo); 2953 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2954 ri.activityInfo.applicationInfo = new ApplicationInfo( 2955 ri.activityInfo.applicationInfo); 2956 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2957 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2958 return ri; 2959 } 2960 return mResolveInfo; 2961 } 2962 } 2963 return null; 2964 } 2965 2966 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2967 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2968 final int N = query.size(); 2969 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2970 .get(userId); 2971 // Get the list of persistent preferred activities that handle the intent 2972 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2973 List<PersistentPreferredActivity> pprefs = ppir != null 2974 ? ppir.queryIntent(intent, resolvedType, 2975 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2976 : null; 2977 if (pprefs != null && pprefs.size() > 0) { 2978 final int M = pprefs.size(); 2979 for (int i=0; i<M; i++) { 2980 final PersistentPreferredActivity ppa = pprefs.get(i); 2981 if (DEBUG_PREFERRED || debug) { 2982 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2983 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2984 + "\n component=" + ppa.mComponent); 2985 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2986 } 2987 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2988 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2989 if (DEBUG_PREFERRED || debug) { 2990 Slog.v(TAG, "Found persistent preferred activity:"); 2991 if (ai != null) { 2992 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2993 } else { 2994 Slog.v(TAG, " null"); 2995 } 2996 } 2997 if (ai == null) { 2998 // This previously registered persistent preferred activity 2999 // component is no longer known. Ignore it and do NOT remove it. 3000 continue; 3001 } 3002 for (int j=0; j<N; j++) { 3003 final ResolveInfo ri = query.get(j); 3004 if (!ri.activityInfo.applicationInfo.packageName 3005 .equals(ai.applicationInfo.packageName)) { 3006 continue; 3007 } 3008 if (!ri.activityInfo.name.equals(ai.name)) { 3009 continue; 3010 } 3011 // Found a persistent preference that can handle the intent. 3012 if (DEBUG_PREFERRED || debug) { 3013 Slog.v(TAG, "Returning persistent preferred activity: " + 3014 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3015 } 3016 return ri; 3017 } 3018 } 3019 } 3020 return null; 3021 } 3022 3023 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3024 List<ResolveInfo> query, int priority, boolean always, 3025 boolean removeMatches, boolean debug, int userId) { 3026 if (!sUserManager.exists(userId)) return null; 3027 // writer 3028 synchronized (mPackages) { 3029 if (intent.getSelector() != null) { 3030 intent = intent.getSelector(); 3031 } 3032 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3033 3034 // Try to find a matching persistent preferred activity. 3035 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3036 debug, userId); 3037 3038 // If a persistent preferred activity matched, use it. 3039 if (pri != null) { 3040 return pri; 3041 } 3042 3043 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3044 // Get the list of preferred activities that handle the intent 3045 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3046 List<PreferredActivity> prefs = pir != null 3047 ? pir.queryIntent(intent, resolvedType, 3048 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3049 : null; 3050 if (prefs != null && prefs.size() > 0) { 3051 // First figure out how good the original match set is. 3052 // We will only allow preferred activities that came 3053 // from the same match quality. 3054 int match = 0; 3055 3056 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3057 3058 final int N = query.size(); 3059 for (int j=0; j<N; j++) { 3060 final ResolveInfo ri = query.get(j); 3061 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3062 + ": 0x" + Integer.toHexString(match)); 3063 if (ri.match > match) { 3064 match = ri.match; 3065 } 3066 } 3067 3068 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3069 + Integer.toHexString(match)); 3070 3071 match &= IntentFilter.MATCH_CATEGORY_MASK; 3072 final int M = prefs.size(); 3073 for (int i=0; i<M; i++) { 3074 final PreferredActivity pa = prefs.get(i); 3075 if (DEBUG_PREFERRED || debug) { 3076 Slog.v(TAG, "Checking PreferredActivity ds=" 3077 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3078 + "\n component=" + pa.mPref.mComponent); 3079 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3080 } 3081 if (pa.mPref.mMatch != match) { 3082 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3083 + Integer.toHexString(pa.mPref.mMatch)); 3084 continue; 3085 } 3086 // If it's not an "always" type preferred activity and that's what we're 3087 // looking for, skip it. 3088 if (always && !pa.mPref.mAlways) { 3089 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3090 continue; 3091 } 3092 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3093 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3094 if (DEBUG_PREFERRED || debug) { 3095 Slog.v(TAG, "Found preferred activity:"); 3096 if (ai != null) { 3097 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3098 } else { 3099 Slog.v(TAG, " null"); 3100 } 3101 } 3102 if (ai == null) { 3103 // This previously registered preferred activity 3104 // component is no longer known. Most likely an update 3105 // to the app was installed and in the new version this 3106 // component no longer exists. Clean it up by removing 3107 // it from the preferred activities list, and skip it. 3108 Slog.w(TAG, "Removing dangling preferred activity: " 3109 + pa.mPref.mComponent); 3110 pir.removeFilter(pa); 3111 continue; 3112 } 3113 for (int j=0; j<N; j++) { 3114 final ResolveInfo ri = query.get(j); 3115 if (!ri.activityInfo.applicationInfo.packageName 3116 .equals(ai.applicationInfo.packageName)) { 3117 continue; 3118 } 3119 if (!ri.activityInfo.name.equals(ai.name)) { 3120 continue; 3121 } 3122 3123 if (removeMatches) { 3124 pir.removeFilter(pa); 3125 if (DEBUG_PREFERRED) { 3126 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3127 } 3128 break; 3129 } 3130 3131 // Okay we found a previously set preferred or last chosen app. 3132 // If the result set is different from when this 3133 // was created, we need to clear it and re-ask the 3134 // user their preference, if we're looking for an "always" type entry. 3135 if (always && !pa.mPref.sameSet(query, priority)) { 3136 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3137 + intent + " type " + resolvedType); 3138 if (DEBUG_PREFERRED) { 3139 Slog.v(TAG, "Removing preferred activity since set changed " 3140 + pa.mPref.mComponent); 3141 } 3142 pir.removeFilter(pa); 3143 // Re-add the filter as a "last chosen" entry (!always) 3144 PreferredActivity lastChosen = new PreferredActivity( 3145 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3146 pir.addFilter(lastChosen); 3147 mSettings.writePackageRestrictionsLPr(userId); 3148 return null; 3149 } 3150 3151 // Yay! Either the set matched or we're looking for the last chosen 3152 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3153 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3154 mSettings.writePackageRestrictionsLPr(userId); 3155 return ri; 3156 } 3157 } 3158 } 3159 mSettings.writePackageRestrictionsLPr(userId); 3160 } 3161 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3162 return null; 3163 } 3164 3165 @Override 3166 public List<ResolveInfo> queryIntentActivities(Intent intent, 3167 String resolvedType, int flags, int userId) { 3168 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3169 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3170 ComponentName comp = intent.getComponent(); 3171 if (comp == null) { 3172 if (intent.getSelector() != null) { 3173 intent = intent.getSelector(); 3174 comp = intent.getComponent(); 3175 } 3176 } 3177 3178 if (comp != null) { 3179 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3180 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3181 if (ai != null) { 3182 final ResolveInfo ri = new ResolveInfo(); 3183 ri.activityInfo = ai; 3184 list.add(ri); 3185 } 3186 return list; 3187 } 3188 3189 // reader 3190 synchronized (mPackages) { 3191 final String pkgName = intent.getPackage(); 3192 if (pkgName == null) { 3193 return mActivities.queryIntent(intent, resolvedType, flags, userId); 3194 } 3195 final PackageParser.Package pkg = mPackages.get(pkgName); 3196 if (pkg != null) { 3197 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3198 pkg.activities, userId); 3199 } 3200 return new ArrayList<ResolveInfo>(); 3201 } 3202 } 3203 3204 @Override 3205 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3206 Intent[] specifics, String[] specificTypes, Intent intent, 3207 String resolvedType, int flags, int userId) { 3208 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3209 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3210 "query intent activity options"); 3211 final String resultsAction = intent.getAction(); 3212 3213 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3214 | PackageManager.GET_RESOLVED_FILTER, userId); 3215 3216 if (DEBUG_INTENT_MATCHING) { 3217 Log.v(TAG, "Query " + intent + ": " + results); 3218 } 3219 3220 int specificsPos = 0; 3221 int N; 3222 3223 // todo: note that the algorithm used here is O(N^2). This 3224 // isn't a problem in our current environment, but if we start running 3225 // into situations where we have more than 5 or 10 matches then this 3226 // should probably be changed to something smarter... 3227 3228 // First we go through and resolve each of the specific items 3229 // that were supplied, taking care of removing any corresponding 3230 // duplicate items in the generic resolve list. 3231 if (specifics != null) { 3232 for (int i=0; i<specifics.length; i++) { 3233 final Intent sintent = specifics[i]; 3234 if (sintent == null) { 3235 continue; 3236 } 3237 3238 if (DEBUG_INTENT_MATCHING) { 3239 Log.v(TAG, "Specific #" + i + ": " + sintent); 3240 } 3241 3242 String action = sintent.getAction(); 3243 if (resultsAction != null && resultsAction.equals(action)) { 3244 // If this action was explicitly requested, then don't 3245 // remove things that have it. 3246 action = null; 3247 } 3248 3249 ResolveInfo ri = null; 3250 ActivityInfo ai = null; 3251 3252 ComponentName comp = sintent.getComponent(); 3253 if (comp == null) { 3254 ri = resolveIntent( 3255 sintent, 3256 specificTypes != null ? specificTypes[i] : null, 3257 flags, userId); 3258 if (ri == null) { 3259 continue; 3260 } 3261 if (ri == mResolveInfo) { 3262 // ACK! Must do something better with this. 3263 } 3264 ai = ri.activityInfo; 3265 comp = new ComponentName(ai.applicationInfo.packageName, 3266 ai.name); 3267 } else { 3268 ai = getActivityInfo(comp, flags, userId); 3269 if (ai == null) { 3270 continue; 3271 } 3272 } 3273 3274 // Look for any generic query activities that are duplicates 3275 // of this specific one, and remove them from the results. 3276 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3277 N = results.size(); 3278 int j; 3279 for (j=specificsPos; j<N; j++) { 3280 ResolveInfo sri = results.get(j); 3281 if ((sri.activityInfo.name.equals(comp.getClassName()) 3282 && sri.activityInfo.applicationInfo.packageName.equals( 3283 comp.getPackageName())) 3284 || (action != null && sri.filter.matchAction(action))) { 3285 results.remove(j); 3286 if (DEBUG_INTENT_MATCHING) Log.v( 3287 TAG, "Removing duplicate item from " + j 3288 + " due to specific " + specificsPos); 3289 if (ri == null) { 3290 ri = sri; 3291 } 3292 j--; 3293 N--; 3294 } 3295 } 3296 3297 // Add this specific item to its proper place. 3298 if (ri == null) { 3299 ri = new ResolveInfo(); 3300 ri.activityInfo = ai; 3301 } 3302 results.add(specificsPos, ri); 3303 ri.specificIndex = i; 3304 specificsPos++; 3305 } 3306 } 3307 3308 // Now we go through the remaining generic results and remove any 3309 // duplicate actions that are found here. 3310 N = results.size(); 3311 for (int i=specificsPos; i<N-1; i++) { 3312 final ResolveInfo rii = results.get(i); 3313 if (rii.filter == null) { 3314 continue; 3315 } 3316 3317 // Iterate over all of the actions of this result's intent 3318 // filter... typically this should be just one. 3319 final Iterator<String> it = rii.filter.actionsIterator(); 3320 if (it == null) { 3321 continue; 3322 } 3323 while (it.hasNext()) { 3324 final String action = it.next(); 3325 if (resultsAction != null && resultsAction.equals(action)) { 3326 // If this action was explicitly requested, then don't 3327 // remove things that have it. 3328 continue; 3329 } 3330 for (int j=i+1; j<N; j++) { 3331 final ResolveInfo rij = results.get(j); 3332 if (rij.filter != null && rij.filter.hasAction(action)) { 3333 results.remove(j); 3334 if (DEBUG_INTENT_MATCHING) Log.v( 3335 TAG, "Removing duplicate item from " + j 3336 + " due to action " + action + " at " + i); 3337 j--; 3338 N--; 3339 } 3340 } 3341 } 3342 3343 // If the caller didn't request filter information, drop it now 3344 // so we don't have to marshall/unmarshall it. 3345 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3346 rii.filter = null; 3347 } 3348 } 3349 3350 // Filter out the caller activity if so requested. 3351 if (caller != null) { 3352 N = results.size(); 3353 for (int i=0; i<N; i++) { 3354 ActivityInfo ainfo = results.get(i).activityInfo; 3355 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3356 && caller.getClassName().equals(ainfo.name)) { 3357 results.remove(i); 3358 break; 3359 } 3360 } 3361 } 3362 3363 // If the caller didn't request filter information, 3364 // drop them now so we don't have to 3365 // marshall/unmarshall it. 3366 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3367 N = results.size(); 3368 for (int i=0; i<N; i++) { 3369 results.get(i).filter = null; 3370 } 3371 } 3372 3373 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3374 return results; 3375 } 3376 3377 @Override 3378 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3379 int userId) { 3380 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3381 ComponentName comp = intent.getComponent(); 3382 if (comp == null) { 3383 if (intent.getSelector() != null) { 3384 intent = intent.getSelector(); 3385 comp = intent.getComponent(); 3386 } 3387 } 3388 if (comp != null) { 3389 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3390 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3391 if (ai != null) { 3392 ResolveInfo ri = new ResolveInfo(); 3393 ri.activityInfo = ai; 3394 list.add(ri); 3395 } 3396 return list; 3397 } 3398 3399 // reader 3400 synchronized (mPackages) { 3401 String pkgName = intent.getPackage(); 3402 if (pkgName == null) { 3403 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3404 } 3405 final PackageParser.Package pkg = mPackages.get(pkgName); 3406 if (pkg != null) { 3407 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3408 userId); 3409 } 3410 return null; 3411 } 3412 } 3413 3414 @Override 3415 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3416 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3417 if (!sUserManager.exists(userId)) return null; 3418 if (query != null) { 3419 if (query.size() >= 1) { 3420 // If there is more than one service with the same priority, 3421 // just arbitrarily pick the first one. 3422 return query.get(0); 3423 } 3424 } 3425 return null; 3426 } 3427 3428 @Override 3429 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3430 int userId) { 3431 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3432 ComponentName comp = intent.getComponent(); 3433 if (comp == null) { 3434 if (intent.getSelector() != null) { 3435 intent = intent.getSelector(); 3436 comp = intent.getComponent(); 3437 } 3438 } 3439 if (comp != null) { 3440 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3441 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3442 if (si != null) { 3443 final ResolveInfo ri = new ResolveInfo(); 3444 ri.serviceInfo = si; 3445 list.add(ri); 3446 } 3447 return list; 3448 } 3449 3450 // reader 3451 synchronized (mPackages) { 3452 String pkgName = intent.getPackage(); 3453 if (pkgName == null) { 3454 return mServices.queryIntent(intent, resolvedType, flags, userId); 3455 } 3456 final PackageParser.Package pkg = mPackages.get(pkgName); 3457 if (pkg != null) { 3458 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3459 userId); 3460 } 3461 return null; 3462 } 3463 } 3464 3465 @Override 3466 public List<ResolveInfo> queryIntentContentProviders( 3467 Intent intent, String resolvedType, int flags, int userId) { 3468 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3469 ComponentName comp = intent.getComponent(); 3470 if (comp == null) { 3471 if (intent.getSelector() != null) { 3472 intent = intent.getSelector(); 3473 comp = intent.getComponent(); 3474 } 3475 } 3476 if (comp != null) { 3477 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3478 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3479 if (pi != null) { 3480 final ResolveInfo ri = new ResolveInfo(); 3481 ri.providerInfo = pi; 3482 list.add(ri); 3483 } 3484 return list; 3485 } 3486 3487 // reader 3488 synchronized (mPackages) { 3489 String pkgName = intent.getPackage(); 3490 if (pkgName == null) { 3491 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3492 } 3493 final PackageParser.Package pkg = mPackages.get(pkgName); 3494 if (pkg != null) { 3495 return mProviders.queryIntentForPackage( 3496 intent, resolvedType, flags, pkg.providers, userId); 3497 } 3498 return null; 3499 } 3500 } 3501 3502 @Override 3503 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3504 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3505 3506 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3507 3508 // writer 3509 synchronized (mPackages) { 3510 ArrayList<PackageInfo> list; 3511 if (listUninstalled) { 3512 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3513 for (PackageSetting ps : mSettings.mPackages.values()) { 3514 PackageInfo pi; 3515 if (ps.pkg != null) { 3516 pi = generatePackageInfo(ps.pkg, flags, userId); 3517 } else { 3518 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3519 } 3520 if (pi != null) { 3521 list.add(pi); 3522 } 3523 } 3524 } else { 3525 list = new ArrayList<PackageInfo>(mPackages.size()); 3526 for (PackageParser.Package p : mPackages.values()) { 3527 PackageInfo pi = generatePackageInfo(p, flags, userId); 3528 if (pi != null) { 3529 list.add(pi); 3530 } 3531 } 3532 } 3533 3534 return new ParceledListSlice<PackageInfo>(list); 3535 } 3536 } 3537 3538 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3539 String[] permissions, boolean[] tmp, int flags, int userId) { 3540 int numMatch = 0; 3541 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3542 for (int i=0; i<permissions.length; i++) { 3543 if (gp.grantedPermissions.contains(permissions[i])) { 3544 tmp[i] = true; 3545 numMatch++; 3546 } else { 3547 tmp[i] = false; 3548 } 3549 } 3550 if (numMatch == 0) { 3551 return; 3552 } 3553 PackageInfo pi; 3554 if (ps.pkg != null) { 3555 pi = generatePackageInfo(ps.pkg, flags, userId); 3556 } else { 3557 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3558 } 3559 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3560 if (numMatch == permissions.length) { 3561 pi.requestedPermissions = permissions; 3562 } else { 3563 pi.requestedPermissions = new String[numMatch]; 3564 numMatch = 0; 3565 for (int i=0; i<permissions.length; i++) { 3566 if (tmp[i]) { 3567 pi.requestedPermissions[numMatch] = permissions[i]; 3568 numMatch++; 3569 } 3570 } 3571 } 3572 } 3573 list.add(pi); 3574 } 3575 3576 @Override 3577 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3578 String[] permissions, int flags, int userId) { 3579 if (!sUserManager.exists(userId)) return null; 3580 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3581 3582 // writer 3583 synchronized (mPackages) { 3584 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3585 boolean[] tmpBools = new boolean[permissions.length]; 3586 if (listUninstalled) { 3587 for (PackageSetting ps : mSettings.mPackages.values()) { 3588 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3589 } 3590 } else { 3591 for (PackageParser.Package pkg : mPackages.values()) { 3592 PackageSetting ps = (PackageSetting)pkg.mExtras; 3593 if (ps != null) { 3594 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3595 userId); 3596 } 3597 } 3598 } 3599 3600 return new ParceledListSlice<PackageInfo>(list); 3601 } 3602 } 3603 3604 @Override 3605 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3606 if (!sUserManager.exists(userId)) return null; 3607 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3608 3609 // writer 3610 synchronized (mPackages) { 3611 ArrayList<ApplicationInfo> list; 3612 if (listUninstalled) { 3613 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3614 for (PackageSetting ps : mSettings.mPackages.values()) { 3615 ApplicationInfo ai; 3616 if (ps.pkg != null) { 3617 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3618 ps.readUserState(userId), userId); 3619 } else { 3620 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3621 } 3622 if (ai != null) { 3623 list.add(ai); 3624 } 3625 } 3626 } else { 3627 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3628 for (PackageParser.Package p : mPackages.values()) { 3629 if (p.mExtras != null) { 3630 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3631 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3632 if (ai != null) { 3633 list.add(ai); 3634 } 3635 } 3636 } 3637 } 3638 3639 return new ParceledListSlice<ApplicationInfo>(list); 3640 } 3641 } 3642 3643 public List<ApplicationInfo> getPersistentApplications(int flags) { 3644 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3645 3646 // reader 3647 synchronized (mPackages) { 3648 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3649 final int userId = UserHandle.getCallingUserId(); 3650 while (i.hasNext()) { 3651 final PackageParser.Package p = i.next(); 3652 if (p.applicationInfo != null 3653 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3654 && (!mSafeMode || isSystemApp(p))) { 3655 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3656 if (ps != null) { 3657 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3658 ps.readUserState(userId), userId); 3659 if (ai != null) { 3660 finalList.add(ai); 3661 } 3662 } 3663 } 3664 } 3665 } 3666 3667 return finalList; 3668 } 3669 3670 @Override 3671 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3672 if (!sUserManager.exists(userId)) return null; 3673 // reader 3674 synchronized (mPackages) { 3675 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3676 PackageSetting ps = provider != null 3677 ? mSettings.mPackages.get(provider.owner.packageName) 3678 : null; 3679 return ps != null 3680 && mSettings.isEnabledLPr(provider.info, flags, userId) 3681 && (!mSafeMode || (provider.info.applicationInfo.flags 3682 &ApplicationInfo.FLAG_SYSTEM) != 0) 3683 ? PackageParser.generateProviderInfo(provider, flags, 3684 ps.readUserState(userId), userId) 3685 : null; 3686 } 3687 } 3688 3689 /** 3690 * @deprecated 3691 */ 3692 @Deprecated 3693 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3694 // reader 3695 synchronized (mPackages) { 3696 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3697 .entrySet().iterator(); 3698 final int userId = UserHandle.getCallingUserId(); 3699 while (i.hasNext()) { 3700 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3701 PackageParser.Provider p = entry.getValue(); 3702 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3703 3704 if (ps != null && p.syncable 3705 && (!mSafeMode || (p.info.applicationInfo.flags 3706 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3707 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3708 ps.readUserState(userId), userId); 3709 if (info != null) { 3710 outNames.add(entry.getKey()); 3711 outInfo.add(info); 3712 } 3713 } 3714 } 3715 } 3716 } 3717 3718 public List<ProviderInfo> queryContentProviders(String processName, 3719 int uid, int flags) { 3720 ArrayList<ProviderInfo> finalList = null; 3721 // reader 3722 synchronized (mPackages) { 3723 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3724 final int userId = processName != null ? 3725 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3726 while (i.hasNext()) { 3727 final PackageParser.Provider p = i.next(); 3728 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3729 if (ps != null && p.info.authority != null 3730 && (processName == null 3731 || (p.info.processName.equals(processName) 3732 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3733 && mSettings.isEnabledLPr(p.info, flags, userId) 3734 && (!mSafeMode 3735 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3736 if (finalList == null) { 3737 finalList = new ArrayList<ProviderInfo>(3); 3738 } 3739 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3740 ps.readUserState(userId), userId); 3741 if (info != null) { 3742 finalList.add(info); 3743 } 3744 } 3745 } 3746 } 3747 3748 if (finalList != null) { 3749 Collections.sort(finalList, mProviderInitOrderSorter); 3750 } 3751 3752 return finalList; 3753 } 3754 3755 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3756 int flags) { 3757 // reader 3758 synchronized (mPackages) { 3759 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3760 return PackageParser.generateInstrumentationInfo(i, flags); 3761 } 3762 } 3763 3764 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3765 int flags) { 3766 ArrayList<InstrumentationInfo> finalList = 3767 new ArrayList<InstrumentationInfo>(); 3768 3769 // reader 3770 synchronized (mPackages) { 3771 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3772 while (i.hasNext()) { 3773 final PackageParser.Instrumentation p = i.next(); 3774 if (targetPackage == null 3775 || targetPackage.equals(p.info.targetPackage)) { 3776 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3777 flags); 3778 if (ii != null) { 3779 finalList.add(ii); 3780 } 3781 } 3782 } 3783 } 3784 3785 return finalList; 3786 } 3787 3788 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 3789 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 3790 if (overlays == null) { 3791 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 3792 return; 3793 } 3794 for (PackageParser.Package opkg : overlays.values()) { 3795 // Not much to do if idmap fails: we already logged the error 3796 // and we certainly don't want to abort installation of pkg simply 3797 // because an overlay didn't fit properly. For these reasons, 3798 // ignore the return value of createIdmapForPackagePairLI. 3799 createIdmapForPackagePairLI(pkg, opkg); 3800 } 3801 } 3802 3803 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 3804 PackageParser.Package opkg) { 3805 if (!opkg.mTrustedOverlay) { 3806 Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " + 3807 opkg.mScanPath + ": overlay not trusted"); 3808 return false; 3809 } 3810 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 3811 if (overlaySet == null) { 3812 Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " + 3813 opkg.mScanPath + " but target package has no known overlays"); 3814 return false; 3815 } 3816 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 3817 if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) { 3818 Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath); 3819 return false; 3820 } 3821 PackageParser.Package[] overlayArray = 3822 overlaySet.values().toArray(new PackageParser.Package[0]); 3823 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 3824 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 3825 return p1.mOverlayPriority - p2.mOverlayPriority; 3826 } 3827 }; 3828 Arrays.sort(overlayArray, cmp); 3829 3830 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 3831 int i = 0; 3832 for (PackageParser.Package p : overlayArray) { 3833 pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir; 3834 } 3835 return true; 3836 } 3837 3838 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 3839 String[] files = dir.list(); 3840 if (files == null) { 3841 Log.d(TAG, "No files in app dir " + dir); 3842 return; 3843 } 3844 3845 if (DEBUG_PACKAGE_SCANNING) { 3846 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 3847 + " flags=0x" + Integer.toHexString(flags)); 3848 } 3849 3850 int i; 3851 for (i=0; i<files.length; i++) { 3852 File file = new File(dir, files[i]); 3853 if (!isPackageFilename(files[i])) { 3854 // Ignore entries which are not apk's 3855 continue; 3856 } 3857 PackageParser.Package pkg = scanPackageLI(file, 3858 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null); 3859 // Don't mess around with apps in system partition. 3860 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 3861 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 3862 // Delete the apk 3863 Slog.w(TAG, "Cleaning up failed install of " + file); 3864 file.delete(); 3865 } 3866 } 3867 } 3868 3869 private static File getSettingsProblemFile() { 3870 File dataDir = Environment.getDataDirectory(); 3871 File systemDir = new File(dataDir, "system"); 3872 File fname = new File(systemDir, "uiderrors.txt"); 3873 return fname; 3874 } 3875 3876 static void reportSettingsProblem(int priority, String msg) { 3877 try { 3878 File fname = getSettingsProblemFile(); 3879 FileOutputStream out = new FileOutputStream(fname, true); 3880 PrintWriter pw = new FastPrintWriter(out); 3881 SimpleDateFormat formatter = new SimpleDateFormat(); 3882 String dateString = formatter.format(new Date(System.currentTimeMillis())); 3883 pw.println(dateString + ": " + msg); 3884 pw.close(); 3885 FileUtils.setPermissions( 3886 fname.toString(), 3887 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 3888 -1, -1); 3889 } catch (java.io.IOException e) { 3890 } 3891 Slog.println(priority, TAG, msg); 3892 } 3893 3894 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 3895 PackageParser.Package pkg, File srcFile, int parseFlags) { 3896 if (ps != null 3897 && ps.codePath.equals(srcFile) 3898 && ps.timeStamp == srcFile.lastModified() 3899 && !isCompatSignatureUpdateNeeded(pkg)) { 3900 if (ps.signatures.mSignatures != null 3901 && ps.signatures.mSignatures.length != 0) { 3902 // Optimization: reuse the existing cached certificates 3903 // if the package appears to be unchanged. 3904 pkg.mSignatures = ps.signatures.mSignatures; 3905 return true; 3906 } 3907 3908 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 3909 } else { 3910 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 3911 } 3912 3913 if (!pp.collectCertificates(pkg, parseFlags)) { 3914 mLastScanError = pp.getParseError(); 3915 return false; 3916 } 3917 return true; 3918 } 3919 3920 /* 3921 * Scan a package and return the newly parsed package. 3922 * Returns null in case of errors and the error code is stored in mLastScanError 3923 */ 3924 private PackageParser.Package scanPackageLI(File scanFile, 3925 int parseFlags, int scanMode, long currentTime, UserHandle user) { 3926 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 3927 String scanPath = scanFile.getPath(); 3928 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath); 3929 parseFlags |= mDefParseFlags; 3930 PackageParser pp = new PackageParser(scanPath); 3931 pp.setSeparateProcesses(mSeparateProcesses); 3932 pp.setOnlyCoreApps(mOnlyCore); 3933 final PackageParser.Package pkg = pp.parsePackage(scanFile, 3934 scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0); 3935 3936 if (pkg == null) { 3937 mLastScanError = pp.getParseError(); 3938 return null; 3939 } 3940 3941 PackageSetting ps = null; 3942 PackageSetting updatedPkg; 3943 // reader 3944 synchronized (mPackages) { 3945 // Look to see if we already know about this package. 3946 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 3947 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 3948 // This package has been renamed to its original name. Let's 3949 // use that. 3950 ps = mSettings.peekPackageLPr(oldName); 3951 } 3952 // If there was no original package, see one for the real package name. 3953 if (ps == null) { 3954 ps = mSettings.peekPackageLPr(pkg.packageName); 3955 } 3956 // Check to see if this package could be hiding/updating a system 3957 // package. Must look for it either under the original or real 3958 // package name depending on our state. 3959 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 3960 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 3961 } 3962 boolean updatedPkgBetter = false; 3963 // First check if this is a system package that may involve an update 3964 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 3965 if (ps != null && !ps.codePath.equals(scanFile)) { 3966 // The path has changed from what was last scanned... check the 3967 // version of the new path against what we have stored to determine 3968 // what to do. 3969 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 3970 if (pkg.mVersionCode < ps.versionCode) { 3971 // The system package has been updated and the code path does not match 3972 // Ignore entry. Skip it. 3973 Log.i(TAG, "Package " + ps.name + " at " + scanFile 3974 + " ignored: updated version " + ps.versionCode 3975 + " better than this " + pkg.mVersionCode); 3976 if (!updatedPkg.codePath.equals(scanFile)) { 3977 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 3978 + ps.name + " changing from " + updatedPkg.codePathString 3979 + " to " + scanFile); 3980 updatedPkg.codePath = scanFile; 3981 updatedPkg.codePathString = scanFile.toString(); 3982 // This is the point at which we know that the system-disk APK 3983 // for this package has moved during a reboot (e.g. due to an OTA), 3984 // so we need to reevaluate it for privilege policy. 3985 if (locationIsPrivileged(scanFile)) { 3986 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 3987 } 3988 } 3989 updatedPkg.pkg = pkg; 3990 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 3991 return null; 3992 } else { 3993 // The current app on the system partion is better than 3994 // what we have updated to on the data partition; switch 3995 // back to the system partition version. 3996 // At this point, its safely assumed that package installation for 3997 // apps in system partition will go through. If not there won't be a working 3998 // version of the app 3999 // writer 4000 synchronized (mPackages) { 4001 // Just remove the loaded entries from package lists. 4002 mPackages.remove(ps.name); 4003 } 4004 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4005 + "reverting from " + ps.codePathString 4006 + ": new version " + pkg.mVersionCode 4007 + " better than installed " + ps.versionCode); 4008 4009 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4010 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4011 getAppInstructionSetFromSettings(ps)); 4012 synchronized (mInstallLock) { 4013 args.cleanUpResourcesLI(); 4014 } 4015 synchronized (mPackages) { 4016 mSettings.enableSystemPackageLPw(ps.name); 4017 } 4018 updatedPkgBetter = true; 4019 } 4020 } 4021 } 4022 4023 if (updatedPkg != null) { 4024 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4025 // initially 4026 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4027 4028 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4029 // flag set initially 4030 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4031 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4032 } 4033 } 4034 // Verify certificates against what was last scanned 4035 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 4036 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 4037 return null; 4038 } 4039 4040 /* 4041 * A new system app appeared, but we already had a non-system one of the 4042 * same name installed earlier. 4043 */ 4044 boolean shouldHideSystemApp = false; 4045 if (updatedPkg == null && ps != null 4046 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4047 /* 4048 * Check to make sure the signatures match first. If they don't, 4049 * wipe the installed application and its data. 4050 */ 4051 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4052 != PackageManager.SIGNATURE_MATCH) { 4053 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4054 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4055 ps = null; 4056 } else { 4057 /* 4058 * If the newly-added system app is an older version than the 4059 * already installed version, hide it. It will be scanned later 4060 * and re-added like an update. 4061 */ 4062 if (pkg.mVersionCode < ps.versionCode) { 4063 shouldHideSystemApp = true; 4064 } else { 4065 /* 4066 * The newly found system app is a newer version that the 4067 * one previously installed. Simply remove the 4068 * already-installed application and replace it with our own 4069 * while keeping the application data. 4070 */ 4071 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4072 + ps.codePathString + ": new version " + pkg.mVersionCode 4073 + " better than installed " + ps.versionCode); 4074 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4075 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4076 getAppInstructionSetFromSettings(ps)); 4077 synchronized (mInstallLock) { 4078 args.cleanUpResourcesLI(); 4079 } 4080 } 4081 } 4082 } 4083 4084 // The apk is forward locked (not public) if its code and resources 4085 // are kept in different files. (except for app in either system or 4086 // vendor path). 4087 // TODO grab this value from PackageSettings 4088 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4089 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4090 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4091 } 4092 } 4093 4094 String codePath = null; 4095 String resPath = null; 4096 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4097 if (ps != null && ps.resourcePathString != null) { 4098 resPath = ps.resourcePathString; 4099 } else { 4100 // Should not happen at all. Just log an error. 4101 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4102 } 4103 } else { 4104 resPath = pkg.mScanPath; 4105 } 4106 4107 codePath = pkg.mScanPath; 4108 // Set application objects path explicitly. 4109 setApplicationInfoPaths(pkg, codePath, resPath); 4110 // Note that we invoke the following method only if we are about to unpack an application 4111 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4112 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4113 4114 /* 4115 * If the system app should be overridden by a previously installed 4116 * data, hide the system app now and let the /data/app scan pick it up 4117 * again. 4118 */ 4119 if (shouldHideSystemApp) { 4120 synchronized (mPackages) { 4121 /* 4122 * We have to grant systems permissions before we hide, because 4123 * grantPermissions will assume the package update is trying to 4124 * expand its permissions. 4125 */ 4126 grantPermissionsLPw(pkg, true); 4127 mSettings.disableSystemPackageLPw(pkg.packageName); 4128 } 4129 } 4130 4131 return scannedPkg; 4132 } 4133 4134 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath, 4135 String destResPath) { 4136 pkg.mPath = pkg.mScanPath = destCodePath; 4137 pkg.applicationInfo.sourceDir = destCodePath; 4138 pkg.applicationInfo.publicSourceDir = destResPath; 4139 } 4140 4141 private static String fixProcessName(String defProcessName, 4142 String processName, int uid) { 4143 if (processName == null) { 4144 return defProcessName; 4145 } 4146 return processName; 4147 } 4148 4149 private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) { 4150 if (pkgSetting.signatures.mSignatures != null) { 4151 // Already existing package. Make sure signatures match 4152 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4153 == PackageManager.SIGNATURE_MATCH; 4154 if (!match) { 4155 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4156 == PackageManager.SIGNATURE_MATCH; 4157 } 4158 if (!match) { 4159 Slog.e(TAG, "Package " + pkg.packageName 4160 + " signatures do not match the previously installed version; ignoring!"); 4161 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4162 return false; 4163 } 4164 } 4165 // Check for shared user signatures 4166 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4167 // Already existing package. Make sure signatures match 4168 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4169 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4170 if (!match) { 4171 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4172 == PackageManager.SIGNATURE_MATCH; 4173 } 4174 if (!match) { 4175 Slog.e(TAG, "Package " + pkg.packageName 4176 + " has no signatures that match those in shared user " 4177 + pkgSetting.sharedUser.name + "; ignoring!"); 4178 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4179 return false; 4180 } 4181 } 4182 return true; 4183 } 4184 4185 /** 4186 * Enforces that only the system UID or root's UID can call a method exposed 4187 * via Binder. 4188 * 4189 * @param message used as message if SecurityException is thrown 4190 * @throws SecurityException if the caller is not system or root 4191 */ 4192 private static final void enforceSystemOrRoot(String message) { 4193 final int uid = Binder.getCallingUid(); 4194 if (uid != Process.SYSTEM_UID && uid != 0) { 4195 throw new SecurityException(message); 4196 } 4197 } 4198 4199 @Override 4200 public void performBootDexOpt() { 4201 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4202 4203 final HashSet<PackageParser.Package> pkgs; 4204 synchronized (mPackages) { 4205 pkgs = mDeferredDexOpt; 4206 mDeferredDexOpt = null; 4207 } 4208 4209 if (pkgs != null) { 4210 int i = 0; 4211 for (PackageParser.Package pkg : pkgs) { 4212 if (!isFirstBoot()) { 4213 i++; 4214 try { 4215 ActivityManagerNative.getDefault().showBootMessage( 4216 mContext.getResources().getString( 4217 com.android.internal.R.string.android_upgrading_apk, 4218 i, pkgs.size()), true); 4219 } catch (RemoteException e) { 4220 } 4221 } 4222 PackageParser.Package p = pkg; 4223 synchronized (mInstallLock) { 4224 if (!p.mDidDexOpt) { 4225 performDexOptLI(p, false /* force dex */, false /* defer */, 4226 true /* include dependencies */); 4227 } 4228 } 4229 } 4230 } 4231 } 4232 4233 @Override 4234 public boolean performDexOpt(String packageName) { 4235 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4236 if (!mNoDexOpt) { 4237 return false; 4238 } 4239 4240 PackageParser.Package p; 4241 synchronized (mPackages) { 4242 p = mPackages.get(packageName); 4243 if (p == null || p.mDidDexOpt) { 4244 return false; 4245 } 4246 } 4247 synchronized (mInstallLock) { 4248 return performDexOptLI(p, false /* force dex */, false /* defer */, 4249 true /* include dependencies */) == DEX_OPT_PERFORMED; 4250 } 4251 } 4252 4253 private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, boolean forceDex, 4254 boolean defer, HashSet<String> done) { 4255 for (int i=0; i<libs.size(); i++) { 4256 PackageParser.Package libPkg; 4257 String libName; 4258 synchronized (mPackages) { 4259 libName = libs.get(i); 4260 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4261 if (lib != null && lib.apk != null) { 4262 libPkg = mPackages.get(lib.apk); 4263 } else { 4264 libPkg = null; 4265 } 4266 } 4267 if (libPkg != null && !done.contains(libName)) { 4268 performDexOptLI(libPkg, instructionSet, forceDex, defer, done); 4269 } 4270 } 4271 } 4272 4273 static final int DEX_OPT_SKIPPED = 0; 4274 static final int DEX_OPT_PERFORMED = 1; 4275 static final int DEX_OPT_DEFERRED = 2; 4276 static final int DEX_OPT_FAILED = -1; 4277 4278 private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride, 4279 boolean forceDex, 4280 boolean defer, HashSet<String> done) { 4281 final String instructionSet = instructionSetOverride != null ? 4282 instructionSetOverride : getAppInstructionSet(pkg.applicationInfo); 4283 4284 if (done != null) { 4285 done.add(pkg.packageName); 4286 if (pkg.usesLibraries != null) { 4287 performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done); 4288 } 4289 if (pkg.usesOptionalLibraries != null) { 4290 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done); 4291 } 4292 } 4293 4294 boolean performed = false; 4295 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 4296 String path = pkg.mScanPath; 4297 int ret = 0; 4298 try { 4299 if (forceDex || dalvik.system.DexFile.isDexOptNeededInternal(path, 4300 pkg.packageName, instructionSet, defer)) { 4301 if (!forceDex && defer) { 4302 if (mDeferredDexOpt == null) { 4303 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4304 } 4305 mDeferredDexOpt.add(pkg); 4306 return DEX_OPT_DEFERRED; 4307 } else { 4308 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName + 4309 " (instructionSet=" + instructionSet + ")"); 4310 4311 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4312 ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4313 pkg.packageName, instructionSet); 4314 pkg.mDidDexOpt = true; 4315 performed = true; 4316 } 4317 } 4318 } catch (FileNotFoundException e) { 4319 Slog.w(TAG, "Apk not found for dexopt: " + path); 4320 ret = -1; 4321 } catch (IOException e) { 4322 Slog.w(TAG, "IOException reading apk: " + path, e); 4323 ret = -1; 4324 } catch (dalvik.system.StaleDexCacheError e) { 4325 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4326 ret = -1; 4327 } catch (Exception e) { 4328 Slog.w(TAG, "Exception when doing dexopt : ", e); 4329 ret = -1; 4330 } 4331 if (ret < 0) { 4332 //error from installer 4333 return DEX_OPT_FAILED; 4334 } 4335 } 4336 4337 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4338 } 4339 4340 private String getAppInstructionSet(ApplicationInfo info) { 4341 String instructionSet = getPreferredInstructionSet(); 4342 4343 if (info.requiredCpuAbi != null) { 4344 instructionSet = VMRuntime.getInstructionSet(info.requiredCpuAbi); 4345 } 4346 4347 return instructionSet; 4348 } 4349 4350 private String getAppInstructionSetFromSettings(PackageSetting ps) { 4351 String instructionSet = getPreferredInstructionSet(); 4352 4353 if (ps.requiredCpuAbiString != null) { 4354 instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString); 4355 } 4356 4357 return instructionSet; 4358 } 4359 4360 private static String getPreferredInstructionSet() { 4361 if (sPreferredInstructionSet == null) { 4362 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4363 } 4364 4365 return sPreferredInstructionSet; 4366 } 4367 4368 private static List<String> getAllInstructionSets() { 4369 final String[] allAbis = Build.SUPPORTED_ABIS; 4370 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4371 4372 for (String abi : allAbis) { 4373 final String instructionSet = VMRuntime.getInstructionSet(abi); 4374 if (!allInstructionSets.contains(instructionSet)) { 4375 allInstructionSets.add(instructionSet); 4376 } 4377 } 4378 4379 return allInstructionSets; 4380 } 4381 4382 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4383 boolean inclDependencies) { 4384 HashSet<String> done; 4385 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4386 done = new HashSet<String>(); 4387 done.add(pkg.packageName); 4388 } else { 4389 done = null; 4390 } 4391 return performDexOptLI(pkg, null /* instruction set override */, forceDex, defer, done); 4392 } 4393 4394 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4395 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4396 Slog.w(TAG, "Unable to update from " + oldPkg.name 4397 + " to " + newPkg.packageName 4398 + ": old package not in system partition"); 4399 return false; 4400 } else if (mPackages.get(oldPkg.name) != null) { 4401 Slog.w(TAG, "Unable to update from " + oldPkg.name 4402 + " to " + newPkg.packageName 4403 + ": old package still exists"); 4404 return false; 4405 } 4406 return true; 4407 } 4408 4409 File getDataPathForUser(int userId) { 4410 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4411 } 4412 4413 private File getDataPathForPackage(String packageName, int userId) { 4414 /* 4415 * Until we fully support multiple users, return the directory we 4416 * previously would have. The PackageManagerTests will need to be 4417 * revised when this is changed back.. 4418 */ 4419 if (userId == 0) { 4420 return new File(mAppDataDir, packageName); 4421 } else { 4422 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4423 + File.separator + packageName); 4424 } 4425 } 4426 4427 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4428 int[] users = sUserManager.getUserIds(); 4429 int res = mInstaller.install(packageName, uid, uid, seinfo); 4430 if (res < 0) { 4431 return res; 4432 } 4433 for (int user : users) { 4434 if (user != 0) { 4435 res = mInstaller.createUserData(packageName, 4436 UserHandle.getUid(user, uid), user, seinfo); 4437 if (res < 0) { 4438 return res; 4439 } 4440 } 4441 } 4442 return res; 4443 } 4444 4445 private int removeDataDirsLI(String packageName) { 4446 int[] users = sUserManager.getUserIds(); 4447 int res = 0; 4448 for (int user : users) { 4449 int resInner = mInstaller.remove(packageName, user); 4450 if (resInner < 0) { 4451 res = resInner; 4452 } 4453 } 4454 4455 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4456 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4457 if (!nativeLibraryFile.delete()) { 4458 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4459 } 4460 4461 return res; 4462 } 4463 4464 private int addSharedLibraryLPw(final SharedLibraryEntry file, int num, 4465 PackageParser.Package changingLib) { 4466 if (file.path != null) { 4467 mTmpSharedLibraries[num] = file.path; 4468 return num+1; 4469 } 4470 PackageParser.Package p = mPackages.get(file.apk); 4471 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4472 // If we are doing this while in the middle of updating a library apk, 4473 // then we need to make sure to use that new apk for determining the 4474 // dependencies here. (We haven't yet finished committing the new apk 4475 // to the package manager state.) 4476 if (p == null || p.packageName.equals(changingLib.packageName)) { 4477 p = changingLib; 4478 } 4479 } 4480 if (p != null) { 4481 String path = p.mPath; 4482 for (int i=0; i<num; i++) { 4483 if (mTmpSharedLibraries[i].equals(path)) { 4484 return num; 4485 } 4486 } 4487 mTmpSharedLibraries[num] = p.mPath; 4488 return num+1; 4489 } 4490 return num; 4491 } 4492 4493 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4494 PackageParser.Package changingLib) { 4495 // We might be upgrading from a version of the platform that did not 4496 // provide per-package native library directories for system apps. 4497 // Fix that up here. 4498 if (isSystemApp(pkg)) { 4499 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4500 setInternalAppNativeLibraryPath(pkg, ps); 4501 } 4502 4503 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4504 if (mTmpSharedLibraries == null || 4505 mTmpSharedLibraries.length < mSharedLibraries.size()) { 4506 mTmpSharedLibraries = new String[mSharedLibraries.size()]; 4507 } 4508 int num = 0; 4509 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4510 for (int i=0; i<N; i++) { 4511 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4512 if (file == null) { 4513 Slog.e(TAG, "Package " + pkg.packageName 4514 + " requires unavailable shared library " 4515 + pkg.usesLibraries.get(i) + "; failing!"); 4516 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4517 return false; 4518 } 4519 num = addSharedLibraryLPw(file, num, changingLib); 4520 } 4521 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4522 for (int i=0; i<N; i++) { 4523 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4524 if (file == null) { 4525 Slog.w(TAG, "Package " + pkg.packageName 4526 + " desires unavailable shared library " 4527 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4528 } else { 4529 num = addSharedLibraryLPw(file, num, changingLib); 4530 } 4531 } 4532 if (num > 0) { 4533 pkg.usesLibraryFiles = new String[num]; 4534 System.arraycopy(mTmpSharedLibraries, 0, 4535 pkg.usesLibraryFiles, 0, num); 4536 } else { 4537 pkg.usesLibraryFiles = null; 4538 } 4539 } 4540 return true; 4541 } 4542 4543 private static boolean hasString(List<String> list, List<String> which) { 4544 if (list == null) { 4545 return false; 4546 } 4547 for (int i=list.size()-1; i>=0; i--) { 4548 for (int j=which.size()-1; j>=0; j--) { 4549 if (which.get(j).equals(list.get(i))) { 4550 return true; 4551 } 4552 } 4553 } 4554 return false; 4555 } 4556 4557 private void updateAllSharedLibrariesLPw() { 4558 for (PackageParser.Package pkg : mPackages.values()) { 4559 updateSharedLibrariesLPw(pkg, null); 4560 } 4561 } 4562 4563 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4564 PackageParser.Package changingPkg) { 4565 ArrayList<PackageParser.Package> res = null; 4566 for (PackageParser.Package pkg : mPackages.values()) { 4567 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4568 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4569 if (res == null) { 4570 res = new ArrayList<PackageParser.Package>(); 4571 } 4572 res.add(pkg); 4573 updateSharedLibrariesLPw(pkg, changingPkg); 4574 } 4575 } 4576 return res; 4577 } 4578 4579 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4580 int parseFlags, int scanMode, long currentTime, UserHandle user) { 4581 File scanFile = new File(pkg.mScanPath); 4582 if (scanFile == null || pkg.applicationInfo.sourceDir == null || 4583 pkg.applicationInfo.publicSourceDir == null) { 4584 // Bail out. The resource and code paths haven't been set. 4585 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4586 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4587 return null; 4588 } 4589 4590 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4591 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4592 } 4593 4594 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4595 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4596 } 4597 4598 if (mCustomResolverComponentName != null && 4599 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4600 setUpCustomResolverActivity(pkg); 4601 } 4602 4603 if (pkg.packageName.equals("android")) { 4604 synchronized (mPackages) { 4605 if (mAndroidApplication != null) { 4606 Slog.w(TAG, "*************************************************"); 4607 Slog.w(TAG, "Core android package being redefined. Skipping."); 4608 Slog.w(TAG, " file=" + scanFile); 4609 Slog.w(TAG, "*************************************************"); 4610 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4611 return null; 4612 } 4613 4614 // Set up information for our fall-back user intent resolution activity. 4615 mPlatformPackage = pkg; 4616 pkg.mVersionCode = mSdkVersion; 4617 mAndroidApplication = pkg.applicationInfo; 4618 4619 if (!mResolverReplaced) { 4620 mResolveActivity.applicationInfo = mAndroidApplication; 4621 mResolveActivity.name = ResolverActivity.class.getName(); 4622 mResolveActivity.packageName = mAndroidApplication.packageName; 4623 mResolveActivity.processName = "system:ui"; 4624 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4625 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4626 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert; 4627 mResolveActivity.exported = true; 4628 mResolveActivity.enabled = true; 4629 mResolveInfo.activityInfo = mResolveActivity; 4630 mResolveInfo.priority = 0; 4631 mResolveInfo.preferredOrder = 0; 4632 mResolveInfo.match = 0; 4633 mResolveComponentName = new ComponentName( 4634 mAndroidApplication.packageName, mResolveActivity.name); 4635 } 4636 } 4637 } 4638 4639 if (DEBUG_PACKAGE_SCANNING) { 4640 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4641 Log.d(TAG, "Scanning package " + pkg.packageName); 4642 } 4643 4644 if (mPackages.containsKey(pkg.packageName) 4645 || mSharedLibraries.containsKey(pkg.packageName)) { 4646 Slog.w(TAG, "Application package " + pkg.packageName 4647 + " already installed. Skipping duplicate."); 4648 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4649 return null; 4650 } 4651 4652 // Initialize package source and resource directories 4653 File destCodeFile = new File(pkg.applicationInfo.sourceDir); 4654 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir); 4655 4656 SharedUserSetting suid = null; 4657 PackageSetting pkgSetting = null; 4658 4659 if (!isSystemApp(pkg)) { 4660 // Only system apps can use these features. 4661 pkg.mOriginalPackages = null; 4662 pkg.mRealPackage = null; 4663 pkg.mAdoptPermissions = null; 4664 } 4665 4666 // writer 4667 synchronized (mPackages) { 4668 if (pkg.mSharedUserId != null) { 4669 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 4670 if (suid == null) { 4671 Slog.w(TAG, "Creating application package " + pkg.packageName 4672 + " for shared user failed"); 4673 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4674 return null; 4675 } 4676 if (DEBUG_PACKAGE_SCANNING) { 4677 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4678 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 4679 + "): packages=" + suid.packages); 4680 } 4681 } 4682 4683 // Check if we are renaming from an original package name. 4684 PackageSetting origPackage = null; 4685 String realName = null; 4686 if (pkg.mOriginalPackages != null) { 4687 // This package may need to be renamed to a previously 4688 // installed name. Let's check on that... 4689 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 4690 if (pkg.mOriginalPackages.contains(renamed)) { 4691 // This package had originally been installed as the 4692 // original name, and we have already taken care of 4693 // transitioning to the new one. Just update the new 4694 // one to continue using the old name. 4695 realName = pkg.mRealPackage; 4696 if (!pkg.packageName.equals(renamed)) { 4697 // Callers into this function may have already taken 4698 // care of renaming the package; only do it here if 4699 // it is not already done. 4700 pkg.setPackageName(renamed); 4701 } 4702 4703 } else { 4704 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 4705 if ((origPackage = mSettings.peekPackageLPr( 4706 pkg.mOriginalPackages.get(i))) != null) { 4707 // We do have the package already installed under its 4708 // original name... should we use it? 4709 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 4710 // New package is not compatible with original. 4711 origPackage = null; 4712 continue; 4713 } else if (origPackage.sharedUser != null) { 4714 // Make sure uid is compatible between packages. 4715 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 4716 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 4717 + " to " + pkg.packageName + ": old uid " 4718 + origPackage.sharedUser.name 4719 + " differs from " + pkg.mSharedUserId); 4720 origPackage = null; 4721 continue; 4722 } 4723 } else { 4724 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 4725 + pkg.packageName + " to old name " + origPackage.name); 4726 } 4727 break; 4728 } 4729 } 4730 } 4731 } 4732 4733 if (mTransferedPackages.contains(pkg.packageName)) { 4734 Slog.w(TAG, "Package " + pkg.packageName 4735 + " was transferred to another, but its .apk remains"); 4736 } 4737 4738 // Just create the setting, don't add it yet. For already existing packages 4739 // the PkgSetting exists already and doesn't have to be created. 4740 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 4741 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 4742 pkg.applicationInfo.requiredCpuAbi, 4743 pkg.applicationInfo.flags, user, false); 4744 if (pkgSetting == null) { 4745 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 4746 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4747 return null; 4748 } 4749 4750 if (pkgSetting.origPackage != null) { 4751 // If we are first transitioning from an original package, 4752 // fix up the new package's name now. We need to do this after 4753 // looking up the package under its new name, so getPackageLP 4754 // can take care of fiddling things correctly. 4755 pkg.setPackageName(origPackage.name); 4756 4757 // File a report about this. 4758 String msg = "New package " + pkgSetting.realName 4759 + " renamed to replace old package " + pkgSetting.name; 4760 reportSettingsProblem(Log.WARN, msg); 4761 4762 // Make a note of it. 4763 mTransferedPackages.add(origPackage.name); 4764 4765 // No longer need to retain this. 4766 pkgSetting.origPackage = null; 4767 } 4768 4769 if (realName != null) { 4770 // Make a note of it. 4771 mTransferedPackages.add(pkg.packageName); 4772 } 4773 4774 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 4775 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 4776 } 4777 4778 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4779 // Check all shared libraries and map to their actual file path. 4780 // We only do this here for apps not on a system dir, because those 4781 // are the only ones that can fail an install due to this. We 4782 // will take care of the system apps by updating all of their 4783 // library paths after the scan is done. 4784 if (!updateSharedLibrariesLPw(pkg, null)) { 4785 return null; 4786 } 4787 } 4788 4789 if (mFoundPolicyFile) { 4790 SELinuxMMAC.assignSeinfoValue(pkg); 4791 } 4792 4793 pkg.applicationInfo.uid = pkgSetting.appId; 4794 pkg.mExtras = pkgSetting; 4795 4796 if (!verifySignaturesLP(pkgSetting, pkg)) { 4797 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4798 return null; 4799 } 4800 // The signature has changed, but this package is in the system 4801 // image... let's recover! 4802 pkgSetting.signatures.mSignatures = pkg.mSignatures; 4803 // However... if this package is part of a shared user, but it 4804 // doesn't match the signature of the shared user, let's fail. 4805 // What this means is that you can't change the signatures 4806 // associated with an overall shared user, which doesn't seem all 4807 // that unreasonable. 4808 if (pkgSetting.sharedUser != null) { 4809 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4810 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 4811 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 4812 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 4813 return null; 4814 } 4815 } 4816 // File a report about this. 4817 String msg = "System package " + pkg.packageName 4818 + " signature changed; retaining data."; 4819 reportSettingsProblem(Log.WARN, msg); 4820 } 4821 4822 // Verify that this new package doesn't have any content providers 4823 // that conflict with existing packages. Only do this if the 4824 // package isn't already installed, since we don't want to break 4825 // things that are installed. 4826 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 4827 final int N = pkg.providers.size(); 4828 int i; 4829 for (i=0; i<N; i++) { 4830 PackageParser.Provider p = pkg.providers.get(i); 4831 if (p.info.authority != null) { 4832 String names[] = p.info.authority.split(";"); 4833 for (int j = 0; j < names.length; j++) { 4834 if (mProvidersByAuthority.containsKey(names[j])) { 4835 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 4836 Slog.w(TAG, "Can't install because provider name " + names[j] + 4837 " (in package " + pkg.applicationInfo.packageName + 4838 ") is already used by " 4839 + ((other != null && other.getComponentName() != null) 4840 ? other.getComponentName().getPackageName() : "?")); 4841 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 4842 return null; 4843 } 4844 } 4845 } 4846 } 4847 } 4848 4849 if (pkg.mAdoptPermissions != null) { 4850 // This package wants to adopt ownership of permissions from 4851 // another package. 4852 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 4853 final String origName = pkg.mAdoptPermissions.get(i); 4854 final PackageSetting orig = mSettings.peekPackageLPr(origName); 4855 if (orig != null) { 4856 if (verifyPackageUpdateLPr(orig, pkg)) { 4857 Slog.i(TAG, "Adopting permissions from " + origName + " to " 4858 + pkg.packageName); 4859 mSettings.transferPermissionsLPw(origName, pkg.packageName); 4860 } 4861 } 4862 } 4863 } 4864 } 4865 4866 final String pkgName = pkg.packageName; 4867 4868 final long scanFileTime = scanFile.lastModified(); 4869 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 4870 pkg.applicationInfo.processName = fixProcessName( 4871 pkg.applicationInfo.packageName, 4872 pkg.applicationInfo.processName, 4873 pkg.applicationInfo.uid); 4874 4875 File dataPath; 4876 if (mPlatformPackage == pkg) { 4877 // The system package is special. 4878 dataPath = new File (Environment.getDataDirectory(), "system"); 4879 pkg.applicationInfo.dataDir = dataPath.getPath(); 4880 } else { 4881 // This is a normal package, need to make its data directory. 4882 dataPath = getDataPathForPackage(pkg.packageName, 0); 4883 4884 boolean uidError = false; 4885 4886 if (dataPath.exists()) { 4887 int currentUid = 0; 4888 try { 4889 StructStat stat = Os.stat(dataPath.getPath()); 4890 currentUid = stat.st_uid; 4891 } catch (ErrnoException e) { 4892 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 4893 } 4894 4895 // If we have mismatched owners for the data path, we have a problem. 4896 if (currentUid != pkg.applicationInfo.uid) { 4897 boolean recovered = false; 4898 if (currentUid == 0) { 4899 // The directory somehow became owned by root. Wow. 4900 // This is probably because the system was stopped while 4901 // installd was in the middle of messing with its libs 4902 // directory. Ask installd to fix that. 4903 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 4904 pkg.applicationInfo.uid); 4905 if (ret >= 0) { 4906 recovered = true; 4907 String msg = "Package " + pkg.packageName 4908 + " unexpectedly changed to uid 0; recovered to " + 4909 + pkg.applicationInfo.uid; 4910 reportSettingsProblem(Log.WARN, msg); 4911 } 4912 } 4913 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 4914 || (scanMode&SCAN_BOOTING) != 0)) { 4915 // If this is a system app, we can at least delete its 4916 // current data so the application will still work. 4917 int ret = removeDataDirsLI(pkgName); 4918 if (ret >= 0) { 4919 // TODO: Kill the processes first 4920 // Old data gone! 4921 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 4922 ? "System package " : "Third party package "; 4923 String msg = prefix + pkg.packageName 4924 + " has changed from uid: " 4925 + currentUid + " to " 4926 + pkg.applicationInfo.uid + "; old data erased"; 4927 reportSettingsProblem(Log.WARN, msg); 4928 recovered = true; 4929 4930 // And now re-install the app. 4931 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 4932 pkg.applicationInfo.seinfo); 4933 if (ret == -1) { 4934 // Ack should not happen! 4935 msg = prefix + pkg.packageName 4936 + " could not have data directory re-created after delete."; 4937 reportSettingsProblem(Log.WARN, msg); 4938 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4939 return null; 4940 } 4941 } 4942 if (!recovered) { 4943 mHasSystemUidErrors = true; 4944 } 4945 } else if (!recovered) { 4946 // If we allow this install to proceed, we will be broken. 4947 // Abort, abort! 4948 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 4949 return null; 4950 } 4951 if (!recovered) { 4952 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 4953 + pkg.applicationInfo.uid + "/fs_" 4954 + currentUid; 4955 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 4956 String msg = "Package " + pkg.packageName 4957 + " has mismatched uid: " 4958 + currentUid + " on disk, " 4959 + pkg.applicationInfo.uid + " in settings"; 4960 // writer 4961 synchronized (mPackages) { 4962 mSettings.mReadMessages.append(msg); 4963 mSettings.mReadMessages.append('\n'); 4964 uidError = true; 4965 if (!pkgSetting.uidError) { 4966 reportSettingsProblem(Log.ERROR, msg); 4967 } 4968 } 4969 } 4970 } 4971 pkg.applicationInfo.dataDir = dataPath.getPath(); 4972 if (mShouldRestoreconData) { 4973 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 4974 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 4975 pkg.applicationInfo.uid); 4976 } 4977 } else { 4978 if (DEBUG_PACKAGE_SCANNING) { 4979 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4980 Log.v(TAG, "Want this data dir: " + dataPath); 4981 } 4982 //invoke installer to do the actual installation 4983 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 4984 pkg.applicationInfo.seinfo); 4985 if (ret < 0) { 4986 // Error from installer 4987 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4988 return null; 4989 } 4990 4991 if (dataPath.exists()) { 4992 pkg.applicationInfo.dataDir = dataPath.getPath(); 4993 } else { 4994 Slog.w(TAG, "Unable to create data directory: " + dataPath); 4995 pkg.applicationInfo.dataDir = null; 4996 } 4997 } 4998 4999 /* 5000 * Set the data dir to the default "/data/data/<package name>/lib" 5001 * if we got here without anyone telling us different (e.g., apps 5002 * stored on SD card have their native libraries stored in the ASEC 5003 * container with the APK). 5004 * 5005 * This happens during an upgrade from a package settings file that 5006 * doesn't have a native library path attribute at all. 5007 */ 5008 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 5009 if (pkgSetting.nativeLibraryPathString == null) { 5010 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5011 } else { 5012 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 5013 } 5014 } 5015 pkgSetting.uidError = uidError; 5016 } 5017 5018 String path = scanFile.getPath(); 5019 /* Note: We don't want to unpack the native binaries for 5020 * system applications, unless they have been updated 5021 * (the binaries are already under /system/lib). 5022 * Also, don't unpack libs for apps on the external card 5023 * since they should have their libraries in the ASEC 5024 * container already. 5025 * 5026 * In other words, we're going to unpack the binaries 5027 * only for non-system apps and system app upgrades. 5028 */ 5029 if (pkg.applicationInfo.nativeLibraryDir != null) { 5030 try { 5031 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5032 final String dataPathString = dataPath.getCanonicalPath(); 5033 5034 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5035 /* 5036 * Upgrading from a previous version of the OS sometimes 5037 * leaves native libraries in the /data/data/<app>/lib 5038 * directory for system apps even when they shouldn't be. 5039 * Recent changes in the JNI library search path 5040 * necessitates we remove those to match previous behavior. 5041 */ 5042 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 5043 Log.i(TAG, "removed obsolete native libraries for system package " 5044 + path); 5045 } 5046 5047 setInternalAppAbi(pkg, pkgSetting); 5048 } else { 5049 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 5050 /* 5051 * Update native library dir if it starts with 5052 * /data/data 5053 */ 5054 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 5055 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5056 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5057 } 5058 5059 try { 5060 int copyRet = copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir); 5061 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5062 Slog.e(TAG, "Unable to copy native libraries"); 5063 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5064 return null; 5065 } 5066 5067 // We've successfully copied native libraries across, so we make a 5068 // note of what ABI we're using 5069 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5070 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[copyRet]; 5071 } else { 5072 pkg.applicationInfo.requiredCpuAbi = null; 5073 } 5074 } catch (IOException e) { 5075 Slog.e(TAG, "Unable to copy native libraries", e); 5076 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5077 return null; 5078 } 5079 } else { 5080 // We don't have to copy the shared libraries if we're in the ASEC container 5081 // but we still need to scan the file to figure out what ABI the app needs. 5082 // 5083 // TODO: This duplicates work done in the default container service. It's possible 5084 // to clean this up but we'll need to change the interface between this service 5085 // and IMediaContainerService (but doing so will spread this logic out, rather 5086 // than centralizing it). 5087 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile); 5088 final int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS); 5089 if (abi >= 0) { 5090 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[abi]; 5091 } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) { 5092 // Note that (non upgraded) system apps will not have any native 5093 // libraries bundled in their APK, but we're guaranteed not to be 5094 // such an app at this point. 5095 pkg.applicationInfo.requiredCpuAbi = null; 5096 } else { 5097 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5098 return null; 5099 } 5100 handle.close(); 5101 } 5102 5103 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5104 final int[] userIds = sUserManager.getUserIds(); 5105 synchronized (mInstallLock) { 5106 for (int userId : userIds) { 5107 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 5108 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 5109 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5110 + ")"); 5111 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5112 return null; 5113 } 5114 } 5115 } 5116 } 5117 } catch (IOException ioe) { 5118 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5119 } 5120 } 5121 pkg.mScanPath = path; 5122 5123 if ((scanMode&SCAN_NO_DEX) == 0) { 5124 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5125 == DEX_OPT_FAILED) { 5126 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5127 removeDataDirsLI(pkg.packageName); 5128 } 5129 5130 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5131 return null; 5132 } 5133 } 5134 5135 if (mFactoryTest && pkg.requestedPermissions.contains( 5136 android.Manifest.permission.FACTORY_TEST)) { 5137 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5138 } 5139 5140 ArrayList<PackageParser.Package> clientLibPkgs = null; 5141 5142 // writer 5143 synchronized (mPackages) { 5144 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5145 // Only system apps can add new shared libraries. 5146 if (pkg.libraryNames != null) { 5147 for (int i=0; i<pkg.libraryNames.size(); i++) { 5148 String name = pkg.libraryNames.get(i); 5149 boolean allowed = false; 5150 if (isUpdatedSystemApp(pkg)) { 5151 // New library entries can only be added through the 5152 // system image. This is important to get rid of a lot 5153 // of nasty edge cases: for example if we allowed a non- 5154 // system update of the app to add a library, then uninstalling 5155 // the update would make the library go away, and assumptions 5156 // we made such as through app install filtering would now 5157 // have allowed apps on the device which aren't compatible 5158 // with it. Better to just have the restriction here, be 5159 // conservative, and create many fewer cases that can negatively 5160 // impact the user experience. 5161 final PackageSetting sysPs = mSettings 5162 .getDisabledSystemPkgLPr(pkg.packageName); 5163 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5164 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5165 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5166 allowed = true; 5167 allowed = true; 5168 break; 5169 } 5170 } 5171 } 5172 } else { 5173 allowed = true; 5174 } 5175 if (allowed) { 5176 if (!mSharedLibraries.containsKey(name)) { 5177 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5178 } else if (!name.equals(pkg.packageName)) { 5179 Slog.w(TAG, "Package " + pkg.packageName + " library " 5180 + name + " already exists; skipping"); 5181 } 5182 } else { 5183 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5184 + name + " that is not declared on system image; skipping"); 5185 } 5186 } 5187 if ((scanMode&SCAN_BOOTING) == 0) { 5188 // If we are not booting, we need to update any applications 5189 // that are clients of our shared library. If we are booting, 5190 // this will all be done once the scan is complete. 5191 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5192 } 5193 } 5194 } 5195 } 5196 5197 // We also need to dexopt any apps that are dependent on this library. Note that 5198 // if these fail, we should abort the install since installing the library will 5199 // result in some apps being broken. 5200 if (clientLibPkgs != null) { 5201 if ((scanMode&SCAN_NO_DEX) == 0) { 5202 for (int i=0; i<clientLibPkgs.size(); i++) { 5203 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5204 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5205 == DEX_OPT_FAILED) { 5206 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5207 removeDataDirsLI(pkg.packageName); 5208 } 5209 5210 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5211 return null; 5212 } 5213 } 5214 } 5215 } 5216 5217 // Request the ActivityManager to kill the process(only for existing packages) 5218 // so that we do not end up in a confused state while the user is still using the older 5219 // version of the application while the new one gets installed. 5220 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5221 // If the package lives in an asec, tell everyone that the container is going 5222 // away so they can clean up any references to its resources (which would prevent 5223 // vold from being able to unmount the asec) 5224 if (isForwardLocked(pkg) || isExternal(pkg)) { 5225 if (DEBUG_INSTALL) { 5226 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5227 } 5228 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5229 final ArrayList<String> pkgList = new ArrayList<String>(1); 5230 pkgList.add(pkg.applicationInfo.packageName); 5231 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5232 } 5233 5234 // Post the request that it be killed now that the going-away broadcast is en route 5235 killApplication(pkg.applicationInfo.packageName, 5236 pkg.applicationInfo.uid, "update pkg"); 5237 } 5238 5239 // Also need to kill any apps that are dependent on the library. 5240 if (clientLibPkgs != null) { 5241 for (int i=0; i<clientLibPkgs.size(); i++) { 5242 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5243 killApplication(clientPkg.applicationInfo.packageName, 5244 clientPkg.applicationInfo.uid, "update lib"); 5245 } 5246 } 5247 5248 // writer 5249 synchronized (mPackages) { 5250 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5251 // We don't do this here during boot because we can do it all 5252 // at once after scanning all existing packages. 5253 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5254 true, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5255 } 5256 // We don't expect installation to fail beyond this point, 5257 if ((scanMode&SCAN_MONITOR) != 0) { 5258 mAppDirs.put(pkg.mPath, pkg); 5259 } 5260 // Add the new setting to mSettings 5261 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5262 // Add the new setting to mPackages 5263 mPackages.put(pkg.applicationInfo.packageName, pkg); 5264 // Make sure we don't accidentally delete its data. 5265 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5266 while (iter.hasNext()) { 5267 PackageCleanItem item = iter.next(); 5268 if (pkgName.equals(item.packageName)) { 5269 iter.remove(); 5270 } 5271 } 5272 5273 // Take care of first install / last update times. 5274 if (currentTime != 0) { 5275 if (pkgSetting.firstInstallTime == 0) { 5276 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5277 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5278 pkgSetting.lastUpdateTime = currentTime; 5279 } 5280 } else if (pkgSetting.firstInstallTime == 0) { 5281 // We need *something*. Take time time stamp of the file. 5282 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5283 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5284 if (scanFileTime != pkgSetting.timeStamp) { 5285 // A package on the system image has changed; consider this 5286 // to be an update. 5287 pkgSetting.lastUpdateTime = scanFileTime; 5288 } 5289 } 5290 5291 // Add the package's KeySets to the global KeySetManager 5292 KeySetManager ksm = mSettings.mKeySetManager; 5293 try { 5294 ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5295 if (pkg.mKeySetMapping != null) { 5296 for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) { 5297 if (entry.getValue() != null) { 5298 ksm.addDefinedKeySetToPackage(pkg.packageName, 5299 entry.getValue(), entry.getKey()); 5300 } 5301 } 5302 } 5303 } catch (NullPointerException e) { 5304 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5305 } catch (IllegalArgumentException e) { 5306 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5307 } 5308 5309 int N = pkg.providers.size(); 5310 StringBuilder r = null; 5311 int i; 5312 for (i=0; i<N; i++) { 5313 PackageParser.Provider p = pkg.providers.get(i); 5314 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5315 p.info.processName, pkg.applicationInfo.uid); 5316 mProviders.addProvider(p); 5317 p.syncable = p.info.isSyncable; 5318 if (p.info.authority != null) { 5319 String names[] = p.info.authority.split(";"); 5320 p.info.authority = null; 5321 for (int j = 0; j < names.length; j++) { 5322 if (j == 1 && p.syncable) { 5323 // We only want the first authority for a provider to possibly be 5324 // syncable, so if we already added this provider using a different 5325 // authority clear the syncable flag. We copy the provider before 5326 // changing it because the mProviders object contains a reference 5327 // to a provider that we don't want to change. 5328 // Only do this for the second authority since the resulting provider 5329 // object can be the same for all future authorities for this provider. 5330 p = new PackageParser.Provider(p); 5331 p.syncable = false; 5332 } 5333 if (!mProvidersByAuthority.containsKey(names[j])) { 5334 mProvidersByAuthority.put(names[j], p); 5335 if (p.info.authority == null) { 5336 p.info.authority = names[j]; 5337 } else { 5338 p.info.authority = p.info.authority + ";" + names[j]; 5339 } 5340 if (DEBUG_PACKAGE_SCANNING) { 5341 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5342 Log.d(TAG, "Registered content provider: " + names[j] 5343 + ", className = " + p.info.name + ", isSyncable = " 5344 + p.info.isSyncable); 5345 } 5346 } else { 5347 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5348 Slog.w(TAG, "Skipping provider name " + names[j] + 5349 " (in package " + pkg.applicationInfo.packageName + 5350 "): name already used by " 5351 + ((other != null && other.getComponentName() != null) 5352 ? other.getComponentName().getPackageName() : "?")); 5353 } 5354 } 5355 } 5356 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5357 if (r == null) { 5358 r = new StringBuilder(256); 5359 } else { 5360 r.append(' '); 5361 } 5362 r.append(p.info.name); 5363 } 5364 } 5365 if (r != null) { 5366 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5367 } 5368 5369 N = pkg.services.size(); 5370 r = null; 5371 for (i=0; i<N; i++) { 5372 PackageParser.Service s = pkg.services.get(i); 5373 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5374 s.info.processName, pkg.applicationInfo.uid); 5375 mServices.addService(s); 5376 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5377 if (r == null) { 5378 r = new StringBuilder(256); 5379 } else { 5380 r.append(' '); 5381 } 5382 r.append(s.info.name); 5383 } 5384 } 5385 if (r != null) { 5386 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5387 } 5388 5389 N = pkg.receivers.size(); 5390 r = null; 5391 for (i=0; i<N; i++) { 5392 PackageParser.Activity a = pkg.receivers.get(i); 5393 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5394 a.info.processName, pkg.applicationInfo.uid); 5395 mReceivers.addActivity(a, "receiver"); 5396 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5397 if (r == null) { 5398 r = new StringBuilder(256); 5399 } else { 5400 r.append(' '); 5401 } 5402 r.append(a.info.name); 5403 } 5404 } 5405 if (r != null) { 5406 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5407 } 5408 5409 N = pkg.activities.size(); 5410 r = null; 5411 for (i=0; i<N; i++) { 5412 PackageParser.Activity a = pkg.activities.get(i); 5413 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5414 a.info.processName, pkg.applicationInfo.uid); 5415 mActivities.addActivity(a, "activity"); 5416 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5417 if (r == null) { 5418 r = new StringBuilder(256); 5419 } else { 5420 r.append(' '); 5421 } 5422 r.append(a.info.name); 5423 } 5424 } 5425 if (r != null) { 5426 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5427 } 5428 5429 N = pkg.permissionGroups.size(); 5430 r = null; 5431 for (i=0; i<N; i++) { 5432 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5433 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5434 if (cur == null) { 5435 mPermissionGroups.put(pg.info.name, pg); 5436 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5437 if (r == null) { 5438 r = new StringBuilder(256); 5439 } else { 5440 r.append(' '); 5441 } 5442 r.append(pg.info.name); 5443 } 5444 } else { 5445 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5446 + pg.info.packageName + " ignored: original from " 5447 + cur.info.packageName); 5448 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5449 if (r == null) { 5450 r = new StringBuilder(256); 5451 } else { 5452 r.append(' '); 5453 } 5454 r.append("DUP:"); 5455 r.append(pg.info.name); 5456 } 5457 } 5458 } 5459 if (r != null) { 5460 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5461 } 5462 5463 N = pkg.permissions.size(); 5464 r = null; 5465 for (i=0; i<N; i++) { 5466 PackageParser.Permission p = pkg.permissions.get(i); 5467 HashMap<String, BasePermission> permissionMap = 5468 p.tree ? mSettings.mPermissionTrees 5469 : mSettings.mPermissions; 5470 p.group = mPermissionGroups.get(p.info.group); 5471 if (p.info.group == null || p.group != null) { 5472 BasePermission bp = permissionMap.get(p.info.name); 5473 if (bp == null) { 5474 bp = new BasePermission(p.info.name, p.info.packageName, 5475 BasePermission.TYPE_NORMAL); 5476 permissionMap.put(p.info.name, bp); 5477 } 5478 if (bp.perm == null) { 5479 if (bp.sourcePackage != null 5480 && !bp.sourcePackage.equals(p.info.packageName)) { 5481 // If this is a permission that was formerly defined by a non-system 5482 // app, but is now defined by a system app (following an upgrade), 5483 // discard the previous declaration and consider the system's to be 5484 // canonical. 5485 if (isSystemApp(p.owner)) { 5486 String msg = "New decl " + p.owner + " of permission " 5487 + p.info.name + " is system"; 5488 reportSettingsProblem(Log.WARN, msg); 5489 bp.sourcePackage = null; 5490 } 5491 } 5492 if (bp.sourcePackage == null 5493 || bp.sourcePackage.equals(p.info.packageName)) { 5494 BasePermission tree = findPermissionTreeLP(p.info.name); 5495 if (tree == null 5496 || tree.sourcePackage.equals(p.info.packageName)) { 5497 bp.packageSetting = pkgSetting; 5498 bp.perm = p; 5499 bp.uid = pkg.applicationInfo.uid; 5500 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5501 if (r == null) { 5502 r = new StringBuilder(256); 5503 } else { 5504 r.append(' '); 5505 } 5506 r.append(p.info.name); 5507 } 5508 } else { 5509 Slog.w(TAG, "Permission " + p.info.name + " from package " 5510 + p.info.packageName + " ignored: base tree " 5511 + tree.name + " is from package " 5512 + tree.sourcePackage); 5513 } 5514 } else { 5515 Slog.w(TAG, "Permission " + p.info.name + " from package " 5516 + p.info.packageName + " ignored: original from " 5517 + bp.sourcePackage); 5518 } 5519 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5520 if (r == null) { 5521 r = new StringBuilder(256); 5522 } else { 5523 r.append(' '); 5524 } 5525 r.append("DUP:"); 5526 r.append(p.info.name); 5527 } 5528 if (bp.perm == p) { 5529 bp.protectionLevel = p.info.protectionLevel; 5530 } 5531 } else { 5532 Slog.w(TAG, "Permission " + p.info.name + " from package " 5533 + p.info.packageName + " ignored: no group " 5534 + p.group); 5535 } 5536 } 5537 if (r != null) { 5538 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5539 } 5540 5541 N = pkg.instrumentation.size(); 5542 r = null; 5543 for (i=0; i<N; i++) { 5544 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5545 a.info.packageName = pkg.applicationInfo.packageName; 5546 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5547 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5548 a.info.dataDir = pkg.applicationInfo.dataDir; 5549 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5550 mInstrumentation.put(a.getComponentName(), a); 5551 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5552 if (r == null) { 5553 r = new StringBuilder(256); 5554 } else { 5555 r.append(' '); 5556 } 5557 r.append(a.info.name); 5558 } 5559 } 5560 if (r != null) { 5561 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5562 } 5563 5564 if (pkg.protectedBroadcasts != null) { 5565 N = pkg.protectedBroadcasts.size(); 5566 for (i=0; i<N; i++) { 5567 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5568 } 5569 } 5570 5571 pkgSetting.setTimeStamp(scanFileTime); 5572 5573 // Create idmap files for pairs of (packages, overlay packages). 5574 // Note: "android", ie framework-res.apk, is handled by native layers. 5575 if (pkg.mOverlayTarget != null) { 5576 // This is an overlay package. 5577 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 5578 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 5579 mOverlays.put(pkg.mOverlayTarget, 5580 new HashMap<String, PackageParser.Package>()); 5581 } 5582 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 5583 map.put(pkg.packageName, pkg); 5584 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 5585 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 5586 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5587 return null; 5588 } 5589 } 5590 } else if (mOverlays.containsKey(pkg.packageName) && 5591 !pkg.packageName.equals("android")) { 5592 // This is a regular package, with one or more known overlay packages. 5593 createIdmapsForPackageLI(pkg); 5594 } 5595 } 5596 5597 return pkg; 5598 } 5599 5600 public void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 5601 boolean doDexOpt, boolean forceDexOpt, boolean deferDexOpt) { 5602 String requiredInstructionSet = null; 5603 PackageSetting requirer = null; 5604 for (PackageSetting ps : packagesForUser) { 5605 if (ps.requiredCpuAbiString != null) { 5606 final String instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString); 5607 if (requiredInstructionSet != null) { 5608 if (!instructionSet.equals(requiredInstructionSet)) { 5609 // We have a mismatch between instruction sets (say arm vs arm64). 5610 // 5611 // TODO: We should rescan all the packages in a shared UID to check if 5612 // they do contain shared libs for other ABIs in addition to the ones we've 5613 // already extracted. For example, the package might contain both arm64-v8a 5614 // and armeabi-v7a shared libs, and we'd have chosen arm64-v8a on 64 bit 5615 // devices. 5616 String errorMessage = "Instruction set mismatch, " + requirer.pkg.packageName 5617 + " requires " + requiredInstructionSet + " whereas " + ps.pkg.packageName 5618 + " requires " + instructionSet; 5619 Slog.e(TAG, errorMessage); 5620 5621 reportSettingsProblem(Log.WARN, errorMessage); 5622 // Give up, don't bother making any other changes to the package settings. 5623 return; 5624 } 5625 } else { 5626 requiredInstructionSet = instructionSet; 5627 requirer = ps; 5628 } 5629 } 5630 } 5631 5632 if (requiredInstructionSet != null) { 5633 for (PackageSetting ps : packagesForUser) { 5634 if (ps.requiredCpuAbiString == null) { 5635 ps.requiredCpuAbiString = requirer.requiredCpuAbiString; 5636 if (ps.pkg != null) { 5637 ps.pkg.applicationInfo.requiredCpuAbi = requirer.requiredCpuAbiString; 5638 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + ps.requiredCpuAbiString); 5639 if (doDexOpt) { 5640 performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true); 5641 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 5642 } 5643 } 5644 } 5645 } 5646 } 5647 } 5648 5649 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 5650 synchronized (mPackages) { 5651 mResolverReplaced = true; 5652 // Set up information for custom user intent resolution activity. 5653 mResolveActivity.applicationInfo = pkg.applicationInfo; 5654 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 5655 mResolveActivity.packageName = pkg.applicationInfo.packageName; 5656 mResolveActivity.processName = null; 5657 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5658 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 5659 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 5660 mResolveActivity.theme = 0; 5661 mResolveActivity.exported = true; 5662 mResolveActivity.enabled = true; 5663 mResolveInfo.activityInfo = mResolveActivity; 5664 mResolveInfo.priority = 0; 5665 mResolveInfo.preferredOrder = 0; 5666 mResolveInfo.match = 0; 5667 mResolveComponentName = mCustomResolverComponentName; 5668 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 5669 mResolveComponentName); 5670 } 5671 } 5672 5673 private String calculateApkRoot(final String codePathString) { 5674 final File codePath = new File(codePathString); 5675 final File codeRoot; 5676 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 5677 codeRoot = Environment.getRootDirectory(); 5678 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 5679 codeRoot = Environment.getOemDirectory(); 5680 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 5681 codeRoot = Environment.getVendorDirectory(); 5682 } else { 5683 // Unrecognized code path; take its top real segment as the apk root: 5684 // e.g. /something/app/blah.apk => /something 5685 try { 5686 File f = codePath.getCanonicalFile(); 5687 File parent = f.getParentFile(); // non-null because codePath is a file 5688 File tmp; 5689 while ((tmp = parent.getParentFile()) != null) { 5690 f = parent; 5691 parent = tmp; 5692 } 5693 codeRoot = f; 5694 Slog.w(TAG, "Unrecognized code path " 5695 + codePath + " - using " + codeRoot); 5696 } catch (IOException e) { 5697 // Can't canonicalize the lib path -- shenanigans? 5698 Slog.w(TAG, "Can't canonicalize code path " + codePath); 5699 return Environment.getRootDirectory().getPath(); 5700 } 5701 } 5702 return codeRoot.getPath(); 5703 } 5704 5705 // This is the initial scan-time determination of how to handle a given 5706 // package for purposes of native library location. 5707 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 5708 PackageSetting pkgSetting) { 5709 // "bundled" here means system-installed with no overriding update 5710 final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg); 5711 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 5712 final File libDir; 5713 if (bundledApk) { 5714 // If "/system/lib64/apkname" exists, assume that is the per-package 5715 // native library directory to use; otherwise use "/system/lib/apkname". 5716 String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 5717 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 5718 File packLib64 = new File(lib64, apkName); 5719 libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 5720 } else { 5721 libDir = mAppLibInstallDir; 5722 } 5723 final String nativeLibraryPath = (new File(libDir, apkName)).getPath(); 5724 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 5725 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 5726 } 5727 5728 // Deduces the required ABI of an upgraded system app. 5729 private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) { 5730 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 5731 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 5732 5733 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 5734 // or similar. 5735 final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath()); 5736 final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath()); 5737 5738 // Assume that the bundled native libraries always correspond to the 5739 // most preferred 32 or 64 bit ABI. 5740 if (lib64.exists()) { 5741 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 5742 pkgSetting.requiredCpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0]; 5743 } else if (lib.exists()) { 5744 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5745 pkgSetting.requiredCpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0]; 5746 } else { 5747 // This is the case where the app has no native code. 5748 pkg.applicationInfo.requiredCpuAbi = null; 5749 pkgSetting.requiredCpuAbiString = null; 5750 } 5751 } 5752 5753 private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir) 5754 throws IOException { 5755 if (!nativeLibraryDir.isDirectory()) { 5756 nativeLibraryDir.delete(); 5757 5758 if (!nativeLibraryDir.mkdir()) { 5759 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 5760 } 5761 5762 try { 5763 Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 5764 } catch (ErrnoException e) { 5765 throw new IOException("Cannot chmod native library directory " 5766 + nativeLibraryDir.getPath(), e); 5767 } 5768 } else if (!SELinux.restorecon(nativeLibraryDir)) { 5769 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 5770 } 5771 5772 /* 5773 * If this is an internal application or our nativeLibraryPath points to 5774 * the app-lib directory, unpack the libraries if necessary. 5775 */ 5776 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile); 5777 try { 5778 int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS); 5779 if (abi >= 0) { 5780 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 5781 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 5782 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 5783 return copyRet; 5784 } 5785 } 5786 5787 return abi; 5788 } finally { 5789 handle.close(); 5790 } 5791 } 5792 5793 private void killApplication(String pkgName, int appId, String reason) { 5794 // Request the ActivityManager to kill the process(only for existing packages) 5795 // so that we do not end up in a confused state while the user is still using the older 5796 // version of the application while the new one gets installed. 5797 IActivityManager am = ActivityManagerNative.getDefault(); 5798 if (am != null) { 5799 try { 5800 am.killApplicationWithAppId(pkgName, appId, reason); 5801 } catch (RemoteException e) { 5802 } 5803 } 5804 } 5805 5806 void removePackageLI(PackageSetting ps, boolean chatty) { 5807 if (DEBUG_INSTALL) { 5808 if (chatty) 5809 Log.d(TAG, "Removing package " + ps.name); 5810 } 5811 5812 // writer 5813 synchronized (mPackages) { 5814 mPackages.remove(ps.name); 5815 if (ps.codePathString != null) { 5816 mAppDirs.remove(ps.codePathString); 5817 } 5818 5819 final PackageParser.Package pkg = ps.pkg; 5820 if (pkg != null) { 5821 cleanPackageDataStructuresLILPw(pkg, chatty); 5822 } 5823 } 5824 } 5825 5826 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 5827 if (DEBUG_INSTALL) { 5828 if (chatty) 5829 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 5830 } 5831 5832 // writer 5833 synchronized (mPackages) { 5834 mPackages.remove(pkg.applicationInfo.packageName); 5835 if (pkg.mPath != null) { 5836 mAppDirs.remove(pkg.mPath); 5837 } 5838 cleanPackageDataStructuresLILPw(pkg, chatty); 5839 } 5840 } 5841 5842 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 5843 int N = pkg.providers.size(); 5844 StringBuilder r = null; 5845 int i; 5846 for (i=0; i<N; i++) { 5847 PackageParser.Provider p = pkg.providers.get(i); 5848 mProviders.removeProvider(p); 5849 if (p.info.authority == null) { 5850 5851 /* There was another ContentProvider with this authority when 5852 * this app was installed so this authority is null, 5853 * Ignore it as we don't have to unregister the provider. 5854 */ 5855 continue; 5856 } 5857 String names[] = p.info.authority.split(";"); 5858 for (int j = 0; j < names.length; j++) { 5859 if (mProvidersByAuthority.get(names[j]) == p) { 5860 mProvidersByAuthority.remove(names[j]); 5861 if (DEBUG_REMOVE) { 5862 if (chatty) 5863 Log.d(TAG, "Unregistered content provider: " + names[j] 5864 + ", className = " + p.info.name + ", isSyncable = " 5865 + p.info.isSyncable); 5866 } 5867 } 5868 } 5869 if (DEBUG_REMOVE && chatty) { 5870 if (r == null) { 5871 r = new StringBuilder(256); 5872 } else { 5873 r.append(' '); 5874 } 5875 r.append(p.info.name); 5876 } 5877 } 5878 if (r != null) { 5879 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 5880 } 5881 5882 N = pkg.services.size(); 5883 r = null; 5884 for (i=0; i<N; i++) { 5885 PackageParser.Service s = pkg.services.get(i); 5886 mServices.removeService(s); 5887 if (chatty) { 5888 if (r == null) { 5889 r = new StringBuilder(256); 5890 } else { 5891 r.append(' '); 5892 } 5893 r.append(s.info.name); 5894 } 5895 } 5896 if (r != null) { 5897 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 5898 } 5899 5900 N = pkg.receivers.size(); 5901 r = null; 5902 for (i=0; i<N; i++) { 5903 PackageParser.Activity a = pkg.receivers.get(i); 5904 mReceivers.removeActivity(a, "receiver"); 5905 if (DEBUG_REMOVE && chatty) { 5906 if (r == null) { 5907 r = new StringBuilder(256); 5908 } else { 5909 r.append(' '); 5910 } 5911 r.append(a.info.name); 5912 } 5913 } 5914 if (r != null) { 5915 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 5916 } 5917 5918 N = pkg.activities.size(); 5919 r = null; 5920 for (i=0; i<N; i++) { 5921 PackageParser.Activity a = pkg.activities.get(i); 5922 mActivities.removeActivity(a, "activity"); 5923 if (DEBUG_REMOVE && chatty) { 5924 if (r == null) { 5925 r = new StringBuilder(256); 5926 } else { 5927 r.append(' '); 5928 } 5929 r.append(a.info.name); 5930 } 5931 } 5932 if (r != null) { 5933 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 5934 } 5935 5936 N = pkg.permissions.size(); 5937 r = null; 5938 for (i=0; i<N; i++) { 5939 PackageParser.Permission p = pkg.permissions.get(i); 5940 BasePermission bp = mSettings.mPermissions.get(p.info.name); 5941 if (bp == null) { 5942 bp = mSettings.mPermissionTrees.get(p.info.name); 5943 } 5944 if (bp != null && bp.perm == p) { 5945 bp.perm = null; 5946 if (DEBUG_REMOVE && chatty) { 5947 if (r == null) { 5948 r = new StringBuilder(256); 5949 } else { 5950 r.append(' '); 5951 } 5952 r.append(p.info.name); 5953 } 5954 } 5955 } 5956 if (r != null) { 5957 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 5958 } 5959 5960 N = pkg.instrumentation.size(); 5961 r = null; 5962 for (i=0; i<N; i++) { 5963 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5964 mInstrumentation.remove(a.getComponentName()); 5965 if (DEBUG_REMOVE && chatty) { 5966 if (r == null) { 5967 r = new StringBuilder(256); 5968 } else { 5969 r.append(' '); 5970 } 5971 r.append(a.info.name); 5972 } 5973 } 5974 if (r != null) { 5975 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 5976 } 5977 5978 r = null; 5979 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5980 // Only system apps can hold shared libraries. 5981 if (pkg.libraryNames != null) { 5982 for (i=0; i<pkg.libraryNames.size(); i++) { 5983 String name = pkg.libraryNames.get(i); 5984 SharedLibraryEntry cur = mSharedLibraries.get(name); 5985 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 5986 mSharedLibraries.remove(name); 5987 if (DEBUG_REMOVE && chatty) { 5988 if (r == null) { 5989 r = new StringBuilder(256); 5990 } else { 5991 r.append(' '); 5992 } 5993 r.append(name); 5994 } 5995 } 5996 } 5997 } 5998 } 5999 if (r != null) { 6000 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6001 } 6002 } 6003 6004 private static final boolean isPackageFilename(String name) { 6005 return name != null && name.endsWith(".apk"); 6006 } 6007 6008 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6009 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6010 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6011 return true; 6012 } 6013 } 6014 return false; 6015 } 6016 6017 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6018 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6019 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6020 6021 private void updatePermissionsLPw(String changingPkg, 6022 PackageParser.Package pkgInfo, int flags) { 6023 // Make sure there are no dangling permission trees. 6024 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6025 while (it.hasNext()) { 6026 final BasePermission bp = it.next(); 6027 if (bp.packageSetting == null) { 6028 // We may not yet have parsed the package, so just see if 6029 // we still know about its settings. 6030 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6031 } 6032 if (bp.packageSetting == null) { 6033 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6034 + " from package " + bp.sourcePackage); 6035 it.remove(); 6036 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6037 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6038 Slog.i(TAG, "Removing old permission tree: " + bp.name 6039 + " from package " + bp.sourcePackage); 6040 flags |= UPDATE_PERMISSIONS_ALL; 6041 it.remove(); 6042 } 6043 } 6044 } 6045 6046 // Make sure all dynamic permissions have been assigned to a package, 6047 // and make sure there are no dangling permissions. 6048 it = mSettings.mPermissions.values().iterator(); 6049 while (it.hasNext()) { 6050 final BasePermission bp = it.next(); 6051 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6052 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6053 + bp.name + " pkg=" + bp.sourcePackage 6054 + " info=" + bp.pendingInfo); 6055 if (bp.packageSetting == null && bp.pendingInfo != null) { 6056 final BasePermission tree = findPermissionTreeLP(bp.name); 6057 if (tree != null && tree.perm != null) { 6058 bp.packageSetting = tree.packageSetting; 6059 bp.perm = new PackageParser.Permission(tree.perm.owner, 6060 new PermissionInfo(bp.pendingInfo)); 6061 bp.perm.info.packageName = tree.perm.info.packageName; 6062 bp.perm.info.name = bp.name; 6063 bp.uid = tree.uid; 6064 } 6065 } 6066 } 6067 if (bp.packageSetting == null) { 6068 // We may not yet have parsed the package, so just see if 6069 // we still know about its settings. 6070 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6071 } 6072 if (bp.packageSetting == null) { 6073 Slog.w(TAG, "Removing dangling permission: " + bp.name 6074 + " from package " + bp.sourcePackage); 6075 it.remove(); 6076 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6077 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6078 Slog.i(TAG, "Removing old permission: " + bp.name 6079 + " from package " + bp.sourcePackage); 6080 flags |= UPDATE_PERMISSIONS_ALL; 6081 it.remove(); 6082 } 6083 } 6084 } 6085 6086 // Now update the permissions for all packages, in particular 6087 // replace the granted permissions of the system packages. 6088 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6089 for (PackageParser.Package pkg : mPackages.values()) { 6090 if (pkg != pkgInfo) { 6091 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6092 } 6093 } 6094 } 6095 6096 if (pkgInfo != null) { 6097 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6098 } 6099 } 6100 6101 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6102 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6103 if (ps == null) { 6104 return; 6105 } 6106 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6107 HashSet<String> origPermissions = gp.grantedPermissions; 6108 boolean changedPermission = false; 6109 6110 if (replace) { 6111 ps.permissionsFixed = false; 6112 if (gp == ps) { 6113 origPermissions = new HashSet<String>(gp.grantedPermissions); 6114 gp.grantedPermissions.clear(); 6115 gp.gids = mGlobalGids; 6116 } 6117 } 6118 6119 if (gp.gids == null) { 6120 gp.gids = mGlobalGids; 6121 } 6122 6123 final int N = pkg.requestedPermissions.size(); 6124 for (int i=0; i<N; i++) { 6125 final String name = pkg.requestedPermissions.get(i); 6126 final boolean required = pkg.requestedPermissionsRequired.get(i); 6127 final BasePermission bp = mSettings.mPermissions.get(name); 6128 if (DEBUG_INSTALL) { 6129 if (gp != ps) { 6130 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6131 } 6132 } 6133 6134 if (bp == null || bp.packageSetting == null) { 6135 Slog.w(TAG, "Unknown permission " + name 6136 + " in package " + pkg.packageName); 6137 continue; 6138 } 6139 6140 final String perm = bp.name; 6141 boolean allowed; 6142 boolean allowedSig = false; 6143 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6144 if (level == PermissionInfo.PROTECTION_NORMAL 6145 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6146 // We grant a normal or dangerous permission if any of the following 6147 // are true: 6148 // 1) The permission is required 6149 // 2) The permission is optional, but was granted in the past 6150 // 3) The permission is optional, but was requested by an 6151 // app in /system (not /data) 6152 // 6153 // Otherwise, reject the permission. 6154 allowed = (required || origPermissions.contains(perm) 6155 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6156 } else if (bp.packageSetting == null) { 6157 // This permission is invalid; skip it. 6158 allowed = false; 6159 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6160 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6161 if (allowed) { 6162 allowedSig = true; 6163 } 6164 } else { 6165 allowed = false; 6166 } 6167 if (DEBUG_INSTALL) { 6168 if (gp != ps) { 6169 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6170 } 6171 } 6172 if (allowed) { 6173 if (!isSystemApp(ps) && ps.permissionsFixed) { 6174 // If this is an existing, non-system package, then 6175 // we can't add any new permissions to it. 6176 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6177 // Except... if this is a permission that was added 6178 // to the platform (note: need to only do this when 6179 // updating the platform). 6180 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6181 } 6182 } 6183 if (allowed) { 6184 if (!gp.grantedPermissions.contains(perm)) { 6185 changedPermission = true; 6186 gp.grantedPermissions.add(perm); 6187 gp.gids = appendInts(gp.gids, bp.gids); 6188 } else if (!ps.haveGids) { 6189 gp.gids = appendInts(gp.gids, bp.gids); 6190 } 6191 } else { 6192 Slog.w(TAG, "Not granting permission " + perm 6193 + " to package " + pkg.packageName 6194 + " because it was previously installed without"); 6195 } 6196 } else { 6197 if (gp.grantedPermissions.remove(perm)) { 6198 changedPermission = true; 6199 gp.gids = removeInts(gp.gids, bp.gids); 6200 Slog.i(TAG, "Un-granting permission " + perm 6201 + " from package " + pkg.packageName 6202 + " (protectionLevel=" + bp.protectionLevel 6203 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6204 + ")"); 6205 } else { 6206 Slog.w(TAG, "Not granting permission " + perm 6207 + " to package " + pkg.packageName 6208 + " (protectionLevel=" + bp.protectionLevel 6209 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6210 + ")"); 6211 } 6212 } 6213 } 6214 6215 if ((changedPermission || replace) && !ps.permissionsFixed && 6216 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6217 // This is the first that we have heard about this package, so the 6218 // permissions we have now selected are fixed until explicitly 6219 // changed. 6220 ps.permissionsFixed = true; 6221 } 6222 ps.haveGids = true; 6223 } 6224 6225 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6226 boolean allowed = false; 6227 final int NP = PackageParser.NEW_PERMISSIONS.length; 6228 for (int ip=0; ip<NP; ip++) { 6229 final PackageParser.NewPermissionInfo npi 6230 = PackageParser.NEW_PERMISSIONS[ip]; 6231 if (npi.name.equals(perm) 6232 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6233 allowed = true; 6234 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6235 + pkg.packageName); 6236 break; 6237 } 6238 } 6239 return allowed; 6240 } 6241 6242 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6243 BasePermission bp, HashSet<String> origPermissions) { 6244 boolean allowed; 6245 allowed = (compareSignatures( 6246 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6247 == PackageManager.SIGNATURE_MATCH) 6248 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6249 == PackageManager.SIGNATURE_MATCH); 6250 if (!allowed && (bp.protectionLevel 6251 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6252 if (isSystemApp(pkg)) { 6253 // For updated system applications, a system permission 6254 // is granted only if it had been defined by the original application. 6255 if (isUpdatedSystemApp(pkg)) { 6256 final PackageSetting sysPs = mSettings 6257 .getDisabledSystemPkgLPr(pkg.packageName); 6258 final GrantedPermissions origGp = sysPs.sharedUser != null 6259 ? sysPs.sharedUser : sysPs; 6260 6261 if (origGp.grantedPermissions.contains(perm)) { 6262 // If the original was granted this permission, we take 6263 // that grant decision as read and propagate it to the 6264 // update. 6265 allowed = true; 6266 } else { 6267 // The system apk may have been updated with an older 6268 // version of the one on the data partition, but which 6269 // granted a new system permission that it didn't have 6270 // before. In this case we do want to allow the app to 6271 // now get the new permission if the ancestral apk is 6272 // privileged to get it. 6273 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6274 for (int j=0; 6275 j<sysPs.pkg.requestedPermissions.size(); j++) { 6276 if (perm.equals( 6277 sysPs.pkg.requestedPermissions.get(j))) { 6278 allowed = true; 6279 break; 6280 } 6281 } 6282 } 6283 } 6284 } else { 6285 allowed = isPrivilegedApp(pkg); 6286 } 6287 } 6288 } 6289 if (!allowed && (bp.protectionLevel 6290 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6291 // For development permissions, a development permission 6292 // is granted only if it was already granted. 6293 allowed = origPermissions.contains(perm); 6294 } 6295 return allowed; 6296 } 6297 6298 final class ActivityIntentResolver 6299 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6300 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6301 boolean defaultOnly, int userId) { 6302 if (!sUserManager.exists(userId)) return null; 6303 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6304 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6305 } 6306 6307 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6308 int userId) { 6309 if (!sUserManager.exists(userId)) return null; 6310 mFlags = flags; 6311 return super.queryIntent(intent, resolvedType, 6312 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6313 } 6314 6315 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6316 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6317 if (!sUserManager.exists(userId)) return null; 6318 if (packageActivities == null) { 6319 return null; 6320 } 6321 mFlags = flags; 6322 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6323 final int N = packageActivities.size(); 6324 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6325 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6326 6327 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6328 for (int i = 0; i < N; ++i) { 6329 intentFilters = packageActivities.get(i).intents; 6330 if (intentFilters != null && intentFilters.size() > 0) { 6331 PackageParser.ActivityIntentInfo[] array = 6332 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6333 intentFilters.toArray(array); 6334 listCut.add(array); 6335 } 6336 } 6337 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6338 } 6339 6340 public final void addActivity(PackageParser.Activity a, String type) { 6341 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6342 mActivities.put(a.getComponentName(), a); 6343 if (DEBUG_SHOW_INFO) 6344 Log.v( 6345 TAG, " " + type + " " + 6346 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6347 if (DEBUG_SHOW_INFO) 6348 Log.v(TAG, " Class=" + a.info.name); 6349 final int NI = a.intents.size(); 6350 for (int j=0; j<NI; j++) { 6351 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6352 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6353 intent.setPriority(0); 6354 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6355 + a.className + " with priority > 0, forcing to 0"); 6356 } 6357 if (DEBUG_SHOW_INFO) { 6358 Log.v(TAG, " IntentFilter:"); 6359 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6360 } 6361 if (!intent.debugCheck()) { 6362 Log.w(TAG, "==> For Activity " + a.info.name); 6363 } 6364 addFilter(intent); 6365 } 6366 } 6367 6368 public final void removeActivity(PackageParser.Activity a, String type) { 6369 mActivities.remove(a.getComponentName()); 6370 if (DEBUG_SHOW_INFO) { 6371 Log.v(TAG, " " + type + " " 6372 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6373 : a.info.name) + ":"); 6374 Log.v(TAG, " Class=" + a.info.name); 6375 } 6376 final int NI = a.intents.size(); 6377 for (int j=0; j<NI; j++) { 6378 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6379 if (DEBUG_SHOW_INFO) { 6380 Log.v(TAG, " IntentFilter:"); 6381 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6382 } 6383 removeFilter(intent); 6384 } 6385 } 6386 6387 @Override 6388 protected boolean allowFilterResult( 6389 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6390 ActivityInfo filterAi = filter.activity.info; 6391 for (int i=dest.size()-1; i>=0; i--) { 6392 ActivityInfo destAi = dest.get(i).activityInfo; 6393 if (destAi.name == filterAi.name 6394 && destAi.packageName == filterAi.packageName) { 6395 return false; 6396 } 6397 } 6398 return true; 6399 } 6400 6401 @Override 6402 protected ActivityIntentInfo[] newArray(int size) { 6403 return new ActivityIntentInfo[size]; 6404 } 6405 6406 @Override 6407 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6408 if (!sUserManager.exists(userId)) return true; 6409 PackageParser.Package p = filter.activity.owner; 6410 if (p != null) { 6411 PackageSetting ps = (PackageSetting)p.mExtras; 6412 if (ps != null) { 6413 // System apps are never considered stopped for purposes of 6414 // filtering, because there may be no way for the user to 6415 // actually re-launch them. 6416 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6417 && ps.getStopped(userId); 6418 } 6419 } 6420 return false; 6421 } 6422 6423 @Override 6424 protected boolean isPackageForFilter(String packageName, 6425 PackageParser.ActivityIntentInfo info) { 6426 return packageName.equals(info.activity.owner.packageName); 6427 } 6428 6429 @Override 6430 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6431 int match, int userId) { 6432 if (!sUserManager.exists(userId)) return null; 6433 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6434 return null; 6435 } 6436 final PackageParser.Activity activity = info.activity; 6437 if (mSafeMode && (activity.info.applicationInfo.flags 6438 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6439 return null; 6440 } 6441 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6442 if (ps == null) { 6443 return null; 6444 } 6445 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6446 ps.readUserState(userId), userId); 6447 if (ai == null) { 6448 return null; 6449 } 6450 final ResolveInfo res = new ResolveInfo(); 6451 res.activityInfo = ai; 6452 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6453 res.filter = info; 6454 } 6455 res.priority = info.getPriority(); 6456 res.preferredOrder = activity.owner.mPreferredOrder; 6457 //System.out.println("Result: " + res.activityInfo.className + 6458 // " = " + res.priority); 6459 res.match = match; 6460 res.isDefault = info.hasDefault; 6461 res.labelRes = info.labelRes; 6462 res.nonLocalizedLabel = info.nonLocalizedLabel; 6463 res.icon = info.icon; 6464 res.system = isSystemApp(res.activityInfo.applicationInfo); 6465 return res; 6466 } 6467 6468 @Override 6469 protected void sortResults(List<ResolveInfo> results) { 6470 Collections.sort(results, mResolvePrioritySorter); 6471 } 6472 6473 @Override 6474 protected void dumpFilter(PrintWriter out, String prefix, 6475 PackageParser.ActivityIntentInfo filter) { 6476 out.print(prefix); out.print( 6477 Integer.toHexString(System.identityHashCode(filter.activity))); 6478 out.print(' '); 6479 filter.activity.printComponentShortName(out); 6480 out.print(" filter "); 6481 out.println(Integer.toHexString(System.identityHashCode(filter))); 6482 } 6483 6484// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6485// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6486// final List<ResolveInfo> retList = Lists.newArrayList(); 6487// while (i.hasNext()) { 6488// final ResolveInfo resolveInfo = i.next(); 6489// if (isEnabledLP(resolveInfo.activityInfo)) { 6490// retList.add(resolveInfo); 6491// } 6492// } 6493// return retList; 6494// } 6495 6496 // Keys are String (activity class name), values are Activity. 6497 private final HashMap<ComponentName, PackageParser.Activity> mActivities 6498 = new HashMap<ComponentName, PackageParser.Activity>(); 6499 private int mFlags; 6500 } 6501 6502 private final class ServiceIntentResolver 6503 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 6504 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6505 boolean defaultOnly, int userId) { 6506 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6507 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6508 } 6509 6510 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6511 int userId) { 6512 if (!sUserManager.exists(userId)) return null; 6513 mFlags = flags; 6514 return super.queryIntent(intent, resolvedType, 6515 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6516 } 6517 6518 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6519 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 6520 if (!sUserManager.exists(userId)) return null; 6521 if (packageServices == null) { 6522 return null; 6523 } 6524 mFlags = flags; 6525 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6526 final int N = packageServices.size(); 6527 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 6528 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 6529 6530 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 6531 for (int i = 0; i < N; ++i) { 6532 intentFilters = packageServices.get(i).intents; 6533 if (intentFilters != null && intentFilters.size() > 0) { 6534 PackageParser.ServiceIntentInfo[] array = 6535 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 6536 intentFilters.toArray(array); 6537 listCut.add(array); 6538 } 6539 } 6540 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6541 } 6542 6543 public final void addService(PackageParser.Service s) { 6544 mServices.put(s.getComponentName(), s); 6545 if (DEBUG_SHOW_INFO) { 6546 Log.v(TAG, " " 6547 + (s.info.nonLocalizedLabel != null 6548 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6549 Log.v(TAG, " Class=" + s.info.name); 6550 } 6551 final int NI = s.intents.size(); 6552 int j; 6553 for (j=0; j<NI; j++) { 6554 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6555 if (DEBUG_SHOW_INFO) { 6556 Log.v(TAG, " IntentFilter:"); 6557 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6558 } 6559 if (!intent.debugCheck()) { 6560 Log.w(TAG, "==> For Service " + s.info.name); 6561 } 6562 addFilter(intent); 6563 } 6564 } 6565 6566 public final void removeService(PackageParser.Service s) { 6567 mServices.remove(s.getComponentName()); 6568 if (DEBUG_SHOW_INFO) { 6569 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 6570 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6571 Log.v(TAG, " Class=" + s.info.name); 6572 } 6573 final int NI = s.intents.size(); 6574 int j; 6575 for (j=0; j<NI; j++) { 6576 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6577 if (DEBUG_SHOW_INFO) { 6578 Log.v(TAG, " IntentFilter:"); 6579 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6580 } 6581 removeFilter(intent); 6582 } 6583 } 6584 6585 @Override 6586 protected boolean allowFilterResult( 6587 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 6588 ServiceInfo filterSi = filter.service.info; 6589 for (int i=dest.size()-1; i>=0; i--) { 6590 ServiceInfo destAi = dest.get(i).serviceInfo; 6591 if (destAi.name == filterSi.name 6592 && destAi.packageName == filterSi.packageName) { 6593 return false; 6594 } 6595 } 6596 return true; 6597 } 6598 6599 @Override 6600 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 6601 return new PackageParser.ServiceIntentInfo[size]; 6602 } 6603 6604 @Override 6605 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 6606 if (!sUserManager.exists(userId)) return true; 6607 PackageParser.Package p = filter.service.owner; 6608 if (p != null) { 6609 PackageSetting ps = (PackageSetting)p.mExtras; 6610 if (ps != null) { 6611 // System apps are never considered stopped for purposes of 6612 // filtering, because there may be no way for the user to 6613 // actually re-launch them. 6614 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 6615 && ps.getStopped(userId); 6616 } 6617 } 6618 return false; 6619 } 6620 6621 @Override 6622 protected boolean isPackageForFilter(String packageName, 6623 PackageParser.ServiceIntentInfo info) { 6624 return packageName.equals(info.service.owner.packageName); 6625 } 6626 6627 @Override 6628 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 6629 int match, int userId) { 6630 if (!sUserManager.exists(userId)) return null; 6631 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 6632 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 6633 return null; 6634 } 6635 final PackageParser.Service service = info.service; 6636 if (mSafeMode && (service.info.applicationInfo.flags 6637 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6638 return null; 6639 } 6640 PackageSetting ps = (PackageSetting) service.owner.mExtras; 6641 if (ps == null) { 6642 return null; 6643 } 6644 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 6645 ps.readUserState(userId), userId); 6646 if (si == null) { 6647 return null; 6648 } 6649 final ResolveInfo res = new ResolveInfo(); 6650 res.serviceInfo = si; 6651 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6652 res.filter = filter; 6653 } 6654 res.priority = info.getPriority(); 6655 res.preferredOrder = service.owner.mPreferredOrder; 6656 //System.out.println("Result: " + res.activityInfo.className + 6657 // " = " + res.priority); 6658 res.match = match; 6659 res.isDefault = info.hasDefault; 6660 res.labelRes = info.labelRes; 6661 res.nonLocalizedLabel = info.nonLocalizedLabel; 6662 res.icon = info.icon; 6663 res.system = isSystemApp(res.serviceInfo.applicationInfo); 6664 return res; 6665 } 6666 6667 @Override 6668 protected void sortResults(List<ResolveInfo> results) { 6669 Collections.sort(results, mResolvePrioritySorter); 6670 } 6671 6672 @Override 6673 protected void dumpFilter(PrintWriter out, String prefix, 6674 PackageParser.ServiceIntentInfo filter) { 6675 out.print(prefix); out.print( 6676 Integer.toHexString(System.identityHashCode(filter.service))); 6677 out.print(' '); 6678 filter.service.printComponentShortName(out); 6679 out.print(" filter "); 6680 out.println(Integer.toHexString(System.identityHashCode(filter))); 6681 } 6682 6683// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6684// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6685// final List<ResolveInfo> retList = Lists.newArrayList(); 6686// while (i.hasNext()) { 6687// final ResolveInfo resolveInfo = (ResolveInfo) i; 6688// if (isEnabledLP(resolveInfo.serviceInfo)) { 6689// retList.add(resolveInfo); 6690// } 6691// } 6692// return retList; 6693// } 6694 6695 // Keys are String (activity class name), values are Activity. 6696 private final HashMap<ComponentName, PackageParser.Service> mServices 6697 = new HashMap<ComponentName, PackageParser.Service>(); 6698 private int mFlags; 6699 }; 6700 6701 private final class ProviderIntentResolver 6702 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 6703 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6704 boolean defaultOnly, int userId) { 6705 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6706 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6707 } 6708 6709 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6710 int userId) { 6711 if (!sUserManager.exists(userId)) 6712 return null; 6713 mFlags = flags; 6714 return super.queryIntent(intent, resolvedType, 6715 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6716 } 6717 6718 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6719 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 6720 if (!sUserManager.exists(userId)) 6721 return null; 6722 if (packageProviders == null) { 6723 return null; 6724 } 6725 mFlags = flags; 6726 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 6727 final int N = packageProviders.size(); 6728 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 6729 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 6730 6731 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 6732 for (int i = 0; i < N; ++i) { 6733 intentFilters = packageProviders.get(i).intents; 6734 if (intentFilters != null && intentFilters.size() > 0) { 6735 PackageParser.ProviderIntentInfo[] array = 6736 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 6737 intentFilters.toArray(array); 6738 listCut.add(array); 6739 } 6740 } 6741 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6742 } 6743 6744 public final void addProvider(PackageParser.Provider p) { 6745 if (mProviders.containsKey(p.getComponentName())) { 6746 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 6747 return; 6748 } 6749 6750 mProviders.put(p.getComponentName(), p); 6751 if (DEBUG_SHOW_INFO) { 6752 Log.v(TAG, " " 6753 + (p.info.nonLocalizedLabel != null 6754 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 6755 Log.v(TAG, " Class=" + p.info.name); 6756 } 6757 final int NI = p.intents.size(); 6758 int j; 6759 for (j = 0; j < NI; j++) { 6760 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 6761 if (DEBUG_SHOW_INFO) { 6762 Log.v(TAG, " IntentFilter:"); 6763 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6764 } 6765 if (!intent.debugCheck()) { 6766 Log.w(TAG, "==> For Provider " + p.info.name); 6767 } 6768 addFilter(intent); 6769 } 6770 } 6771 6772 public final void removeProvider(PackageParser.Provider p) { 6773 mProviders.remove(p.getComponentName()); 6774 if (DEBUG_SHOW_INFO) { 6775 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 6776 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 6777 Log.v(TAG, " Class=" + p.info.name); 6778 } 6779 final int NI = p.intents.size(); 6780 int j; 6781 for (j = 0; j < NI; j++) { 6782 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 6783 if (DEBUG_SHOW_INFO) { 6784 Log.v(TAG, " IntentFilter:"); 6785 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6786 } 6787 removeFilter(intent); 6788 } 6789 } 6790 6791 @Override 6792 protected boolean allowFilterResult( 6793 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 6794 ProviderInfo filterPi = filter.provider.info; 6795 for (int i = dest.size() - 1; i >= 0; i--) { 6796 ProviderInfo destPi = dest.get(i).providerInfo; 6797 if (destPi.name == filterPi.name 6798 && destPi.packageName == filterPi.packageName) { 6799 return false; 6800 } 6801 } 6802 return true; 6803 } 6804 6805 @Override 6806 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 6807 return new PackageParser.ProviderIntentInfo[size]; 6808 } 6809 6810 @Override 6811 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 6812 if (!sUserManager.exists(userId)) 6813 return true; 6814 PackageParser.Package p = filter.provider.owner; 6815 if (p != null) { 6816 PackageSetting ps = (PackageSetting) p.mExtras; 6817 if (ps != null) { 6818 // System apps are never considered stopped for purposes of 6819 // filtering, because there may be no way for the user to 6820 // actually re-launch them. 6821 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 6822 && ps.getStopped(userId); 6823 } 6824 } 6825 return false; 6826 } 6827 6828 @Override 6829 protected boolean isPackageForFilter(String packageName, 6830 PackageParser.ProviderIntentInfo info) { 6831 return packageName.equals(info.provider.owner.packageName); 6832 } 6833 6834 @Override 6835 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 6836 int match, int userId) { 6837 if (!sUserManager.exists(userId)) 6838 return null; 6839 final PackageParser.ProviderIntentInfo info = filter; 6840 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 6841 return null; 6842 } 6843 final PackageParser.Provider provider = info.provider; 6844 if (mSafeMode && (provider.info.applicationInfo.flags 6845 & ApplicationInfo.FLAG_SYSTEM) == 0) { 6846 return null; 6847 } 6848 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 6849 if (ps == null) { 6850 return null; 6851 } 6852 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 6853 ps.readUserState(userId), userId); 6854 if (pi == null) { 6855 return null; 6856 } 6857 final ResolveInfo res = new ResolveInfo(); 6858 res.providerInfo = pi; 6859 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 6860 res.filter = filter; 6861 } 6862 res.priority = info.getPriority(); 6863 res.preferredOrder = provider.owner.mPreferredOrder; 6864 res.match = match; 6865 res.isDefault = info.hasDefault; 6866 res.labelRes = info.labelRes; 6867 res.nonLocalizedLabel = info.nonLocalizedLabel; 6868 res.icon = info.icon; 6869 res.system = isSystemApp(res.providerInfo.applicationInfo); 6870 return res; 6871 } 6872 6873 @Override 6874 protected void sortResults(List<ResolveInfo> results) { 6875 Collections.sort(results, mResolvePrioritySorter); 6876 } 6877 6878 @Override 6879 protected void dumpFilter(PrintWriter out, String prefix, 6880 PackageParser.ProviderIntentInfo filter) { 6881 out.print(prefix); 6882 out.print( 6883 Integer.toHexString(System.identityHashCode(filter.provider))); 6884 out.print(' '); 6885 filter.provider.printComponentShortName(out); 6886 out.print(" filter "); 6887 out.println(Integer.toHexString(System.identityHashCode(filter))); 6888 } 6889 6890 private final HashMap<ComponentName, PackageParser.Provider> mProviders 6891 = new HashMap<ComponentName, PackageParser.Provider>(); 6892 private int mFlags; 6893 }; 6894 6895 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 6896 new Comparator<ResolveInfo>() { 6897 public int compare(ResolveInfo r1, ResolveInfo r2) { 6898 int v1 = r1.priority; 6899 int v2 = r2.priority; 6900 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 6901 if (v1 != v2) { 6902 return (v1 > v2) ? -1 : 1; 6903 } 6904 v1 = r1.preferredOrder; 6905 v2 = r2.preferredOrder; 6906 if (v1 != v2) { 6907 return (v1 > v2) ? -1 : 1; 6908 } 6909 if (r1.isDefault != r2.isDefault) { 6910 return r1.isDefault ? -1 : 1; 6911 } 6912 v1 = r1.match; 6913 v2 = r2.match; 6914 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 6915 if (v1 != v2) { 6916 return (v1 > v2) ? -1 : 1; 6917 } 6918 if (r1.system != r2.system) { 6919 return r1.system ? -1 : 1; 6920 } 6921 return 0; 6922 } 6923 }; 6924 6925 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 6926 new Comparator<ProviderInfo>() { 6927 public int compare(ProviderInfo p1, ProviderInfo p2) { 6928 final int v1 = p1.initOrder; 6929 final int v2 = p2.initOrder; 6930 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 6931 } 6932 }; 6933 6934 static final void sendPackageBroadcast(String action, String pkg, 6935 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 6936 int[] userIds) { 6937 IActivityManager am = ActivityManagerNative.getDefault(); 6938 if (am != null) { 6939 try { 6940 if (userIds == null) { 6941 userIds = am.getRunningUserIds(); 6942 } 6943 for (int id : userIds) { 6944 final Intent intent = new Intent(action, 6945 pkg != null ? Uri.fromParts("package", pkg, null) : null); 6946 if (extras != null) { 6947 intent.putExtras(extras); 6948 } 6949 if (targetPkg != null) { 6950 intent.setPackage(targetPkg); 6951 } 6952 // Modify the UID when posting to other users 6953 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 6954 if (uid > 0 && UserHandle.getUserId(uid) != id) { 6955 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 6956 intent.putExtra(Intent.EXTRA_UID, uid); 6957 } 6958 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 6959 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 6960 if (DEBUG_BROADCASTS) { 6961 RuntimeException here = new RuntimeException("here"); 6962 here.fillInStackTrace(); 6963 Slog.d(TAG, "Sending to user " + id + ": " 6964 + intent.toShortString(false, true, false, false) 6965 + " " + intent.getExtras(), here); 6966 } 6967 am.broadcastIntent(null, intent, null, finishedReceiver, 6968 0, null, null, null, android.app.AppOpsManager.OP_NONE, 6969 finishedReceiver != null, false, id); 6970 } 6971 } catch (RemoteException ex) { 6972 } 6973 } 6974 } 6975 6976 /** 6977 * Check if the external storage media is available. This is true if there 6978 * is a mounted external storage medium or if the external storage is 6979 * emulated. 6980 */ 6981 private boolean isExternalMediaAvailable() { 6982 return mMediaMounted || Environment.isExternalStorageEmulated(); 6983 } 6984 6985 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 6986 // writer 6987 synchronized (mPackages) { 6988 if (!isExternalMediaAvailable()) { 6989 // If the external storage is no longer mounted at this point, 6990 // the caller may not have been able to delete all of this 6991 // packages files and can not delete any more. Bail. 6992 return null; 6993 } 6994 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 6995 if (lastPackage != null) { 6996 pkgs.remove(lastPackage); 6997 } 6998 if (pkgs.size() > 0) { 6999 return pkgs.get(0); 7000 } 7001 } 7002 return null; 7003 } 7004 7005 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7006 if (false) { 7007 RuntimeException here = new RuntimeException("here"); 7008 here.fillInStackTrace(); 7009 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7010 + " andCode=" + andCode, here); 7011 } 7012 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7013 userId, andCode ? 1 : 0, packageName)); 7014 } 7015 7016 void startCleaningPackages() { 7017 // reader 7018 synchronized (mPackages) { 7019 if (!isExternalMediaAvailable()) { 7020 return; 7021 } 7022 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7023 return; 7024 } 7025 } 7026 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7027 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7028 IActivityManager am = ActivityManagerNative.getDefault(); 7029 if (am != null) { 7030 try { 7031 am.startService(null, intent, null, UserHandle.USER_OWNER); 7032 } catch (RemoteException e) { 7033 } 7034 } 7035 } 7036 7037 private final class AppDirObserver extends FileObserver { 7038 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7039 super(path, mask); 7040 mRootDir = path; 7041 mIsRom = isrom; 7042 mIsPrivileged = isPrivileged; 7043 } 7044 7045 public void onEvent(int event, String path) { 7046 String removedPackage = null; 7047 int removedAppId = -1; 7048 int[] removedUsers = null; 7049 String addedPackage = null; 7050 int addedAppId = -1; 7051 int[] addedUsers = null; 7052 7053 // TODO post a message to the handler to obtain serial ordering 7054 synchronized (mInstallLock) { 7055 String fullPathStr = null; 7056 File fullPath = null; 7057 if (path != null) { 7058 fullPath = new File(mRootDir, path); 7059 fullPathStr = fullPath.getPath(); 7060 } 7061 7062 if (DEBUG_APP_DIR_OBSERVER) 7063 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7064 7065 if (!isPackageFilename(path)) { 7066 if (DEBUG_APP_DIR_OBSERVER) 7067 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7068 return; 7069 } 7070 7071 // Ignore packages that are being installed or 7072 // have just been installed. 7073 if (ignoreCodePath(fullPathStr)) { 7074 return; 7075 } 7076 PackageParser.Package p = null; 7077 PackageSetting ps = null; 7078 // reader 7079 synchronized (mPackages) { 7080 p = mAppDirs.get(fullPathStr); 7081 if (p != null) { 7082 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7083 if (ps != null) { 7084 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7085 } else { 7086 removedUsers = sUserManager.getUserIds(); 7087 } 7088 } 7089 addedUsers = sUserManager.getUserIds(); 7090 } 7091 if ((event&REMOVE_EVENTS) != 0) { 7092 if (ps != null) { 7093 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7094 removePackageLI(ps, true); 7095 removedPackage = ps.name; 7096 removedAppId = ps.appId; 7097 } 7098 } 7099 7100 if ((event&ADD_EVENTS) != 0) { 7101 if (p == null) { 7102 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7103 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7104 if (mIsRom) { 7105 flags |= PackageParser.PARSE_IS_SYSTEM 7106 | PackageParser.PARSE_IS_SYSTEM_DIR; 7107 if (mIsPrivileged) { 7108 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7109 } 7110 } 7111 p = scanPackageLI(fullPath, flags, 7112 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7113 System.currentTimeMillis(), UserHandle.ALL); 7114 if (p != null) { 7115 /* 7116 * TODO this seems dangerous as the package may have 7117 * changed since we last acquired the mPackages 7118 * lock. 7119 */ 7120 // writer 7121 synchronized (mPackages) { 7122 updatePermissionsLPw(p.packageName, p, 7123 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7124 } 7125 addedPackage = p.applicationInfo.packageName; 7126 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7127 } 7128 } 7129 } 7130 7131 // reader 7132 synchronized (mPackages) { 7133 mSettings.writeLPr(); 7134 } 7135 } 7136 7137 if (removedPackage != null) { 7138 Bundle extras = new Bundle(1); 7139 extras.putInt(Intent.EXTRA_UID, removedAppId); 7140 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7141 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7142 extras, null, null, removedUsers); 7143 } 7144 if (addedPackage != null) { 7145 Bundle extras = new Bundle(1); 7146 extras.putInt(Intent.EXTRA_UID, addedAppId); 7147 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7148 extras, null, null, addedUsers); 7149 } 7150 } 7151 7152 private final String mRootDir; 7153 private final boolean mIsRom; 7154 private final boolean mIsPrivileged; 7155 } 7156 7157 /* 7158 * The old-style observer methods all just trampoline to the newer signature with 7159 * expanded install observer API. The older API continues to work but does not 7160 * supply the additional details of the Observer2 API. 7161 */ 7162 7163 /* Called when a downloaded package installation has been confirmed by the user */ 7164 public void installPackage( 7165 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 7166 installPackageEtc(packageURI, observer, null, flags, null); 7167 } 7168 7169 /* Called when a downloaded package installation has been confirmed by the user */ 7170 public void installPackage( 7171 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 7172 final String installerPackageName) { 7173 installPackageWithVerificationEtc(packageURI, observer, null, flags, 7174 installerPackageName, null, null, null); 7175 } 7176 7177 @Override 7178 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 7179 int flags, String installerPackageName, Uri verificationURI, 7180 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7181 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7182 VerificationParams.NO_UID, manifestDigest); 7183 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7184 installerPackageName, verificationParams, encryptionParams); 7185 } 7186 7187 public void installPackageWithVerificationAndEncryption(Uri packageURI, 7188 IPackageInstallObserver observer, int flags, String installerPackageName, 7189 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7190 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7191 installerPackageName, verificationParams, encryptionParams); 7192 } 7193 7194 /* 7195 * And here are the "live" versions that take both observer arguments 7196 */ 7197 public void installPackageEtc( 7198 final Uri packageURI, final IPackageInstallObserver observer, 7199 IPackageInstallObserver2 observer2, final int flags) { 7200 installPackageEtc(packageURI, observer, observer2, flags, null); 7201 } 7202 7203 public void installPackageEtc( 7204 final Uri packageURI, final IPackageInstallObserver observer, 7205 final IPackageInstallObserver2 observer2, final int flags, 7206 final String installerPackageName) { 7207 installPackageWithVerificationEtc(packageURI, observer, observer2, flags, 7208 installerPackageName, null, null, null); 7209 } 7210 7211 @Override 7212 public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer, 7213 IPackageInstallObserver2 observer2, 7214 int flags, String installerPackageName, Uri verificationURI, 7215 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7216 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7217 VerificationParams.NO_UID, manifestDigest); 7218 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags, 7219 installerPackageName, verificationParams, encryptionParams); 7220 } 7221 7222 /* 7223 * All of the installPackage...*() methods redirect to this one for the master implementation 7224 */ 7225 public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI, 7226 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7227 int flags, String installerPackageName, 7228 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7229 if (observer == null && observer2 == null) { 7230 throw new IllegalArgumentException("No install observer supplied"); 7231 } 7232 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7233 null); 7234 7235 final int uid = Binder.getCallingUid(); 7236 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7237 try { 7238 if (observer != null) { 7239 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7240 } 7241 if (observer2 != null) { 7242 observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7243 } 7244 } catch (RemoteException re) { 7245 } 7246 return; 7247 } 7248 7249 UserHandle user; 7250 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7251 user = UserHandle.ALL; 7252 } else { 7253 user = new UserHandle(UserHandle.getUserId(uid)); 7254 } 7255 7256 final int filteredFlags; 7257 7258 if (uid == Process.SHELL_UID || uid == 0) { 7259 if (DEBUG_INSTALL) { 7260 Slog.v(TAG, "Install from ADB"); 7261 } 7262 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7263 } else { 7264 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7265 } 7266 7267 verificationParams.setInstallerUid(uid); 7268 7269 final Message msg = mHandler.obtainMessage(INIT_COPY); 7270 msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags, 7271 installerPackageName, verificationParams, encryptionParams, user); 7272 mHandler.sendMessage(msg); 7273 } 7274 7275 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7276 Bundle extras = new Bundle(1); 7277 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7278 7279 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7280 packageName, extras, null, null, new int[] {userId}); 7281 try { 7282 IActivityManager am = ActivityManagerNative.getDefault(); 7283 final boolean isSystem = 7284 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7285 if (isSystem && am.isUserRunning(userId, false)) { 7286 // The just-installed/enabled app is bundled on the system, so presumed 7287 // to be able to run automatically without needing an explicit launch. 7288 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7289 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7290 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7291 .setPackage(packageName); 7292 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7293 android.app.AppOpsManager.OP_NONE, false, false, userId); 7294 } 7295 } catch (RemoteException e) { 7296 // shouldn't happen 7297 Slog.w(TAG, "Unable to bootstrap installed package", e); 7298 } 7299 } 7300 7301 @Override 7302 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7303 int userId) { 7304 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7305 PackageSetting pkgSetting; 7306 final int uid = Binder.getCallingUid(); 7307 if (UserHandle.getUserId(uid) != userId) { 7308 mContext.enforceCallingOrSelfPermission( 7309 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7310 "setApplicationBlockedSetting for user " + userId); 7311 } 7312 7313 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7314 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7315 return false; 7316 } 7317 7318 long callingId = Binder.clearCallingIdentity(); 7319 try { 7320 boolean sendAdded = false; 7321 boolean sendRemoved = false; 7322 // writer 7323 synchronized (mPackages) { 7324 pkgSetting = mSettings.mPackages.get(packageName); 7325 if (pkgSetting == null) { 7326 return false; 7327 } 7328 if (pkgSetting.getBlocked(userId) != blocked) { 7329 pkgSetting.setBlocked(blocked, userId); 7330 mSettings.writePackageRestrictionsLPr(userId); 7331 if (blocked) { 7332 sendRemoved = true; 7333 } else { 7334 sendAdded = true; 7335 } 7336 } 7337 } 7338 if (sendAdded) { 7339 sendPackageAddedForUser(packageName, pkgSetting, userId); 7340 return true; 7341 } 7342 if (sendRemoved) { 7343 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7344 "blocking pkg"); 7345 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7346 } 7347 } finally { 7348 Binder.restoreCallingIdentity(callingId); 7349 } 7350 return false; 7351 } 7352 7353 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7354 int userId) { 7355 final PackageRemovedInfo info = new PackageRemovedInfo(); 7356 info.removedPackage = packageName; 7357 info.removedUsers = new int[] {userId}; 7358 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7359 info.sendBroadcast(false, false, false); 7360 } 7361 7362 /** 7363 * Returns true if application is not found or there was an error. Otherwise it returns 7364 * the blocked state of the package for the given user. 7365 */ 7366 @Override 7367 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7368 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7369 PackageSetting pkgSetting; 7370 final int uid = Binder.getCallingUid(); 7371 if (UserHandle.getUserId(uid) != userId) { 7372 mContext.enforceCallingPermission( 7373 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7374 "getApplicationBlocked for user " + userId); 7375 } 7376 long callingId = Binder.clearCallingIdentity(); 7377 try { 7378 // writer 7379 synchronized (mPackages) { 7380 pkgSetting = mSettings.mPackages.get(packageName); 7381 if (pkgSetting == null) { 7382 return true; 7383 } 7384 return pkgSetting.getBlocked(userId); 7385 } 7386 } finally { 7387 Binder.restoreCallingIdentity(callingId); 7388 } 7389 } 7390 7391 /** 7392 * @hide 7393 */ 7394 @Override 7395 public int installExistingPackageAsUser(String packageName, int userId) { 7396 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7397 null); 7398 PackageSetting pkgSetting; 7399 final int uid = Binder.getCallingUid(); 7400 if (UserHandle.getUserId(uid) != userId) { 7401 mContext.enforceCallingPermission( 7402 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7403 "installExistingPackage for user " + userId); 7404 } 7405 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7406 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7407 } 7408 7409 long callingId = Binder.clearCallingIdentity(); 7410 try { 7411 boolean sendAdded = false; 7412 Bundle extras = new Bundle(1); 7413 7414 // writer 7415 synchronized (mPackages) { 7416 pkgSetting = mSettings.mPackages.get(packageName); 7417 if (pkgSetting == null) { 7418 return PackageManager.INSTALL_FAILED_INVALID_URI; 7419 } 7420 if (!pkgSetting.getInstalled(userId)) { 7421 pkgSetting.setInstalled(true, userId); 7422 pkgSetting.setBlocked(false, userId); 7423 mSettings.writePackageRestrictionsLPr(userId); 7424 sendAdded = true; 7425 } 7426 } 7427 7428 if (sendAdded) { 7429 sendPackageAddedForUser(packageName, pkgSetting, userId); 7430 } 7431 } finally { 7432 Binder.restoreCallingIdentity(callingId); 7433 } 7434 7435 return PackageManager.INSTALL_SUCCEEDED; 7436 } 7437 7438 private boolean isUserRestricted(int userId, String restrictionKey) { 7439 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7440 if (restrictions.getBoolean(restrictionKey, false)) { 7441 Log.w(TAG, "User is restricted: " + restrictionKey); 7442 return true; 7443 } 7444 return false; 7445 } 7446 7447 @Override 7448 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7449 mContext.enforceCallingOrSelfPermission( 7450 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7451 "Only package verification agents can verify applications"); 7452 7453 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7454 final PackageVerificationResponse response = new PackageVerificationResponse( 7455 verificationCode, Binder.getCallingUid()); 7456 msg.arg1 = id; 7457 msg.obj = response; 7458 mHandler.sendMessage(msg); 7459 } 7460 7461 @Override 7462 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7463 long millisecondsToDelay) { 7464 mContext.enforceCallingOrSelfPermission( 7465 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7466 "Only package verification agents can extend verification timeouts"); 7467 7468 final PackageVerificationState state = mPendingVerification.get(id); 7469 final PackageVerificationResponse response = new PackageVerificationResponse( 7470 verificationCodeAtTimeout, Binder.getCallingUid()); 7471 7472 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7473 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7474 } 7475 if (millisecondsToDelay < 0) { 7476 millisecondsToDelay = 0; 7477 } 7478 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7479 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7480 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7481 } 7482 7483 if ((state != null) && !state.timeoutExtended()) { 7484 state.extendTimeout(); 7485 7486 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7487 msg.arg1 = id; 7488 msg.obj = response; 7489 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7490 } 7491 } 7492 7493 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7494 int verificationCode, UserHandle user) { 7495 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7496 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7497 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7498 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7499 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7500 7501 mContext.sendBroadcastAsUser(intent, user, 7502 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7503 } 7504 7505 private ComponentName matchComponentForVerifier(String packageName, 7506 List<ResolveInfo> receivers) { 7507 ActivityInfo targetReceiver = null; 7508 7509 final int NR = receivers.size(); 7510 for (int i = 0; i < NR; i++) { 7511 final ResolveInfo info = receivers.get(i); 7512 if (info.activityInfo == null) { 7513 continue; 7514 } 7515 7516 if (packageName.equals(info.activityInfo.packageName)) { 7517 targetReceiver = info.activityInfo; 7518 break; 7519 } 7520 } 7521 7522 if (targetReceiver == null) { 7523 return null; 7524 } 7525 7526 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 7527 } 7528 7529 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 7530 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 7531 if (pkgInfo.verifiers.length == 0) { 7532 return null; 7533 } 7534 7535 final int N = pkgInfo.verifiers.length; 7536 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 7537 for (int i = 0; i < N; i++) { 7538 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 7539 7540 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 7541 receivers); 7542 if (comp == null) { 7543 continue; 7544 } 7545 7546 final int verifierUid = getUidForVerifier(verifierInfo); 7547 if (verifierUid == -1) { 7548 continue; 7549 } 7550 7551 if (DEBUG_VERIFY) { 7552 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 7553 + " with the correct signature"); 7554 } 7555 sufficientVerifiers.add(comp); 7556 verificationState.addSufficientVerifier(verifierUid); 7557 } 7558 7559 return sufficientVerifiers; 7560 } 7561 7562 private int getUidForVerifier(VerifierInfo verifierInfo) { 7563 synchronized (mPackages) { 7564 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 7565 if (pkg == null) { 7566 return -1; 7567 } else if (pkg.mSignatures.length != 1) { 7568 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7569 + " has more than one signature; ignoring"); 7570 return -1; 7571 } 7572 7573 /* 7574 * If the public key of the package's signature does not match 7575 * our expected public key, then this is a different package and 7576 * we should skip. 7577 */ 7578 7579 final byte[] expectedPublicKey; 7580 try { 7581 final Signature verifierSig = pkg.mSignatures[0]; 7582 final PublicKey publicKey = verifierSig.getPublicKey(); 7583 expectedPublicKey = publicKey.getEncoded(); 7584 } catch (CertificateException e) { 7585 return -1; 7586 } 7587 7588 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 7589 7590 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 7591 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7592 + " does not have the expected public key; ignoring"); 7593 return -1; 7594 } 7595 7596 return pkg.applicationInfo.uid; 7597 } 7598 } 7599 7600 public void finishPackageInstall(int token) { 7601 enforceSystemOrRoot("Only the system is allowed to finish installs"); 7602 7603 if (DEBUG_INSTALL) { 7604 Slog.v(TAG, "BM finishing package install for " + token); 7605 } 7606 7607 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 7608 mHandler.sendMessage(msg); 7609 } 7610 7611 /** 7612 * Get the verification agent timeout. 7613 * 7614 * @return verification timeout in milliseconds 7615 */ 7616 private long getVerificationTimeout() { 7617 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 7618 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 7619 DEFAULT_VERIFICATION_TIMEOUT); 7620 } 7621 7622 /** 7623 * Get the default verification agent response code. 7624 * 7625 * @return default verification response code 7626 */ 7627 private int getDefaultVerificationResponse() { 7628 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7629 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 7630 DEFAULT_VERIFICATION_RESPONSE); 7631 } 7632 7633 /** 7634 * Check whether or not package verification has been enabled. 7635 * 7636 * @return true if verification should be performed 7637 */ 7638 private boolean isVerificationEnabled(int flags) { 7639 if (!DEFAULT_VERIFY_ENABLE) { 7640 return false; 7641 } 7642 7643 // Check if installing from ADB 7644 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 7645 // Do not run verification in a test harness environment 7646 if (ActivityManager.isRunningInTestHarness()) { 7647 return false; 7648 } 7649 // Check if the developer does not want package verification for ADB installs 7650 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7651 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 7652 return false; 7653 } 7654 } 7655 7656 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7657 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 7658 } 7659 7660 /** 7661 * Get the "allow unknown sources" setting. 7662 * 7663 * @return the current "allow unknown sources" setting 7664 */ 7665 private int getUnknownSourcesSettings() { 7666 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7667 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 7668 -1); 7669 } 7670 7671 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 7672 final int uid = Binder.getCallingUid(); 7673 // writer 7674 synchronized (mPackages) { 7675 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 7676 if (targetPackageSetting == null) { 7677 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 7678 } 7679 7680 PackageSetting installerPackageSetting; 7681 if (installerPackageName != null) { 7682 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 7683 if (installerPackageSetting == null) { 7684 throw new IllegalArgumentException("Unknown installer package: " 7685 + installerPackageName); 7686 } 7687 } else { 7688 installerPackageSetting = null; 7689 } 7690 7691 Signature[] callerSignature; 7692 Object obj = mSettings.getUserIdLPr(uid); 7693 if (obj != null) { 7694 if (obj instanceof SharedUserSetting) { 7695 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 7696 } else if (obj instanceof PackageSetting) { 7697 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 7698 } else { 7699 throw new SecurityException("Bad object " + obj + " for uid " + uid); 7700 } 7701 } else { 7702 throw new SecurityException("Unknown calling uid " + uid); 7703 } 7704 7705 // Verify: can't set installerPackageName to a package that is 7706 // not signed with the same cert as the caller. 7707 if (installerPackageSetting != null) { 7708 if (compareSignatures(callerSignature, 7709 installerPackageSetting.signatures.mSignatures) 7710 != PackageManager.SIGNATURE_MATCH) { 7711 throw new SecurityException( 7712 "Caller does not have same cert as new installer package " 7713 + installerPackageName); 7714 } 7715 } 7716 7717 // Verify: if target already has an installer package, it must 7718 // be signed with the same cert as the caller. 7719 if (targetPackageSetting.installerPackageName != null) { 7720 PackageSetting setting = mSettings.mPackages.get( 7721 targetPackageSetting.installerPackageName); 7722 // If the currently set package isn't valid, then it's always 7723 // okay to change it. 7724 if (setting != null) { 7725 if (compareSignatures(callerSignature, 7726 setting.signatures.mSignatures) 7727 != PackageManager.SIGNATURE_MATCH) { 7728 throw new SecurityException( 7729 "Caller does not have same cert as old installer package " 7730 + targetPackageSetting.installerPackageName); 7731 } 7732 } 7733 } 7734 7735 // Okay! 7736 targetPackageSetting.installerPackageName = installerPackageName; 7737 scheduleWriteSettingsLocked(); 7738 } 7739 } 7740 7741 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 7742 // Queue up an async operation since the package installation may take a little while. 7743 mHandler.post(new Runnable() { 7744 public void run() { 7745 mHandler.removeCallbacks(this); 7746 // Result object to be returned 7747 PackageInstalledInfo res = new PackageInstalledInfo(); 7748 res.returnCode = currentStatus; 7749 res.uid = -1; 7750 res.pkg = null; 7751 res.removedInfo = new PackageRemovedInfo(); 7752 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 7753 args.doPreInstall(res.returnCode); 7754 synchronized (mInstallLock) { 7755 installPackageLI(args, true, res); 7756 } 7757 args.doPostInstall(res.returnCode, res.uid); 7758 } 7759 7760 // A restore should be performed at this point if (a) the install 7761 // succeeded, (b) the operation is not an update, and (c) the new 7762 // package has a backupAgent defined. 7763 final boolean update = res.removedInfo.removedPackage != null; 7764 boolean doRestore = (!update 7765 && res.pkg != null 7766 && res.pkg.applicationInfo.backupAgentName != null); 7767 7768 // Set up the post-install work request bookkeeping. This will be used 7769 // and cleaned up by the post-install event handling regardless of whether 7770 // there's a restore pass performed. Token values are >= 1. 7771 int token; 7772 if (mNextInstallToken < 0) mNextInstallToken = 1; 7773 token = mNextInstallToken++; 7774 7775 PostInstallData data = new PostInstallData(args, res); 7776 mRunningInstalls.put(token, data); 7777 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 7778 7779 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 7780 // Pass responsibility to the Backup Manager. It will perform a 7781 // restore if appropriate, then pass responsibility back to the 7782 // Package Manager to run the post-install observer callbacks 7783 // and broadcasts. 7784 IBackupManager bm = IBackupManager.Stub.asInterface( 7785 ServiceManager.getService(Context.BACKUP_SERVICE)); 7786 if (bm != null) { 7787 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 7788 + " to BM for possible restore"); 7789 try { 7790 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 7791 } catch (RemoteException e) { 7792 // can't happen; the backup manager is local 7793 } catch (Exception e) { 7794 Slog.e(TAG, "Exception trying to enqueue restore", e); 7795 doRestore = false; 7796 } 7797 } else { 7798 Slog.e(TAG, "Backup Manager not found!"); 7799 doRestore = false; 7800 } 7801 } 7802 7803 if (!doRestore) { 7804 // No restore possible, or the Backup Manager was mysteriously not 7805 // available -- just fire the post-install work request directly. 7806 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 7807 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 7808 mHandler.sendMessage(msg); 7809 } 7810 } 7811 }); 7812 } 7813 7814 private abstract class HandlerParams { 7815 private static final int MAX_RETRIES = 4; 7816 7817 /** 7818 * Number of times startCopy() has been attempted and had a non-fatal 7819 * error. 7820 */ 7821 private int mRetries = 0; 7822 7823 /** User handle for the user requesting the information or installation. */ 7824 private final UserHandle mUser; 7825 7826 HandlerParams(UserHandle user) { 7827 mUser = user; 7828 } 7829 7830 UserHandle getUser() { 7831 return mUser; 7832 } 7833 7834 final boolean startCopy() { 7835 boolean res; 7836 try { 7837 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 7838 7839 if (++mRetries > MAX_RETRIES) { 7840 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 7841 mHandler.sendEmptyMessage(MCS_GIVE_UP); 7842 handleServiceError(); 7843 return false; 7844 } else { 7845 handleStartCopy(); 7846 res = true; 7847 } 7848 } catch (RemoteException e) { 7849 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 7850 mHandler.sendEmptyMessage(MCS_RECONNECT); 7851 res = false; 7852 } 7853 handleReturnCode(); 7854 return res; 7855 } 7856 7857 final void serviceError() { 7858 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 7859 handleServiceError(); 7860 handleReturnCode(); 7861 } 7862 7863 abstract void handleStartCopy() throws RemoteException; 7864 abstract void handleServiceError(); 7865 abstract void handleReturnCode(); 7866 } 7867 7868 class MeasureParams extends HandlerParams { 7869 private final PackageStats mStats; 7870 private boolean mSuccess; 7871 7872 private final IPackageStatsObserver mObserver; 7873 7874 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 7875 super(new UserHandle(stats.userHandle)); 7876 mObserver = observer; 7877 mStats = stats; 7878 } 7879 7880 @Override 7881 public String toString() { 7882 return "MeasureParams{" 7883 + Integer.toHexString(System.identityHashCode(this)) 7884 + " " + mStats.packageName + "}"; 7885 } 7886 7887 @Override 7888 void handleStartCopy() throws RemoteException { 7889 synchronized (mInstallLock) { 7890 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 7891 } 7892 7893 if (mSuccess) { 7894 final boolean mounted; 7895 if (Environment.isExternalStorageEmulated()) { 7896 mounted = true; 7897 } else { 7898 final String status = Environment.getExternalStorageState(); 7899 mounted = (Environment.MEDIA_MOUNTED.equals(status) 7900 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 7901 } 7902 7903 if (mounted) { 7904 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 7905 7906 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 7907 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 7908 7909 mStats.externalDataSize = calculateDirectorySize(mContainerService, 7910 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 7911 7912 // Always subtract cache size, since it's a subdirectory 7913 mStats.externalDataSize -= mStats.externalCacheSize; 7914 7915 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 7916 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 7917 7918 mStats.externalObbSize = calculateDirectorySize(mContainerService, 7919 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 7920 } 7921 } 7922 } 7923 7924 @Override 7925 void handleReturnCode() { 7926 if (mObserver != null) { 7927 try { 7928 mObserver.onGetStatsCompleted(mStats, mSuccess); 7929 } catch (RemoteException e) { 7930 Slog.i(TAG, "Observer no longer exists."); 7931 } 7932 } 7933 } 7934 7935 @Override 7936 void handleServiceError() { 7937 Slog.e(TAG, "Could not measure application " + mStats.packageName 7938 + " external storage"); 7939 } 7940 } 7941 7942 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 7943 throws RemoteException { 7944 long result = 0; 7945 for (File path : paths) { 7946 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 7947 } 7948 return result; 7949 } 7950 7951 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 7952 for (File path : paths) { 7953 try { 7954 mcs.clearDirectory(path.getAbsolutePath()); 7955 } catch (RemoteException e) { 7956 } 7957 } 7958 } 7959 7960 class InstallParams extends HandlerParams { 7961 final IPackageInstallObserver observer; 7962 final IPackageInstallObserver2 observer2; 7963 int flags; 7964 7965 private final Uri mPackageURI; 7966 final String installerPackageName; 7967 final VerificationParams verificationParams; 7968 private InstallArgs mArgs; 7969 private int mRet; 7970 private File mTempPackage; 7971 final ContainerEncryptionParams encryptionParams; 7972 7973 InstallParams(Uri packageURI, 7974 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7975 int flags, String installerPackageName, VerificationParams verificationParams, 7976 ContainerEncryptionParams encryptionParams, UserHandle user) { 7977 super(user); 7978 this.mPackageURI = packageURI; 7979 this.flags = flags; 7980 this.observer = observer; 7981 this.observer2 = observer2; 7982 this.installerPackageName = installerPackageName; 7983 this.verificationParams = verificationParams; 7984 this.encryptionParams = encryptionParams; 7985 } 7986 7987 @Override 7988 public String toString() { 7989 return "InstallParams{" 7990 + Integer.toHexString(System.identityHashCode(this)) 7991 + " " + mPackageURI + "}"; 7992 } 7993 7994 public ManifestDigest getManifestDigest() { 7995 if (verificationParams == null) { 7996 return null; 7997 } 7998 return verificationParams.getManifestDigest(); 7999 } 8000 8001 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8002 String packageName = pkgLite.packageName; 8003 int installLocation = pkgLite.installLocation; 8004 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8005 // reader 8006 synchronized (mPackages) { 8007 PackageParser.Package pkg = mPackages.get(packageName); 8008 if (pkg != null) { 8009 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8010 // Check for downgrading. 8011 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8012 if (pkgLite.versionCode < pkg.mVersionCode) { 8013 Slog.w(TAG, "Can't install update of " + packageName 8014 + " update version " + pkgLite.versionCode 8015 + " is older than installed version " 8016 + pkg.mVersionCode); 8017 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8018 } 8019 } 8020 // Check for updated system application. 8021 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8022 if (onSd) { 8023 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8024 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8025 } 8026 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8027 } else { 8028 if (onSd) { 8029 // Install flag overrides everything. 8030 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8031 } 8032 // If current upgrade specifies particular preference 8033 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8034 // Application explicitly specified internal. 8035 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8036 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8037 // App explictly prefers external. Let policy decide 8038 } else { 8039 // Prefer previous location 8040 if (isExternal(pkg)) { 8041 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8042 } 8043 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8044 } 8045 } 8046 } else { 8047 // Invalid install. Return error code 8048 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8049 } 8050 } 8051 } 8052 // All the special cases have been taken care of. 8053 // Return result based on recommended install location. 8054 if (onSd) { 8055 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8056 } 8057 return pkgLite.recommendedInstallLocation; 8058 } 8059 8060 private long getMemoryLowThreshold() { 8061 final DeviceStorageMonitorInternal 8062 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8063 if (dsm == null) { 8064 return 0L; 8065 } 8066 return dsm.getMemoryLowThreshold(); 8067 } 8068 8069 /* 8070 * Invoke remote method to get package information and install 8071 * location values. Override install location based on default 8072 * policy if needed and then create install arguments based 8073 * on the install location. 8074 */ 8075 public void handleStartCopy() throws RemoteException { 8076 int ret = PackageManager.INSTALL_SUCCEEDED; 8077 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8078 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8079 PackageInfoLite pkgLite = null; 8080 8081 if (onInt && onSd) { 8082 // Check if both bits are set. 8083 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8084 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8085 } else { 8086 final long lowThreshold = getMemoryLowThreshold(); 8087 if (lowThreshold == 0L) { 8088 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8089 } 8090 8091 try { 8092 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI, 8093 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8094 8095 final File packageFile; 8096 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) { 8097 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir); 8098 if (mTempPackage != null) { 8099 ParcelFileDescriptor out; 8100 try { 8101 out = ParcelFileDescriptor.open(mTempPackage, 8102 ParcelFileDescriptor.MODE_READ_WRITE); 8103 } catch (FileNotFoundException e) { 8104 out = null; 8105 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI); 8106 } 8107 8108 // Make a temporary file for decryption. 8109 ret = mContainerService 8110 .copyResource(mPackageURI, encryptionParams, out); 8111 IoUtils.closeQuietly(out); 8112 8113 packageFile = mTempPackage; 8114 8115 FileUtils.setPermissions(packageFile.getAbsolutePath(), 8116 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP 8117 | FileUtils.S_IROTH, 8118 -1, -1); 8119 } else { 8120 packageFile = null; 8121 } 8122 } else { 8123 packageFile = new File(mPackageURI.getPath()); 8124 } 8125 8126 if (packageFile != null) { 8127 // Remote call to find out default install location 8128 final String packageFilePath = packageFile.getAbsolutePath(); 8129 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags, 8130 lowThreshold); 8131 8132 /* 8133 * If we have too little free space, try to free cache 8134 * before giving up. 8135 */ 8136 if (pkgLite.recommendedInstallLocation 8137 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8138 final long size = mContainerService.calculateInstalledSize( 8139 packageFilePath, isForwardLocked()); 8140 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8141 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, 8142 flags, lowThreshold); 8143 } 8144 /* 8145 * The cache free must have deleted the file we 8146 * downloaded to install. 8147 * 8148 * TODO: fix the "freeCache" call to not delete 8149 * the file we care about. 8150 */ 8151 if (pkgLite.recommendedInstallLocation 8152 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8153 pkgLite.recommendedInstallLocation 8154 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8155 } 8156 } 8157 } 8158 } finally { 8159 mContext.revokeUriPermission(mPackageURI, 8160 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8161 } 8162 } 8163 8164 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8165 int loc = pkgLite.recommendedInstallLocation; 8166 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8167 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8168 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8169 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8170 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8171 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8172 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8173 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8174 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8175 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8176 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8177 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8178 } else { 8179 // Override with defaults if needed. 8180 loc = installLocationPolicy(pkgLite, flags); 8181 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8182 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8183 } else if (!onSd && !onInt) { 8184 // Override install location with flags 8185 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8186 // Set the flag to install on external media. 8187 flags |= PackageManager.INSTALL_EXTERNAL; 8188 flags &= ~PackageManager.INSTALL_INTERNAL; 8189 } else { 8190 // Make sure the flag for installing on external 8191 // media is unset 8192 flags |= PackageManager.INSTALL_INTERNAL; 8193 flags &= ~PackageManager.INSTALL_EXTERNAL; 8194 } 8195 } 8196 } 8197 } 8198 8199 final InstallArgs args = createInstallArgs(this); 8200 mArgs = args; 8201 8202 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8203 /* 8204 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8205 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8206 */ 8207 int userIdentifier = getUser().getIdentifier(); 8208 if (userIdentifier == UserHandle.USER_ALL 8209 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8210 userIdentifier = UserHandle.USER_OWNER; 8211 } 8212 8213 /* 8214 * Determine if we have any installed package verifiers. If we 8215 * do, then we'll defer to them to verify the packages. 8216 */ 8217 final int requiredUid = mRequiredVerifierPackage == null ? -1 8218 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8219 if (requiredUid != -1 && isVerificationEnabled(flags)) { 8220 final Intent verification = new Intent( 8221 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8222 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE); 8223 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8224 8225 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8226 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8227 0 /* TODO: Which userId? */); 8228 8229 if (DEBUG_VERIFY) { 8230 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8231 + verification.toString() + " with " + pkgLite.verifiers.length 8232 + " optional verifiers"); 8233 } 8234 8235 final int verificationId = mPendingVerificationToken++; 8236 8237 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8238 8239 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8240 installerPackageName); 8241 8242 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8243 8244 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8245 pkgLite.packageName); 8246 8247 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8248 pkgLite.versionCode); 8249 8250 if (verificationParams != null) { 8251 if (verificationParams.getVerificationURI() != null) { 8252 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8253 verificationParams.getVerificationURI()); 8254 } 8255 if (verificationParams.getOriginatingURI() != null) { 8256 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8257 verificationParams.getOriginatingURI()); 8258 } 8259 if (verificationParams.getReferrer() != null) { 8260 verification.putExtra(Intent.EXTRA_REFERRER, 8261 verificationParams.getReferrer()); 8262 } 8263 if (verificationParams.getOriginatingUid() >= 0) { 8264 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8265 verificationParams.getOriginatingUid()); 8266 } 8267 if (verificationParams.getInstallerUid() >= 0) { 8268 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8269 verificationParams.getInstallerUid()); 8270 } 8271 } 8272 8273 final PackageVerificationState verificationState = new PackageVerificationState( 8274 requiredUid, args); 8275 8276 mPendingVerification.append(verificationId, verificationState); 8277 8278 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8279 receivers, verificationState); 8280 8281 /* 8282 * If any sufficient verifiers were listed in the package 8283 * manifest, attempt to ask them. 8284 */ 8285 if (sufficientVerifiers != null) { 8286 final int N = sufficientVerifiers.size(); 8287 if (N == 0) { 8288 Slog.i(TAG, "Additional verifiers required, but none installed."); 8289 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8290 } else { 8291 for (int i = 0; i < N; i++) { 8292 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8293 8294 final Intent sufficientIntent = new Intent(verification); 8295 sufficientIntent.setComponent(verifierComponent); 8296 8297 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8298 } 8299 } 8300 } 8301 8302 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8303 mRequiredVerifierPackage, receivers); 8304 if (ret == PackageManager.INSTALL_SUCCEEDED 8305 && mRequiredVerifierPackage != null) { 8306 /* 8307 * Send the intent to the required verification agent, 8308 * but only start the verification timeout after the 8309 * target BroadcastReceivers have run. 8310 */ 8311 verification.setComponent(requiredVerifierComponent); 8312 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8313 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8314 new BroadcastReceiver() { 8315 @Override 8316 public void onReceive(Context context, Intent intent) { 8317 final Message msg = mHandler 8318 .obtainMessage(CHECK_PENDING_VERIFICATION); 8319 msg.arg1 = verificationId; 8320 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8321 } 8322 }, null, 0, null, null); 8323 8324 /* 8325 * We don't want the copy to proceed until verification 8326 * succeeds, so null out this field. 8327 */ 8328 mArgs = null; 8329 } 8330 } else { 8331 /* 8332 * No package verification is enabled, so immediately start 8333 * the remote call to initiate copy using temporary file. 8334 */ 8335 ret = args.copyApk(mContainerService, true); 8336 } 8337 } 8338 8339 mRet = ret; 8340 } 8341 8342 @Override 8343 void handleReturnCode() { 8344 // If mArgs is null, then MCS couldn't be reached. When it 8345 // reconnects, it will try again to install. At that point, this 8346 // will succeed. 8347 if (mArgs != null) { 8348 processPendingInstall(mArgs, mRet); 8349 8350 if (mTempPackage != null) { 8351 if (!mTempPackage.delete()) { 8352 Slog.w(TAG, "Couldn't delete temporary file: " + 8353 mTempPackage.getAbsolutePath()); 8354 } 8355 } 8356 } 8357 } 8358 8359 @Override 8360 void handleServiceError() { 8361 mArgs = createInstallArgs(this); 8362 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8363 } 8364 8365 public boolean isForwardLocked() { 8366 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8367 } 8368 8369 public Uri getPackageUri() { 8370 if (mTempPackage != null) { 8371 return Uri.fromFile(mTempPackage); 8372 } else { 8373 return mPackageURI; 8374 } 8375 } 8376 } 8377 8378 /* 8379 * Utility class used in movePackage api. 8380 * srcArgs and targetArgs are not set for invalid flags and make 8381 * sure to do null checks when invoking methods on them. 8382 * We probably want to return ErrorPrams for both failed installs 8383 * and moves. 8384 */ 8385 class MoveParams extends HandlerParams { 8386 final IPackageMoveObserver observer; 8387 final int flags; 8388 final String packageName; 8389 final InstallArgs srcArgs; 8390 final InstallArgs targetArgs; 8391 int uid; 8392 int mRet; 8393 8394 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8395 String packageName, String dataDir, String instructionSet, 8396 int uid, UserHandle user) { 8397 super(user); 8398 this.srcArgs = srcArgs; 8399 this.observer = observer; 8400 this.flags = flags; 8401 this.packageName = packageName; 8402 this.uid = uid; 8403 if (srcArgs != null) { 8404 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath())); 8405 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet); 8406 } else { 8407 targetArgs = null; 8408 } 8409 } 8410 8411 @Override 8412 public String toString() { 8413 return "MoveParams{" 8414 + Integer.toHexString(System.identityHashCode(this)) 8415 + " " + packageName + "}"; 8416 } 8417 8418 public void handleStartCopy() throws RemoteException { 8419 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8420 // Check for storage space on target medium 8421 if (!targetArgs.checkFreeStorage(mContainerService)) { 8422 Log.w(TAG, "Insufficient storage to install"); 8423 return; 8424 } 8425 8426 mRet = srcArgs.doPreCopy(); 8427 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8428 return; 8429 } 8430 8431 mRet = targetArgs.copyApk(mContainerService, false); 8432 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8433 srcArgs.doPostCopy(uid); 8434 return; 8435 } 8436 8437 mRet = srcArgs.doPostCopy(uid); 8438 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8439 return; 8440 } 8441 8442 mRet = targetArgs.doPreInstall(mRet); 8443 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8444 return; 8445 } 8446 8447 if (DEBUG_SD_INSTALL) { 8448 StringBuilder builder = new StringBuilder(); 8449 if (srcArgs != null) { 8450 builder.append("src: "); 8451 builder.append(srcArgs.getCodePath()); 8452 } 8453 if (targetArgs != null) { 8454 builder.append(" target : "); 8455 builder.append(targetArgs.getCodePath()); 8456 } 8457 Log.i(TAG, builder.toString()); 8458 } 8459 } 8460 8461 @Override 8462 void handleReturnCode() { 8463 targetArgs.doPostInstall(mRet, uid); 8464 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8465 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8466 currentStatus = PackageManager.MOVE_SUCCEEDED; 8467 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8468 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8469 } 8470 processPendingMove(this, currentStatus); 8471 } 8472 8473 @Override 8474 void handleServiceError() { 8475 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8476 } 8477 } 8478 8479 /** 8480 * Used during creation of InstallArgs 8481 * 8482 * @param flags package installation flags 8483 * @return true if should be installed on external storage 8484 */ 8485 private static boolean installOnSd(int flags) { 8486 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8487 return false; 8488 } 8489 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8490 return true; 8491 } 8492 return false; 8493 } 8494 8495 /** 8496 * Used during creation of InstallArgs 8497 * 8498 * @param flags package installation flags 8499 * @return true if should be installed as forward locked 8500 */ 8501 private static boolean installForwardLocked(int flags) { 8502 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8503 } 8504 8505 private InstallArgs createInstallArgs(InstallParams params) { 8506 if (installOnSd(params.flags) || params.isForwardLocked()) { 8507 return new AsecInstallArgs(params); 8508 } else { 8509 return new FileInstallArgs(params); 8510 } 8511 } 8512 8513 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath, 8514 String nativeLibraryPath, String instructionSet) { 8515 final boolean isInAsec; 8516 if (installOnSd(flags)) { 8517 /* Apps on SD card are always in ASEC containers. */ 8518 isInAsec = true; 8519 } else if (installForwardLocked(flags) 8520 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8521 /* 8522 * Forward-locked apps are only in ASEC containers if they're the 8523 * new style 8524 */ 8525 isInAsec = true; 8526 } else { 8527 isInAsec = false; 8528 } 8529 8530 if (isInAsec) { 8531 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8532 instructionSet, installOnSd(flags), installForwardLocked(flags)); 8533 } else { 8534 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8535 instructionSet); 8536 } 8537 } 8538 8539 // Used by package mover 8540 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir, 8541 String instructionSet) { 8542 if (installOnSd(flags) || installForwardLocked(flags)) { 8543 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/" 8544 + AsecInstallArgs.RES_FILE_NAME); 8545 return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags), 8546 installForwardLocked(flags)); 8547 } else { 8548 return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet); 8549 } 8550 } 8551 8552 static abstract class InstallArgs { 8553 final IPackageInstallObserver observer; 8554 final IPackageInstallObserver2 observer2; 8555 // Always refers to PackageManager flags only 8556 final int flags; 8557 final Uri packageURI; 8558 final String installerPackageName; 8559 final ManifestDigest manifestDigest; 8560 final UserHandle user; 8561 final String instructionSet; 8562 8563 InstallArgs(Uri packageURI, 8564 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 8565 int flags, String installerPackageName, ManifestDigest manifestDigest, 8566 UserHandle user, String instructionSet) { 8567 this.packageURI = packageURI; 8568 this.flags = flags; 8569 this.observer = observer; 8570 this.observer2 = observer2; 8571 this.installerPackageName = installerPackageName; 8572 this.manifestDigest = manifestDigest; 8573 this.user = user; 8574 this.instructionSet = instructionSet; 8575 } 8576 8577 abstract void createCopyFile(); 8578 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 8579 abstract int doPreInstall(int status); 8580 abstract boolean doRename(int status, String pkgName, String oldCodePath); 8581 8582 abstract int doPostInstall(int status, int uid); 8583 abstract String getCodePath(); 8584 abstract String getResourcePath(); 8585 abstract String getNativeLibraryPath(); 8586 // Need installer lock especially for dex file removal. 8587 abstract void cleanUpResourcesLI(); 8588 abstract boolean doPostDeleteLI(boolean delete); 8589 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 8590 8591 /** 8592 * Called before the source arguments are copied. This is used mostly 8593 * for MoveParams when it needs to read the source file to put it in the 8594 * destination. 8595 */ 8596 int doPreCopy() { 8597 return PackageManager.INSTALL_SUCCEEDED; 8598 } 8599 8600 /** 8601 * Called after the source arguments are copied. This is used mostly for 8602 * MoveParams when it needs to read the source file to put it in the 8603 * destination. 8604 * 8605 * @return 8606 */ 8607 int doPostCopy(int uid) { 8608 return PackageManager.INSTALL_SUCCEEDED; 8609 } 8610 8611 protected boolean isFwdLocked() { 8612 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8613 } 8614 8615 UserHandle getUser() { 8616 return user; 8617 } 8618 } 8619 8620 class FileInstallArgs extends InstallArgs { 8621 File installDir; 8622 String codeFileName; 8623 String resourceFileName; 8624 String libraryPath; 8625 boolean created = false; 8626 8627 FileInstallArgs(InstallParams params) { 8628 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 8629 params.installerPackageName, params.getManifestDigest(), 8630 params.getUser(), null /* instruction set */); 8631 } 8632 8633 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 8634 String instructionSet) { 8635 super(null, null, null, 0, null, null, null, instructionSet); 8636 File codeFile = new File(fullCodePath); 8637 installDir = codeFile.getParentFile(); 8638 codeFileName = fullCodePath; 8639 resourceFileName = fullResourcePath; 8640 libraryPath = nativeLibraryPath; 8641 } 8642 8643 FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) { 8644 super(packageURI, null, null, 0, null, null, null, instructionSet); 8645 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 8646 String apkName = getNextCodePath(null, pkgName, ".apk"); 8647 codeFileName = new File(installDir, apkName + ".apk").getPath(); 8648 resourceFileName = getResourcePathFromCodePath(); 8649 libraryPath = new File(mAppLibInstallDir, pkgName).getPath(); 8650 } 8651 8652 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 8653 final long lowThreshold; 8654 8655 final DeviceStorageMonitorInternal 8656 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8657 if (dsm == null) { 8658 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8659 lowThreshold = 0L; 8660 } else { 8661 if (dsm.isMemoryLow()) { 8662 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 8663 return false; 8664 } 8665 8666 lowThreshold = dsm.getMemoryLowThreshold(); 8667 } 8668 8669 try { 8670 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8671 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8672 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold); 8673 } finally { 8674 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8675 } 8676 } 8677 8678 String getCodePath() { 8679 return codeFileName; 8680 } 8681 8682 void createCopyFile() { 8683 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 8684 codeFileName = createTempPackageFile(installDir).getPath(); 8685 resourceFileName = getResourcePathFromCodePath(); 8686 libraryPath = getLibraryPathFromCodePath(); 8687 created = true; 8688 } 8689 8690 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 8691 if (temp) { 8692 // Generate temp file name 8693 createCopyFile(); 8694 } 8695 // Get a ParcelFileDescriptor to write to the output file 8696 File codeFile = new File(codeFileName); 8697 if (!created) { 8698 try { 8699 codeFile.createNewFile(); 8700 // Set permissions 8701 if (!setPermissions()) { 8702 // Failed setting permissions. 8703 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8704 } 8705 } catch (IOException e) { 8706 Slog.w(TAG, "Failed to create file " + codeFile); 8707 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8708 } 8709 } 8710 ParcelFileDescriptor out = null; 8711 try { 8712 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 8713 } catch (FileNotFoundException e) { 8714 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 8715 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8716 } 8717 // Copy the resource now 8718 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8719 try { 8720 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8721 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8722 ret = imcs.copyResource(packageURI, null, out); 8723 } finally { 8724 IoUtils.closeQuietly(out); 8725 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8726 } 8727 8728 if (isFwdLocked()) { 8729 final File destResourceFile = new File(getResourcePath()); 8730 8731 // Copy the public files 8732 try { 8733 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 8734 } catch (IOException e) { 8735 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 8736 + " forward-locked app."); 8737 destResourceFile.delete(); 8738 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8739 } 8740 } 8741 8742 final File nativeLibraryFile = new File(getNativeLibraryPath()); 8743 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath()); 8744 if (nativeLibraryFile.exists()) { 8745 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 8746 nativeLibraryFile.delete(); 8747 } 8748 try { 8749 int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile); 8750 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8751 return copyRet; 8752 } 8753 } catch (IOException e) { 8754 Slog.e(TAG, "Copying native libraries failed", e); 8755 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8756 } 8757 8758 return ret; 8759 } 8760 8761 int doPreInstall(int status) { 8762 if (status != PackageManager.INSTALL_SUCCEEDED) { 8763 cleanUp(); 8764 } 8765 return status; 8766 } 8767 8768 boolean doRename(int status, final String pkgName, String oldCodePath) { 8769 if (status != PackageManager.INSTALL_SUCCEEDED) { 8770 cleanUp(); 8771 return false; 8772 } else { 8773 final File oldCodeFile = new File(getCodePath()); 8774 final File oldResourceFile = new File(getResourcePath()); 8775 final File oldLibraryFile = new File(getNativeLibraryPath()); 8776 8777 // Rename APK file based on packageName 8778 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 8779 final File newCodeFile = new File(installDir, apkName + ".apk"); 8780 if (!oldCodeFile.renameTo(newCodeFile)) { 8781 return false; 8782 } 8783 codeFileName = newCodeFile.getPath(); 8784 8785 // Rename public resource file if it's forward-locked. 8786 final File newResFile = new File(getResourcePathFromCodePath()); 8787 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 8788 return false; 8789 } 8790 resourceFileName = newResFile.getPath(); 8791 8792 // Rename library path 8793 final File newLibraryFile = new File(getLibraryPathFromCodePath()); 8794 if (newLibraryFile.exists()) { 8795 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile); 8796 newLibraryFile.delete(); 8797 } 8798 if (!oldLibraryFile.renameTo(newLibraryFile)) { 8799 Slog.e(TAG, "Cannot rename native library directory " 8800 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath()); 8801 return false; 8802 } 8803 libraryPath = newLibraryFile.getPath(); 8804 8805 // Attempt to set permissions 8806 if (!setPermissions()) { 8807 return false; 8808 } 8809 8810 if (!SELinux.restorecon(newCodeFile)) { 8811 return false; 8812 } 8813 8814 return true; 8815 } 8816 } 8817 8818 int doPostInstall(int status, int uid) { 8819 if (status != PackageManager.INSTALL_SUCCEEDED) { 8820 cleanUp(); 8821 } 8822 return status; 8823 } 8824 8825 String getResourcePath() { 8826 return resourceFileName; 8827 } 8828 8829 private String getResourcePathFromCodePath() { 8830 final String codePath = getCodePath(); 8831 if (isFwdLocked()) { 8832 final StringBuilder sb = new StringBuilder(); 8833 8834 sb.append(mAppInstallDir.getPath()); 8835 sb.append('/'); 8836 sb.append(getApkName(codePath)); 8837 sb.append(".zip"); 8838 8839 /* 8840 * If our APK is a temporary file, mark the resource as a 8841 * temporary file as well so it can be cleaned up after 8842 * catastrophic failure. 8843 */ 8844 if (codePath.endsWith(".tmp")) { 8845 sb.append(".tmp"); 8846 } 8847 8848 return sb.toString(); 8849 } else { 8850 return codePath; 8851 } 8852 } 8853 8854 private String getLibraryPathFromCodePath() { 8855 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath(); 8856 } 8857 8858 @Override 8859 String getNativeLibraryPath() { 8860 if (libraryPath == null) { 8861 libraryPath = getLibraryPathFromCodePath(); 8862 } 8863 return libraryPath; 8864 } 8865 8866 private boolean cleanUp() { 8867 boolean ret = true; 8868 String sourceDir = getCodePath(); 8869 String publicSourceDir = getResourcePath(); 8870 if (sourceDir != null) { 8871 File sourceFile = new File(sourceDir); 8872 if (!sourceFile.exists()) { 8873 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 8874 ret = false; 8875 } 8876 // Delete application's code and resources 8877 sourceFile.delete(); 8878 } 8879 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 8880 final File publicSourceFile = new File(publicSourceDir); 8881 if (!publicSourceFile.exists()) { 8882 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 8883 } 8884 if (publicSourceFile.exists()) { 8885 publicSourceFile.delete(); 8886 } 8887 } 8888 8889 if (libraryPath != null) { 8890 File nativeLibraryFile = new File(libraryPath); 8891 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 8892 if (!nativeLibraryFile.delete()) { 8893 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath); 8894 } 8895 } 8896 8897 return ret; 8898 } 8899 8900 void cleanUpResourcesLI() { 8901 String sourceDir = getCodePath(); 8902 if (cleanUp()) { 8903 if (instructionSet == null) { 8904 throw new IllegalStateException("instructionSet == null"); 8905 } 8906 int retCode = mInstaller.rmdex(sourceDir, instructionSet); 8907 if (retCode < 0) { 8908 Slog.w(TAG, "Couldn't remove dex file for package: " 8909 + " at location " 8910 + sourceDir + ", retcode=" + retCode); 8911 // we don't consider this to be a failure of the core package deletion 8912 } 8913 } 8914 } 8915 8916 private boolean setPermissions() { 8917 // TODO Do this in a more elegant way later on. for now just a hack 8918 if (!isFwdLocked()) { 8919 final int filePermissions = 8920 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 8921 |FileUtils.S_IROTH; 8922 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 8923 if (retCode != 0) { 8924 Slog.e(TAG, "Couldn't set new package file permissions for " + 8925 getCodePath() 8926 + ". The return code was: " + retCode); 8927 // TODO Define new internal error 8928 return false; 8929 } 8930 return true; 8931 } 8932 return true; 8933 } 8934 8935 boolean doPostDeleteLI(boolean delete) { 8936 // XXX err, shouldn't we respect the delete flag? 8937 cleanUpResourcesLI(); 8938 return true; 8939 } 8940 } 8941 8942 private boolean isAsecExternal(String cid) { 8943 final String asecPath = PackageHelper.getSdFilesystem(cid); 8944 return !asecPath.startsWith(mAsecInternalPath); 8945 } 8946 8947 /** 8948 * Extract the MountService "container ID" from the full code path of an 8949 * .apk. 8950 */ 8951 static String cidFromCodePath(String fullCodePath) { 8952 int eidx = fullCodePath.lastIndexOf("/"); 8953 String subStr1 = fullCodePath.substring(0, eidx); 8954 int sidx = subStr1.lastIndexOf("/"); 8955 return subStr1.substring(sidx+1, eidx); 8956 } 8957 8958 class AsecInstallArgs extends InstallArgs { 8959 static final String RES_FILE_NAME = "pkg.apk"; 8960 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 8961 8962 String cid; 8963 String packagePath; 8964 String resourcePath; 8965 String libraryPath; 8966 8967 AsecInstallArgs(InstallParams params) { 8968 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 8969 params.installerPackageName, params.getManifestDigest(), 8970 params.getUser(), null /* instruction set */); 8971 } 8972 8973 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 8974 String instructionSet, boolean isExternal, boolean isForwardLocked) { 8975 super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 8976 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 8977 null, null, null, instructionSet); 8978 // Extract cid from fullCodePath 8979 int eidx = fullCodePath.lastIndexOf("/"); 8980 String subStr1 = fullCodePath.substring(0, eidx); 8981 int sidx = subStr1.lastIndexOf("/"); 8982 cid = subStr1.substring(sidx+1, eidx); 8983 setCachePath(subStr1); 8984 } 8985 8986 AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) { 8987 super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 8988 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 8989 null, null, null, instructionSet); 8990 this.cid = cid; 8991 setCachePath(PackageHelper.getSdDir(cid)); 8992 } 8993 8994 AsecInstallArgs(Uri packageURI, String cid, String instructionSet, 8995 boolean isExternal, boolean isForwardLocked) { 8996 super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 8997 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 8998 null, null, null, instructionSet); 8999 this.cid = cid; 9000 } 9001 9002 void createCopyFile() { 9003 cid = getTempContainerId(); 9004 } 9005 9006 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9007 try { 9008 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9009 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9010 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked()); 9011 } finally { 9012 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9013 } 9014 } 9015 9016 private final boolean isExternal() { 9017 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9018 } 9019 9020 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9021 if (temp) { 9022 createCopyFile(); 9023 } else { 9024 /* 9025 * Pre-emptively destroy the container since it's destroyed if 9026 * copying fails due to it existing anyway. 9027 */ 9028 PackageHelper.destroySdDir(cid); 9029 } 9030 9031 final String newCachePath; 9032 try { 9033 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9034 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9035 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(), 9036 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked()); 9037 } finally { 9038 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9039 } 9040 9041 if (newCachePath != null) { 9042 setCachePath(newCachePath); 9043 return PackageManager.INSTALL_SUCCEEDED; 9044 } else { 9045 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9046 } 9047 } 9048 9049 @Override 9050 String getCodePath() { 9051 return packagePath; 9052 } 9053 9054 @Override 9055 String getResourcePath() { 9056 return resourcePath; 9057 } 9058 9059 @Override 9060 String getNativeLibraryPath() { 9061 return libraryPath; 9062 } 9063 9064 int doPreInstall(int status) { 9065 if (status != PackageManager.INSTALL_SUCCEEDED) { 9066 // Destroy container 9067 PackageHelper.destroySdDir(cid); 9068 } else { 9069 boolean mounted = PackageHelper.isContainerMounted(cid); 9070 if (!mounted) { 9071 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9072 Process.SYSTEM_UID); 9073 if (newCachePath != null) { 9074 setCachePath(newCachePath); 9075 } else { 9076 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9077 } 9078 } 9079 } 9080 return status; 9081 } 9082 9083 boolean doRename(int status, final String pkgName, 9084 String oldCodePath) { 9085 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 9086 String newCachePath = null; 9087 if (PackageHelper.isContainerMounted(cid)) { 9088 // Unmount the container 9089 if (!PackageHelper.unMountSdDir(cid)) { 9090 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9091 return false; 9092 } 9093 } 9094 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9095 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9096 " which might be stale. Will try to clean up."); 9097 // Clean up the stale container and proceed to recreate. 9098 if (!PackageHelper.destroySdDir(newCacheId)) { 9099 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9100 return false; 9101 } 9102 // Successfully cleaned up stale container. Try to rename again. 9103 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9104 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9105 + " inspite of cleaning it up."); 9106 return false; 9107 } 9108 } 9109 if (!PackageHelper.isContainerMounted(newCacheId)) { 9110 Slog.w(TAG, "Mounting container " + newCacheId); 9111 newCachePath = PackageHelper.mountSdDir(newCacheId, 9112 getEncryptKey(), Process.SYSTEM_UID); 9113 } else { 9114 newCachePath = PackageHelper.getSdDir(newCacheId); 9115 } 9116 if (newCachePath == null) { 9117 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9118 return false; 9119 } 9120 Log.i(TAG, "Succesfully renamed " + cid + 9121 " to " + newCacheId + 9122 " at new path: " + newCachePath); 9123 cid = newCacheId; 9124 setCachePath(newCachePath); 9125 return true; 9126 } 9127 9128 private void setCachePath(String newCachePath) { 9129 File cachePath = new File(newCachePath); 9130 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 9131 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9132 9133 if (isFwdLocked()) { 9134 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9135 } else { 9136 resourcePath = packagePath; 9137 } 9138 } 9139 9140 int doPostInstall(int status, int uid) { 9141 if (status != PackageManager.INSTALL_SUCCEEDED) { 9142 cleanUp(); 9143 } else { 9144 final int groupOwner; 9145 final String protectedFile; 9146 if (isFwdLocked()) { 9147 groupOwner = UserHandle.getSharedAppGid(uid); 9148 protectedFile = RES_FILE_NAME; 9149 } else { 9150 groupOwner = -1; 9151 protectedFile = null; 9152 } 9153 9154 if (uid < Process.FIRST_APPLICATION_UID 9155 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9156 Slog.e(TAG, "Failed to finalize " + cid); 9157 PackageHelper.destroySdDir(cid); 9158 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9159 } 9160 9161 boolean mounted = PackageHelper.isContainerMounted(cid); 9162 if (!mounted) { 9163 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9164 } 9165 } 9166 return status; 9167 } 9168 9169 private void cleanUp() { 9170 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9171 9172 // Destroy secure container 9173 PackageHelper.destroySdDir(cid); 9174 } 9175 9176 void cleanUpResourcesLI() { 9177 String sourceFile = getCodePath(); 9178 // Remove dex file 9179 if (instructionSet == null) { 9180 throw new IllegalStateException("instructionSet == null"); 9181 } 9182 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9183 if (retCode < 0) { 9184 Slog.w(TAG, "Couldn't remove dex file for package: " 9185 + " at location " 9186 + sourceFile.toString() + ", retcode=" + retCode); 9187 // we don't consider this to be a failure of the core package deletion 9188 } 9189 cleanUp(); 9190 } 9191 9192 boolean matchContainer(String app) { 9193 if (cid.startsWith(app)) { 9194 return true; 9195 } 9196 return false; 9197 } 9198 9199 String getPackageName() { 9200 return getAsecPackageName(cid); 9201 } 9202 9203 boolean doPostDeleteLI(boolean delete) { 9204 boolean ret = false; 9205 boolean mounted = PackageHelper.isContainerMounted(cid); 9206 if (mounted) { 9207 // Unmount first 9208 ret = PackageHelper.unMountSdDir(cid); 9209 } 9210 if (ret && delete) { 9211 cleanUpResourcesLI(); 9212 } 9213 return ret; 9214 } 9215 9216 @Override 9217 int doPreCopy() { 9218 if (isFwdLocked()) { 9219 if (!PackageHelper.fixSdPermissions(cid, 9220 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9221 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9222 } 9223 } 9224 9225 return PackageManager.INSTALL_SUCCEEDED; 9226 } 9227 9228 @Override 9229 int doPostCopy(int uid) { 9230 if (isFwdLocked()) { 9231 if (uid < Process.FIRST_APPLICATION_UID 9232 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9233 RES_FILE_NAME)) { 9234 Slog.e(TAG, "Failed to finalize " + cid); 9235 PackageHelper.destroySdDir(cid); 9236 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9237 } 9238 } 9239 9240 return PackageManager.INSTALL_SUCCEEDED; 9241 } 9242 }; 9243 9244 static String getAsecPackageName(String packageCid) { 9245 int idx = packageCid.lastIndexOf("-"); 9246 if (idx == -1) { 9247 return packageCid; 9248 } 9249 return packageCid.substring(0, idx); 9250 } 9251 9252 // Utility method used to create code paths based on package name and available index. 9253 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9254 String idxStr = ""; 9255 int idx = 1; 9256 // Fall back to default value of idx=1 if prefix is not 9257 // part of oldCodePath 9258 if (oldCodePath != null) { 9259 String subStr = oldCodePath; 9260 // Drop the suffix right away 9261 if (subStr.endsWith(suffix)) { 9262 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9263 } 9264 // If oldCodePath already contains prefix find out the 9265 // ending index to either increment or decrement. 9266 int sidx = subStr.lastIndexOf(prefix); 9267 if (sidx != -1) { 9268 subStr = subStr.substring(sidx + prefix.length()); 9269 if (subStr != null) { 9270 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9271 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9272 } 9273 try { 9274 idx = Integer.parseInt(subStr); 9275 if (idx <= 1) { 9276 idx++; 9277 } else { 9278 idx--; 9279 } 9280 } catch(NumberFormatException e) { 9281 } 9282 } 9283 } 9284 } 9285 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9286 return prefix + idxStr; 9287 } 9288 9289 // Utility method used to ignore ADD/REMOVE events 9290 // by directory observer. 9291 private static boolean ignoreCodePath(String fullPathStr) { 9292 String apkName = getApkName(fullPathStr); 9293 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9294 if (idx != -1 && ((idx+1) < apkName.length())) { 9295 // Make sure the package ends with a numeral 9296 String version = apkName.substring(idx+1); 9297 try { 9298 Integer.parseInt(version); 9299 return true; 9300 } catch (NumberFormatException e) {} 9301 } 9302 return false; 9303 } 9304 9305 // Utility method that returns the relative package path with respect 9306 // to the installation directory. Like say for /data/data/com.test-1.apk 9307 // string com.test-1 is returned. 9308 static String getApkName(String codePath) { 9309 if (codePath == null) { 9310 return null; 9311 } 9312 int sidx = codePath.lastIndexOf("/"); 9313 int eidx = codePath.lastIndexOf("."); 9314 if (eidx == -1) { 9315 eidx = codePath.length(); 9316 } else if (eidx == 0) { 9317 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 9318 return null; 9319 } 9320 return codePath.substring(sidx+1, eidx); 9321 } 9322 9323 class PackageInstalledInfo { 9324 String name; 9325 int uid; 9326 // The set of users that originally had this package installed. 9327 int[] origUsers; 9328 // The set of users that now have this package installed. 9329 int[] newUsers; 9330 PackageParser.Package pkg; 9331 int returnCode; 9332 PackageRemovedInfo removedInfo; 9333 9334 // In some error cases we want to convey more info back to the observer 9335 String origPackage; 9336 String origPermission; 9337 } 9338 9339 /* 9340 * Install a non-existing package. 9341 */ 9342 private void installNewPackageLI(PackageParser.Package pkg, 9343 int parseFlags, int scanMode, UserHandle user, 9344 String installerPackageName, PackageInstalledInfo res) { 9345 // Remember this for later, in case we need to rollback this install 9346 String pkgName = pkg.packageName; 9347 9348 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9349 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9350 synchronized(mPackages) { 9351 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9352 // A package with the same name is already installed, though 9353 // it has been renamed to an older name. The package we 9354 // are trying to install should be installed as an update to 9355 // the existing one, but that has not been requested, so bail. 9356 Slog.w(TAG, "Attempt to re-install " + pkgName 9357 + " without first uninstalling package running as " 9358 + mSettings.mRenamedPackages.get(pkgName)); 9359 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9360 return; 9361 } 9362 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) { 9363 // Don't allow installation over an existing package with the same name. 9364 Slog.w(TAG, "Attempt to re-install " + pkgName 9365 + " without first uninstalling."); 9366 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9367 return; 9368 } 9369 } 9370 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9371 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9372 System.currentTimeMillis(), user); 9373 if (newPackage == null) { 9374 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9375 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9376 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9377 } 9378 } else { 9379 updateSettingsLI(newPackage, 9380 installerPackageName, 9381 null, null, 9382 res); 9383 // delete the partially installed application. the data directory will have to be 9384 // restored if it was already existing 9385 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9386 // remove package from internal structures. Note that we want deletePackageX to 9387 // delete the package data and cache directories that it created in 9388 // scanPackageLocked, unless those directories existed before we even tried to 9389 // install. 9390 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9391 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9392 res.removedInfo, true); 9393 } 9394 } 9395 } 9396 9397 private void replacePackageLI(PackageParser.Package pkg, 9398 int parseFlags, int scanMode, UserHandle user, 9399 String installerPackageName, PackageInstalledInfo res) { 9400 9401 PackageParser.Package oldPackage; 9402 String pkgName = pkg.packageName; 9403 int[] allUsers; 9404 boolean[] perUserInstalled; 9405 9406 // First find the old package info and check signatures 9407 synchronized(mPackages) { 9408 oldPackage = mPackages.get(pkgName); 9409 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9410 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9411 != PackageManager.SIGNATURE_MATCH) { 9412 Slog.w(TAG, "New package has a different signature: " + pkgName); 9413 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9414 return; 9415 } 9416 9417 // In case of rollback, remember per-user/profile install state 9418 PackageSetting ps = mSettings.mPackages.get(pkgName); 9419 allUsers = sUserManager.getUserIds(); 9420 perUserInstalled = new boolean[allUsers.length]; 9421 for (int i = 0; i < allUsers.length; i++) { 9422 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9423 } 9424 } 9425 boolean sysPkg = (isSystemApp(oldPackage)); 9426 if (sysPkg) { 9427 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9428 user, allUsers, perUserInstalled, installerPackageName, res); 9429 } else { 9430 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9431 user, allUsers, perUserInstalled, installerPackageName, res); 9432 } 9433 } 9434 9435 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9436 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9437 int[] allUsers, boolean[] perUserInstalled, 9438 String installerPackageName, PackageInstalledInfo res) { 9439 PackageParser.Package newPackage = null; 9440 String pkgName = deletedPackage.packageName; 9441 boolean deletedPkg = true; 9442 boolean updatedSettings = false; 9443 9444 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9445 + deletedPackage); 9446 long origUpdateTime; 9447 if (pkg.mExtras != null) { 9448 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9449 } else { 9450 origUpdateTime = 0; 9451 } 9452 9453 // First delete the existing package while retaining the data directory 9454 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9455 res.removedInfo, true)) { 9456 // If the existing package wasn't successfully deleted 9457 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9458 deletedPkg = false; 9459 } else { 9460 // Successfully deleted the old package. Now proceed with re-installation 9461 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9462 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9463 System.currentTimeMillis(), user); 9464 if (newPackage == null) { 9465 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9466 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9467 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9468 } 9469 } else { 9470 updateSettingsLI(newPackage, 9471 installerPackageName, 9472 allUsers, perUserInstalled, 9473 res); 9474 updatedSettings = true; 9475 } 9476 } 9477 9478 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9479 // remove package from internal structures. Note that we want deletePackageX to 9480 // delete the package data and cache directories that it created in 9481 // scanPackageLocked, unless those directories existed before we even tried to 9482 // install. 9483 if(updatedSettings) { 9484 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9485 deletePackageLI( 9486 pkgName, null, true, allUsers, perUserInstalled, 9487 PackageManager.DELETE_KEEP_DATA, 9488 res.removedInfo, true); 9489 } 9490 // Since we failed to install the new package we need to restore the old 9491 // package that we deleted. 9492 if(deletedPkg) { 9493 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9494 File restoreFile = new File(deletedPackage.mPath); 9495 // Parse old package 9496 boolean oldOnSd = isExternal(deletedPackage); 9497 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9498 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9499 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9500 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 9501 | SCAN_UPDATE_TIME; 9502 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 9503 origUpdateTime, null) == null) { 9504 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 9505 return; 9506 } 9507 // Restore of old package succeeded. Update permissions. 9508 // writer 9509 synchronized (mPackages) { 9510 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9511 UPDATE_PERMISSIONS_ALL); 9512 // can downgrade to reader 9513 mSettings.writeLPr(); 9514 } 9515 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9516 } 9517 } 9518 } 9519 9520 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9521 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9522 int[] allUsers, boolean[] perUserInstalled, 9523 String installerPackageName, PackageInstalledInfo res) { 9524 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9525 + ", old=" + deletedPackage); 9526 PackageParser.Package newPackage = null; 9527 boolean updatedSettings = false; 9528 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 9529 PackageParser.PARSE_IS_SYSTEM; 9530 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9531 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9532 } 9533 String packageName = deletedPackage.packageName; 9534 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9535 if (packageName == null) { 9536 Slog.w(TAG, "Attempt to delete null packageName."); 9537 return; 9538 } 9539 PackageParser.Package oldPkg; 9540 PackageSetting oldPkgSetting; 9541 // reader 9542 synchronized (mPackages) { 9543 oldPkg = mPackages.get(packageName); 9544 oldPkgSetting = mSettings.mPackages.get(packageName); 9545 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 9546 (oldPkgSetting == null)) { 9547 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 9548 return; 9549 } 9550 } 9551 9552 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 9553 9554 res.removedInfo.uid = oldPkg.applicationInfo.uid; 9555 res.removedInfo.removedPackage = packageName; 9556 // Remove existing system package 9557 removePackageLI(oldPkgSetting, true); 9558 // writer 9559 synchronized (mPackages) { 9560 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 9561 // We didn't need to disable the .apk as a current system package, 9562 // which means we are replacing another update that is already 9563 // installed. We need to make sure to delete the older one's .apk. 9564 res.removedInfo.args = createInstallArgs(0, 9565 deletedPackage.applicationInfo.sourceDir, 9566 deletedPackage.applicationInfo.publicSourceDir, 9567 deletedPackage.applicationInfo.nativeLibraryDir, 9568 getAppInstructionSet(deletedPackage.applicationInfo)); 9569 } else { 9570 res.removedInfo.args = null; 9571 } 9572 } 9573 9574 // Successfully disabled the old package. Now proceed with re-installation 9575 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9576 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9577 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user); 9578 if (newPackage == null) { 9579 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9580 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9581 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9582 } 9583 } else { 9584 if (newPackage.mExtras != null) { 9585 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 9586 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 9587 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 9588 9589 // is the update attempting to change shared user? that isn't going to work... 9590 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 9591 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 9592 + " to " + newPkgSetting.sharedUser); 9593 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 9594 updatedSettings = true; 9595 } 9596 } 9597 9598 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9599 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9600 updatedSettings = true; 9601 } 9602 } 9603 9604 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9605 // Re installation failed. Restore old information 9606 // Remove new pkg information 9607 if (newPackage != null) { 9608 removeInstalledPackageLI(newPackage, true); 9609 } 9610 // Add back the old system package 9611 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user); 9612 // Restore the old system information in Settings 9613 synchronized(mPackages) { 9614 if (updatedSettings) { 9615 mSettings.enableSystemPackageLPw(packageName); 9616 mSettings.setInstallerPackageName(packageName, 9617 oldPkgSetting.installerPackageName); 9618 } 9619 mSettings.writeLPr(); 9620 } 9621 } 9622 } 9623 9624 // Utility method used to move dex files during install. 9625 private int moveDexFilesLI(PackageParser.Package newPackage) { 9626 int retCode; 9627 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 9628 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath, 9629 getAppInstructionSet(newPackage.applicationInfo)); 9630 if (retCode != 0) { 9631 if (mNoDexOpt) { 9632 /* 9633 * If we're in an engineering build, programs are lazily run 9634 * through dexopt. If the .dex file doesn't exist yet, it 9635 * will be created when the program is run next. 9636 */ 9637 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath); 9638 } else { 9639 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath); 9640 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9641 } 9642 } 9643 } 9644 return PackageManager.INSTALL_SUCCEEDED; 9645 } 9646 9647 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 9648 int[] allUsers, boolean[] perUserInstalled, 9649 PackageInstalledInfo res) { 9650 String pkgName = newPackage.packageName; 9651 synchronized (mPackages) { 9652 //write settings. the installStatus will be incomplete at this stage. 9653 //note that the new package setting would have already been 9654 //added to mPackages. It hasn't been persisted yet. 9655 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 9656 mSettings.writeLPr(); 9657 } 9658 9659 if ((res.returnCode = moveDexFilesLI(newPackage)) 9660 != PackageManager.INSTALL_SUCCEEDED) { 9661 // Discontinue if moving dex files failed. 9662 return; 9663 } 9664 9665 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath); 9666 9667 synchronized (mPackages) { 9668 updatePermissionsLPw(newPackage.packageName, newPackage, 9669 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 9670 ? UPDATE_PERMISSIONS_ALL : 0)); 9671 // For system-bundled packages, we assume that installing an upgraded version 9672 // of the package implies that the user actually wants to run that new code, 9673 // so we enable the package. 9674 if (isSystemApp(newPackage)) { 9675 // NB: implicit assumption that system package upgrades apply to all users 9676 if (DEBUG_INSTALL) { 9677 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 9678 } 9679 PackageSetting ps = mSettings.mPackages.get(pkgName); 9680 if (ps != null) { 9681 if (res.origUsers != null) { 9682 for (int userHandle : res.origUsers) { 9683 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 9684 userHandle, installerPackageName); 9685 } 9686 } 9687 // Also convey the prior install/uninstall state 9688 if (allUsers != null && perUserInstalled != null) { 9689 for (int i = 0; i < allUsers.length; i++) { 9690 if (DEBUG_INSTALL) { 9691 Slog.d(TAG, " user " + allUsers[i] 9692 + " => " + perUserInstalled[i]); 9693 } 9694 ps.setInstalled(perUserInstalled[i], allUsers[i]); 9695 } 9696 // these install state changes will be persisted in the 9697 // upcoming call to mSettings.writeLPr(). 9698 } 9699 } 9700 } 9701 res.name = pkgName; 9702 res.uid = newPackage.applicationInfo.uid; 9703 res.pkg = newPackage; 9704 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 9705 mSettings.setInstallerPackageName(pkgName, installerPackageName); 9706 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 9707 //to update install status 9708 mSettings.writeLPr(); 9709 } 9710 } 9711 9712 private void installPackageLI(InstallArgs args, 9713 boolean newInstall, PackageInstalledInfo res) { 9714 int pFlags = args.flags; 9715 String installerPackageName = args.installerPackageName; 9716 File tmpPackageFile = new File(args.getCodePath()); 9717 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 9718 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 9719 boolean replace = false; 9720 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 9721 | (newInstall ? SCAN_NEW_INSTALL : 0); 9722 // Result object to be returned 9723 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 9724 9725 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 9726 // Retrieve PackageSettings and parse package 9727 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 9728 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 9729 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 9730 PackageParser pp = new PackageParser(tmpPackageFile.getPath()); 9731 pp.setSeparateProcesses(mSeparateProcesses); 9732 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile, 9733 null, mMetrics, parseFlags); 9734 if (pkg == null) { 9735 res.returnCode = pp.getParseError(); 9736 return; 9737 } 9738 String pkgName = res.name = pkg.packageName; 9739 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 9740 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 9741 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 9742 return; 9743 } 9744 } 9745 if (!pp.collectCertificates(pkg, parseFlags)) { 9746 res.returnCode = pp.getParseError(); 9747 return; 9748 } 9749 9750 /* If the installer passed in a manifest digest, compare it now. */ 9751 if (args.manifestDigest != null) { 9752 if (DEBUG_INSTALL) { 9753 final String parsedManifest = pkg.manifestDigest == null ? "null" 9754 : pkg.manifestDigest.toString(); 9755 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 9756 + parsedManifest); 9757 } 9758 9759 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 9760 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 9761 return; 9762 } 9763 } else if (DEBUG_INSTALL) { 9764 final String parsedManifest = pkg.manifestDigest == null 9765 ? "null" : pkg.manifestDigest.toString(); 9766 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 9767 } 9768 9769 // Get rid of all references to package scan path via parser. 9770 pp = null; 9771 String oldCodePath = null; 9772 boolean systemApp = false; 9773 synchronized (mPackages) { 9774 // Check whether the newly-scanned package wants to define an already-defined perm 9775 int N = pkg.permissions.size(); 9776 for (int i = 0; i < N; i++) { 9777 PackageParser.Permission perm = pkg.permissions.get(i); 9778 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 9779 if (bp != null) { 9780 // If the defining package is signed with our cert, it's okay. This 9781 // also includes the "updating the same package" case, of course. 9782 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 9783 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9784 Slog.w(TAG, "Package " + pkg.packageName 9785 + " attempting to redeclare permission " + perm.info.name 9786 + " already owned by " + bp.sourcePackage); 9787 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 9788 res.origPermission = perm.info.name; 9789 res.origPackage = bp.sourcePackage; 9790 return; 9791 } 9792 } 9793 } 9794 9795 // Check if installing already existing package 9796 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9797 String oldName = mSettings.mRenamedPackages.get(pkgName); 9798 if (pkg.mOriginalPackages != null 9799 && pkg.mOriginalPackages.contains(oldName) 9800 && mPackages.containsKey(oldName)) { 9801 // This package is derived from an original package, 9802 // and this device has been updating from that original 9803 // name. We must continue using the original name, so 9804 // rename the new package here. 9805 pkg.setPackageName(oldName); 9806 pkgName = pkg.packageName; 9807 replace = true; 9808 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 9809 + oldName + " pkgName=" + pkgName); 9810 } else if (mPackages.containsKey(pkgName)) { 9811 // This package, under its official name, already exists 9812 // on the device; we should replace it. 9813 replace = true; 9814 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 9815 } 9816 } 9817 PackageSetting ps = mSettings.mPackages.get(pkgName); 9818 if (ps != null) { 9819 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 9820 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 9821 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 9822 systemApp = (ps.pkg.applicationInfo.flags & 9823 ApplicationInfo.FLAG_SYSTEM) != 0; 9824 } 9825 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 9826 } 9827 } 9828 9829 if (systemApp && onSd) { 9830 // Disable updates to system apps on sdcard 9831 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 9832 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9833 return; 9834 } 9835 9836 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 9837 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9838 return; 9839 } 9840 // Set application objects path explicitly after the rename 9841 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath()); 9842 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 9843 if (replace) { 9844 replacePackageLI(pkg, parseFlags, scanMode, args.user, 9845 installerPackageName, res); 9846 } else { 9847 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 9848 installerPackageName, res); 9849 } 9850 synchronized (mPackages) { 9851 final PackageSetting ps = mSettings.mPackages.get(pkgName); 9852 if (ps != null) { 9853 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 9854 } 9855 } 9856 } 9857 9858 private static boolean isForwardLocked(PackageParser.Package pkg) { 9859 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 9860 } 9861 9862 9863 private boolean isForwardLocked(PackageSetting ps) { 9864 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 9865 } 9866 9867 private static boolean isExternal(PackageParser.Package pkg) { 9868 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 9869 } 9870 9871 private static boolean isExternal(PackageSetting ps) { 9872 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 9873 } 9874 9875 private static boolean isSystemApp(PackageParser.Package pkg) { 9876 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9877 } 9878 9879 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 9880 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 9881 } 9882 9883 private static boolean isSystemApp(ApplicationInfo info) { 9884 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9885 } 9886 9887 private static boolean isSystemApp(PackageSetting ps) { 9888 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 9889 } 9890 9891 private static boolean isUpdatedSystemApp(PackageSetting ps) { 9892 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 9893 } 9894 9895 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 9896 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 9897 } 9898 9899 private int packageFlagsToInstallFlags(PackageSetting ps) { 9900 int installFlags = 0; 9901 if (isExternal(ps)) { 9902 installFlags |= PackageManager.INSTALL_EXTERNAL; 9903 } 9904 if (isForwardLocked(ps)) { 9905 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 9906 } 9907 return installFlags; 9908 } 9909 9910 private void deleteTempPackageFiles() { 9911 final FilenameFilter filter = new FilenameFilter() { 9912 public boolean accept(File dir, String name) { 9913 return name.startsWith("vmdl") && name.endsWith(".tmp"); 9914 } 9915 }; 9916 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 9917 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 9918 } 9919 9920 private static final void deleteTempPackageFilesInDirectory(File directory, 9921 FilenameFilter filter) { 9922 final String[] tmpFilesList = directory.list(filter); 9923 if (tmpFilesList == null) { 9924 return; 9925 } 9926 for (int i = 0; i < tmpFilesList.length; i++) { 9927 final File tmpFile = new File(directory, tmpFilesList[i]); 9928 tmpFile.delete(); 9929 } 9930 } 9931 9932 private File createTempPackageFile(File installDir) { 9933 File tmpPackageFile; 9934 try { 9935 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 9936 } catch (IOException e) { 9937 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 9938 return null; 9939 } 9940 try { 9941 FileUtils.setPermissions( 9942 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 9943 -1, -1); 9944 if (!SELinux.restorecon(tmpPackageFile)) { 9945 return null; 9946 } 9947 } catch (IOException e) { 9948 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 9949 return null; 9950 } 9951 return tmpPackageFile; 9952 } 9953 9954 @Override 9955 public void deletePackageAsUser(final String packageName, 9956 final IPackageDeleteObserver observer, 9957 final int userId, final int flags) { 9958 mContext.enforceCallingOrSelfPermission( 9959 android.Manifest.permission.DELETE_PACKAGES, null); 9960 final int uid = Binder.getCallingUid(); 9961 if (UserHandle.getUserId(uid) != userId) { 9962 mContext.enforceCallingPermission( 9963 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 9964 "deletePackage for user " + userId); 9965 } 9966 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 9967 try { 9968 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 9969 } catch (RemoteException re) { 9970 } 9971 return; 9972 } 9973 9974 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 9975 // Queue up an async operation since the package deletion may take a little while. 9976 mHandler.post(new Runnable() { 9977 public void run() { 9978 mHandler.removeCallbacks(this); 9979 final int returnCode = deletePackageX(packageName, userId, flags); 9980 if (observer != null) { 9981 try { 9982 observer.packageDeleted(packageName, returnCode); 9983 } catch (RemoteException e) { 9984 Log.i(TAG, "Observer no longer exists."); 9985 } //end catch 9986 } //end if 9987 } //end run 9988 }); 9989 } 9990 9991 private boolean isPackageDeviceAdmin(String packageName, int userId) { 9992 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 9993 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 9994 try { 9995 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 9996 || dpm.isDeviceOwner(packageName))) { 9997 return true; 9998 } 9999 } catch (RemoteException e) { 10000 } 10001 return false; 10002 } 10003 10004 /** 10005 * This method is an internal method that could be get invoked either 10006 * to delete an installed package or to clean up a failed installation. 10007 * After deleting an installed package, a broadcast is sent to notify any 10008 * listeners that the package has been installed. For cleaning up a failed 10009 * installation, the broadcast is not necessary since the package's 10010 * installation wouldn't have sent the initial broadcast either 10011 * The key steps in deleting a package are 10012 * deleting the package information in internal structures like mPackages, 10013 * deleting the packages base directories through installd 10014 * updating mSettings to reflect current status 10015 * persisting settings for later use 10016 * sending a broadcast if necessary 10017 */ 10018 private int deletePackageX(String packageName, int userId, int flags) { 10019 final PackageRemovedInfo info = new PackageRemovedInfo(); 10020 final boolean res; 10021 10022 if (isPackageDeviceAdmin(packageName, userId)) { 10023 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10024 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10025 } 10026 10027 boolean removedForAllUsers = false; 10028 boolean systemUpdate = false; 10029 10030 // for the uninstall-updates case and restricted profiles, remember the per- 10031 // userhandle installed state 10032 int[] allUsers; 10033 boolean[] perUserInstalled; 10034 synchronized (mPackages) { 10035 PackageSetting ps = mSettings.mPackages.get(packageName); 10036 allUsers = sUserManager.getUserIds(); 10037 perUserInstalled = new boolean[allUsers.length]; 10038 for (int i = 0; i < allUsers.length; i++) { 10039 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10040 } 10041 } 10042 10043 synchronized (mInstallLock) { 10044 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10045 res = deletePackageLI(packageName, 10046 (flags & PackageManager.DELETE_ALL_USERS) != 0 10047 ? UserHandle.ALL : new UserHandle(userId), 10048 true, allUsers, perUserInstalled, 10049 flags | REMOVE_CHATTY, info, true); 10050 systemUpdate = info.isRemovedPackageSystemUpdate; 10051 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10052 removedForAllUsers = true; 10053 } 10054 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10055 + " removedForAllUsers=" + removedForAllUsers); 10056 } 10057 10058 if (res) { 10059 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10060 10061 // If the removed package was a system update, the old system package 10062 // was re-enabled; we need to broadcast this information 10063 if (systemUpdate) { 10064 Bundle extras = new Bundle(1); 10065 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10066 ? info.removedAppId : info.uid); 10067 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10068 10069 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10070 extras, null, null, null); 10071 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10072 extras, null, null, null); 10073 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10074 null, packageName, null, null); 10075 } 10076 } 10077 // Force a gc here. 10078 Runtime.getRuntime().gc(); 10079 // Delete the resources here after sending the broadcast to let 10080 // other processes clean up before deleting resources. 10081 if (info.args != null) { 10082 synchronized (mInstallLock) { 10083 info.args.doPostDeleteLI(true); 10084 } 10085 } 10086 10087 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10088 } 10089 10090 static class PackageRemovedInfo { 10091 String removedPackage; 10092 int uid = -1; 10093 int removedAppId = -1; 10094 int[] removedUsers = null; 10095 boolean isRemovedPackageSystemUpdate = false; 10096 // Clean up resources deleted packages. 10097 InstallArgs args = null; 10098 10099 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10100 Bundle extras = new Bundle(1); 10101 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10102 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10103 if (replacing) { 10104 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10105 } 10106 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10107 if (removedPackage != null) { 10108 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10109 extras, null, null, removedUsers); 10110 if (fullRemove && !replacing) { 10111 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10112 extras, null, null, removedUsers); 10113 } 10114 } 10115 if (removedAppId >= 0) { 10116 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10117 removedUsers); 10118 } 10119 } 10120 } 10121 10122 /* 10123 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10124 * flag is not set, the data directory is removed as well. 10125 * make sure this flag is set for partially installed apps. If not its meaningless to 10126 * delete a partially installed application. 10127 */ 10128 private void removePackageDataLI(PackageSetting ps, 10129 int[] allUserHandles, boolean[] perUserInstalled, 10130 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10131 String packageName = ps.name; 10132 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10133 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10134 // Retrieve object to delete permissions for shared user later on 10135 final PackageSetting deletedPs; 10136 // reader 10137 synchronized (mPackages) { 10138 deletedPs = mSettings.mPackages.get(packageName); 10139 if (outInfo != null) { 10140 outInfo.removedPackage = packageName; 10141 outInfo.removedUsers = deletedPs != null 10142 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10143 : null; 10144 } 10145 } 10146 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10147 removeDataDirsLI(packageName); 10148 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10149 } 10150 // writer 10151 synchronized (mPackages) { 10152 if (deletedPs != null) { 10153 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10154 if (outInfo != null) { 10155 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10156 } 10157 if (deletedPs != null) { 10158 updatePermissionsLPw(deletedPs.name, null, 0); 10159 if (deletedPs.sharedUser != null) { 10160 // remove permissions associated with package 10161 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10162 } 10163 } 10164 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10165 } 10166 // make sure to preserve per-user disabled state if this removal was just 10167 // a downgrade of a system app to the factory package 10168 if (allUserHandles != null && perUserInstalled != null) { 10169 if (DEBUG_REMOVE) { 10170 Slog.d(TAG, "Propagating install state across downgrade"); 10171 } 10172 for (int i = 0; i < allUserHandles.length; i++) { 10173 if (DEBUG_REMOVE) { 10174 Slog.d(TAG, " user " + allUserHandles[i] 10175 + " => " + perUserInstalled[i]); 10176 } 10177 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10178 } 10179 } 10180 } 10181 // can downgrade to reader 10182 if (writeSettings) { 10183 // Save settings now 10184 mSettings.writeLPr(); 10185 } 10186 } 10187 if (outInfo != null) { 10188 // A user ID was deleted here. Go through all users and remove it 10189 // from KeyStore. 10190 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10191 } 10192 } 10193 10194 static boolean locationIsPrivileged(File path) { 10195 try { 10196 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10197 .getCanonicalPath(); 10198 return path.getCanonicalPath().startsWith(privilegedAppDir); 10199 } catch (IOException e) { 10200 Slog.e(TAG, "Unable to access code path " + path); 10201 } 10202 return false; 10203 } 10204 10205 /* 10206 * Tries to delete system package. 10207 */ 10208 private boolean deleteSystemPackageLI(PackageSetting newPs, 10209 int[] allUserHandles, boolean[] perUserInstalled, 10210 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10211 final boolean applyUserRestrictions 10212 = (allUserHandles != null) && (perUserInstalled != null); 10213 PackageSetting disabledPs = null; 10214 // Confirm if the system package has been updated 10215 // An updated system app can be deleted. This will also have to restore 10216 // the system pkg from system partition 10217 // reader 10218 synchronized (mPackages) { 10219 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10220 } 10221 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10222 + " disabledPs=" + disabledPs); 10223 if (disabledPs == null) { 10224 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10225 return false; 10226 } else if (DEBUG_REMOVE) { 10227 Slog.d(TAG, "Deleting system pkg from data partition"); 10228 } 10229 if (DEBUG_REMOVE) { 10230 if (applyUserRestrictions) { 10231 Slog.d(TAG, "Remembering install states:"); 10232 for (int i = 0; i < allUserHandles.length; i++) { 10233 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10234 } 10235 } 10236 } 10237 // Delete the updated package 10238 outInfo.isRemovedPackageSystemUpdate = true; 10239 if (disabledPs.versionCode < newPs.versionCode) { 10240 // Delete data for downgrades 10241 flags &= ~PackageManager.DELETE_KEEP_DATA; 10242 } else { 10243 // Preserve data by setting flag 10244 flags |= PackageManager.DELETE_KEEP_DATA; 10245 } 10246 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10247 allUserHandles, perUserInstalled, outInfo, writeSettings); 10248 if (!ret) { 10249 return false; 10250 } 10251 // writer 10252 synchronized (mPackages) { 10253 // Reinstate the old system package 10254 mSettings.enableSystemPackageLPw(newPs.name); 10255 // Remove any native libraries from the upgraded package. 10256 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 10257 } 10258 // Install the system package 10259 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10260 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10261 if (locationIsPrivileged(disabledPs.codePath)) { 10262 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10263 } 10264 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10265 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null); 10266 10267 if (newPkg == null) { 10268 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10269 + " with error:" + mLastScanError); 10270 return false; 10271 } 10272 // writer 10273 synchronized (mPackages) { 10274 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10275 setInternalAppNativeLibraryPath(newPkg, ps); 10276 updatePermissionsLPw(newPkg.packageName, newPkg, 10277 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10278 if (applyUserRestrictions) { 10279 if (DEBUG_REMOVE) { 10280 Slog.d(TAG, "Propagating install state across reinstall"); 10281 } 10282 for (int i = 0; i < allUserHandles.length; i++) { 10283 if (DEBUG_REMOVE) { 10284 Slog.d(TAG, " user " + allUserHandles[i] 10285 + " => " + perUserInstalled[i]); 10286 } 10287 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10288 } 10289 // Regardless of writeSettings we need to ensure that this restriction 10290 // state propagation is persisted 10291 mSettings.writeAllUsersPackageRestrictionsLPr(); 10292 } 10293 // can downgrade to reader here 10294 if (writeSettings) { 10295 mSettings.writeLPr(); 10296 } 10297 } 10298 return true; 10299 } 10300 10301 private boolean deleteInstalledPackageLI(PackageSetting ps, 10302 boolean deleteCodeAndResources, int flags, 10303 int[] allUserHandles, boolean[] perUserInstalled, 10304 PackageRemovedInfo outInfo, boolean writeSettings) { 10305 if (outInfo != null) { 10306 outInfo.uid = ps.appId; 10307 } 10308 10309 // Delete package data from internal structures and also remove data if flag is set 10310 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10311 10312 // Delete application code and resources 10313 if (deleteCodeAndResources && (outInfo != null)) { 10314 outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString, 10315 ps.resourcePathString, ps.nativeLibraryPathString, 10316 getAppInstructionSetFromSettings(ps)); 10317 } 10318 return true; 10319 } 10320 10321 /* 10322 * This method handles package deletion in general 10323 */ 10324 private boolean deletePackageLI(String packageName, UserHandle user, 10325 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10326 int flags, PackageRemovedInfo outInfo, 10327 boolean writeSettings) { 10328 if (packageName == null) { 10329 Slog.w(TAG, "Attempt to delete null packageName."); 10330 return false; 10331 } 10332 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10333 PackageSetting ps; 10334 boolean dataOnly = false; 10335 int removeUser = -1; 10336 int appId = -1; 10337 synchronized (mPackages) { 10338 ps = mSettings.mPackages.get(packageName); 10339 if (ps == null) { 10340 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10341 return false; 10342 } 10343 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10344 && user.getIdentifier() != UserHandle.USER_ALL) { 10345 // The caller is asking that the package only be deleted for a single 10346 // user. To do this, we just mark its uninstalled state and delete 10347 // its data. If this is a system app, we only allow this to happen if 10348 // they have set the special DELETE_SYSTEM_APP which requests different 10349 // semantics than normal for uninstalling system apps. 10350 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10351 ps.setUserState(user.getIdentifier(), 10352 COMPONENT_ENABLED_STATE_DEFAULT, 10353 false, //installed 10354 true, //stopped 10355 true, //notLaunched 10356 false, //blocked 10357 null, null, null); 10358 if (!isSystemApp(ps)) { 10359 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10360 // Other user still have this package installed, so all 10361 // we need to do is clear this user's data and save that 10362 // it is uninstalled. 10363 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10364 removeUser = user.getIdentifier(); 10365 appId = ps.appId; 10366 mSettings.writePackageRestrictionsLPr(removeUser); 10367 } else { 10368 // We need to set it back to 'installed' so the uninstall 10369 // broadcasts will be sent correctly. 10370 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10371 ps.setInstalled(true, user.getIdentifier()); 10372 } 10373 } else { 10374 // This is a system app, so we assume that the 10375 // other users still have this package installed, so all 10376 // we need to do is clear this user's data and save that 10377 // it is uninstalled. 10378 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10379 removeUser = user.getIdentifier(); 10380 appId = ps.appId; 10381 mSettings.writePackageRestrictionsLPr(removeUser); 10382 } 10383 } 10384 } 10385 10386 if (removeUser >= 0) { 10387 // From above, we determined that we are deleting this only 10388 // for a single user. Continue the work here. 10389 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10390 if (outInfo != null) { 10391 outInfo.removedPackage = packageName; 10392 outInfo.removedAppId = appId; 10393 outInfo.removedUsers = new int[] {removeUser}; 10394 } 10395 mInstaller.clearUserData(packageName, removeUser); 10396 removeKeystoreDataIfNeeded(removeUser, appId); 10397 schedulePackageCleaning(packageName, removeUser, false); 10398 return true; 10399 } 10400 10401 if (dataOnly) { 10402 // Delete application data first 10403 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10404 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10405 return true; 10406 } 10407 10408 boolean ret = false; 10409 mSettings.mKeySetManager.removeAppKeySetData(packageName); 10410 if (isSystemApp(ps)) { 10411 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10412 // When an updated system application is deleted we delete the existing resources as well and 10413 // fall back to existing code in system partition 10414 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10415 flags, outInfo, writeSettings); 10416 } else { 10417 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10418 // Kill application pre-emptively especially for apps on sd. 10419 killApplication(packageName, ps.appId, "uninstall pkg"); 10420 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10421 allUserHandles, perUserInstalled, 10422 outInfo, writeSettings); 10423 } 10424 10425 return ret; 10426 } 10427 10428 private final class ClearStorageConnection implements ServiceConnection { 10429 IMediaContainerService mContainerService; 10430 10431 @Override 10432 public void onServiceConnected(ComponentName name, IBinder service) { 10433 synchronized (this) { 10434 mContainerService = IMediaContainerService.Stub.asInterface(service); 10435 notifyAll(); 10436 } 10437 } 10438 10439 @Override 10440 public void onServiceDisconnected(ComponentName name) { 10441 } 10442 } 10443 10444 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10445 final boolean mounted; 10446 if (Environment.isExternalStorageEmulated()) { 10447 mounted = true; 10448 } else { 10449 final String status = Environment.getExternalStorageState(); 10450 10451 mounted = status.equals(Environment.MEDIA_MOUNTED) 10452 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10453 } 10454 10455 if (!mounted) { 10456 return; 10457 } 10458 10459 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10460 int[] users; 10461 if (userId == UserHandle.USER_ALL) { 10462 users = sUserManager.getUserIds(); 10463 } else { 10464 users = new int[] { userId }; 10465 } 10466 final ClearStorageConnection conn = new ClearStorageConnection(); 10467 if (mContext.bindServiceAsUser( 10468 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10469 try { 10470 for (int curUser : users) { 10471 long timeout = SystemClock.uptimeMillis() + 5000; 10472 synchronized (conn) { 10473 long now = SystemClock.uptimeMillis(); 10474 while (conn.mContainerService == null && now < timeout) { 10475 try { 10476 conn.wait(timeout - now); 10477 } catch (InterruptedException e) { 10478 } 10479 } 10480 } 10481 if (conn.mContainerService == null) { 10482 return; 10483 } 10484 10485 final UserEnvironment userEnv = new UserEnvironment(curUser); 10486 clearDirectory(conn.mContainerService, 10487 userEnv.buildExternalStorageAppCacheDirs(packageName)); 10488 if (allData) { 10489 clearDirectory(conn.mContainerService, 10490 userEnv.buildExternalStorageAppDataDirs(packageName)); 10491 clearDirectory(conn.mContainerService, 10492 userEnv.buildExternalStorageAppMediaDirs(packageName)); 10493 } 10494 } 10495 } finally { 10496 mContext.unbindService(conn); 10497 } 10498 } 10499 } 10500 10501 @Override 10502 public void clearApplicationUserData(final String packageName, 10503 final IPackageDataObserver observer, final int userId) { 10504 mContext.enforceCallingOrSelfPermission( 10505 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 10506 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 10507 // Queue up an async operation since the package deletion may take a little while. 10508 mHandler.post(new Runnable() { 10509 public void run() { 10510 mHandler.removeCallbacks(this); 10511 final boolean succeeded; 10512 synchronized (mInstallLock) { 10513 succeeded = clearApplicationUserDataLI(packageName, userId); 10514 } 10515 clearExternalStorageDataSync(packageName, userId, true); 10516 if (succeeded) { 10517 // invoke DeviceStorageMonitor's update method to clear any notifications 10518 DeviceStorageMonitorInternal 10519 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 10520 if (dsm != null) { 10521 dsm.checkMemory(); 10522 } 10523 } 10524 if(observer != null) { 10525 try { 10526 observer.onRemoveCompleted(packageName, succeeded); 10527 } catch (RemoteException e) { 10528 Log.i(TAG, "Observer no longer exists."); 10529 } 10530 } //end if observer 10531 } //end run 10532 }); 10533 } 10534 10535 private boolean clearApplicationUserDataLI(String packageName, int userId) { 10536 if (packageName == null) { 10537 Slog.w(TAG, "Attempt to delete null packageName."); 10538 return false; 10539 } 10540 PackageParser.Package p; 10541 boolean dataOnly = false; 10542 final int appId; 10543 synchronized (mPackages) { 10544 p = mPackages.get(packageName); 10545 if (p == null) { 10546 dataOnly = true; 10547 PackageSetting ps = mSettings.mPackages.get(packageName); 10548 if ((ps == null) || (ps.pkg == null)) { 10549 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10550 return false; 10551 } 10552 p = ps.pkg; 10553 } 10554 if (!dataOnly) { 10555 // need to check this only for fully installed applications 10556 if (p == null) { 10557 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10558 return false; 10559 } 10560 final ApplicationInfo applicationInfo = p.applicationInfo; 10561 if (applicationInfo == null) { 10562 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10563 return false; 10564 } 10565 } 10566 if (p != null && p.applicationInfo != null) { 10567 appId = p.applicationInfo.uid; 10568 } else { 10569 appId = -1; 10570 } 10571 } 10572 int retCode = mInstaller.clearUserData(packageName, userId); 10573 if (retCode < 0) { 10574 Slog.w(TAG, "Couldn't remove cache files for package: " 10575 + packageName); 10576 return false; 10577 } 10578 removeKeystoreDataIfNeeded(userId, appId); 10579 return true; 10580 } 10581 10582 /** 10583 * Remove entries from the keystore daemon. Will only remove it if the 10584 * {@code appId} is valid. 10585 */ 10586 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 10587 if (appId < 0) { 10588 return; 10589 } 10590 10591 final KeyStore keyStore = KeyStore.getInstance(); 10592 if (keyStore != null) { 10593 if (userId == UserHandle.USER_ALL) { 10594 for (final int individual : sUserManager.getUserIds()) { 10595 keyStore.clearUid(UserHandle.getUid(individual, appId)); 10596 } 10597 } else { 10598 keyStore.clearUid(UserHandle.getUid(userId, appId)); 10599 } 10600 } else { 10601 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 10602 } 10603 } 10604 10605 public void deleteApplicationCacheFiles(final String packageName, 10606 final IPackageDataObserver observer) { 10607 mContext.enforceCallingOrSelfPermission( 10608 android.Manifest.permission.DELETE_CACHE_FILES, null); 10609 // Queue up an async operation since the package deletion may take a little while. 10610 final int userId = UserHandle.getCallingUserId(); 10611 mHandler.post(new Runnable() { 10612 public void run() { 10613 mHandler.removeCallbacks(this); 10614 final boolean succeded; 10615 synchronized (mInstallLock) { 10616 succeded = deleteApplicationCacheFilesLI(packageName, userId); 10617 } 10618 clearExternalStorageDataSync(packageName, userId, false); 10619 if(observer != null) { 10620 try { 10621 observer.onRemoveCompleted(packageName, succeded); 10622 } catch (RemoteException e) { 10623 Log.i(TAG, "Observer no longer exists."); 10624 } 10625 } //end if observer 10626 } //end run 10627 }); 10628 } 10629 10630 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 10631 if (packageName == null) { 10632 Slog.w(TAG, "Attempt to delete null packageName."); 10633 return false; 10634 } 10635 PackageParser.Package p; 10636 synchronized (mPackages) { 10637 p = mPackages.get(packageName); 10638 } 10639 if (p == null) { 10640 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 10641 return false; 10642 } 10643 final ApplicationInfo applicationInfo = p.applicationInfo; 10644 if (applicationInfo == null) { 10645 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10646 return false; 10647 } 10648 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 10649 if (retCode < 0) { 10650 Slog.w(TAG, "Couldn't remove cache files for package: " 10651 + packageName + " u" + userId); 10652 return false; 10653 } 10654 return true; 10655 } 10656 10657 public void getPackageSizeInfo(final String packageName, int userHandle, 10658 final IPackageStatsObserver observer) { 10659 mContext.enforceCallingOrSelfPermission( 10660 android.Manifest.permission.GET_PACKAGE_SIZE, null); 10661 if (packageName == null) { 10662 throw new IllegalArgumentException("Attempt to get size of null packageName"); 10663 } 10664 10665 PackageStats stats = new PackageStats(packageName, userHandle); 10666 10667 /* 10668 * Queue up an async operation since the package measurement may take a 10669 * little while. 10670 */ 10671 Message msg = mHandler.obtainMessage(INIT_COPY); 10672 msg.obj = new MeasureParams(stats, observer); 10673 mHandler.sendMessage(msg); 10674 } 10675 10676 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 10677 PackageStats pStats) { 10678 if (packageName == null) { 10679 Slog.w(TAG, "Attempt to get size of null packageName."); 10680 return false; 10681 } 10682 PackageParser.Package p; 10683 boolean dataOnly = false; 10684 String libDirPath = null; 10685 String asecPath = null; 10686 PackageSetting ps = null; 10687 synchronized (mPackages) { 10688 p = mPackages.get(packageName); 10689 ps = mSettings.mPackages.get(packageName); 10690 if(p == null) { 10691 dataOnly = true; 10692 if((ps == null) || (ps.pkg == null)) { 10693 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 10694 return false; 10695 } 10696 p = ps.pkg; 10697 } 10698 if (ps != null) { 10699 libDirPath = ps.nativeLibraryPathString; 10700 } 10701 if (p != null && (isExternal(p) || isForwardLocked(p))) { 10702 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 10703 if (secureContainerId != null) { 10704 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 10705 } 10706 } 10707 } 10708 String publicSrcDir = null; 10709 if(!dataOnly) { 10710 final ApplicationInfo applicationInfo = p.applicationInfo; 10711 if (applicationInfo == null) { 10712 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10713 return false; 10714 } 10715 if (isForwardLocked(p)) { 10716 publicSrcDir = applicationInfo.publicSourceDir; 10717 } 10718 } 10719 int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath, 10720 publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps), 10721 pStats); 10722 if (res < 0) { 10723 return false; 10724 } 10725 10726 // Fix-up for forward-locked applications in ASEC containers. 10727 if (!isExternal(p)) { 10728 pStats.codeSize += pStats.externalCodeSize; 10729 pStats.externalCodeSize = 0L; 10730 } 10731 10732 return true; 10733 } 10734 10735 10736 public void addPackageToPreferred(String packageName) { 10737 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 10738 } 10739 10740 public void removePackageFromPreferred(String packageName) { 10741 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 10742 } 10743 10744 public List<PackageInfo> getPreferredPackages(int flags) { 10745 return new ArrayList<PackageInfo>(); 10746 } 10747 10748 private int getUidTargetSdkVersionLockedLPr(int uid) { 10749 Object obj = mSettings.getUserIdLPr(uid); 10750 if (obj instanceof SharedUserSetting) { 10751 final SharedUserSetting sus = (SharedUserSetting) obj; 10752 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 10753 final Iterator<PackageSetting> it = sus.packages.iterator(); 10754 while (it.hasNext()) { 10755 final PackageSetting ps = it.next(); 10756 if (ps.pkg != null) { 10757 int v = ps.pkg.applicationInfo.targetSdkVersion; 10758 if (v < vers) vers = v; 10759 } 10760 } 10761 return vers; 10762 } else if (obj instanceof PackageSetting) { 10763 final PackageSetting ps = (PackageSetting) obj; 10764 if (ps.pkg != null) { 10765 return ps.pkg.applicationInfo.targetSdkVersion; 10766 } 10767 } 10768 return Build.VERSION_CODES.CUR_DEVELOPMENT; 10769 } 10770 10771 public void addPreferredActivity(IntentFilter filter, int match, 10772 ComponentName[] set, ComponentName activity, int userId) { 10773 addPreferredActivityInternal(filter, match, set, activity, true, userId); 10774 } 10775 10776 private void addPreferredActivityInternal(IntentFilter filter, int match, 10777 ComponentName[] set, ComponentName activity, boolean always, int userId) { 10778 // writer 10779 int callingUid = Binder.getCallingUid(); 10780 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 10781 if (filter.countActions() == 0) { 10782 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 10783 return; 10784 } 10785 synchronized (mPackages) { 10786 if (mContext.checkCallingOrSelfPermission( 10787 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10788 != PackageManager.PERMISSION_GRANTED) { 10789 if (getUidTargetSdkVersionLockedLPr(callingUid) 10790 < Build.VERSION_CODES.FROYO) { 10791 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 10792 + callingUid); 10793 return; 10794 } 10795 mContext.enforceCallingOrSelfPermission( 10796 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10797 } 10798 10799 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 10800 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10801 mSettings.editPreferredActivitiesLPw(userId).addFilter( 10802 new PreferredActivity(filter, match, set, activity, always)); 10803 mSettings.writePackageRestrictionsLPr(userId); 10804 } 10805 } 10806 10807 public void replacePreferredActivity(IntentFilter filter, int match, 10808 ComponentName[] set, ComponentName activity) { 10809 if (filter.countActions() != 1) { 10810 throw new IllegalArgumentException( 10811 "replacePreferredActivity expects filter to have only 1 action."); 10812 } 10813 if (filter.countDataAuthorities() != 0 10814 || filter.countDataPaths() != 0 10815 || filter.countDataSchemes() > 1 10816 || filter.countDataTypes() != 0) { 10817 throw new IllegalArgumentException( 10818 "replacePreferredActivity expects filter to have no data authorities, " + 10819 "paths, or types; and at most one scheme."); 10820 } 10821 synchronized (mPackages) { 10822 if (mContext.checkCallingOrSelfPermission( 10823 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10824 != PackageManager.PERMISSION_GRANTED) { 10825 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 10826 < Build.VERSION_CODES.FROYO) { 10827 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 10828 + Binder.getCallingUid()); 10829 return; 10830 } 10831 mContext.enforceCallingOrSelfPermission( 10832 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10833 } 10834 10835 final int callingUserId = UserHandle.getCallingUserId(); 10836 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 10837 if (pir != null) { 10838 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 10839 if (filter.countDataSchemes() == 1) { 10840 Uri.Builder builder = new Uri.Builder(); 10841 builder.scheme(filter.getDataScheme(0)); 10842 intent.setData(builder.build()); 10843 } 10844 List<PreferredActivity> matches = pir.queryIntent( 10845 intent, null, true, callingUserId); 10846 if (DEBUG_PREFERRED) { 10847 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 10848 } 10849 for (int i = 0; i < matches.size(); i++) { 10850 PreferredActivity pa = matches.get(i); 10851 if (DEBUG_PREFERRED) { 10852 Slog.i(TAG, "Removing preferred activity " 10853 + pa.mPref.mComponent + ":"); 10854 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10855 } 10856 pir.removeFilter(pa); 10857 } 10858 } 10859 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 10860 } 10861 } 10862 10863 public void clearPackagePreferredActivities(String packageName) { 10864 final int uid = Binder.getCallingUid(); 10865 // writer 10866 synchronized (mPackages) { 10867 PackageParser.Package pkg = mPackages.get(packageName); 10868 if (pkg == null || pkg.applicationInfo.uid != uid) { 10869 if (mContext.checkCallingOrSelfPermission( 10870 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10871 != PackageManager.PERMISSION_GRANTED) { 10872 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 10873 < Build.VERSION_CODES.FROYO) { 10874 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 10875 + Binder.getCallingUid()); 10876 return; 10877 } 10878 mContext.enforceCallingOrSelfPermission( 10879 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10880 } 10881 } 10882 10883 int user = UserHandle.getCallingUserId(); 10884 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 10885 mSettings.writePackageRestrictionsLPr(user); 10886 scheduleWriteSettingsLocked(); 10887 } 10888 } 10889 } 10890 10891 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 10892 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 10893 ArrayList<PreferredActivity> removed = null; 10894 boolean changed = false; 10895 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 10896 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 10897 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 10898 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 10899 continue; 10900 } 10901 Iterator<PreferredActivity> it = pir.filterIterator(); 10902 while (it.hasNext()) { 10903 PreferredActivity pa = it.next(); 10904 // Mark entry for removal only if it matches the package name 10905 // and the entry is of type "always". 10906 if (packageName == null || 10907 (pa.mPref.mComponent.getPackageName().equals(packageName) 10908 && pa.mPref.mAlways)) { 10909 if (removed == null) { 10910 removed = new ArrayList<PreferredActivity>(); 10911 } 10912 removed.add(pa); 10913 } 10914 } 10915 if (removed != null) { 10916 for (int j=0; j<removed.size(); j++) { 10917 PreferredActivity pa = removed.get(j); 10918 pir.removeFilter(pa); 10919 } 10920 changed = true; 10921 } 10922 } 10923 return changed; 10924 } 10925 10926 public void resetPreferredActivities(int userId) { 10927 mContext.enforceCallingOrSelfPermission( 10928 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10929 // writer 10930 synchronized (mPackages) { 10931 int user = UserHandle.getCallingUserId(); 10932 clearPackagePreferredActivitiesLPw(null, user); 10933 mSettings.readDefaultPreferredAppsLPw(this, user); 10934 mSettings.writePackageRestrictionsLPr(user); 10935 scheduleWriteSettingsLocked(); 10936 } 10937 } 10938 10939 public int getPreferredActivities(List<IntentFilter> outFilters, 10940 List<ComponentName> outActivities, String packageName) { 10941 10942 int num = 0; 10943 final int userId = UserHandle.getCallingUserId(); 10944 // reader 10945 synchronized (mPackages) { 10946 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 10947 if (pir != null) { 10948 final Iterator<PreferredActivity> it = pir.filterIterator(); 10949 while (it.hasNext()) { 10950 final PreferredActivity pa = it.next(); 10951 if (packageName == null 10952 || (pa.mPref.mComponent.getPackageName().equals(packageName) 10953 && pa.mPref.mAlways)) { 10954 if (outFilters != null) { 10955 outFilters.add(new IntentFilter(pa)); 10956 } 10957 if (outActivities != null) { 10958 outActivities.add(pa.mPref.mComponent); 10959 } 10960 } 10961 } 10962 } 10963 } 10964 10965 return num; 10966 } 10967 10968 @Override 10969 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 10970 int userId) { 10971 int callingUid = Binder.getCallingUid(); 10972 if (callingUid != Process.SYSTEM_UID) { 10973 throw new SecurityException( 10974 "addPersistentPreferredActivity can only be run by the system"); 10975 } 10976 if (filter.countActions() == 0) { 10977 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 10978 return; 10979 } 10980 synchronized (mPackages) { 10981 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 10982 " :"); 10983 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10984 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 10985 new PersistentPreferredActivity(filter, activity)); 10986 mSettings.writePackageRestrictionsLPr(userId); 10987 } 10988 } 10989 10990 @Override 10991 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 10992 int callingUid = Binder.getCallingUid(); 10993 if (callingUid != Process.SYSTEM_UID) { 10994 throw new SecurityException( 10995 "clearPackagePersistentPreferredActivities can only be run by the system"); 10996 } 10997 ArrayList<PersistentPreferredActivity> removed = null; 10998 boolean changed = false; 10999 synchronized (mPackages) { 11000 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11001 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11002 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11003 .valueAt(i); 11004 if (userId != thisUserId) { 11005 continue; 11006 } 11007 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11008 while (it.hasNext()) { 11009 PersistentPreferredActivity ppa = it.next(); 11010 // Mark entry for removal only if it matches the package name. 11011 if (ppa.mComponent.getPackageName().equals(packageName)) { 11012 if (removed == null) { 11013 removed = new ArrayList<PersistentPreferredActivity>(); 11014 } 11015 removed.add(ppa); 11016 } 11017 } 11018 if (removed != null) { 11019 for (int j=0; j<removed.size(); j++) { 11020 PersistentPreferredActivity ppa = removed.get(j); 11021 ppir.removeFilter(ppa); 11022 } 11023 changed = true; 11024 } 11025 } 11026 11027 if (changed) { 11028 mSettings.writePackageRestrictionsLPr(userId); 11029 } 11030 } 11031 } 11032 11033 @Override 11034 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11035 Intent intent = new Intent(Intent.ACTION_MAIN); 11036 intent.addCategory(Intent.CATEGORY_HOME); 11037 11038 final int callingUserId = UserHandle.getCallingUserId(); 11039 List<ResolveInfo> list = queryIntentActivities(intent, null, 11040 PackageManager.GET_META_DATA, callingUserId); 11041 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11042 true, false, false, callingUserId); 11043 11044 allHomeCandidates.clear(); 11045 if (list != null) { 11046 for (ResolveInfo ri : list) { 11047 allHomeCandidates.add(ri); 11048 } 11049 } 11050 return (preferred == null || preferred.activityInfo == null) 11051 ? null 11052 : new ComponentName(preferred.activityInfo.packageName, 11053 preferred.activityInfo.name); 11054 } 11055 11056 @Override 11057 public void setApplicationEnabledSetting(String appPackageName, 11058 int newState, int flags, int userId, String callingPackage) { 11059 if (!sUserManager.exists(userId)) return; 11060 if (callingPackage == null) { 11061 callingPackage = Integer.toString(Binder.getCallingUid()); 11062 } 11063 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11064 } 11065 11066 @Override 11067 public void setComponentEnabledSetting(ComponentName componentName, 11068 int newState, int flags, int userId) { 11069 if (!sUserManager.exists(userId)) return; 11070 setEnabledSetting(componentName.getPackageName(), 11071 componentName.getClassName(), newState, flags, userId, null); 11072 } 11073 11074 private void setEnabledSetting(final String packageName, String className, int newState, 11075 final int flags, int userId, String callingPackage) { 11076 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11077 || newState == COMPONENT_ENABLED_STATE_ENABLED 11078 || newState == COMPONENT_ENABLED_STATE_DISABLED 11079 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11080 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11081 throw new IllegalArgumentException("Invalid new component state: " 11082 + newState); 11083 } 11084 PackageSetting pkgSetting; 11085 final int uid = Binder.getCallingUid(); 11086 final int permission = mContext.checkCallingOrSelfPermission( 11087 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11088 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11089 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11090 boolean sendNow = false; 11091 boolean isApp = (className == null); 11092 String componentName = isApp ? packageName : className; 11093 int packageUid = -1; 11094 ArrayList<String> components; 11095 11096 // writer 11097 synchronized (mPackages) { 11098 pkgSetting = mSettings.mPackages.get(packageName); 11099 if (pkgSetting == null) { 11100 if (className == null) { 11101 throw new IllegalArgumentException( 11102 "Unknown package: " + packageName); 11103 } 11104 throw new IllegalArgumentException( 11105 "Unknown component: " + packageName 11106 + "/" + className); 11107 } 11108 // Allow root and verify that userId is not being specified by a different user 11109 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11110 throw new SecurityException( 11111 "Permission Denial: attempt to change component state from pid=" 11112 + Binder.getCallingPid() 11113 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11114 } 11115 if (className == null) { 11116 // We're dealing with an application/package level state change 11117 if (pkgSetting.getEnabled(userId) == newState) { 11118 // Nothing to do 11119 return; 11120 } 11121 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11122 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11123 // Don't care about who enables an app. 11124 callingPackage = null; 11125 } 11126 pkgSetting.setEnabled(newState, userId, callingPackage); 11127 // pkgSetting.pkg.mSetEnabled = newState; 11128 } else { 11129 // We're dealing with a component level state change 11130 // First, verify that this is a valid class name. 11131 PackageParser.Package pkg = pkgSetting.pkg; 11132 if (pkg == null || !pkg.hasComponentClassName(className)) { 11133 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11134 throw new IllegalArgumentException("Component class " + className 11135 + " does not exist in " + packageName); 11136 } else { 11137 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11138 + className + " does not exist in " + packageName); 11139 } 11140 } 11141 switch (newState) { 11142 case COMPONENT_ENABLED_STATE_ENABLED: 11143 if (!pkgSetting.enableComponentLPw(className, userId)) { 11144 return; 11145 } 11146 break; 11147 case COMPONENT_ENABLED_STATE_DISABLED: 11148 if (!pkgSetting.disableComponentLPw(className, userId)) { 11149 return; 11150 } 11151 break; 11152 case COMPONENT_ENABLED_STATE_DEFAULT: 11153 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11154 return; 11155 } 11156 break; 11157 default: 11158 Slog.e(TAG, "Invalid new component state: " + newState); 11159 return; 11160 } 11161 } 11162 mSettings.writePackageRestrictionsLPr(userId); 11163 components = mPendingBroadcasts.get(userId, packageName); 11164 final boolean newPackage = components == null; 11165 if (newPackage) { 11166 components = new ArrayList<String>(); 11167 } 11168 if (!components.contains(componentName)) { 11169 components.add(componentName); 11170 } 11171 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11172 sendNow = true; 11173 // Purge entry from pending broadcast list if another one exists already 11174 // since we are sending one right away. 11175 mPendingBroadcasts.remove(userId, packageName); 11176 } else { 11177 if (newPackage) { 11178 mPendingBroadcasts.put(userId, packageName, components); 11179 } 11180 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11181 // Schedule a message 11182 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11183 } 11184 } 11185 } 11186 11187 long callingId = Binder.clearCallingIdentity(); 11188 try { 11189 if (sendNow) { 11190 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11191 sendPackageChangedBroadcast(packageName, 11192 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11193 } 11194 } finally { 11195 Binder.restoreCallingIdentity(callingId); 11196 } 11197 } 11198 11199 private void sendPackageChangedBroadcast(String packageName, 11200 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11201 if (DEBUG_INSTALL) 11202 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11203 + componentNames); 11204 Bundle extras = new Bundle(4); 11205 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11206 String nameList[] = new String[componentNames.size()]; 11207 componentNames.toArray(nameList); 11208 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11209 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11210 extras.putInt(Intent.EXTRA_UID, packageUid); 11211 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11212 new int[] {UserHandle.getUserId(packageUid)}); 11213 } 11214 11215 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11216 if (!sUserManager.exists(userId)) return; 11217 final int uid = Binder.getCallingUid(); 11218 final int permission = mContext.checkCallingOrSelfPermission( 11219 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11220 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11221 enforceCrossUserPermission(uid, userId, true, "stop package"); 11222 // writer 11223 synchronized (mPackages) { 11224 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11225 uid, userId)) { 11226 scheduleWritePackageRestrictionsLocked(userId); 11227 } 11228 } 11229 } 11230 11231 public String getInstallerPackageName(String packageName) { 11232 // reader 11233 synchronized (mPackages) { 11234 return mSettings.getInstallerPackageNameLPr(packageName); 11235 } 11236 } 11237 11238 @Override 11239 public int getApplicationEnabledSetting(String packageName, int userId) { 11240 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11241 int uid = Binder.getCallingUid(); 11242 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11243 // reader 11244 synchronized (mPackages) { 11245 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11246 } 11247 } 11248 11249 @Override 11250 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11251 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11252 int uid = Binder.getCallingUid(); 11253 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11254 // reader 11255 synchronized (mPackages) { 11256 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11257 } 11258 } 11259 11260 public void enterSafeMode() { 11261 enforceSystemOrRoot("Only the system can request entering safe mode"); 11262 11263 if (!mSystemReady) { 11264 mSafeMode = true; 11265 } 11266 } 11267 11268 public void systemReady() { 11269 mSystemReady = true; 11270 11271 // Read the compatibilty setting when the system is ready. 11272 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11273 mContext.getContentResolver(), 11274 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11275 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11276 if (DEBUG_SETTINGS) { 11277 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11278 } 11279 11280 synchronized (mPackages) { 11281 // Verify that all of the preferred activity components actually 11282 // exist. It is possible for applications to be updated and at 11283 // that point remove a previously declared activity component that 11284 // had been set as a preferred activity. We try to clean this up 11285 // the next time we encounter that preferred activity, but it is 11286 // possible for the user flow to never be able to return to that 11287 // situation so here we do a sanity check to make sure we haven't 11288 // left any junk around. 11289 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11290 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11291 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11292 removed.clear(); 11293 for (PreferredActivity pa : pir.filterSet()) { 11294 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11295 removed.add(pa); 11296 } 11297 } 11298 if (removed.size() > 0) { 11299 for (int j=0; j<removed.size(); j++) { 11300 PreferredActivity pa = removed.get(i); 11301 Slog.w(TAG, "Removing dangling preferred activity: " 11302 + pa.mPref.mComponent); 11303 pir.removeFilter(pa); 11304 } 11305 mSettings.writePackageRestrictionsLPr( 11306 mSettings.mPreferredActivities.keyAt(i)); 11307 } 11308 } 11309 } 11310 sUserManager.systemReady(); 11311 } 11312 11313 public boolean isSafeMode() { 11314 return mSafeMode; 11315 } 11316 11317 public boolean hasSystemUidErrors() { 11318 return mHasSystemUidErrors; 11319 } 11320 11321 static String arrayToString(int[] array) { 11322 StringBuffer buf = new StringBuffer(128); 11323 buf.append('['); 11324 if (array != null) { 11325 for (int i=0; i<array.length; i++) { 11326 if (i > 0) buf.append(", "); 11327 buf.append(array[i]); 11328 } 11329 } 11330 buf.append(']'); 11331 return buf.toString(); 11332 } 11333 11334 static class DumpState { 11335 public static final int DUMP_LIBS = 1 << 0; 11336 11337 public static final int DUMP_FEATURES = 1 << 1; 11338 11339 public static final int DUMP_RESOLVERS = 1 << 2; 11340 11341 public static final int DUMP_PERMISSIONS = 1 << 3; 11342 11343 public static final int DUMP_PACKAGES = 1 << 4; 11344 11345 public static final int DUMP_SHARED_USERS = 1 << 5; 11346 11347 public static final int DUMP_MESSAGES = 1 << 6; 11348 11349 public static final int DUMP_PROVIDERS = 1 << 7; 11350 11351 public static final int DUMP_VERIFIERS = 1 << 8; 11352 11353 public static final int DUMP_PREFERRED = 1 << 9; 11354 11355 public static final int DUMP_PREFERRED_XML = 1 << 10; 11356 11357 public static final int DUMP_KEYSETS = 1 << 11; 11358 11359 public static final int DUMP_VERSION = 1 << 12; 11360 11361 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11362 11363 private int mTypes; 11364 11365 private int mOptions; 11366 11367 private boolean mTitlePrinted; 11368 11369 private SharedUserSetting mSharedUser; 11370 11371 public boolean isDumping(int type) { 11372 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11373 return true; 11374 } 11375 11376 return (mTypes & type) != 0; 11377 } 11378 11379 public void setDump(int type) { 11380 mTypes |= type; 11381 } 11382 11383 public boolean isOptionEnabled(int option) { 11384 return (mOptions & option) != 0; 11385 } 11386 11387 public void setOptionEnabled(int option) { 11388 mOptions |= option; 11389 } 11390 11391 public boolean onTitlePrinted() { 11392 final boolean printed = mTitlePrinted; 11393 mTitlePrinted = true; 11394 return printed; 11395 } 11396 11397 public boolean getTitlePrinted() { 11398 return mTitlePrinted; 11399 } 11400 11401 public void setTitlePrinted(boolean enabled) { 11402 mTitlePrinted = enabled; 11403 } 11404 11405 public SharedUserSetting getSharedUser() { 11406 return mSharedUser; 11407 } 11408 11409 public void setSharedUser(SharedUserSetting user) { 11410 mSharedUser = user; 11411 } 11412 } 11413 11414 @Override 11415 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 11416 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 11417 != PackageManager.PERMISSION_GRANTED) { 11418 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 11419 + Binder.getCallingPid() 11420 + ", uid=" + Binder.getCallingUid() 11421 + " without permission " 11422 + android.Manifest.permission.DUMP); 11423 return; 11424 } 11425 11426 DumpState dumpState = new DumpState(); 11427 boolean fullPreferred = false; 11428 boolean checkin = false; 11429 11430 String packageName = null; 11431 11432 int opti = 0; 11433 while (opti < args.length) { 11434 String opt = args[opti]; 11435 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 11436 break; 11437 } 11438 opti++; 11439 if ("-a".equals(opt)) { 11440 // Right now we only know how to print all. 11441 } else if ("-h".equals(opt)) { 11442 pw.println("Package manager dump options:"); 11443 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 11444 pw.println(" --checkin: dump for a checkin"); 11445 pw.println(" -f: print details of intent filters"); 11446 pw.println(" -h: print this help"); 11447 pw.println(" cmd may be one of:"); 11448 pw.println(" l[ibraries]: list known shared libraries"); 11449 pw.println(" f[ibraries]: list device features"); 11450 pw.println(" r[esolvers]: dump intent resolvers"); 11451 pw.println(" perm[issions]: dump permissions"); 11452 pw.println(" pref[erred]: print preferred package settings"); 11453 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 11454 pw.println(" prov[iders]: dump content providers"); 11455 pw.println(" p[ackages]: dump installed packages"); 11456 pw.println(" s[hared-users]: dump shared user IDs"); 11457 pw.println(" m[essages]: print collected runtime messages"); 11458 pw.println(" v[erifiers]: print package verifier info"); 11459 pw.println(" version: print database version info"); 11460 pw.println(" <package.name>: info about given package"); 11461 pw.println(" k[eysets]: print known keysets"); 11462 return; 11463 } else if ("--checkin".equals(opt)) { 11464 checkin = true; 11465 } else if ("-f".equals(opt)) { 11466 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11467 } else { 11468 pw.println("Unknown argument: " + opt + "; use -h for help"); 11469 } 11470 } 11471 11472 // Is the caller requesting to dump a particular piece of data? 11473 if (opti < args.length) { 11474 String cmd = args[opti]; 11475 opti++; 11476 // Is this a package name? 11477 if ("android".equals(cmd) || cmd.contains(".")) { 11478 packageName = cmd; 11479 // When dumping a single package, we always dump all of its 11480 // filter information since the amount of data will be reasonable. 11481 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11482 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 11483 dumpState.setDump(DumpState.DUMP_LIBS); 11484 } else if ("f".equals(cmd) || "features".equals(cmd)) { 11485 dumpState.setDump(DumpState.DUMP_FEATURES); 11486 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 11487 dumpState.setDump(DumpState.DUMP_RESOLVERS); 11488 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 11489 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 11490 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 11491 dumpState.setDump(DumpState.DUMP_PREFERRED); 11492 } else if ("preferred-xml".equals(cmd)) { 11493 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 11494 if (opti < args.length && "--full".equals(args[opti])) { 11495 fullPreferred = true; 11496 opti++; 11497 } 11498 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 11499 dumpState.setDump(DumpState.DUMP_PACKAGES); 11500 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 11501 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 11502 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 11503 dumpState.setDump(DumpState.DUMP_PROVIDERS); 11504 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 11505 dumpState.setDump(DumpState.DUMP_MESSAGES); 11506 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 11507 dumpState.setDump(DumpState.DUMP_VERIFIERS); 11508 } else if ("version".equals(cmd)) { 11509 dumpState.setDump(DumpState.DUMP_VERSION); 11510 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 11511 dumpState.setDump(DumpState.DUMP_KEYSETS); 11512 } 11513 } 11514 11515 if (checkin) { 11516 pw.println("vers,1"); 11517 } 11518 11519 // reader 11520 synchronized (mPackages) { 11521 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 11522 if (!checkin) { 11523 if (dumpState.onTitlePrinted()) 11524 pw.println(); 11525 pw.println("Database versions:"); 11526 pw.print(" SDK Version:"); 11527 pw.print(" internal="); 11528 pw.print(mSettings.mInternalSdkPlatform); 11529 pw.print(" external="); 11530 pw.println(mSettings.mExternalSdkPlatform); 11531 pw.print(" DB Version:"); 11532 pw.print(" internal="); 11533 pw.print(mSettings.mInternalDatabaseVersion); 11534 pw.print(" external="); 11535 pw.println(mSettings.mExternalDatabaseVersion); 11536 } 11537 } 11538 11539 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 11540 if (!checkin) { 11541 if (dumpState.onTitlePrinted()) 11542 pw.println(); 11543 pw.println("Verifiers:"); 11544 pw.print(" Required: "); 11545 pw.print(mRequiredVerifierPackage); 11546 pw.print(" (uid="); 11547 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 11548 pw.println(")"); 11549 } else if (mRequiredVerifierPackage != null) { 11550 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 11551 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 11552 } 11553 } 11554 11555 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 11556 boolean printedHeader = false; 11557 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 11558 while (it.hasNext()) { 11559 String name = it.next(); 11560 SharedLibraryEntry ent = mSharedLibraries.get(name); 11561 if (!checkin) { 11562 if (!printedHeader) { 11563 if (dumpState.onTitlePrinted()) 11564 pw.println(); 11565 pw.println("Libraries:"); 11566 printedHeader = true; 11567 } 11568 pw.print(" "); 11569 } else { 11570 pw.print("lib,"); 11571 } 11572 pw.print(name); 11573 if (!checkin) { 11574 pw.print(" -> "); 11575 } 11576 if (ent.path != null) { 11577 if (!checkin) { 11578 pw.print("(jar) "); 11579 pw.print(ent.path); 11580 } else { 11581 pw.print(",jar,"); 11582 pw.print(ent.path); 11583 } 11584 } else { 11585 if (!checkin) { 11586 pw.print("(apk) "); 11587 pw.print(ent.apk); 11588 } else { 11589 pw.print(",apk,"); 11590 pw.print(ent.apk); 11591 } 11592 } 11593 pw.println(); 11594 } 11595 } 11596 11597 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 11598 if (dumpState.onTitlePrinted()) 11599 pw.println(); 11600 if (!checkin) { 11601 pw.println("Features:"); 11602 } 11603 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 11604 while (it.hasNext()) { 11605 String name = it.next(); 11606 if (!checkin) { 11607 pw.print(" "); 11608 } else { 11609 pw.print("feat,"); 11610 } 11611 pw.println(name); 11612 } 11613 } 11614 11615 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 11616 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 11617 : "Activity Resolver Table:", " ", packageName, 11618 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11619 dumpState.setTitlePrinted(true); 11620 } 11621 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 11622 : "Receiver Resolver Table:", " ", packageName, 11623 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11624 dumpState.setTitlePrinted(true); 11625 } 11626 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 11627 : "Service Resolver Table:", " ", packageName, 11628 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11629 dumpState.setTitlePrinted(true); 11630 } 11631 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 11632 : "Provider Resolver Table:", " ", packageName, 11633 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11634 dumpState.setTitlePrinted(true); 11635 } 11636 } 11637 11638 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 11639 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11640 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11641 int user = mSettings.mPreferredActivities.keyAt(i); 11642 if (pir.dump(pw, 11643 dumpState.getTitlePrinted() 11644 ? "\nPreferred Activities User " + user + ":" 11645 : "Preferred Activities User " + user + ":", " ", 11646 packageName, true)) { 11647 dumpState.setTitlePrinted(true); 11648 } 11649 } 11650 } 11651 11652 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 11653 pw.flush(); 11654 FileOutputStream fout = new FileOutputStream(fd); 11655 BufferedOutputStream str = new BufferedOutputStream(fout); 11656 XmlSerializer serializer = new FastXmlSerializer(); 11657 try { 11658 serializer.setOutput(str, "utf-8"); 11659 serializer.startDocument(null, true); 11660 serializer.setFeature( 11661 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 11662 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 11663 serializer.endDocument(); 11664 serializer.flush(); 11665 } catch (IllegalArgumentException e) { 11666 pw.println("Failed writing: " + e); 11667 } catch (IllegalStateException e) { 11668 pw.println("Failed writing: " + e); 11669 } catch (IOException e) { 11670 pw.println("Failed writing: " + e); 11671 } 11672 } 11673 11674 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 11675 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 11676 } 11677 11678 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 11679 boolean printedSomething = false; 11680 for (PackageParser.Provider p : mProviders.mProviders.values()) { 11681 if (packageName != null && !packageName.equals(p.info.packageName)) { 11682 continue; 11683 } 11684 if (!printedSomething) { 11685 if (dumpState.onTitlePrinted()) 11686 pw.println(); 11687 pw.println("Registered ContentProviders:"); 11688 printedSomething = true; 11689 } 11690 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 11691 pw.print(" "); pw.println(p.toString()); 11692 } 11693 printedSomething = false; 11694 for (Map.Entry<String, PackageParser.Provider> entry : 11695 mProvidersByAuthority.entrySet()) { 11696 PackageParser.Provider p = entry.getValue(); 11697 if (packageName != null && !packageName.equals(p.info.packageName)) { 11698 continue; 11699 } 11700 if (!printedSomething) { 11701 if (dumpState.onTitlePrinted()) 11702 pw.println(); 11703 pw.println("ContentProvider Authorities:"); 11704 printedSomething = true; 11705 } 11706 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 11707 pw.print(" "); pw.println(p.toString()); 11708 if (p.info != null && p.info.applicationInfo != null) { 11709 final String appInfo = p.info.applicationInfo.toString(); 11710 pw.print(" applicationInfo="); pw.println(appInfo); 11711 } 11712 } 11713 } 11714 11715 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 11716 mSettings.mKeySetManager.dump(pw, packageName, dumpState); 11717 } 11718 11719 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 11720 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 11721 } 11722 11723 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 11724 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 11725 } 11726 11727 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 11728 if (dumpState.onTitlePrinted()) 11729 pw.println(); 11730 mSettings.dumpReadMessagesLPr(pw, dumpState); 11731 11732 pw.println(); 11733 pw.println("Package warning messages:"); 11734 final File fname = getSettingsProblemFile(); 11735 FileInputStream in = null; 11736 try { 11737 in = new FileInputStream(fname); 11738 final int avail = in.available(); 11739 final byte[] data = new byte[avail]; 11740 in.read(data); 11741 pw.print(new String(data)); 11742 } catch (FileNotFoundException e) { 11743 } catch (IOException e) { 11744 } finally { 11745 if (in != null) { 11746 try { 11747 in.close(); 11748 } catch (IOException e) { 11749 } 11750 } 11751 } 11752 } 11753 } 11754 } 11755 11756 // ------- apps on sdcard specific code ------- 11757 static final boolean DEBUG_SD_INSTALL = false; 11758 11759 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 11760 11761 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 11762 11763 private boolean mMediaMounted = false; 11764 11765 private String getEncryptKey() { 11766 try { 11767 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 11768 SD_ENCRYPTION_KEYSTORE_NAME); 11769 if (sdEncKey == null) { 11770 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 11771 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 11772 if (sdEncKey == null) { 11773 Slog.e(TAG, "Failed to create encryption keys"); 11774 return null; 11775 } 11776 } 11777 return sdEncKey; 11778 } catch (NoSuchAlgorithmException nsae) { 11779 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 11780 return null; 11781 } catch (IOException ioe) { 11782 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 11783 return null; 11784 } 11785 11786 } 11787 11788 /* package */static String getTempContainerId() { 11789 int tmpIdx = 1; 11790 String list[] = PackageHelper.getSecureContainerList(); 11791 if (list != null) { 11792 for (final String name : list) { 11793 // Ignore null and non-temporary container entries 11794 if (name == null || !name.startsWith(mTempContainerPrefix)) { 11795 continue; 11796 } 11797 11798 String subStr = name.substring(mTempContainerPrefix.length()); 11799 try { 11800 int cid = Integer.parseInt(subStr); 11801 if (cid >= tmpIdx) { 11802 tmpIdx = cid + 1; 11803 } 11804 } catch (NumberFormatException e) { 11805 } 11806 } 11807 } 11808 return mTempContainerPrefix + tmpIdx; 11809 } 11810 11811 /* 11812 * Update media status on PackageManager. 11813 */ 11814 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 11815 int callingUid = Binder.getCallingUid(); 11816 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 11817 throw new SecurityException("Media status can only be updated by the system"); 11818 } 11819 // reader; this apparently protects mMediaMounted, but should probably 11820 // be a different lock in that case. 11821 synchronized (mPackages) { 11822 Log.i(TAG, "Updating external media status from " 11823 + (mMediaMounted ? "mounted" : "unmounted") + " to " 11824 + (mediaStatus ? "mounted" : "unmounted")); 11825 if (DEBUG_SD_INSTALL) 11826 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 11827 + ", mMediaMounted=" + mMediaMounted); 11828 if (mediaStatus == mMediaMounted) { 11829 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 11830 : 0, -1); 11831 mHandler.sendMessage(msg); 11832 return; 11833 } 11834 mMediaMounted = mediaStatus; 11835 } 11836 // Queue up an async operation since the package installation may take a 11837 // little while. 11838 mHandler.post(new Runnable() { 11839 public void run() { 11840 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 11841 } 11842 }); 11843 } 11844 11845 /** 11846 * Called by MountService when the initial ASECs to scan are available. 11847 * Should block until all the ASEC containers are finished being scanned. 11848 */ 11849 public void scanAvailableAsecs() { 11850 updateExternalMediaStatusInner(true, false, false); 11851 if (mShouldRestoreconData) { 11852 SELinuxMMAC.setRestoreconDone(); 11853 mShouldRestoreconData = false; 11854 } 11855 } 11856 11857 /* 11858 * Collect information of applications on external media, map them against 11859 * existing containers and update information based on current mount status. 11860 * Please note that we always have to report status if reportStatus has been 11861 * set to true especially when unloading packages. 11862 */ 11863 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 11864 boolean externalStorage) { 11865 // Collection of uids 11866 int uidArr[] = null; 11867 // Collection of stale containers 11868 HashSet<String> removeCids = new HashSet<String>(); 11869 // Collection of packages on external media with valid containers. 11870 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 11871 // Get list of secure containers. 11872 final String list[] = PackageHelper.getSecureContainerList(); 11873 if (list == null || list.length == 0) { 11874 Log.i(TAG, "No secure containers on sdcard"); 11875 } else { 11876 // Process list of secure containers and categorize them 11877 // as active or stale based on their package internal state. 11878 int uidList[] = new int[list.length]; 11879 int num = 0; 11880 // reader 11881 synchronized (mPackages) { 11882 for (String cid : list) { 11883 if (DEBUG_SD_INSTALL) 11884 Log.i(TAG, "Processing container " + cid); 11885 String pkgName = getAsecPackageName(cid); 11886 if (pkgName == null) { 11887 if (DEBUG_SD_INSTALL) 11888 Log.i(TAG, "Container : " + cid + " stale"); 11889 removeCids.add(cid); 11890 continue; 11891 } 11892 if (DEBUG_SD_INSTALL) 11893 Log.i(TAG, "Looking for pkg : " + pkgName); 11894 11895 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11896 if (ps == null) { 11897 Log.i(TAG, "Deleting container with no matching settings " + cid); 11898 removeCids.add(cid); 11899 continue; 11900 } 11901 11902 /* 11903 * Skip packages that are not external if we're unmounting 11904 * external storage. 11905 */ 11906 if (externalStorage && !isMounted && !isExternal(ps)) { 11907 continue; 11908 } 11909 11910 final AsecInstallArgs args = new AsecInstallArgs(cid, 11911 getAppInstructionSetFromSettings(ps), 11912 isForwardLocked(ps)); 11913 // The package status is changed only if the code path 11914 // matches between settings and the container id. 11915 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 11916 if (DEBUG_SD_INSTALL) { 11917 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 11918 + " at code path: " + ps.codePathString); 11919 } 11920 11921 // We do have a valid package installed on sdcard 11922 processCids.put(args, ps.codePathString); 11923 final int uid = ps.appId; 11924 if (uid != -1) { 11925 uidList[num++] = uid; 11926 } 11927 } else { 11928 Log.i(TAG, "Deleting stale container for " + cid); 11929 removeCids.add(cid); 11930 } 11931 } 11932 } 11933 11934 if (num > 0) { 11935 // Sort uid list 11936 Arrays.sort(uidList, 0, num); 11937 // Throw away duplicates 11938 uidArr = new int[num]; 11939 uidArr[0] = uidList[0]; 11940 int di = 0; 11941 for (int i = 1; i < num; i++) { 11942 if (uidList[i - 1] != uidList[i]) { 11943 uidArr[di++] = uidList[i]; 11944 } 11945 } 11946 } 11947 } 11948 // Process packages with valid entries. 11949 if (isMounted) { 11950 if (DEBUG_SD_INSTALL) 11951 Log.i(TAG, "Loading packages"); 11952 loadMediaPackages(processCids, uidArr, removeCids); 11953 startCleaningPackages(); 11954 } else { 11955 if (DEBUG_SD_INSTALL) 11956 Log.i(TAG, "Unloading packages"); 11957 unloadMediaPackages(processCids, uidArr, reportStatus); 11958 } 11959 } 11960 11961 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 11962 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 11963 int size = pkgList.size(); 11964 if (size > 0) { 11965 // Send broadcasts here 11966 Bundle extras = new Bundle(); 11967 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 11968 .toArray(new String[size])); 11969 if (uidArr != null) { 11970 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 11971 } 11972 if (replacing) { 11973 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 11974 } 11975 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 11976 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 11977 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 11978 } 11979 } 11980 11981 /* 11982 * Look at potentially valid container ids from processCids If package 11983 * information doesn't match the one on record or package scanning fails, 11984 * the cid is added to list of removeCids. We currently don't delete stale 11985 * containers. 11986 */ 11987 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 11988 HashSet<String> removeCids) { 11989 ArrayList<String> pkgList = new ArrayList<String>(); 11990 Set<AsecInstallArgs> keys = processCids.keySet(); 11991 boolean doGc = false; 11992 for (AsecInstallArgs args : keys) { 11993 String codePath = processCids.get(args); 11994 if (DEBUG_SD_INSTALL) 11995 Log.i(TAG, "Loading container : " + args.cid); 11996 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11997 try { 11998 // Make sure there are no container errors first. 11999 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12000 Slog.e(TAG, "Failed to mount cid : " + args.cid 12001 + " when installing from sdcard"); 12002 continue; 12003 } 12004 // Check code path here. 12005 if (codePath == null || !codePath.equals(args.getCodePath())) { 12006 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12007 + " does not match one in settings " + codePath); 12008 continue; 12009 } 12010 // Parse package 12011 int parseFlags = mDefParseFlags; 12012 if (args.isExternal()) { 12013 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12014 } 12015 if (args.isFwdLocked()) { 12016 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12017 } 12018 12019 doGc = true; 12020 synchronized (mInstallLock) { 12021 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 12022 0, 0, null); 12023 // Scan the package 12024 if (pkg != null) { 12025 /* 12026 * TODO why is the lock being held? doPostInstall is 12027 * called in other places without the lock. This needs 12028 * to be straightened out. 12029 */ 12030 // writer 12031 synchronized (mPackages) { 12032 retCode = PackageManager.INSTALL_SUCCEEDED; 12033 pkgList.add(pkg.packageName); 12034 // Post process args 12035 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12036 pkg.applicationInfo.uid); 12037 } 12038 } else { 12039 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12040 } 12041 } 12042 12043 } finally { 12044 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12045 // Don't destroy container here. Wait till gc clears things 12046 // up. 12047 removeCids.add(args.cid); 12048 } 12049 } 12050 } 12051 // writer 12052 synchronized (mPackages) { 12053 // If the platform SDK has changed since the last time we booted, 12054 // we need to re-grant app permission to catch any new ones that 12055 // appear. This is really a hack, and means that apps can in some 12056 // cases get permissions that the user didn't initially explicitly 12057 // allow... it would be nice to have some better way to handle 12058 // this situation. 12059 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12060 if (regrantPermissions) 12061 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12062 + mSdkVersion + "; regranting permissions for external storage"); 12063 mSettings.mExternalSdkPlatform = mSdkVersion; 12064 12065 // Make sure group IDs have been assigned, and any permission 12066 // changes in other apps are accounted for 12067 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12068 | (regrantPermissions 12069 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12070 : 0)); 12071 12072 mSettings.updateExternalDatabaseVersion(); 12073 12074 // can downgrade to reader 12075 // Persist settings 12076 mSettings.writeLPr(); 12077 } 12078 // Send a broadcast to let everyone know we are done processing 12079 if (pkgList.size() > 0) { 12080 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12081 } 12082 // Force gc to avoid any stale parser references that we might have. 12083 if (doGc) { 12084 Runtime.getRuntime().gc(); 12085 } 12086 // List stale containers and destroy stale temporary containers. 12087 if (removeCids != null) { 12088 for (String cid : removeCids) { 12089 if (cid.startsWith(mTempContainerPrefix)) { 12090 Log.i(TAG, "Destroying stale temporary container " + cid); 12091 PackageHelper.destroySdDir(cid); 12092 } else { 12093 Log.w(TAG, "Container " + cid + " is stale"); 12094 } 12095 } 12096 } 12097 } 12098 12099 /* 12100 * Utility method to unload a list of specified containers 12101 */ 12102 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12103 // Just unmount all valid containers. 12104 for (AsecInstallArgs arg : cidArgs) { 12105 synchronized (mInstallLock) { 12106 arg.doPostDeleteLI(false); 12107 } 12108 } 12109 } 12110 12111 /* 12112 * Unload packages mounted on external media. This involves deleting package 12113 * data from internal structures, sending broadcasts about diabled packages, 12114 * gc'ing to free up references, unmounting all secure containers 12115 * corresponding to packages on external media, and posting a 12116 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12117 * that we always have to post this message if status has been requested no 12118 * matter what. 12119 */ 12120 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12121 final boolean reportStatus) { 12122 if (DEBUG_SD_INSTALL) 12123 Log.i(TAG, "unloading media packages"); 12124 ArrayList<String> pkgList = new ArrayList<String>(); 12125 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12126 final Set<AsecInstallArgs> keys = processCids.keySet(); 12127 for (AsecInstallArgs args : keys) { 12128 String pkgName = args.getPackageName(); 12129 if (DEBUG_SD_INSTALL) 12130 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12131 // Delete package internally 12132 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12133 synchronized (mInstallLock) { 12134 boolean res = deletePackageLI(pkgName, null, false, null, null, 12135 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12136 if (res) { 12137 pkgList.add(pkgName); 12138 } else { 12139 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12140 failedList.add(args); 12141 } 12142 } 12143 } 12144 12145 // reader 12146 synchronized (mPackages) { 12147 // We didn't update the settings after removing each package; 12148 // write them now for all packages. 12149 mSettings.writeLPr(); 12150 } 12151 12152 // We have to absolutely send UPDATED_MEDIA_STATUS only 12153 // after confirming that all the receivers processed the ordered 12154 // broadcast when packages get disabled, force a gc to clean things up. 12155 // and unload all the containers. 12156 if (pkgList.size() > 0) { 12157 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12158 new IIntentReceiver.Stub() { 12159 public void performReceive(Intent intent, int resultCode, String data, 12160 Bundle extras, boolean ordered, boolean sticky, 12161 int sendingUser) throws RemoteException { 12162 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12163 reportStatus ? 1 : 0, 1, keys); 12164 mHandler.sendMessage(msg); 12165 } 12166 }); 12167 } else { 12168 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12169 keys); 12170 mHandler.sendMessage(msg); 12171 } 12172 } 12173 12174 /** Binder call */ 12175 @Override 12176 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12177 final int flags) { 12178 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12179 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12180 int returnCode = PackageManager.MOVE_SUCCEEDED; 12181 int currFlags = 0; 12182 int newFlags = 0; 12183 // reader 12184 synchronized (mPackages) { 12185 PackageParser.Package pkg = mPackages.get(packageName); 12186 if (pkg == null) { 12187 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12188 } else { 12189 // Disable moving fwd locked apps and system packages 12190 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12191 Slog.w(TAG, "Cannot move system application"); 12192 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12193 } else if (pkg.mOperationPending) { 12194 Slog.w(TAG, "Attempt to move package which has pending operations"); 12195 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12196 } else { 12197 // Find install location first 12198 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12199 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12200 Slog.w(TAG, "Ambigous flags specified for move location."); 12201 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12202 } else { 12203 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12204 : PackageManager.INSTALL_INTERNAL; 12205 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12206 : PackageManager.INSTALL_INTERNAL; 12207 12208 if (newFlags == currFlags) { 12209 Slog.w(TAG, "No move required. Trying to move to same location"); 12210 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12211 } else { 12212 if (isForwardLocked(pkg)) { 12213 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12214 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12215 } 12216 } 12217 } 12218 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12219 pkg.mOperationPending = true; 12220 } 12221 } 12222 } 12223 12224 /* 12225 * TODO this next block probably shouldn't be inside the lock. We 12226 * can't guarantee these won't change after this is fired off 12227 * anyway. 12228 */ 12229 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12230 processPendingMove(new MoveParams(null, observer, 0, packageName, null, 12231 null, -1, user), 12232 returnCode); 12233 } else { 12234 Message msg = mHandler.obtainMessage(INIT_COPY); 12235 final String instructionSet = getAppInstructionSet(pkg.applicationInfo); 12236 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir, 12237 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir, 12238 instructionSet); 12239 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12240 pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user); 12241 msg.obj = mp; 12242 mHandler.sendMessage(msg); 12243 } 12244 } 12245 } 12246 12247 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12248 // Queue up an async operation since the package deletion may take a 12249 // little while. 12250 mHandler.post(new Runnable() { 12251 public void run() { 12252 // TODO fix this; this does nothing. 12253 mHandler.removeCallbacks(this); 12254 int returnCode = currentStatus; 12255 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12256 int uidArr[] = null; 12257 ArrayList<String> pkgList = null; 12258 synchronized (mPackages) { 12259 PackageParser.Package pkg = mPackages.get(mp.packageName); 12260 if (pkg == null) { 12261 Slog.w(TAG, " Package " + mp.packageName 12262 + " doesn't exist. Aborting move"); 12263 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12264 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 12265 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12266 + mp.srcArgs.getCodePath() + " to " 12267 + pkg.applicationInfo.sourceDir 12268 + " Aborting move and returning error"); 12269 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12270 } else { 12271 uidArr = new int[] { 12272 pkg.applicationInfo.uid 12273 }; 12274 pkgList = new ArrayList<String>(); 12275 pkgList.add(mp.packageName); 12276 } 12277 } 12278 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12279 // Send resources unavailable broadcast 12280 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12281 // Update package code and resource paths 12282 synchronized (mInstallLock) { 12283 synchronized (mPackages) { 12284 PackageParser.Package pkg = mPackages.get(mp.packageName); 12285 // Recheck for package again. 12286 if (pkg == null) { 12287 Slog.w(TAG, " Package " + mp.packageName 12288 + " doesn't exist. Aborting move"); 12289 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12290 } else if (!mp.srcArgs.getCodePath().equals( 12291 pkg.applicationInfo.sourceDir)) { 12292 Slog.w(TAG, "Package " + mp.packageName 12293 + " code path changed from " + mp.srcArgs.getCodePath() 12294 + " to " + pkg.applicationInfo.sourceDir 12295 + " Aborting move and returning error"); 12296 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12297 } else { 12298 final String oldCodePath = pkg.mPath; 12299 final String newCodePath = mp.targetArgs.getCodePath(); 12300 final String newResPath = mp.targetArgs.getResourcePath(); 12301 final String newNativePath = mp.targetArgs 12302 .getNativeLibraryPath(); 12303 12304 final File newNativeDir = new File(newNativePath); 12305 12306 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12307 // NOTE: We do not report any errors from the APK scan and library 12308 // copy at this point. 12309 NativeLibraryHelper.ApkHandle handle = 12310 new NativeLibraryHelper.ApkHandle(newCodePath); 12311 final int abi = NativeLibraryHelper.findSupportedAbi( 12312 handle, Build.SUPPORTED_ABIS); 12313 if (abi >= 0) { 12314 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12315 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12316 } 12317 handle.close(); 12318 } 12319 final int[] users = sUserManager.getUserIds(); 12320 for (int user : users) { 12321 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 12322 newNativePath, user) < 0) { 12323 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12324 } 12325 } 12326 12327 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12328 pkg.mPath = newCodePath; 12329 // Move dex files around 12330 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) { 12331 // Moving of dex files failed. Set 12332 // error code and abort move. 12333 pkg.mPath = pkg.mScanPath; 12334 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12335 } 12336 } 12337 12338 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12339 pkg.mScanPath = newCodePath; 12340 pkg.applicationInfo.sourceDir = newCodePath; 12341 pkg.applicationInfo.publicSourceDir = newResPath; 12342 pkg.applicationInfo.nativeLibraryDir = newNativePath; 12343 PackageSetting ps = (PackageSetting) pkg.mExtras; 12344 ps.codePath = new File(pkg.applicationInfo.sourceDir); 12345 ps.codePathString = ps.codePath.getPath(); 12346 ps.resourcePath = new File( 12347 pkg.applicationInfo.publicSourceDir); 12348 ps.resourcePathString = ps.resourcePath.getPath(); 12349 ps.nativeLibraryPathString = newNativePath; 12350 // Set the application info flag 12351 // correctly. 12352 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 12353 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12354 } else { 12355 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12356 } 12357 ps.setFlags(pkg.applicationInfo.flags); 12358 mAppDirs.remove(oldCodePath); 12359 mAppDirs.put(newCodePath, pkg); 12360 // Persist settings 12361 mSettings.writeLPr(); 12362 } 12363 } 12364 } 12365 } 12366 // Send resources available broadcast 12367 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12368 } 12369 } 12370 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12371 // Clean up failed installation 12372 if (mp.targetArgs != null) { 12373 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 12374 -1); 12375 } 12376 } else { 12377 // Force a gc to clear things up. 12378 Runtime.getRuntime().gc(); 12379 // Delete older code 12380 synchronized (mInstallLock) { 12381 mp.srcArgs.doPostDeleteLI(true); 12382 } 12383 } 12384 12385 // Allow more operations on this file if we didn't fail because 12386 // an operation was already pending for this package. 12387 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 12388 synchronized (mPackages) { 12389 PackageParser.Package pkg = mPackages.get(mp.packageName); 12390 if (pkg != null) { 12391 pkg.mOperationPending = false; 12392 } 12393 } 12394 } 12395 12396 IPackageMoveObserver observer = mp.observer; 12397 if (observer != null) { 12398 try { 12399 observer.packageMoved(mp.packageName, returnCode); 12400 } catch (RemoteException e) { 12401 Log.i(TAG, "Observer no longer exists."); 12402 } 12403 } 12404 } 12405 }); 12406 } 12407 12408 public boolean setInstallLocation(int loc) { 12409 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12410 null); 12411 if (getInstallLocation() == loc) { 12412 return true; 12413 } 12414 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12415 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12416 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12417 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12418 return true; 12419 } 12420 return false; 12421 } 12422 12423 public int getInstallLocation() { 12424 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12425 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12426 PackageHelper.APP_INSTALL_AUTO); 12427 } 12428 12429 /** Called by UserManagerService */ 12430 void cleanUpUserLILPw(int userHandle) { 12431 mDirtyUsers.remove(userHandle); 12432 mSettings.removeUserLPr(userHandle); 12433 mPendingBroadcasts.remove(userHandle); 12434 if (mInstaller != null) { 12435 // Technically, we shouldn't be doing this with the package lock 12436 // held. However, this is very rare, and there is already so much 12437 // other disk I/O going on, that we'll let it slide for now. 12438 mInstaller.removeUserDataDirs(userHandle); 12439 } 12440 } 12441 12442 /** Called by UserManagerService */ 12443 void createNewUserLILPw(int userHandle, File path) { 12444 if (mInstaller != null) { 12445 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 12446 } 12447 } 12448 12449 @Override 12450 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 12451 mContext.enforceCallingOrSelfPermission( 12452 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12453 "Only package verification agents can read the verifier device identity"); 12454 12455 synchronized (mPackages) { 12456 return mSettings.getVerifierDeviceIdentityLPw(); 12457 } 12458 } 12459 12460 @Override 12461 public void setPermissionEnforced(String permission, boolean enforced) { 12462 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 12463 if (READ_EXTERNAL_STORAGE.equals(permission)) { 12464 synchronized (mPackages) { 12465 if (mSettings.mReadExternalStorageEnforced == null 12466 || mSettings.mReadExternalStorageEnforced != enforced) { 12467 mSettings.mReadExternalStorageEnforced = enforced; 12468 mSettings.writeLPr(); 12469 } 12470 } 12471 // kill any non-foreground processes so we restart them and 12472 // grant/revoke the GID. 12473 final IActivityManager am = ActivityManagerNative.getDefault(); 12474 if (am != null) { 12475 final long token = Binder.clearCallingIdentity(); 12476 try { 12477 am.killProcessesBelowForeground("setPermissionEnforcement"); 12478 } catch (RemoteException e) { 12479 } finally { 12480 Binder.restoreCallingIdentity(token); 12481 } 12482 } 12483 } else { 12484 throw new IllegalArgumentException("No selective enforcement for " + permission); 12485 } 12486 } 12487 12488 @Override 12489 @Deprecated 12490 public boolean isPermissionEnforced(String permission) { 12491 return true; 12492 } 12493 12494 @Override 12495 public boolean isStorageLow() { 12496 final long token = Binder.clearCallingIdentity(); 12497 try { 12498 final DeviceStorageMonitorInternal 12499 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12500 if (dsm != null) { 12501 return dsm.isMemoryLow(); 12502 } else { 12503 return false; 12504 } 12505 } finally { 12506 Binder.restoreCallingIdentity(token); 12507 } 12508 } 12509} 12510