PackageManagerService.java revision 010cfd458121034075c7439020ffef4eedbcc0fc
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.system.OsConstants.S_IRWXU; 27import static android.system.OsConstants.S_IRGRP; 28import static android.system.OsConstants.S_IXGRP; 29import static android.system.OsConstants.S_IROTH; 30import static android.system.OsConstants.S_IXOTH; 31import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 32import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 33import static com.android.internal.util.ArrayUtils.appendInt; 34import static com.android.internal.util.ArrayUtils.removeInt; 35 36import android.content.pm.PackageParser.*; 37import com.android.internal.app.IMediaContainerService; 38import com.android.internal.app.ResolverActivity; 39import com.android.internal.content.NativeLibraryHelper; 40import com.android.internal.content.PackageHelper; 41import com.android.internal.util.FastPrintWriter; 42import com.android.internal.util.FastXmlSerializer; 43import com.android.internal.util.XmlUtils; 44import com.android.server.EventLogTags; 45import com.android.server.IntentResolver; 46import com.android.server.ServiceThread; 47 48import com.android.server.LocalServices; 49import com.android.server.Watchdog; 50import org.xmlpull.v1.XmlPullParser; 51import org.xmlpull.v1.XmlPullParserException; 52import org.xmlpull.v1.XmlSerializer; 53 54import android.app.ActivityManager; 55import android.app.ActivityManagerNative; 56import android.app.IActivityManager; 57import android.app.admin.IDevicePolicyManager; 58import android.app.backup.IBackupManager; 59import android.content.BroadcastReceiver; 60import android.content.ComponentName; 61import android.content.Context; 62import android.content.IIntentReceiver; 63import android.content.Intent; 64import android.content.IntentFilter; 65import android.content.IntentSender; 66import android.content.IntentSender.SendIntentException; 67import android.content.ServiceConnection; 68import android.content.pm.ActivityInfo; 69import android.content.pm.ApplicationInfo; 70import android.content.pm.ContainerEncryptionParams; 71import android.content.pm.FeatureInfo; 72import android.content.pm.IPackageDataObserver; 73import android.content.pm.IPackageDeleteObserver; 74import android.content.pm.IPackageInstallObserver; 75import android.content.pm.IPackageInstallObserver2; 76import android.content.pm.IPackageManager; 77import android.content.pm.IPackageMoveObserver; 78import android.content.pm.IPackageStatsObserver; 79import android.content.pm.InstrumentationInfo; 80import android.content.pm.ManifestDigest; 81import android.content.pm.PackageCleanItem; 82import android.content.pm.PackageInfo; 83import android.content.pm.PackageInfoLite; 84import android.content.pm.PackageManager; 85import android.content.pm.PackageParser; 86import android.content.pm.PackageStats; 87import android.content.pm.PackageUserState; 88import android.content.pm.ParceledListSlice; 89import android.content.pm.PermissionGroupInfo; 90import android.content.pm.PermissionInfo; 91import android.content.pm.ProviderInfo; 92import android.content.pm.ResolveInfo; 93import android.content.pm.ServiceInfo; 94import android.content.pm.Signature; 95import android.content.pm.VerificationParams; 96import android.content.pm.VerifierDeviceIdentity; 97import android.content.pm.VerifierInfo; 98import android.content.res.Resources; 99import android.hardware.display.DisplayManager; 100import android.net.Uri; 101import android.os.Binder; 102import android.os.Build; 103import android.os.Bundle; 104import android.os.Environment; 105import android.os.Environment.UserEnvironment; 106import android.os.FileObserver; 107import android.os.FileUtils; 108import android.os.Handler; 109import android.os.IBinder; 110import android.os.Looper; 111import android.os.Message; 112import android.os.Parcel; 113import android.os.ParcelFileDescriptor; 114import android.os.Process; 115import android.os.RemoteException; 116import android.os.SELinux; 117import android.os.ServiceManager; 118import android.os.SystemClock; 119import android.os.SystemProperties; 120import android.os.UserHandle; 121import android.os.UserManager; 122import android.security.KeyStore; 123import android.security.SystemKeyStore; 124import android.system.ErrnoException; 125import android.system.Os; 126import android.system.StructStat; 127import android.text.TextUtils; 128import android.util.DisplayMetrics; 129import android.util.EventLog; 130import android.util.Log; 131import android.util.LogPrinter; 132import android.util.PrintStreamPrinter; 133import android.util.Slog; 134import android.util.SparseArray; 135import android.util.Xml; 136import android.view.Display; 137 138import java.io.BufferedOutputStream; 139import java.io.File; 140import java.io.FileDescriptor; 141import java.io.FileInputStream; 142import java.io.FileNotFoundException; 143import java.io.FileOutputStream; 144import java.io.FileReader; 145import java.io.FilenameFilter; 146import java.io.IOException; 147import java.io.PrintWriter; 148import java.security.NoSuchAlgorithmException; 149import java.security.PublicKey; 150import java.security.cert.Certificate; 151import java.security.cert.CertificateEncodingException; 152import java.security.cert.CertificateException; 153import java.text.SimpleDateFormat; 154import java.util.ArrayList; 155import java.util.Arrays; 156import java.util.Collection; 157import java.util.Collections; 158import java.util.Comparator; 159import java.util.Date; 160import java.util.HashMap; 161import java.util.HashSet; 162import java.util.Iterator; 163import java.util.List; 164import java.util.Map; 165import java.util.Set; 166 167import dalvik.system.VMRuntime; 168import libcore.io.IoUtils; 169 170import com.android.internal.R; 171import com.android.server.pm.Settings.DatabaseVersion; 172import com.android.server.storage.DeviceStorageMonitorInternal; 173 174/** 175 * Keep track of all those .apks everywhere. 176 * 177 * This is very central to the platform's security; please run the unit 178 * tests whenever making modifications here: 179 * 180mmm frameworks/base/tests/AndroidTests 181adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 182adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 183 * 184 * {@hide} 185 */ 186public class PackageManagerService extends IPackageManager.Stub { 187 static final String TAG = "PackageManager"; 188 static final boolean DEBUG_SETTINGS = false; 189 static final boolean DEBUG_PREFERRED = false; 190 static final boolean DEBUG_UPGRADE = false; 191 private static final boolean DEBUG_INSTALL = false; 192 private static final boolean DEBUG_REMOVE = false; 193 private static final boolean DEBUG_BROADCASTS = false; 194 private static final boolean DEBUG_SHOW_INFO = false; 195 private static final boolean DEBUG_PACKAGE_INFO = false; 196 private static final boolean DEBUG_INTENT_MATCHING = false; 197 private static final boolean DEBUG_PACKAGE_SCANNING = false; 198 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 199 private static final boolean DEBUG_VERIFY = false; 200 201 private static final int RADIO_UID = Process.PHONE_UID; 202 private static final int LOG_UID = Process.LOG_UID; 203 private static final int NFC_UID = Process.NFC_UID; 204 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 205 private static final int SHELL_UID = Process.SHELL_UID; 206 207 // Cap the size of permission trees that 3rd party apps can define 208 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 209 210 private static final int REMOVE_EVENTS = 211 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 212 private static final int ADD_EVENTS = 213 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 214 215 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 216 // Suffix used during package installation when copying/moving 217 // package apks to install directory. 218 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 219 220 static final int SCAN_MONITOR = 1<<0; 221 static final int SCAN_NO_DEX = 1<<1; 222 static final int SCAN_FORCE_DEX = 1<<2; 223 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 224 static final int SCAN_NEW_INSTALL = 1<<4; 225 static final int SCAN_NO_PATHS = 1<<5; 226 static final int SCAN_UPDATE_TIME = 1<<6; 227 static final int SCAN_DEFER_DEX = 1<<7; 228 static final int SCAN_BOOTING = 1<<8; 229 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 230 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 231 232 static final int REMOVE_CHATTY = 1<<16; 233 234 /** 235 * Timeout (in milliseconds) after which the watchdog should declare that 236 * our handler thread is wedged. The usual default for such things is one 237 * minute but we sometimes do very lengthy I/O operations on this thread, 238 * such as installing multi-gigabyte applications, so ours needs to be longer. 239 */ 240 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 241 242 /** 243 * Whether verification is enabled by default. 244 */ 245 private static final boolean DEFAULT_VERIFY_ENABLE = true; 246 247 /** 248 * The default maximum time to wait for the verification agent to return in 249 * milliseconds. 250 */ 251 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 252 253 /** 254 * The default response for package verification timeout. 255 * 256 * This can be either PackageManager.VERIFICATION_ALLOW or 257 * PackageManager.VERIFICATION_REJECT. 258 */ 259 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 260 261 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 262 263 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 264 DEFAULT_CONTAINER_PACKAGE, 265 "com.android.defcontainer.DefaultContainerService"); 266 267 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 268 269 private static final String LIB_DIR_NAME = "lib"; 270 private static final String LIB64_DIR_NAME = "lib64"; 271 272 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 273 274 static final String mTempContainerPrefix = "smdl2tmp"; 275 276 private static String sPreferredInstructionSet; 277 278 final ServiceThread mHandlerThread; 279 280 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 281 private static final String IDMAP_SUFFIX = "@idmap"; 282 283 final PackageHandler mHandler; 284 285 final int mSdkVersion = Build.VERSION.SDK_INT; 286 287 final Context mContext; 288 final boolean mFactoryTest; 289 final boolean mOnlyCore; 290 final boolean mNoDexOpt; 291 final DisplayMetrics mMetrics; 292 final int mDefParseFlags; 293 final String[] mSeparateProcesses; 294 295 // This is where all application persistent data goes. 296 final File mAppDataDir; 297 298 // This is where all application persistent data goes for secondary users. 299 final File mUserAppDataDir; 300 301 /** The location for ASEC container files on internal storage. */ 302 final String mAsecInternalPath; 303 304 // This is the object monitoring the framework dir. 305 final FileObserver mFrameworkInstallObserver; 306 307 // This is the object monitoring the system app dir. 308 final FileObserver mSystemInstallObserver; 309 310 // This is the object monitoring the privileged system app dir. 311 final FileObserver mPrivilegedInstallObserver; 312 313 // This is the object monitoring the vendor app dir. 314 final FileObserver mVendorInstallObserver; 315 316 // This is the object monitoring the vendor overlay package dir. 317 final FileObserver mVendorOverlayInstallObserver; 318 319 // This is the object monitoring the OEM app dir. 320 final FileObserver mOemInstallObserver; 321 322 // This is the object monitoring mAppInstallDir. 323 final FileObserver mAppInstallObserver; 324 325 // This is the object monitoring mDrmAppPrivateInstallDir. 326 final FileObserver mDrmAppInstallObserver; 327 328 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 329 // LOCK HELD. Can be called with mInstallLock held. 330 final Installer mInstaller; 331 332 final File mAppInstallDir; 333 334 /** 335 * Directory to which applications installed internally have native 336 * libraries copied. 337 */ 338 private File mAppLibInstallDir; 339 340 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 341 // apps. 342 final File mDrmAppPrivateInstallDir; 343 344 // ---------------------------------------------------------------- 345 346 // Lock for state used when installing and doing other long running 347 // operations. Methods that must be called with this lock held have 348 // the suffix "LI". 349 final Object mInstallLock = new Object(); 350 351 // These are the directories in the 3rd party applications installed dir 352 // that we have currently loaded packages from. Keys are the application's 353 // installed zip file (absolute codePath), and values are Package. 354 final HashMap<String, PackageParser.Package> mAppDirs = 355 new HashMap<String, PackageParser.Package>(); 356 357 // Information for the parser to write more useful error messages. 358 int mLastScanError; 359 360 // ---------------------------------------------------------------- 361 362 // Keys are String (package name), values are Package. This also serves 363 // as the lock for the global state. Methods that must be called with 364 // this lock held have the prefix "LP". 365 final HashMap<String, PackageParser.Package> mPackages = 366 new HashMap<String, PackageParser.Package>(); 367 368 // Tracks available target package names -> overlay package paths. 369 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 370 new HashMap<String, HashMap<String, PackageParser.Package>>(); 371 372 final Settings mSettings; 373 boolean mRestoredSettings; 374 375 // Group-ids that are given to all packages as read from etc/permissions/*.xml. 376 int[] mGlobalGids; 377 378 // These are the built-in uid -> permission mappings that were read from the 379 // etc/permissions.xml file. 380 final SparseArray<HashSet<String>> mSystemPermissions = 381 new SparseArray<HashSet<String>>(); 382 383 static final class SharedLibraryEntry { 384 final String path; 385 final String apk; 386 387 SharedLibraryEntry(String _path, String _apk) { 388 path = _path; 389 apk = _apk; 390 } 391 } 392 393 // These are the built-in shared libraries that were read from the 394 // etc/permissions.xml file. 395 final HashMap<String, SharedLibraryEntry> mSharedLibraries 396 = new HashMap<String, SharedLibraryEntry>(); 397 398 // Temporary for building the final shared libraries for an .apk. 399 String[] mTmpSharedLibraries = null; 400 401 // These are the features this devices supports that were read from the 402 // etc/permissions.xml file. 403 final HashMap<String, FeatureInfo> mAvailableFeatures = 404 new HashMap<String, FeatureInfo>(); 405 406 // If mac_permissions.xml was found for seinfo labeling. 407 boolean mFoundPolicyFile; 408 409 // If a recursive restorecon of /data/data/<pkg> is needed. 410 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 411 412 // All available activities, for your resolving pleasure. 413 final ActivityIntentResolver mActivities = 414 new ActivityIntentResolver(); 415 416 // All available receivers, for your resolving pleasure. 417 final ActivityIntentResolver mReceivers = 418 new ActivityIntentResolver(); 419 420 // All available services, for your resolving pleasure. 421 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 422 423 // All available providers, for your resolving pleasure. 424 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 425 426 // Mapping from provider base names (first directory in content URI codePath) 427 // to the provider information. 428 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 429 new HashMap<String, PackageParser.Provider>(); 430 431 // Mapping from instrumentation class names to info about them. 432 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 433 new HashMap<ComponentName, PackageParser.Instrumentation>(); 434 435 // Mapping from permission names to info about them. 436 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 437 new HashMap<String, PackageParser.PermissionGroup>(); 438 439 // Packages whose data we have transfered into another package, thus 440 // should no longer exist. 441 final HashSet<String> mTransferedPackages = new HashSet<String>(); 442 443 // Broadcast actions that are only available to the system. 444 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 445 446 /** List of packages waiting for verification. */ 447 final SparseArray<PackageVerificationState> mPendingVerification 448 = new SparseArray<PackageVerificationState>(); 449 450 HashSet<PackageParser.Package> mDeferredDexOpt = null; 451 452 /** Token for keys in mPendingVerification. */ 453 private int mPendingVerificationToken = 0; 454 455 boolean mSystemReady; 456 boolean mSafeMode; 457 boolean mHasSystemUidErrors; 458 459 ApplicationInfo mAndroidApplication; 460 final ActivityInfo mResolveActivity = new ActivityInfo(); 461 final ResolveInfo mResolveInfo = new ResolveInfo(); 462 ComponentName mResolveComponentName; 463 PackageParser.Package mPlatformPackage; 464 ComponentName mCustomResolverComponentName; 465 466 boolean mResolverReplaced = false; 467 468 // Set of pending broadcasts for aggregating enable/disable of components. 469 static class PendingPackageBroadcasts { 470 // for each user id, a map of <package name -> components within that package> 471 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 472 473 public PendingPackageBroadcasts() { 474 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 475 } 476 477 public ArrayList<String> get(int userId, String packageName) { 478 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 479 return packages.get(packageName); 480 } 481 482 public void put(int userId, String packageName, ArrayList<String> components) { 483 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 484 packages.put(packageName, components); 485 } 486 487 public void remove(int userId, String packageName) { 488 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 489 if (packages != null) { 490 packages.remove(packageName); 491 } 492 } 493 494 public void remove(int userId) { 495 mUidMap.remove(userId); 496 } 497 498 public int userIdCount() { 499 return mUidMap.size(); 500 } 501 502 public int userIdAt(int n) { 503 return mUidMap.keyAt(n); 504 } 505 506 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 507 return mUidMap.get(userId); 508 } 509 510 public int size() { 511 // total number of pending broadcast entries across all userIds 512 int num = 0; 513 for (int i = 0; i< mUidMap.size(); i++) { 514 num += mUidMap.valueAt(i).size(); 515 } 516 return num; 517 } 518 519 public void clear() { 520 mUidMap.clear(); 521 } 522 523 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 524 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 525 if (map == null) { 526 map = new HashMap<String, ArrayList<String>>(); 527 mUidMap.put(userId, map); 528 } 529 return map; 530 } 531 } 532 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 533 534 // Service Connection to remote media container service to copy 535 // package uri's from external media onto secure containers 536 // or internal storage. 537 private IMediaContainerService mContainerService = null; 538 539 static final int SEND_PENDING_BROADCAST = 1; 540 static final int MCS_BOUND = 3; 541 static final int END_COPY = 4; 542 static final int INIT_COPY = 5; 543 static final int MCS_UNBIND = 6; 544 static final int START_CLEANING_PACKAGE = 7; 545 static final int FIND_INSTALL_LOC = 8; 546 static final int POST_INSTALL = 9; 547 static final int MCS_RECONNECT = 10; 548 static final int MCS_GIVE_UP = 11; 549 static final int UPDATED_MEDIA_STATUS = 12; 550 static final int WRITE_SETTINGS = 13; 551 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 552 static final int PACKAGE_VERIFIED = 15; 553 static final int CHECK_PENDING_VERIFICATION = 16; 554 555 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 556 557 // Delay time in millisecs 558 static final int BROADCAST_DELAY = 10 * 1000; 559 560 static UserManagerService sUserManager; 561 562 // Stores a list of users whose package restrictions file needs to be updated 563 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 564 565 final private DefaultContainerConnection mDefContainerConn = 566 new DefaultContainerConnection(); 567 class DefaultContainerConnection implements ServiceConnection { 568 public void onServiceConnected(ComponentName name, IBinder service) { 569 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 570 IMediaContainerService imcs = 571 IMediaContainerService.Stub.asInterface(service); 572 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 573 } 574 575 public void onServiceDisconnected(ComponentName name) { 576 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 577 } 578 }; 579 580 // Recordkeeping of restore-after-install operations that are currently in flight 581 // between the Package Manager and the Backup Manager 582 class PostInstallData { 583 public InstallArgs args; 584 public PackageInstalledInfo res; 585 586 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 587 args = _a; 588 res = _r; 589 } 590 }; 591 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 592 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 593 594 private final String mRequiredVerifierPackage; 595 596 class PackageHandler extends Handler { 597 private boolean mBound = false; 598 final ArrayList<HandlerParams> mPendingInstalls = 599 new ArrayList<HandlerParams>(); 600 601 private boolean connectToService() { 602 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 603 " DefaultContainerService"); 604 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 605 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 606 if (mContext.bindServiceAsUser(service, mDefContainerConn, 607 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 608 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 609 mBound = true; 610 return true; 611 } 612 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 613 return false; 614 } 615 616 private void disconnectService() { 617 mContainerService = null; 618 mBound = false; 619 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 620 mContext.unbindService(mDefContainerConn); 621 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 622 } 623 624 PackageHandler(Looper looper) { 625 super(looper); 626 } 627 628 public void handleMessage(Message msg) { 629 try { 630 doHandleMessage(msg); 631 } finally { 632 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 633 } 634 } 635 636 void doHandleMessage(Message msg) { 637 switch (msg.what) { 638 case INIT_COPY: { 639 HandlerParams params = (HandlerParams) msg.obj; 640 int idx = mPendingInstalls.size(); 641 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 642 // If a bind was already initiated we dont really 643 // need to do anything. The pending install 644 // will be processed later on. 645 if (!mBound) { 646 // If this is the only one pending we might 647 // have to bind to the service again. 648 if (!connectToService()) { 649 Slog.e(TAG, "Failed to bind to media container service"); 650 params.serviceError(); 651 return; 652 } else { 653 // Once we bind to the service, the first 654 // pending request will be processed. 655 mPendingInstalls.add(idx, params); 656 } 657 } else { 658 mPendingInstalls.add(idx, params); 659 // Already bound to the service. Just make 660 // sure we trigger off processing the first request. 661 if (idx == 0) { 662 mHandler.sendEmptyMessage(MCS_BOUND); 663 } 664 } 665 break; 666 } 667 case MCS_BOUND: { 668 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 669 if (msg.obj != null) { 670 mContainerService = (IMediaContainerService) msg.obj; 671 } 672 if (mContainerService == null) { 673 // Something seriously wrong. Bail out 674 Slog.e(TAG, "Cannot bind to media container service"); 675 for (HandlerParams params : mPendingInstalls) { 676 // Indicate service bind error 677 params.serviceError(); 678 } 679 mPendingInstalls.clear(); 680 } else if (mPendingInstalls.size() > 0) { 681 HandlerParams params = mPendingInstalls.get(0); 682 if (params != null) { 683 if (params.startCopy()) { 684 // We are done... look for more work or to 685 // go idle. 686 if (DEBUG_SD_INSTALL) Log.i(TAG, 687 "Checking for more work or unbind..."); 688 // Delete pending install 689 if (mPendingInstalls.size() > 0) { 690 mPendingInstalls.remove(0); 691 } 692 if (mPendingInstalls.size() == 0) { 693 if (mBound) { 694 if (DEBUG_SD_INSTALL) Log.i(TAG, 695 "Posting delayed MCS_UNBIND"); 696 removeMessages(MCS_UNBIND); 697 Message ubmsg = obtainMessage(MCS_UNBIND); 698 // Unbind after a little delay, to avoid 699 // continual thrashing. 700 sendMessageDelayed(ubmsg, 10000); 701 } 702 } else { 703 // There are more pending requests in queue. 704 // Just post MCS_BOUND message to trigger processing 705 // of next pending install. 706 if (DEBUG_SD_INSTALL) Log.i(TAG, 707 "Posting MCS_BOUND for next work"); 708 mHandler.sendEmptyMessage(MCS_BOUND); 709 } 710 } 711 } 712 } else { 713 // Should never happen ideally. 714 Slog.w(TAG, "Empty queue"); 715 } 716 break; 717 } 718 case MCS_RECONNECT: { 719 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 720 if (mPendingInstalls.size() > 0) { 721 if (mBound) { 722 disconnectService(); 723 } 724 if (!connectToService()) { 725 Slog.e(TAG, "Failed to bind to media container service"); 726 for (HandlerParams params : mPendingInstalls) { 727 // Indicate service bind error 728 params.serviceError(); 729 } 730 mPendingInstalls.clear(); 731 } 732 } 733 break; 734 } 735 case MCS_UNBIND: { 736 // If there is no actual work left, then time to unbind. 737 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 738 739 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 740 if (mBound) { 741 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 742 743 disconnectService(); 744 } 745 } else if (mPendingInstalls.size() > 0) { 746 // There are more pending requests in queue. 747 // Just post MCS_BOUND message to trigger processing 748 // of next pending install. 749 mHandler.sendEmptyMessage(MCS_BOUND); 750 } 751 752 break; 753 } 754 case MCS_GIVE_UP: { 755 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 756 mPendingInstalls.remove(0); 757 break; 758 } 759 case SEND_PENDING_BROADCAST: { 760 String packages[]; 761 ArrayList<String> components[]; 762 int size = 0; 763 int uids[]; 764 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 765 synchronized (mPackages) { 766 if (mPendingBroadcasts == null) { 767 return; 768 } 769 size = mPendingBroadcasts.size(); 770 if (size <= 0) { 771 // Nothing to be done. Just return 772 return; 773 } 774 packages = new String[size]; 775 components = new ArrayList[size]; 776 uids = new int[size]; 777 int i = 0; // filling out the above arrays 778 779 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 780 int packageUserId = mPendingBroadcasts.userIdAt(n); 781 Iterator<Map.Entry<String, ArrayList<String>>> it 782 = mPendingBroadcasts.packagesForUserId(packageUserId) 783 .entrySet().iterator(); 784 while (it.hasNext() && i < size) { 785 Map.Entry<String, ArrayList<String>> ent = it.next(); 786 packages[i] = ent.getKey(); 787 components[i] = ent.getValue(); 788 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 789 uids[i] = (ps != null) 790 ? UserHandle.getUid(packageUserId, ps.appId) 791 : -1; 792 i++; 793 } 794 } 795 size = i; 796 mPendingBroadcasts.clear(); 797 } 798 // Send broadcasts 799 for (int i = 0; i < size; i++) { 800 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 801 } 802 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 803 break; 804 } 805 case START_CLEANING_PACKAGE: { 806 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 807 final String packageName = (String)msg.obj; 808 final int userId = msg.arg1; 809 final boolean andCode = msg.arg2 != 0; 810 synchronized (mPackages) { 811 if (userId == UserHandle.USER_ALL) { 812 int[] users = sUserManager.getUserIds(); 813 for (int user : users) { 814 mSettings.addPackageToCleanLPw( 815 new PackageCleanItem(user, packageName, andCode)); 816 } 817 } else { 818 mSettings.addPackageToCleanLPw( 819 new PackageCleanItem(userId, packageName, andCode)); 820 } 821 } 822 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 823 startCleaningPackages(); 824 } break; 825 case POST_INSTALL: { 826 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 827 PostInstallData data = mRunningInstalls.get(msg.arg1); 828 mRunningInstalls.delete(msg.arg1); 829 boolean deleteOld = false; 830 831 if (data != null) { 832 InstallArgs args = data.args; 833 PackageInstalledInfo res = data.res; 834 835 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 836 res.removedInfo.sendBroadcast(false, true, false); 837 Bundle extras = new Bundle(1); 838 extras.putInt(Intent.EXTRA_UID, res.uid); 839 // Determine the set of users who are adding this 840 // package for the first time vs. those who are seeing 841 // an update. 842 int[] firstUsers; 843 int[] updateUsers = new int[0]; 844 if (res.origUsers == null || res.origUsers.length == 0) { 845 firstUsers = res.newUsers; 846 } else { 847 firstUsers = new int[0]; 848 for (int i=0; i<res.newUsers.length; i++) { 849 int user = res.newUsers[i]; 850 boolean isNew = true; 851 for (int j=0; j<res.origUsers.length; j++) { 852 if (res.origUsers[j] == user) { 853 isNew = false; 854 break; 855 } 856 } 857 if (isNew) { 858 int[] newFirst = new int[firstUsers.length+1]; 859 System.arraycopy(firstUsers, 0, newFirst, 0, 860 firstUsers.length); 861 newFirst[firstUsers.length] = user; 862 firstUsers = newFirst; 863 } else { 864 int[] newUpdate = new int[updateUsers.length+1]; 865 System.arraycopy(updateUsers, 0, newUpdate, 0, 866 updateUsers.length); 867 newUpdate[updateUsers.length] = user; 868 updateUsers = newUpdate; 869 } 870 } 871 } 872 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 873 res.pkg.applicationInfo.packageName, 874 extras, null, null, firstUsers); 875 final boolean update = res.removedInfo.removedPackage != null; 876 if (update) { 877 extras.putBoolean(Intent.EXTRA_REPLACING, true); 878 } 879 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 880 res.pkg.applicationInfo.packageName, 881 extras, null, null, updateUsers); 882 if (update) { 883 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 884 res.pkg.applicationInfo.packageName, 885 extras, null, null, updateUsers); 886 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 887 null, null, 888 res.pkg.applicationInfo.packageName, null, updateUsers); 889 890 // treat asec-hosted packages like removable media on upgrade 891 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 892 if (DEBUG_INSTALL) { 893 Slog.i(TAG, "upgrading pkg " + res.pkg 894 + " is ASEC-hosted -> AVAILABLE"); 895 } 896 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 897 ArrayList<String> pkgList = new ArrayList<String>(1); 898 pkgList.add(res.pkg.applicationInfo.packageName); 899 sendResourcesChangedBroadcast(true, true, 900 pkgList,uidArray, null); 901 } 902 } 903 if (res.removedInfo.args != null) { 904 // Remove the replaced package's older resources safely now 905 deleteOld = true; 906 } 907 908 // Log current value of "unknown sources" setting 909 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 910 getUnknownSourcesSettings()); 911 } 912 // Force a gc to clear up things 913 Runtime.getRuntime().gc(); 914 // We delete after a gc for applications on sdcard. 915 if (deleteOld) { 916 synchronized (mInstallLock) { 917 res.removedInfo.args.doPostDeleteLI(true); 918 } 919 } 920 if (args.observer != null) { 921 try { 922 args.observer.packageInstalled(res.name, res.returnCode); 923 } catch (RemoteException e) { 924 Slog.i(TAG, "Observer no longer exists."); 925 } 926 } 927 if (args.observer2 != null) { 928 try { 929 Bundle extras = extrasForInstallResult(res); 930 args.observer2.packageInstalled(res.name, extras, res.returnCode); 931 } catch (RemoteException e) { 932 Slog.i(TAG, "Observer no longer exists."); 933 } 934 } 935 } else { 936 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 937 } 938 } break; 939 case UPDATED_MEDIA_STATUS: { 940 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 941 boolean reportStatus = msg.arg1 == 1; 942 boolean doGc = msg.arg2 == 1; 943 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 944 if (doGc) { 945 // Force a gc to clear up stale containers. 946 Runtime.getRuntime().gc(); 947 } 948 if (msg.obj != null) { 949 @SuppressWarnings("unchecked") 950 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 951 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 952 // Unload containers 953 unloadAllContainers(args); 954 } 955 if (reportStatus) { 956 try { 957 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 958 PackageHelper.getMountService().finishMediaUpdate(); 959 } catch (RemoteException e) { 960 Log.e(TAG, "MountService not running?"); 961 } 962 } 963 } break; 964 case WRITE_SETTINGS: { 965 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 966 synchronized (mPackages) { 967 removeMessages(WRITE_SETTINGS); 968 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 969 mSettings.writeLPr(); 970 mDirtyUsers.clear(); 971 } 972 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 973 } break; 974 case WRITE_PACKAGE_RESTRICTIONS: { 975 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 976 synchronized (mPackages) { 977 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 978 for (int userId : mDirtyUsers) { 979 mSettings.writePackageRestrictionsLPr(userId); 980 } 981 mDirtyUsers.clear(); 982 } 983 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 984 } break; 985 case CHECK_PENDING_VERIFICATION: { 986 final int verificationId = msg.arg1; 987 final PackageVerificationState state = mPendingVerification.get(verificationId); 988 989 if ((state != null) && !state.timeoutExtended()) { 990 final InstallArgs args = state.getInstallArgs(); 991 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString()); 992 mPendingVerification.remove(verificationId); 993 994 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 995 996 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 997 Slog.i(TAG, "Continuing with installation of " 998 + args.packageURI.toString()); 999 state.setVerifierResponse(Binder.getCallingUid(), 1000 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1001 broadcastPackageVerified(verificationId, args.packageURI, 1002 PackageManager.VERIFICATION_ALLOW, 1003 state.getInstallArgs().getUser()); 1004 try { 1005 ret = args.copyApk(mContainerService, true); 1006 } catch (RemoteException e) { 1007 Slog.e(TAG, "Could not contact the ContainerService"); 1008 } 1009 } else { 1010 broadcastPackageVerified(verificationId, args.packageURI, 1011 PackageManager.VERIFICATION_REJECT, 1012 state.getInstallArgs().getUser()); 1013 } 1014 1015 processPendingInstall(args, ret); 1016 mHandler.sendEmptyMessage(MCS_UNBIND); 1017 } 1018 break; 1019 } 1020 case PACKAGE_VERIFIED: { 1021 final int verificationId = msg.arg1; 1022 1023 final PackageVerificationState state = mPendingVerification.get(verificationId); 1024 if (state == null) { 1025 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1026 break; 1027 } 1028 1029 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1030 1031 state.setVerifierResponse(response.callerUid, response.code); 1032 1033 if (state.isVerificationComplete()) { 1034 mPendingVerification.remove(verificationId); 1035 1036 final InstallArgs args = state.getInstallArgs(); 1037 1038 int ret; 1039 if (state.isInstallAllowed()) { 1040 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1041 broadcastPackageVerified(verificationId, args.packageURI, 1042 response.code, state.getInstallArgs().getUser()); 1043 try { 1044 ret = args.copyApk(mContainerService, true); 1045 } catch (RemoteException e) { 1046 Slog.e(TAG, "Could not contact the ContainerService"); 1047 } 1048 } else { 1049 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1050 } 1051 1052 processPendingInstall(args, ret); 1053 1054 mHandler.sendEmptyMessage(MCS_UNBIND); 1055 } 1056 1057 break; 1058 } 1059 } 1060 } 1061 } 1062 1063 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1064 Bundle extras = null; 1065 switch (res.returnCode) { 1066 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1067 extras = new Bundle(); 1068 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1069 res.origPermission); 1070 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1071 res.origPackage); 1072 break; 1073 } 1074 } 1075 return extras; 1076 } 1077 1078 void scheduleWriteSettingsLocked() { 1079 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1080 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1081 } 1082 } 1083 1084 void scheduleWritePackageRestrictionsLocked(int userId) { 1085 if (!sUserManager.exists(userId)) return; 1086 mDirtyUsers.add(userId); 1087 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1088 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1089 } 1090 } 1091 1092 public static final IPackageManager main(Context context, Installer installer, 1093 boolean factoryTest, boolean onlyCore) { 1094 PackageManagerService m = new PackageManagerService(context, installer, 1095 factoryTest, onlyCore); 1096 ServiceManager.addService("package", m); 1097 return m; 1098 } 1099 1100 static String[] splitString(String str, char sep) { 1101 int count = 1; 1102 int i = 0; 1103 while ((i=str.indexOf(sep, i)) >= 0) { 1104 count++; 1105 i++; 1106 } 1107 1108 String[] res = new String[count]; 1109 i=0; 1110 count = 0; 1111 int lastI=0; 1112 while ((i=str.indexOf(sep, i)) >= 0) { 1113 res[count] = str.substring(lastI, i); 1114 count++; 1115 i++; 1116 lastI = i; 1117 } 1118 res[count] = str.substring(lastI, str.length()); 1119 return res; 1120 } 1121 1122 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1123 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1124 Context.DISPLAY_SERVICE); 1125 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1126 } 1127 1128 public PackageManagerService(Context context, Installer installer, 1129 boolean factoryTest, boolean onlyCore) { 1130 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1131 SystemClock.uptimeMillis()); 1132 1133 if (mSdkVersion <= 0) { 1134 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1135 } 1136 1137 mContext = context; 1138 mFactoryTest = factoryTest; 1139 mOnlyCore = onlyCore; 1140 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1141 mMetrics = new DisplayMetrics(); 1142 mSettings = new Settings(context); 1143 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1144 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1145 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1146 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1147 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1148 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1149 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1150 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1151 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1152 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1153 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1154 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1155 1156 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1157 if (separateProcesses != null && separateProcesses.length() > 0) { 1158 if ("*".equals(separateProcesses)) { 1159 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1160 mSeparateProcesses = null; 1161 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1162 } else { 1163 mDefParseFlags = 0; 1164 mSeparateProcesses = separateProcesses.split(","); 1165 Slog.w(TAG, "Running with debug.separate_processes: " 1166 + separateProcesses); 1167 } 1168 } else { 1169 mDefParseFlags = 0; 1170 mSeparateProcesses = null; 1171 } 1172 1173 mInstaller = installer; 1174 1175 getDefaultDisplayMetrics(context, mMetrics); 1176 1177 synchronized (mInstallLock) { 1178 // writer 1179 synchronized (mPackages) { 1180 mHandlerThread = new ServiceThread(TAG, 1181 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1182 mHandlerThread.start(); 1183 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1184 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1185 1186 File dataDir = Environment.getDataDirectory(); 1187 mAppDataDir = new File(dataDir, "data"); 1188 mAppInstallDir = new File(dataDir, "app"); 1189 mAppLibInstallDir = new File(dataDir, "app-lib"); 1190 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1191 mUserAppDataDir = new File(dataDir, "user"); 1192 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1193 1194 sUserManager = new UserManagerService(context, this, 1195 mInstallLock, mPackages); 1196 1197 // Read permissions and features from system 1198 readPermissions(Environment.buildPath( 1199 Environment.getRootDirectory(), "etc", "permissions"), false); 1200 // Only read features from OEM 1201 readPermissions(Environment.buildPath( 1202 Environment.getOemDirectory(), "etc", "permissions"), true); 1203 1204 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1205 1206 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1207 mSdkVersion, mOnlyCore); 1208 1209 String customResolverActivity = Resources.getSystem().getString( 1210 R.string.config_customResolverActivity); 1211 if (TextUtils.isEmpty(customResolverActivity)) { 1212 customResolverActivity = null; 1213 } else { 1214 mCustomResolverComponentName = ComponentName.unflattenFromString( 1215 customResolverActivity); 1216 } 1217 1218 long startTime = SystemClock.uptimeMillis(); 1219 1220 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1221 startTime); 1222 1223 // Set flag to monitor and not change apk file paths when 1224 // scanning install directories. 1225 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1226 if (mNoDexOpt) { 1227 Slog.w(TAG, "Running ENG build: no pre-dexopt!"); 1228 scanMode |= SCAN_NO_DEX; 1229 } 1230 1231 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1232 1233 /** 1234 * Add everything in the in the boot class path to the 1235 * list of process files because dexopt will have been run 1236 * if necessary during zygote startup. 1237 */ 1238 String bootClassPath = System.getProperty("java.boot.class.path"); 1239 if (bootClassPath != null) { 1240 String[] paths = splitString(bootClassPath, ':'); 1241 for (int i=0; i<paths.length; i++) { 1242 alreadyDexOpted.add(paths[i]); 1243 } 1244 } else { 1245 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1246 } 1247 1248 boolean didDexOpt = false; 1249 1250 final List<String> instructionSets = getAllInstructionSets(); 1251 1252 /** 1253 * Ensure all external libraries have had dexopt run on them. 1254 */ 1255 if (mSharedLibraries.size() > 0) { 1256 // NOTE: For now, we're compiling these system "shared libraries" 1257 // (and framework jars) into all available architectures. It's possible 1258 // to compile them only when we come across an app that uses them (there's 1259 // already logic for that in scanPackageLI) but that adds some complexity. 1260 for (String instructionSet : instructionSets) { 1261 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1262 final String lib = libEntry.path; 1263 if (lib == null) { 1264 continue; 1265 } 1266 1267 try { 1268 if (dalvik.system.DexFile.isDexOptNeededInternal( 1269 lib, null, instructionSet, false)) { 1270 alreadyDexOpted.add(lib); 1271 1272 // The list of "shared libraries" we have at this point is 1273 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1274 didDexOpt = true; 1275 } 1276 } catch (FileNotFoundException e) { 1277 Slog.w(TAG, "Library not found: " + lib); 1278 } catch (IOException e) { 1279 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1280 + e.getMessage()); 1281 } 1282 } 1283 } 1284 } 1285 1286 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1287 1288 // Gross hack for now: we know this file doesn't contain any 1289 // code, so don't dexopt it to avoid the resulting log spew. 1290 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1291 1292 // Gross hack for now: we know this file is only part of 1293 // the boot class path for art, so don't dexopt it to 1294 // avoid the resulting log spew. 1295 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1296 1297 /** 1298 * And there are a number of commands implemented in Java, which 1299 * we currently need to do the dexopt on so that they can be 1300 * run from a non-root shell. 1301 */ 1302 String[] frameworkFiles = frameworkDir.list(); 1303 if (frameworkFiles != null) { 1304 // TODO: We could compile these only for the most preferred ABI. We should 1305 // first double check that the dex files for these commands are not referenced 1306 // by other system apps. 1307 for (String instructionSet : instructionSets) { 1308 for (int i=0; i<frameworkFiles.length; i++) { 1309 File libPath = new File(frameworkDir, frameworkFiles[i]); 1310 String path = libPath.getPath(); 1311 // Skip the file if we already did it. 1312 if (alreadyDexOpted.contains(path)) { 1313 continue; 1314 } 1315 // Skip the file if it is not a type we want to dexopt. 1316 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1317 continue; 1318 } 1319 try { 1320 if (dalvik.system.DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1321 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1322 didDexOpt = true; 1323 } 1324 } catch (FileNotFoundException e) { 1325 Slog.w(TAG, "Jar not found: " + path); 1326 } catch (IOException e) { 1327 Slog.w(TAG, "Exception reading jar: " + path, e); 1328 } 1329 } 1330 } 1331 } 1332 1333 if (didDexOpt) { 1334 pruneDexFiles(new File(dataDir, "dalvik-cache")); 1335 } 1336 1337 // Collect vendor overlay packages. 1338 // (Do this before scanning any apps.) 1339 // For security and version matching reason, only consider 1340 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1341 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1342 mVendorOverlayInstallObserver = new AppDirObserver( 1343 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1344 mVendorOverlayInstallObserver.startWatching(); 1345 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1346 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1347 1348 // Find base frameworks (resource packages without code). 1349 mFrameworkInstallObserver = new AppDirObserver( 1350 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1351 mFrameworkInstallObserver.startWatching(); 1352 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1353 | PackageParser.PARSE_IS_SYSTEM_DIR 1354 | PackageParser.PARSE_IS_PRIVILEGED, 1355 scanMode | SCAN_NO_DEX, 0); 1356 1357 // Collected privileged system packages. 1358 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1359 mPrivilegedInstallObserver = new AppDirObserver( 1360 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1361 mPrivilegedInstallObserver.startWatching(); 1362 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1363 | PackageParser.PARSE_IS_SYSTEM_DIR 1364 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1365 1366 // Collect ordinary system packages. 1367 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1368 mSystemInstallObserver = new AppDirObserver( 1369 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1370 mSystemInstallObserver.startWatching(); 1371 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1372 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1373 1374 // Collect all vendor packages. 1375 File vendorAppDir = new File("/vendor/app"); 1376 try { 1377 vendorAppDir = vendorAppDir.getCanonicalFile(); 1378 } catch (IOException e) { 1379 // failed to look up canonical path, continue with original one 1380 } 1381 mVendorInstallObserver = new AppDirObserver( 1382 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1383 mVendorInstallObserver.startWatching(); 1384 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1385 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1386 1387 // Collect all OEM packages. 1388 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1389 mOemInstallObserver = new AppDirObserver( 1390 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1391 mOemInstallObserver.startWatching(); 1392 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1393 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1394 1395 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1396 mInstaller.moveFiles(); 1397 1398 // Prune any system packages that no longer exist. 1399 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1400 if (!mOnlyCore) { 1401 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1402 while (psit.hasNext()) { 1403 PackageSetting ps = psit.next(); 1404 1405 /* 1406 * If this is not a system app, it can't be a 1407 * disable system app. 1408 */ 1409 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1410 continue; 1411 } 1412 1413 /* 1414 * If the package is scanned, it's not erased. 1415 */ 1416 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1417 if (scannedPkg != null) { 1418 /* 1419 * If the system app is both scanned and in the 1420 * disabled packages list, then it must have been 1421 * added via OTA. Remove it from the currently 1422 * scanned package so the previously user-installed 1423 * application can be scanned. 1424 */ 1425 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1426 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1427 + "; removing system app"); 1428 removePackageLI(ps, true); 1429 } 1430 1431 continue; 1432 } 1433 1434 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1435 psit.remove(); 1436 String msg = "System package " + ps.name 1437 + " no longer exists; wiping its data"; 1438 reportSettingsProblem(Log.WARN, msg); 1439 removeDataDirsLI(ps.name); 1440 } else { 1441 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1442 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1443 possiblyDeletedUpdatedSystemApps.add(ps.name); 1444 } 1445 } 1446 } 1447 } 1448 1449 //look for any incomplete package installations 1450 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1451 //clean up list 1452 for(int i = 0; i < deletePkgsList.size(); i++) { 1453 //clean up here 1454 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1455 } 1456 //delete tmp files 1457 deleteTempPackageFiles(); 1458 1459 // Remove any shared userIDs that have no associated packages 1460 mSettings.pruneSharedUsersLPw(); 1461 1462 if (!mOnlyCore) { 1463 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1464 SystemClock.uptimeMillis()); 1465 mAppInstallObserver = new AppDirObserver( 1466 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1467 mAppInstallObserver.startWatching(); 1468 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1469 1470 mDrmAppInstallObserver = new AppDirObserver( 1471 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1472 mDrmAppInstallObserver.startWatching(); 1473 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1474 scanMode, 0); 1475 1476 /** 1477 * Remove disable package settings for any updated system 1478 * apps that were removed via an OTA. If they're not a 1479 * previously-updated app, remove them completely. 1480 * Otherwise, just revoke their system-level permissions. 1481 */ 1482 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1483 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1484 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1485 1486 String msg; 1487 if (deletedPkg == null) { 1488 msg = "Updated system package " + deletedAppName 1489 + " no longer exists; wiping its data"; 1490 removeDataDirsLI(deletedAppName); 1491 } else { 1492 msg = "Updated system app + " + deletedAppName 1493 + " no longer present; removing system privileges for " 1494 + deletedAppName; 1495 1496 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1497 1498 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1499 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1500 } 1501 reportSettingsProblem(Log.WARN, msg); 1502 } 1503 } else { 1504 mAppInstallObserver = null; 1505 mDrmAppInstallObserver = null; 1506 } 1507 1508 // Now that we know all of the shared libraries, update all clients to have 1509 // the correct library paths. 1510 updateAllSharedLibrariesLPw(); 1511 1512 1513 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1514 adjustCpuAbisForSharedUserLPw(setting.packages, true /* do dexopt */, 1515 false /* force dexopt */, false /* defer dexopt */); 1516 } 1517 1518 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1519 SystemClock.uptimeMillis()); 1520 Slog.i(TAG, "Time to scan packages: " 1521 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1522 + " seconds"); 1523 1524 // If the platform SDK has changed since the last time we booted, 1525 // we need to re-grant app permission to catch any new ones that 1526 // appear. This is really a hack, and means that apps can in some 1527 // cases get permissions that the user didn't initially explicitly 1528 // allow... it would be nice to have some better way to handle 1529 // this situation. 1530 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1531 != mSdkVersion; 1532 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1533 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1534 + "; regranting permissions for internal storage"); 1535 mSettings.mInternalSdkPlatform = mSdkVersion; 1536 1537 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1538 | (regrantPermissions 1539 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1540 : 0)); 1541 1542 // If this is the first boot, and it is a normal boot, then 1543 // we need to initialize the default preferred apps. 1544 if (!mRestoredSettings && !onlyCore) { 1545 mSettings.readDefaultPreferredAppsLPw(this, 0); 1546 } 1547 1548 // All the changes are done during package scanning. 1549 mSettings.updateInternalDatabaseVersion(); 1550 1551 // can downgrade to reader 1552 mSettings.writeLPr(); 1553 1554 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1555 SystemClock.uptimeMillis()); 1556 1557 // Now after opening every single application zip, make sure they 1558 // are all flushed. Not really needed, but keeps things nice and 1559 // tidy. 1560 Runtime.getRuntime().gc(); 1561 1562 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1563 } // synchronized (mPackages) 1564 } // synchronized (mInstallLock) 1565 } 1566 1567 private static void pruneDexFiles(File cacheDir) { 1568 // If we had to do a dexopt of one of the previous 1569 // things, then something on the system has changed. 1570 // Consider this significant, and wipe away all other 1571 // existing dexopt files to ensure we don't leave any 1572 // dangling around. 1573 // 1574 // Additionally, delete all dex files from the root directory 1575 // since there shouldn't be any there anyway. 1576 File[] files = cacheDir.listFiles(); 1577 if (files != null) { 1578 for (File file : files) { 1579 if (!file.isDirectory()) { 1580 Slog.i(TAG, "Pruning dalvik file: " + file.getAbsolutePath()); 1581 file.delete(); 1582 } else { 1583 File[] subDirList = file.listFiles(); 1584 if (subDirList != null) { 1585 for (File subDirFile : subDirList) { 1586 final String fn = subDirFile.getName(); 1587 if (fn.startsWith("data@app@") || fn.startsWith("data@app-private@")) { 1588 Slog.i(TAG, "Pruning dalvik file: " + fn); 1589 subDirFile.delete(); 1590 } 1591 } 1592 } 1593 } 1594 } 1595 } 1596 } 1597 1598 public boolean isFirstBoot() { 1599 return !mRestoredSettings; 1600 } 1601 1602 public boolean isOnlyCoreApps() { 1603 return mOnlyCore; 1604 } 1605 1606 private String getRequiredVerifierLPr() { 1607 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1608 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1609 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1610 1611 String requiredVerifier = null; 1612 1613 final int N = receivers.size(); 1614 for (int i = 0; i < N; i++) { 1615 final ResolveInfo info = receivers.get(i); 1616 1617 if (info.activityInfo == null) { 1618 continue; 1619 } 1620 1621 final String packageName = info.activityInfo.packageName; 1622 1623 final PackageSetting ps = mSettings.mPackages.get(packageName); 1624 if (ps == null) { 1625 continue; 1626 } 1627 1628 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1629 if (!gp.grantedPermissions 1630 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1631 continue; 1632 } 1633 1634 if (requiredVerifier != null) { 1635 throw new RuntimeException("There can be only one required verifier"); 1636 } 1637 1638 requiredVerifier = packageName; 1639 } 1640 1641 return requiredVerifier; 1642 } 1643 1644 @Override 1645 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1646 throws RemoteException { 1647 try { 1648 return super.onTransact(code, data, reply, flags); 1649 } catch (RuntimeException e) { 1650 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1651 Slog.wtf(TAG, "Package Manager Crash", e); 1652 } 1653 throw e; 1654 } 1655 } 1656 1657 void cleanupInstallFailedPackage(PackageSetting ps) { 1658 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1659 removeDataDirsLI(ps.name); 1660 if (ps.codePath != null) { 1661 if (!ps.codePath.delete()) { 1662 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1663 } 1664 } 1665 if (ps.resourcePath != null) { 1666 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1667 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1668 } 1669 } 1670 mSettings.removePackageLPw(ps.name); 1671 } 1672 1673 void readPermissions(File libraryDir, boolean onlyFeatures) { 1674 // Read permissions from .../etc/permission directory. 1675 if (!libraryDir.exists() || !libraryDir.isDirectory()) { 1676 Slog.w(TAG, "No directory " + libraryDir + ", skipping"); 1677 return; 1678 } 1679 if (!libraryDir.canRead()) { 1680 Slog.w(TAG, "Directory " + libraryDir + " cannot be read"); 1681 return; 1682 } 1683 1684 // Iterate over the files in the directory and scan .xml files 1685 for (File f : libraryDir.listFiles()) { 1686 // We'll read platform.xml last 1687 if (f.getPath().endsWith("etc/permissions/platform.xml")) { 1688 continue; 1689 } 1690 1691 if (!f.getPath().endsWith(".xml")) { 1692 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring"); 1693 continue; 1694 } 1695 if (!f.canRead()) { 1696 Slog.w(TAG, "Permissions library file " + f + " cannot be read"); 1697 continue; 1698 } 1699 1700 readPermissionsFromXml(f, onlyFeatures); 1701 } 1702 1703 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence 1704 final File permFile = new File(Environment.getRootDirectory(), 1705 "etc/permissions/platform.xml"); 1706 readPermissionsFromXml(permFile, onlyFeatures); 1707 } 1708 1709 private void readPermissionsFromXml(File permFile, boolean onlyFeatures) { 1710 FileReader permReader = null; 1711 try { 1712 permReader = new FileReader(permFile); 1713 } catch (FileNotFoundException e) { 1714 Slog.w(TAG, "Couldn't find or open permissions file " + permFile); 1715 return; 1716 } 1717 1718 try { 1719 XmlPullParser parser = Xml.newPullParser(); 1720 parser.setInput(permReader); 1721 1722 XmlUtils.beginDocument(parser, "permissions"); 1723 1724 while (true) { 1725 XmlUtils.nextElement(parser); 1726 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) { 1727 break; 1728 } 1729 1730 String name = parser.getName(); 1731 if ("group".equals(name) && !onlyFeatures) { 1732 String gidStr = parser.getAttributeValue(null, "gid"); 1733 if (gidStr != null) { 1734 int gid = Process.getGidForName(gidStr); 1735 mGlobalGids = appendInt(mGlobalGids, gid); 1736 } else { 1737 Slog.w(TAG, "<group> without gid at " 1738 + parser.getPositionDescription()); 1739 } 1740 1741 XmlUtils.skipCurrentTag(parser); 1742 continue; 1743 } else if ("permission".equals(name) && !onlyFeatures) { 1744 String perm = parser.getAttributeValue(null, "name"); 1745 if (perm == null) { 1746 Slog.w(TAG, "<permission> without name at " 1747 + parser.getPositionDescription()); 1748 XmlUtils.skipCurrentTag(parser); 1749 continue; 1750 } 1751 perm = perm.intern(); 1752 readPermission(parser, perm); 1753 1754 } else if ("assign-permission".equals(name) && !onlyFeatures) { 1755 String perm = parser.getAttributeValue(null, "name"); 1756 if (perm == null) { 1757 Slog.w(TAG, "<assign-permission> without name at " 1758 + parser.getPositionDescription()); 1759 XmlUtils.skipCurrentTag(parser); 1760 continue; 1761 } 1762 String uidStr = parser.getAttributeValue(null, "uid"); 1763 if (uidStr == null) { 1764 Slog.w(TAG, "<assign-permission> without uid at " 1765 + parser.getPositionDescription()); 1766 XmlUtils.skipCurrentTag(parser); 1767 continue; 1768 } 1769 int uid = Process.getUidForName(uidStr); 1770 if (uid < 0) { 1771 Slog.w(TAG, "<assign-permission> with unknown uid \"" 1772 + uidStr + "\" at " 1773 + parser.getPositionDescription()); 1774 XmlUtils.skipCurrentTag(parser); 1775 continue; 1776 } 1777 perm = perm.intern(); 1778 HashSet<String> perms = mSystemPermissions.get(uid); 1779 if (perms == null) { 1780 perms = new HashSet<String>(); 1781 mSystemPermissions.put(uid, perms); 1782 } 1783 perms.add(perm); 1784 XmlUtils.skipCurrentTag(parser); 1785 1786 } else if ("library".equals(name) && !onlyFeatures) { 1787 String lname = parser.getAttributeValue(null, "name"); 1788 String lfile = parser.getAttributeValue(null, "file"); 1789 if (lname == null) { 1790 Slog.w(TAG, "<library> without name at " 1791 + parser.getPositionDescription()); 1792 } else if (lfile == null) { 1793 Slog.w(TAG, "<library> without file at " 1794 + parser.getPositionDescription()); 1795 } else { 1796 //Log.i(TAG, "Got library " + lname + " in " + lfile); 1797 mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null)); 1798 } 1799 XmlUtils.skipCurrentTag(parser); 1800 continue; 1801 1802 } else if ("feature".equals(name)) { 1803 String fname = parser.getAttributeValue(null, "name"); 1804 if (fname == null) { 1805 Slog.w(TAG, "<feature> without name at " 1806 + parser.getPositionDescription()); 1807 } else { 1808 //Log.i(TAG, "Got feature " + fname); 1809 FeatureInfo fi = new FeatureInfo(); 1810 fi.name = fname; 1811 mAvailableFeatures.put(fname, fi); 1812 } 1813 XmlUtils.skipCurrentTag(parser); 1814 continue; 1815 1816 } else { 1817 XmlUtils.skipCurrentTag(parser); 1818 continue; 1819 } 1820 1821 } 1822 permReader.close(); 1823 } catch (XmlPullParserException e) { 1824 Slog.w(TAG, "Got execption parsing permissions.", e); 1825 } catch (IOException e) { 1826 Slog.w(TAG, "Got execption parsing permissions.", e); 1827 } 1828 } 1829 1830 void readPermission(XmlPullParser parser, String name) 1831 throws IOException, XmlPullParserException { 1832 1833 name = name.intern(); 1834 1835 BasePermission bp = mSettings.mPermissions.get(name); 1836 if (bp == null) { 1837 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN); 1838 mSettings.mPermissions.put(name, bp); 1839 } 1840 int outerDepth = parser.getDepth(); 1841 int type; 1842 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 1843 && (type != XmlPullParser.END_TAG 1844 || parser.getDepth() > outerDepth)) { 1845 if (type == XmlPullParser.END_TAG 1846 || type == XmlPullParser.TEXT) { 1847 continue; 1848 } 1849 1850 String tagName = parser.getName(); 1851 if ("group".equals(tagName)) { 1852 String gidStr = parser.getAttributeValue(null, "gid"); 1853 if (gidStr != null) { 1854 int gid = Process.getGidForName(gidStr); 1855 bp.gids = appendInt(bp.gids, gid); 1856 } else { 1857 Slog.w(TAG, "<group> without gid at " 1858 + parser.getPositionDescription()); 1859 } 1860 } 1861 XmlUtils.skipCurrentTag(parser); 1862 } 1863 } 1864 1865 static int[] appendInts(int[] cur, int[] add) { 1866 if (add == null) return cur; 1867 if (cur == null) return add; 1868 final int N = add.length; 1869 for (int i=0; i<N; i++) { 1870 cur = appendInt(cur, add[i]); 1871 } 1872 return cur; 1873 } 1874 1875 static int[] removeInts(int[] cur, int[] rem) { 1876 if (rem == null) return cur; 1877 if (cur == null) return cur; 1878 final int N = rem.length; 1879 for (int i=0; i<N; i++) { 1880 cur = removeInt(cur, rem[i]); 1881 } 1882 return cur; 1883 } 1884 1885 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1886 if (!sUserManager.exists(userId)) return null; 1887 final PackageSetting ps = (PackageSetting) p.mExtras; 1888 if (ps == null) { 1889 return null; 1890 } 1891 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1892 final PackageUserState state = ps.readUserState(userId); 1893 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1894 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1895 state, userId); 1896 } 1897 1898 public boolean isPackageAvailable(String packageName, int userId) { 1899 if (!sUserManager.exists(userId)) return false; 1900 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1901 synchronized (mPackages) { 1902 PackageParser.Package p = mPackages.get(packageName); 1903 if (p != null) { 1904 final PackageSetting ps = (PackageSetting) p.mExtras; 1905 if (ps != null) { 1906 final PackageUserState state = ps.readUserState(userId); 1907 if (state != null) { 1908 return PackageParser.isAvailable(state); 1909 } 1910 } 1911 } 1912 } 1913 return false; 1914 } 1915 1916 @Override 1917 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1918 if (!sUserManager.exists(userId)) return null; 1919 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1920 // reader 1921 synchronized (mPackages) { 1922 PackageParser.Package p = mPackages.get(packageName); 1923 if (DEBUG_PACKAGE_INFO) 1924 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1925 if (p != null) { 1926 return generatePackageInfo(p, flags, userId); 1927 } 1928 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1929 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1930 } 1931 } 1932 return null; 1933 } 1934 1935 public String[] currentToCanonicalPackageNames(String[] names) { 1936 String[] out = new String[names.length]; 1937 // reader 1938 synchronized (mPackages) { 1939 for (int i=names.length-1; i>=0; i--) { 1940 PackageSetting ps = mSettings.mPackages.get(names[i]); 1941 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1942 } 1943 } 1944 return out; 1945 } 1946 1947 public String[] canonicalToCurrentPackageNames(String[] names) { 1948 String[] out = new String[names.length]; 1949 // reader 1950 synchronized (mPackages) { 1951 for (int i=names.length-1; i>=0; i--) { 1952 String cur = mSettings.mRenamedPackages.get(names[i]); 1953 out[i] = cur != null ? cur : names[i]; 1954 } 1955 } 1956 return out; 1957 } 1958 1959 @Override 1960 public int getPackageUid(String packageName, int userId) { 1961 if (!sUserManager.exists(userId)) return -1; 1962 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1963 // reader 1964 synchronized (mPackages) { 1965 PackageParser.Package p = mPackages.get(packageName); 1966 if(p != null) { 1967 return UserHandle.getUid(userId, p.applicationInfo.uid); 1968 } 1969 PackageSetting ps = mSettings.mPackages.get(packageName); 1970 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1971 return -1; 1972 } 1973 p = ps.pkg; 1974 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1975 } 1976 } 1977 1978 @Override 1979 public int[] getPackageGids(String packageName) { 1980 // reader 1981 synchronized (mPackages) { 1982 PackageParser.Package p = mPackages.get(packageName); 1983 if (DEBUG_PACKAGE_INFO) 1984 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1985 if (p != null) { 1986 final PackageSetting ps = (PackageSetting)p.mExtras; 1987 return ps.getGids(); 1988 } 1989 } 1990 // stupid thing to indicate an error. 1991 return new int[0]; 1992 } 1993 1994 static final PermissionInfo generatePermissionInfo( 1995 BasePermission bp, int flags) { 1996 if (bp.perm != null) { 1997 return PackageParser.generatePermissionInfo(bp.perm, flags); 1998 } 1999 PermissionInfo pi = new PermissionInfo(); 2000 pi.name = bp.name; 2001 pi.packageName = bp.sourcePackage; 2002 pi.nonLocalizedLabel = bp.name; 2003 pi.protectionLevel = bp.protectionLevel; 2004 return pi; 2005 } 2006 2007 public PermissionInfo getPermissionInfo(String name, int flags) { 2008 // reader 2009 synchronized (mPackages) { 2010 final BasePermission p = mSettings.mPermissions.get(name); 2011 if (p != null) { 2012 return generatePermissionInfo(p, flags); 2013 } 2014 return null; 2015 } 2016 } 2017 2018 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2019 // reader 2020 synchronized (mPackages) { 2021 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2022 for (BasePermission p : mSettings.mPermissions.values()) { 2023 if (group == null) { 2024 if (p.perm == null || p.perm.info.group == null) { 2025 out.add(generatePermissionInfo(p, flags)); 2026 } 2027 } else { 2028 if (p.perm != null && group.equals(p.perm.info.group)) { 2029 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2030 } 2031 } 2032 } 2033 2034 if (out.size() > 0) { 2035 return out; 2036 } 2037 return mPermissionGroups.containsKey(group) ? out : null; 2038 } 2039 } 2040 2041 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2042 // reader 2043 synchronized (mPackages) { 2044 return PackageParser.generatePermissionGroupInfo( 2045 mPermissionGroups.get(name), flags); 2046 } 2047 } 2048 2049 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2050 // reader 2051 synchronized (mPackages) { 2052 final int N = mPermissionGroups.size(); 2053 ArrayList<PermissionGroupInfo> out 2054 = new ArrayList<PermissionGroupInfo>(N); 2055 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2056 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2057 } 2058 return out; 2059 } 2060 } 2061 2062 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2063 int userId) { 2064 if (!sUserManager.exists(userId)) return null; 2065 PackageSetting ps = mSettings.mPackages.get(packageName); 2066 if (ps != null) { 2067 if (ps.pkg == null) { 2068 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2069 flags, userId); 2070 if (pInfo != null) { 2071 return pInfo.applicationInfo; 2072 } 2073 return null; 2074 } 2075 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2076 ps.readUserState(userId), userId); 2077 } 2078 return null; 2079 } 2080 2081 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2082 int userId) { 2083 if (!sUserManager.exists(userId)) return null; 2084 PackageSetting ps = mSettings.mPackages.get(packageName); 2085 if (ps != null) { 2086 PackageParser.Package pkg = ps.pkg; 2087 if (pkg == null) { 2088 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2089 return null; 2090 } 2091 pkg = new PackageParser.Package(packageName); 2092 pkg.applicationInfo.packageName = packageName; 2093 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2094 pkg.applicationInfo.publicSourceDir = ps.resourcePathString; 2095 pkg.applicationInfo.sourceDir = ps.codePathString; 2096 pkg.applicationInfo.dataDir = 2097 getDataPathForPackage(packageName, 0).getPath(); 2098 pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString; 2099 pkg.applicationInfo.requiredCpuAbi = ps.requiredCpuAbiString; 2100 } 2101 return generatePackageInfo(pkg, flags, userId); 2102 } 2103 return null; 2104 } 2105 2106 @Override 2107 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2108 if (!sUserManager.exists(userId)) return null; 2109 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2110 // writer 2111 synchronized (mPackages) { 2112 PackageParser.Package p = mPackages.get(packageName); 2113 if (DEBUG_PACKAGE_INFO) Log.v( 2114 TAG, "getApplicationInfo " + packageName 2115 + ": " + p); 2116 if (p != null) { 2117 PackageSetting ps = mSettings.mPackages.get(packageName); 2118 if (ps == null) return null; 2119 // Note: isEnabledLP() does not apply here - always return info 2120 return PackageParser.generateApplicationInfo( 2121 p, flags, ps.readUserState(userId), userId); 2122 } 2123 if ("android".equals(packageName)||"system".equals(packageName)) { 2124 return mAndroidApplication; 2125 } 2126 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2127 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2128 } 2129 } 2130 return null; 2131 } 2132 2133 2134 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2135 mContext.enforceCallingOrSelfPermission( 2136 android.Manifest.permission.CLEAR_APP_CACHE, null); 2137 // Queue up an async operation since clearing cache may take a little while. 2138 mHandler.post(new Runnable() { 2139 public void run() { 2140 mHandler.removeCallbacks(this); 2141 int retCode = -1; 2142 synchronized (mInstallLock) { 2143 retCode = mInstaller.freeCache(freeStorageSize); 2144 if (retCode < 0) { 2145 Slog.w(TAG, "Couldn't clear application caches"); 2146 } 2147 } 2148 if (observer != null) { 2149 try { 2150 observer.onRemoveCompleted(null, (retCode >= 0)); 2151 } catch (RemoteException e) { 2152 Slog.w(TAG, "RemoveException when invoking call back"); 2153 } 2154 } 2155 } 2156 }); 2157 } 2158 2159 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2160 mContext.enforceCallingOrSelfPermission( 2161 android.Manifest.permission.CLEAR_APP_CACHE, null); 2162 // Queue up an async operation since clearing cache may take a little while. 2163 mHandler.post(new Runnable() { 2164 public void run() { 2165 mHandler.removeCallbacks(this); 2166 int retCode = -1; 2167 synchronized (mInstallLock) { 2168 retCode = mInstaller.freeCache(freeStorageSize); 2169 if (retCode < 0) { 2170 Slog.w(TAG, "Couldn't clear application caches"); 2171 } 2172 } 2173 if(pi != null) { 2174 try { 2175 // Callback via pending intent 2176 int code = (retCode >= 0) ? 1 : 0; 2177 pi.sendIntent(null, code, null, 2178 null, null); 2179 } catch (SendIntentException e1) { 2180 Slog.i(TAG, "Failed to send pending intent"); 2181 } 2182 } 2183 } 2184 }); 2185 } 2186 2187 @Override 2188 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2189 if (!sUserManager.exists(userId)) return null; 2190 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2191 synchronized (mPackages) { 2192 PackageParser.Activity a = mActivities.mActivities.get(component); 2193 2194 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2195 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2196 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2197 if (ps == null) return null; 2198 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2199 userId); 2200 } 2201 if (mResolveComponentName.equals(component)) { 2202 return mResolveActivity; 2203 } 2204 } 2205 return null; 2206 } 2207 2208 @Override 2209 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2210 String resolvedType) { 2211 synchronized (mPackages) { 2212 PackageParser.Activity a = mActivities.mActivities.get(component); 2213 if (a == null) { 2214 return false; 2215 } 2216 for (int i=0; i<a.intents.size(); i++) { 2217 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2218 intent.getData(), intent.getCategories(), TAG) >= 0) { 2219 return true; 2220 } 2221 } 2222 return false; 2223 } 2224 } 2225 2226 @Override 2227 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2228 if (!sUserManager.exists(userId)) return null; 2229 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2230 synchronized (mPackages) { 2231 PackageParser.Activity a = mReceivers.mActivities.get(component); 2232 if (DEBUG_PACKAGE_INFO) Log.v( 2233 TAG, "getReceiverInfo " + component + ": " + a); 2234 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2235 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2236 if (ps == null) return null; 2237 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2238 userId); 2239 } 2240 } 2241 return null; 2242 } 2243 2244 @Override 2245 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2246 if (!sUserManager.exists(userId)) return null; 2247 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2248 synchronized (mPackages) { 2249 PackageParser.Service s = mServices.mServices.get(component); 2250 if (DEBUG_PACKAGE_INFO) Log.v( 2251 TAG, "getServiceInfo " + component + ": " + s); 2252 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2253 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2254 if (ps == null) return null; 2255 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2256 userId); 2257 } 2258 } 2259 return null; 2260 } 2261 2262 @Override 2263 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2264 if (!sUserManager.exists(userId)) return null; 2265 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2266 synchronized (mPackages) { 2267 PackageParser.Provider p = mProviders.mProviders.get(component); 2268 if (DEBUG_PACKAGE_INFO) Log.v( 2269 TAG, "getProviderInfo " + component + ": " + p); 2270 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2271 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2272 if (ps == null) return null; 2273 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2274 userId); 2275 } 2276 } 2277 return null; 2278 } 2279 2280 public String[] getSystemSharedLibraryNames() { 2281 Set<String> libSet; 2282 synchronized (mPackages) { 2283 libSet = mSharedLibraries.keySet(); 2284 int size = libSet.size(); 2285 if (size > 0) { 2286 String[] libs = new String[size]; 2287 libSet.toArray(libs); 2288 return libs; 2289 } 2290 } 2291 return null; 2292 } 2293 2294 public FeatureInfo[] getSystemAvailableFeatures() { 2295 Collection<FeatureInfo> featSet; 2296 synchronized (mPackages) { 2297 featSet = mAvailableFeatures.values(); 2298 int size = featSet.size(); 2299 if (size > 0) { 2300 FeatureInfo[] features = new FeatureInfo[size+1]; 2301 featSet.toArray(features); 2302 FeatureInfo fi = new FeatureInfo(); 2303 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2304 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2305 features[size] = fi; 2306 return features; 2307 } 2308 } 2309 return null; 2310 } 2311 2312 public boolean hasSystemFeature(String name) { 2313 synchronized (mPackages) { 2314 return mAvailableFeatures.containsKey(name); 2315 } 2316 } 2317 2318 private void checkValidCaller(int uid, int userId) { 2319 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2320 return; 2321 2322 throw new SecurityException("Caller uid=" + uid 2323 + " is not privileged to communicate with user=" + userId); 2324 } 2325 2326 public int checkPermission(String permName, String pkgName) { 2327 synchronized (mPackages) { 2328 PackageParser.Package p = mPackages.get(pkgName); 2329 if (p != null && p.mExtras != null) { 2330 PackageSetting ps = (PackageSetting)p.mExtras; 2331 if (ps.sharedUser != null) { 2332 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2333 return PackageManager.PERMISSION_GRANTED; 2334 } 2335 } else if (ps.grantedPermissions.contains(permName)) { 2336 return PackageManager.PERMISSION_GRANTED; 2337 } 2338 } 2339 } 2340 return PackageManager.PERMISSION_DENIED; 2341 } 2342 2343 public int checkUidPermission(String permName, int uid) { 2344 synchronized (mPackages) { 2345 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2346 if (obj != null) { 2347 GrantedPermissions gp = (GrantedPermissions)obj; 2348 if (gp.grantedPermissions.contains(permName)) { 2349 return PackageManager.PERMISSION_GRANTED; 2350 } 2351 } else { 2352 HashSet<String> perms = mSystemPermissions.get(uid); 2353 if (perms != null && perms.contains(permName)) { 2354 return PackageManager.PERMISSION_GRANTED; 2355 } 2356 } 2357 } 2358 return PackageManager.PERMISSION_DENIED; 2359 } 2360 2361 /** 2362 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2363 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2364 * @param message the message to log on security exception 2365 * @return 2366 */ 2367 private void enforceCrossUserPermission(int callingUid, int userId, 2368 boolean requireFullPermission, String message) { 2369 if (userId < 0) { 2370 throw new IllegalArgumentException("Invalid userId " + userId); 2371 } 2372 if (userId == UserHandle.getUserId(callingUid)) return; 2373 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2374 if (requireFullPermission) { 2375 mContext.enforceCallingOrSelfPermission( 2376 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2377 } else { 2378 try { 2379 mContext.enforceCallingOrSelfPermission( 2380 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2381 } catch (SecurityException se) { 2382 mContext.enforceCallingOrSelfPermission( 2383 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2384 } 2385 } 2386 } 2387 } 2388 2389 private BasePermission findPermissionTreeLP(String permName) { 2390 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2391 if (permName.startsWith(bp.name) && 2392 permName.length() > bp.name.length() && 2393 permName.charAt(bp.name.length()) == '.') { 2394 return bp; 2395 } 2396 } 2397 return null; 2398 } 2399 2400 private BasePermission checkPermissionTreeLP(String permName) { 2401 if (permName != null) { 2402 BasePermission bp = findPermissionTreeLP(permName); 2403 if (bp != null) { 2404 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2405 return bp; 2406 } 2407 throw new SecurityException("Calling uid " 2408 + Binder.getCallingUid() 2409 + " is not allowed to add to permission tree " 2410 + bp.name + " owned by uid " + bp.uid); 2411 } 2412 } 2413 throw new SecurityException("No permission tree found for " + permName); 2414 } 2415 2416 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2417 if (s1 == null) { 2418 return s2 == null; 2419 } 2420 if (s2 == null) { 2421 return false; 2422 } 2423 if (s1.getClass() != s2.getClass()) { 2424 return false; 2425 } 2426 return s1.equals(s2); 2427 } 2428 2429 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2430 if (pi1.icon != pi2.icon) return false; 2431 if (pi1.logo != pi2.logo) return false; 2432 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2433 if (!compareStrings(pi1.name, pi2.name)) return false; 2434 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2435 // We'll take care of setting this one. 2436 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2437 // These are not currently stored in settings. 2438 //if (!compareStrings(pi1.group, pi2.group)) return false; 2439 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2440 //if (pi1.labelRes != pi2.labelRes) return false; 2441 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2442 return true; 2443 } 2444 2445 int permissionInfoFootprint(PermissionInfo info) { 2446 int size = info.name.length(); 2447 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2448 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2449 return size; 2450 } 2451 2452 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2453 int size = 0; 2454 for (BasePermission perm : mSettings.mPermissions.values()) { 2455 if (perm.uid == tree.uid) { 2456 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2457 } 2458 } 2459 return size; 2460 } 2461 2462 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2463 // We calculate the max size of permissions defined by this uid and throw 2464 // if that plus the size of 'info' would exceed our stated maximum. 2465 if (tree.uid != Process.SYSTEM_UID) { 2466 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2467 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2468 throw new SecurityException("Permission tree size cap exceeded"); 2469 } 2470 } 2471 } 2472 2473 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2474 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2475 throw new SecurityException("Label must be specified in permission"); 2476 } 2477 BasePermission tree = checkPermissionTreeLP(info.name); 2478 BasePermission bp = mSettings.mPermissions.get(info.name); 2479 boolean added = bp == null; 2480 boolean changed = true; 2481 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2482 if (added) { 2483 enforcePermissionCapLocked(info, tree); 2484 bp = new BasePermission(info.name, tree.sourcePackage, 2485 BasePermission.TYPE_DYNAMIC); 2486 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2487 throw new SecurityException( 2488 "Not allowed to modify non-dynamic permission " 2489 + info.name); 2490 } else { 2491 if (bp.protectionLevel == fixedLevel 2492 && bp.perm.owner.equals(tree.perm.owner) 2493 && bp.uid == tree.uid 2494 && comparePermissionInfos(bp.perm.info, info)) { 2495 changed = false; 2496 } 2497 } 2498 bp.protectionLevel = fixedLevel; 2499 info = new PermissionInfo(info); 2500 info.protectionLevel = fixedLevel; 2501 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2502 bp.perm.info.packageName = tree.perm.info.packageName; 2503 bp.uid = tree.uid; 2504 if (added) { 2505 mSettings.mPermissions.put(info.name, bp); 2506 } 2507 if (changed) { 2508 if (!async) { 2509 mSettings.writeLPr(); 2510 } else { 2511 scheduleWriteSettingsLocked(); 2512 } 2513 } 2514 return added; 2515 } 2516 2517 public boolean addPermission(PermissionInfo info) { 2518 synchronized (mPackages) { 2519 return addPermissionLocked(info, false); 2520 } 2521 } 2522 2523 public boolean addPermissionAsync(PermissionInfo info) { 2524 synchronized (mPackages) { 2525 return addPermissionLocked(info, true); 2526 } 2527 } 2528 2529 public void removePermission(String name) { 2530 synchronized (mPackages) { 2531 checkPermissionTreeLP(name); 2532 BasePermission bp = mSettings.mPermissions.get(name); 2533 if (bp != null) { 2534 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2535 throw new SecurityException( 2536 "Not allowed to modify non-dynamic permission " 2537 + name); 2538 } 2539 mSettings.mPermissions.remove(name); 2540 mSettings.writeLPr(); 2541 } 2542 } 2543 } 2544 2545 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2546 int index = pkg.requestedPermissions.indexOf(bp.name); 2547 if (index == -1) { 2548 throw new SecurityException("Package " + pkg.packageName 2549 + " has not requested permission " + bp.name); 2550 } 2551 boolean isNormal = 2552 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2553 == PermissionInfo.PROTECTION_NORMAL); 2554 boolean isDangerous = 2555 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2556 == PermissionInfo.PROTECTION_DANGEROUS); 2557 boolean isDevelopment = 2558 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2559 2560 if (!isNormal && !isDangerous && !isDevelopment) { 2561 throw new SecurityException("Permission " + bp.name 2562 + " is not a changeable permission type"); 2563 } 2564 2565 if (isNormal || isDangerous) { 2566 if (pkg.requestedPermissionsRequired.get(index)) { 2567 throw new SecurityException("Can't change " + bp.name 2568 + ". It is required by the application"); 2569 } 2570 } 2571 } 2572 2573 public void grantPermission(String packageName, String permissionName) { 2574 mContext.enforceCallingOrSelfPermission( 2575 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2576 synchronized (mPackages) { 2577 final PackageParser.Package pkg = mPackages.get(packageName); 2578 if (pkg == null) { 2579 throw new IllegalArgumentException("Unknown package: " + packageName); 2580 } 2581 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2582 if (bp == null) { 2583 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2584 } 2585 2586 checkGrantRevokePermissions(pkg, bp); 2587 2588 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2589 if (ps == null) { 2590 return; 2591 } 2592 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2593 if (gp.grantedPermissions.add(permissionName)) { 2594 if (ps.haveGids) { 2595 gp.gids = appendInts(gp.gids, bp.gids); 2596 } 2597 mSettings.writeLPr(); 2598 } 2599 } 2600 } 2601 2602 public void revokePermission(String packageName, String permissionName) { 2603 int changedAppId = -1; 2604 2605 synchronized (mPackages) { 2606 final PackageParser.Package pkg = mPackages.get(packageName); 2607 if (pkg == null) { 2608 throw new IllegalArgumentException("Unknown package: " + packageName); 2609 } 2610 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2611 mContext.enforceCallingOrSelfPermission( 2612 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2613 } 2614 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2615 if (bp == null) { 2616 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2617 } 2618 2619 checkGrantRevokePermissions(pkg, bp); 2620 2621 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2622 if (ps == null) { 2623 return; 2624 } 2625 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2626 if (gp.grantedPermissions.remove(permissionName)) { 2627 gp.grantedPermissions.remove(permissionName); 2628 if (ps.haveGids) { 2629 gp.gids = removeInts(gp.gids, bp.gids); 2630 } 2631 mSettings.writeLPr(); 2632 changedAppId = ps.appId; 2633 } 2634 } 2635 2636 if (changedAppId >= 0) { 2637 // We changed the perm on someone, kill its processes. 2638 IActivityManager am = ActivityManagerNative.getDefault(); 2639 if (am != null) { 2640 final int callingUserId = UserHandle.getCallingUserId(); 2641 final long ident = Binder.clearCallingIdentity(); 2642 try { 2643 //XXX we should only revoke for the calling user's app permissions, 2644 // but for now we impact all users. 2645 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2646 // "revoke " + permissionName); 2647 int[] users = sUserManager.getUserIds(); 2648 for (int user : users) { 2649 am.killUid(UserHandle.getUid(user, changedAppId), 2650 "revoke " + permissionName); 2651 } 2652 } catch (RemoteException e) { 2653 } finally { 2654 Binder.restoreCallingIdentity(ident); 2655 } 2656 } 2657 } 2658 } 2659 2660 public boolean isProtectedBroadcast(String actionName) { 2661 synchronized (mPackages) { 2662 return mProtectedBroadcasts.contains(actionName); 2663 } 2664 } 2665 2666 public int checkSignatures(String pkg1, String pkg2) { 2667 synchronized (mPackages) { 2668 final PackageParser.Package p1 = mPackages.get(pkg1); 2669 final PackageParser.Package p2 = mPackages.get(pkg2); 2670 if (p1 == null || p1.mExtras == null 2671 || p2 == null || p2.mExtras == null) { 2672 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2673 } 2674 return compareSignatures(p1.mSignatures, p2.mSignatures); 2675 } 2676 } 2677 2678 public int checkUidSignatures(int uid1, int uid2) { 2679 // Map to base uids. 2680 uid1 = UserHandle.getAppId(uid1); 2681 uid2 = UserHandle.getAppId(uid2); 2682 // reader 2683 synchronized (mPackages) { 2684 Signature[] s1; 2685 Signature[] s2; 2686 Object obj = mSettings.getUserIdLPr(uid1); 2687 if (obj != null) { 2688 if (obj instanceof SharedUserSetting) { 2689 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2690 } else if (obj instanceof PackageSetting) { 2691 s1 = ((PackageSetting)obj).signatures.mSignatures; 2692 } else { 2693 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2694 } 2695 } else { 2696 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2697 } 2698 obj = mSettings.getUserIdLPr(uid2); 2699 if (obj != null) { 2700 if (obj instanceof SharedUserSetting) { 2701 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2702 } else if (obj instanceof PackageSetting) { 2703 s2 = ((PackageSetting)obj).signatures.mSignatures; 2704 } else { 2705 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2706 } 2707 } else { 2708 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2709 } 2710 return compareSignatures(s1, s2); 2711 } 2712 } 2713 2714 /** 2715 * Compares two sets of signatures. Returns: 2716 * <br /> 2717 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2718 * <br /> 2719 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2720 * <br /> 2721 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2722 * <br /> 2723 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2724 * <br /> 2725 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2726 */ 2727 static int compareSignatures(Signature[] s1, Signature[] s2) { 2728 if (s1 == null) { 2729 return s2 == null 2730 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2731 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2732 } 2733 2734 if (s2 == null) { 2735 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2736 } 2737 2738 if (s1.length != s2.length) { 2739 return PackageManager.SIGNATURE_NO_MATCH; 2740 } 2741 2742 // Since both signature sets are of size 1, we can compare without HashSets. 2743 if (s1.length == 1) { 2744 return s1[0].equals(s2[0]) ? 2745 PackageManager.SIGNATURE_MATCH : 2746 PackageManager.SIGNATURE_NO_MATCH; 2747 } 2748 2749 HashSet<Signature> set1 = new HashSet<Signature>(); 2750 for (Signature sig : s1) { 2751 set1.add(sig); 2752 } 2753 HashSet<Signature> set2 = new HashSet<Signature>(); 2754 for (Signature sig : s2) { 2755 set2.add(sig); 2756 } 2757 // Make sure s2 contains all signatures in s1. 2758 if (set1.equals(set2)) { 2759 return PackageManager.SIGNATURE_MATCH; 2760 } 2761 return PackageManager.SIGNATURE_NO_MATCH; 2762 } 2763 2764 /** 2765 * If the database version for this type of package (internal storage or 2766 * external storage) is less than the version where package signatures 2767 * were updated, return true. 2768 */ 2769 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2770 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2771 DatabaseVersion.SIGNATURE_END_ENTITY)) 2772 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2773 DatabaseVersion.SIGNATURE_END_ENTITY)); 2774 } 2775 2776 /** 2777 * Used for backward compatibility to make sure any packages with 2778 * certificate chains get upgraded to the new style. {@code existingSigs} 2779 * will be in the old format (since they were stored on disk from before the 2780 * system upgrade) and {@code scannedSigs} will be in the newer format. 2781 */ 2782 private int compareSignaturesCompat(PackageSignatures existingSigs, 2783 PackageParser.Package scannedPkg) { 2784 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2785 return PackageManager.SIGNATURE_NO_MATCH; 2786 } 2787 2788 HashSet<Signature> existingSet = new HashSet<Signature>(); 2789 for (Signature sig : existingSigs.mSignatures) { 2790 existingSet.add(sig); 2791 } 2792 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2793 for (Signature sig : scannedPkg.mSignatures) { 2794 try { 2795 Signature[] chainSignatures = sig.getChainSignatures(); 2796 for (Signature chainSig : chainSignatures) { 2797 scannedCompatSet.add(chainSig); 2798 } 2799 } catch (CertificateEncodingException e) { 2800 scannedCompatSet.add(sig); 2801 } 2802 } 2803 /* 2804 * Make sure the expanded scanned set contains all signatures in the 2805 * existing one. 2806 */ 2807 if (scannedCompatSet.equals(existingSet)) { 2808 // Migrate the old signatures to the new scheme. 2809 existingSigs.assignSignatures(scannedPkg.mSignatures); 2810 // The new KeySets will be re-added later in the scanning process. 2811 mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName); 2812 return PackageManager.SIGNATURE_MATCH; 2813 } 2814 return PackageManager.SIGNATURE_NO_MATCH; 2815 } 2816 2817 public String[] getPackagesForUid(int uid) { 2818 uid = UserHandle.getAppId(uid); 2819 // reader 2820 synchronized (mPackages) { 2821 Object obj = mSettings.getUserIdLPr(uid); 2822 if (obj instanceof SharedUserSetting) { 2823 final SharedUserSetting sus = (SharedUserSetting) obj; 2824 final int N = sus.packages.size(); 2825 final String[] res = new String[N]; 2826 final Iterator<PackageSetting> it = sus.packages.iterator(); 2827 int i = 0; 2828 while (it.hasNext()) { 2829 res[i++] = it.next().name; 2830 } 2831 return res; 2832 } else if (obj instanceof PackageSetting) { 2833 final PackageSetting ps = (PackageSetting) obj; 2834 return new String[] { ps.name }; 2835 } 2836 } 2837 return null; 2838 } 2839 2840 public String getNameForUid(int uid) { 2841 // reader 2842 synchronized (mPackages) { 2843 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2844 if (obj instanceof SharedUserSetting) { 2845 final SharedUserSetting sus = (SharedUserSetting) obj; 2846 return sus.name + ":" + sus.userId; 2847 } else if (obj instanceof PackageSetting) { 2848 final PackageSetting ps = (PackageSetting) obj; 2849 return ps.name; 2850 } 2851 } 2852 return null; 2853 } 2854 2855 public int getUidForSharedUser(String sharedUserName) { 2856 if(sharedUserName == null) { 2857 return -1; 2858 } 2859 // reader 2860 synchronized (mPackages) { 2861 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2862 if (suid == null) { 2863 return -1; 2864 } 2865 return suid.userId; 2866 } 2867 } 2868 2869 public int getFlagsForUid(int uid) { 2870 synchronized (mPackages) { 2871 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2872 if (obj instanceof SharedUserSetting) { 2873 final SharedUserSetting sus = (SharedUserSetting) obj; 2874 return sus.pkgFlags; 2875 } else if (obj instanceof PackageSetting) { 2876 final PackageSetting ps = (PackageSetting) obj; 2877 return ps.pkgFlags; 2878 } 2879 } 2880 return 0; 2881 } 2882 2883 @Override 2884 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2885 int flags, int userId) { 2886 if (!sUserManager.exists(userId)) return null; 2887 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2888 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2889 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2890 } 2891 2892 @Override 2893 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2894 IntentFilter filter, int match, ComponentName activity) { 2895 final int userId = UserHandle.getCallingUserId(); 2896 if (DEBUG_PREFERRED) { 2897 Log.v(TAG, "setLastChosenActivity intent=" + intent 2898 + " resolvedType=" + resolvedType 2899 + " flags=" + flags 2900 + " filter=" + filter 2901 + " match=" + match 2902 + " activity=" + activity); 2903 filter.dump(new PrintStreamPrinter(System.out), " "); 2904 } 2905 intent.setComponent(null); 2906 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2907 // Find any earlier preferred or last chosen entries and nuke them 2908 findPreferredActivity(intent, resolvedType, 2909 flags, query, 0, false, true, false, userId); 2910 // Add the new activity as the last chosen for this filter 2911 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2912 } 2913 2914 @Override 2915 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2916 final int userId = UserHandle.getCallingUserId(); 2917 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2918 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2919 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2920 false, false, false, userId); 2921 } 2922 2923 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2924 int flags, List<ResolveInfo> query, int userId) { 2925 if (query != null) { 2926 final int N = query.size(); 2927 if (N == 1) { 2928 return query.get(0); 2929 } else if (N > 1) { 2930 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2931 // If there is more than one activity with the same priority, 2932 // then let the user decide between them. 2933 ResolveInfo r0 = query.get(0); 2934 ResolveInfo r1 = query.get(1); 2935 if (DEBUG_INTENT_MATCHING || debug) { 2936 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2937 + r1.activityInfo.name + "=" + r1.priority); 2938 } 2939 // If the first activity has a higher priority, or a different 2940 // default, then it is always desireable to pick it. 2941 if (r0.priority != r1.priority 2942 || r0.preferredOrder != r1.preferredOrder 2943 || r0.isDefault != r1.isDefault) { 2944 return query.get(0); 2945 } 2946 // If we have saved a preference for a preferred activity for 2947 // this Intent, use that. 2948 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2949 flags, query, r0.priority, true, false, debug, userId); 2950 if (ri != null) { 2951 return ri; 2952 } 2953 if (userId != 0) { 2954 ri = new ResolveInfo(mResolveInfo); 2955 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2956 ri.activityInfo.applicationInfo = new ApplicationInfo( 2957 ri.activityInfo.applicationInfo); 2958 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2959 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2960 return ri; 2961 } 2962 return mResolveInfo; 2963 } 2964 } 2965 return null; 2966 } 2967 2968 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2969 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2970 final int N = query.size(); 2971 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2972 .get(userId); 2973 // Get the list of persistent preferred activities that handle the intent 2974 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2975 List<PersistentPreferredActivity> pprefs = ppir != null 2976 ? ppir.queryIntent(intent, resolvedType, 2977 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2978 : null; 2979 if (pprefs != null && pprefs.size() > 0) { 2980 final int M = pprefs.size(); 2981 for (int i=0; i<M; i++) { 2982 final PersistentPreferredActivity ppa = pprefs.get(i); 2983 if (DEBUG_PREFERRED || debug) { 2984 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2985 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2986 + "\n component=" + ppa.mComponent); 2987 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2988 } 2989 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2990 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2991 if (DEBUG_PREFERRED || debug) { 2992 Slog.v(TAG, "Found persistent preferred activity:"); 2993 if (ai != null) { 2994 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2995 } else { 2996 Slog.v(TAG, " null"); 2997 } 2998 } 2999 if (ai == null) { 3000 // This previously registered persistent preferred activity 3001 // component is no longer known. Ignore it and do NOT remove it. 3002 continue; 3003 } 3004 for (int j=0; j<N; j++) { 3005 final ResolveInfo ri = query.get(j); 3006 if (!ri.activityInfo.applicationInfo.packageName 3007 .equals(ai.applicationInfo.packageName)) { 3008 continue; 3009 } 3010 if (!ri.activityInfo.name.equals(ai.name)) { 3011 continue; 3012 } 3013 // Found a persistent preference that can handle the intent. 3014 if (DEBUG_PREFERRED || debug) { 3015 Slog.v(TAG, "Returning persistent preferred activity: " + 3016 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3017 } 3018 return ri; 3019 } 3020 } 3021 } 3022 return null; 3023 } 3024 3025 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3026 List<ResolveInfo> query, int priority, boolean always, 3027 boolean removeMatches, boolean debug, int userId) { 3028 if (!sUserManager.exists(userId)) return null; 3029 // writer 3030 synchronized (mPackages) { 3031 if (intent.getSelector() != null) { 3032 intent = intent.getSelector(); 3033 } 3034 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3035 3036 // Try to find a matching persistent preferred activity. 3037 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3038 debug, userId); 3039 3040 // If a persistent preferred activity matched, use it. 3041 if (pri != null) { 3042 return pri; 3043 } 3044 3045 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3046 // Get the list of preferred activities that handle the intent 3047 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3048 List<PreferredActivity> prefs = pir != null 3049 ? pir.queryIntent(intent, resolvedType, 3050 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3051 : null; 3052 if (prefs != null && prefs.size() > 0) { 3053 // First figure out how good the original match set is. 3054 // We will only allow preferred activities that came 3055 // from the same match quality. 3056 int match = 0; 3057 3058 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3059 3060 final int N = query.size(); 3061 for (int j=0; j<N; j++) { 3062 final ResolveInfo ri = query.get(j); 3063 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3064 + ": 0x" + Integer.toHexString(match)); 3065 if (ri.match > match) { 3066 match = ri.match; 3067 } 3068 } 3069 3070 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3071 + Integer.toHexString(match)); 3072 3073 match &= IntentFilter.MATCH_CATEGORY_MASK; 3074 final int M = prefs.size(); 3075 for (int i=0; i<M; i++) { 3076 final PreferredActivity pa = prefs.get(i); 3077 if (DEBUG_PREFERRED || debug) { 3078 Slog.v(TAG, "Checking PreferredActivity ds=" 3079 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3080 + "\n component=" + pa.mPref.mComponent); 3081 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3082 } 3083 if (pa.mPref.mMatch != match) { 3084 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3085 + Integer.toHexString(pa.mPref.mMatch)); 3086 continue; 3087 } 3088 // If it's not an "always" type preferred activity and that's what we're 3089 // looking for, skip it. 3090 if (always && !pa.mPref.mAlways) { 3091 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3092 continue; 3093 } 3094 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3095 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3096 if (DEBUG_PREFERRED || debug) { 3097 Slog.v(TAG, "Found preferred activity:"); 3098 if (ai != null) { 3099 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3100 } else { 3101 Slog.v(TAG, " null"); 3102 } 3103 } 3104 if (ai == null) { 3105 // This previously registered preferred activity 3106 // component is no longer known. Most likely an update 3107 // to the app was installed and in the new version this 3108 // component no longer exists. Clean it up by removing 3109 // it from the preferred activities list, and skip it. 3110 Slog.w(TAG, "Removing dangling preferred activity: " 3111 + pa.mPref.mComponent); 3112 pir.removeFilter(pa); 3113 continue; 3114 } 3115 for (int j=0; j<N; j++) { 3116 final ResolveInfo ri = query.get(j); 3117 if (!ri.activityInfo.applicationInfo.packageName 3118 .equals(ai.applicationInfo.packageName)) { 3119 continue; 3120 } 3121 if (!ri.activityInfo.name.equals(ai.name)) { 3122 continue; 3123 } 3124 3125 if (removeMatches) { 3126 pir.removeFilter(pa); 3127 if (DEBUG_PREFERRED) { 3128 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3129 } 3130 break; 3131 } 3132 3133 // Okay we found a previously set preferred or last chosen app. 3134 // If the result set is different from when this 3135 // was created, we need to clear it and re-ask the 3136 // user their preference, if we're looking for an "always" type entry. 3137 if (always && !pa.mPref.sameSet(query, priority)) { 3138 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3139 + intent + " type " + resolvedType); 3140 if (DEBUG_PREFERRED) { 3141 Slog.v(TAG, "Removing preferred activity since set changed " 3142 + pa.mPref.mComponent); 3143 } 3144 pir.removeFilter(pa); 3145 // Re-add the filter as a "last chosen" entry (!always) 3146 PreferredActivity lastChosen = new PreferredActivity( 3147 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3148 pir.addFilter(lastChosen); 3149 mSettings.writePackageRestrictionsLPr(userId); 3150 return null; 3151 } 3152 3153 // Yay! Either the set matched or we're looking for the last chosen 3154 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3155 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3156 mSettings.writePackageRestrictionsLPr(userId); 3157 return ri; 3158 } 3159 } 3160 } 3161 mSettings.writePackageRestrictionsLPr(userId); 3162 } 3163 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3164 return null; 3165 } 3166 3167 /* 3168 * Returns if intent can be forwarded from the userId from to dest 3169 */ 3170 @Override 3171 public boolean canForwardTo(Intent intent, String resolvedType, int userIdFrom, int userIdDest) { 3172 mContext.enforceCallingOrSelfPermission( 3173 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3174 List<ForwardingIntentFilter> matches = 3175 getMatchingForwardingIntentFilters(intent, resolvedType, userIdFrom); 3176 if (matches != null) { 3177 int size = matches.size(); 3178 for (int i = 0; i < size; i++) { 3179 if (matches.get(i).getUserIdDest() == userIdDest) return true; 3180 } 3181 } 3182 return false; 3183 } 3184 3185 private List<ForwardingIntentFilter> getMatchingForwardingIntentFilters(Intent intent, 3186 String resolvedType, int userId) { 3187 ForwardingIntentResolver fir = mSettings.mForwardingIntentResolvers.get(userId); 3188 if (fir != null) { 3189 return fir.queryIntent(intent, resolvedType, false, userId); 3190 } 3191 return null; 3192 } 3193 3194 @Override 3195 public List<ResolveInfo> queryIntentActivities(Intent intent, 3196 String resolvedType, int flags, int userId) { 3197 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3198 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3199 ComponentName comp = intent.getComponent(); 3200 if (comp == null) { 3201 if (intent.getSelector() != null) { 3202 intent = intent.getSelector(); 3203 comp = intent.getComponent(); 3204 } 3205 } 3206 3207 if (comp != null) { 3208 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3209 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3210 if (ai != null) { 3211 final ResolveInfo ri = new ResolveInfo(); 3212 ri.activityInfo = ai; 3213 list.add(ri); 3214 } 3215 return list; 3216 } 3217 3218 // reader 3219 synchronized (mPackages) { 3220 final String pkgName = intent.getPackage(); 3221 if (pkgName == null) { 3222 List<ResolveInfo> result = 3223 mActivities.queryIntent(intent, resolvedType, flags, userId); 3224 // Checking if we can forward the intent to another user 3225 List<ForwardingIntentFilter> fifs = 3226 getMatchingForwardingIntentFilters(intent, resolvedType, userId); 3227 if (fifs != null) { 3228 ForwardingIntentFilter forwardingIntentFilterWithResult = null; 3229 HashSet<Integer> alreadyTriedUserIds = new HashSet<Integer>(); 3230 for (ForwardingIntentFilter fif : fifs) { 3231 int userIdDest = fif.getUserIdDest(); 3232 // Two {@link ForwardingIntentFilter}s can have the same userIdDest and 3233 // match the same an intent. For performance reasons, it is better not to 3234 // run queryIntent twice for the same userId 3235 if (!alreadyTriedUserIds.contains(userIdDest)) { 3236 List<ResolveInfo> resultUser = mActivities.queryIntent(intent, 3237 resolvedType, flags, userIdDest); 3238 if (resultUser != null) { 3239 forwardingIntentFilterWithResult = fif; 3240 // As soon as there is a match in another user, we add the 3241 // intentForwarderActivity to the list of ResolveInfo. 3242 break; 3243 } 3244 alreadyTriedUserIds.add(userIdDest); 3245 } 3246 } 3247 if (forwardingIntentFilterWithResult != null) { 3248 ResolveInfo forwardingResolveInfo = createForwardingResolveInfo( 3249 forwardingIntentFilterWithResult, userId); 3250 result.add(forwardingResolveInfo); 3251 } 3252 } 3253 return result; 3254 } 3255 final PackageParser.Package pkg = mPackages.get(pkgName); 3256 if (pkg != null) { 3257 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3258 pkg.activities, userId); 3259 } 3260 return new ArrayList<ResolveInfo>(); 3261 } 3262 } 3263 3264 private ResolveInfo createForwardingResolveInfo(ForwardingIntentFilter fif, int userIdFrom) { 3265 String className; 3266 int userIdDest = fif.getUserIdDest(); 3267 if (userIdDest == UserHandle.USER_OWNER) { 3268 className = FORWARD_INTENT_TO_USER_OWNER; 3269 } else { 3270 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3271 } 3272 ComponentName forwardingActivityComponentName = new ComponentName( 3273 mAndroidApplication.packageName, className); 3274 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3275 userIdFrom); 3276 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3277 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3278 forwardingResolveInfo.priority = 0; 3279 forwardingResolveInfo.preferredOrder = 0; 3280 forwardingResolveInfo.match = 0; 3281 forwardingResolveInfo.isDefault = true; 3282 forwardingResolveInfo.filter = fif; 3283 return forwardingResolveInfo; 3284 } 3285 3286 @Override 3287 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3288 Intent[] specifics, String[] specificTypes, Intent intent, 3289 String resolvedType, int flags, int userId) { 3290 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3291 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3292 "query intent activity options"); 3293 final String resultsAction = intent.getAction(); 3294 3295 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3296 | PackageManager.GET_RESOLVED_FILTER, userId); 3297 3298 if (DEBUG_INTENT_MATCHING) { 3299 Log.v(TAG, "Query " + intent + ": " + results); 3300 } 3301 3302 int specificsPos = 0; 3303 int N; 3304 3305 // todo: note that the algorithm used here is O(N^2). This 3306 // isn't a problem in our current environment, but if we start running 3307 // into situations where we have more than 5 or 10 matches then this 3308 // should probably be changed to something smarter... 3309 3310 // First we go through and resolve each of the specific items 3311 // that were supplied, taking care of removing any corresponding 3312 // duplicate items in the generic resolve list. 3313 if (specifics != null) { 3314 for (int i=0; i<specifics.length; i++) { 3315 final Intent sintent = specifics[i]; 3316 if (sintent == null) { 3317 continue; 3318 } 3319 3320 if (DEBUG_INTENT_MATCHING) { 3321 Log.v(TAG, "Specific #" + i + ": " + sintent); 3322 } 3323 3324 String action = sintent.getAction(); 3325 if (resultsAction != null && resultsAction.equals(action)) { 3326 // If this action was explicitly requested, then don't 3327 // remove things that have it. 3328 action = null; 3329 } 3330 3331 ResolveInfo ri = null; 3332 ActivityInfo ai = null; 3333 3334 ComponentName comp = sintent.getComponent(); 3335 if (comp == null) { 3336 ri = resolveIntent( 3337 sintent, 3338 specificTypes != null ? specificTypes[i] : null, 3339 flags, userId); 3340 if (ri == null) { 3341 continue; 3342 } 3343 if (ri == mResolveInfo) { 3344 // ACK! Must do something better with this. 3345 } 3346 ai = ri.activityInfo; 3347 comp = new ComponentName(ai.applicationInfo.packageName, 3348 ai.name); 3349 } else { 3350 ai = getActivityInfo(comp, flags, userId); 3351 if (ai == null) { 3352 continue; 3353 } 3354 } 3355 3356 // Look for any generic query activities that are duplicates 3357 // of this specific one, and remove them from the results. 3358 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3359 N = results.size(); 3360 int j; 3361 for (j=specificsPos; j<N; j++) { 3362 ResolveInfo sri = results.get(j); 3363 if ((sri.activityInfo.name.equals(comp.getClassName()) 3364 && sri.activityInfo.applicationInfo.packageName.equals( 3365 comp.getPackageName())) 3366 || (action != null && sri.filter.matchAction(action))) { 3367 results.remove(j); 3368 if (DEBUG_INTENT_MATCHING) Log.v( 3369 TAG, "Removing duplicate item from " + j 3370 + " due to specific " + specificsPos); 3371 if (ri == null) { 3372 ri = sri; 3373 } 3374 j--; 3375 N--; 3376 } 3377 } 3378 3379 // Add this specific item to its proper place. 3380 if (ri == null) { 3381 ri = new ResolveInfo(); 3382 ri.activityInfo = ai; 3383 } 3384 results.add(specificsPos, ri); 3385 ri.specificIndex = i; 3386 specificsPos++; 3387 } 3388 } 3389 3390 // Now we go through the remaining generic results and remove any 3391 // duplicate actions that are found here. 3392 N = results.size(); 3393 for (int i=specificsPos; i<N-1; i++) { 3394 final ResolveInfo rii = results.get(i); 3395 if (rii.filter == null) { 3396 continue; 3397 } 3398 3399 // Iterate over all of the actions of this result's intent 3400 // filter... typically this should be just one. 3401 final Iterator<String> it = rii.filter.actionsIterator(); 3402 if (it == null) { 3403 continue; 3404 } 3405 while (it.hasNext()) { 3406 final String action = it.next(); 3407 if (resultsAction != null && resultsAction.equals(action)) { 3408 // If this action was explicitly requested, then don't 3409 // remove things that have it. 3410 continue; 3411 } 3412 for (int j=i+1; j<N; j++) { 3413 final ResolveInfo rij = results.get(j); 3414 if (rij.filter != null && rij.filter.hasAction(action)) { 3415 results.remove(j); 3416 if (DEBUG_INTENT_MATCHING) Log.v( 3417 TAG, "Removing duplicate item from " + j 3418 + " due to action " + action + " at " + i); 3419 j--; 3420 N--; 3421 } 3422 } 3423 } 3424 3425 // If the caller didn't request filter information, drop it now 3426 // so we don't have to marshall/unmarshall it. 3427 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3428 rii.filter = null; 3429 } 3430 } 3431 3432 // Filter out the caller activity if so requested. 3433 if (caller != null) { 3434 N = results.size(); 3435 for (int i=0; i<N; i++) { 3436 ActivityInfo ainfo = results.get(i).activityInfo; 3437 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3438 && caller.getClassName().equals(ainfo.name)) { 3439 results.remove(i); 3440 break; 3441 } 3442 } 3443 } 3444 3445 // If the caller didn't request filter information, 3446 // drop them now so we don't have to 3447 // marshall/unmarshall it. 3448 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3449 N = results.size(); 3450 for (int i=0; i<N; i++) { 3451 results.get(i).filter = null; 3452 } 3453 } 3454 3455 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3456 return results; 3457 } 3458 3459 @Override 3460 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3461 int userId) { 3462 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3463 ComponentName comp = intent.getComponent(); 3464 if (comp == null) { 3465 if (intent.getSelector() != null) { 3466 intent = intent.getSelector(); 3467 comp = intent.getComponent(); 3468 } 3469 } 3470 if (comp != null) { 3471 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3472 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3473 if (ai != null) { 3474 ResolveInfo ri = new ResolveInfo(); 3475 ri.activityInfo = ai; 3476 list.add(ri); 3477 } 3478 return list; 3479 } 3480 3481 // reader 3482 synchronized (mPackages) { 3483 String pkgName = intent.getPackage(); 3484 if (pkgName == null) { 3485 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3486 } 3487 final PackageParser.Package pkg = mPackages.get(pkgName); 3488 if (pkg != null) { 3489 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3490 userId); 3491 } 3492 return null; 3493 } 3494 } 3495 3496 @Override 3497 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3498 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3499 if (!sUserManager.exists(userId)) return null; 3500 if (query != null) { 3501 if (query.size() >= 1) { 3502 // If there is more than one service with the same priority, 3503 // just arbitrarily pick the first one. 3504 return query.get(0); 3505 } 3506 } 3507 return null; 3508 } 3509 3510 @Override 3511 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3512 int userId) { 3513 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3514 ComponentName comp = intent.getComponent(); 3515 if (comp == null) { 3516 if (intent.getSelector() != null) { 3517 intent = intent.getSelector(); 3518 comp = intent.getComponent(); 3519 } 3520 } 3521 if (comp != null) { 3522 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3523 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3524 if (si != null) { 3525 final ResolveInfo ri = new ResolveInfo(); 3526 ri.serviceInfo = si; 3527 list.add(ri); 3528 } 3529 return list; 3530 } 3531 3532 // reader 3533 synchronized (mPackages) { 3534 String pkgName = intent.getPackage(); 3535 if (pkgName == null) { 3536 return mServices.queryIntent(intent, resolvedType, flags, userId); 3537 } 3538 final PackageParser.Package pkg = mPackages.get(pkgName); 3539 if (pkg != null) { 3540 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3541 userId); 3542 } 3543 return null; 3544 } 3545 } 3546 3547 @Override 3548 public List<ResolveInfo> queryIntentContentProviders( 3549 Intent intent, String resolvedType, int flags, int userId) { 3550 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3551 ComponentName comp = intent.getComponent(); 3552 if (comp == null) { 3553 if (intent.getSelector() != null) { 3554 intent = intent.getSelector(); 3555 comp = intent.getComponent(); 3556 } 3557 } 3558 if (comp != null) { 3559 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3560 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3561 if (pi != null) { 3562 final ResolveInfo ri = new ResolveInfo(); 3563 ri.providerInfo = pi; 3564 list.add(ri); 3565 } 3566 return list; 3567 } 3568 3569 // reader 3570 synchronized (mPackages) { 3571 String pkgName = intent.getPackage(); 3572 if (pkgName == null) { 3573 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3574 } 3575 final PackageParser.Package pkg = mPackages.get(pkgName); 3576 if (pkg != null) { 3577 return mProviders.queryIntentForPackage( 3578 intent, resolvedType, flags, pkg.providers, userId); 3579 } 3580 return null; 3581 } 3582 } 3583 3584 @Override 3585 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3586 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3587 3588 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3589 3590 // writer 3591 synchronized (mPackages) { 3592 ArrayList<PackageInfo> list; 3593 if (listUninstalled) { 3594 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3595 for (PackageSetting ps : mSettings.mPackages.values()) { 3596 PackageInfo pi; 3597 if (ps.pkg != null) { 3598 pi = generatePackageInfo(ps.pkg, flags, userId); 3599 } else { 3600 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3601 } 3602 if (pi != null) { 3603 list.add(pi); 3604 } 3605 } 3606 } else { 3607 list = new ArrayList<PackageInfo>(mPackages.size()); 3608 for (PackageParser.Package p : mPackages.values()) { 3609 PackageInfo pi = generatePackageInfo(p, flags, userId); 3610 if (pi != null) { 3611 list.add(pi); 3612 } 3613 } 3614 } 3615 3616 return new ParceledListSlice<PackageInfo>(list); 3617 } 3618 } 3619 3620 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3621 String[] permissions, boolean[] tmp, int flags, int userId) { 3622 int numMatch = 0; 3623 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3624 for (int i=0; i<permissions.length; i++) { 3625 if (gp.grantedPermissions.contains(permissions[i])) { 3626 tmp[i] = true; 3627 numMatch++; 3628 } else { 3629 tmp[i] = false; 3630 } 3631 } 3632 if (numMatch == 0) { 3633 return; 3634 } 3635 PackageInfo pi; 3636 if (ps.pkg != null) { 3637 pi = generatePackageInfo(ps.pkg, flags, userId); 3638 } else { 3639 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3640 } 3641 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3642 if (numMatch == permissions.length) { 3643 pi.requestedPermissions = permissions; 3644 } else { 3645 pi.requestedPermissions = new String[numMatch]; 3646 numMatch = 0; 3647 for (int i=0; i<permissions.length; i++) { 3648 if (tmp[i]) { 3649 pi.requestedPermissions[numMatch] = permissions[i]; 3650 numMatch++; 3651 } 3652 } 3653 } 3654 } 3655 list.add(pi); 3656 } 3657 3658 @Override 3659 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3660 String[] permissions, int flags, int userId) { 3661 if (!sUserManager.exists(userId)) return null; 3662 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3663 3664 // writer 3665 synchronized (mPackages) { 3666 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3667 boolean[] tmpBools = new boolean[permissions.length]; 3668 if (listUninstalled) { 3669 for (PackageSetting ps : mSettings.mPackages.values()) { 3670 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3671 } 3672 } else { 3673 for (PackageParser.Package pkg : mPackages.values()) { 3674 PackageSetting ps = (PackageSetting)pkg.mExtras; 3675 if (ps != null) { 3676 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3677 userId); 3678 } 3679 } 3680 } 3681 3682 return new ParceledListSlice<PackageInfo>(list); 3683 } 3684 } 3685 3686 @Override 3687 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3688 if (!sUserManager.exists(userId)) return null; 3689 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3690 3691 // writer 3692 synchronized (mPackages) { 3693 ArrayList<ApplicationInfo> list; 3694 if (listUninstalled) { 3695 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3696 for (PackageSetting ps : mSettings.mPackages.values()) { 3697 ApplicationInfo ai; 3698 if (ps.pkg != null) { 3699 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3700 ps.readUserState(userId), userId); 3701 } else { 3702 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3703 } 3704 if (ai != null) { 3705 list.add(ai); 3706 } 3707 } 3708 } else { 3709 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3710 for (PackageParser.Package p : mPackages.values()) { 3711 if (p.mExtras != null) { 3712 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3713 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3714 if (ai != null) { 3715 list.add(ai); 3716 } 3717 } 3718 } 3719 } 3720 3721 return new ParceledListSlice<ApplicationInfo>(list); 3722 } 3723 } 3724 3725 public List<ApplicationInfo> getPersistentApplications(int flags) { 3726 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3727 3728 // reader 3729 synchronized (mPackages) { 3730 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3731 final int userId = UserHandle.getCallingUserId(); 3732 while (i.hasNext()) { 3733 final PackageParser.Package p = i.next(); 3734 if (p.applicationInfo != null 3735 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3736 && (!mSafeMode || isSystemApp(p))) { 3737 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3738 if (ps != null) { 3739 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3740 ps.readUserState(userId), userId); 3741 if (ai != null) { 3742 finalList.add(ai); 3743 } 3744 } 3745 } 3746 } 3747 } 3748 3749 return finalList; 3750 } 3751 3752 @Override 3753 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3754 if (!sUserManager.exists(userId)) return null; 3755 // reader 3756 synchronized (mPackages) { 3757 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3758 PackageSetting ps = provider != null 3759 ? mSettings.mPackages.get(provider.owner.packageName) 3760 : null; 3761 return ps != null 3762 && mSettings.isEnabledLPr(provider.info, flags, userId) 3763 && (!mSafeMode || (provider.info.applicationInfo.flags 3764 &ApplicationInfo.FLAG_SYSTEM) != 0) 3765 ? PackageParser.generateProviderInfo(provider, flags, 3766 ps.readUserState(userId), userId) 3767 : null; 3768 } 3769 } 3770 3771 /** 3772 * @deprecated 3773 */ 3774 @Deprecated 3775 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3776 // reader 3777 synchronized (mPackages) { 3778 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3779 .entrySet().iterator(); 3780 final int userId = UserHandle.getCallingUserId(); 3781 while (i.hasNext()) { 3782 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3783 PackageParser.Provider p = entry.getValue(); 3784 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3785 3786 if (ps != null && p.syncable 3787 && (!mSafeMode || (p.info.applicationInfo.flags 3788 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3789 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3790 ps.readUserState(userId), userId); 3791 if (info != null) { 3792 outNames.add(entry.getKey()); 3793 outInfo.add(info); 3794 } 3795 } 3796 } 3797 } 3798 } 3799 3800 public List<ProviderInfo> queryContentProviders(String processName, 3801 int uid, int flags) { 3802 ArrayList<ProviderInfo> finalList = null; 3803 // reader 3804 synchronized (mPackages) { 3805 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3806 final int userId = processName != null ? 3807 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3808 while (i.hasNext()) { 3809 final PackageParser.Provider p = i.next(); 3810 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3811 if (ps != null && p.info.authority != null 3812 && (processName == null 3813 || (p.info.processName.equals(processName) 3814 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3815 && mSettings.isEnabledLPr(p.info, flags, userId) 3816 && (!mSafeMode 3817 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3818 if (finalList == null) { 3819 finalList = new ArrayList<ProviderInfo>(3); 3820 } 3821 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3822 ps.readUserState(userId), userId); 3823 if (info != null) { 3824 finalList.add(info); 3825 } 3826 } 3827 } 3828 } 3829 3830 if (finalList != null) { 3831 Collections.sort(finalList, mProviderInitOrderSorter); 3832 } 3833 3834 return finalList; 3835 } 3836 3837 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3838 int flags) { 3839 // reader 3840 synchronized (mPackages) { 3841 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3842 return PackageParser.generateInstrumentationInfo(i, flags); 3843 } 3844 } 3845 3846 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3847 int flags) { 3848 ArrayList<InstrumentationInfo> finalList = 3849 new ArrayList<InstrumentationInfo>(); 3850 3851 // reader 3852 synchronized (mPackages) { 3853 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3854 while (i.hasNext()) { 3855 final PackageParser.Instrumentation p = i.next(); 3856 if (targetPackage == null 3857 || targetPackage.equals(p.info.targetPackage)) { 3858 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3859 flags); 3860 if (ii != null) { 3861 finalList.add(ii); 3862 } 3863 } 3864 } 3865 } 3866 3867 return finalList; 3868 } 3869 3870 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 3871 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 3872 if (overlays == null) { 3873 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 3874 return; 3875 } 3876 for (PackageParser.Package opkg : overlays.values()) { 3877 // Not much to do if idmap fails: we already logged the error 3878 // and we certainly don't want to abort installation of pkg simply 3879 // because an overlay didn't fit properly. For these reasons, 3880 // ignore the return value of createIdmapForPackagePairLI. 3881 createIdmapForPackagePairLI(pkg, opkg); 3882 } 3883 } 3884 3885 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 3886 PackageParser.Package opkg) { 3887 if (!opkg.mTrustedOverlay) { 3888 Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " + 3889 opkg.mScanPath + ": overlay not trusted"); 3890 return false; 3891 } 3892 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 3893 if (overlaySet == null) { 3894 Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " + 3895 opkg.mScanPath + " but target package has no known overlays"); 3896 return false; 3897 } 3898 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 3899 if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) { 3900 Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath); 3901 return false; 3902 } 3903 PackageParser.Package[] overlayArray = 3904 overlaySet.values().toArray(new PackageParser.Package[0]); 3905 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 3906 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 3907 return p1.mOverlayPriority - p2.mOverlayPriority; 3908 } 3909 }; 3910 Arrays.sort(overlayArray, cmp); 3911 3912 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 3913 int i = 0; 3914 for (PackageParser.Package p : overlayArray) { 3915 pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir; 3916 } 3917 return true; 3918 } 3919 3920 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 3921 String[] files = dir.list(); 3922 if (files == null) { 3923 Log.d(TAG, "No files in app dir " + dir); 3924 return; 3925 } 3926 3927 if (DEBUG_PACKAGE_SCANNING) { 3928 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 3929 + " flags=0x" + Integer.toHexString(flags)); 3930 } 3931 3932 int i; 3933 for (i=0; i<files.length; i++) { 3934 File file = new File(dir, files[i]); 3935 if (!isPackageFilename(files[i])) { 3936 // Ignore entries which are not apk's 3937 continue; 3938 } 3939 PackageParser.Package pkg = scanPackageLI(file, 3940 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null); 3941 // Don't mess around with apps in system partition. 3942 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 3943 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 3944 // Delete the apk 3945 Slog.w(TAG, "Cleaning up failed install of " + file); 3946 file.delete(); 3947 } 3948 } 3949 } 3950 3951 private static File getSettingsProblemFile() { 3952 File dataDir = Environment.getDataDirectory(); 3953 File systemDir = new File(dataDir, "system"); 3954 File fname = new File(systemDir, "uiderrors.txt"); 3955 return fname; 3956 } 3957 3958 static void reportSettingsProblem(int priority, String msg) { 3959 try { 3960 File fname = getSettingsProblemFile(); 3961 FileOutputStream out = new FileOutputStream(fname, true); 3962 PrintWriter pw = new FastPrintWriter(out); 3963 SimpleDateFormat formatter = new SimpleDateFormat(); 3964 String dateString = formatter.format(new Date(System.currentTimeMillis())); 3965 pw.println(dateString + ": " + msg); 3966 pw.close(); 3967 FileUtils.setPermissions( 3968 fname.toString(), 3969 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 3970 -1, -1); 3971 } catch (java.io.IOException e) { 3972 } 3973 Slog.println(priority, TAG, msg); 3974 } 3975 3976 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 3977 PackageParser.Package pkg, File srcFile, int parseFlags) { 3978 if (ps != null 3979 && ps.codePath.equals(srcFile) 3980 && ps.timeStamp == srcFile.lastModified() 3981 && !isCompatSignatureUpdateNeeded(pkg)) { 3982 if (ps.signatures.mSignatures != null 3983 && ps.signatures.mSignatures.length != 0) { 3984 // Optimization: reuse the existing cached certificates 3985 // if the package appears to be unchanged. 3986 pkg.mSignatures = ps.signatures.mSignatures; 3987 return true; 3988 } 3989 3990 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 3991 } else { 3992 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 3993 } 3994 3995 if (!pp.collectCertificates(pkg, parseFlags)) { 3996 mLastScanError = pp.getParseError(); 3997 return false; 3998 } 3999 return true; 4000 } 4001 4002 /* 4003 * Scan a package and return the newly parsed package. 4004 * Returns null in case of errors and the error code is stored in mLastScanError 4005 */ 4006 private PackageParser.Package scanPackageLI(File scanFile, 4007 int parseFlags, int scanMode, long currentTime, UserHandle user) { 4008 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 4009 String scanPath = scanFile.getPath(); 4010 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath); 4011 parseFlags |= mDefParseFlags; 4012 PackageParser pp = new PackageParser(scanPath); 4013 pp.setSeparateProcesses(mSeparateProcesses); 4014 pp.setOnlyCoreApps(mOnlyCore); 4015 final PackageParser.Package pkg = pp.parsePackage(scanFile, 4016 scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0); 4017 4018 if (pkg == null) { 4019 mLastScanError = pp.getParseError(); 4020 return null; 4021 } 4022 4023 PackageSetting ps = null; 4024 PackageSetting updatedPkg; 4025 // reader 4026 synchronized (mPackages) { 4027 // Look to see if we already know about this package. 4028 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4029 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4030 // This package has been renamed to its original name. Let's 4031 // use that. 4032 ps = mSettings.peekPackageLPr(oldName); 4033 } 4034 // If there was no original package, see one for the real package name. 4035 if (ps == null) { 4036 ps = mSettings.peekPackageLPr(pkg.packageName); 4037 } 4038 // Check to see if this package could be hiding/updating a system 4039 // package. Must look for it either under the original or real 4040 // package name depending on our state. 4041 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4042 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4043 } 4044 boolean updatedPkgBetter = false; 4045 // First check if this is a system package that may involve an update 4046 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4047 if (ps != null && !ps.codePath.equals(scanFile)) { 4048 // The path has changed from what was last scanned... check the 4049 // version of the new path against what we have stored to determine 4050 // what to do. 4051 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4052 if (pkg.mVersionCode < ps.versionCode) { 4053 // The system package has been updated and the code path does not match 4054 // Ignore entry. Skip it. 4055 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4056 + " ignored: updated version " + ps.versionCode 4057 + " better than this " + pkg.mVersionCode); 4058 if (!updatedPkg.codePath.equals(scanFile)) { 4059 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4060 + ps.name + " changing from " + updatedPkg.codePathString 4061 + " to " + scanFile); 4062 updatedPkg.codePath = scanFile; 4063 updatedPkg.codePathString = scanFile.toString(); 4064 // This is the point at which we know that the system-disk APK 4065 // for this package has moved during a reboot (e.g. due to an OTA), 4066 // so we need to reevaluate it for privilege policy. 4067 if (locationIsPrivileged(scanFile)) { 4068 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4069 } 4070 } 4071 updatedPkg.pkg = pkg; 4072 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4073 return null; 4074 } else { 4075 // The current app on the system partion is better than 4076 // what we have updated to on the data partition; switch 4077 // back to the system partition version. 4078 // At this point, its safely assumed that package installation for 4079 // apps in system partition will go through. If not there won't be a working 4080 // version of the app 4081 // writer 4082 synchronized (mPackages) { 4083 // Just remove the loaded entries from package lists. 4084 mPackages.remove(ps.name); 4085 } 4086 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4087 + "reverting from " + ps.codePathString 4088 + ": new version " + pkg.mVersionCode 4089 + " better than installed " + ps.versionCode); 4090 4091 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4092 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4093 getAppInstructionSetFromSettings(ps)); 4094 synchronized (mInstallLock) { 4095 args.cleanUpResourcesLI(); 4096 } 4097 synchronized (mPackages) { 4098 mSettings.enableSystemPackageLPw(ps.name); 4099 } 4100 updatedPkgBetter = true; 4101 } 4102 } 4103 } 4104 4105 if (updatedPkg != null) { 4106 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4107 // initially 4108 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4109 4110 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4111 // flag set initially 4112 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4113 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4114 } 4115 } 4116 // Verify certificates against what was last scanned 4117 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 4118 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 4119 return null; 4120 } 4121 4122 /* 4123 * A new system app appeared, but we already had a non-system one of the 4124 * same name installed earlier. 4125 */ 4126 boolean shouldHideSystemApp = false; 4127 if (updatedPkg == null && ps != null 4128 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4129 /* 4130 * Check to make sure the signatures match first. If they don't, 4131 * wipe the installed application and its data. 4132 */ 4133 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4134 != PackageManager.SIGNATURE_MATCH) { 4135 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4136 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4137 ps = null; 4138 } else { 4139 /* 4140 * If the newly-added system app is an older version than the 4141 * already installed version, hide it. It will be scanned later 4142 * and re-added like an update. 4143 */ 4144 if (pkg.mVersionCode < ps.versionCode) { 4145 shouldHideSystemApp = true; 4146 } else { 4147 /* 4148 * The newly found system app is a newer version that the 4149 * one previously installed. Simply remove the 4150 * already-installed application and replace it with our own 4151 * while keeping the application data. 4152 */ 4153 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4154 + ps.codePathString + ": new version " + pkg.mVersionCode 4155 + " better than installed " + ps.versionCode); 4156 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4157 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4158 getAppInstructionSetFromSettings(ps)); 4159 synchronized (mInstallLock) { 4160 args.cleanUpResourcesLI(); 4161 } 4162 } 4163 } 4164 } 4165 4166 // The apk is forward locked (not public) if its code and resources 4167 // are kept in different files. (except for app in either system or 4168 // vendor path). 4169 // TODO grab this value from PackageSettings 4170 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4171 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4172 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4173 } 4174 } 4175 4176 String codePath = null; 4177 String resPath = null; 4178 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4179 if (ps != null && ps.resourcePathString != null) { 4180 resPath = ps.resourcePathString; 4181 } else { 4182 // Should not happen at all. Just log an error. 4183 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4184 } 4185 } else { 4186 resPath = pkg.mScanPath; 4187 } 4188 4189 codePath = pkg.mScanPath; 4190 // Set application objects path explicitly. 4191 setApplicationInfoPaths(pkg, codePath, resPath); 4192 // Note that we invoke the following method only if we are about to unpack an application 4193 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4194 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4195 4196 /* 4197 * If the system app should be overridden by a previously installed 4198 * data, hide the system app now and let the /data/app scan pick it up 4199 * again. 4200 */ 4201 if (shouldHideSystemApp) { 4202 synchronized (mPackages) { 4203 /* 4204 * We have to grant systems permissions before we hide, because 4205 * grantPermissions will assume the package update is trying to 4206 * expand its permissions. 4207 */ 4208 grantPermissionsLPw(pkg, true); 4209 mSettings.disableSystemPackageLPw(pkg.packageName); 4210 } 4211 } 4212 4213 return scannedPkg; 4214 } 4215 4216 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath, 4217 String destResPath) { 4218 pkg.mPath = pkg.mScanPath = destCodePath; 4219 pkg.applicationInfo.sourceDir = destCodePath; 4220 pkg.applicationInfo.publicSourceDir = destResPath; 4221 } 4222 4223 private static String fixProcessName(String defProcessName, 4224 String processName, int uid) { 4225 if (processName == null) { 4226 return defProcessName; 4227 } 4228 return processName; 4229 } 4230 4231 private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) { 4232 if (pkgSetting.signatures.mSignatures != null) { 4233 // Already existing package. Make sure signatures match 4234 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4235 == PackageManager.SIGNATURE_MATCH; 4236 if (!match) { 4237 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4238 == PackageManager.SIGNATURE_MATCH; 4239 } 4240 if (!match) { 4241 Slog.e(TAG, "Package " + pkg.packageName 4242 + " signatures do not match the previously installed version; ignoring!"); 4243 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4244 return false; 4245 } 4246 } 4247 // Check for shared user signatures 4248 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4249 // Already existing package. Make sure signatures match 4250 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4251 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4252 if (!match) { 4253 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4254 == PackageManager.SIGNATURE_MATCH; 4255 } 4256 if (!match) { 4257 Slog.e(TAG, "Package " + pkg.packageName 4258 + " has no signatures that match those in shared user " 4259 + pkgSetting.sharedUser.name + "; ignoring!"); 4260 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4261 return false; 4262 } 4263 } 4264 return true; 4265 } 4266 4267 /** 4268 * Enforces that only the system UID or root's UID can call a method exposed 4269 * via Binder. 4270 * 4271 * @param message used as message if SecurityException is thrown 4272 * @throws SecurityException if the caller is not system or root 4273 */ 4274 private static final void enforceSystemOrRoot(String message) { 4275 final int uid = Binder.getCallingUid(); 4276 if (uid != Process.SYSTEM_UID && uid != 0) { 4277 throw new SecurityException(message); 4278 } 4279 } 4280 4281 @Override 4282 public void performBootDexOpt() { 4283 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4284 4285 final HashSet<PackageParser.Package> pkgs; 4286 synchronized (mPackages) { 4287 pkgs = mDeferredDexOpt; 4288 mDeferredDexOpt = null; 4289 } 4290 4291 if (pkgs != null) { 4292 int i = 0; 4293 for (PackageParser.Package pkg : pkgs) { 4294 if (!isFirstBoot()) { 4295 i++; 4296 try { 4297 ActivityManagerNative.getDefault().showBootMessage( 4298 mContext.getResources().getString( 4299 com.android.internal.R.string.android_upgrading_apk, 4300 i, pkgs.size()), true); 4301 } catch (RemoteException e) { 4302 } 4303 } 4304 PackageParser.Package p = pkg; 4305 synchronized (mInstallLock) { 4306 if (!p.mDidDexOpt) { 4307 performDexOptLI(p, false /* force dex */, false /* defer */, 4308 true /* include dependencies */); 4309 } 4310 } 4311 } 4312 } 4313 } 4314 4315 @Override 4316 public boolean performDexOpt(String packageName) { 4317 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4318 if (!mNoDexOpt) { 4319 return false; 4320 } 4321 4322 PackageParser.Package p; 4323 synchronized (mPackages) { 4324 p = mPackages.get(packageName); 4325 if (p == null || p.mDidDexOpt) { 4326 return false; 4327 } 4328 } 4329 synchronized (mInstallLock) { 4330 return performDexOptLI(p, false /* force dex */, false /* defer */, 4331 true /* include dependencies */) == DEX_OPT_PERFORMED; 4332 } 4333 } 4334 4335 private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, boolean forceDex, 4336 boolean defer, HashSet<String> done) { 4337 for (int i=0; i<libs.size(); i++) { 4338 PackageParser.Package libPkg; 4339 String libName; 4340 synchronized (mPackages) { 4341 libName = libs.get(i); 4342 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4343 if (lib != null && lib.apk != null) { 4344 libPkg = mPackages.get(lib.apk); 4345 } else { 4346 libPkg = null; 4347 } 4348 } 4349 if (libPkg != null && !done.contains(libName)) { 4350 performDexOptLI(libPkg, instructionSet, forceDex, defer, done); 4351 } 4352 } 4353 } 4354 4355 static final int DEX_OPT_SKIPPED = 0; 4356 static final int DEX_OPT_PERFORMED = 1; 4357 static final int DEX_OPT_DEFERRED = 2; 4358 static final int DEX_OPT_FAILED = -1; 4359 4360 private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride, 4361 boolean forceDex, 4362 boolean defer, HashSet<String> done) { 4363 final String instructionSet = instructionSetOverride != null ? 4364 instructionSetOverride : getAppInstructionSet(pkg.applicationInfo); 4365 4366 if (done != null) { 4367 done.add(pkg.packageName); 4368 if (pkg.usesLibraries != null) { 4369 performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done); 4370 } 4371 if (pkg.usesOptionalLibraries != null) { 4372 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done); 4373 } 4374 } 4375 4376 boolean performed = false; 4377 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 4378 String path = pkg.mScanPath; 4379 int ret = 0; 4380 try { 4381 if (forceDex || dalvik.system.DexFile.isDexOptNeededInternal(path, 4382 pkg.packageName, instructionSet, defer)) { 4383 if (!forceDex && defer) { 4384 if (mDeferredDexOpt == null) { 4385 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4386 } 4387 mDeferredDexOpt.add(pkg); 4388 return DEX_OPT_DEFERRED; 4389 } else { 4390 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName + 4391 " (instructionSet=" + instructionSet + ")"); 4392 4393 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4394 ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4395 pkg.packageName, instructionSet); 4396 pkg.mDidDexOpt = true; 4397 performed = true; 4398 } 4399 } 4400 } catch (FileNotFoundException e) { 4401 Slog.w(TAG, "Apk not found for dexopt: " + path); 4402 ret = -1; 4403 } catch (IOException e) { 4404 Slog.w(TAG, "IOException reading apk: " + path, e); 4405 ret = -1; 4406 } catch (dalvik.system.StaleDexCacheError e) { 4407 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4408 ret = -1; 4409 } catch (Exception e) { 4410 Slog.w(TAG, "Exception when doing dexopt : ", e); 4411 ret = -1; 4412 } 4413 if (ret < 0) { 4414 //error from installer 4415 return DEX_OPT_FAILED; 4416 } 4417 } 4418 4419 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4420 } 4421 4422 private String getAppInstructionSet(ApplicationInfo info) { 4423 String instructionSet = getPreferredInstructionSet(); 4424 4425 if (info.requiredCpuAbi != null) { 4426 instructionSet = VMRuntime.getInstructionSet(info.requiredCpuAbi); 4427 } 4428 4429 return instructionSet; 4430 } 4431 4432 private String getAppInstructionSetFromSettings(PackageSetting ps) { 4433 String instructionSet = getPreferredInstructionSet(); 4434 4435 if (ps.requiredCpuAbiString != null) { 4436 instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString); 4437 } 4438 4439 return instructionSet; 4440 } 4441 4442 private static String getPreferredInstructionSet() { 4443 if (sPreferredInstructionSet == null) { 4444 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4445 } 4446 4447 return sPreferredInstructionSet; 4448 } 4449 4450 private static List<String> getAllInstructionSets() { 4451 final String[] allAbis = Build.SUPPORTED_ABIS; 4452 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4453 4454 for (String abi : allAbis) { 4455 final String instructionSet = VMRuntime.getInstructionSet(abi); 4456 if (!allInstructionSets.contains(instructionSet)) { 4457 allInstructionSets.add(instructionSet); 4458 } 4459 } 4460 4461 return allInstructionSets; 4462 } 4463 4464 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4465 boolean inclDependencies) { 4466 HashSet<String> done; 4467 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4468 done = new HashSet<String>(); 4469 done.add(pkg.packageName); 4470 } else { 4471 done = null; 4472 } 4473 return performDexOptLI(pkg, null /* instruction set override */, forceDex, defer, done); 4474 } 4475 4476 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4477 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4478 Slog.w(TAG, "Unable to update from " + oldPkg.name 4479 + " to " + newPkg.packageName 4480 + ": old package not in system partition"); 4481 return false; 4482 } else if (mPackages.get(oldPkg.name) != null) { 4483 Slog.w(TAG, "Unable to update from " + oldPkg.name 4484 + " to " + newPkg.packageName 4485 + ": old package still exists"); 4486 return false; 4487 } 4488 return true; 4489 } 4490 4491 File getDataPathForUser(int userId) { 4492 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4493 } 4494 4495 private File getDataPathForPackage(String packageName, int userId) { 4496 /* 4497 * Until we fully support multiple users, return the directory we 4498 * previously would have. The PackageManagerTests will need to be 4499 * revised when this is changed back.. 4500 */ 4501 if (userId == 0) { 4502 return new File(mAppDataDir, packageName); 4503 } else { 4504 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4505 + File.separator + packageName); 4506 } 4507 } 4508 4509 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4510 int[] users = sUserManager.getUserIds(); 4511 int res = mInstaller.install(packageName, uid, uid, seinfo); 4512 if (res < 0) { 4513 return res; 4514 } 4515 for (int user : users) { 4516 if (user != 0) { 4517 res = mInstaller.createUserData(packageName, 4518 UserHandle.getUid(user, uid), user, seinfo); 4519 if (res < 0) { 4520 return res; 4521 } 4522 } 4523 } 4524 return res; 4525 } 4526 4527 private int removeDataDirsLI(String packageName) { 4528 int[] users = sUserManager.getUserIds(); 4529 int res = 0; 4530 for (int user : users) { 4531 int resInner = mInstaller.remove(packageName, user); 4532 if (resInner < 0) { 4533 res = resInner; 4534 } 4535 } 4536 4537 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4538 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4539 if (!nativeLibraryFile.delete()) { 4540 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4541 } 4542 4543 return res; 4544 } 4545 4546 private int addSharedLibraryLPw(final SharedLibraryEntry file, int num, 4547 PackageParser.Package changingLib) { 4548 if (file.path != null) { 4549 mTmpSharedLibraries[num] = file.path; 4550 return num+1; 4551 } 4552 PackageParser.Package p = mPackages.get(file.apk); 4553 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4554 // If we are doing this while in the middle of updating a library apk, 4555 // then we need to make sure to use that new apk for determining the 4556 // dependencies here. (We haven't yet finished committing the new apk 4557 // to the package manager state.) 4558 if (p == null || p.packageName.equals(changingLib.packageName)) { 4559 p = changingLib; 4560 } 4561 } 4562 if (p != null) { 4563 String path = p.mPath; 4564 for (int i=0; i<num; i++) { 4565 if (mTmpSharedLibraries[i].equals(path)) { 4566 return num; 4567 } 4568 } 4569 mTmpSharedLibraries[num] = p.mPath; 4570 return num+1; 4571 } 4572 return num; 4573 } 4574 4575 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4576 PackageParser.Package changingLib) { 4577 // We might be upgrading from a version of the platform that did not 4578 // provide per-package native library directories for system apps. 4579 // Fix that up here. 4580 if (isSystemApp(pkg)) { 4581 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4582 setInternalAppNativeLibraryPath(pkg, ps); 4583 } 4584 4585 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4586 if (mTmpSharedLibraries == null || 4587 mTmpSharedLibraries.length < mSharedLibraries.size()) { 4588 mTmpSharedLibraries = new String[mSharedLibraries.size()]; 4589 } 4590 int num = 0; 4591 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4592 for (int i=0; i<N; i++) { 4593 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4594 if (file == null) { 4595 Slog.e(TAG, "Package " + pkg.packageName 4596 + " requires unavailable shared library " 4597 + pkg.usesLibraries.get(i) + "; failing!"); 4598 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4599 return false; 4600 } 4601 num = addSharedLibraryLPw(file, num, changingLib); 4602 } 4603 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4604 for (int i=0; i<N; i++) { 4605 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4606 if (file == null) { 4607 Slog.w(TAG, "Package " + pkg.packageName 4608 + " desires unavailable shared library " 4609 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4610 } else { 4611 num = addSharedLibraryLPw(file, num, changingLib); 4612 } 4613 } 4614 if (num > 0) { 4615 pkg.usesLibraryFiles = new String[num]; 4616 System.arraycopy(mTmpSharedLibraries, 0, 4617 pkg.usesLibraryFiles, 0, num); 4618 } else { 4619 pkg.usesLibraryFiles = null; 4620 } 4621 } 4622 return true; 4623 } 4624 4625 private static boolean hasString(List<String> list, List<String> which) { 4626 if (list == null) { 4627 return false; 4628 } 4629 for (int i=list.size()-1; i>=0; i--) { 4630 for (int j=which.size()-1; j>=0; j--) { 4631 if (which.get(j).equals(list.get(i))) { 4632 return true; 4633 } 4634 } 4635 } 4636 return false; 4637 } 4638 4639 private void updateAllSharedLibrariesLPw() { 4640 for (PackageParser.Package pkg : mPackages.values()) { 4641 updateSharedLibrariesLPw(pkg, null); 4642 } 4643 } 4644 4645 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4646 PackageParser.Package changingPkg) { 4647 ArrayList<PackageParser.Package> res = null; 4648 for (PackageParser.Package pkg : mPackages.values()) { 4649 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4650 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4651 if (res == null) { 4652 res = new ArrayList<PackageParser.Package>(); 4653 } 4654 res.add(pkg); 4655 updateSharedLibrariesLPw(pkg, changingPkg); 4656 } 4657 } 4658 return res; 4659 } 4660 4661 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4662 int parseFlags, int scanMode, long currentTime, UserHandle user) { 4663 File scanFile = new File(pkg.mScanPath); 4664 if (scanFile == null || pkg.applicationInfo.sourceDir == null || 4665 pkg.applicationInfo.publicSourceDir == null) { 4666 // Bail out. The resource and code paths haven't been set. 4667 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4668 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4669 return null; 4670 } 4671 4672 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4673 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4674 } 4675 4676 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4677 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4678 } 4679 4680 if (mCustomResolverComponentName != null && 4681 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4682 setUpCustomResolverActivity(pkg); 4683 } 4684 4685 if (pkg.packageName.equals("android")) { 4686 synchronized (mPackages) { 4687 if (mAndroidApplication != null) { 4688 Slog.w(TAG, "*************************************************"); 4689 Slog.w(TAG, "Core android package being redefined. Skipping."); 4690 Slog.w(TAG, " file=" + scanFile); 4691 Slog.w(TAG, "*************************************************"); 4692 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4693 return null; 4694 } 4695 4696 // Set up information for our fall-back user intent resolution activity. 4697 mPlatformPackage = pkg; 4698 pkg.mVersionCode = mSdkVersion; 4699 mAndroidApplication = pkg.applicationInfo; 4700 4701 if (!mResolverReplaced) { 4702 mResolveActivity.applicationInfo = mAndroidApplication; 4703 mResolveActivity.name = ResolverActivity.class.getName(); 4704 mResolveActivity.packageName = mAndroidApplication.packageName; 4705 mResolveActivity.processName = "system:ui"; 4706 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4707 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4708 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert; 4709 mResolveActivity.exported = true; 4710 mResolveActivity.enabled = true; 4711 mResolveInfo.activityInfo = mResolveActivity; 4712 mResolveInfo.priority = 0; 4713 mResolveInfo.preferredOrder = 0; 4714 mResolveInfo.match = 0; 4715 mResolveComponentName = new ComponentName( 4716 mAndroidApplication.packageName, mResolveActivity.name); 4717 } 4718 } 4719 } 4720 4721 if (DEBUG_PACKAGE_SCANNING) { 4722 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4723 Log.d(TAG, "Scanning package " + pkg.packageName); 4724 } 4725 4726 if (mPackages.containsKey(pkg.packageName) 4727 || mSharedLibraries.containsKey(pkg.packageName)) { 4728 Slog.w(TAG, "Application package " + pkg.packageName 4729 + " already installed. Skipping duplicate."); 4730 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4731 return null; 4732 } 4733 4734 // Initialize package source and resource directories 4735 File destCodeFile = new File(pkg.applicationInfo.sourceDir); 4736 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir); 4737 4738 SharedUserSetting suid = null; 4739 PackageSetting pkgSetting = null; 4740 4741 if (!isSystemApp(pkg)) { 4742 // Only system apps can use these features. 4743 pkg.mOriginalPackages = null; 4744 pkg.mRealPackage = null; 4745 pkg.mAdoptPermissions = null; 4746 } 4747 4748 // writer 4749 synchronized (mPackages) { 4750 if (pkg.mSharedUserId != null) { 4751 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 4752 if (suid == null) { 4753 Slog.w(TAG, "Creating application package " + pkg.packageName 4754 + " for shared user failed"); 4755 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4756 return null; 4757 } 4758 if (DEBUG_PACKAGE_SCANNING) { 4759 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4760 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 4761 + "): packages=" + suid.packages); 4762 } 4763 } 4764 4765 // Check if we are renaming from an original package name. 4766 PackageSetting origPackage = null; 4767 String realName = null; 4768 if (pkg.mOriginalPackages != null) { 4769 // This package may need to be renamed to a previously 4770 // installed name. Let's check on that... 4771 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 4772 if (pkg.mOriginalPackages.contains(renamed)) { 4773 // This package had originally been installed as the 4774 // original name, and we have already taken care of 4775 // transitioning to the new one. Just update the new 4776 // one to continue using the old name. 4777 realName = pkg.mRealPackage; 4778 if (!pkg.packageName.equals(renamed)) { 4779 // Callers into this function may have already taken 4780 // care of renaming the package; only do it here if 4781 // it is not already done. 4782 pkg.setPackageName(renamed); 4783 } 4784 4785 } else { 4786 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 4787 if ((origPackage = mSettings.peekPackageLPr( 4788 pkg.mOriginalPackages.get(i))) != null) { 4789 // We do have the package already installed under its 4790 // original name... should we use it? 4791 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 4792 // New package is not compatible with original. 4793 origPackage = null; 4794 continue; 4795 } else if (origPackage.sharedUser != null) { 4796 // Make sure uid is compatible between packages. 4797 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 4798 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 4799 + " to " + pkg.packageName + ": old uid " 4800 + origPackage.sharedUser.name 4801 + " differs from " + pkg.mSharedUserId); 4802 origPackage = null; 4803 continue; 4804 } 4805 } else { 4806 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 4807 + pkg.packageName + " to old name " + origPackage.name); 4808 } 4809 break; 4810 } 4811 } 4812 } 4813 } 4814 4815 if (mTransferedPackages.contains(pkg.packageName)) { 4816 Slog.w(TAG, "Package " + pkg.packageName 4817 + " was transferred to another, but its .apk remains"); 4818 } 4819 4820 // Just create the setting, don't add it yet. For already existing packages 4821 // the PkgSetting exists already and doesn't have to be created. 4822 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 4823 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 4824 pkg.applicationInfo.requiredCpuAbi, 4825 pkg.applicationInfo.flags, user, false); 4826 if (pkgSetting == null) { 4827 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 4828 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4829 return null; 4830 } 4831 4832 if (pkgSetting.origPackage != null) { 4833 // If we are first transitioning from an original package, 4834 // fix up the new package's name now. We need to do this after 4835 // looking up the package under its new name, so getPackageLP 4836 // can take care of fiddling things correctly. 4837 pkg.setPackageName(origPackage.name); 4838 4839 // File a report about this. 4840 String msg = "New package " + pkgSetting.realName 4841 + " renamed to replace old package " + pkgSetting.name; 4842 reportSettingsProblem(Log.WARN, msg); 4843 4844 // Make a note of it. 4845 mTransferedPackages.add(origPackage.name); 4846 4847 // No longer need to retain this. 4848 pkgSetting.origPackage = null; 4849 } 4850 4851 if (realName != null) { 4852 // Make a note of it. 4853 mTransferedPackages.add(pkg.packageName); 4854 } 4855 4856 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 4857 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 4858 } 4859 4860 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4861 // Check all shared libraries and map to their actual file path. 4862 // We only do this here for apps not on a system dir, because those 4863 // are the only ones that can fail an install due to this. We 4864 // will take care of the system apps by updating all of their 4865 // library paths after the scan is done. 4866 if (!updateSharedLibrariesLPw(pkg, null)) { 4867 return null; 4868 } 4869 } 4870 4871 if (mFoundPolicyFile) { 4872 SELinuxMMAC.assignSeinfoValue(pkg); 4873 } 4874 4875 pkg.applicationInfo.uid = pkgSetting.appId; 4876 pkg.mExtras = pkgSetting; 4877 4878 if (!verifySignaturesLP(pkgSetting, pkg)) { 4879 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4880 return null; 4881 } 4882 // The signature has changed, but this package is in the system 4883 // image... let's recover! 4884 pkgSetting.signatures.mSignatures = pkg.mSignatures; 4885 // However... if this package is part of a shared user, but it 4886 // doesn't match the signature of the shared user, let's fail. 4887 // What this means is that you can't change the signatures 4888 // associated with an overall shared user, which doesn't seem all 4889 // that unreasonable. 4890 if (pkgSetting.sharedUser != null) { 4891 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4892 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 4893 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 4894 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 4895 return null; 4896 } 4897 } 4898 // File a report about this. 4899 String msg = "System package " + pkg.packageName 4900 + " signature changed; retaining data."; 4901 reportSettingsProblem(Log.WARN, msg); 4902 } 4903 4904 // Verify that this new package doesn't have any content providers 4905 // that conflict with existing packages. Only do this if the 4906 // package isn't already installed, since we don't want to break 4907 // things that are installed. 4908 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 4909 final int N = pkg.providers.size(); 4910 int i; 4911 for (i=0; i<N; i++) { 4912 PackageParser.Provider p = pkg.providers.get(i); 4913 if (p.info.authority != null) { 4914 String names[] = p.info.authority.split(";"); 4915 for (int j = 0; j < names.length; j++) { 4916 if (mProvidersByAuthority.containsKey(names[j])) { 4917 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 4918 Slog.w(TAG, "Can't install because provider name " + names[j] + 4919 " (in package " + pkg.applicationInfo.packageName + 4920 ") is already used by " 4921 + ((other != null && other.getComponentName() != null) 4922 ? other.getComponentName().getPackageName() : "?")); 4923 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 4924 return null; 4925 } 4926 } 4927 } 4928 } 4929 } 4930 4931 if (pkg.mAdoptPermissions != null) { 4932 // This package wants to adopt ownership of permissions from 4933 // another package. 4934 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 4935 final String origName = pkg.mAdoptPermissions.get(i); 4936 final PackageSetting orig = mSettings.peekPackageLPr(origName); 4937 if (orig != null) { 4938 if (verifyPackageUpdateLPr(orig, pkg)) { 4939 Slog.i(TAG, "Adopting permissions from " + origName + " to " 4940 + pkg.packageName); 4941 mSettings.transferPermissionsLPw(origName, pkg.packageName); 4942 } 4943 } 4944 } 4945 } 4946 } 4947 4948 final String pkgName = pkg.packageName; 4949 4950 final long scanFileTime = scanFile.lastModified(); 4951 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 4952 pkg.applicationInfo.processName = fixProcessName( 4953 pkg.applicationInfo.packageName, 4954 pkg.applicationInfo.processName, 4955 pkg.applicationInfo.uid); 4956 4957 File dataPath; 4958 if (mPlatformPackage == pkg) { 4959 // The system package is special. 4960 dataPath = new File (Environment.getDataDirectory(), "system"); 4961 pkg.applicationInfo.dataDir = dataPath.getPath(); 4962 } else { 4963 // This is a normal package, need to make its data directory. 4964 dataPath = getDataPathForPackage(pkg.packageName, 0); 4965 4966 boolean uidError = false; 4967 4968 if (dataPath.exists()) { 4969 int currentUid = 0; 4970 try { 4971 StructStat stat = Os.stat(dataPath.getPath()); 4972 currentUid = stat.st_uid; 4973 } catch (ErrnoException e) { 4974 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 4975 } 4976 4977 // If we have mismatched owners for the data path, we have a problem. 4978 if (currentUid != pkg.applicationInfo.uid) { 4979 boolean recovered = false; 4980 if (currentUid == 0) { 4981 // The directory somehow became owned by root. Wow. 4982 // This is probably because the system was stopped while 4983 // installd was in the middle of messing with its libs 4984 // directory. Ask installd to fix that. 4985 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 4986 pkg.applicationInfo.uid); 4987 if (ret >= 0) { 4988 recovered = true; 4989 String msg = "Package " + pkg.packageName 4990 + " unexpectedly changed to uid 0; recovered to " + 4991 + pkg.applicationInfo.uid; 4992 reportSettingsProblem(Log.WARN, msg); 4993 } 4994 } 4995 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 4996 || (scanMode&SCAN_BOOTING) != 0)) { 4997 // If this is a system app, we can at least delete its 4998 // current data so the application will still work. 4999 int ret = removeDataDirsLI(pkgName); 5000 if (ret >= 0) { 5001 // TODO: Kill the processes first 5002 // Old data gone! 5003 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5004 ? "System package " : "Third party package "; 5005 String msg = prefix + pkg.packageName 5006 + " has changed from uid: " 5007 + currentUid + " to " 5008 + pkg.applicationInfo.uid + "; old data erased"; 5009 reportSettingsProblem(Log.WARN, msg); 5010 recovered = true; 5011 5012 // And now re-install the app. 5013 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5014 pkg.applicationInfo.seinfo); 5015 if (ret == -1) { 5016 // Ack should not happen! 5017 msg = prefix + pkg.packageName 5018 + " could not have data directory re-created after delete."; 5019 reportSettingsProblem(Log.WARN, msg); 5020 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5021 return null; 5022 } 5023 } 5024 if (!recovered) { 5025 mHasSystemUidErrors = true; 5026 } 5027 } else if (!recovered) { 5028 // If we allow this install to proceed, we will be broken. 5029 // Abort, abort! 5030 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 5031 return null; 5032 } 5033 if (!recovered) { 5034 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5035 + pkg.applicationInfo.uid + "/fs_" 5036 + currentUid; 5037 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5038 String msg = "Package " + pkg.packageName 5039 + " has mismatched uid: " 5040 + currentUid + " on disk, " 5041 + pkg.applicationInfo.uid + " in settings"; 5042 // writer 5043 synchronized (mPackages) { 5044 mSettings.mReadMessages.append(msg); 5045 mSettings.mReadMessages.append('\n'); 5046 uidError = true; 5047 if (!pkgSetting.uidError) { 5048 reportSettingsProblem(Log.ERROR, msg); 5049 } 5050 } 5051 } 5052 } 5053 pkg.applicationInfo.dataDir = dataPath.getPath(); 5054 if (mShouldRestoreconData) { 5055 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5056 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5057 pkg.applicationInfo.uid); 5058 } 5059 } else { 5060 if (DEBUG_PACKAGE_SCANNING) { 5061 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5062 Log.v(TAG, "Want this data dir: " + dataPath); 5063 } 5064 //invoke installer to do the actual installation 5065 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5066 pkg.applicationInfo.seinfo); 5067 if (ret < 0) { 5068 // Error from installer 5069 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5070 return null; 5071 } 5072 5073 if (dataPath.exists()) { 5074 pkg.applicationInfo.dataDir = dataPath.getPath(); 5075 } else { 5076 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5077 pkg.applicationInfo.dataDir = null; 5078 } 5079 } 5080 5081 /* 5082 * Set the data dir to the default "/data/data/<package name>/lib" 5083 * if we got here without anyone telling us different (e.g., apps 5084 * stored on SD card have their native libraries stored in the ASEC 5085 * container with the APK). 5086 * 5087 * This happens during an upgrade from a package settings file that 5088 * doesn't have a native library path attribute at all. 5089 */ 5090 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 5091 if (pkgSetting.nativeLibraryPathString == null) { 5092 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5093 } else { 5094 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 5095 } 5096 } 5097 pkgSetting.uidError = uidError; 5098 } 5099 5100 String path = scanFile.getPath(); 5101 /* Note: We don't want to unpack the native binaries for 5102 * system applications, unless they have been updated 5103 * (the binaries are already under /system/lib). 5104 * Also, don't unpack libs for apps on the external card 5105 * since they should have their libraries in the ASEC 5106 * container already. 5107 * 5108 * In other words, we're going to unpack the binaries 5109 * only for non-system apps and system app upgrades. 5110 */ 5111 if (pkg.applicationInfo.nativeLibraryDir != null) { 5112 try { 5113 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5114 final String dataPathString = dataPath.getCanonicalPath(); 5115 5116 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5117 /* 5118 * Upgrading from a previous version of the OS sometimes 5119 * leaves native libraries in the /data/data/<app>/lib 5120 * directory for system apps even when they shouldn't be. 5121 * Recent changes in the JNI library search path 5122 * necessitates we remove those to match previous behavior. 5123 */ 5124 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 5125 Log.i(TAG, "removed obsolete native libraries for system package " 5126 + path); 5127 } 5128 5129 setInternalAppAbi(pkg, pkgSetting); 5130 } else { 5131 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 5132 /* 5133 * Update native library dir if it starts with 5134 * /data/data 5135 */ 5136 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 5137 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5138 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5139 } 5140 5141 try { 5142 int copyRet = copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir); 5143 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5144 Slog.e(TAG, "Unable to copy native libraries"); 5145 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5146 return null; 5147 } 5148 5149 // We've successfully copied native libraries across, so we make a 5150 // note of what ABI we're using 5151 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5152 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[copyRet]; 5153 } else { 5154 pkg.applicationInfo.requiredCpuAbi = null; 5155 } 5156 } catch (IOException e) { 5157 Slog.e(TAG, "Unable to copy native libraries", e); 5158 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5159 return null; 5160 } 5161 } else { 5162 // We don't have to copy the shared libraries if we're in the ASEC container 5163 // but we still need to scan the file to figure out what ABI the app needs. 5164 // 5165 // TODO: This duplicates work done in the default container service. It's possible 5166 // to clean this up but we'll need to change the interface between this service 5167 // and IMediaContainerService (but doing so will spread this logic out, rather 5168 // than centralizing it). 5169 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile); 5170 final int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS); 5171 if (abi >= 0) { 5172 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[abi]; 5173 } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) { 5174 // Note that (non upgraded) system apps will not have any native 5175 // libraries bundled in their APK, but we're guaranteed not to be 5176 // such an app at this point. 5177 pkg.applicationInfo.requiredCpuAbi = null; 5178 } else { 5179 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5180 return null; 5181 } 5182 handle.close(); 5183 } 5184 5185 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5186 final int[] userIds = sUserManager.getUserIds(); 5187 synchronized (mInstallLock) { 5188 for (int userId : userIds) { 5189 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 5190 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 5191 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5192 + ")"); 5193 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5194 return null; 5195 } 5196 } 5197 } 5198 } 5199 } catch (IOException ioe) { 5200 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5201 } 5202 } 5203 pkg.mScanPath = path; 5204 5205 if ((scanMode&SCAN_NO_DEX) == 0) { 5206 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5207 == DEX_OPT_FAILED) { 5208 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5209 removeDataDirsLI(pkg.packageName); 5210 } 5211 5212 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5213 return null; 5214 } 5215 } 5216 5217 if (mFactoryTest && pkg.requestedPermissions.contains( 5218 android.Manifest.permission.FACTORY_TEST)) { 5219 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5220 } 5221 5222 ArrayList<PackageParser.Package> clientLibPkgs = null; 5223 5224 // writer 5225 synchronized (mPackages) { 5226 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5227 // Only system apps can add new shared libraries. 5228 if (pkg.libraryNames != null) { 5229 for (int i=0; i<pkg.libraryNames.size(); i++) { 5230 String name = pkg.libraryNames.get(i); 5231 boolean allowed = false; 5232 if (isUpdatedSystemApp(pkg)) { 5233 // New library entries can only be added through the 5234 // system image. This is important to get rid of a lot 5235 // of nasty edge cases: for example if we allowed a non- 5236 // system update of the app to add a library, then uninstalling 5237 // the update would make the library go away, and assumptions 5238 // we made such as through app install filtering would now 5239 // have allowed apps on the device which aren't compatible 5240 // with it. Better to just have the restriction here, be 5241 // conservative, and create many fewer cases that can negatively 5242 // impact the user experience. 5243 final PackageSetting sysPs = mSettings 5244 .getDisabledSystemPkgLPr(pkg.packageName); 5245 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5246 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5247 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5248 allowed = true; 5249 allowed = true; 5250 break; 5251 } 5252 } 5253 } 5254 } else { 5255 allowed = true; 5256 } 5257 if (allowed) { 5258 if (!mSharedLibraries.containsKey(name)) { 5259 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5260 } else if (!name.equals(pkg.packageName)) { 5261 Slog.w(TAG, "Package " + pkg.packageName + " library " 5262 + name + " already exists; skipping"); 5263 } 5264 } else { 5265 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5266 + name + " that is not declared on system image; skipping"); 5267 } 5268 } 5269 if ((scanMode&SCAN_BOOTING) == 0) { 5270 // If we are not booting, we need to update any applications 5271 // that are clients of our shared library. If we are booting, 5272 // this will all be done once the scan is complete. 5273 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5274 } 5275 } 5276 } 5277 } 5278 5279 // We also need to dexopt any apps that are dependent on this library. Note that 5280 // if these fail, we should abort the install since installing the library will 5281 // result in some apps being broken. 5282 if (clientLibPkgs != null) { 5283 if ((scanMode&SCAN_NO_DEX) == 0) { 5284 for (int i=0; i<clientLibPkgs.size(); i++) { 5285 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5286 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5287 == DEX_OPT_FAILED) { 5288 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5289 removeDataDirsLI(pkg.packageName); 5290 } 5291 5292 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5293 return null; 5294 } 5295 } 5296 } 5297 } 5298 5299 // Request the ActivityManager to kill the process(only for existing packages) 5300 // so that we do not end up in a confused state while the user is still using the older 5301 // version of the application while the new one gets installed. 5302 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5303 // If the package lives in an asec, tell everyone that the container is going 5304 // away so they can clean up any references to its resources (which would prevent 5305 // vold from being able to unmount the asec) 5306 if (isForwardLocked(pkg) || isExternal(pkg)) { 5307 if (DEBUG_INSTALL) { 5308 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5309 } 5310 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5311 final ArrayList<String> pkgList = new ArrayList<String>(1); 5312 pkgList.add(pkg.applicationInfo.packageName); 5313 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5314 } 5315 5316 // Post the request that it be killed now that the going-away broadcast is en route 5317 killApplication(pkg.applicationInfo.packageName, 5318 pkg.applicationInfo.uid, "update pkg"); 5319 } 5320 5321 // Also need to kill any apps that are dependent on the library. 5322 if (clientLibPkgs != null) { 5323 for (int i=0; i<clientLibPkgs.size(); i++) { 5324 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5325 killApplication(clientPkg.applicationInfo.packageName, 5326 clientPkg.applicationInfo.uid, "update lib"); 5327 } 5328 } 5329 5330 // writer 5331 synchronized (mPackages) { 5332 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5333 // We don't do this here during boot because we can do it all 5334 // at once after scanning all existing packages. 5335 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5336 true, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5337 } 5338 // We don't expect installation to fail beyond this point, 5339 if ((scanMode&SCAN_MONITOR) != 0) { 5340 mAppDirs.put(pkg.mPath, pkg); 5341 } 5342 // Add the new setting to mSettings 5343 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5344 // Add the new setting to mPackages 5345 mPackages.put(pkg.applicationInfo.packageName, pkg); 5346 // Make sure we don't accidentally delete its data. 5347 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5348 while (iter.hasNext()) { 5349 PackageCleanItem item = iter.next(); 5350 if (pkgName.equals(item.packageName)) { 5351 iter.remove(); 5352 } 5353 } 5354 5355 // Take care of first install / last update times. 5356 if (currentTime != 0) { 5357 if (pkgSetting.firstInstallTime == 0) { 5358 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5359 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5360 pkgSetting.lastUpdateTime = currentTime; 5361 } 5362 } else if (pkgSetting.firstInstallTime == 0) { 5363 // We need *something*. Take time time stamp of the file. 5364 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5365 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5366 if (scanFileTime != pkgSetting.timeStamp) { 5367 // A package on the system image has changed; consider this 5368 // to be an update. 5369 pkgSetting.lastUpdateTime = scanFileTime; 5370 } 5371 } 5372 5373 // Add the package's KeySets to the global KeySetManager 5374 KeySetManager ksm = mSettings.mKeySetManager; 5375 try { 5376 ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5377 if (pkg.mKeySetMapping != null) { 5378 for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) { 5379 if (entry.getValue() != null) { 5380 ksm.addDefinedKeySetToPackage(pkg.packageName, 5381 entry.getValue(), entry.getKey()); 5382 } 5383 } 5384 } 5385 } catch (NullPointerException e) { 5386 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5387 } catch (IllegalArgumentException e) { 5388 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5389 } 5390 5391 int N = pkg.providers.size(); 5392 StringBuilder r = null; 5393 int i; 5394 for (i=0; i<N; i++) { 5395 PackageParser.Provider p = pkg.providers.get(i); 5396 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5397 p.info.processName, pkg.applicationInfo.uid); 5398 mProviders.addProvider(p); 5399 p.syncable = p.info.isSyncable; 5400 if (p.info.authority != null) { 5401 String names[] = p.info.authority.split(";"); 5402 p.info.authority = null; 5403 for (int j = 0; j < names.length; j++) { 5404 if (j == 1 && p.syncable) { 5405 // We only want the first authority for a provider to possibly be 5406 // syncable, so if we already added this provider using a different 5407 // authority clear the syncable flag. We copy the provider before 5408 // changing it because the mProviders object contains a reference 5409 // to a provider that we don't want to change. 5410 // Only do this for the second authority since the resulting provider 5411 // object can be the same for all future authorities for this provider. 5412 p = new PackageParser.Provider(p); 5413 p.syncable = false; 5414 } 5415 if (!mProvidersByAuthority.containsKey(names[j])) { 5416 mProvidersByAuthority.put(names[j], p); 5417 if (p.info.authority == null) { 5418 p.info.authority = names[j]; 5419 } else { 5420 p.info.authority = p.info.authority + ";" + names[j]; 5421 } 5422 if (DEBUG_PACKAGE_SCANNING) { 5423 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5424 Log.d(TAG, "Registered content provider: " + names[j] 5425 + ", className = " + p.info.name + ", isSyncable = " 5426 + p.info.isSyncable); 5427 } 5428 } else { 5429 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5430 Slog.w(TAG, "Skipping provider name " + names[j] + 5431 " (in package " + pkg.applicationInfo.packageName + 5432 "): name already used by " 5433 + ((other != null && other.getComponentName() != null) 5434 ? other.getComponentName().getPackageName() : "?")); 5435 } 5436 } 5437 } 5438 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5439 if (r == null) { 5440 r = new StringBuilder(256); 5441 } else { 5442 r.append(' '); 5443 } 5444 r.append(p.info.name); 5445 } 5446 } 5447 if (r != null) { 5448 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5449 } 5450 5451 N = pkg.services.size(); 5452 r = null; 5453 for (i=0; i<N; i++) { 5454 PackageParser.Service s = pkg.services.get(i); 5455 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5456 s.info.processName, pkg.applicationInfo.uid); 5457 mServices.addService(s); 5458 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5459 if (r == null) { 5460 r = new StringBuilder(256); 5461 } else { 5462 r.append(' '); 5463 } 5464 r.append(s.info.name); 5465 } 5466 } 5467 if (r != null) { 5468 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5469 } 5470 5471 N = pkg.receivers.size(); 5472 r = null; 5473 for (i=0; i<N; i++) { 5474 PackageParser.Activity a = pkg.receivers.get(i); 5475 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5476 a.info.processName, pkg.applicationInfo.uid); 5477 mReceivers.addActivity(a, "receiver"); 5478 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5479 if (r == null) { 5480 r = new StringBuilder(256); 5481 } else { 5482 r.append(' '); 5483 } 5484 r.append(a.info.name); 5485 } 5486 } 5487 if (r != null) { 5488 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5489 } 5490 5491 N = pkg.activities.size(); 5492 r = null; 5493 for (i=0; i<N; i++) { 5494 PackageParser.Activity a = pkg.activities.get(i); 5495 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5496 a.info.processName, pkg.applicationInfo.uid); 5497 mActivities.addActivity(a, "activity"); 5498 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5499 if (r == null) { 5500 r = new StringBuilder(256); 5501 } else { 5502 r.append(' '); 5503 } 5504 r.append(a.info.name); 5505 } 5506 } 5507 if (r != null) { 5508 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5509 } 5510 5511 N = pkg.permissionGroups.size(); 5512 r = null; 5513 for (i=0; i<N; i++) { 5514 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5515 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5516 if (cur == null) { 5517 mPermissionGroups.put(pg.info.name, pg); 5518 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5519 if (r == null) { 5520 r = new StringBuilder(256); 5521 } else { 5522 r.append(' '); 5523 } 5524 r.append(pg.info.name); 5525 } 5526 } else { 5527 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5528 + pg.info.packageName + " ignored: original from " 5529 + cur.info.packageName); 5530 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5531 if (r == null) { 5532 r = new StringBuilder(256); 5533 } else { 5534 r.append(' '); 5535 } 5536 r.append("DUP:"); 5537 r.append(pg.info.name); 5538 } 5539 } 5540 } 5541 if (r != null) { 5542 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5543 } 5544 5545 N = pkg.permissions.size(); 5546 r = null; 5547 for (i=0; i<N; i++) { 5548 PackageParser.Permission p = pkg.permissions.get(i); 5549 HashMap<String, BasePermission> permissionMap = 5550 p.tree ? mSettings.mPermissionTrees 5551 : mSettings.mPermissions; 5552 p.group = mPermissionGroups.get(p.info.group); 5553 if (p.info.group == null || p.group != null) { 5554 BasePermission bp = permissionMap.get(p.info.name); 5555 if (bp == null) { 5556 bp = new BasePermission(p.info.name, p.info.packageName, 5557 BasePermission.TYPE_NORMAL); 5558 permissionMap.put(p.info.name, bp); 5559 } 5560 if (bp.perm == null) { 5561 if (bp.sourcePackage != null 5562 && !bp.sourcePackage.equals(p.info.packageName)) { 5563 // If this is a permission that was formerly defined by a non-system 5564 // app, but is now defined by a system app (following an upgrade), 5565 // discard the previous declaration and consider the system's to be 5566 // canonical. 5567 if (isSystemApp(p.owner)) { 5568 String msg = "New decl " + p.owner + " of permission " 5569 + p.info.name + " is system"; 5570 reportSettingsProblem(Log.WARN, msg); 5571 bp.sourcePackage = null; 5572 } 5573 } 5574 if (bp.sourcePackage == null 5575 || bp.sourcePackage.equals(p.info.packageName)) { 5576 BasePermission tree = findPermissionTreeLP(p.info.name); 5577 if (tree == null 5578 || tree.sourcePackage.equals(p.info.packageName)) { 5579 bp.packageSetting = pkgSetting; 5580 bp.perm = p; 5581 bp.uid = pkg.applicationInfo.uid; 5582 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5583 if (r == null) { 5584 r = new StringBuilder(256); 5585 } else { 5586 r.append(' '); 5587 } 5588 r.append(p.info.name); 5589 } 5590 } else { 5591 Slog.w(TAG, "Permission " + p.info.name + " from package " 5592 + p.info.packageName + " ignored: base tree " 5593 + tree.name + " is from package " 5594 + tree.sourcePackage); 5595 } 5596 } else { 5597 Slog.w(TAG, "Permission " + p.info.name + " from package " 5598 + p.info.packageName + " ignored: original from " 5599 + bp.sourcePackage); 5600 } 5601 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5602 if (r == null) { 5603 r = new StringBuilder(256); 5604 } else { 5605 r.append(' '); 5606 } 5607 r.append("DUP:"); 5608 r.append(p.info.name); 5609 } 5610 if (bp.perm == p) { 5611 bp.protectionLevel = p.info.protectionLevel; 5612 } 5613 } else { 5614 Slog.w(TAG, "Permission " + p.info.name + " from package " 5615 + p.info.packageName + " ignored: no group " 5616 + p.group); 5617 } 5618 } 5619 if (r != null) { 5620 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5621 } 5622 5623 N = pkg.instrumentation.size(); 5624 r = null; 5625 for (i=0; i<N; i++) { 5626 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5627 a.info.packageName = pkg.applicationInfo.packageName; 5628 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5629 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5630 a.info.dataDir = pkg.applicationInfo.dataDir; 5631 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5632 mInstrumentation.put(a.getComponentName(), a); 5633 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5634 if (r == null) { 5635 r = new StringBuilder(256); 5636 } else { 5637 r.append(' '); 5638 } 5639 r.append(a.info.name); 5640 } 5641 } 5642 if (r != null) { 5643 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5644 } 5645 5646 if (pkg.protectedBroadcasts != null) { 5647 N = pkg.protectedBroadcasts.size(); 5648 for (i=0; i<N; i++) { 5649 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5650 } 5651 } 5652 5653 pkgSetting.setTimeStamp(scanFileTime); 5654 5655 // Create idmap files for pairs of (packages, overlay packages). 5656 // Note: "android", ie framework-res.apk, is handled by native layers. 5657 if (pkg.mOverlayTarget != null) { 5658 // This is an overlay package. 5659 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 5660 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 5661 mOverlays.put(pkg.mOverlayTarget, 5662 new HashMap<String, PackageParser.Package>()); 5663 } 5664 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 5665 map.put(pkg.packageName, pkg); 5666 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 5667 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 5668 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5669 return null; 5670 } 5671 } 5672 } else if (mOverlays.containsKey(pkg.packageName) && 5673 !pkg.packageName.equals("android")) { 5674 // This is a regular package, with one or more known overlay packages. 5675 createIdmapsForPackageLI(pkg); 5676 } 5677 } 5678 5679 return pkg; 5680 } 5681 5682 public void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 5683 boolean doDexOpt, boolean forceDexOpt, boolean deferDexOpt) { 5684 String requiredInstructionSet = null; 5685 PackageSetting requirer = null; 5686 for (PackageSetting ps : packagesForUser) { 5687 if (ps.requiredCpuAbiString != null) { 5688 final String instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString); 5689 if (requiredInstructionSet != null) { 5690 if (!instructionSet.equals(requiredInstructionSet)) { 5691 // We have a mismatch between instruction sets (say arm vs arm64). 5692 // 5693 // TODO: We should rescan all the packages in a shared UID to check if 5694 // they do contain shared libs for other ABIs in addition to the ones we've 5695 // already extracted. For example, the package might contain both arm64-v8a 5696 // and armeabi-v7a shared libs, and we'd have chosen arm64-v8a on 64 bit 5697 // devices. 5698 String errorMessage = "Instruction set mismatch, " + requirer.pkg.packageName 5699 + " requires " + requiredInstructionSet + " whereas " + ps.pkg.packageName 5700 + " requires " + instructionSet; 5701 Slog.e(TAG, errorMessage); 5702 5703 reportSettingsProblem(Log.WARN, errorMessage); 5704 // Give up, don't bother making any other changes to the package settings. 5705 return; 5706 } 5707 } else { 5708 requiredInstructionSet = instructionSet; 5709 requirer = ps; 5710 } 5711 } 5712 } 5713 5714 if (requiredInstructionSet != null) { 5715 for (PackageSetting ps : packagesForUser) { 5716 if (ps.requiredCpuAbiString == null) { 5717 ps.requiredCpuAbiString = requirer.requiredCpuAbiString; 5718 if (ps.pkg != null) { 5719 ps.pkg.applicationInfo.requiredCpuAbi = requirer.requiredCpuAbiString; 5720 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + ps.requiredCpuAbiString); 5721 if (doDexOpt) { 5722 performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true); 5723 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 5724 } 5725 } 5726 } 5727 } 5728 } 5729 } 5730 5731 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 5732 synchronized (mPackages) { 5733 mResolverReplaced = true; 5734 // Set up information for custom user intent resolution activity. 5735 mResolveActivity.applicationInfo = pkg.applicationInfo; 5736 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 5737 mResolveActivity.packageName = pkg.applicationInfo.packageName; 5738 mResolveActivity.processName = null; 5739 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5740 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 5741 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 5742 mResolveActivity.theme = 0; 5743 mResolveActivity.exported = true; 5744 mResolveActivity.enabled = true; 5745 mResolveInfo.activityInfo = mResolveActivity; 5746 mResolveInfo.priority = 0; 5747 mResolveInfo.preferredOrder = 0; 5748 mResolveInfo.match = 0; 5749 mResolveComponentName = mCustomResolverComponentName; 5750 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 5751 mResolveComponentName); 5752 } 5753 } 5754 5755 private String calculateApkRoot(final String codePathString) { 5756 final File codePath = new File(codePathString); 5757 final File codeRoot; 5758 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 5759 codeRoot = Environment.getRootDirectory(); 5760 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 5761 codeRoot = Environment.getOemDirectory(); 5762 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 5763 codeRoot = Environment.getVendorDirectory(); 5764 } else { 5765 // Unrecognized code path; take its top real segment as the apk root: 5766 // e.g. /something/app/blah.apk => /something 5767 try { 5768 File f = codePath.getCanonicalFile(); 5769 File parent = f.getParentFile(); // non-null because codePath is a file 5770 File tmp; 5771 while ((tmp = parent.getParentFile()) != null) { 5772 f = parent; 5773 parent = tmp; 5774 } 5775 codeRoot = f; 5776 Slog.w(TAG, "Unrecognized code path " 5777 + codePath + " - using " + codeRoot); 5778 } catch (IOException e) { 5779 // Can't canonicalize the lib path -- shenanigans? 5780 Slog.w(TAG, "Can't canonicalize code path " + codePath); 5781 return Environment.getRootDirectory().getPath(); 5782 } 5783 } 5784 return codeRoot.getPath(); 5785 } 5786 5787 // This is the initial scan-time determination of how to handle a given 5788 // package for purposes of native library location. 5789 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 5790 PackageSetting pkgSetting) { 5791 // "bundled" here means system-installed with no overriding update 5792 final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg); 5793 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 5794 final File libDir; 5795 if (bundledApk) { 5796 // If "/system/lib64/apkname" exists, assume that is the per-package 5797 // native library directory to use; otherwise use "/system/lib/apkname". 5798 String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 5799 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 5800 File packLib64 = new File(lib64, apkName); 5801 libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 5802 } else { 5803 libDir = mAppLibInstallDir; 5804 } 5805 final String nativeLibraryPath = (new File(libDir, apkName)).getPath(); 5806 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 5807 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 5808 } 5809 5810 // Deduces the required ABI of an upgraded system app. 5811 private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) { 5812 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 5813 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 5814 5815 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 5816 // or similar. 5817 final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath()); 5818 final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath()); 5819 5820 // Assume that the bundled native libraries always correspond to the 5821 // most preferred 32 or 64 bit ABI. 5822 if (lib64.exists()) { 5823 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 5824 pkgSetting.requiredCpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0]; 5825 } else if (lib.exists()) { 5826 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5827 pkgSetting.requiredCpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0]; 5828 } else { 5829 // This is the case where the app has no native code. 5830 pkg.applicationInfo.requiredCpuAbi = null; 5831 pkgSetting.requiredCpuAbiString = null; 5832 } 5833 } 5834 5835 private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir) 5836 throws IOException { 5837 if (!nativeLibraryDir.isDirectory()) { 5838 nativeLibraryDir.delete(); 5839 5840 if (!nativeLibraryDir.mkdir()) { 5841 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 5842 } 5843 5844 try { 5845 Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 5846 } catch (ErrnoException e) { 5847 throw new IOException("Cannot chmod native library directory " 5848 + nativeLibraryDir.getPath(), e); 5849 } 5850 } else if (!SELinux.restorecon(nativeLibraryDir)) { 5851 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 5852 } 5853 5854 /* 5855 * If this is an internal application or our nativeLibraryPath points to 5856 * the app-lib directory, unpack the libraries if necessary. 5857 */ 5858 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile); 5859 try { 5860 int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS); 5861 if (abi >= 0) { 5862 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 5863 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 5864 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 5865 return copyRet; 5866 } 5867 } 5868 5869 return abi; 5870 } finally { 5871 handle.close(); 5872 } 5873 } 5874 5875 private void killApplication(String pkgName, int appId, String reason) { 5876 // Request the ActivityManager to kill the process(only for existing packages) 5877 // so that we do not end up in a confused state while the user is still using the older 5878 // version of the application while the new one gets installed. 5879 IActivityManager am = ActivityManagerNative.getDefault(); 5880 if (am != null) { 5881 try { 5882 am.killApplicationWithAppId(pkgName, appId, reason); 5883 } catch (RemoteException e) { 5884 } 5885 } 5886 } 5887 5888 void removePackageLI(PackageSetting ps, boolean chatty) { 5889 if (DEBUG_INSTALL) { 5890 if (chatty) 5891 Log.d(TAG, "Removing package " + ps.name); 5892 } 5893 5894 // writer 5895 synchronized (mPackages) { 5896 mPackages.remove(ps.name); 5897 if (ps.codePathString != null) { 5898 mAppDirs.remove(ps.codePathString); 5899 } 5900 5901 final PackageParser.Package pkg = ps.pkg; 5902 if (pkg != null) { 5903 cleanPackageDataStructuresLILPw(pkg, chatty); 5904 } 5905 } 5906 } 5907 5908 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 5909 if (DEBUG_INSTALL) { 5910 if (chatty) 5911 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 5912 } 5913 5914 // writer 5915 synchronized (mPackages) { 5916 mPackages.remove(pkg.applicationInfo.packageName); 5917 if (pkg.mPath != null) { 5918 mAppDirs.remove(pkg.mPath); 5919 } 5920 cleanPackageDataStructuresLILPw(pkg, chatty); 5921 } 5922 } 5923 5924 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 5925 int N = pkg.providers.size(); 5926 StringBuilder r = null; 5927 int i; 5928 for (i=0; i<N; i++) { 5929 PackageParser.Provider p = pkg.providers.get(i); 5930 mProviders.removeProvider(p); 5931 if (p.info.authority == null) { 5932 5933 /* There was another ContentProvider with this authority when 5934 * this app was installed so this authority is null, 5935 * Ignore it as we don't have to unregister the provider. 5936 */ 5937 continue; 5938 } 5939 String names[] = p.info.authority.split(";"); 5940 for (int j = 0; j < names.length; j++) { 5941 if (mProvidersByAuthority.get(names[j]) == p) { 5942 mProvidersByAuthority.remove(names[j]); 5943 if (DEBUG_REMOVE) { 5944 if (chatty) 5945 Log.d(TAG, "Unregistered content provider: " + names[j] 5946 + ", className = " + p.info.name + ", isSyncable = " 5947 + p.info.isSyncable); 5948 } 5949 } 5950 } 5951 if (DEBUG_REMOVE && chatty) { 5952 if (r == null) { 5953 r = new StringBuilder(256); 5954 } else { 5955 r.append(' '); 5956 } 5957 r.append(p.info.name); 5958 } 5959 } 5960 if (r != null) { 5961 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 5962 } 5963 5964 N = pkg.services.size(); 5965 r = null; 5966 for (i=0; i<N; i++) { 5967 PackageParser.Service s = pkg.services.get(i); 5968 mServices.removeService(s); 5969 if (chatty) { 5970 if (r == null) { 5971 r = new StringBuilder(256); 5972 } else { 5973 r.append(' '); 5974 } 5975 r.append(s.info.name); 5976 } 5977 } 5978 if (r != null) { 5979 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 5980 } 5981 5982 N = pkg.receivers.size(); 5983 r = null; 5984 for (i=0; i<N; i++) { 5985 PackageParser.Activity a = pkg.receivers.get(i); 5986 mReceivers.removeActivity(a, "receiver"); 5987 if (DEBUG_REMOVE && chatty) { 5988 if (r == null) { 5989 r = new StringBuilder(256); 5990 } else { 5991 r.append(' '); 5992 } 5993 r.append(a.info.name); 5994 } 5995 } 5996 if (r != null) { 5997 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 5998 } 5999 6000 N = pkg.activities.size(); 6001 r = null; 6002 for (i=0; i<N; i++) { 6003 PackageParser.Activity a = pkg.activities.get(i); 6004 mActivities.removeActivity(a, "activity"); 6005 if (DEBUG_REMOVE && chatty) { 6006 if (r == null) { 6007 r = new StringBuilder(256); 6008 } else { 6009 r.append(' '); 6010 } 6011 r.append(a.info.name); 6012 } 6013 } 6014 if (r != null) { 6015 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6016 } 6017 6018 N = pkg.permissions.size(); 6019 r = null; 6020 for (i=0; i<N; i++) { 6021 PackageParser.Permission p = pkg.permissions.get(i); 6022 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6023 if (bp == null) { 6024 bp = mSettings.mPermissionTrees.get(p.info.name); 6025 } 6026 if (bp != null && bp.perm == p) { 6027 bp.perm = null; 6028 if (DEBUG_REMOVE && chatty) { 6029 if (r == null) { 6030 r = new StringBuilder(256); 6031 } else { 6032 r.append(' '); 6033 } 6034 r.append(p.info.name); 6035 } 6036 } 6037 } 6038 if (r != null) { 6039 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6040 } 6041 6042 N = pkg.instrumentation.size(); 6043 r = null; 6044 for (i=0; i<N; i++) { 6045 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6046 mInstrumentation.remove(a.getComponentName()); 6047 if (DEBUG_REMOVE && chatty) { 6048 if (r == null) { 6049 r = new StringBuilder(256); 6050 } else { 6051 r.append(' '); 6052 } 6053 r.append(a.info.name); 6054 } 6055 } 6056 if (r != null) { 6057 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6058 } 6059 6060 r = null; 6061 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6062 // Only system apps can hold shared libraries. 6063 if (pkg.libraryNames != null) { 6064 for (i=0; i<pkg.libraryNames.size(); i++) { 6065 String name = pkg.libraryNames.get(i); 6066 SharedLibraryEntry cur = mSharedLibraries.get(name); 6067 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6068 mSharedLibraries.remove(name); 6069 if (DEBUG_REMOVE && chatty) { 6070 if (r == null) { 6071 r = new StringBuilder(256); 6072 } else { 6073 r.append(' '); 6074 } 6075 r.append(name); 6076 } 6077 } 6078 } 6079 } 6080 } 6081 if (r != null) { 6082 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6083 } 6084 } 6085 6086 private static final boolean isPackageFilename(String name) { 6087 return name != null && name.endsWith(".apk"); 6088 } 6089 6090 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6091 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6092 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6093 return true; 6094 } 6095 } 6096 return false; 6097 } 6098 6099 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6100 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6101 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6102 6103 private void updatePermissionsLPw(String changingPkg, 6104 PackageParser.Package pkgInfo, int flags) { 6105 // Make sure there are no dangling permission trees. 6106 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6107 while (it.hasNext()) { 6108 final BasePermission bp = it.next(); 6109 if (bp.packageSetting == null) { 6110 // We may not yet have parsed the package, so just see if 6111 // we still know about its settings. 6112 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6113 } 6114 if (bp.packageSetting == null) { 6115 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6116 + " from package " + bp.sourcePackage); 6117 it.remove(); 6118 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6119 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6120 Slog.i(TAG, "Removing old permission tree: " + bp.name 6121 + " from package " + bp.sourcePackage); 6122 flags |= UPDATE_PERMISSIONS_ALL; 6123 it.remove(); 6124 } 6125 } 6126 } 6127 6128 // Make sure all dynamic permissions have been assigned to a package, 6129 // and make sure there are no dangling permissions. 6130 it = mSettings.mPermissions.values().iterator(); 6131 while (it.hasNext()) { 6132 final BasePermission bp = it.next(); 6133 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6134 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6135 + bp.name + " pkg=" + bp.sourcePackage 6136 + " info=" + bp.pendingInfo); 6137 if (bp.packageSetting == null && bp.pendingInfo != null) { 6138 final BasePermission tree = findPermissionTreeLP(bp.name); 6139 if (tree != null && tree.perm != null) { 6140 bp.packageSetting = tree.packageSetting; 6141 bp.perm = new PackageParser.Permission(tree.perm.owner, 6142 new PermissionInfo(bp.pendingInfo)); 6143 bp.perm.info.packageName = tree.perm.info.packageName; 6144 bp.perm.info.name = bp.name; 6145 bp.uid = tree.uid; 6146 } 6147 } 6148 } 6149 if (bp.packageSetting == null) { 6150 // We may not yet have parsed the package, so just see if 6151 // we still know about its settings. 6152 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6153 } 6154 if (bp.packageSetting == null) { 6155 Slog.w(TAG, "Removing dangling permission: " + bp.name 6156 + " from package " + bp.sourcePackage); 6157 it.remove(); 6158 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6159 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6160 Slog.i(TAG, "Removing old permission: " + bp.name 6161 + " from package " + bp.sourcePackage); 6162 flags |= UPDATE_PERMISSIONS_ALL; 6163 it.remove(); 6164 } 6165 } 6166 } 6167 6168 // Now update the permissions for all packages, in particular 6169 // replace the granted permissions of the system packages. 6170 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6171 for (PackageParser.Package pkg : mPackages.values()) { 6172 if (pkg != pkgInfo) { 6173 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6174 } 6175 } 6176 } 6177 6178 if (pkgInfo != null) { 6179 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6180 } 6181 } 6182 6183 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6184 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6185 if (ps == null) { 6186 return; 6187 } 6188 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6189 HashSet<String> origPermissions = gp.grantedPermissions; 6190 boolean changedPermission = false; 6191 6192 if (replace) { 6193 ps.permissionsFixed = false; 6194 if (gp == ps) { 6195 origPermissions = new HashSet<String>(gp.grantedPermissions); 6196 gp.grantedPermissions.clear(); 6197 gp.gids = mGlobalGids; 6198 } 6199 } 6200 6201 if (gp.gids == null) { 6202 gp.gids = mGlobalGids; 6203 } 6204 6205 final int N = pkg.requestedPermissions.size(); 6206 for (int i=0; i<N; i++) { 6207 final String name = pkg.requestedPermissions.get(i); 6208 final boolean required = pkg.requestedPermissionsRequired.get(i); 6209 final BasePermission bp = mSettings.mPermissions.get(name); 6210 if (DEBUG_INSTALL) { 6211 if (gp != ps) { 6212 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6213 } 6214 } 6215 6216 if (bp == null || bp.packageSetting == null) { 6217 Slog.w(TAG, "Unknown permission " + name 6218 + " in package " + pkg.packageName); 6219 continue; 6220 } 6221 6222 final String perm = bp.name; 6223 boolean allowed; 6224 boolean allowedSig = false; 6225 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6226 if (level == PermissionInfo.PROTECTION_NORMAL 6227 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6228 // We grant a normal or dangerous permission if any of the following 6229 // are true: 6230 // 1) The permission is required 6231 // 2) The permission is optional, but was granted in the past 6232 // 3) The permission is optional, but was requested by an 6233 // app in /system (not /data) 6234 // 6235 // Otherwise, reject the permission. 6236 allowed = (required || origPermissions.contains(perm) 6237 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6238 } else if (bp.packageSetting == null) { 6239 // This permission is invalid; skip it. 6240 allowed = false; 6241 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6242 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6243 if (allowed) { 6244 allowedSig = true; 6245 } 6246 } else { 6247 allowed = false; 6248 } 6249 if (DEBUG_INSTALL) { 6250 if (gp != ps) { 6251 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6252 } 6253 } 6254 if (allowed) { 6255 if (!isSystemApp(ps) && ps.permissionsFixed) { 6256 // If this is an existing, non-system package, then 6257 // we can't add any new permissions to it. 6258 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6259 // Except... if this is a permission that was added 6260 // to the platform (note: need to only do this when 6261 // updating the platform). 6262 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6263 } 6264 } 6265 if (allowed) { 6266 if (!gp.grantedPermissions.contains(perm)) { 6267 changedPermission = true; 6268 gp.grantedPermissions.add(perm); 6269 gp.gids = appendInts(gp.gids, bp.gids); 6270 } else if (!ps.haveGids) { 6271 gp.gids = appendInts(gp.gids, bp.gids); 6272 } 6273 } else { 6274 Slog.w(TAG, "Not granting permission " + perm 6275 + " to package " + pkg.packageName 6276 + " because it was previously installed without"); 6277 } 6278 } else { 6279 if (gp.grantedPermissions.remove(perm)) { 6280 changedPermission = true; 6281 gp.gids = removeInts(gp.gids, bp.gids); 6282 Slog.i(TAG, "Un-granting permission " + perm 6283 + " from package " + pkg.packageName 6284 + " (protectionLevel=" + bp.protectionLevel 6285 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6286 + ")"); 6287 } else { 6288 Slog.w(TAG, "Not granting permission " + perm 6289 + " to package " + pkg.packageName 6290 + " (protectionLevel=" + bp.protectionLevel 6291 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6292 + ")"); 6293 } 6294 } 6295 } 6296 6297 if ((changedPermission || replace) && !ps.permissionsFixed && 6298 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6299 // This is the first that we have heard about this package, so the 6300 // permissions we have now selected are fixed until explicitly 6301 // changed. 6302 ps.permissionsFixed = true; 6303 } 6304 ps.haveGids = true; 6305 } 6306 6307 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6308 boolean allowed = false; 6309 final int NP = PackageParser.NEW_PERMISSIONS.length; 6310 for (int ip=0; ip<NP; ip++) { 6311 final PackageParser.NewPermissionInfo npi 6312 = PackageParser.NEW_PERMISSIONS[ip]; 6313 if (npi.name.equals(perm) 6314 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6315 allowed = true; 6316 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6317 + pkg.packageName); 6318 break; 6319 } 6320 } 6321 return allowed; 6322 } 6323 6324 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6325 BasePermission bp, HashSet<String> origPermissions) { 6326 boolean allowed; 6327 allowed = (compareSignatures( 6328 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6329 == PackageManager.SIGNATURE_MATCH) 6330 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6331 == PackageManager.SIGNATURE_MATCH); 6332 if (!allowed && (bp.protectionLevel 6333 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6334 if (isSystemApp(pkg)) { 6335 // For updated system applications, a system permission 6336 // is granted only if it had been defined by the original application. 6337 if (isUpdatedSystemApp(pkg)) { 6338 final PackageSetting sysPs = mSettings 6339 .getDisabledSystemPkgLPr(pkg.packageName); 6340 final GrantedPermissions origGp = sysPs.sharedUser != null 6341 ? sysPs.sharedUser : sysPs; 6342 6343 if (origGp.grantedPermissions.contains(perm)) { 6344 // If the original was granted this permission, we take 6345 // that grant decision as read and propagate it to the 6346 // update. 6347 allowed = true; 6348 } else { 6349 // The system apk may have been updated with an older 6350 // version of the one on the data partition, but which 6351 // granted a new system permission that it didn't have 6352 // before. In this case we do want to allow the app to 6353 // now get the new permission if the ancestral apk is 6354 // privileged to get it. 6355 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6356 for (int j=0; 6357 j<sysPs.pkg.requestedPermissions.size(); j++) { 6358 if (perm.equals( 6359 sysPs.pkg.requestedPermissions.get(j))) { 6360 allowed = true; 6361 break; 6362 } 6363 } 6364 } 6365 } 6366 } else { 6367 allowed = isPrivilegedApp(pkg); 6368 } 6369 } 6370 } 6371 if (!allowed && (bp.protectionLevel 6372 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6373 // For development permissions, a development permission 6374 // is granted only if it was already granted. 6375 allowed = origPermissions.contains(perm); 6376 } 6377 return allowed; 6378 } 6379 6380 final class ActivityIntentResolver 6381 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6382 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6383 boolean defaultOnly, int userId) { 6384 if (!sUserManager.exists(userId)) return null; 6385 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6386 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6387 } 6388 6389 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6390 int userId) { 6391 if (!sUserManager.exists(userId)) return null; 6392 mFlags = flags; 6393 return super.queryIntent(intent, resolvedType, 6394 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6395 } 6396 6397 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6398 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6399 if (!sUserManager.exists(userId)) return null; 6400 if (packageActivities == null) { 6401 return null; 6402 } 6403 mFlags = flags; 6404 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6405 final int N = packageActivities.size(); 6406 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6407 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6408 6409 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6410 for (int i = 0; i < N; ++i) { 6411 intentFilters = packageActivities.get(i).intents; 6412 if (intentFilters != null && intentFilters.size() > 0) { 6413 PackageParser.ActivityIntentInfo[] array = 6414 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6415 intentFilters.toArray(array); 6416 listCut.add(array); 6417 } 6418 } 6419 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6420 } 6421 6422 public final void addActivity(PackageParser.Activity a, String type) { 6423 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6424 mActivities.put(a.getComponentName(), a); 6425 if (DEBUG_SHOW_INFO) 6426 Log.v( 6427 TAG, " " + type + " " + 6428 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6429 if (DEBUG_SHOW_INFO) 6430 Log.v(TAG, " Class=" + a.info.name); 6431 final int NI = a.intents.size(); 6432 for (int j=0; j<NI; j++) { 6433 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6434 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6435 intent.setPriority(0); 6436 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6437 + a.className + " with priority > 0, forcing to 0"); 6438 } 6439 if (DEBUG_SHOW_INFO) { 6440 Log.v(TAG, " IntentFilter:"); 6441 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6442 } 6443 if (!intent.debugCheck()) { 6444 Log.w(TAG, "==> For Activity " + a.info.name); 6445 } 6446 addFilter(intent); 6447 } 6448 } 6449 6450 public final void removeActivity(PackageParser.Activity a, String type) { 6451 mActivities.remove(a.getComponentName()); 6452 if (DEBUG_SHOW_INFO) { 6453 Log.v(TAG, " " + type + " " 6454 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6455 : a.info.name) + ":"); 6456 Log.v(TAG, " Class=" + a.info.name); 6457 } 6458 final int NI = a.intents.size(); 6459 for (int j=0; j<NI; j++) { 6460 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6461 if (DEBUG_SHOW_INFO) { 6462 Log.v(TAG, " IntentFilter:"); 6463 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6464 } 6465 removeFilter(intent); 6466 } 6467 } 6468 6469 @Override 6470 protected boolean allowFilterResult( 6471 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6472 ActivityInfo filterAi = filter.activity.info; 6473 for (int i=dest.size()-1; i>=0; i--) { 6474 ActivityInfo destAi = dest.get(i).activityInfo; 6475 if (destAi.name == filterAi.name 6476 && destAi.packageName == filterAi.packageName) { 6477 return false; 6478 } 6479 } 6480 return true; 6481 } 6482 6483 @Override 6484 protected ActivityIntentInfo[] newArray(int size) { 6485 return new ActivityIntentInfo[size]; 6486 } 6487 6488 @Override 6489 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6490 if (!sUserManager.exists(userId)) return true; 6491 PackageParser.Package p = filter.activity.owner; 6492 if (p != null) { 6493 PackageSetting ps = (PackageSetting)p.mExtras; 6494 if (ps != null) { 6495 // System apps are never considered stopped for purposes of 6496 // filtering, because there may be no way for the user to 6497 // actually re-launch them. 6498 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6499 && ps.getStopped(userId); 6500 } 6501 } 6502 return false; 6503 } 6504 6505 @Override 6506 protected boolean isPackageForFilter(String packageName, 6507 PackageParser.ActivityIntentInfo info) { 6508 return packageName.equals(info.activity.owner.packageName); 6509 } 6510 6511 @Override 6512 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6513 int match, int userId) { 6514 if (!sUserManager.exists(userId)) return null; 6515 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6516 return null; 6517 } 6518 final PackageParser.Activity activity = info.activity; 6519 if (mSafeMode && (activity.info.applicationInfo.flags 6520 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6521 return null; 6522 } 6523 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6524 if (ps == null) { 6525 return null; 6526 } 6527 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6528 ps.readUserState(userId), userId); 6529 if (ai == null) { 6530 return null; 6531 } 6532 final ResolveInfo res = new ResolveInfo(); 6533 res.activityInfo = ai; 6534 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6535 res.filter = info; 6536 } 6537 res.priority = info.getPriority(); 6538 res.preferredOrder = activity.owner.mPreferredOrder; 6539 //System.out.println("Result: " + res.activityInfo.className + 6540 // " = " + res.priority); 6541 res.match = match; 6542 res.isDefault = info.hasDefault; 6543 res.labelRes = info.labelRes; 6544 res.nonLocalizedLabel = info.nonLocalizedLabel; 6545 res.icon = info.icon; 6546 res.system = isSystemApp(res.activityInfo.applicationInfo); 6547 return res; 6548 } 6549 6550 @Override 6551 protected void sortResults(List<ResolveInfo> results) { 6552 Collections.sort(results, mResolvePrioritySorter); 6553 } 6554 6555 @Override 6556 protected void dumpFilter(PrintWriter out, String prefix, 6557 PackageParser.ActivityIntentInfo filter) { 6558 out.print(prefix); out.print( 6559 Integer.toHexString(System.identityHashCode(filter.activity))); 6560 out.print(' '); 6561 filter.activity.printComponentShortName(out); 6562 out.print(" filter "); 6563 out.println(Integer.toHexString(System.identityHashCode(filter))); 6564 } 6565 6566// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6567// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6568// final List<ResolveInfo> retList = Lists.newArrayList(); 6569// while (i.hasNext()) { 6570// final ResolveInfo resolveInfo = i.next(); 6571// if (isEnabledLP(resolveInfo.activityInfo)) { 6572// retList.add(resolveInfo); 6573// } 6574// } 6575// return retList; 6576// } 6577 6578 // Keys are String (activity class name), values are Activity. 6579 private final HashMap<ComponentName, PackageParser.Activity> mActivities 6580 = new HashMap<ComponentName, PackageParser.Activity>(); 6581 private int mFlags; 6582 } 6583 6584 private final class ServiceIntentResolver 6585 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 6586 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6587 boolean defaultOnly, int userId) { 6588 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6589 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6590 } 6591 6592 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6593 int userId) { 6594 if (!sUserManager.exists(userId)) return null; 6595 mFlags = flags; 6596 return super.queryIntent(intent, resolvedType, 6597 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6598 } 6599 6600 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6601 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 6602 if (!sUserManager.exists(userId)) return null; 6603 if (packageServices == null) { 6604 return null; 6605 } 6606 mFlags = flags; 6607 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6608 final int N = packageServices.size(); 6609 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 6610 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 6611 6612 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 6613 for (int i = 0; i < N; ++i) { 6614 intentFilters = packageServices.get(i).intents; 6615 if (intentFilters != null && intentFilters.size() > 0) { 6616 PackageParser.ServiceIntentInfo[] array = 6617 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 6618 intentFilters.toArray(array); 6619 listCut.add(array); 6620 } 6621 } 6622 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6623 } 6624 6625 public final void addService(PackageParser.Service s) { 6626 mServices.put(s.getComponentName(), s); 6627 if (DEBUG_SHOW_INFO) { 6628 Log.v(TAG, " " 6629 + (s.info.nonLocalizedLabel != null 6630 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6631 Log.v(TAG, " Class=" + s.info.name); 6632 } 6633 final int NI = s.intents.size(); 6634 int j; 6635 for (j=0; j<NI; j++) { 6636 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6637 if (DEBUG_SHOW_INFO) { 6638 Log.v(TAG, " IntentFilter:"); 6639 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6640 } 6641 if (!intent.debugCheck()) { 6642 Log.w(TAG, "==> For Service " + s.info.name); 6643 } 6644 addFilter(intent); 6645 } 6646 } 6647 6648 public final void removeService(PackageParser.Service s) { 6649 mServices.remove(s.getComponentName()); 6650 if (DEBUG_SHOW_INFO) { 6651 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 6652 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6653 Log.v(TAG, " Class=" + s.info.name); 6654 } 6655 final int NI = s.intents.size(); 6656 int j; 6657 for (j=0; j<NI; j++) { 6658 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6659 if (DEBUG_SHOW_INFO) { 6660 Log.v(TAG, " IntentFilter:"); 6661 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6662 } 6663 removeFilter(intent); 6664 } 6665 } 6666 6667 @Override 6668 protected boolean allowFilterResult( 6669 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 6670 ServiceInfo filterSi = filter.service.info; 6671 for (int i=dest.size()-1; i>=0; i--) { 6672 ServiceInfo destAi = dest.get(i).serviceInfo; 6673 if (destAi.name == filterSi.name 6674 && destAi.packageName == filterSi.packageName) { 6675 return false; 6676 } 6677 } 6678 return true; 6679 } 6680 6681 @Override 6682 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 6683 return new PackageParser.ServiceIntentInfo[size]; 6684 } 6685 6686 @Override 6687 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 6688 if (!sUserManager.exists(userId)) return true; 6689 PackageParser.Package p = filter.service.owner; 6690 if (p != null) { 6691 PackageSetting ps = (PackageSetting)p.mExtras; 6692 if (ps != null) { 6693 // System apps are never considered stopped for purposes of 6694 // filtering, because there may be no way for the user to 6695 // actually re-launch them. 6696 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 6697 && ps.getStopped(userId); 6698 } 6699 } 6700 return false; 6701 } 6702 6703 @Override 6704 protected boolean isPackageForFilter(String packageName, 6705 PackageParser.ServiceIntentInfo info) { 6706 return packageName.equals(info.service.owner.packageName); 6707 } 6708 6709 @Override 6710 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 6711 int match, int userId) { 6712 if (!sUserManager.exists(userId)) return null; 6713 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 6714 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 6715 return null; 6716 } 6717 final PackageParser.Service service = info.service; 6718 if (mSafeMode && (service.info.applicationInfo.flags 6719 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6720 return null; 6721 } 6722 PackageSetting ps = (PackageSetting) service.owner.mExtras; 6723 if (ps == null) { 6724 return null; 6725 } 6726 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 6727 ps.readUserState(userId), userId); 6728 if (si == null) { 6729 return null; 6730 } 6731 final ResolveInfo res = new ResolveInfo(); 6732 res.serviceInfo = si; 6733 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6734 res.filter = filter; 6735 } 6736 res.priority = info.getPriority(); 6737 res.preferredOrder = service.owner.mPreferredOrder; 6738 //System.out.println("Result: " + res.activityInfo.className + 6739 // " = " + res.priority); 6740 res.match = match; 6741 res.isDefault = info.hasDefault; 6742 res.labelRes = info.labelRes; 6743 res.nonLocalizedLabel = info.nonLocalizedLabel; 6744 res.icon = info.icon; 6745 res.system = isSystemApp(res.serviceInfo.applicationInfo); 6746 return res; 6747 } 6748 6749 @Override 6750 protected void sortResults(List<ResolveInfo> results) { 6751 Collections.sort(results, mResolvePrioritySorter); 6752 } 6753 6754 @Override 6755 protected void dumpFilter(PrintWriter out, String prefix, 6756 PackageParser.ServiceIntentInfo filter) { 6757 out.print(prefix); out.print( 6758 Integer.toHexString(System.identityHashCode(filter.service))); 6759 out.print(' '); 6760 filter.service.printComponentShortName(out); 6761 out.print(" filter "); 6762 out.println(Integer.toHexString(System.identityHashCode(filter))); 6763 } 6764 6765// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6766// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6767// final List<ResolveInfo> retList = Lists.newArrayList(); 6768// while (i.hasNext()) { 6769// final ResolveInfo resolveInfo = (ResolveInfo) i; 6770// if (isEnabledLP(resolveInfo.serviceInfo)) { 6771// retList.add(resolveInfo); 6772// } 6773// } 6774// return retList; 6775// } 6776 6777 // Keys are String (activity class name), values are Activity. 6778 private final HashMap<ComponentName, PackageParser.Service> mServices 6779 = new HashMap<ComponentName, PackageParser.Service>(); 6780 private int mFlags; 6781 }; 6782 6783 private final class ProviderIntentResolver 6784 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 6785 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6786 boolean defaultOnly, int userId) { 6787 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6788 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6789 } 6790 6791 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6792 int userId) { 6793 if (!sUserManager.exists(userId)) 6794 return null; 6795 mFlags = flags; 6796 return super.queryIntent(intent, resolvedType, 6797 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6798 } 6799 6800 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6801 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 6802 if (!sUserManager.exists(userId)) 6803 return null; 6804 if (packageProviders == null) { 6805 return null; 6806 } 6807 mFlags = flags; 6808 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 6809 final int N = packageProviders.size(); 6810 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 6811 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 6812 6813 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 6814 for (int i = 0; i < N; ++i) { 6815 intentFilters = packageProviders.get(i).intents; 6816 if (intentFilters != null && intentFilters.size() > 0) { 6817 PackageParser.ProviderIntentInfo[] array = 6818 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 6819 intentFilters.toArray(array); 6820 listCut.add(array); 6821 } 6822 } 6823 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6824 } 6825 6826 public final void addProvider(PackageParser.Provider p) { 6827 if (mProviders.containsKey(p.getComponentName())) { 6828 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 6829 return; 6830 } 6831 6832 mProviders.put(p.getComponentName(), p); 6833 if (DEBUG_SHOW_INFO) { 6834 Log.v(TAG, " " 6835 + (p.info.nonLocalizedLabel != null 6836 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 6837 Log.v(TAG, " Class=" + p.info.name); 6838 } 6839 final int NI = p.intents.size(); 6840 int j; 6841 for (j = 0; j < NI; j++) { 6842 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 6843 if (DEBUG_SHOW_INFO) { 6844 Log.v(TAG, " IntentFilter:"); 6845 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6846 } 6847 if (!intent.debugCheck()) { 6848 Log.w(TAG, "==> For Provider " + p.info.name); 6849 } 6850 addFilter(intent); 6851 } 6852 } 6853 6854 public final void removeProvider(PackageParser.Provider p) { 6855 mProviders.remove(p.getComponentName()); 6856 if (DEBUG_SHOW_INFO) { 6857 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 6858 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 6859 Log.v(TAG, " Class=" + p.info.name); 6860 } 6861 final int NI = p.intents.size(); 6862 int j; 6863 for (j = 0; j < NI; j++) { 6864 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 6865 if (DEBUG_SHOW_INFO) { 6866 Log.v(TAG, " IntentFilter:"); 6867 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6868 } 6869 removeFilter(intent); 6870 } 6871 } 6872 6873 @Override 6874 protected boolean allowFilterResult( 6875 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 6876 ProviderInfo filterPi = filter.provider.info; 6877 for (int i = dest.size() - 1; i >= 0; i--) { 6878 ProviderInfo destPi = dest.get(i).providerInfo; 6879 if (destPi.name == filterPi.name 6880 && destPi.packageName == filterPi.packageName) { 6881 return false; 6882 } 6883 } 6884 return true; 6885 } 6886 6887 @Override 6888 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 6889 return new PackageParser.ProviderIntentInfo[size]; 6890 } 6891 6892 @Override 6893 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 6894 if (!sUserManager.exists(userId)) 6895 return true; 6896 PackageParser.Package p = filter.provider.owner; 6897 if (p != null) { 6898 PackageSetting ps = (PackageSetting) p.mExtras; 6899 if (ps != null) { 6900 // System apps are never considered stopped for purposes of 6901 // filtering, because there may be no way for the user to 6902 // actually re-launch them. 6903 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 6904 && ps.getStopped(userId); 6905 } 6906 } 6907 return false; 6908 } 6909 6910 @Override 6911 protected boolean isPackageForFilter(String packageName, 6912 PackageParser.ProviderIntentInfo info) { 6913 return packageName.equals(info.provider.owner.packageName); 6914 } 6915 6916 @Override 6917 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 6918 int match, int userId) { 6919 if (!sUserManager.exists(userId)) 6920 return null; 6921 final PackageParser.ProviderIntentInfo info = filter; 6922 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 6923 return null; 6924 } 6925 final PackageParser.Provider provider = info.provider; 6926 if (mSafeMode && (provider.info.applicationInfo.flags 6927 & ApplicationInfo.FLAG_SYSTEM) == 0) { 6928 return null; 6929 } 6930 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 6931 if (ps == null) { 6932 return null; 6933 } 6934 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 6935 ps.readUserState(userId), userId); 6936 if (pi == null) { 6937 return null; 6938 } 6939 final ResolveInfo res = new ResolveInfo(); 6940 res.providerInfo = pi; 6941 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 6942 res.filter = filter; 6943 } 6944 res.priority = info.getPriority(); 6945 res.preferredOrder = provider.owner.mPreferredOrder; 6946 res.match = match; 6947 res.isDefault = info.hasDefault; 6948 res.labelRes = info.labelRes; 6949 res.nonLocalizedLabel = info.nonLocalizedLabel; 6950 res.icon = info.icon; 6951 res.system = isSystemApp(res.providerInfo.applicationInfo); 6952 return res; 6953 } 6954 6955 @Override 6956 protected void sortResults(List<ResolveInfo> results) { 6957 Collections.sort(results, mResolvePrioritySorter); 6958 } 6959 6960 @Override 6961 protected void dumpFilter(PrintWriter out, String prefix, 6962 PackageParser.ProviderIntentInfo filter) { 6963 out.print(prefix); 6964 out.print( 6965 Integer.toHexString(System.identityHashCode(filter.provider))); 6966 out.print(' '); 6967 filter.provider.printComponentShortName(out); 6968 out.print(" filter "); 6969 out.println(Integer.toHexString(System.identityHashCode(filter))); 6970 } 6971 6972 private final HashMap<ComponentName, PackageParser.Provider> mProviders 6973 = new HashMap<ComponentName, PackageParser.Provider>(); 6974 private int mFlags; 6975 }; 6976 6977 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 6978 new Comparator<ResolveInfo>() { 6979 public int compare(ResolveInfo r1, ResolveInfo r2) { 6980 int v1 = r1.priority; 6981 int v2 = r2.priority; 6982 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 6983 if (v1 != v2) { 6984 return (v1 > v2) ? -1 : 1; 6985 } 6986 v1 = r1.preferredOrder; 6987 v2 = r2.preferredOrder; 6988 if (v1 != v2) { 6989 return (v1 > v2) ? -1 : 1; 6990 } 6991 if (r1.isDefault != r2.isDefault) { 6992 return r1.isDefault ? -1 : 1; 6993 } 6994 v1 = r1.match; 6995 v2 = r2.match; 6996 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 6997 if (v1 != v2) { 6998 return (v1 > v2) ? -1 : 1; 6999 } 7000 if (r1.system != r2.system) { 7001 return r1.system ? -1 : 1; 7002 } 7003 return 0; 7004 } 7005 }; 7006 7007 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7008 new Comparator<ProviderInfo>() { 7009 public int compare(ProviderInfo p1, ProviderInfo p2) { 7010 final int v1 = p1.initOrder; 7011 final int v2 = p2.initOrder; 7012 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7013 } 7014 }; 7015 7016 static final void sendPackageBroadcast(String action, String pkg, 7017 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7018 int[] userIds) { 7019 IActivityManager am = ActivityManagerNative.getDefault(); 7020 if (am != null) { 7021 try { 7022 if (userIds == null) { 7023 userIds = am.getRunningUserIds(); 7024 } 7025 for (int id : userIds) { 7026 final Intent intent = new Intent(action, 7027 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7028 if (extras != null) { 7029 intent.putExtras(extras); 7030 } 7031 if (targetPkg != null) { 7032 intent.setPackage(targetPkg); 7033 } 7034 // Modify the UID when posting to other users 7035 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7036 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7037 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7038 intent.putExtra(Intent.EXTRA_UID, uid); 7039 } 7040 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7041 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7042 if (DEBUG_BROADCASTS) { 7043 RuntimeException here = new RuntimeException("here"); 7044 here.fillInStackTrace(); 7045 Slog.d(TAG, "Sending to user " + id + ": " 7046 + intent.toShortString(false, true, false, false) 7047 + " " + intent.getExtras(), here); 7048 } 7049 am.broadcastIntent(null, intent, null, finishedReceiver, 7050 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7051 finishedReceiver != null, false, id); 7052 } 7053 } catch (RemoteException ex) { 7054 } 7055 } 7056 } 7057 7058 /** 7059 * Check if the external storage media is available. This is true if there 7060 * is a mounted external storage medium or if the external storage is 7061 * emulated. 7062 */ 7063 private boolean isExternalMediaAvailable() { 7064 return mMediaMounted || Environment.isExternalStorageEmulated(); 7065 } 7066 7067 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7068 // writer 7069 synchronized (mPackages) { 7070 if (!isExternalMediaAvailable()) { 7071 // If the external storage is no longer mounted at this point, 7072 // the caller may not have been able to delete all of this 7073 // packages files and can not delete any more. Bail. 7074 return null; 7075 } 7076 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7077 if (lastPackage != null) { 7078 pkgs.remove(lastPackage); 7079 } 7080 if (pkgs.size() > 0) { 7081 return pkgs.get(0); 7082 } 7083 } 7084 return null; 7085 } 7086 7087 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7088 if (false) { 7089 RuntimeException here = new RuntimeException("here"); 7090 here.fillInStackTrace(); 7091 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7092 + " andCode=" + andCode, here); 7093 } 7094 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7095 userId, andCode ? 1 : 0, packageName)); 7096 } 7097 7098 void startCleaningPackages() { 7099 // reader 7100 synchronized (mPackages) { 7101 if (!isExternalMediaAvailable()) { 7102 return; 7103 } 7104 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7105 return; 7106 } 7107 } 7108 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7109 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7110 IActivityManager am = ActivityManagerNative.getDefault(); 7111 if (am != null) { 7112 try { 7113 am.startService(null, intent, null, UserHandle.USER_OWNER); 7114 } catch (RemoteException e) { 7115 } 7116 } 7117 } 7118 7119 private final class AppDirObserver extends FileObserver { 7120 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7121 super(path, mask); 7122 mRootDir = path; 7123 mIsRom = isrom; 7124 mIsPrivileged = isPrivileged; 7125 } 7126 7127 public void onEvent(int event, String path) { 7128 String removedPackage = null; 7129 int removedAppId = -1; 7130 int[] removedUsers = null; 7131 String addedPackage = null; 7132 int addedAppId = -1; 7133 int[] addedUsers = null; 7134 7135 // TODO post a message to the handler to obtain serial ordering 7136 synchronized (mInstallLock) { 7137 String fullPathStr = null; 7138 File fullPath = null; 7139 if (path != null) { 7140 fullPath = new File(mRootDir, path); 7141 fullPathStr = fullPath.getPath(); 7142 } 7143 7144 if (DEBUG_APP_DIR_OBSERVER) 7145 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7146 7147 if (!isPackageFilename(path)) { 7148 if (DEBUG_APP_DIR_OBSERVER) 7149 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7150 return; 7151 } 7152 7153 // Ignore packages that are being installed or 7154 // have just been installed. 7155 if (ignoreCodePath(fullPathStr)) { 7156 return; 7157 } 7158 PackageParser.Package p = null; 7159 PackageSetting ps = null; 7160 // reader 7161 synchronized (mPackages) { 7162 p = mAppDirs.get(fullPathStr); 7163 if (p != null) { 7164 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7165 if (ps != null) { 7166 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7167 } else { 7168 removedUsers = sUserManager.getUserIds(); 7169 } 7170 } 7171 addedUsers = sUserManager.getUserIds(); 7172 } 7173 if ((event&REMOVE_EVENTS) != 0) { 7174 if (ps != null) { 7175 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7176 removePackageLI(ps, true); 7177 removedPackage = ps.name; 7178 removedAppId = ps.appId; 7179 } 7180 } 7181 7182 if ((event&ADD_EVENTS) != 0) { 7183 if (p == null) { 7184 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7185 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7186 if (mIsRom) { 7187 flags |= PackageParser.PARSE_IS_SYSTEM 7188 | PackageParser.PARSE_IS_SYSTEM_DIR; 7189 if (mIsPrivileged) { 7190 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7191 } 7192 } 7193 p = scanPackageLI(fullPath, flags, 7194 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7195 System.currentTimeMillis(), UserHandle.ALL); 7196 if (p != null) { 7197 /* 7198 * TODO this seems dangerous as the package may have 7199 * changed since we last acquired the mPackages 7200 * lock. 7201 */ 7202 // writer 7203 synchronized (mPackages) { 7204 updatePermissionsLPw(p.packageName, p, 7205 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7206 } 7207 addedPackage = p.applicationInfo.packageName; 7208 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7209 } 7210 } 7211 } 7212 7213 // reader 7214 synchronized (mPackages) { 7215 mSettings.writeLPr(); 7216 } 7217 } 7218 7219 if (removedPackage != null) { 7220 Bundle extras = new Bundle(1); 7221 extras.putInt(Intent.EXTRA_UID, removedAppId); 7222 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7223 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7224 extras, null, null, removedUsers); 7225 } 7226 if (addedPackage != null) { 7227 Bundle extras = new Bundle(1); 7228 extras.putInt(Intent.EXTRA_UID, addedAppId); 7229 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7230 extras, null, null, addedUsers); 7231 } 7232 } 7233 7234 private final String mRootDir; 7235 private final boolean mIsRom; 7236 private final boolean mIsPrivileged; 7237 } 7238 7239 /* 7240 * The old-style observer methods all just trampoline to the newer signature with 7241 * expanded install observer API. The older API continues to work but does not 7242 * supply the additional details of the Observer2 API. 7243 */ 7244 7245 /* Called when a downloaded package installation has been confirmed by the user */ 7246 public void installPackage( 7247 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 7248 installPackageEtc(packageURI, observer, null, flags, null); 7249 } 7250 7251 /* Called when a downloaded package installation has been confirmed by the user */ 7252 public void installPackage( 7253 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 7254 final String installerPackageName) { 7255 installPackageWithVerificationEtc(packageURI, observer, null, flags, 7256 installerPackageName, null, null, null); 7257 } 7258 7259 @Override 7260 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 7261 int flags, String installerPackageName, Uri verificationURI, 7262 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7263 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7264 VerificationParams.NO_UID, manifestDigest); 7265 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7266 installerPackageName, verificationParams, encryptionParams); 7267 } 7268 7269 public void installPackageWithVerificationAndEncryption(Uri packageURI, 7270 IPackageInstallObserver observer, int flags, String installerPackageName, 7271 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7272 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7273 installerPackageName, verificationParams, encryptionParams); 7274 } 7275 7276 /* 7277 * And here are the "live" versions that take both observer arguments 7278 */ 7279 public void installPackageEtc( 7280 final Uri packageURI, final IPackageInstallObserver observer, 7281 IPackageInstallObserver2 observer2, final int flags) { 7282 installPackageEtc(packageURI, observer, observer2, flags, null); 7283 } 7284 7285 public void installPackageEtc( 7286 final Uri packageURI, final IPackageInstallObserver observer, 7287 final IPackageInstallObserver2 observer2, final int flags, 7288 final String installerPackageName) { 7289 installPackageWithVerificationEtc(packageURI, observer, observer2, flags, 7290 installerPackageName, null, null, null); 7291 } 7292 7293 @Override 7294 public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer, 7295 IPackageInstallObserver2 observer2, 7296 int flags, String installerPackageName, Uri verificationURI, 7297 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7298 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7299 VerificationParams.NO_UID, manifestDigest); 7300 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags, 7301 installerPackageName, verificationParams, encryptionParams); 7302 } 7303 7304 /* 7305 * All of the installPackage...*() methods redirect to this one for the master implementation 7306 */ 7307 public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI, 7308 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7309 int flags, String installerPackageName, 7310 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7311 if (observer == null && observer2 == null) { 7312 throw new IllegalArgumentException("No install observer supplied"); 7313 } 7314 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7315 null); 7316 7317 final int uid = Binder.getCallingUid(); 7318 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7319 try { 7320 if (observer != null) { 7321 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7322 } 7323 if (observer2 != null) { 7324 observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7325 } 7326 } catch (RemoteException re) { 7327 } 7328 return; 7329 } 7330 7331 UserHandle user; 7332 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7333 user = UserHandle.ALL; 7334 } else { 7335 user = new UserHandle(UserHandle.getUserId(uid)); 7336 } 7337 7338 final int filteredFlags; 7339 7340 if (uid == Process.SHELL_UID || uid == 0) { 7341 if (DEBUG_INSTALL) { 7342 Slog.v(TAG, "Install from ADB"); 7343 } 7344 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7345 } else { 7346 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7347 } 7348 7349 verificationParams.setInstallerUid(uid); 7350 7351 final Message msg = mHandler.obtainMessage(INIT_COPY); 7352 msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags, 7353 installerPackageName, verificationParams, encryptionParams, user); 7354 mHandler.sendMessage(msg); 7355 } 7356 7357 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7358 Bundle extras = new Bundle(1); 7359 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7360 7361 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7362 packageName, extras, null, null, new int[] {userId}); 7363 try { 7364 IActivityManager am = ActivityManagerNative.getDefault(); 7365 final boolean isSystem = 7366 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7367 if (isSystem && am.isUserRunning(userId, false)) { 7368 // The just-installed/enabled app is bundled on the system, so presumed 7369 // to be able to run automatically without needing an explicit launch. 7370 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7371 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7372 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7373 .setPackage(packageName); 7374 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7375 android.app.AppOpsManager.OP_NONE, false, false, userId); 7376 } 7377 } catch (RemoteException e) { 7378 // shouldn't happen 7379 Slog.w(TAG, "Unable to bootstrap installed package", e); 7380 } 7381 } 7382 7383 @Override 7384 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7385 int userId) { 7386 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7387 PackageSetting pkgSetting; 7388 final int uid = Binder.getCallingUid(); 7389 if (UserHandle.getUserId(uid) != userId) { 7390 mContext.enforceCallingOrSelfPermission( 7391 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7392 "setApplicationBlockedSetting for user " + userId); 7393 } 7394 7395 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7396 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7397 return false; 7398 } 7399 7400 long callingId = Binder.clearCallingIdentity(); 7401 try { 7402 boolean sendAdded = false; 7403 boolean sendRemoved = false; 7404 // writer 7405 synchronized (mPackages) { 7406 pkgSetting = mSettings.mPackages.get(packageName); 7407 if (pkgSetting == null) { 7408 return false; 7409 } 7410 if (pkgSetting.getBlocked(userId) != blocked) { 7411 pkgSetting.setBlocked(blocked, userId); 7412 mSettings.writePackageRestrictionsLPr(userId); 7413 if (blocked) { 7414 sendRemoved = true; 7415 } else { 7416 sendAdded = true; 7417 } 7418 } 7419 } 7420 if (sendAdded) { 7421 sendPackageAddedForUser(packageName, pkgSetting, userId); 7422 return true; 7423 } 7424 if (sendRemoved) { 7425 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7426 "blocking pkg"); 7427 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7428 } 7429 } finally { 7430 Binder.restoreCallingIdentity(callingId); 7431 } 7432 return false; 7433 } 7434 7435 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7436 int userId) { 7437 final PackageRemovedInfo info = new PackageRemovedInfo(); 7438 info.removedPackage = packageName; 7439 info.removedUsers = new int[] {userId}; 7440 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7441 info.sendBroadcast(false, false, false); 7442 } 7443 7444 /** 7445 * Returns true if application is not found or there was an error. Otherwise it returns 7446 * the blocked state of the package for the given user. 7447 */ 7448 @Override 7449 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7450 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7451 PackageSetting pkgSetting; 7452 final int uid = Binder.getCallingUid(); 7453 if (UserHandle.getUserId(uid) != userId) { 7454 mContext.enforceCallingPermission( 7455 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7456 "getApplicationBlocked for user " + userId); 7457 } 7458 long callingId = Binder.clearCallingIdentity(); 7459 try { 7460 // writer 7461 synchronized (mPackages) { 7462 pkgSetting = mSettings.mPackages.get(packageName); 7463 if (pkgSetting == null) { 7464 return true; 7465 } 7466 return pkgSetting.getBlocked(userId); 7467 } 7468 } finally { 7469 Binder.restoreCallingIdentity(callingId); 7470 } 7471 } 7472 7473 /** 7474 * @hide 7475 */ 7476 @Override 7477 public int installExistingPackageAsUser(String packageName, int userId) { 7478 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7479 null); 7480 PackageSetting pkgSetting; 7481 final int uid = Binder.getCallingUid(); 7482 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7483 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7484 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7485 } 7486 7487 long callingId = Binder.clearCallingIdentity(); 7488 try { 7489 boolean sendAdded = false; 7490 Bundle extras = new Bundle(1); 7491 7492 // writer 7493 synchronized (mPackages) { 7494 pkgSetting = mSettings.mPackages.get(packageName); 7495 if (pkgSetting == null) { 7496 return PackageManager.INSTALL_FAILED_INVALID_URI; 7497 } 7498 if (!pkgSetting.getInstalled(userId)) { 7499 pkgSetting.setInstalled(true, userId); 7500 pkgSetting.setBlocked(false, userId); 7501 mSettings.writePackageRestrictionsLPr(userId); 7502 sendAdded = true; 7503 } 7504 } 7505 7506 if (sendAdded) { 7507 sendPackageAddedForUser(packageName, pkgSetting, userId); 7508 } 7509 } finally { 7510 Binder.restoreCallingIdentity(callingId); 7511 } 7512 7513 return PackageManager.INSTALL_SUCCEEDED; 7514 } 7515 7516 private boolean isUserRestricted(int userId, String restrictionKey) { 7517 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7518 if (restrictions.getBoolean(restrictionKey, false)) { 7519 Log.w(TAG, "User is restricted: " + restrictionKey); 7520 return true; 7521 } 7522 return false; 7523 } 7524 7525 @Override 7526 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7527 mContext.enforceCallingOrSelfPermission( 7528 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7529 "Only package verification agents can verify applications"); 7530 7531 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7532 final PackageVerificationResponse response = new PackageVerificationResponse( 7533 verificationCode, Binder.getCallingUid()); 7534 msg.arg1 = id; 7535 msg.obj = response; 7536 mHandler.sendMessage(msg); 7537 } 7538 7539 @Override 7540 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7541 long millisecondsToDelay) { 7542 mContext.enforceCallingOrSelfPermission( 7543 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7544 "Only package verification agents can extend verification timeouts"); 7545 7546 final PackageVerificationState state = mPendingVerification.get(id); 7547 final PackageVerificationResponse response = new PackageVerificationResponse( 7548 verificationCodeAtTimeout, Binder.getCallingUid()); 7549 7550 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7551 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7552 } 7553 if (millisecondsToDelay < 0) { 7554 millisecondsToDelay = 0; 7555 } 7556 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7557 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7558 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7559 } 7560 7561 if ((state != null) && !state.timeoutExtended()) { 7562 state.extendTimeout(); 7563 7564 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7565 msg.arg1 = id; 7566 msg.obj = response; 7567 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7568 } 7569 } 7570 7571 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7572 int verificationCode, UserHandle user) { 7573 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7574 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7575 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7576 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7577 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7578 7579 mContext.sendBroadcastAsUser(intent, user, 7580 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7581 } 7582 7583 private ComponentName matchComponentForVerifier(String packageName, 7584 List<ResolveInfo> receivers) { 7585 ActivityInfo targetReceiver = null; 7586 7587 final int NR = receivers.size(); 7588 for (int i = 0; i < NR; i++) { 7589 final ResolveInfo info = receivers.get(i); 7590 if (info.activityInfo == null) { 7591 continue; 7592 } 7593 7594 if (packageName.equals(info.activityInfo.packageName)) { 7595 targetReceiver = info.activityInfo; 7596 break; 7597 } 7598 } 7599 7600 if (targetReceiver == null) { 7601 return null; 7602 } 7603 7604 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 7605 } 7606 7607 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 7608 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 7609 if (pkgInfo.verifiers.length == 0) { 7610 return null; 7611 } 7612 7613 final int N = pkgInfo.verifiers.length; 7614 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 7615 for (int i = 0; i < N; i++) { 7616 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 7617 7618 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 7619 receivers); 7620 if (comp == null) { 7621 continue; 7622 } 7623 7624 final int verifierUid = getUidForVerifier(verifierInfo); 7625 if (verifierUid == -1) { 7626 continue; 7627 } 7628 7629 if (DEBUG_VERIFY) { 7630 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 7631 + " with the correct signature"); 7632 } 7633 sufficientVerifiers.add(comp); 7634 verificationState.addSufficientVerifier(verifierUid); 7635 } 7636 7637 return sufficientVerifiers; 7638 } 7639 7640 private int getUidForVerifier(VerifierInfo verifierInfo) { 7641 synchronized (mPackages) { 7642 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 7643 if (pkg == null) { 7644 return -1; 7645 } else if (pkg.mSignatures.length != 1) { 7646 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7647 + " has more than one signature; ignoring"); 7648 return -1; 7649 } 7650 7651 /* 7652 * If the public key of the package's signature does not match 7653 * our expected public key, then this is a different package and 7654 * we should skip. 7655 */ 7656 7657 final byte[] expectedPublicKey; 7658 try { 7659 final Signature verifierSig = pkg.mSignatures[0]; 7660 final PublicKey publicKey = verifierSig.getPublicKey(); 7661 expectedPublicKey = publicKey.getEncoded(); 7662 } catch (CertificateException e) { 7663 return -1; 7664 } 7665 7666 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 7667 7668 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 7669 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7670 + " does not have the expected public key; ignoring"); 7671 return -1; 7672 } 7673 7674 return pkg.applicationInfo.uid; 7675 } 7676 } 7677 7678 public void finishPackageInstall(int token) { 7679 enforceSystemOrRoot("Only the system is allowed to finish installs"); 7680 7681 if (DEBUG_INSTALL) { 7682 Slog.v(TAG, "BM finishing package install for " + token); 7683 } 7684 7685 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 7686 mHandler.sendMessage(msg); 7687 } 7688 7689 /** 7690 * Get the verification agent timeout. 7691 * 7692 * @return verification timeout in milliseconds 7693 */ 7694 private long getVerificationTimeout() { 7695 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 7696 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 7697 DEFAULT_VERIFICATION_TIMEOUT); 7698 } 7699 7700 /** 7701 * Get the default verification agent response code. 7702 * 7703 * @return default verification response code 7704 */ 7705 private int getDefaultVerificationResponse() { 7706 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7707 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 7708 DEFAULT_VERIFICATION_RESPONSE); 7709 } 7710 7711 /** 7712 * Check whether or not package verification has been enabled. 7713 * 7714 * @return true if verification should be performed 7715 */ 7716 private boolean isVerificationEnabled(int flags) { 7717 if (!DEFAULT_VERIFY_ENABLE) { 7718 return false; 7719 } 7720 7721 // Check if installing from ADB 7722 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 7723 // Do not run verification in a test harness environment 7724 if (ActivityManager.isRunningInTestHarness()) { 7725 return false; 7726 } 7727 // Check if the developer does not want package verification for ADB installs 7728 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7729 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 7730 return false; 7731 } 7732 } 7733 7734 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7735 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 7736 } 7737 7738 /** 7739 * Get the "allow unknown sources" setting. 7740 * 7741 * @return the current "allow unknown sources" setting 7742 */ 7743 private int getUnknownSourcesSettings() { 7744 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7745 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 7746 -1); 7747 } 7748 7749 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 7750 final int uid = Binder.getCallingUid(); 7751 // writer 7752 synchronized (mPackages) { 7753 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 7754 if (targetPackageSetting == null) { 7755 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 7756 } 7757 7758 PackageSetting installerPackageSetting; 7759 if (installerPackageName != null) { 7760 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 7761 if (installerPackageSetting == null) { 7762 throw new IllegalArgumentException("Unknown installer package: " 7763 + installerPackageName); 7764 } 7765 } else { 7766 installerPackageSetting = null; 7767 } 7768 7769 Signature[] callerSignature; 7770 Object obj = mSettings.getUserIdLPr(uid); 7771 if (obj != null) { 7772 if (obj instanceof SharedUserSetting) { 7773 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 7774 } else if (obj instanceof PackageSetting) { 7775 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 7776 } else { 7777 throw new SecurityException("Bad object " + obj + " for uid " + uid); 7778 } 7779 } else { 7780 throw new SecurityException("Unknown calling uid " + uid); 7781 } 7782 7783 // Verify: can't set installerPackageName to a package that is 7784 // not signed with the same cert as the caller. 7785 if (installerPackageSetting != null) { 7786 if (compareSignatures(callerSignature, 7787 installerPackageSetting.signatures.mSignatures) 7788 != PackageManager.SIGNATURE_MATCH) { 7789 throw new SecurityException( 7790 "Caller does not have same cert as new installer package " 7791 + installerPackageName); 7792 } 7793 } 7794 7795 // Verify: if target already has an installer package, it must 7796 // be signed with the same cert as the caller. 7797 if (targetPackageSetting.installerPackageName != null) { 7798 PackageSetting setting = mSettings.mPackages.get( 7799 targetPackageSetting.installerPackageName); 7800 // If the currently set package isn't valid, then it's always 7801 // okay to change it. 7802 if (setting != null) { 7803 if (compareSignatures(callerSignature, 7804 setting.signatures.mSignatures) 7805 != PackageManager.SIGNATURE_MATCH) { 7806 throw new SecurityException( 7807 "Caller does not have same cert as old installer package " 7808 + targetPackageSetting.installerPackageName); 7809 } 7810 } 7811 } 7812 7813 // Okay! 7814 targetPackageSetting.installerPackageName = installerPackageName; 7815 scheduleWriteSettingsLocked(); 7816 } 7817 } 7818 7819 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 7820 // Queue up an async operation since the package installation may take a little while. 7821 mHandler.post(new Runnable() { 7822 public void run() { 7823 mHandler.removeCallbacks(this); 7824 // Result object to be returned 7825 PackageInstalledInfo res = new PackageInstalledInfo(); 7826 res.returnCode = currentStatus; 7827 res.uid = -1; 7828 res.pkg = null; 7829 res.removedInfo = new PackageRemovedInfo(); 7830 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 7831 args.doPreInstall(res.returnCode); 7832 synchronized (mInstallLock) { 7833 installPackageLI(args, true, res); 7834 } 7835 args.doPostInstall(res.returnCode, res.uid); 7836 } 7837 7838 // A restore should be performed at this point if (a) the install 7839 // succeeded, (b) the operation is not an update, and (c) the new 7840 // package has a backupAgent defined. 7841 final boolean update = res.removedInfo.removedPackage != null; 7842 boolean doRestore = (!update 7843 && res.pkg != null 7844 && res.pkg.applicationInfo.backupAgentName != null); 7845 7846 // Set up the post-install work request bookkeeping. This will be used 7847 // and cleaned up by the post-install event handling regardless of whether 7848 // there's a restore pass performed. Token values are >= 1. 7849 int token; 7850 if (mNextInstallToken < 0) mNextInstallToken = 1; 7851 token = mNextInstallToken++; 7852 7853 PostInstallData data = new PostInstallData(args, res); 7854 mRunningInstalls.put(token, data); 7855 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 7856 7857 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 7858 // Pass responsibility to the Backup Manager. It will perform a 7859 // restore if appropriate, then pass responsibility back to the 7860 // Package Manager to run the post-install observer callbacks 7861 // and broadcasts. 7862 IBackupManager bm = IBackupManager.Stub.asInterface( 7863 ServiceManager.getService(Context.BACKUP_SERVICE)); 7864 if (bm != null) { 7865 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 7866 + " to BM for possible restore"); 7867 try { 7868 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 7869 } catch (RemoteException e) { 7870 // can't happen; the backup manager is local 7871 } catch (Exception e) { 7872 Slog.e(TAG, "Exception trying to enqueue restore", e); 7873 doRestore = false; 7874 } 7875 } else { 7876 Slog.e(TAG, "Backup Manager not found!"); 7877 doRestore = false; 7878 } 7879 } 7880 7881 if (!doRestore) { 7882 // No restore possible, or the Backup Manager was mysteriously not 7883 // available -- just fire the post-install work request directly. 7884 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 7885 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 7886 mHandler.sendMessage(msg); 7887 } 7888 } 7889 }); 7890 } 7891 7892 private abstract class HandlerParams { 7893 private static final int MAX_RETRIES = 4; 7894 7895 /** 7896 * Number of times startCopy() has been attempted and had a non-fatal 7897 * error. 7898 */ 7899 private int mRetries = 0; 7900 7901 /** User handle for the user requesting the information or installation. */ 7902 private final UserHandle mUser; 7903 7904 HandlerParams(UserHandle user) { 7905 mUser = user; 7906 } 7907 7908 UserHandle getUser() { 7909 return mUser; 7910 } 7911 7912 final boolean startCopy() { 7913 boolean res; 7914 try { 7915 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 7916 7917 if (++mRetries > MAX_RETRIES) { 7918 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 7919 mHandler.sendEmptyMessage(MCS_GIVE_UP); 7920 handleServiceError(); 7921 return false; 7922 } else { 7923 handleStartCopy(); 7924 res = true; 7925 } 7926 } catch (RemoteException e) { 7927 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 7928 mHandler.sendEmptyMessage(MCS_RECONNECT); 7929 res = false; 7930 } 7931 handleReturnCode(); 7932 return res; 7933 } 7934 7935 final void serviceError() { 7936 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 7937 handleServiceError(); 7938 handleReturnCode(); 7939 } 7940 7941 abstract void handleStartCopy() throws RemoteException; 7942 abstract void handleServiceError(); 7943 abstract void handleReturnCode(); 7944 } 7945 7946 class MeasureParams extends HandlerParams { 7947 private final PackageStats mStats; 7948 private boolean mSuccess; 7949 7950 private final IPackageStatsObserver mObserver; 7951 7952 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 7953 super(new UserHandle(stats.userHandle)); 7954 mObserver = observer; 7955 mStats = stats; 7956 } 7957 7958 @Override 7959 public String toString() { 7960 return "MeasureParams{" 7961 + Integer.toHexString(System.identityHashCode(this)) 7962 + " " + mStats.packageName + "}"; 7963 } 7964 7965 @Override 7966 void handleStartCopy() throws RemoteException { 7967 synchronized (mInstallLock) { 7968 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 7969 } 7970 7971 if (mSuccess) { 7972 final boolean mounted; 7973 if (Environment.isExternalStorageEmulated()) { 7974 mounted = true; 7975 } else { 7976 final String status = Environment.getExternalStorageState(); 7977 mounted = (Environment.MEDIA_MOUNTED.equals(status) 7978 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 7979 } 7980 7981 if (mounted) { 7982 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 7983 7984 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 7985 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 7986 7987 mStats.externalDataSize = calculateDirectorySize(mContainerService, 7988 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 7989 7990 // Always subtract cache size, since it's a subdirectory 7991 mStats.externalDataSize -= mStats.externalCacheSize; 7992 7993 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 7994 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 7995 7996 mStats.externalObbSize = calculateDirectorySize(mContainerService, 7997 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 7998 } 7999 } 8000 } 8001 8002 @Override 8003 void handleReturnCode() { 8004 if (mObserver != null) { 8005 try { 8006 mObserver.onGetStatsCompleted(mStats, mSuccess); 8007 } catch (RemoteException e) { 8008 Slog.i(TAG, "Observer no longer exists."); 8009 } 8010 } 8011 } 8012 8013 @Override 8014 void handleServiceError() { 8015 Slog.e(TAG, "Could not measure application " + mStats.packageName 8016 + " external storage"); 8017 } 8018 } 8019 8020 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8021 throws RemoteException { 8022 long result = 0; 8023 for (File path : paths) { 8024 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8025 } 8026 return result; 8027 } 8028 8029 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8030 for (File path : paths) { 8031 try { 8032 mcs.clearDirectory(path.getAbsolutePath()); 8033 } catch (RemoteException e) { 8034 } 8035 } 8036 } 8037 8038 class InstallParams extends HandlerParams { 8039 final IPackageInstallObserver observer; 8040 final IPackageInstallObserver2 observer2; 8041 int flags; 8042 8043 private final Uri mPackageURI; 8044 final String installerPackageName; 8045 final VerificationParams verificationParams; 8046 private InstallArgs mArgs; 8047 private int mRet; 8048 private File mTempPackage; 8049 final ContainerEncryptionParams encryptionParams; 8050 8051 InstallParams(Uri packageURI, 8052 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 8053 int flags, String installerPackageName, VerificationParams verificationParams, 8054 ContainerEncryptionParams encryptionParams, UserHandle user) { 8055 super(user); 8056 this.mPackageURI = packageURI; 8057 this.flags = flags; 8058 this.observer = observer; 8059 this.observer2 = observer2; 8060 this.installerPackageName = installerPackageName; 8061 this.verificationParams = verificationParams; 8062 this.encryptionParams = encryptionParams; 8063 } 8064 8065 @Override 8066 public String toString() { 8067 return "InstallParams{" 8068 + Integer.toHexString(System.identityHashCode(this)) 8069 + " " + mPackageURI + "}"; 8070 } 8071 8072 public ManifestDigest getManifestDigest() { 8073 if (verificationParams == null) { 8074 return null; 8075 } 8076 return verificationParams.getManifestDigest(); 8077 } 8078 8079 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8080 String packageName = pkgLite.packageName; 8081 int installLocation = pkgLite.installLocation; 8082 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8083 // reader 8084 synchronized (mPackages) { 8085 PackageParser.Package pkg = mPackages.get(packageName); 8086 if (pkg != null) { 8087 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8088 // Check for downgrading. 8089 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8090 if (pkgLite.versionCode < pkg.mVersionCode) { 8091 Slog.w(TAG, "Can't install update of " + packageName 8092 + " update version " + pkgLite.versionCode 8093 + " is older than installed version " 8094 + pkg.mVersionCode); 8095 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8096 } 8097 } 8098 // Check for updated system application. 8099 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8100 if (onSd) { 8101 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8102 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8103 } 8104 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8105 } else { 8106 if (onSd) { 8107 // Install flag overrides everything. 8108 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8109 } 8110 // If current upgrade specifies particular preference 8111 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8112 // Application explicitly specified internal. 8113 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8114 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8115 // App explictly prefers external. Let policy decide 8116 } else { 8117 // Prefer previous location 8118 if (isExternal(pkg)) { 8119 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8120 } 8121 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8122 } 8123 } 8124 } else { 8125 // Invalid install. Return error code 8126 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8127 } 8128 } 8129 } 8130 // All the special cases have been taken care of. 8131 // Return result based on recommended install location. 8132 if (onSd) { 8133 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8134 } 8135 return pkgLite.recommendedInstallLocation; 8136 } 8137 8138 private long getMemoryLowThreshold() { 8139 final DeviceStorageMonitorInternal 8140 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8141 if (dsm == null) { 8142 return 0L; 8143 } 8144 return dsm.getMemoryLowThreshold(); 8145 } 8146 8147 /* 8148 * Invoke remote method to get package information and install 8149 * location values. Override install location based on default 8150 * policy if needed and then create install arguments based 8151 * on the install location. 8152 */ 8153 public void handleStartCopy() throws RemoteException { 8154 int ret = PackageManager.INSTALL_SUCCEEDED; 8155 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8156 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8157 PackageInfoLite pkgLite = null; 8158 8159 if (onInt && onSd) { 8160 // Check if both bits are set. 8161 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8162 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8163 } else { 8164 final long lowThreshold = getMemoryLowThreshold(); 8165 if (lowThreshold == 0L) { 8166 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8167 } 8168 8169 try { 8170 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI, 8171 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8172 8173 final File packageFile; 8174 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) { 8175 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir); 8176 if (mTempPackage != null) { 8177 ParcelFileDescriptor out; 8178 try { 8179 out = ParcelFileDescriptor.open(mTempPackage, 8180 ParcelFileDescriptor.MODE_READ_WRITE); 8181 } catch (FileNotFoundException e) { 8182 out = null; 8183 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI); 8184 } 8185 8186 // Make a temporary file for decryption. 8187 ret = mContainerService 8188 .copyResource(mPackageURI, encryptionParams, out); 8189 IoUtils.closeQuietly(out); 8190 8191 packageFile = mTempPackage; 8192 8193 FileUtils.setPermissions(packageFile.getAbsolutePath(), 8194 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP 8195 | FileUtils.S_IROTH, 8196 -1, -1); 8197 } else { 8198 packageFile = null; 8199 } 8200 } else { 8201 packageFile = new File(mPackageURI.getPath()); 8202 } 8203 8204 if (packageFile != null) { 8205 // Remote call to find out default install location 8206 final String packageFilePath = packageFile.getAbsolutePath(); 8207 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags, 8208 lowThreshold); 8209 8210 /* 8211 * If we have too little free space, try to free cache 8212 * before giving up. 8213 */ 8214 if (pkgLite.recommendedInstallLocation 8215 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8216 final long size = mContainerService.calculateInstalledSize( 8217 packageFilePath, isForwardLocked()); 8218 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8219 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, 8220 flags, lowThreshold); 8221 } 8222 /* 8223 * The cache free must have deleted the file we 8224 * downloaded to install. 8225 * 8226 * TODO: fix the "freeCache" call to not delete 8227 * the file we care about. 8228 */ 8229 if (pkgLite.recommendedInstallLocation 8230 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8231 pkgLite.recommendedInstallLocation 8232 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8233 } 8234 } 8235 } 8236 } finally { 8237 mContext.revokeUriPermission(mPackageURI, 8238 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8239 } 8240 } 8241 8242 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8243 int loc = pkgLite.recommendedInstallLocation; 8244 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8245 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8246 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8247 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8248 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8249 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8250 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8251 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8252 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8253 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8254 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8255 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8256 } else { 8257 // Override with defaults if needed. 8258 loc = installLocationPolicy(pkgLite, flags); 8259 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8260 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8261 } else if (!onSd && !onInt) { 8262 // Override install location with flags 8263 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8264 // Set the flag to install on external media. 8265 flags |= PackageManager.INSTALL_EXTERNAL; 8266 flags &= ~PackageManager.INSTALL_INTERNAL; 8267 } else { 8268 // Make sure the flag for installing on external 8269 // media is unset 8270 flags |= PackageManager.INSTALL_INTERNAL; 8271 flags &= ~PackageManager.INSTALL_EXTERNAL; 8272 } 8273 } 8274 } 8275 } 8276 8277 final InstallArgs args = createInstallArgs(this); 8278 mArgs = args; 8279 8280 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8281 /* 8282 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8283 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8284 */ 8285 int userIdentifier = getUser().getIdentifier(); 8286 if (userIdentifier == UserHandle.USER_ALL 8287 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8288 userIdentifier = UserHandle.USER_OWNER; 8289 } 8290 8291 /* 8292 * Determine if we have any installed package verifiers. If we 8293 * do, then we'll defer to them to verify the packages. 8294 */ 8295 final int requiredUid = mRequiredVerifierPackage == null ? -1 8296 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8297 if (requiredUid != -1 && isVerificationEnabled(flags)) { 8298 final Intent verification = new Intent( 8299 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8300 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE); 8301 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8302 8303 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8304 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8305 0 /* TODO: Which userId? */); 8306 8307 if (DEBUG_VERIFY) { 8308 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8309 + verification.toString() + " with " + pkgLite.verifiers.length 8310 + " optional verifiers"); 8311 } 8312 8313 final int verificationId = mPendingVerificationToken++; 8314 8315 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8316 8317 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8318 installerPackageName); 8319 8320 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8321 8322 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8323 pkgLite.packageName); 8324 8325 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8326 pkgLite.versionCode); 8327 8328 if (verificationParams != null) { 8329 if (verificationParams.getVerificationURI() != null) { 8330 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8331 verificationParams.getVerificationURI()); 8332 } 8333 if (verificationParams.getOriginatingURI() != null) { 8334 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8335 verificationParams.getOriginatingURI()); 8336 } 8337 if (verificationParams.getReferrer() != null) { 8338 verification.putExtra(Intent.EXTRA_REFERRER, 8339 verificationParams.getReferrer()); 8340 } 8341 if (verificationParams.getOriginatingUid() >= 0) { 8342 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8343 verificationParams.getOriginatingUid()); 8344 } 8345 if (verificationParams.getInstallerUid() >= 0) { 8346 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8347 verificationParams.getInstallerUid()); 8348 } 8349 } 8350 8351 final PackageVerificationState verificationState = new PackageVerificationState( 8352 requiredUid, args); 8353 8354 mPendingVerification.append(verificationId, verificationState); 8355 8356 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8357 receivers, verificationState); 8358 8359 /* 8360 * If any sufficient verifiers were listed in the package 8361 * manifest, attempt to ask them. 8362 */ 8363 if (sufficientVerifiers != null) { 8364 final int N = sufficientVerifiers.size(); 8365 if (N == 0) { 8366 Slog.i(TAG, "Additional verifiers required, but none installed."); 8367 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8368 } else { 8369 for (int i = 0; i < N; i++) { 8370 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8371 8372 final Intent sufficientIntent = new Intent(verification); 8373 sufficientIntent.setComponent(verifierComponent); 8374 8375 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8376 } 8377 } 8378 } 8379 8380 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8381 mRequiredVerifierPackage, receivers); 8382 if (ret == PackageManager.INSTALL_SUCCEEDED 8383 && mRequiredVerifierPackage != null) { 8384 /* 8385 * Send the intent to the required verification agent, 8386 * but only start the verification timeout after the 8387 * target BroadcastReceivers have run. 8388 */ 8389 verification.setComponent(requiredVerifierComponent); 8390 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8391 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8392 new BroadcastReceiver() { 8393 @Override 8394 public void onReceive(Context context, Intent intent) { 8395 final Message msg = mHandler 8396 .obtainMessage(CHECK_PENDING_VERIFICATION); 8397 msg.arg1 = verificationId; 8398 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8399 } 8400 }, null, 0, null, null); 8401 8402 /* 8403 * We don't want the copy to proceed until verification 8404 * succeeds, so null out this field. 8405 */ 8406 mArgs = null; 8407 } 8408 } else { 8409 /* 8410 * No package verification is enabled, so immediately start 8411 * the remote call to initiate copy using temporary file. 8412 */ 8413 ret = args.copyApk(mContainerService, true); 8414 } 8415 } 8416 8417 mRet = ret; 8418 } 8419 8420 @Override 8421 void handleReturnCode() { 8422 // If mArgs is null, then MCS couldn't be reached. When it 8423 // reconnects, it will try again to install. At that point, this 8424 // will succeed. 8425 if (mArgs != null) { 8426 processPendingInstall(mArgs, mRet); 8427 8428 if (mTempPackage != null) { 8429 if (!mTempPackage.delete()) { 8430 Slog.w(TAG, "Couldn't delete temporary file: " + 8431 mTempPackage.getAbsolutePath()); 8432 } 8433 } 8434 } 8435 } 8436 8437 @Override 8438 void handleServiceError() { 8439 mArgs = createInstallArgs(this); 8440 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8441 } 8442 8443 public boolean isForwardLocked() { 8444 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8445 } 8446 8447 public Uri getPackageUri() { 8448 if (mTempPackage != null) { 8449 return Uri.fromFile(mTempPackage); 8450 } else { 8451 return mPackageURI; 8452 } 8453 } 8454 } 8455 8456 /* 8457 * Utility class used in movePackage api. 8458 * srcArgs and targetArgs are not set for invalid flags and make 8459 * sure to do null checks when invoking methods on them. 8460 * We probably want to return ErrorPrams for both failed installs 8461 * and moves. 8462 */ 8463 class MoveParams extends HandlerParams { 8464 final IPackageMoveObserver observer; 8465 final int flags; 8466 final String packageName; 8467 final InstallArgs srcArgs; 8468 final InstallArgs targetArgs; 8469 int uid; 8470 int mRet; 8471 8472 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8473 String packageName, String dataDir, String instructionSet, 8474 int uid, UserHandle user) { 8475 super(user); 8476 this.srcArgs = srcArgs; 8477 this.observer = observer; 8478 this.flags = flags; 8479 this.packageName = packageName; 8480 this.uid = uid; 8481 if (srcArgs != null) { 8482 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath())); 8483 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet); 8484 } else { 8485 targetArgs = null; 8486 } 8487 } 8488 8489 @Override 8490 public String toString() { 8491 return "MoveParams{" 8492 + Integer.toHexString(System.identityHashCode(this)) 8493 + " " + packageName + "}"; 8494 } 8495 8496 public void handleStartCopy() throws RemoteException { 8497 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8498 // Check for storage space on target medium 8499 if (!targetArgs.checkFreeStorage(mContainerService)) { 8500 Log.w(TAG, "Insufficient storage to install"); 8501 return; 8502 } 8503 8504 mRet = srcArgs.doPreCopy(); 8505 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8506 return; 8507 } 8508 8509 mRet = targetArgs.copyApk(mContainerService, false); 8510 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8511 srcArgs.doPostCopy(uid); 8512 return; 8513 } 8514 8515 mRet = srcArgs.doPostCopy(uid); 8516 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8517 return; 8518 } 8519 8520 mRet = targetArgs.doPreInstall(mRet); 8521 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8522 return; 8523 } 8524 8525 if (DEBUG_SD_INSTALL) { 8526 StringBuilder builder = new StringBuilder(); 8527 if (srcArgs != null) { 8528 builder.append("src: "); 8529 builder.append(srcArgs.getCodePath()); 8530 } 8531 if (targetArgs != null) { 8532 builder.append(" target : "); 8533 builder.append(targetArgs.getCodePath()); 8534 } 8535 Log.i(TAG, builder.toString()); 8536 } 8537 } 8538 8539 @Override 8540 void handleReturnCode() { 8541 targetArgs.doPostInstall(mRet, uid); 8542 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8543 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8544 currentStatus = PackageManager.MOVE_SUCCEEDED; 8545 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8546 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8547 } 8548 processPendingMove(this, currentStatus); 8549 } 8550 8551 @Override 8552 void handleServiceError() { 8553 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8554 } 8555 } 8556 8557 /** 8558 * Used during creation of InstallArgs 8559 * 8560 * @param flags package installation flags 8561 * @return true if should be installed on external storage 8562 */ 8563 private static boolean installOnSd(int flags) { 8564 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8565 return false; 8566 } 8567 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8568 return true; 8569 } 8570 return false; 8571 } 8572 8573 /** 8574 * Used during creation of InstallArgs 8575 * 8576 * @param flags package installation flags 8577 * @return true if should be installed as forward locked 8578 */ 8579 private static boolean installForwardLocked(int flags) { 8580 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8581 } 8582 8583 private InstallArgs createInstallArgs(InstallParams params) { 8584 if (installOnSd(params.flags) || params.isForwardLocked()) { 8585 return new AsecInstallArgs(params); 8586 } else { 8587 return new FileInstallArgs(params); 8588 } 8589 } 8590 8591 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath, 8592 String nativeLibraryPath, String instructionSet) { 8593 final boolean isInAsec; 8594 if (installOnSd(flags)) { 8595 /* Apps on SD card are always in ASEC containers. */ 8596 isInAsec = true; 8597 } else if (installForwardLocked(flags) 8598 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8599 /* 8600 * Forward-locked apps are only in ASEC containers if they're the 8601 * new style 8602 */ 8603 isInAsec = true; 8604 } else { 8605 isInAsec = false; 8606 } 8607 8608 if (isInAsec) { 8609 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8610 instructionSet, installOnSd(flags), installForwardLocked(flags)); 8611 } else { 8612 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8613 instructionSet); 8614 } 8615 } 8616 8617 // Used by package mover 8618 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir, 8619 String instructionSet) { 8620 if (installOnSd(flags) || installForwardLocked(flags)) { 8621 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/" 8622 + AsecInstallArgs.RES_FILE_NAME); 8623 return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags), 8624 installForwardLocked(flags)); 8625 } else { 8626 return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet); 8627 } 8628 } 8629 8630 static abstract class InstallArgs { 8631 final IPackageInstallObserver observer; 8632 final IPackageInstallObserver2 observer2; 8633 // Always refers to PackageManager flags only 8634 final int flags; 8635 final Uri packageURI; 8636 final String installerPackageName; 8637 final ManifestDigest manifestDigest; 8638 final UserHandle user; 8639 final String instructionSet; 8640 8641 InstallArgs(Uri packageURI, 8642 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 8643 int flags, String installerPackageName, ManifestDigest manifestDigest, 8644 UserHandle user, String instructionSet) { 8645 this.packageURI = packageURI; 8646 this.flags = flags; 8647 this.observer = observer; 8648 this.observer2 = observer2; 8649 this.installerPackageName = installerPackageName; 8650 this.manifestDigest = manifestDigest; 8651 this.user = user; 8652 this.instructionSet = instructionSet; 8653 } 8654 8655 abstract void createCopyFile(); 8656 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 8657 abstract int doPreInstall(int status); 8658 abstract boolean doRename(int status, String pkgName, String oldCodePath); 8659 8660 abstract int doPostInstall(int status, int uid); 8661 abstract String getCodePath(); 8662 abstract String getResourcePath(); 8663 abstract String getNativeLibraryPath(); 8664 // Need installer lock especially for dex file removal. 8665 abstract void cleanUpResourcesLI(); 8666 abstract boolean doPostDeleteLI(boolean delete); 8667 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 8668 8669 /** 8670 * Called before the source arguments are copied. This is used mostly 8671 * for MoveParams when it needs to read the source file to put it in the 8672 * destination. 8673 */ 8674 int doPreCopy() { 8675 return PackageManager.INSTALL_SUCCEEDED; 8676 } 8677 8678 /** 8679 * Called after the source arguments are copied. This is used mostly for 8680 * MoveParams when it needs to read the source file to put it in the 8681 * destination. 8682 * 8683 * @return 8684 */ 8685 int doPostCopy(int uid) { 8686 return PackageManager.INSTALL_SUCCEEDED; 8687 } 8688 8689 protected boolean isFwdLocked() { 8690 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8691 } 8692 8693 UserHandle getUser() { 8694 return user; 8695 } 8696 } 8697 8698 class FileInstallArgs extends InstallArgs { 8699 File installDir; 8700 String codeFileName; 8701 String resourceFileName; 8702 String libraryPath; 8703 boolean created = false; 8704 8705 FileInstallArgs(InstallParams params) { 8706 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 8707 params.installerPackageName, params.getManifestDigest(), 8708 params.getUser(), null /* instruction set */); 8709 } 8710 8711 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 8712 String instructionSet) { 8713 super(null, null, null, 0, null, null, null, instructionSet); 8714 File codeFile = new File(fullCodePath); 8715 installDir = codeFile.getParentFile(); 8716 codeFileName = fullCodePath; 8717 resourceFileName = fullResourcePath; 8718 libraryPath = nativeLibraryPath; 8719 } 8720 8721 FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) { 8722 super(packageURI, null, null, 0, null, null, null, instructionSet); 8723 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 8724 String apkName = getNextCodePath(null, pkgName, ".apk"); 8725 codeFileName = new File(installDir, apkName + ".apk").getPath(); 8726 resourceFileName = getResourcePathFromCodePath(); 8727 libraryPath = new File(mAppLibInstallDir, pkgName).getPath(); 8728 } 8729 8730 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 8731 final long lowThreshold; 8732 8733 final DeviceStorageMonitorInternal 8734 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8735 if (dsm == null) { 8736 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8737 lowThreshold = 0L; 8738 } else { 8739 if (dsm.isMemoryLow()) { 8740 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 8741 return false; 8742 } 8743 8744 lowThreshold = dsm.getMemoryLowThreshold(); 8745 } 8746 8747 try { 8748 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8749 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8750 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold); 8751 } finally { 8752 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8753 } 8754 } 8755 8756 String getCodePath() { 8757 return codeFileName; 8758 } 8759 8760 void createCopyFile() { 8761 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 8762 codeFileName = createTempPackageFile(installDir).getPath(); 8763 resourceFileName = getResourcePathFromCodePath(); 8764 libraryPath = getLibraryPathFromCodePath(); 8765 created = true; 8766 } 8767 8768 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 8769 if (temp) { 8770 // Generate temp file name 8771 createCopyFile(); 8772 } 8773 // Get a ParcelFileDescriptor to write to the output file 8774 File codeFile = new File(codeFileName); 8775 if (!created) { 8776 try { 8777 codeFile.createNewFile(); 8778 // Set permissions 8779 if (!setPermissions()) { 8780 // Failed setting permissions. 8781 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8782 } 8783 } catch (IOException e) { 8784 Slog.w(TAG, "Failed to create file " + codeFile); 8785 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8786 } 8787 } 8788 ParcelFileDescriptor out = null; 8789 try { 8790 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 8791 } catch (FileNotFoundException e) { 8792 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 8793 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8794 } 8795 // Copy the resource now 8796 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8797 try { 8798 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8799 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8800 ret = imcs.copyResource(packageURI, null, out); 8801 } finally { 8802 IoUtils.closeQuietly(out); 8803 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8804 } 8805 8806 if (isFwdLocked()) { 8807 final File destResourceFile = new File(getResourcePath()); 8808 8809 // Copy the public files 8810 try { 8811 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 8812 } catch (IOException e) { 8813 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 8814 + " forward-locked app."); 8815 destResourceFile.delete(); 8816 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8817 } 8818 } 8819 8820 final File nativeLibraryFile = new File(getNativeLibraryPath()); 8821 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath()); 8822 if (nativeLibraryFile.exists()) { 8823 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 8824 nativeLibraryFile.delete(); 8825 } 8826 try { 8827 int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile); 8828 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8829 return copyRet; 8830 } 8831 } catch (IOException e) { 8832 Slog.e(TAG, "Copying native libraries failed", e); 8833 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8834 } 8835 8836 return ret; 8837 } 8838 8839 int doPreInstall(int status) { 8840 if (status != PackageManager.INSTALL_SUCCEEDED) { 8841 cleanUp(); 8842 } 8843 return status; 8844 } 8845 8846 boolean doRename(int status, final String pkgName, String oldCodePath) { 8847 if (status != PackageManager.INSTALL_SUCCEEDED) { 8848 cleanUp(); 8849 return false; 8850 } else { 8851 final File oldCodeFile = new File(getCodePath()); 8852 final File oldResourceFile = new File(getResourcePath()); 8853 final File oldLibraryFile = new File(getNativeLibraryPath()); 8854 8855 // Rename APK file based on packageName 8856 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 8857 final File newCodeFile = new File(installDir, apkName + ".apk"); 8858 if (!oldCodeFile.renameTo(newCodeFile)) { 8859 return false; 8860 } 8861 codeFileName = newCodeFile.getPath(); 8862 8863 // Rename public resource file if it's forward-locked. 8864 final File newResFile = new File(getResourcePathFromCodePath()); 8865 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 8866 return false; 8867 } 8868 resourceFileName = newResFile.getPath(); 8869 8870 // Rename library path 8871 final File newLibraryFile = new File(getLibraryPathFromCodePath()); 8872 if (newLibraryFile.exists()) { 8873 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile); 8874 newLibraryFile.delete(); 8875 } 8876 if (!oldLibraryFile.renameTo(newLibraryFile)) { 8877 Slog.e(TAG, "Cannot rename native library directory " 8878 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath()); 8879 return false; 8880 } 8881 libraryPath = newLibraryFile.getPath(); 8882 8883 // Attempt to set permissions 8884 if (!setPermissions()) { 8885 return false; 8886 } 8887 8888 if (!SELinux.restorecon(newCodeFile)) { 8889 return false; 8890 } 8891 8892 return true; 8893 } 8894 } 8895 8896 int doPostInstall(int status, int uid) { 8897 if (status != PackageManager.INSTALL_SUCCEEDED) { 8898 cleanUp(); 8899 } 8900 return status; 8901 } 8902 8903 String getResourcePath() { 8904 return resourceFileName; 8905 } 8906 8907 private String getResourcePathFromCodePath() { 8908 final String codePath = getCodePath(); 8909 if (isFwdLocked()) { 8910 final StringBuilder sb = new StringBuilder(); 8911 8912 sb.append(mAppInstallDir.getPath()); 8913 sb.append('/'); 8914 sb.append(getApkName(codePath)); 8915 sb.append(".zip"); 8916 8917 /* 8918 * If our APK is a temporary file, mark the resource as a 8919 * temporary file as well so it can be cleaned up after 8920 * catastrophic failure. 8921 */ 8922 if (codePath.endsWith(".tmp")) { 8923 sb.append(".tmp"); 8924 } 8925 8926 return sb.toString(); 8927 } else { 8928 return codePath; 8929 } 8930 } 8931 8932 private String getLibraryPathFromCodePath() { 8933 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath(); 8934 } 8935 8936 @Override 8937 String getNativeLibraryPath() { 8938 if (libraryPath == null) { 8939 libraryPath = getLibraryPathFromCodePath(); 8940 } 8941 return libraryPath; 8942 } 8943 8944 private boolean cleanUp() { 8945 boolean ret = true; 8946 String sourceDir = getCodePath(); 8947 String publicSourceDir = getResourcePath(); 8948 if (sourceDir != null) { 8949 File sourceFile = new File(sourceDir); 8950 if (!sourceFile.exists()) { 8951 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 8952 ret = false; 8953 } 8954 // Delete application's code and resources 8955 sourceFile.delete(); 8956 } 8957 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 8958 final File publicSourceFile = new File(publicSourceDir); 8959 if (!publicSourceFile.exists()) { 8960 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 8961 } 8962 if (publicSourceFile.exists()) { 8963 publicSourceFile.delete(); 8964 } 8965 } 8966 8967 if (libraryPath != null) { 8968 File nativeLibraryFile = new File(libraryPath); 8969 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 8970 if (!nativeLibraryFile.delete()) { 8971 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath); 8972 } 8973 } 8974 8975 return ret; 8976 } 8977 8978 void cleanUpResourcesLI() { 8979 String sourceDir = getCodePath(); 8980 if (cleanUp()) { 8981 if (instructionSet == null) { 8982 throw new IllegalStateException("instructionSet == null"); 8983 } 8984 int retCode = mInstaller.rmdex(sourceDir, instructionSet); 8985 if (retCode < 0) { 8986 Slog.w(TAG, "Couldn't remove dex file for package: " 8987 + " at location " 8988 + sourceDir + ", retcode=" + retCode); 8989 // we don't consider this to be a failure of the core package deletion 8990 } 8991 } 8992 } 8993 8994 private boolean setPermissions() { 8995 // TODO Do this in a more elegant way later on. for now just a hack 8996 if (!isFwdLocked()) { 8997 final int filePermissions = 8998 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 8999 |FileUtils.S_IROTH; 9000 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 9001 if (retCode != 0) { 9002 Slog.e(TAG, "Couldn't set new package file permissions for " + 9003 getCodePath() 9004 + ". The return code was: " + retCode); 9005 // TODO Define new internal error 9006 return false; 9007 } 9008 return true; 9009 } 9010 return true; 9011 } 9012 9013 boolean doPostDeleteLI(boolean delete) { 9014 // XXX err, shouldn't we respect the delete flag? 9015 cleanUpResourcesLI(); 9016 return true; 9017 } 9018 } 9019 9020 private boolean isAsecExternal(String cid) { 9021 final String asecPath = PackageHelper.getSdFilesystem(cid); 9022 return !asecPath.startsWith(mAsecInternalPath); 9023 } 9024 9025 /** 9026 * Extract the MountService "container ID" from the full code path of an 9027 * .apk. 9028 */ 9029 static String cidFromCodePath(String fullCodePath) { 9030 int eidx = fullCodePath.lastIndexOf("/"); 9031 String subStr1 = fullCodePath.substring(0, eidx); 9032 int sidx = subStr1.lastIndexOf("/"); 9033 return subStr1.substring(sidx+1, eidx); 9034 } 9035 9036 class AsecInstallArgs extends InstallArgs { 9037 static final String RES_FILE_NAME = "pkg.apk"; 9038 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9039 9040 String cid; 9041 String packagePath; 9042 String resourcePath; 9043 String libraryPath; 9044 9045 AsecInstallArgs(InstallParams params) { 9046 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 9047 params.installerPackageName, params.getManifestDigest(), 9048 params.getUser(), null /* instruction set */); 9049 } 9050 9051 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9052 String instructionSet, boolean isExternal, boolean isForwardLocked) { 9053 super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9054 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9055 null, null, null, instructionSet); 9056 // Extract cid from fullCodePath 9057 int eidx = fullCodePath.lastIndexOf("/"); 9058 String subStr1 = fullCodePath.substring(0, eidx); 9059 int sidx = subStr1.lastIndexOf("/"); 9060 cid = subStr1.substring(sidx+1, eidx); 9061 setCachePath(subStr1); 9062 } 9063 9064 AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) { 9065 super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 9066 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9067 null, null, null, instructionSet); 9068 this.cid = cid; 9069 setCachePath(PackageHelper.getSdDir(cid)); 9070 } 9071 9072 AsecInstallArgs(Uri packageURI, String cid, String instructionSet, 9073 boolean isExternal, boolean isForwardLocked) { 9074 super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9075 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9076 null, null, null, instructionSet); 9077 this.cid = cid; 9078 } 9079 9080 void createCopyFile() { 9081 cid = getTempContainerId(); 9082 } 9083 9084 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9085 try { 9086 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9087 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9088 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked()); 9089 } finally { 9090 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9091 } 9092 } 9093 9094 private final boolean isExternal() { 9095 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9096 } 9097 9098 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9099 if (temp) { 9100 createCopyFile(); 9101 } else { 9102 /* 9103 * Pre-emptively destroy the container since it's destroyed if 9104 * copying fails due to it existing anyway. 9105 */ 9106 PackageHelper.destroySdDir(cid); 9107 } 9108 9109 final String newCachePath; 9110 try { 9111 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9112 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9113 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(), 9114 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked()); 9115 } finally { 9116 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9117 } 9118 9119 if (newCachePath != null) { 9120 setCachePath(newCachePath); 9121 return PackageManager.INSTALL_SUCCEEDED; 9122 } else { 9123 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9124 } 9125 } 9126 9127 @Override 9128 String getCodePath() { 9129 return packagePath; 9130 } 9131 9132 @Override 9133 String getResourcePath() { 9134 return resourcePath; 9135 } 9136 9137 @Override 9138 String getNativeLibraryPath() { 9139 return libraryPath; 9140 } 9141 9142 int doPreInstall(int status) { 9143 if (status != PackageManager.INSTALL_SUCCEEDED) { 9144 // Destroy container 9145 PackageHelper.destroySdDir(cid); 9146 } else { 9147 boolean mounted = PackageHelper.isContainerMounted(cid); 9148 if (!mounted) { 9149 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9150 Process.SYSTEM_UID); 9151 if (newCachePath != null) { 9152 setCachePath(newCachePath); 9153 } else { 9154 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9155 } 9156 } 9157 } 9158 return status; 9159 } 9160 9161 boolean doRename(int status, final String pkgName, 9162 String oldCodePath) { 9163 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 9164 String newCachePath = null; 9165 if (PackageHelper.isContainerMounted(cid)) { 9166 // Unmount the container 9167 if (!PackageHelper.unMountSdDir(cid)) { 9168 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9169 return false; 9170 } 9171 } 9172 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9173 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9174 " which might be stale. Will try to clean up."); 9175 // Clean up the stale container and proceed to recreate. 9176 if (!PackageHelper.destroySdDir(newCacheId)) { 9177 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9178 return false; 9179 } 9180 // Successfully cleaned up stale container. Try to rename again. 9181 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9182 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9183 + " inspite of cleaning it up."); 9184 return false; 9185 } 9186 } 9187 if (!PackageHelper.isContainerMounted(newCacheId)) { 9188 Slog.w(TAG, "Mounting container " + newCacheId); 9189 newCachePath = PackageHelper.mountSdDir(newCacheId, 9190 getEncryptKey(), Process.SYSTEM_UID); 9191 } else { 9192 newCachePath = PackageHelper.getSdDir(newCacheId); 9193 } 9194 if (newCachePath == null) { 9195 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9196 return false; 9197 } 9198 Log.i(TAG, "Succesfully renamed " + cid + 9199 " to " + newCacheId + 9200 " at new path: " + newCachePath); 9201 cid = newCacheId; 9202 setCachePath(newCachePath); 9203 return true; 9204 } 9205 9206 private void setCachePath(String newCachePath) { 9207 File cachePath = new File(newCachePath); 9208 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 9209 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9210 9211 if (isFwdLocked()) { 9212 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9213 } else { 9214 resourcePath = packagePath; 9215 } 9216 } 9217 9218 int doPostInstall(int status, int uid) { 9219 if (status != PackageManager.INSTALL_SUCCEEDED) { 9220 cleanUp(); 9221 } else { 9222 final int groupOwner; 9223 final String protectedFile; 9224 if (isFwdLocked()) { 9225 groupOwner = UserHandle.getSharedAppGid(uid); 9226 protectedFile = RES_FILE_NAME; 9227 } else { 9228 groupOwner = -1; 9229 protectedFile = null; 9230 } 9231 9232 if (uid < Process.FIRST_APPLICATION_UID 9233 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9234 Slog.e(TAG, "Failed to finalize " + cid); 9235 PackageHelper.destroySdDir(cid); 9236 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9237 } 9238 9239 boolean mounted = PackageHelper.isContainerMounted(cid); 9240 if (!mounted) { 9241 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9242 } 9243 } 9244 return status; 9245 } 9246 9247 private void cleanUp() { 9248 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9249 9250 // Destroy secure container 9251 PackageHelper.destroySdDir(cid); 9252 } 9253 9254 void cleanUpResourcesLI() { 9255 String sourceFile = getCodePath(); 9256 // Remove dex file 9257 if (instructionSet == null) { 9258 throw new IllegalStateException("instructionSet == null"); 9259 } 9260 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9261 if (retCode < 0) { 9262 Slog.w(TAG, "Couldn't remove dex file for package: " 9263 + " at location " 9264 + sourceFile.toString() + ", retcode=" + retCode); 9265 // we don't consider this to be a failure of the core package deletion 9266 } 9267 cleanUp(); 9268 } 9269 9270 boolean matchContainer(String app) { 9271 if (cid.startsWith(app)) { 9272 return true; 9273 } 9274 return false; 9275 } 9276 9277 String getPackageName() { 9278 return getAsecPackageName(cid); 9279 } 9280 9281 boolean doPostDeleteLI(boolean delete) { 9282 boolean ret = false; 9283 boolean mounted = PackageHelper.isContainerMounted(cid); 9284 if (mounted) { 9285 // Unmount first 9286 ret = PackageHelper.unMountSdDir(cid); 9287 } 9288 if (ret && delete) { 9289 cleanUpResourcesLI(); 9290 } 9291 return ret; 9292 } 9293 9294 @Override 9295 int doPreCopy() { 9296 if (isFwdLocked()) { 9297 if (!PackageHelper.fixSdPermissions(cid, 9298 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9299 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9300 } 9301 } 9302 9303 return PackageManager.INSTALL_SUCCEEDED; 9304 } 9305 9306 @Override 9307 int doPostCopy(int uid) { 9308 if (isFwdLocked()) { 9309 if (uid < Process.FIRST_APPLICATION_UID 9310 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9311 RES_FILE_NAME)) { 9312 Slog.e(TAG, "Failed to finalize " + cid); 9313 PackageHelper.destroySdDir(cid); 9314 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9315 } 9316 } 9317 9318 return PackageManager.INSTALL_SUCCEEDED; 9319 } 9320 }; 9321 9322 static String getAsecPackageName(String packageCid) { 9323 int idx = packageCid.lastIndexOf("-"); 9324 if (idx == -1) { 9325 return packageCid; 9326 } 9327 return packageCid.substring(0, idx); 9328 } 9329 9330 // Utility method used to create code paths based on package name and available index. 9331 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9332 String idxStr = ""; 9333 int idx = 1; 9334 // Fall back to default value of idx=1 if prefix is not 9335 // part of oldCodePath 9336 if (oldCodePath != null) { 9337 String subStr = oldCodePath; 9338 // Drop the suffix right away 9339 if (subStr.endsWith(suffix)) { 9340 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9341 } 9342 // If oldCodePath already contains prefix find out the 9343 // ending index to either increment or decrement. 9344 int sidx = subStr.lastIndexOf(prefix); 9345 if (sidx != -1) { 9346 subStr = subStr.substring(sidx + prefix.length()); 9347 if (subStr != null) { 9348 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9349 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9350 } 9351 try { 9352 idx = Integer.parseInt(subStr); 9353 if (idx <= 1) { 9354 idx++; 9355 } else { 9356 idx--; 9357 } 9358 } catch(NumberFormatException e) { 9359 } 9360 } 9361 } 9362 } 9363 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9364 return prefix + idxStr; 9365 } 9366 9367 // Utility method used to ignore ADD/REMOVE events 9368 // by directory observer. 9369 private static boolean ignoreCodePath(String fullPathStr) { 9370 String apkName = getApkName(fullPathStr); 9371 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9372 if (idx != -1 && ((idx+1) < apkName.length())) { 9373 // Make sure the package ends with a numeral 9374 String version = apkName.substring(idx+1); 9375 try { 9376 Integer.parseInt(version); 9377 return true; 9378 } catch (NumberFormatException e) {} 9379 } 9380 return false; 9381 } 9382 9383 // Utility method that returns the relative package path with respect 9384 // to the installation directory. Like say for /data/data/com.test-1.apk 9385 // string com.test-1 is returned. 9386 static String getApkName(String codePath) { 9387 if (codePath == null) { 9388 return null; 9389 } 9390 int sidx = codePath.lastIndexOf("/"); 9391 int eidx = codePath.lastIndexOf("."); 9392 if (eidx == -1) { 9393 eidx = codePath.length(); 9394 } else if (eidx == 0) { 9395 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 9396 return null; 9397 } 9398 return codePath.substring(sidx+1, eidx); 9399 } 9400 9401 class PackageInstalledInfo { 9402 String name; 9403 int uid; 9404 // The set of users that originally had this package installed. 9405 int[] origUsers; 9406 // The set of users that now have this package installed. 9407 int[] newUsers; 9408 PackageParser.Package pkg; 9409 int returnCode; 9410 PackageRemovedInfo removedInfo; 9411 9412 // In some error cases we want to convey more info back to the observer 9413 String origPackage; 9414 String origPermission; 9415 } 9416 9417 /* 9418 * Install a non-existing package. 9419 */ 9420 private void installNewPackageLI(PackageParser.Package pkg, 9421 int parseFlags, int scanMode, UserHandle user, 9422 String installerPackageName, PackageInstalledInfo res) { 9423 // Remember this for later, in case we need to rollback this install 9424 String pkgName = pkg.packageName; 9425 9426 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9427 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9428 synchronized(mPackages) { 9429 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9430 // A package with the same name is already installed, though 9431 // it has been renamed to an older name. The package we 9432 // are trying to install should be installed as an update to 9433 // the existing one, but that has not been requested, so bail. 9434 Slog.w(TAG, "Attempt to re-install " + pkgName 9435 + " without first uninstalling package running as " 9436 + mSettings.mRenamedPackages.get(pkgName)); 9437 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9438 return; 9439 } 9440 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) { 9441 // Don't allow installation over an existing package with the same name. 9442 Slog.w(TAG, "Attempt to re-install " + pkgName 9443 + " without first uninstalling."); 9444 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9445 return; 9446 } 9447 } 9448 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9449 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9450 System.currentTimeMillis(), user); 9451 if (newPackage == null) { 9452 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9453 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9454 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9455 } 9456 } else { 9457 updateSettingsLI(newPackage, 9458 installerPackageName, 9459 null, null, 9460 res); 9461 // delete the partially installed application. the data directory will have to be 9462 // restored if it was already existing 9463 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9464 // remove package from internal structures. Note that we want deletePackageX to 9465 // delete the package data and cache directories that it created in 9466 // scanPackageLocked, unless those directories existed before we even tried to 9467 // install. 9468 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9469 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9470 res.removedInfo, true); 9471 } 9472 } 9473 } 9474 9475 private void replacePackageLI(PackageParser.Package pkg, 9476 int parseFlags, int scanMode, UserHandle user, 9477 String installerPackageName, PackageInstalledInfo res) { 9478 9479 PackageParser.Package oldPackage; 9480 String pkgName = pkg.packageName; 9481 int[] allUsers; 9482 boolean[] perUserInstalled; 9483 9484 // First find the old package info and check signatures 9485 synchronized(mPackages) { 9486 oldPackage = mPackages.get(pkgName); 9487 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9488 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9489 != PackageManager.SIGNATURE_MATCH) { 9490 Slog.w(TAG, "New package has a different signature: " + pkgName); 9491 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9492 return; 9493 } 9494 9495 // In case of rollback, remember per-user/profile install state 9496 PackageSetting ps = mSettings.mPackages.get(pkgName); 9497 allUsers = sUserManager.getUserIds(); 9498 perUserInstalled = new boolean[allUsers.length]; 9499 for (int i = 0; i < allUsers.length; i++) { 9500 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9501 } 9502 } 9503 boolean sysPkg = (isSystemApp(oldPackage)); 9504 if (sysPkg) { 9505 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9506 user, allUsers, perUserInstalled, installerPackageName, res); 9507 } else { 9508 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9509 user, allUsers, perUserInstalled, installerPackageName, res); 9510 } 9511 } 9512 9513 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9514 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9515 int[] allUsers, boolean[] perUserInstalled, 9516 String installerPackageName, PackageInstalledInfo res) { 9517 PackageParser.Package newPackage = null; 9518 String pkgName = deletedPackage.packageName; 9519 boolean deletedPkg = true; 9520 boolean updatedSettings = false; 9521 9522 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9523 + deletedPackage); 9524 long origUpdateTime; 9525 if (pkg.mExtras != null) { 9526 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9527 } else { 9528 origUpdateTime = 0; 9529 } 9530 9531 // First delete the existing package while retaining the data directory 9532 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9533 res.removedInfo, true)) { 9534 // If the existing package wasn't successfully deleted 9535 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9536 deletedPkg = false; 9537 } else { 9538 // Successfully deleted the old package. Now proceed with re-installation 9539 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9540 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9541 System.currentTimeMillis(), user); 9542 if (newPackage == null) { 9543 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9544 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9545 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9546 } 9547 } else { 9548 updateSettingsLI(newPackage, 9549 installerPackageName, 9550 allUsers, perUserInstalled, 9551 res); 9552 updatedSettings = true; 9553 } 9554 } 9555 9556 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9557 // remove package from internal structures. Note that we want deletePackageX to 9558 // delete the package data and cache directories that it created in 9559 // scanPackageLocked, unless those directories existed before we even tried to 9560 // install. 9561 if(updatedSettings) { 9562 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9563 deletePackageLI( 9564 pkgName, null, true, allUsers, perUserInstalled, 9565 PackageManager.DELETE_KEEP_DATA, 9566 res.removedInfo, true); 9567 } 9568 // Since we failed to install the new package we need to restore the old 9569 // package that we deleted. 9570 if(deletedPkg) { 9571 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9572 File restoreFile = new File(deletedPackage.mPath); 9573 // Parse old package 9574 boolean oldOnSd = isExternal(deletedPackage); 9575 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9576 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9577 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9578 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 9579 | SCAN_UPDATE_TIME; 9580 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 9581 origUpdateTime, null) == null) { 9582 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 9583 return; 9584 } 9585 // Restore of old package succeeded. Update permissions. 9586 // writer 9587 synchronized (mPackages) { 9588 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9589 UPDATE_PERMISSIONS_ALL); 9590 // can downgrade to reader 9591 mSettings.writeLPr(); 9592 } 9593 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9594 } 9595 } 9596 } 9597 9598 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9599 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9600 int[] allUsers, boolean[] perUserInstalled, 9601 String installerPackageName, PackageInstalledInfo res) { 9602 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9603 + ", old=" + deletedPackage); 9604 PackageParser.Package newPackage = null; 9605 boolean updatedSettings = false; 9606 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 9607 PackageParser.PARSE_IS_SYSTEM; 9608 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9609 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9610 } 9611 String packageName = deletedPackage.packageName; 9612 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9613 if (packageName == null) { 9614 Slog.w(TAG, "Attempt to delete null packageName."); 9615 return; 9616 } 9617 PackageParser.Package oldPkg; 9618 PackageSetting oldPkgSetting; 9619 // reader 9620 synchronized (mPackages) { 9621 oldPkg = mPackages.get(packageName); 9622 oldPkgSetting = mSettings.mPackages.get(packageName); 9623 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 9624 (oldPkgSetting == null)) { 9625 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 9626 return; 9627 } 9628 } 9629 9630 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 9631 9632 res.removedInfo.uid = oldPkg.applicationInfo.uid; 9633 res.removedInfo.removedPackage = packageName; 9634 // Remove existing system package 9635 removePackageLI(oldPkgSetting, true); 9636 // writer 9637 synchronized (mPackages) { 9638 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 9639 // We didn't need to disable the .apk as a current system package, 9640 // which means we are replacing another update that is already 9641 // installed. We need to make sure to delete the older one's .apk. 9642 res.removedInfo.args = createInstallArgs(0, 9643 deletedPackage.applicationInfo.sourceDir, 9644 deletedPackage.applicationInfo.publicSourceDir, 9645 deletedPackage.applicationInfo.nativeLibraryDir, 9646 getAppInstructionSet(deletedPackage.applicationInfo)); 9647 } else { 9648 res.removedInfo.args = null; 9649 } 9650 } 9651 9652 // Successfully disabled the old package. Now proceed with re-installation 9653 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9654 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9655 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user); 9656 if (newPackage == null) { 9657 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9658 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9659 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9660 } 9661 } else { 9662 if (newPackage.mExtras != null) { 9663 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 9664 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 9665 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 9666 9667 // is the update attempting to change shared user? that isn't going to work... 9668 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 9669 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 9670 + " to " + newPkgSetting.sharedUser); 9671 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 9672 updatedSettings = true; 9673 } 9674 } 9675 9676 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9677 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9678 updatedSettings = true; 9679 } 9680 } 9681 9682 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9683 // Re installation failed. Restore old information 9684 // Remove new pkg information 9685 if (newPackage != null) { 9686 removeInstalledPackageLI(newPackage, true); 9687 } 9688 // Add back the old system package 9689 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user); 9690 // Restore the old system information in Settings 9691 synchronized(mPackages) { 9692 if (updatedSettings) { 9693 mSettings.enableSystemPackageLPw(packageName); 9694 mSettings.setInstallerPackageName(packageName, 9695 oldPkgSetting.installerPackageName); 9696 } 9697 mSettings.writeLPr(); 9698 } 9699 } 9700 } 9701 9702 // Utility method used to move dex files during install. 9703 private int moveDexFilesLI(PackageParser.Package newPackage) { 9704 int retCode; 9705 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 9706 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath, 9707 getAppInstructionSet(newPackage.applicationInfo)); 9708 if (retCode != 0) { 9709 if (mNoDexOpt) { 9710 /* 9711 * If we're in an engineering build, programs are lazily run 9712 * through dexopt. If the .dex file doesn't exist yet, it 9713 * will be created when the program is run next. 9714 */ 9715 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath); 9716 } else { 9717 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath); 9718 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9719 } 9720 } 9721 } 9722 return PackageManager.INSTALL_SUCCEEDED; 9723 } 9724 9725 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 9726 int[] allUsers, boolean[] perUserInstalled, 9727 PackageInstalledInfo res) { 9728 String pkgName = newPackage.packageName; 9729 synchronized (mPackages) { 9730 //write settings. the installStatus will be incomplete at this stage. 9731 //note that the new package setting would have already been 9732 //added to mPackages. It hasn't been persisted yet. 9733 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 9734 mSettings.writeLPr(); 9735 } 9736 9737 if ((res.returnCode = moveDexFilesLI(newPackage)) 9738 != PackageManager.INSTALL_SUCCEEDED) { 9739 // Discontinue if moving dex files failed. 9740 return; 9741 } 9742 9743 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath); 9744 9745 synchronized (mPackages) { 9746 updatePermissionsLPw(newPackage.packageName, newPackage, 9747 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 9748 ? UPDATE_PERMISSIONS_ALL : 0)); 9749 // For system-bundled packages, we assume that installing an upgraded version 9750 // of the package implies that the user actually wants to run that new code, 9751 // so we enable the package. 9752 if (isSystemApp(newPackage)) { 9753 // NB: implicit assumption that system package upgrades apply to all users 9754 if (DEBUG_INSTALL) { 9755 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 9756 } 9757 PackageSetting ps = mSettings.mPackages.get(pkgName); 9758 if (ps != null) { 9759 if (res.origUsers != null) { 9760 for (int userHandle : res.origUsers) { 9761 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 9762 userHandle, installerPackageName); 9763 } 9764 } 9765 // Also convey the prior install/uninstall state 9766 if (allUsers != null && perUserInstalled != null) { 9767 for (int i = 0; i < allUsers.length; i++) { 9768 if (DEBUG_INSTALL) { 9769 Slog.d(TAG, " user " + allUsers[i] 9770 + " => " + perUserInstalled[i]); 9771 } 9772 ps.setInstalled(perUserInstalled[i], allUsers[i]); 9773 } 9774 // these install state changes will be persisted in the 9775 // upcoming call to mSettings.writeLPr(). 9776 } 9777 } 9778 } 9779 res.name = pkgName; 9780 res.uid = newPackage.applicationInfo.uid; 9781 res.pkg = newPackage; 9782 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 9783 mSettings.setInstallerPackageName(pkgName, installerPackageName); 9784 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 9785 //to update install status 9786 mSettings.writeLPr(); 9787 } 9788 } 9789 9790 private void installPackageLI(InstallArgs args, 9791 boolean newInstall, PackageInstalledInfo res) { 9792 int pFlags = args.flags; 9793 String installerPackageName = args.installerPackageName; 9794 File tmpPackageFile = new File(args.getCodePath()); 9795 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 9796 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 9797 boolean replace = false; 9798 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 9799 | (newInstall ? SCAN_NEW_INSTALL : 0); 9800 // Result object to be returned 9801 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 9802 9803 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 9804 // Retrieve PackageSettings and parse package 9805 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 9806 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 9807 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 9808 PackageParser pp = new PackageParser(tmpPackageFile.getPath()); 9809 pp.setSeparateProcesses(mSeparateProcesses); 9810 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile, 9811 null, mMetrics, parseFlags); 9812 if (pkg == null) { 9813 res.returnCode = pp.getParseError(); 9814 return; 9815 } 9816 String pkgName = res.name = pkg.packageName; 9817 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 9818 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 9819 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 9820 return; 9821 } 9822 } 9823 if (!pp.collectCertificates(pkg, parseFlags)) { 9824 res.returnCode = pp.getParseError(); 9825 return; 9826 } 9827 9828 /* If the installer passed in a manifest digest, compare it now. */ 9829 if (args.manifestDigest != null) { 9830 if (DEBUG_INSTALL) { 9831 final String parsedManifest = pkg.manifestDigest == null ? "null" 9832 : pkg.manifestDigest.toString(); 9833 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 9834 + parsedManifest); 9835 } 9836 9837 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 9838 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 9839 return; 9840 } 9841 } else if (DEBUG_INSTALL) { 9842 final String parsedManifest = pkg.manifestDigest == null 9843 ? "null" : pkg.manifestDigest.toString(); 9844 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 9845 } 9846 9847 // Get rid of all references to package scan path via parser. 9848 pp = null; 9849 String oldCodePath = null; 9850 boolean systemApp = false; 9851 synchronized (mPackages) { 9852 // Check whether the newly-scanned package wants to define an already-defined perm 9853 int N = pkg.permissions.size(); 9854 for (int i = 0; i < N; i++) { 9855 PackageParser.Permission perm = pkg.permissions.get(i); 9856 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 9857 if (bp != null) { 9858 // If the defining package is signed with our cert, it's okay. This 9859 // also includes the "updating the same package" case, of course. 9860 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 9861 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9862 Slog.w(TAG, "Package " + pkg.packageName 9863 + " attempting to redeclare permission " + perm.info.name 9864 + " already owned by " + bp.sourcePackage); 9865 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 9866 res.origPermission = perm.info.name; 9867 res.origPackage = bp.sourcePackage; 9868 return; 9869 } 9870 } 9871 } 9872 9873 // Check if installing already existing package 9874 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9875 String oldName = mSettings.mRenamedPackages.get(pkgName); 9876 if (pkg.mOriginalPackages != null 9877 && pkg.mOriginalPackages.contains(oldName) 9878 && mPackages.containsKey(oldName)) { 9879 // This package is derived from an original package, 9880 // and this device has been updating from that original 9881 // name. We must continue using the original name, so 9882 // rename the new package here. 9883 pkg.setPackageName(oldName); 9884 pkgName = pkg.packageName; 9885 replace = true; 9886 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 9887 + oldName + " pkgName=" + pkgName); 9888 } else if (mPackages.containsKey(pkgName)) { 9889 // This package, under its official name, already exists 9890 // on the device; we should replace it. 9891 replace = true; 9892 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 9893 } 9894 } 9895 PackageSetting ps = mSettings.mPackages.get(pkgName); 9896 if (ps != null) { 9897 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 9898 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 9899 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 9900 systemApp = (ps.pkg.applicationInfo.flags & 9901 ApplicationInfo.FLAG_SYSTEM) != 0; 9902 } 9903 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 9904 } 9905 } 9906 9907 if (systemApp && onSd) { 9908 // Disable updates to system apps on sdcard 9909 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 9910 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9911 return; 9912 } 9913 9914 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 9915 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9916 return; 9917 } 9918 // Set application objects path explicitly after the rename 9919 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath()); 9920 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 9921 if (replace) { 9922 replacePackageLI(pkg, parseFlags, scanMode, args.user, 9923 installerPackageName, res); 9924 } else { 9925 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 9926 installerPackageName, res); 9927 } 9928 synchronized (mPackages) { 9929 final PackageSetting ps = mSettings.mPackages.get(pkgName); 9930 if (ps != null) { 9931 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 9932 } 9933 } 9934 } 9935 9936 private static boolean isForwardLocked(PackageParser.Package pkg) { 9937 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 9938 } 9939 9940 9941 private boolean isForwardLocked(PackageSetting ps) { 9942 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 9943 } 9944 9945 private static boolean isExternal(PackageParser.Package pkg) { 9946 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 9947 } 9948 9949 private static boolean isExternal(PackageSetting ps) { 9950 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 9951 } 9952 9953 private static boolean isSystemApp(PackageParser.Package pkg) { 9954 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9955 } 9956 9957 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 9958 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 9959 } 9960 9961 private static boolean isSystemApp(ApplicationInfo info) { 9962 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9963 } 9964 9965 private static boolean isSystemApp(PackageSetting ps) { 9966 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 9967 } 9968 9969 private static boolean isUpdatedSystemApp(PackageSetting ps) { 9970 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 9971 } 9972 9973 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 9974 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 9975 } 9976 9977 private int packageFlagsToInstallFlags(PackageSetting ps) { 9978 int installFlags = 0; 9979 if (isExternal(ps)) { 9980 installFlags |= PackageManager.INSTALL_EXTERNAL; 9981 } 9982 if (isForwardLocked(ps)) { 9983 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 9984 } 9985 return installFlags; 9986 } 9987 9988 private void deleteTempPackageFiles() { 9989 final FilenameFilter filter = new FilenameFilter() { 9990 public boolean accept(File dir, String name) { 9991 return name.startsWith("vmdl") && name.endsWith(".tmp"); 9992 } 9993 }; 9994 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 9995 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 9996 } 9997 9998 private static final void deleteTempPackageFilesInDirectory(File directory, 9999 FilenameFilter filter) { 10000 final String[] tmpFilesList = directory.list(filter); 10001 if (tmpFilesList == null) { 10002 return; 10003 } 10004 for (int i = 0; i < tmpFilesList.length; i++) { 10005 final File tmpFile = new File(directory, tmpFilesList[i]); 10006 tmpFile.delete(); 10007 } 10008 } 10009 10010 private File createTempPackageFile(File installDir) { 10011 File tmpPackageFile; 10012 try { 10013 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 10014 } catch (IOException e) { 10015 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 10016 return null; 10017 } 10018 try { 10019 FileUtils.setPermissions( 10020 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 10021 -1, -1); 10022 if (!SELinux.restorecon(tmpPackageFile)) { 10023 return null; 10024 } 10025 } catch (IOException e) { 10026 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 10027 return null; 10028 } 10029 return tmpPackageFile; 10030 } 10031 10032 @Override 10033 public void deletePackageAsUser(final String packageName, 10034 final IPackageDeleteObserver observer, 10035 final int userId, final int flags) { 10036 mContext.enforceCallingOrSelfPermission( 10037 android.Manifest.permission.DELETE_PACKAGES, null); 10038 final int uid = Binder.getCallingUid(); 10039 if (UserHandle.getUserId(uid) != userId) { 10040 mContext.enforceCallingPermission( 10041 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10042 "deletePackage for user " + userId); 10043 } 10044 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10045 try { 10046 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10047 } catch (RemoteException re) { 10048 } 10049 return; 10050 } 10051 10052 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10053 // Queue up an async operation since the package deletion may take a little while. 10054 mHandler.post(new Runnable() { 10055 public void run() { 10056 mHandler.removeCallbacks(this); 10057 final int returnCode = deletePackageX(packageName, userId, flags); 10058 if (observer != null) { 10059 try { 10060 observer.packageDeleted(packageName, returnCode); 10061 } catch (RemoteException e) { 10062 Log.i(TAG, "Observer no longer exists."); 10063 } //end catch 10064 } //end if 10065 } //end run 10066 }); 10067 } 10068 10069 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10070 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10071 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10072 try { 10073 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10074 || dpm.isDeviceOwner(packageName))) { 10075 return true; 10076 } 10077 } catch (RemoteException e) { 10078 } 10079 return false; 10080 } 10081 10082 /** 10083 * This method is an internal method that could be get invoked either 10084 * to delete an installed package or to clean up a failed installation. 10085 * After deleting an installed package, a broadcast is sent to notify any 10086 * listeners that the package has been installed. For cleaning up a failed 10087 * installation, the broadcast is not necessary since the package's 10088 * installation wouldn't have sent the initial broadcast either 10089 * The key steps in deleting a package are 10090 * deleting the package information in internal structures like mPackages, 10091 * deleting the packages base directories through installd 10092 * updating mSettings to reflect current status 10093 * persisting settings for later use 10094 * sending a broadcast if necessary 10095 */ 10096 private int deletePackageX(String packageName, int userId, int flags) { 10097 final PackageRemovedInfo info = new PackageRemovedInfo(); 10098 final boolean res; 10099 10100 if (isPackageDeviceAdmin(packageName, userId)) { 10101 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10102 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10103 } 10104 10105 boolean removedForAllUsers = false; 10106 boolean systemUpdate = false; 10107 10108 // for the uninstall-updates case and restricted profiles, remember the per- 10109 // userhandle installed state 10110 int[] allUsers; 10111 boolean[] perUserInstalled; 10112 synchronized (mPackages) { 10113 PackageSetting ps = mSettings.mPackages.get(packageName); 10114 allUsers = sUserManager.getUserIds(); 10115 perUserInstalled = new boolean[allUsers.length]; 10116 for (int i = 0; i < allUsers.length; i++) { 10117 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10118 } 10119 } 10120 10121 synchronized (mInstallLock) { 10122 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10123 res = deletePackageLI(packageName, 10124 (flags & PackageManager.DELETE_ALL_USERS) != 0 10125 ? UserHandle.ALL : new UserHandle(userId), 10126 true, allUsers, perUserInstalled, 10127 flags | REMOVE_CHATTY, info, true); 10128 systemUpdate = info.isRemovedPackageSystemUpdate; 10129 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10130 removedForAllUsers = true; 10131 } 10132 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10133 + " removedForAllUsers=" + removedForAllUsers); 10134 } 10135 10136 if (res) { 10137 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10138 10139 // If the removed package was a system update, the old system package 10140 // was re-enabled; we need to broadcast this information 10141 if (systemUpdate) { 10142 Bundle extras = new Bundle(1); 10143 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10144 ? info.removedAppId : info.uid); 10145 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10146 10147 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10148 extras, null, null, null); 10149 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10150 extras, null, null, null); 10151 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10152 null, packageName, null, null); 10153 } 10154 } 10155 // Force a gc here. 10156 Runtime.getRuntime().gc(); 10157 // Delete the resources here after sending the broadcast to let 10158 // other processes clean up before deleting resources. 10159 if (info.args != null) { 10160 synchronized (mInstallLock) { 10161 info.args.doPostDeleteLI(true); 10162 } 10163 } 10164 10165 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10166 } 10167 10168 static class PackageRemovedInfo { 10169 String removedPackage; 10170 int uid = -1; 10171 int removedAppId = -1; 10172 int[] removedUsers = null; 10173 boolean isRemovedPackageSystemUpdate = false; 10174 // Clean up resources deleted packages. 10175 InstallArgs args = null; 10176 10177 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10178 Bundle extras = new Bundle(1); 10179 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10180 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10181 if (replacing) { 10182 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10183 } 10184 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10185 if (removedPackage != null) { 10186 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10187 extras, null, null, removedUsers); 10188 if (fullRemove && !replacing) { 10189 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10190 extras, null, null, removedUsers); 10191 } 10192 } 10193 if (removedAppId >= 0) { 10194 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10195 removedUsers); 10196 } 10197 } 10198 } 10199 10200 /* 10201 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10202 * flag is not set, the data directory is removed as well. 10203 * make sure this flag is set for partially installed apps. If not its meaningless to 10204 * delete a partially installed application. 10205 */ 10206 private void removePackageDataLI(PackageSetting ps, 10207 int[] allUserHandles, boolean[] perUserInstalled, 10208 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10209 String packageName = ps.name; 10210 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10211 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10212 // Retrieve object to delete permissions for shared user later on 10213 final PackageSetting deletedPs; 10214 // reader 10215 synchronized (mPackages) { 10216 deletedPs = mSettings.mPackages.get(packageName); 10217 if (outInfo != null) { 10218 outInfo.removedPackage = packageName; 10219 outInfo.removedUsers = deletedPs != null 10220 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10221 : null; 10222 } 10223 } 10224 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10225 removeDataDirsLI(packageName); 10226 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10227 } 10228 // writer 10229 synchronized (mPackages) { 10230 if (deletedPs != null) { 10231 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10232 if (outInfo != null) { 10233 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10234 } 10235 if (deletedPs != null) { 10236 updatePermissionsLPw(deletedPs.name, null, 0); 10237 if (deletedPs.sharedUser != null) { 10238 // remove permissions associated with package 10239 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10240 } 10241 } 10242 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10243 } 10244 // make sure to preserve per-user disabled state if this removal was just 10245 // a downgrade of a system app to the factory package 10246 if (allUserHandles != null && perUserInstalled != null) { 10247 if (DEBUG_REMOVE) { 10248 Slog.d(TAG, "Propagating install state across downgrade"); 10249 } 10250 for (int i = 0; i < allUserHandles.length; i++) { 10251 if (DEBUG_REMOVE) { 10252 Slog.d(TAG, " user " + allUserHandles[i] 10253 + " => " + perUserInstalled[i]); 10254 } 10255 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10256 } 10257 } 10258 } 10259 // can downgrade to reader 10260 if (writeSettings) { 10261 // Save settings now 10262 mSettings.writeLPr(); 10263 } 10264 } 10265 if (outInfo != null) { 10266 // A user ID was deleted here. Go through all users and remove it 10267 // from KeyStore. 10268 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10269 } 10270 } 10271 10272 static boolean locationIsPrivileged(File path) { 10273 try { 10274 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10275 .getCanonicalPath(); 10276 return path.getCanonicalPath().startsWith(privilegedAppDir); 10277 } catch (IOException e) { 10278 Slog.e(TAG, "Unable to access code path " + path); 10279 } 10280 return false; 10281 } 10282 10283 /* 10284 * Tries to delete system package. 10285 */ 10286 private boolean deleteSystemPackageLI(PackageSetting newPs, 10287 int[] allUserHandles, boolean[] perUserInstalled, 10288 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10289 final boolean applyUserRestrictions 10290 = (allUserHandles != null) && (perUserInstalled != null); 10291 PackageSetting disabledPs = null; 10292 // Confirm if the system package has been updated 10293 // An updated system app can be deleted. This will also have to restore 10294 // the system pkg from system partition 10295 // reader 10296 synchronized (mPackages) { 10297 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10298 } 10299 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10300 + " disabledPs=" + disabledPs); 10301 if (disabledPs == null) { 10302 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10303 return false; 10304 } else if (DEBUG_REMOVE) { 10305 Slog.d(TAG, "Deleting system pkg from data partition"); 10306 } 10307 if (DEBUG_REMOVE) { 10308 if (applyUserRestrictions) { 10309 Slog.d(TAG, "Remembering install states:"); 10310 for (int i = 0; i < allUserHandles.length; i++) { 10311 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10312 } 10313 } 10314 } 10315 // Delete the updated package 10316 outInfo.isRemovedPackageSystemUpdate = true; 10317 if (disabledPs.versionCode < newPs.versionCode) { 10318 // Delete data for downgrades 10319 flags &= ~PackageManager.DELETE_KEEP_DATA; 10320 } else { 10321 // Preserve data by setting flag 10322 flags |= PackageManager.DELETE_KEEP_DATA; 10323 } 10324 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10325 allUserHandles, perUserInstalled, outInfo, writeSettings); 10326 if (!ret) { 10327 return false; 10328 } 10329 // writer 10330 synchronized (mPackages) { 10331 // Reinstate the old system package 10332 mSettings.enableSystemPackageLPw(newPs.name); 10333 // Remove any native libraries from the upgraded package. 10334 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 10335 } 10336 // Install the system package 10337 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10338 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10339 if (locationIsPrivileged(disabledPs.codePath)) { 10340 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10341 } 10342 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10343 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null); 10344 10345 if (newPkg == null) { 10346 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10347 + " with error:" + mLastScanError); 10348 return false; 10349 } 10350 // writer 10351 synchronized (mPackages) { 10352 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10353 setInternalAppNativeLibraryPath(newPkg, ps); 10354 updatePermissionsLPw(newPkg.packageName, newPkg, 10355 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10356 if (applyUserRestrictions) { 10357 if (DEBUG_REMOVE) { 10358 Slog.d(TAG, "Propagating install state across reinstall"); 10359 } 10360 for (int i = 0; i < allUserHandles.length; i++) { 10361 if (DEBUG_REMOVE) { 10362 Slog.d(TAG, " user " + allUserHandles[i] 10363 + " => " + perUserInstalled[i]); 10364 } 10365 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10366 } 10367 // Regardless of writeSettings we need to ensure that this restriction 10368 // state propagation is persisted 10369 mSettings.writeAllUsersPackageRestrictionsLPr(); 10370 } 10371 // can downgrade to reader here 10372 if (writeSettings) { 10373 mSettings.writeLPr(); 10374 } 10375 } 10376 return true; 10377 } 10378 10379 private boolean deleteInstalledPackageLI(PackageSetting ps, 10380 boolean deleteCodeAndResources, int flags, 10381 int[] allUserHandles, boolean[] perUserInstalled, 10382 PackageRemovedInfo outInfo, boolean writeSettings) { 10383 if (outInfo != null) { 10384 outInfo.uid = ps.appId; 10385 } 10386 10387 // Delete package data from internal structures and also remove data if flag is set 10388 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10389 10390 // Delete application code and resources 10391 if (deleteCodeAndResources && (outInfo != null)) { 10392 outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString, 10393 ps.resourcePathString, ps.nativeLibraryPathString, 10394 getAppInstructionSetFromSettings(ps)); 10395 } 10396 return true; 10397 } 10398 10399 /* 10400 * This method handles package deletion in general 10401 */ 10402 private boolean deletePackageLI(String packageName, UserHandle user, 10403 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10404 int flags, PackageRemovedInfo outInfo, 10405 boolean writeSettings) { 10406 if (packageName == null) { 10407 Slog.w(TAG, "Attempt to delete null packageName."); 10408 return false; 10409 } 10410 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10411 PackageSetting ps; 10412 boolean dataOnly = false; 10413 int removeUser = -1; 10414 int appId = -1; 10415 synchronized (mPackages) { 10416 ps = mSettings.mPackages.get(packageName); 10417 if (ps == null) { 10418 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10419 return false; 10420 } 10421 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10422 && user.getIdentifier() != UserHandle.USER_ALL) { 10423 // The caller is asking that the package only be deleted for a single 10424 // user. To do this, we just mark its uninstalled state and delete 10425 // its data. If this is a system app, we only allow this to happen if 10426 // they have set the special DELETE_SYSTEM_APP which requests different 10427 // semantics than normal for uninstalling system apps. 10428 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10429 ps.setUserState(user.getIdentifier(), 10430 COMPONENT_ENABLED_STATE_DEFAULT, 10431 false, //installed 10432 true, //stopped 10433 true, //notLaunched 10434 false, //blocked 10435 null, null, null); 10436 if (!isSystemApp(ps)) { 10437 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10438 // Other user still have this package installed, so all 10439 // we need to do is clear this user's data and save that 10440 // it is uninstalled. 10441 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10442 removeUser = user.getIdentifier(); 10443 appId = ps.appId; 10444 mSettings.writePackageRestrictionsLPr(removeUser); 10445 } else { 10446 // We need to set it back to 'installed' so the uninstall 10447 // broadcasts will be sent correctly. 10448 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10449 ps.setInstalled(true, user.getIdentifier()); 10450 } 10451 } else { 10452 // This is a system app, so we assume that the 10453 // other users still have this package installed, so all 10454 // we need to do is clear this user's data and save that 10455 // it is uninstalled. 10456 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10457 removeUser = user.getIdentifier(); 10458 appId = ps.appId; 10459 mSettings.writePackageRestrictionsLPr(removeUser); 10460 } 10461 } 10462 } 10463 10464 if (removeUser >= 0) { 10465 // From above, we determined that we are deleting this only 10466 // for a single user. Continue the work here. 10467 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10468 if (outInfo != null) { 10469 outInfo.removedPackage = packageName; 10470 outInfo.removedAppId = appId; 10471 outInfo.removedUsers = new int[] {removeUser}; 10472 } 10473 mInstaller.clearUserData(packageName, removeUser); 10474 removeKeystoreDataIfNeeded(removeUser, appId); 10475 schedulePackageCleaning(packageName, removeUser, false); 10476 return true; 10477 } 10478 10479 if (dataOnly) { 10480 // Delete application data first 10481 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10482 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10483 return true; 10484 } 10485 10486 boolean ret = false; 10487 mSettings.mKeySetManager.removeAppKeySetData(packageName); 10488 if (isSystemApp(ps)) { 10489 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10490 // When an updated system application is deleted we delete the existing resources as well and 10491 // fall back to existing code in system partition 10492 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10493 flags, outInfo, writeSettings); 10494 } else { 10495 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10496 // Kill application pre-emptively especially for apps on sd. 10497 killApplication(packageName, ps.appId, "uninstall pkg"); 10498 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10499 allUserHandles, perUserInstalled, 10500 outInfo, writeSettings); 10501 } 10502 10503 return ret; 10504 } 10505 10506 private final class ClearStorageConnection implements ServiceConnection { 10507 IMediaContainerService mContainerService; 10508 10509 @Override 10510 public void onServiceConnected(ComponentName name, IBinder service) { 10511 synchronized (this) { 10512 mContainerService = IMediaContainerService.Stub.asInterface(service); 10513 notifyAll(); 10514 } 10515 } 10516 10517 @Override 10518 public void onServiceDisconnected(ComponentName name) { 10519 } 10520 } 10521 10522 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10523 final boolean mounted; 10524 if (Environment.isExternalStorageEmulated()) { 10525 mounted = true; 10526 } else { 10527 final String status = Environment.getExternalStorageState(); 10528 10529 mounted = status.equals(Environment.MEDIA_MOUNTED) 10530 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10531 } 10532 10533 if (!mounted) { 10534 return; 10535 } 10536 10537 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10538 int[] users; 10539 if (userId == UserHandle.USER_ALL) { 10540 users = sUserManager.getUserIds(); 10541 } else { 10542 users = new int[] { userId }; 10543 } 10544 final ClearStorageConnection conn = new ClearStorageConnection(); 10545 if (mContext.bindServiceAsUser( 10546 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10547 try { 10548 for (int curUser : users) { 10549 long timeout = SystemClock.uptimeMillis() + 5000; 10550 synchronized (conn) { 10551 long now = SystemClock.uptimeMillis(); 10552 while (conn.mContainerService == null && now < timeout) { 10553 try { 10554 conn.wait(timeout - now); 10555 } catch (InterruptedException e) { 10556 } 10557 } 10558 } 10559 if (conn.mContainerService == null) { 10560 return; 10561 } 10562 10563 final UserEnvironment userEnv = new UserEnvironment(curUser); 10564 clearDirectory(conn.mContainerService, 10565 userEnv.buildExternalStorageAppCacheDirs(packageName)); 10566 if (allData) { 10567 clearDirectory(conn.mContainerService, 10568 userEnv.buildExternalStorageAppDataDirs(packageName)); 10569 clearDirectory(conn.mContainerService, 10570 userEnv.buildExternalStorageAppMediaDirs(packageName)); 10571 } 10572 } 10573 } finally { 10574 mContext.unbindService(conn); 10575 } 10576 } 10577 } 10578 10579 @Override 10580 public void clearApplicationUserData(final String packageName, 10581 final IPackageDataObserver observer, final int userId) { 10582 mContext.enforceCallingOrSelfPermission( 10583 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 10584 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 10585 // Queue up an async operation since the package deletion may take a little while. 10586 mHandler.post(new Runnable() { 10587 public void run() { 10588 mHandler.removeCallbacks(this); 10589 final boolean succeeded; 10590 synchronized (mInstallLock) { 10591 succeeded = clearApplicationUserDataLI(packageName, userId); 10592 } 10593 clearExternalStorageDataSync(packageName, userId, true); 10594 if (succeeded) { 10595 // invoke DeviceStorageMonitor's update method to clear any notifications 10596 DeviceStorageMonitorInternal 10597 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 10598 if (dsm != null) { 10599 dsm.checkMemory(); 10600 } 10601 } 10602 if(observer != null) { 10603 try { 10604 observer.onRemoveCompleted(packageName, succeeded); 10605 } catch (RemoteException e) { 10606 Log.i(TAG, "Observer no longer exists."); 10607 } 10608 } //end if observer 10609 } //end run 10610 }); 10611 } 10612 10613 private boolean clearApplicationUserDataLI(String packageName, int userId) { 10614 if (packageName == null) { 10615 Slog.w(TAG, "Attempt to delete null packageName."); 10616 return false; 10617 } 10618 PackageParser.Package p; 10619 boolean dataOnly = false; 10620 final int appId; 10621 synchronized (mPackages) { 10622 p = mPackages.get(packageName); 10623 if (p == null) { 10624 dataOnly = true; 10625 PackageSetting ps = mSettings.mPackages.get(packageName); 10626 if ((ps == null) || (ps.pkg == null)) { 10627 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10628 return false; 10629 } 10630 p = ps.pkg; 10631 } 10632 if (!dataOnly) { 10633 // need to check this only for fully installed applications 10634 if (p == null) { 10635 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10636 return false; 10637 } 10638 final ApplicationInfo applicationInfo = p.applicationInfo; 10639 if (applicationInfo == null) { 10640 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10641 return false; 10642 } 10643 } 10644 if (p != null && p.applicationInfo != null) { 10645 appId = p.applicationInfo.uid; 10646 } else { 10647 appId = -1; 10648 } 10649 } 10650 int retCode = mInstaller.clearUserData(packageName, userId); 10651 if (retCode < 0) { 10652 Slog.w(TAG, "Couldn't remove cache files for package: " 10653 + packageName); 10654 return false; 10655 } 10656 removeKeystoreDataIfNeeded(userId, appId); 10657 return true; 10658 } 10659 10660 /** 10661 * Remove entries from the keystore daemon. Will only remove it if the 10662 * {@code appId} is valid. 10663 */ 10664 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 10665 if (appId < 0) { 10666 return; 10667 } 10668 10669 final KeyStore keyStore = KeyStore.getInstance(); 10670 if (keyStore != null) { 10671 if (userId == UserHandle.USER_ALL) { 10672 for (final int individual : sUserManager.getUserIds()) { 10673 keyStore.clearUid(UserHandle.getUid(individual, appId)); 10674 } 10675 } else { 10676 keyStore.clearUid(UserHandle.getUid(userId, appId)); 10677 } 10678 } else { 10679 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 10680 } 10681 } 10682 10683 public void deleteApplicationCacheFiles(final String packageName, 10684 final IPackageDataObserver observer) { 10685 mContext.enforceCallingOrSelfPermission( 10686 android.Manifest.permission.DELETE_CACHE_FILES, null); 10687 // Queue up an async operation since the package deletion may take a little while. 10688 final int userId = UserHandle.getCallingUserId(); 10689 mHandler.post(new Runnable() { 10690 public void run() { 10691 mHandler.removeCallbacks(this); 10692 final boolean succeded; 10693 synchronized (mInstallLock) { 10694 succeded = deleteApplicationCacheFilesLI(packageName, userId); 10695 } 10696 clearExternalStorageDataSync(packageName, userId, false); 10697 if(observer != null) { 10698 try { 10699 observer.onRemoveCompleted(packageName, succeded); 10700 } catch (RemoteException e) { 10701 Log.i(TAG, "Observer no longer exists."); 10702 } 10703 } //end if observer 10704 } //end run 10705 }); 10706 } 10707 10708 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 10709 if (packageName == null) { 10710 Slog.w(TAG, "Attempt to delete null packageName."); 10711 return false; 10712 } 10713 PackageParser.Package p; 10714 synchronized (mPackages) { 10715 p = mPackages.get(packageName); 10716 } 10717 if (p == null) { 10718 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 10719 return false; 10720 } 10721 final ApplicationInfo applicationInfo = p.applicationInfo; 10722 if (applicationInfo == null) { 10723 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10724 return false; 10725 } 10726 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 10727 if (retCode < 0) { 10728 Slog.w(TAG, "Couldn't remove cache files for package: " 10729 + packageName + " u" + userId); 10730 return false; 10731 } 10732 return true; 10733 } 10734 10735 public void getPackageSizeInfo(final String packageName, int userHandle, 10736 final IPackageStatsObserver observer) { 10737 mContext.enforceCallingOrSelfPermission( 10738 android.Manifest.permission.GET_PACKAGE_SIZE, null); 10739 if (packageName == null) { 10740 throw new IllegalArgumentException("Attempt to get size of null packageName"); 10741 } 10742 10743 PackageStats stats = new PackageStats(packageName, userHandle); 10744 10745 /* 10746 * Queue up an async operation since the package measurement may take a 10747 * little while. 10748 */ 10749 Message msg = mHandler.obtainMessage(INIT_COPY); 10750 msg.obj = new MeasureParams(stats, observer); 10751 mHandler.sendMessage(msg); 10752 } 10753 10754 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 10755 PackageStats pStats) { 10756 if (packageName == null) { 10757 Slog.w(TAG, "Attempt to get size of null packageName."); 10758 return false; 10759 } 10760 PackageParser.Package p; 10761 boolean dataOnly = false; 10762 String libDirPath = null; 10763 String asecPath = null; 10764 PackageSetting ps = null; 10765 synchronized (mPackages) { 10766 p = mPackages.get(packageName); 10767 ps = mSettings.mPackages.get(packageName); 10768 if(p == null) { 10769 dataOnly = true; 10770 if((ps == null) || (ps.pkg == null)) { 10771 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 10772 return false; 10773 } 10774 p = ps.pkg; 10775 } 10776 if (ps != null) { 10777 libDirPath = ps.nativeLibraryPathString; 10778 } 10779 if (p != null && (isExternal(p) || isForwardLocked(p))) { 10780 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 10781 if (secureContainerId != null) { 10782 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 10783 } 10784 } 10785 } 10786 String publicSrcDir = null; 10787 if(!dataOnly) { 10788 final ApplicationInfo applicationInfo = p.applicationInfo; 10789 if (applicationInfo == null) { 10790 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10791 return false; 10792 } 10793 if (isForwardLocked(p)) { 10794 publicSrcDir = applicationInfo.publicSourceDir; 10795 } 10796 } 10797 int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath, 10798 publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps), 10799 pStats); 10800 if (res < 0) { 10801 return false; 10802 } 10803 10804 // Fix-up for forward-locked applications in ASEC containers. 10805 if (!isExternal(p)) { 10806 pStats.codeSize += pStats.externalCodeSize; 10807 pStats.externalCodeSize = 0L; 10808 } 10809 10810 return true; 10811 } 10812 10813 10814 public void addPackageToPreferred(String packageName) { 10815 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 10816 } 10817 10818 public void removePackageFromPreferred(String packageName) { 10819 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 10820 } 10821 10822 public List<PackageInfo> getPreferredPackages(int flags) { 10823 return new ArrayList<PackageInfo>(); 10824 } 10825 10826 private int getUidTargetSdkVersionLockedLPr(int uid) { 10827 Object obj = mSettings.getUserIdLPr(uid); 10828 if (obj instanceof SharedUserSetting) { 10829 final SharedUserSetting sus = (SharedUserSetting) obj; 10830 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 10831 final Iterator<PackageSetting> it = sus.packages.iterator(); 10832 while (it.hasNext()) { 10833 final PackageSetting ps = it.next(); 10834 if (ps.pkg != null) { 10835 int v = ps.pkg.applicationInfo.targetSdkVersion; 10836 if (v < vers) vers = v; 10837 } 10838 } 10839 return vers; 10840 } else if (obj instanceof PackageSetting) { 10841 final PackageSetting ps = (PackageSetting) obj; 10842 if (ps.pkg != null) { 10843 return ps.pkg.applicationInfo.targetSdkVersion; 10844 } 10845 } 10846 return Build.VERSION_CODES.CUR_DEVELOPMENT; 10847 } 10848 10849 public void addPreferredActivity(IntentFilter filter, int match, 10850 ComponentName[] set, ComponentName activity, int userId) { 10851 addPreferredActivityInternal(filter, match, set, activity, true, userId); 10852 } 10853 10854 private void addPreferredActivityInternal(IntentFilter filter, int match, 10855 ComponentName[] set, ComponentName activity, boolean always, int userId) { 10856 // writer 10857 int callingUid = Binder.getCallingUid(); 10858 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 10859 if (filter.countActions() == 0) { 10860 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 10861 return; 10862 } 10863 synchronized (mPackages) { 10864 if (mContext.checkCallingOrSelfPermission( 10865 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10866 != PackageManager.PERMISSION_GRANTED) { 10867 if (getUidTargetSdkVersionLockedLPr(callingUid) 10868 < Build.VERSION_CODES.FROYO) { 10869 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 10870 + callingUid); 10871 return; 10872 } 10873 mContext.enforceCallingOrSelfPermission( 10874 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10875 } 10876 10877 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 10878 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10879 mSettings.editPreferredActivitiesLPw(userId).addFilter( 10880 new PreferredActivity(filter, match, set, activity, always)); 10881 mSettings.writePackageRestrictionsLPr(userId); 10882 } 10883 } 10884 10885 public void replacePreferredActivity(IntentFilter filter, int match, 10886 ComponentName[] set, ComponentName activity) { 10887 if (filter.countActions() != 1) { 10888 throw new IllegalArgumentException( 10889 "replacePreferredActivity expects filter to have only 1 action."); 10890 } 10891 if (filter.countDataAuthorities() != 0 10892 || filter.countDataPaths() != 0 10893 || filter.countDataSchemes() > 1 10894 || filter.countDataTypes() != 0) { 10895 throw new IllegalArgumentException( 10896 "replacePreferredActivity expects filter to have no data authorities, " + 10897 "paths, or types; and at most one scheme."); 10898 } 10899 synchronized (mPackages) { 10900 if (mContext.checkCallingOrSelfPermission( 10901 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10902 != PackageManager.PERMISSION_GRANTED) { 10903 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 10904 < Build.VERSION_CODES.FROYO) { 10905 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 10906 + Binder.getCallingUid()); 10907 return; 10908 } 10909 mContext.enforceCallingOrSelfPermission( 10910 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10911 } 10912 10913 final int callingUserId = UserHandle.getCallingUserId(); 10914 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 10915 if (pir != null) { 10916 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 10917 if (filter.countDataSchemes() == 1) { 10918 Uri.Builder builder = new Uri.Builder(); 10919 builder.scheme(filter.getDataScheme(0)); 10920 intent.setData(builder.build()); 10921 } 10922 List<PreferredActivity> matches = pir.queryIntent( 10923 intent, null, true, callingUserId); 10924 if (DEBUG_PREFERRED) { 10925 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 10926 } 10927 for (int i = 0; i < matches.size(); i++) { 10928 PreferredActivity pa = matches.get(i); 10929 if (DEBUG_PREFERRED) { 10930 Slog.i(TAG, "Removing preferred activity " 10931 + pa.mPref.mComponent + ":"); 10932 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10933 } 10934 pir.removeFilter(pa); 10935 } 10936 } 10937 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 10938 } 10939 } 10940 10941 public void clearPackagePreferredActivities(String packageName) { 10942 final int uid = Binder.getCallingUid(); 10943 // writer 10944 synchronized (mPackages) { 10945 PackageParser.Package pkg = mPackages.get(packageName); 10946 if (pkg == null || pkg.applicationInfo.uid != uid) { 10947 if (mContext.checkCallingOrSelfPermission( 10948 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10949 != PackageManager.PERMISSION_GRANTED) { 10950 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 10951 < Build.VERSION_CODES.FROYO) { 10952 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 10953 + Binder.getCallingUid()); 10954 return; 10955 } 10956 mContext.enforceCallingOrSelfPermission( 10957 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10958 } 10959 } 10960 10961 int user = UserHandle.getCallingUserId(); 10962 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 10963 mSettings.writePackageRestrictionsLPr(user); 10964 scheduleWriteSettingsLocked(); 10965 } 10966 } 10967 } 10968 10969 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 10970 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 10971 ArrayList<PreferredActivity> removed = null; 10972 boolean changed = false; 10973 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 10974 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 10975 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 10976 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 10977 continue; 10978 } 10979 Iterator<PreferredActivity> it = pir.filterIterator(); 10980 while (it.hasNext()) { 10981 PreferredActivity pa = it.next(); 10982 // Mark entry for removal only if it matches the package name 10983 // and the entry is of type "always". 10984 if (packageName == null || 10985 (pa.mPref.mComponent.getPackageName().equals(packageName) 10986 && pa.mPref.mAlways)) { 10987 if (removed == null) { 10988 removed = new ArrayList<PreferredActivity>(); 10989 } 10990 removed.add(pa); 10991 } 10992 } 10993 if (removed != null) { 10994 for (int j=0; j<removed.size(); j++) { 10995 PreferredActivity pa = removed.get(j); 10996 pir.removeFilter(pa); 10997 } 10998 changed = true; 10999 } 11000 } 11001 return changed; 11002 } 11003 11004 public void resetPreferredActivities(int userId) { 11005 mContext.enforceCallingOrSelfPermission( 11006 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11007 // writer 11008 synchronized (mPackages) { 11009 int user = UserHandle.getCallingUserId(); 11010 clearPackagePreferredActivitiesLPw(null, user); 11011 mSettings.readDefaultPreferredAppsLPw(this, user); 11012 mSettings.writePackageRestrictionsLPr(user); 11013 scheduleWriteSettingsLocked(); 11014 } 11015 } 11016 11017 public int getPreferredActivities(List<IntentFilter> outFilters, 11018 List<ComponentName> outActivities, String packageName) { 11019 11020 int num = 0; 11021 final int userId = UserHandle.getCallingUserId(); 11022 // reader 11023 synchronized (mPackages) { 11024 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11025 if (pir != null) { 11026 final Iterator<PreferredActivity> it = pir.filterIterator(); 11027 while (it.hasNext()) { 11028 final PreferredActivity pa = it.next(); 11029 if (packageName == null 11030 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11031 && pa.mPref.mAlways)) { 11032 if (outFilters != null) { 11033 outFilters.add(new IntentFilter(pa)); 11034 } 11035 if (outActivities != null) { 11036 outActivities.add(pa.mPref.mComponent); 11037 } 11038 } 11039 } 11040 } 11041 } 11042 11043 return num; 11044 } 11045 11046 @Override 11047 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11048 int userId) { 11049 int callingUid = Binder.getCallingUid(); 11050 if (callingUid != Process.SYSTEM_UID) { 11051 throw new SecurityException( 11052 "addPersistentPreferredActivity can only be run by the system"); 11053 } 11054 if (filter.countActions() == 0) { 11055 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11056 return; 11057 } 11058 synchronized (mPackages) { 11059 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11060 " :"); 11061 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11062 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11063 new PersistentPreferredActivity(filter, activity)); 11064 mSettings.writePackageRestrictionsLPr(userId); 11065 } 11066 } 11067 11068 @Override 11069 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11070 int callingUid = Binder.getCallingUid(); 11071 if (callingUid != Process.SYSTEM_UID) { 11072 throw new SecurityException( 11073 "clearPackagePersistentPreferredActivities can only be run by the system"); 11074 } 11075 ArrayList<PersistentPreferredActivity> removed = null; 11076 boolean changed = false; 11077 synchronized (mPackages) { 11078 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11079 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11080 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11081 .valueAt(i); 11082 if (userId != thisUserId) { 11083 continue; 11084 } 11085 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11086 while (it.hasNext()) { 11087 PersistentPreferredActivity ppa = it.next(); 11088 // Mark entry for removal only if it matches the package name. 11089 if (ppa.mComponent.getPackageName().equals(packageName)) { 11090 if (removed == null) { 11091 removed = new ArrayList<PersistentPreferredActivity>(); 11092 } 11093 removed.add(ppa); 11094 } 11095 } 11096 if (removed != null) { 11097 for (int j=0; j<removed.size(); j++) { 11098 PersistentPreferredActivity ppa = removed.get(j); 11099 ppir.removeFilter(ppa); 11100 } 11101 changed = true; 11102 } 11103 } 11104 11105 if (changed) { 11106 mSettings.writePackageRestrictionsLPr(userId); 11107 } 11108 } 11109 } 11110 11111 @Override 11112 public void addForwardingIntentFilter(IntentFilter filter, boolean removable, int userIdOrig, 11113 int userIdDest) { 11114 mContext.enforceCallingOrSelfPermission( 11115 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11116 if (filter.countActions() == 0) { 11117 Slog.w(TAG, "Cannot set a forwarding intent filter with no filter actions"); 11118 return; 11119 } 11120 synchronized (mPackages) { 11121 mSettings.editForwardingIntentResolverLPw(userIdOrig).addFilter( 11122 new ForwardingIntentFilter(filter, removable, userIdDest)); 11123 mSettings.writePackageRestrictionsLPr(userIdOrig); 11124 } 11125 } 11126 11127 @Override 11128 public void clearForwardingIntentFilters(int userIdOrig) { 11129 mContext.enforceCallingOrSelfPermission( 11130 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11131 synchronized (mPackages) { 11132 ForwardingIntentResolver fir = mSettings.editForwardingIntentResolverLPw(userIdOrig); 11133 HashSet<ForwardingIntentFilter> set = 11134 new HashSet<ForwardingIntentFilter>(fir.filterSet()); 11135 for (ForwardingIntentFilter fif : set) { 11136 if (fif.isRemovable()) fir.removeFilter(fif); 11137 } 11138 mSettings.writePackageRestrictionsLPr(userIdOrig); 11139 } 11140 } 11141 11142 @Override 11143 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11144 Intent intent = new Intent(Intent.ACTION_MAIN); 11145 intent.addCategory(Intent.CATEGORY_HOME); 11146 11147 final int callingUserId = UserHandle.getCallingUserId(); 11148 List<ResolveInfo> list = queryIntentActivities(intent, null, 11149 PackageManager.GET_META_DATA, callingUserId); 11150 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11151 true, false, false, callingUserId); 11152 11153 allHomeCandidates.clear(); 11154 if (list != null) { 11155 for (ResolveInfo ri : list) { 11156 allHomeCandidates.add(ri); 11157 } 11158 } 11159 return (preferred == null || preferred.activityInfo == null) 11160 ? null 11161 : new ComponentName(preferred.activityInfo.packageName, 11162 preferred.activityInfo.name); 11163 } 11164 11165 @Override 11166 public void setApplicationEnabledSetting(String appPackageName, 11167 int newState, int flags, int userId, String callingPackage) { 11168 if (!sUserManager.exists(userId)) return; 11169 if (callingPackage == null) { 11170 callingPackage = Integer.toString(Binder.getCallingUid()); 11171 } 11172 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11173 } 11174 11175 @Override 11176 public void setComponentEnabledSetting(ComponentName componentName, 11177 int newState, int flags, int userId) { 11178 if (!sUserManager.exists(userId)) return; 11179 setEnabledSetting(componentName.getPackageName(), 11180 componentName.getClassName(), newState, flags, userId, null); 11181 } 11182 11183 private void setEnabledSetting(final String packageName, String className, int newState, 11184 final int flags, int userId, String callingPackage) { 11185 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11186 || newState == COMPONENT_ENABLED_STATE_ENABLED 11187 || newState == COMPONENT_ENABLED_STATE_DISABLED 11188 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11189 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11190 throw new IllegalArgumentException("Invalid new component state: " 11191 + newState); 11192 } 11193 PackageSetting pkgSetting; 11194 final int uid = Binder.getCallingUid(); 11195 final int permission = mContext.checkCallingOrSelfPermission( 11196 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11197 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11198 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11199 boolean sendNow = false; 11200 boolean isApp = (className == null); 11201 String componentName = isApp ? packageName : className; 11202 int packageUid = -1; 11203 ArrayList<String> components; 11204 11205 // writer 11206 synchronized (mPackages) { 11207 pkgSetting = mSettings.mPackages.get(packageName); 11208 if (pkgSetting == null) { 11209 if (className == null) { 11210 throw new IllegalArgumentException( 11211 "Unknown package: " + packageName); 11212 } 11213 throw new IllegalArgumentException( 11214 "Unknown component: " + packageName 11215 + "/" + className); 11216 } 11217 // Allow root and verify that userId is not being specified by a different user 11218 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11219 throw new SecurityException( 11220 "Permission Denial: attempt to change component state from pid=" 11221 + Binder.getCallingPid() 11222 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11223 } 11224 if (className == null) { 11225 // We're dealing with an application/package level state change 11226 if (pkgSetting.getEnabled(userId) == newState) { 11227 // Nothing to do 11228 return; 11229 } 11230 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11231 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11232 // Don't care about who enables an app. 11233 callingPackage = null; 11234 } 11235 pkgSetting.setEnabled(newState, userId, callingPackage); 11236 // pkgSetting.pkg.mSetEnabled = newState; 11237 } else { 11238 // We're dealing with a component level state change 11239 // First, verify that this is a valid class name. 11240 PackageParser.Package pkg = pkgSetting.pkg; 11241 if (pkg == null || !pkg.hasComponentClassName(className)) { 11242 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11243 throw new IllegalArgumentException("Component class " + className 11244 + " does not exist in " + packageName); 11245 } else { 11246 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11247 + className + " does not exist in " + packageName); 11248 } 11249 } 11250 switch (newState) { 11251 case COMPONENT_ENABLED_STATE_ENABLED: 11252 if (!pkgSetting.enableComponentLPw(className, userId)) { 11253 return; 11254 } 11255 break; 11256 case COMPONENT_ENABLED_STATE_DISABLED: 11257 if (!pkgSetting.disableComponentLPw(className, userId)) { 11258 return; 11259 } 11260 break; 11261 case COMPONENT_ENABLED_STATE_DEFAULT: 11262 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11263 return; 11264 } 11265 break; 11266 default: 11267 Slog.e(TAG, "Invalid new component state: " + newState); 11268 return; 11269 } 11270 } 11271 mSettings.writePackageRestrictionsLPr(userId); 11272 components = mPendingBroadcasts.get(userId, packageName); 11273 final boolean newPackage = components == null; 11274 if (newPackage) { 11275 components = new ArrayList<String>(); 11276 } 11277 if (!components.contains(componentName)) { 11278 components.add(componentName); 11279 } 11280 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11281 sendNow = true; 11282 // Purge entry from pending broadcast list if another one exists already 11283 // since we are sending one right away. 11284 mPendingBroadcasts.remove(userId, packageName); 11285 } else { 11286 if (newPackage) { 11287 mPendingBroadcasts.put(userId, packageName, components); 11288 } 11289 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11290 // Schedule a message 11291 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11292 } 11293 } 11294 } 11295 11296 long callingId = Binder.clearCallingIdentity(); 11297 try { 11298 if (sendNow) { 11299 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11300 sendPackageChangedBroadcast(packageName, 11301 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11302 } 11303 } finally { 11304 Binder.restoreCallingIdentity(callingId); 11305 } 11306 } 11307 11308 private void sendPackageChangedBroadcast(String packageName, 11309 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11310 if (DEBUG_INSTALL) 11311 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11312 + componentNames); 11313 Bundle extras = new Bundle(4); 11314 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11315 String nameList[] = new String[componentNames.size()]; 11316 componentNames.toArray(nameList); 11317 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11318 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11319 extras.putInt(Intent.EXTRA_UID, packageUid); 11320 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11321 new int[] {UserHandle.getUserId(packageUid)}); 11322 } 11323 11324 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11325 if (!sUserManager.exists(userId)) return; 11326 final int uid = Binder.getCallingUid(); 11327 final int permission = mContext.checkCallingOrSelfPermission( 11328 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11329 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11330 enforceCrossUserPermission(uid, userId, true, "stop package"); 11331 // writer 11332 synchronized (mPackages) { 11333 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11334 uid, userId)) { 11335 scheduleWritePackageRestrictionsLocked(userId); 11336 } 11337 } 11338 } 11339 11340 public String getInstallerPackageName(String packageName) { 11341 // reader 11342 synchronized (mPackages) { 11343 return mSettings.getInstallerPackageNameLPr(packageName); 11344 } 11345 } 11346 11347 @Override 11348 public int getApplicationEnabledSetting(String packageName, int userId) { 11349 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11350 int uid = Binder.getCallingUid(); 11351 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11352 // reader 11353 synchronized (mPackages) { 11354 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11355 } 11356 } 11357 11358 @Override 11359 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11360 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11361 int uid = Binder.getCallingUid(); 11362 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11363 // reader 11364 synchronized (mPackages) { 11365 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11366 } 11367 } 11368 11369 public void enterSafeMode() { 11370 enforceSystemOrRoot("Only the system can request entering safe mode"); 11371 11372 if (!mSystemReady) { 11373 mSafeMode = true; 11374 } 11375 } 11376 11377 public void systemReady() { 11378 mSystemReady = true; 11379 11380 // Read the compatibilty setting when the system is ready. 11381 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11382 mContext.getContentResolver(), 11383 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11384 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11385 if (DEBUG_SETTINGS) { 11386 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11387 } 11388 11389 synchronized (mPackages) { 11390 // Verify that all of the preferred activity components actually 11391 // exist. It is possible for applications to be updated and at 11392 // that point remove a previously declared activity component that 11393 // had been set as a preferred activity. We try to clean this up 11394 // the next time we encounter that preferred activity, but it is 11395 // possible for the user flow to never be able to return to that 11396 // situation so here we do a sanity check to make sure we haven't 11397 // left any junk around. 11398 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11399 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11400 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11401 removed.clear(); 11402 for (PreferredActivity pa : pir.filterSet()) { 11403 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11404 removed.add(pa); 11405 } 11406 } 11407 if (removed.size() > 0) { 11408 for (int j=0; j<removed.size(); j++) { 11409 PreferredActivity pa = removed.get(i); 11410 Slog.w(TAG, "Removing dangling preferred activity: " 11411 + pa.mPref.mComponent); 11412 pir.removeFilter(pa); 11413 } 11414 mSettings.writePackageRestrictionsLPr( 11415 mSettings.mPreferredActivities.keyAt(i)); 11416 } 11417 } 11418 } 11419 sUserManager.systemReady(); 11420 } 11421 11422 public boolean isSafeMode() { 11423 return mSafeMode; 11424 } 11425 11426 public boolean hasSystemUidErrors() { 11427 return mHasSystemUidErrors; 11428 } 11429 11430 static String arrayToString(int[] array) { 11431 StringBuffer buf = new StringBuffer(128); 11432 buf.append('['); 11433 if (array != null) { 11434 for (int i=0; i<array.length; i++) { 11435 if (i > 0) buf.append(", "); 11436 buf.append(array[i]); 11437 } 11438 } 11439 buf.append(']'); 11440 return buf.toString(); 11441 } 11442 11443 static class DumpState { 11444 public static final int DUMP_LIBS = 1 << 0; 11445 11446 public static final int DUMP_FEATURES = 1 << 1; 11447 11448 public static final int DUMP_RESOLVERS = 1 << 2; 11449 11450 public static final int DUMP_PERMISSIONS = 1 << 3; 11451 11452 public static final int DUMP_PACKAGES = 1 << 4; 11453 11454 public static final int DUMP_SHARED_USERS = 1 << 5; 11455 11456 public static final int DUMP_MESSAGES = 1 << 6; 11457 11458 public static final int DUMP_PROVIDERS = 1 << 7; 11459 11460 public static final int DUMP_VERIFIERS = 1 << 8; 11461 11462 public static final int DUMP_PREFERRED = 1 << 9; 11463 11464 public static final int DUMP_PREFERRED_XML = 1 << 10; 11465 11466 public static final int DUMP_KEYSETS = 1 << 11; 11467 11468 public static final int DUMP_VERSION = 1 << 12; 11469 11470 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11471 11472 private int mTypes; 11473 11474 private int mOptions; 11475 11476 private boolean mTitlePrinted; 11477 11478 private SharedUserSetting mSharedUser; 11479 11480 public boolean isDumping(int type) { 11481 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11482 return true; 11483 } 11484 11485 return (mTypes & type) != 0; 11486 } 11487 11488 public void setDump(int type) { 11489 mTypes |= type; 11490 } 11491 11492 public boolean isOptionEnabled(int option) { 11493 return (mOptions & option) != 0; 11494 } 11495 11496 public void setOptionEnabled(int option) { 11497 mOptions |= option; 11498 } 11499 11500 public boolean onTitlePrinted() { 11501 final boolean printed = mTitlePrinted; 11502 mTitlePrinted = true; 11503 return printed; 11504 } 11505 11506 public boolean getTitlePrinted() { 11507 return mTitlePrinted; 11508 } 11509 11510 public void setTitlePrinted(boolean enabled) { 11511 mTitlePrinted = enabled; 11512 } 11513 11514 public SharedUserSetting getSharedUser() { 11515 return mSharedUser; 11516 } 11517 11518 public void setSharedUser(SharedUserSetting user) { 11519 mSharedUser = user; 11520 } 11521 } 11522 11523 @Override 11524 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 11525 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 11526 != PackageManager.PERMISSION_GRANTED) { 11527 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 11528 + Binder.getCallingPid() 11529 + ", uid=" + Binder.getCallingUid() 11530 + " without permission " 11531 + android.Manifest.permission.DUMP); 11532 return; 11533 } 11534 11535 DumpState dumpState = new DumpState(); 11536 boolean fullPreferred = false; 11537 boolean checkin = false; 11538 11539 String packageName = null; 11540 11541 int opti = 0; 11542 while (opti < args.length) { 11543 String opt = args[opti]; 11544 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 11545 break; 11546 } 11547 opti++; 11548 if ("-a".equals(opt)) { 11549 // Right now we only know how to print all. 11550 } else if ("-h".equals(opt)) { 11551 pw.println("Package manager dump options:"); 11552 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 11553 pw.println(" --checkin: dump for a checkin"); 11554 pw.println(" -f: print details of intent filters"); 11555 pw.println(" -h: print this help"); 11556 pw.println(" cmd may be one of:"); 11557 pw.println(" l[ibraries]: list known shared libraries"); 11558 pw.println(" f[ibraries]: list device features"); 11559 pw.println(" r[esolvers]: dump intent resolvers"); 11560 pw.println(" perm[issions]: dump permissions"); 11561 pw.println(" pref[erred]: print preferred package settings"); 11562 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 11563 pw.println(" prov[iders]: dump content providers"); 11564 pw.println(" p[ackages]: dump installed packages"); 11565 pw.println(" s[hared-users]: dump shared user IDs"); 11566 pw.println(" m[essages]: print collected runtime messages"); 11567 pw.println(" v[erifiers]: print package verifier info"); 11568 pw.println(" version: print database version info"); 11569 pw.println(" <package.name>: info about given package"); 11570 pw.println(" k[eysets]: print known keysets"); 11571 return; 11572 } else if ("--checkin".equals(opt)) { 11573 checkin = true; 11574 } else if ("-f".equals(opt)) { 11575 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11576 } else { 11577 pw.println("Unknown argument: " + opt + "; use -h for help"); 11578 } 11579 } 11580 11581 // Is the caller requesting to dump a particular piece of data? 11582 if (opti < args.length) { 11583 String cmd = args[opti]; 11584 opti++; 11585 // Is this a package name? 11586 if ("android".equals(cmd) || cmd.contains(".")) { 11587 packageName = cmd; 11588 // When dumping a single package, we always dump all of its 11589 // filter information since the amount of data will be reasonable. 11590 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11591 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 11592 dumpState.setDump(DumpState.DUMP_LIBS); 11593 } else if ("f".equals(cmd) || "features".equals(cmd)) { 11594 dumpState.setDump(DumpState.DUMP_FEATURES); 11595 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 11596 dumpState.setDump(DumpState.DUMP_RESOLVERS); 11597 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 11598 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 11599 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 11600 dumpState.setDump(DumpState.DUMP_PREFERRED); 11601 } else if ("preferred-xml".equals(cmd)) { 11602 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 11603 if (opti < args.length && "--full".equals(args[opti])) { 11604 fullPreferred = true; 11605 opti++; 11606 } 11607 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 11608 dumpState.setDump(DumpState.DUMP_PACKAGES); 11609 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 11610 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 11611 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 11612 dumpState.setDump(DumpState.DUMP_PROVIDERS); 11613 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 11614 dumpState.setDump(DumpState.DUMP_MESSAGES); 11615 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 11616 dumpState.setDump(DumpState.DUMP_VERIFIERS); 11617 } else if ("version".equals(cmd)) { 11618 dumpState.setDump(DumpState.DUMP_VERSION); 11619 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 11620 dumpState.setDump(DumpState.DUMP_KEYSETS); 11621 } 11622 } 11623 11624 if (checkin) { 11625 pw.println("vers,1"); 11626 } 11627 11628 // reader 11629 synchronized (mPackages) { 11630 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 11631 if (!checkin) { 11632 if (dumpState.onTitlePrinted()) 11633 pw.println(); 11634 pw.println("Database versions:"); 11635 pw.print(" SDK Version:"); 11636 pw.print(" internal="); 11637 pw.print(mSettings.mInternalSdkPlatform); 11638 pw.print(" external="); 11639 pw.println(mSettings.mExternalSdkPlatform); 11640 pw.print(" DB Version:"); 11641 pw.print(" internal="); 11642 pw.print(mSettings.mInternalDatabaseVersion); 11643 pw.print(" external="); 11644 pw.println(mSettings.mExternalDatabaseVersion); 11645 } 11646 } 11647 11648 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 11649 if (!checkin) { 11650 if (dumpState.onTitlePrinted()) 11651 pw.println(); 11652 pw.println("Verifiers:"); 11653 pw.print(" Required: "); 11654 pw.print(mRequiredVerifierPackage); 11655 pw.print(" (uid="); 11656 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 11657 pw.println(")"); 11658 } else if (mRequiredVerifierPackage != null) { 11659 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 11660 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 11661 } 11662 } 11663 11664 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 11665 boolean printedHeader = false; 11666 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 11667 while (it.hasNext()) { 11668 String name = it.next(); 11669 SharedLibraryEntry ent = mSharedLibraries.get(name); 11670 if (!checkin) { 11671 if (!printedHeader) { 11672 if (dumpState.onTitlePrinted()) 11673 pw.println(); 11674 pw.println("Libraries:"); 11675 printedHeader = true; 11676 } 11677 pw.print(" "); 11678 } else { 11679 pw.print("lib,"); 11680 } 11681 pw.print(name); 11682 if (!checkin) { 11683 pw.print(" -> "); 11684 } 11685 if (ent.path != null) { 11686 if (!checkin) { 11687 pw.print("(jar) "); 11688 pw.print(ent.path); 11689 } else { 11690 pw.print(",jar,"); 11691 pw.print(ent.path); 11692 } 11693 } else { 11694 if (!checkin) { 11695 pw.print("(apk) "); 11696 pw.print(ent.apk); 11697 } else { 11698 pw.print(",apk,"); 11699 pw.print(ent.apk); 11700 } 11701 } 11702 pw.println(); 11703 } 11704 } 11705 11706 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 11707 if (dumpState.onTitlePrinted()) 11708 pw.println(); 11709 if (!checkin) { 11710 pw.println("Features:"); 11711 } 11712 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 11713 while (it.hasNext()) { 11714 String name = it.next(); 11715 if (!checkin) { 11716 pw.print(" "); 11717 } else { 11718 pw.print("feat,"); 11719 } 11720 pw.println(name); 11721 } 11722 } 11723 11724 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 11725 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 11726 : "Activity Resolver Table:", " ", packageName, 11727 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11728 dumpState.setTitlePrinted(true); 11729 } 11730 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 11731 : "Receiver Resolver Table:", " ", packageName, 11732 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11733 dumpState.setTitlePrinted(true); 11734 } 11735 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 11736 : "Service Resolver Table:", " ", packageName, 11737 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11738 dumpState.setTitlePrinted(true); 11739 } 11740 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 11741 : "Provider Resolver Table:", " ", packageName, 11742 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11743 dumpState.setTitlePrinted(true); 11744 } 11745 } 11746 11747 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 11748 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11749 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11750 int user = mSettings.mPreferredActivities.keyAt(i); 11751 if (pir.dump(pw, 11752 dumpState.getTitlePrinted() 11753 ? "\nPreferred Activities User " + user + ":" 11754 : "Preferred Activities User " + user + ":", " ", 11755 packageName, true)) { 11756 dumpState.setTitlePrinted(true); 11757 } 11758 } 11759 } 11760 11761 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 11762 pw.flush(); 11763 FileOutputStream fout = new FileOutputStream(fd); 11764 BufferedOutputStream str = new BufferedOutputStream(fout); 11765 XmlSerializer serializer = new FastXmlSerializer(); 11766 try { 11767 serializer.setOutput(str, "utf-8"); 11768 serializer.startDocument(null, true); 11769 serializer.setFeature( 11770 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 11771 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 11772 serializer.endDocument(); 11773 serializer.flush(); 11774 } catch (IllegalArgumentException e) { 11775 pw.println("Failed writing: " + e); 11776 } catch (IllegalStateException e) { 11777 pw.println("Failed writing: " + e); 11778 } catch (IOException e) { 11779 pw.println("Failed writing: " + e); 11780 } 11781 } 11782 11783 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 11784 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 11785 } 11786 11787 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 11788 boolean printedSomething = false; 11789 for (PackageParser.Provider p : mProviders.mProviders.values()) { 11790 if (packageName != null && !packageName.equals(p.info.packageName)) { 11791 continue; 11792 } 11793 if (!printedSomething) { 11794 if (dumpState.onTitlePrinted()) 11795 pw.println(); 11796 pw.println("Registered ContentProviders:"); 11797 printedSomething = true; 11798 } 11799 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 11800 pw.print(" "); pw.println(p.toString()); 11801 } 11802 printedSomething = false; 11803 for (Map.Entry<String, PackageParser.Provider> entry : 11804 mProvidersByAuthority.entrySet()) { 11805 PackageParser.Provider p = entry.getValue(); 11806 if (packageName != null && !packageName.equals(p.info.packageName)) { 11807 continue; 11808 } 11809 if (!printedSomething) { 11810 if (dumpState.onTitlePrinted()) 11811 pw.println(); 11812 pw.println("ContentProvider Authorities:"); 11813 printedSomething = true; 11814 } 11815 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 11816 pw.print(" "); pw.println(p.toString()); 11817 if (p.info != null && p.info.applicationInfo != null) { 11818 final String appInfo = p.info.applicationInfo.toString(); 11819 pw.print(" applicationInfo="); pw.println(appInfo); 11820 } 11821 } 11822 } 11823 11824 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 11825 mSettings.mKeySetManager.dump(pw, packageName, dumpState); 11826 } 11827 11828 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 11829 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 11830 } 11831 11832 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 11833 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 11834 } 11835 11836 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 11837 if (dumpState.onTitlePrinted()) 11838 pw.println(); 11839 mSettings.dumpReadMessagesLPr(pw, dumpState); 11840 11841 pw.println(); 11842 pw.println("Package warning messages:"); 11843 final File fname = getSettingsProblemFile(); 11844 FileInputStream in = null; 11845 try { 11846 in = new FileInputStream(fname); 11847 final int avail = in.available(); 11848 final byte[] data = new byte[avail]; 11849 in.read(data); 11850 pw.print(new String(data)); 11851 } catch (FileNotFoundException e) { 11852 } catch (IOException e) { 11853 } finally { 11854 if (in != null) { 11855 try { 11856 in.close(); 11857 } catch (IOException e) { 11858 } 11859 } 11860 } 11861 } 11862 } 11863 } 11864 11865 // ------- apps on sdcard specific code ------- 11866 static final boolean DEBUG_SD_INSTALL = false; 11867 11868 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 11869 11870 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 11871 11872 private boolean mMediaMounted = false; 11873 11874 private String getEncryptKey() { 11875 try { 11876 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 11877 SD_ENCRYPTION_KEYSTORE_NAME); 11878 if (sdEncKey == null) { 11879 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 11880 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 11881 if (sdEncKey == null) { 11882 Slog.e(TAG, "Failed to create encryption keys"); 11883 return null; 11884 } 11885 } 11886 return sdEncKey; 11887 } catch (NoSuchAlgorithmException nsae) { 11888 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 11889 return null; 11890 } catch (IOException ioe) { 11891 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 11892 return null; 11893 } 11894 11895 } 11896 11897 /* package */static String getTempContainerId() { 11898 int tmpIdx = 1; 11899 String list[] = PackageHelper.getSecureContainerList(); 11900 if (list != null) { 11901 for (final String name : list) { 11902 // Ignore null and non-temporary container entries 11903 if (name == null || !name.startsWith(mTempContainerPrefix)) { 11904 continue; 11905 } 11906 11907 String subStr = name.substring(mTempContainerPrefix.length()); 11908 try { 11909 int cid = Integer.parseInt(subStr); 11910 if (cid >= tmpIdx) { 11911 tmpIdx = cid + 1; 11912 } 11913 } catch (NumberFormatException e) { 11914 } 11915 } 11916 } 11917 return mTempContainerPrefix + tmpIdx; 11918 } 11919 11920 /* 11921 * Update media status on PackageManager. 11922 */ 11923 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 11924 int callingUid = Binder.getCallingUid(); 11925 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 11926 throw new SecurityException("Media status can only be updated by the system"); 11927 } 11928 // reader; this apparently protects mMediaMounted, but should probably 11929 // be a different lock in that case. 11930 synchronized (mPackages) { 11931 Log.i(TAG, "Updating external media status from " 11932 + (mMediaMounted ? "mounted" : "unmounted") + " to " 11933 + (mediaStatus ? "mounted" : "unmounted")); 11934 if (DEBUG_SD_INSTALL) 11935 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 11936 + ", mMediaMounted=" + mMediaMounted); 11937 if (mediaStatus == mMediaMounted) { 11938 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 11939 : 0, -1); 11940 mHandler.sendMessage(msg); 11941 return; 11942 } 11943 mMediaMounted = mediaStatus; 11944 } 11945 // Queue up an async operation since the package installation may take a 11946 // little while. 11947 mHandler.post(new Runnable() { 11948 public void run() { 11949 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 11950 } 11951 }); 11952 } 11953 11954 /** 11955 * Called by MountService when the initial ASECs to scan are available. 11956 * Should block until all the ASEC containers are finished being scanned. 11957 */ 11958 public void scanAvailableAsecs() { 11959 updateExternalMediaStatusInner(true, false, false); 11960 if (mShouldRestoreconData) { 11961 SELinuxMMAC.setRestoreconDone(); 11962 mShouldRestoreconData = false; 11963 } 11964 } 11965 11966 /* 11967 * Collect information of applications on external media, map them against 11968 * existing containers and update information based on current mount status. 11969 * Please note that we always have to report status if reportStatus has been 11970 * set to true especially when unloading packages. 11971 */ 11972 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 11973 boolean externalStorage) { 11974 // Collection of uids 11975 int uidArr[] = null; 11976 // Collection of stale containers 11977 HashSet<String> removeCids = new HashSet<String>(); 11978 // Collection of packages on external media with valid containers. 11979 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 11980 // Get list of secure containers. 11981 final String list[] = PackageHelper.getSecureContainerList(); 11982 if (list == null || list.length == 0) { 11983 Log.i(TAG, "No secure containers on sdcard"); 11984 } else { 11985 // Process list of secure containers and categorize them 11986 // as active or stale based on their package internal state. 11987 int uidList[] = new int[list.length]; 11988 int num = 0; 11989 // reader 11990 synchronized (mPackages) { 11991 for (String cid : list) { 11992 if (DEBUG_SD_INSTALL) 11993 Log.i(TAG, "Processing container " + cid); 11994 String pkgName = getAsecPackageName(cid); 11995 if (pkgName == null) { 11996 if (DEBUG_SD_INSTALL) 11997 Log.i(TAG, "Container : " + cid + " stale"); 11998 removeCids.add(cid); 11999 continue; 12000 } 12001 if (DEBUG_SD_INSTALL) 12002 Log.i(TAG, "Looking for pkg : " + pkgName); 12003 12004 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12005 if (ps == null) { 12006 Log.i(TAG, "Deleting container with no matching settings " + cid); 12007 removeCids.add(cid); 12008 continue; 12009 } 12010 12011 /* 12012 * Skip packages that are not external if we're unmounting 12013 * external storage. 12014 */ 12015 if (externalStorage && !isMounted && !isExternal(ps)) { 12016 continue; 12017 } 12018 12019 final AsecInstallArgs args = new AsecInstallArgs(cid, 12020 getAppInstructionSetFromSettings(ps), 12021 isForwardLocked(ps)); 12022 // The package status is changed only if the code path 12023 // matches between settings and the container id. 12024 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12025 if (DEBUG_SD_INSTALL) { 12026 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12027 + " at code path: " + ps.codePathString); 12028 } 12029 12030 // We do have a valid package installed on sdcard 12031 processCids.put(args, ps.codePathString); 12032 final int uid = ps.appId; 12033 if (uid != -1) { 12034 uidList[num++] = uid; 12035 } 12036 } else { 12037 Log.i(TAG, "Deleting stale container for " + cid); 12038 removeCids.add(cid); 12039 } 12040 } 12041 } 12042 12043 if (num > 0) { 12044 // Sort uid list 12045 Arrays.sort(uidList, 0, num); 12046 // Throw away duplicates 12047 uidArr = new int[num]; 12048 uidArr[0] = uidList[0]; 12049 int di = 0; 12050 for (int i = 1; i < num; i++) { 12051 if (uidList[i - 1] != uidList[i]) { 12052 uidArr[di++] = uidList[i]; 12053 } 12054 } 12055 } 12056 } 12057 // Process packages with valid entries. 12058 if (isMounted) { 12059 if (DEBUG_SD_INSTALL) 12060 Log.i(TAG, "Loading packages"); 12061 loadMediaPackages(processCids, uidArr, removeCids); 12062 startCleaningPackages(); 12063 } else { 12064 if (DEBUG_SD_INSTALL) 12065 Log.i(TAG, "Unloading packages"); 12066 unloadMediaPackages(processCids, uidArr, reportStatus); 12067 } 12068 } 12069 12070 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12071 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12072 int size = pkgList.size(); 12073 if (size > 0) { 12074 // Send broadcasts here 12075 Bundle extras = new Bundle(); 12076 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12077 .toArray(new String[size])); 12078 if (uidArr != null) { 12079 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12080 } 12081 if (replacing) { 12082 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12083 } 12084 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12085 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12086 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12087 } 12088 } 12089 12090 /* 12091 * Look at potentially valid container ids from processCids If package 12092 * information doesn't match the one on record or package scanning fails, 12093 * the cid is added to list of removeCids. We currently don't delete stale 12094 * containers. 12095 */ 12096 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12097 HashSet<String> removeCids) { 12098 ArrayList<String> pkgList = new ArrayList<String>(); 12099 Set<AsecInstallArgs> keys = processCids.keySet(); 12100 boolean doGc = false; 12101 for (AsecInstallArgs args : keys) { 12102 String codePath = processCids.get(args); 12103 if (DEBUG_SD_INSTALL) 12104 Log.i(TAG, "Loading container : " + args.cid); 12105 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12106 try { 12107 // Make sure there are no container errors first. 12108 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12109 Slog.e(TAG, "Failed to mount cid : " + args.cid 12110 + " when installing from sdcard"); 12111 continue; 12112 } 12113 // Check code path here. 12114 if (codePath == null || !codePath.equals(args.getCodePath())) { 12115 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12116 + " does not match one in settings " + codePath); 12117 continue; 12118 } 12119 // Parse package 12120 int parseFlags = mDefParseFlags; 12121 if (args.isExternal()) { 12122 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12123 } 12124 if (args.isFwdLocked()) { 12125 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12126 } 12127 12128 doGc = true; 12129 synchronized (mInstallLock) { 12130 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 12131 0, 0, null); 12132 // Scan the package 12133 if (pkg != null) { 12134 /* 12135 * TODO why is the lock being held? doPostInstall is 12136 * called in other places without the lock. This needs 12137 * to be straightened out. 12138 */ 12139 // writer 12140 synchronized (mPackages) { 12141 retCode = PackageManager.INSTALL_SUCCEEDED; 12142 pkgList.add(pkg.packageName); 12143 // Post process args 12144 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12145 pkg.applicationInfo.uid); 12146 } 12147 } else { 12148 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12149 } 12150 } 12151 12152 } finally { 12153 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12154 // Don't destroy container here. Wait till gc clears things 12155 // up. 12156 removeCids.add(args.cid); 12157 } 12158 } 12159 } 12160 // writer 12161 synchronized (mPackages) { 12162 // If the platform SDK has changed since the last time we booted, 12163 // we need to re-grant app permission to catch any new ones that 12164 // appear. This is really a hack, and means that apps can in some 12165 // cases get permissions that the user didn't initially explicitly 12166 // allow... it would be nice to have some better way to handle 12167 // this situation. 12168 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12169 if (regrantPermissions) 12170 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12171 + mSdkVersion + "; regranting permissions for external storage"); 12172 mSettings.mExternalSdkPlatform = mSdkVersion; 12173 12174 // Make sure group IDs have been assigned, and any permission 12175 // changes in other apps are accounted for 12176 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12177 | (regrantPermissions 12178 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12179 : 0)); 12180 12181 mSettings.updateExternalDatabaseVersion(); 12182 12183 // can downgrade to reader 12184 // Persist settings 12185 mSettings.writeLPr(); 12186 } 12187 // Send a broadcast to let everyone know we are done processing 12188 if (pkgList.size() > 0) { 12189 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12190 } 12191 // Force gc to avoid any stale parser references that we might have. 12192 if (doGc) { 12193 Runtime.getRuntime().gc(); 12194 } 12195 // List stale containers and destroy stale temporary containers. 12196 if (removeCids != null) { 12197 for (String cid : removeCids) { 12198 if (cid.startsWith(mTempContainerPrefix)) { 12199 Log.i(TAG, "Destroying stale temporary container " + cid); 12200 PackageHelper.destroySdDir(cid); 12201 } else { 12202 Log.w(TAG, "Container " + cid + " is stale"); 12203 } 12204 } 12205 } 12206 } 12207 12208 /* 12209 * Utility method to unload a list of specified containers 12210 */ 12211 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12212 // Just unmount all valid containers. 12213 for (AsecInstallArgs arg : cidArgs) { 12214 synchronized (mInstallLock) { 12215 arg.doPostDeleteLI(false); 12216 } 12217 } 12218 } 12219 12220 /* 12221 * Unload packages mounted on external media. This involves deleting package 12222 * data from internal structures, sending broadcasts about diabled packages, 12223 * gc'ing to free up references, unmounting all secure containers 12224 * corresponding to packages on external media, and posting a 12225 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12226 * that we always have to post this message if status has been requested no 12227 * matter what. 12228 */ 12229 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12230 final boolean reportStatus) { 12231 if (DEBUG_SD_INSTALL) 12232 Log.i(TAG, "unloading media packages"); 12233 ArrayList<String> pkgList = new ArrayList<String>(); 12234 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12235 final Set<AsecInstallArgs> keys = processCids.keySet(); 12236 for (AsecInstallArgs args : keys) { 12237 String pkgName = args.getPackageName(); 12238 if (DEBUG_SD_INSTALL) 12239 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12240 // Delete package internally 12241 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12242 synchronized (mInstallLock) { 12243 boolean res = deletePackageLI(pkgName, null, false, null, null, 12244 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12245 if (res) { 12246 pkgList.add(pkgName); 12247 } else { 12248 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12249 failedList.add(args); 12250 } 12251 } 12252 } 12253 12254 // reader 12255 synchronized (mPackages) { 12256 // We didn't update the settings after removing each package; 12257 // write them now for all packages. 12258 mSettings.writeLPr(); 12259 } 12260 12261 // We have to absolutely send UPDATED_MEDIA_STATUS only 12262 // after confirming that all the receivers processed the ordered 12263 // broadcast when packages get disabled, force a gc to clean things up. 12264 // and unload all the containers. 12265 if (pkgList.size() > 0) { 12266 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12267 new IIntentReceiver.Stub() { 12268 public void performReceive(Intent intent, int resultCode, String data, 12269 Bundle extras, boolean ordered, boolean sticky, 12270 int sendingUser) throws RemoteException { 12271 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12272 reportStatus ? 1 : 0, 1, keys); 12273 mHandler.sendMessage(msg); 12274 } 12275 }); 12276 } else { 12277 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12278 keys); 12279 mHandler.sendMessage(msg); 12280 } 12281 } 12282 12283 /** Binder call */ 12284 @Override 12285 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12286 final int flags) { 12287 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12288 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12289 int returnCode = PackageManager.MOVE_SUCCEEDED; 12290 int currFlags = 0; 12291 int newFlags = 0; 12292 // reader 12293 synchronized (mPackages) { 12294 PackageParser.Package pkg = mPackages.get(packageName); 12295 if (pkg == null) { 12296 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12297 } else { 12298 // Disable moving fwd locked apps and system packages 12299 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12300 Slog.w(TAG, "Cannot move system application"); 12301 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12302 } else if (pkg.mOperationPending) { 12303 Slog.w(TAG, "Attempt to move package which has pending operations"); 12304 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12305 } else { 12306 // Find install location first 12307 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12308 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12309 Slog.w(TAG, "Ambigous flags specified for move location."); 12310 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12311 } else { 12312 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12313 : PackageManager.INSTALL_INTERNAL; 12314 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12315 : PackageManager.INSTALL_INTERNAL; 12316 12317 if (newFlags == currFlags) { 12318 Slog.w(TAG, "No move required. Trying to move to same location"); 12319 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12320 } else { 12321 if (isForwardLocked(pkg)) { 12322 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12323 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12324 } 12325 } 12326 } 12327 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12328 pkg.mOperationPending = true; 12329 } 12330 } 12331 } 12332 12333 /* 12334 * TODO this next block probably shouldn't be inside the lock. We 12335 * can't guarantee these won't change after this is fired off 12336 * anyway. 12337 */ 12338 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12339 processPendingMove(new MoveParams(null, observer, 0, packageName, null, 12340 null, -1, user), 12341 returnCode); 12342 } else { 12343 Message msg = mHandler.obtainMessage(INIT_COPY); 12344 final String instructionSet = getAppInstructionSet(pkg.applicationInfo); 12345 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir, 12346 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir, 12347 instructionSet); 12348 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12349 pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user); 12350 msg.obj = mp; 12351 mHandler.sendMessage(msg); 12352 } 12353 } 12354 } 12355 12356 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12357 // Queue up an async operation since the package deletion may take a 12358 // little while. 12359 mHandler.post(new Runnable() { 12360 public void run() { 12361 // TODO fix this; this does nothing. 12362 mHandler.removeCallbacks(this); 12363 int returnCode = currentStatus; 12364 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12365 int uidArr[] = null; 12366 ArrayList<String> pkgList = null; 12367 synchronized (mPackages) { 12368 PackageParser.Package pkg = mPackages.get(mp.packageName); 12369 if (pkg == null) { 12370 Slog.w(TAG, " Package " + mp.packageName 12371 + " doesn't exist. Aborting move"); 12372 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12373 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 12374 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12375 + mp.srcArgs.getCodePath() + " to " 12376 + pkg.applicationInfo.sourceDir 12377 + " Aborting move and returning error"); 12378 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12379 } else { 12380 uidArr = new int[] { 12381 pkg.applicationInfo.uid 12382 }; 12383 pkgList = new ArrayList<String>(); 12384 pkgList.add(mp.packageName); 12385 } 12386 } 12387 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12388 // Send resources unavailable broadcast 12389 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12390 // Update package code and resource paths 12391 synchronized (mInstallLock) { 12392 synchronized (mPackages) { 12393 PackageParser.Package pkg = mPackages.get(mp.packageName); 12394 // Recheck for package again. 12395 if (pkg == null) { 12396 Slog.w(TAG, " Package " + mp.packageName 12397 + " doesn't exist. Aborting move"); 12398 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12399 } else if (!mp.srcArgs.getCodePath().equals( 12400 pkg.applicationInfo.sourceDir)) { 12401 Slog.w(TAG, "Package " + mp.packageName 12402 + " code path changed from " + mp.srcArgs.getCodePath() 12403 + " to " + pkg.applicationInfo.sourceDir 12404 + " Aborting move and returning error"); 12405 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12406 } else { 12407 final String oldCodePath = pkg.mPath; 12408 final String newCodePath = mp.targetArgs.getCodePath(); 12409 final String newResPath = mp.targetArgs.getResourcePath(); 12410 final String newNativePath = mp.targetArgs 12411 .getNativeLibraryPath(); 12412 12413 final File newNativeDir = new File(newNativePath); 12414 12415 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12416 // NOTE: We do not report any errors from the APK scan and library 12417 // copy at this point. 12418 NativeLibraryHelper.ApkHandle handle = 12419 new NativeLibraryHelper.ApkHandle(newCodePath); 12420 final int abi = NativeLibraryHelper.findSupportedAbi( 12421 handle, Build.SUPPORTED_ABIS); 12422 if (abi >= 0) { 12423 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12424 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12425 } 12426 handle.close(); 12427 } 12428 final int[] users = sUserManager.getUserIds(); 12429 for (int user : users) { 12430 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 12431 newNativePath, user) < 0) { 12432 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12433 } 12434 } 12435 12436 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12437 pkg.mPath = newCodePath; 12438 // Move dex files around 12439 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) { 12440 // Moving of dex files failed. Set 12441 // error code and abort move. 12442 pkg.mPath = pkg.mScanPath; 12443 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12444 } 12445 } 12446 12447 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12448 pkg.mScanPath = newCodePath; 12449 pkg.applicationInfo.sourceDir = newCodePath; 12450 pkg.applicationInfo.publicSourceDir = newResPath; 12451 pkg.applicationInfo.nativeLibraryDir = newNativePath; 12452 PackageSetting ps = (PackageSetting) pkg.mExtras; 12453 ps.codePath = new File(pkg.applicationInfo.sourceDir); 12454 ps.codePathString = ps.codePath.getPath(); 12455 ps.resourcePath = new File( 12456 pkg.applicationInfo.publicSourceDir); 12457 ps.resourcePathString = ps.resourcePath.getPath(); 12458 ps.nativeLibraryPathString = newNativePath; 12459 // Set the application info flag 12460 // correctly. 12461 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 12462 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12463 } else { 12464 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12465 } 12466 ps.setFlags(pkg.applicationInfo.flags); 12467 mAppDirs.remove(oldCodePath); 12468 mAppDirs.put(newCodePath, pkg); 12469 // Persist settings 12470 mSettings.writeLPr(); 12471 } 12472 } 12473 } 12474 } 12475 // Send resources available broadcast 12476 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12477 } 12478 } 12479 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12480 // Clean up failed installation 12481 if (mp.targetArgs != null) { 12482 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 12483 -1); 12484 } 12485 } else { 12486 // Force a gc to clear things up. 12487 Runtime.getRuntime().gc(); 12488 // Delete older code 12489 synchronized (mInstallLock) { 12490 mp.srcArgs.doPostDeleteLI(true); 12491 } 12492 } 12493 12494 // Allow more operations on this file if we didn't fail because 12495 // an operation was already pending for this package. 12496 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 12497 synchronized (mPackages) { 12498 PackageParser.Package pkg = mPackages.get(mp.packageName); 12499 if (pkg != null) { 12500 pkg.mOperationPending = false; 12501 } 12502 } 12503 } 12504 12505 IPackageMoveObserver observer = mp.observer; 12506 if (observer != null) { 12507 try { 12508 observer.packageMoved(mp.packageName, returnCode); 12509 } catch (RemoteException e) { 12510 Log.i(TAG, "Observer no longer exists."); 12511 } 12512 } 12513 } 12514 }); 12515 } 12516 12517 public boolean setInstallLocation(int loc) { 12518 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12519 null); 12520 if (getInstallLocation() == loc) { 12521 return true; 12522 } 12523 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12524 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12525 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12526 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12527 return true; 12528 } 12529 return false; 12530 } 12531 12532 public int getInstallLocation() { 12533 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12534 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12535 PackageHelper.APP_INSTALL_AUTO); 12536 } 12537 12538 /** Called by UserManagerService */ 12539 void cleanUpUserLILPw(int userHandle) { 12540 mDirtyUsers.remove(userHandle); 12541 mSettings.removeUserLPr(userHandle); 12542 mPendingBroadcasts.remove(userHandle); 12543 if (mInstaller != null) { 12544 // Technically, we shouldn't be doing this with the package lock 12545 // held. However, this is very rare, and there is already so much 12546 // other disk I/O going on, that we'll let it slide for now. 12547 mInstaller.removeUserDataDirs(userHandle); 12548 } 12549 } 12550 12551 /** Called by UserManagerService */ 12552 void createNewUserLILPw(int userHandle, File path) { 12553 if (mInstaller != null) { 12554 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 12555 } 12556 } 12557 12558 @Override 12559 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 12560 mContext.enforceCallingOrSelfPermission( 12561 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12562 "Only package verification agents can read the verifier device identity"); 12563 12564 synchronized (mPackages) { 12565 return mSettings.getVerifierDeviceIdentityLPw(); 12566 } 12567 } 12568 12569 @Override 12570 public void setPermissionEnforced(String permission, boolean enforced) { 12571 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 12572 if (READ_EXTERNAL_STORAGE.equals(permission)) { 12573 synchronized (mPackages) { 12574 if (mSettings.mReadExternalStorageEnforced == null 12575 || mSettings.mReadExternalStorageEnforced != enforced) { 12576 mSettings.mReadExternalStorageEnforced = enforced; 12577 mSettings.writeLPr(); 12578 } 12579 } 12580 // kill any non-foreground processes so we restart them and 12581 // grant/revoke the GID. 12582 final IActivityManager am = ActivityManagerNative.getDefault(); 12583 if (am != null) { 12584 final long token = Binder.clearCallingIdentity(); 12585 try { 12586 am.killProcessesBelowForeground("setPermissionEnforcement"); 12587 } catch (RemoteException e) { 12588 } finally { 12589 Binder.restoreCallingIdentity(token); 12590 } 12591 } 12592 } else { 12593 throw new IllegalArgumentException("No selective enforcement for " + permission); 12594 } 12595 } 12596 12597 @Override 12598 @Deprecated 12599 public boolean isPermissionEnforced(String permission) { 12600 return true; 12601 } 12602 12603 @Override 12604 public boolean isStorageLow() { 12605 final long token = Binder.clearCallingIdentity(); 12606 try { 12607 final DeviceStorageMonitorInternal 12608 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12609 if (dsm != null) { 12610 return dsm.isMemoryLow(); 12611 } else { 12612 return false; 12613 } 12614 } finally { 12615 Binder.restoreCallingIdentity(token); 12616 } 12617 } 12618} 12619