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