PackageManagerService.java revision 0f206a149d27385ef092a34e0009a8607d663659
1282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski/* 2282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski * Copyright (C) 2006 The Android Open Source Project 3282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski * 4282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski * Licensed under the Apache License, Version 2.0 (the "License"); 5282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski * you may not use this file except in compliance with the License. 6282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski * You may obtain a copy of the License at 7282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski * 8282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski * http://www.apache.org/licenses/LICENSE-2.0 9282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski * 10282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski * Unless required by applicable law or agreed to in writing, software 11282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski * distributed under the License is distributed on an "AS IS" BASIS, 12282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski * See the License for the specific language governing permissions and 14282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski * limitations under the License. 15282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski */ 16282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski 17282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskipackage com.android.server.pm; 18282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski 19282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport static android.system.OsConstants.S_IRWXU; 27282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport static android.system.OsConstants.S_IRGRP; 28282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport static android.system.OsConstants.S_IXGRP; 29282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport static android.system.OsConstants.S_IROTH; 30282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport static android.system.OsConstants.S_IXOTH; 31282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport static com.android.internal.util.ArrayUtils.appendInt; 32282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport static com.android.internal.util.ArrayUtils.removeInt; 33282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski 34282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport android.content.pm.PackageParser.*; 35282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport com.android.internal.app.IMediaContainerService; 36282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport com.android.internal.app.ResolverActivity; 37282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport com.android.internal.content.NativeLibraryHelper; 38282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport com.android.internal.content.PackageHelper; 39282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport com.android.internal.util.FastPrintWriter; 40282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport com.android.internal.util.FastXmlSerializer; 41282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport com.android.internal.util.XmlUtils; 42282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport com.android.server.EventLogTags; 43282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport com.android.server.IntentResolver; 44282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport com.android.server.ServiceThread; 45282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski 46282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport com.android.server.LocalServices; 47282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport com.android.server.Watchdog; 48282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport org.xmlpull.v1.XmlPullParser; 49282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport org.xmlpull.v1.XmlPullParserException; 50282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport org.xmlpull.v1.XmlSerializer; 51282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinski 52282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport android.app.ActivityManager; 53282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport android.app.ActivityManagerNative; 54282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport android.app.IActivityManager; 55282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport android.app.admin.IDevicePolicyManager; 56282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport android.app.backup.IBackupManager; 57282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport android.content.BroadcastReceiver; 58282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport android.content.ComponentName; 59282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport android.content.Context; 60282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport android.content.IIntentReceiver; 61282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport android.content.Intent; 62282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport android.content.IntentFilter; 63282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport android.content.IntentSender; 64282e181b58cf72b6ca770dc7ca5f91f135444502Adam Lesinskiimport android.content.IntentSender.SendIntentException; 65import android.content.ServiceConnection; 66import android.content.pm.ActivityInfo; 67import android.content.pm.ApplicationInfo; 68import android.content.pm.ContainerEncryptionParams; 69import android.content.pm.FeatureInfo; 70import android.content.pm.IPackageDataObserver; 71import android.content.pm.IPackageDeleteObserver; 72import android.content.pm.IPackageInstallObserver; 73import android.content.pm.IPackageInstallObserver2; 74import android.content.pm.IPackageManager; 75import android.content.pm.IPackageMoveObserver; 76import android.content.pm.IPackageStatsObserver; 77import android.content.pm.InstrumentationInfo; 78import android.content.pm.ManifestDigest; 79import android.content.pm.PackageCleanItem; 80import android.content.pm.PackageInfo; 81import android.content.pm.PackageInfoLite; 82import android.content.pm.PackageManager; 83import android.content.pm.PackageParser; 84import android.content.pm.PackageStats; 85import android.content.pm.PackageUserState; 86import android.content.pm.ParceledListSlice; 87import android.content.pm.PermissionGroupInfo; 88import android.content.pm.PermissionInfo; 89import android.content.pm.ProviderInfo; 90import android.content.pm.ResolveInfo; 91import android.content.pm.ServiceInfo; 92import android.content.pm.Signature; 93import android.content.pm.VerificationParams; 94import android.content.pm.VerifierDeviceIdentity; 95import android.content.pm.VerifierInfo; 96import android.content.res.Resources; 97import android.hardware.display.DisplayManager; 98import android.net.Uri; 99import android.os.Binder; 100import android.os.Build; 101import android.os.Bundle; 102import android.os.Environment; 103import android.os.Environment.UserEnvironment; 104import android.os.FileObserver; 105import android.os.FileUtils; 106import android.os.Handler; 107import android.os.IBinder; 108import android.os.Looper; 109import android.os.Message; 110import android.os.Parcel; 111import android.os.ParcelFileDescriptor; 112import android.os.Process; 113import android.os.RemoteException; 114import android.os.SELinux; 115import android.os.ServiceManager; 116import android.os.SystemClock; 117import android.os.SystemProperties; 118import android.os.UserHandle; 119import android.os.UserManager; 120import android.security.KeyStore; 121import android.security.SystemKeyStore; 122import android.system.ErrnoException; 123import android.system.Os; 124import android.system.StructStat; 125import android.text.TextUtils; 126import android.util.DisplayMetrics; 127import android.util.EventLog; 128import android.util.Log; 129import android.util.LogPrinter; 130import android.util.PrintStreamPrinter; 131import android.util.Slog; 132import android.util.SparseArray; 133import android.util.Xml; 134import android.view.Display; 135 136import java.io.BufferedOutputStream; 137import java.io.File; 138import java.io.FileDescriptor; 139import java.io.FileInputStream; 140import java.io.FileNotFoundException; 141import java.io.FileOutputStream; 142import java.io.FileReader; 143import java.io.FilenameFilter; 144import java.io.IOException; 145import java.io.PrintWriter; 146import java.security.NoSuchAlgorithmException; 147import java.security.PublicKey; 148import java.security.cert.Certificate; 149import java.security.cert.CertificateEncodingException; 150import java.security.cert.CertificateException; 151import java.text.SimpleDateFormat; 152import java.util.ArrayList; 153import java.util.Arrays; 154import java.util.Collection; 155import java.util.Collections; 156import java.util.Comparator; 157import java.util.Date; 158import java.util.HashMap; 159import java.util.HashSet; 160import java.util.Iterator; 161import java.util.List; 162import java.util.Map; 163import java.util.Set; 164 165import dalvik.system.VMRuntime; 166import libcore.io.IoUtils; 167 168import com.android.internal.R; 169import com.android.server.pm.Settings.DatabaseVersion; 170import com.android.server.storage.DeviceStorageMonitorInternal; 171 172/** 173 * Keep track of all those .apks everywhere. 174 * 175 * This is very central to the platform's security; please run the unit 176 * tests whenever making modifications here: 177 * 178mmm frameworks/base/tests/AndroidTests 179adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 180adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 181 * 182 * {@hide} 183 */ 184public class PackageManagerService extends IPackageManager.Stub { 185 static final String TAG = "PackageManager"; 186 static final boolean DEBUG_SETTINGS = false; 187 static final boolean DEBUG_PREFERRED = false; 188 static final boolean DEBUG_UPGRADE = false; 189 private static final boolean DEBUG_INSTALL = false; 190 private static final boolean DEBUG_REMOVE = false; 191 private static final boolean DEBUG_BROADCASTS = false; 192 private static final boolean DEBUG_SHOW_INFO = false; 193 private static final boolean DEBUG_PACKAGE_INFO = false; 194 private static final boolean DEBUG_INTENT_MATCHING = false; 195 private static final boolean DEBUG_PACKAGE_SCANNING = false; 196 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 197 private static final boolean DEBUG_VERIFY = false; 198 199 private static final int RADIO_UID = Process.PHONE_UID; 200 private static final int LOG_UID = Process.LOG_UID; 201 private static final int NFC_UID = Process.NFC_UID; 202 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 203 private static final int SHELL_UID = Process.SHELL_UID; 204 205 // Cap the size of permission trees that 3rd party apps can define 206 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 207 208 private static final int REMOVE_EVENTS = 209 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 210 private static final int ADD_EVENTS = 211 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 212 213 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 214 // Suffix used during package installation when copying/moving 215 // package apks to install directory. 216 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 217 218 static final int SCAN_MONITOR = 1<<0; 219 static final int SCAN_NO_DEX = 1<<1; 220 static final int SCAN_FORCE_DEX = 1<<2; 221 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 222 static final int SCAN_NEW_INSTALL = 1<<4; 223 static final int SCAN_NO_PATHS = 1<<5; 224 static final int SCAN_UPDATE_TIME = 1<<6; 225 static final int SCAN_DEFER_DEX = 1<<7; 226 static final int SCAN_BOOTING = 1<<8; 227 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 228 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 229 230 static final int REMOVE_CHATTY = 1<<16; 231 232 /** 233 * Timeout (in milliseconds) after which the watchdog should declare that 234 * our handler thread is wedged. The usual default for such things is one 235 * minute but we sometimes do very lengthy I/O operations on this thread, 236 * such as installing multi-gigabyte applications, so ours needs to be longer. 237 */ 238 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 239 240 /** 241 * Whether verification is enabled by default. 242 */ 243 private static final boolean DEFAULT_VERIFY_ENABLE = true; 244 245 /** 246 * The default maximum time to wait for the verification agent to return in 247 * milliseconds. 248 */ 249 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 250 251 /** 252 * The default response for package verification timeout. 253 * 254 * This can be either PackageManager.VERIFICATION_ALLOW or 255 * PackageManager.VERIFICATION_REJECT. 256 */ 257 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 258 259 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 260 261 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 262 DEFAULT_CONTAINER_PACKAGE, 263 "com.android.defcontainer.DefaultContainerService"); 264 265 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 266 267 private static final String LIB_DIR_NAME = "lib"; 268 private static final String LIB64_DIR_NAME = "lib64"; 269 270 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 271 272 static final String mTempContainerPrefix = "smdl2tmp"; 273 274 private static String sPreferredInstructionSet; 275 276 final ServiceThread mHandlerThread; 277 278 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 279 private static final String IDMAP_SUFFIX = "@idmap"; 280 281 final PackageHandler mHandler; 282 283 final int mSdkVersion = Build.VERSION.SDK_INT; 284 285 final Context mContext; 286 final boolean mFactoryTest; 287 final boolean mOnlyCore; 288 final boolean mNoDexOpt; 289 final DisplayMetrics mMetrics; 290 final int mDefParseFlags; 291 final String[] mSeparateProcesses; 292 293 // This is where all application persistent data goes. 294 final File mAppDataDir; 295 296 // This is where all application persistent data goes for secondary users. 297 final File mUserAppDataDir; 298 299 /** The location for ASEC container files on internal storage. */ 300 final String mAsecInternalPath; 301 302 // This is the object monitoring the framework dir. 303 final FileObserver mFrameworkInstallObserver; 304 305 // This is the object monitoring the system app dir. 306 final FileObserver mSystemInstallObserver; 307 308 // This is the object monitoring the privileged system app dir. 309 final FileObserver mPrivilegedInstallObserver; 310 311 // This is the object monitoring the vendor app dir. 312 final FileObserver mVendorInstallObserver; 313 314 // This is the object monitoring the vendor overlay package dir. 315 final FileObserver mVendorOverlayInstallObserver; 316 317 // This is the object monitoring the OEM app dir. 318 final FileObserver mOemInstallObserver; 319 320 // This is the object monitoring mAppInstallDir. 321 final FileObserver mAppInstallObserver; 322 323 // This is the object monitoring mDrmAppPrivateInstallDir. 324 final FileObserver mDrmAppInstallObserver; 325 326 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 327 // LOCK HELD. Can be called with mInstallLock held. 328 final Installer mInstaller; 329 330 final File mAppInstallDir; 331 332 /** 333 * Directory to which applications installed internally have native 334 * libraries copied. 335 */ 336 private File mAppLibInstallDir; 337 338 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 339 // apps. 340 final File mDrmAppPrivateInstallDir; 341 342 // ---------------------------------------------------------------- 343 344 // Lock for state used when installing and doing other long running 345 // operations. Methods that must be called with this lock held have 346 // the suffix "LI". 347 final Object mInstallLock = new Object(); 348 349 // These are the directories in the 3rd party applications installed dir 350 // that we have currently loaded packages from. Keys are the application's 351 // installed zip file (absolute codePath), and values are Package. 352 final HashMap<String, PackageParser.Package> mAppDirs = 353 new HashMap<String, PackageParser.Package>(); 354 355 // Information for the parser to write more useful error messages. 356 int mLastScanError; 357 358 // ---------------------------------------------------------------- 359 360 // Keys are String (package name), values are Package. This also serves 361 // as the lock for the global state. Methods that must be called with 362 // this lock held have the prefix "LP". 363 final HashMap<String, PackageParser.Package> mPackages = 364 new HashMap<String, PackageParser.Package>(); 365 366 // Tracks available target package names -> overlay package paths. 367 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 368 new HashMap<String, HashMap<String, PackageParser.Package>>(); 369 370 final Settings mSettings; 371 boolean mRestoredSettings; 372 373 // Group-ids that are given to all packages as read from etc/permissions/*.xml. 374 int[] mGlobalGids; 375 376 // These are the built-in uid -> permission mappings that were read from the 377 // etc/permissions.xml file. 378 final SparseArray<HashSet<String>> mSystemPermissions = 379 new SparseArray<HashSet<String>>(); 380 381 static final class SharedLibraryEntry { 382 final String path; 383 final String apk; 384 385 SharedLibraryEntry(String _path, String _apk) { 386 path = _path; 387 apk = _apk; 388 } 389 } 390 391 // These are the built-in shared libraries that were read from the 392 // etc/permissions.xml file. 393 final HashMap<String, SharedLibraryEntry> mSharedLibraries 394 = new HashMap<String, SharedLibraryEntry>(); 395 396 // Temporary for building the final shared libraries for an .apk. 397 String[] mTmpSharedLibraries = null; 398 399 // These are the features this devices supports that were read from the 400 // etc/permissions.xml file. 401 final HashMap<String, FeatureInfo> mAvailableFeatures = 402 new HashMap<String, FeatureInfo>(); 403 404 // If mac_permissions.xml was found for seinfo labeling. 405 boolean mFoundPolicyFile; 406 407 // If a recursive restorecon of /data/data/<pkg> is needed. 408 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 409 410 // All available activities, for your resolving pleasure. 411 final ActivityIntentResolver mActivities = 412 new ActivityIntentResolver(); 413 414 // All available receivers, for your resolving pleasure. 415 final ActivityIntentResolver mReceivers = 416 new ActivityIntentResolver(); 417 418 // All available services, for your resolving pleasure. 419 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 420 421 // All available providers, for your resolving pleasure. 422 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 423 424 // Mapping from provider base names (first directory in content URI codePath) 425 // to the provider information. 426 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 427 new HashMap<String, PackageParser.Provider>(); 428 429 // Mapping from instrumentation class names to info about them. 430 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 431 new HashMap<ComponentName, PackageParser.Instrumentation>(); 432 433 // Mapping from permission names to info about them. 434 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 435 new HashMap<String, PackageParser.PermissionGroup>(); 436 437 // Packages whose data we have transfered into another package, thus 438 // should no longer exist. 439 final HashSet<String> mTransferedPackages = new HashSet<String>(); 440 441 // Broadcast actions that are only available to the system. 442 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 443 444 /** List of packages waiting for verification. */ 445 final SparseArray<PackageVerificationState> mPendingVerification 446 = new SparseArray<PackageVerificationState>(); 447 448 HashSet<PackageParser.Package> mDeferredDexOpt = null; 449 450 /** Token for keys in mPendingVerification. */ 451 private int mPendingVerificationToken = 0; 452 453 boolean mSystemReady; 454 boolean mSafeMode; 455 boolean mHasSystemUidErrors; 456 457 ApplicationInfo mAndroidApplication; 458 final ActivityInfo mResolveActivity = new ActivityInfo(); 459 final ResolveInfo mResolveInfo = new ResolveInfo(); 460 ComponentName mResolveComponentName; 461 PackageParser.Package mPlatformPackage; 462 ComponentName mCustomResolverComponentName; 463 464 boolean mResolverReplaced = false; 465 466 // Set of pending broadcasts for aggregating enable/disable of components. 467 static class PendingPackageBroadcasts { 468 // for each user id, a map of <package name -> components within that package> 469 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 470 471 public PendingPackageBroadcasts() { 472 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 473 } 474 475 public ArrayList<String> get(int userId, String packageName) { 476 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 477 return packages.get(packageName); 478 } 479 480 public void put(int userId, String packageName, ArrayList<String> components) { 481 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 482 packages.put(packageName, components); 483 } 484 485 public void remove(int userId, String packageName) { 486 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 487 if (packages != null) { 488 packages.remove(packageName); 489 } 490 } 491 492 public void remove(int userId) { 493 mUidMap.remove(userId); 494 } 495 496 public int userIdCount() { 497 return mUidMap.size(); 498 } 499 500 public int userIdAt(int n) { 501 return mUidMap.keyAt(n); 502 } 503 504 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 505 return mUidMap.get(userId); 506 } 507 508 public int size() { 509 // total number of pending broadcast entries across all userIds 510 int num = 0; 511 for (int i = 0; i< mUidMap.size(); i++) { 512 num += mUidMap.valueAt(i).size(); 513 } 514 return num; 515 } 516 517 public void clear() { 518 mUidMap.clear(); 519 } 520 521 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 522 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 523 if (map == null) { 524 map = new HashMap<String, ArrayList<String>>(); 525 mUidMap.put(userId, map); 526 } 527 return map; 528 } 529 } 530 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 531 532 // Service Connection to remote media container service to copy 533 // package uri's from external media onto secure containers 534 // or internal storage. 535 private IMediaContainerService mContainerService = null; 536 537 static final int SEND_PENDING_BROADCAST = 1; 538 static final int MCS_BOUND = 3; 539 static final int END_COPY = 4; 540 static final int INIT_COPY = 5; 541 static final int MCS_UNBIND = 6; 542 static final int START_CLEANING_PACKAGE = 7; 543 static final int FIND_INSTALL_LOC = 8; 544 static final int POST_INSTALL = 9; 545 static final int MCS_RECONNECT = 10; 546 static final int MCS_GIVE_UP = 11; 547 static final int UPDATED_MEDIA_STATUS = 12; 548 static final int WRITE_SETTINGS = 13; 549 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 550 static final int PACKAGE_VERIFIED = 15; 551 static final int CHECK_PENDING_VERIFICATION = 16; 552 553 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 554 555 // Delay time in millisecs 556 static final int BROADCAST_DELAY = 10 * 1000; 557 558 static UserManagerService sUserManager; 559 560 // Stores a list of users whose package restrictions file needs to be updated 561 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 562 563 final private DefaultContainerConnection mDefContainerConn = 564 new DefaultContainerConnection(); 565 class DefaultContainerConnection implements ServiceConnection { 566 public void onServiceConnected(ComponentName name, IBinder service) { 567 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 568 IMediaContainerService imcs = 569 IMediaContainerService.Stub.asInterface(service); 570 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 571 } 572 573 public void onServiceDisconnected(ComponentName name) { 574 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 575 } 576 }; 577 578 // Recordkeeping of restore-after-install operations that are currently in flight 579 // between the Package Manager and the Backup Manager 580 class PostInstallData { 581 public InstallArgs args; 582 public PackageInstalledInfo res; 583 584 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 585 args = _a; 586 res = _r; 587 } 588 }; 589 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 590 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 591 592 private final String mRequiredVerifierPackage; 593 594 class PackageHandler extends Handler { 595 private boolean mBound = false; 596 final ArrayList<HandlerParams> mPendingInstalls = 597 new ArrayList<HandlerParams>(); 598 599 private boolean connectToService() { 600 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 601 " DefaultContainerService"); 602 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 603 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 604 if (mContext.bindServiceAsUser(service, mDefContainerConn, 605 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 606 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 607 mBound = true; 608 return true; 609 } 610 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 611 return false; 612 } 613 614 private void disconnectService() { 615 mContainerService = null; 616 mBound = false; 617 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 618 mContext.unbindService(mDefContainerConn); 619 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 620 } 621 622 PackageHandler(Looper looper) { 623 super(looper); 624 } 625 626 public void handleMessage(Message msg) { 627 try { 628 doHandleMessage(msg); 629 } finally { 630 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 631 } 632 } 633 634 void doHandleMessage(Message msg) { 635 switch (msg.what) { 636 case INIT_COPY: { 637 HandlerParams params = (HandlerParams) msg.obj; 638 int idx = mPendingInstalls.size(); 639 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 640 // If a bind was already initiated we dont really 641 // need to do anything. The pending install 642 // will be processed later on. 643 if (!mBound) { 644 // If this is the only one pending we might 645 // have to bind to the service again. 646 if (!connectToService()) { 647 Slog.e(TAG, "Failed to bind to media container service"); 648 params.serviceError(); 649 return; 650 } else { 651 // Once we bind to the service, the first 652 // pending request will be processed. 653 mPendingInstalls.add(idx, params); 654 } 655 } else { 656 mPendingInstalls.add(idx, params); 657 // Already bound to the service. Just make 658 // sure we trigger off processing the first request. 659 if (idx == 0) { 660 mHandler.sendEmptyMessage(MCS_BOUND); 661 } 662 } 663 break; 664 } 665 case MCS_BOUND: { 666 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 667 if (msg.obj != null) { 668 mContainerService = (IMediaContainerService) msg.obj; 669 } 670 if (mContainerService == null) { 671 // Something seriously wrong. Bail out 672 Slog.e(TAG, "Cannot bind to media container service"); 673 for (HandlerParams params : mPendingInstalls) { 674 // Indicate service bind error 675 params.serviceError(); 676 } 677 mPendingInstalls.clear(); 678 } else if (mPendingInstalls.size() > 0) { 679 HandlerParams params = mPendingInstalls.get(0); 680 if (params != null) { 681 if (params.startCopy()) { 682 // We are done... look for more work or to 683 // go idle. 684 if (DEBUG_SD_INSTALL) Log.i(TAG, 685 "Checking for more work or unbind..."); 686 // Delete pending install 687 if (mPendingInstalls.size() > 0) { 688 mPendingInstalls.remove(0); 689 } 690 if (mPendingInstalls.size() == 0) { 691 if (mBound) { 692 if (DEBUG_SD_INSTALL) Log.i(TAG, 693 "Posting delayed MCS_UNBIND"); 694 removeMessages(MCS_UNBIND); 695 Message ubmsg = obtainMessage(MCS_UNBIND); 696 // Unbind after a little delay, to avoid 697 // continual thrashing. 698 sendMessageDelayed(ubmsg, 10000); 699 } 700 } else { 701 // There are more pending requests in queue. 702 // Just post MCS_BOUND message to trigger processing 703 // of next pending install. 704 if (DEBUG_SD_INSTALL) Log.i(TAG, 705 "Posting MCS_BOUND for next work"); 706 mHandler.sendEmptyMessage(MCS_BOUND); 707 } 708 } 709 } 710 } else { 711 // Should never happen ideally. 712 Slog.w(TAG, "Empty queue"); 713 } 714 break; 715 } 716 case MCS_RECONNECT: { 717 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 718 if (mPendingInstalls.size() > 0) { 719 if (mBound) { 720 disconnectService(); 721 } 722 if (!connectToService()) { 723 Slog.e(TAG, "Failed to bind to media container service"); 724 for (HandlerParams params : mPendingInstalls) { 725 // Indicate service bind error 726 params.serviceError(); 727 } 728 mPendingInstalls.clear(); 729 } 730 } 731 break; 732 } 733 case MCS_UNBIND: { 734 // If there is no actual work left, then time to unbind. 735 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 736 737 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 738 if (mBound) { 739 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 740 741 disconnectService(); 742 } 743 } else if (mPendingInstalls.size() > 0) { 744 // There are more pending requests in queue. 745 // Just post MCS_BOUND message to trigger processing 746 // of next pending install. 747 mHandler.sendEmptyMessage(MCS_BOUND); 748 } 749 750 break; 751 } 752 case MCS_GIVE_UP: { 753 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 754 mPendingInstalls.remove(0); 755 break; 756 } 757 case SEND_PENDING_BROADCAST: { 758 String packages[]; 759 ArrayList<String> components[]; 760 int size = 0; 761 int uids[]; 762 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 763 synchronized (mPackages) { 764 if (mPendingBroadcasts == null) { 765 return; 766 } 767 size = mPendingBroadcasts.size(); 768 if (size <= 0) { 769 // Nothing to be done. Just return 770 return; 771 } 772 packages = new String[size]; 773 components = new ArrayList[size]; 774 uids = new int[size]; 775 int i = 0; // filling out the above arrays 776 777 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 778 int packageUserId = mPendingBroadcasts.userIdAt(n); 779 Iterator<Map.Entry<String, ArrayList<String>>> it 780 = mPendingBroadcasts.packagesForUserId(packageUserId) 781 .entrySet().iterator(); 782 while (it.hasNext() && i < size) { 783 Map.Entry<String, ArrayList<String>> ent = it.next(); 784 packages[i] = ent.getKey(); 785 components[i] = ent.getValue(); 786 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 787 uids[i] = (ps != null) 788 ? UserHandle.getUid(packageUserId, ps.appId) 789 : -1; 790 i++; 791 } 792 } 793 size = i; 794 mPendingBroadcasts.clear(); 795 } 796 // Send broadcasts 797 for (int i = 0; i < size; i++) { 798 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 799 } 800 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 801 break; 802 } 803 case START_CLEANING_PACKAGE: { 804 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 805 final String packageName = (String)msg.obj; 806 final int userId = msg.arg1; 807 final boolean andCode = msg.arg2 != 0; 808 synchronized (mPackages) { 809 if (userId == UserHandle.USER_ALL) { 810 int[] users = sUserManager.getUserIds(); 811 for (int user : users) { 812 mSettings.addPackageToCleanLPw( 813 new PackageCleanItem(user, packageName, andCode)); 814 } 815 } else { 816 mSettings.addPackageToCleanLPw( 817 new PackageCleanItem(userId, packageName, andCode)); 818 } 819 } 820 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 821 startCleaningPackages(); 822 } break; 823 case POST_INSTALL: { 824 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 825 PostInstallData data = mRunningInstalls.get(msg.arg1); 826 mRunningInstalls.delete(msg.arg1); 827 boolean deleteOld = false; 828 829 if (data != null) { 830 InstallArgs args = data.args; 831 PackageInstalledInfo res = data.res; 832 833 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 834 res.removedInfo.sendBroadcast(false, true, false); 835 Bundle extras = new Bundle(1); 836 extras.putInt(Intent.EXTRA_UID, res.uid); 837 // Determine the set of users who are adding this 838 // package for the first time vs. those who are seeing 839 // an update. 840 int[] firstUsers; 841 int[] updateUsers = new int[0]; 842 if (res.origUsers == null || res.origUsers.length == 0) { 843 firstUsers = res.newUsers; 844 } else { 845 firstUsers = new int[0]; 846 for (int i=0; i<res.newUsers.length; i++) { 847 int user = res.newUsers[i]; 848 boolean isNew = true; 849 for (int j=0; j<res.origUsers.length; j++) { 850 if (res.origUsers[j] == user) { 851 isNew = false; 852 break; 853 } 854 } 855 if (isNew) { 856 int[] newFirst = new int[firstUsers.length+1]; 857 System.arraycopy(firstUsers, 0, newFirst, 0, 858 firstUsers.length); 859 newFirst[firstUsers.length] = user; 860 firstUsers = newFirst; 861 } else { 862 int[] newUpdate = new int[updateUsers.length+1]; 863 System.arraycopy(updateUsers, 0, newUpdate, 0, 864 updateUsers.length); 865 newUpdate[updateUsers.length] = user; 866 updateUsers = newUpdate; 867 } 868 } 869 } 870 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 871 res.pkg.applicationInfo.packageName, 872 extras, null, null, firstUsers); 873 final boolean update = res.removedInfo.removedPackage != null; 874 if (update) { 875 extras.putBoolean(Intent.EXTRA_REPLACING, true); 876 } 877 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 878 res.pkg.applicationInfo.packageName, 879 extras, null, null, updateUsers); 880 if (update) { 881 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 882 res.pkg.applicationInfo.packageName, 883 extras, null, null, updateUsers); 884 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 885 null, null, 886 res.pkg.applicationInfo.packageName, null, updateUsers); 887 888 // treat asec-hosted packages like removable media on upgrade 889 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 890 if (DEBUG_INSTALL) { 891 Slog.i(TAG, "upgrading pkg " + res.pkg 892 + " is ASEC-hosted -> AVAILABLE"); 893 } 894 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 895 ArrayList<String> pkgList = new ArrayList<String>(1); 896 pkgList.add(res.pkg.applicationInfo.packageName); 897 sendResourcesChangedBroadcast(true, true, 898 pkgList,uidArray, null); 899 } 900 } 901 if (res.removedInfo.args != null) { 902 // Remove the replaced package's older resources safely now 903 deleteOld = true; 904 } 905 906 // Log current value of "unknown sources" setting 907 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 908 getUnknownSourcesSettings()); 909 } 910 // Force a gc to clear up things 911 Runtime.getRuntime().gc(); 912 // We delete after a gc for applications on sdcard. 913 if (deleteOld) { 914 synchronized (mInstallLock) { 915 res.removedInfo.args.doPostDeleteLI(true); 916 } 917 } 918 if (args.observer != null) { 919 try { 920 args.observer.packageInstalled(res.name, res.returnCode); 921 } catch (RemoteException e) { 922 Slog.i(TAG, "Observer no longer exists."); 923 } 924 } 925 if (args.observer2 != null) { 926 try { 927 Bundle extras = extrasForInstallResult(res); 928 args.observer2.packageInstalled(res.name, extras, res.returnCode); 929 } catch (RemoteException e) { 930 Slog.i(TAG, "Observer no longer exists."); 931 } 932 } 933 } else { 934 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 935 } 936 } break; 937 case UPDATED_MEDIA_STATUS: { 938 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 939 boolean reportStatus = msg.arg1 == 1; 940 boolean doGc = msg.arg2 == 1; 941 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 942 if (doGc) { 943 // Force a gc to clear up stale containers. 944 Runtime.getRuntime().gc(); 945 } 946 if (msg.obj != null) { 947 @SuppressWarnings("unchecked") 948 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 949 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 950 // Unload containers 951 unloadAllContainers(args); 952 } 953 if (reportStatus) { 954 try { 955 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 956 PackageHelper.getMountService().finishMediaUpdate(); 957 } catch (RemoteException e) { 958 Log.e(TAG, "MountService not running?"); 959 } 960 } 961 } break; 962 case WRITE_SETTINGS: { 963 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 964 synchronized (mPackages) { 965 removeMessages(WRITE_SETTINGS); 966 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 967 mSettings.writeLPr(); 968 mDirtyUsers.clear(); 969 } 970 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 971 } break; 972 case WRITE_PACKAGE_RESTRICTIONS: { 973 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 974 synchronized (mPackages) { 975 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 976 for (int userId : mDirtyUsers) { 977 mSettings.writePackageRestrictionsLPr(userId); 978 } 979 mDirtyUsers.clear(); 980 } 981 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 982 } break; 983 case CHECK_PENDING_VERIFICATION: { 984 final int verificationId = msg.arg1; 985 final PackageVerificationState state = mPendingVerification.get(verificationId); 986 987 if ((state != null) && !state.timeoutExtended()) { 988 final InstallArgs args = state.getInstallArgs(); 989 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString()); 990 mPendingVerification.remove(verificationId); 991 992 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 993 994 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 995 Slog.i(TAG, "Continuing with installation of " 996 + args.packageURI.toString()); 997 state.setVerifierResponse(Binder.getCallingUid(), 998 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 999 broadcastPackageVerified(verificationId, args.packageURI, 1000 PackageManager.VERIFICATION_ALLOW, 1001 state.getInstallArgs().getUser()); 1002 try { 1003 ret = args.copyApk(mContainerService, true); 1004 } catch (RemoteException e) { 1005 Slog.e(TAG, "Could not contact the ContainerService"); 1006 } 1007 } else { 1008 broadcastPackageVerified(verificationId, args.packageURI, 1009 PackageManager.VERIFICATION_REJECT, 1010 state.getInstallArgs().getUser()); 1011 } 1012 1013 processPendingInstall(args, ret); 1014 mHandler.sendEmptyMessage(MCS_UNBIND); 1015 } 1016 break; 1017 } 1018 case PACKAGE_VERIFIED: { 1019 final int verificationId = msg.arg1; 1020 1021 final PackageVerificationState state = mPendingVerification.get(verificationId); 1022 if (state == null) { 1023 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1024 break; 1025 } 1026 1027 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1028 1029 state.setVerifierResponse(response.callerUid, response.code); 1030 1031 if (state.isVerificationComplete()) { 1032 mPendingVerification.remove(verificationId); 1033 1034 final InstallArgs args = state.getInstallArgs(); 1035 1036 int ret; 1037 if (state.isInstallAllowed()) { 1038 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1039 broadcastPackageVerified(verificationId, args.packageURI, 1040 response.code, state.getInstallArgs().getUser()); 1041 try { 1042 ret = args.copyApk(mContainerService, true); 1043 } catch (RemoteException e) { 1044 Slog.e(TAG, "Could not contact the ContainerService"); 1045 } 1046 } else { 1047 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1048 } 1049 1050 processPendingInstall(args, ret); 1051 1052 mHandler.sendEmptyMessage(MCS_UNBIND); 1053 } 1054 1055 break; 1056 } 1057 } 1058 } 1059 } 1060 1061 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1062 Bundle extras = null; 1063 switch (res.returnCode) { 1064 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1065 extras = new Bundle(); 1066 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1067 res.origPermission); 1068 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1069 res.origPackage); 1070 break; 1071 } 1072 } 1073 return extras; 1074 } 1075 1076 void scheduleWriteSettingsLocked() { 1077 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1078 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1079 } 1080 } 1081 1082 void scheduleWritePackageRestrictionsLocked(int userId) { 1083 if (!sUserManager.exists(userId)) return; 1084 mDirtyUsers.add(userId); 1085 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1086 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1087 } 1088 } 1089 1090 public static final IPackageManager main(Context context, Installer installer, 1091 boolean factoryTest, boolean onlyCore) { 1092 PackageManagerService m = new PackageManagerService(context, installer, 1093 factoryTest, onlyCore); 1094 ServiceManager.addService("package", m); 1095 return m; 1096 } 1097 1098 static String[] splitString(String str, char sep) { 1099 int count = 1; 1100 int i = 0; 1101 while ((i=str.indexOf(sep, i)) >= 0) { 1102 count++; 1103 i++; 1104 } 1105 1106 String[] res = new String[count]; 1107 i=0; 1108 count = 0; 1109 int lastI=0; 1110 while ((i=str.indexOf(sep, i)) >= 0) { 1111 res[count] = str.substring(lastI, i); 1112 count++; 1113 i++; 1114 lastI = i; 1115 } 1116 res[count] = str.substring(lastI, str.length()); 1117 return res; 1118 } 1119 1120 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1121 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1122 Context.DISPLAY_SERVICE); 1123 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1124 } 1125 1126 public PackageManagerService(Context context, Installer installer, 1127 boolean factoryTest, boolean onlyCore) { 1128 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1129 SystemClock.uptimeMillis()); 1130 1131 if (mSdkVersion <= 0) { 1132 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1133 } 1134 1135 mContext = context; 1136 mFactoryTest = factoryTest; 1137 mOnlyCore = onlyCore; 1138 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1139 mMetrics = new DisplayMetrics(); 1140 mSettings = new Settings(context); 1141 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1142 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1143 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1144 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1145 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1146 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1147 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1148 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1149 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1150 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1151 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1152 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1153 1154 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1155 if (separateProcesses != null && separateProcesses.length() > 0) { 1156 if ("*".equals(separateProcesses)) { 1157 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1158 mSeparateProcesses = null; 1159 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1160 } else { 1161 mDefParseFlags = 0; 1162 mSeparateProcesses = separateProcesses.split(","); 1163 Slog.w(TAG, "Running with debug.separate_processes: " 1164 + separateProcesses); 1165 } 1166 } else { 1167 mDefParseFlags = 0; 1168 mSeparateProcesses = null; 1169 } 1170 1171 mInstaller = installer; 1172 1173 getDefaultDisplayMetrics(context, mMetrics); 1174 1175 synchronized (mInstallLock) { 1176 // writer 1177 synchronized (mPackages) { 1178 mHandlerThread = new ServiceThread(TAG, 1179 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1180 mHandlerThread.start(); 1181 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1182 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1183 1184 File dataDir = Environment.getDataDirectory(); 1185 mAppDataDir = new File(dataDir, "data"); 1186 mAppInstallDir = new File(dataDir, "app"); 1187 mAppLibInstallDir = new File(dataDir, "app-lib"); 1188 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1189 mUserAppDataDir = new File(dataDir, "user"); 1190 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1191 1192 sUserManager = new UserManagerService(context, this, 1193 mInstallLock, mPackages); 1194 1195 // Read permissions and features from system 1196 readPermissions(Environment.buildPath( 1197 Environment.getRootDirectory(), "etc", "permissions"), false); 1198 // Only read features from OEM 1199 readPermissions(Environment.buildPath( 1200 Environment.getOemDirectory(), "etc", "permissions"), true); 1201 1202 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1203 1204 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1205 mSdkVersion, mOnlyCore); 1206 1207 String customResolverActivity = Resources.getSystem().getString( 1208 R.string.config_customResolverActivity); 1209 if (TextUtils.isEmpty(customResolverActivity)) { 1210 customResolverActivity = null; 1211 } else { 1212 mCustomResolverComponentName = ComponentName.unflattenFromString( 1213 customResolverActivity); 1214 } 1215 1216 long startTime = SystemClock.uptimeMillis(); 1217 1218 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1219 startTime); 1220 1221 // Set flag to monitor and not change apk file paths when 1222 // scanning install directories. 1223 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1224 if (mNoDexOpt) { 1225 Slog.w(TAG, "Running ENG build: no pre-dexopt!"); 1226 scanMode |= SCAN_NO_DEX; 1227 } 1228 1229 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1230 1231 /** 1232 * Add everything in the in the boot class path to the 1233 * list of process files because dexopt will have been run 1234 * if necessary during zygote startup. 1235 */ 1236 String bootClassPath = System.getProperty("java.boot.class.path"); 1237 if (bootClassPath != null) { 1238 String[] paths = splitString(bootClassPath, ':'); 1239 for (int i=0; i<paths.length; i++) { 1240 alreadyDexOpted.add(paths[i]); 1241 } 1242 } else { 1243 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1244 } 1245 1246 boolean didDexOpt = false; 1247 1248 final List<String> instructionSets = getAllInstructionSets(); 1249 1250 /** 1251 * Ensure all external libraries have had dexopt run on them. 1252 */ 1253 if (mSharedLibraries.size() > 0) { 1254 // NOTE: For now, we're compiling these system "shared libraries" 1255 // (and framework jars) into all available architectures. It's possible 1256 // to compile them only when we come across an app that uses them (there's 1257 // already logic for that in scanPackageLI) but that adds some complexity. 1258 for (String instructionSet : instructionSets) { 1259 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1260 final String lib = libEntry.path; 1261 if (lib == null) { 1262 continue; 1263 } 1264 1265 try { 1266 if (dalvik.system.DexFile.isDexOptNeededInternal( 1267 lib, null, instructionSet, false)) { 1268 alreadyDexOpted.add(lib); 1269 1270 // The list of "shared libraries" we have at this point is 1271 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1272 didDexOpt = true; 1273 } 1274 } catch (FileNotFoundException e) { 1275 Slog.w(TAG, "Library not found: " + lib); 1276 } catch (IOException e) { 1277 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1278 + e.getMessage()); 1279 } 1280 } 1281 } 1282 } 1283 1284 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1285 1286 // Gross hack for now: we know this file doesn't contain any 1287 // code, so don't dexopt it to avoid the resulting log spew. 1288 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1289 1290 // Gross hack for now: we know this file is only part of 1291 // the boot class path for art, so don't dexopt it to 1292 // avoid the resulting log spew. 1293 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1294 1295 /** 1296 * And there are a number of commands implemented in Java, which 1297 * we currently need to do the dexopt on so that they can be 1298 * run from a non-root shell. 1299 */ 1300 String[] frameworkFiles = frameworkDir.list(); 1301 if (frameworkFiles != null) { 1302 // TODO: We could compile these only for the most preferred ABI. We should 1303 // first double check that the dex files for these commands are not referenced 1304 // by other system apps. 1305 for (String instructionSet : instructionSets) { 1306 for (int i=0; i<frameworkFiles.length; i++) { 1307 File libPath = new File(frameworkDir, frameworkFiles[i]); 1308 String path = libPath.getPath(); 1309 // Skip the file if we already did it. 1310 if (alreadyDexOpted.contains(path)) { 1311 continue; 1312 } 1313 // Skip the file if it is not a type we want to dexopt. 1314 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1315 continue; 1316 } 1317 try { 1318 if (dalvik.system.DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1319 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1320 didDexOpt = true; 1321 } 1322 } catch (FileNotFoundException e) { 1323 Slog.w(TAG, "Jar not found: " + path); 1324 } catch (IOException e) { 1325 Slog.w(TAG, "Exception reading jar: " + path, e); 1326 } 1327 } 1328 } 1329 } 1330 1331 if (didDexOpt) { 1332 File dalvikCacheDir = new File(dataDir, "dalvik-cache"); 1333 1334 // If we had to do a dexopt of one of the previous 1335 // things, then something on the system has changed. 1336 // Consider this significant, and wipe away all other 1337 // existing dexopt files to ensure we don't leave any 1338 // dangling around. 1339 String[] files = dalvikCacheDir.list(); 1340 if (files != null) { 1341 for (int i=0; i<files.length; i++) { 1342 String fn = files[i]; 1343 if (fn.startsWith("data@app@") 1344 || fn.startsWith("data@app-private@")) { 1345 Slog.i(TAG, "Pruning dalvik file: " + fn); 1346 (new File(dalvikCacheDir, fn)).delete(); 1347 } 1348 } 1349 } 1350 } 1351 1352 // Collect vendor overlay packages. 1353 // (Do this before scanning any apps.) 1354 // For security and version matching reason, only consider 1355 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1356 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1357 mVendorOverlayInstallObserver = new AppDirObserver( 1358 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1359 mVendorOverlayInstallObserver.startWatching(); 1360 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1361 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1362 1363 // Find base frameworks (resource packages without code). 1364 mFrameworkInstallObserver = new AppDirObserver( 1365 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1366 mFrameworkInstallObserver.startWatching(); 1367 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1368 | PackageParser.PARSE_IS_SYSTEM_DIR 1369 | PackageParser.PARSE_IS_PRIVILEGED, 1370 scanMode | SCAN_NO_DEX, 0); 1371 1372 // Collected privileged system packages. 1373 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1374 mPrivilegedInstallObserver = new AppDirObserver( 1375 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1376 mPrivilegedInstallObserver.startWatching(); 1377 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1378 | PackageParser.PARSE_IS_SYSTEM_DIR 1379 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1380 1381 // Collect ordinary system packages. 1382 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1383 mSystemInstallObserver = new AppDirObserver( 1384 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1385 mSystemInstallObserver.startWatching(); 1386 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1387 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1388 1389 // Collect all vendor packages. 1390 File vendorAppDir = new File("/vendor/app"); 1391 try { 1392 vendorAppDir = vendorAppDir.getCanonicalFile(); 1393 } catch (IOException e) { 1394 // failed to look up canonical path, continue with original one 1395 } 1396 mVendorInstallObserver = new AppDirObserver( 1397 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1398 mVendorInstallObserver.startWatching(); 1399 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1400 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1401 1402 // Collect all OEM packages. 1403 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1404 mOemInstallObserver = new AppDirObserver( 1405 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1406 mOemInstallObserver.startWatching(); 1407 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1408 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1409 1410 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1411 mInstaller.moveFiles(); 1412 1413 // Prune any system packages that no longer exist. 1414 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1415 if (!mOnlyCore) { 1416 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1417 while (psit.hasNext()) { 1418 PackageSetting ps = psit.next(); 1419 1420 /* 1421 * If this is not a system app, it can't be a 1422 * disable system app. 1423 */ 1424 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1425 continue; 1426 } 1427 1428 /* 1429 * If the package is scanned, it's not erased. 1430 */ 1431 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1432 if (scannedPkg != null) { 1433 /* 1434 * If the system app is both scanned and in the 1435 * disabled packages list, then it must have been 1436 * added via OTA. Remove it from the currently 1437 * scanned package so the previously user-installed 1438 * application can be scanned. 1439 */ 1440 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1441 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1442 + "; removing system app"); 1443 removePackageLI(ps, true); 1444 } 1445 1446 continue; 1447 } 1448 1449 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1450 psit.remove(); 1451 String msg = "System package " + ps.name 1452 + " no longer exists; wiping its data"; 1453 reportSettingsProblem(Log.WARN, msg); 1454 removeDataDirsLI(ps.name); 1455 } else { 1456 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1457 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1458 possiblyDeletedUpdatedSystemApps.add(ps.name); 1459 } 1460 } 1461 } 1462 } 1463 1464 //look for any incomplete package installations 1465 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1466 //clean up list 1467 for(int i = 0; i < deletePkgsList.size(); i++) { 1468 //clean up here 1469 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1470 } 1471 //delete tmp files 1472 deleteTempPackageFiles(); 1473 1474 // Remove any shared userIDs that have no associated packages 1475 mSettings.pruneSharedUsersLPw(); 1476 1477 if (!mOnlyCore) { 1478 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1479 SystemClock.uptimeMillis()); 1480 mAppInstallObserver = new AppDirObserver( 1481 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1482 mAppInstallObserver.startWatching(); 1483 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1484 1485 mDrmAppInstallObserver = new AppDirObserver( 1486 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1487 mDrmAppInstallObserver.startWatching(); 1488 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1489 scanMode, 0); 1490 1491 /** 1492 * Remove disable package settings for any updated system 1493 * apps that were removed via an OTA. If they're not a 1494 * previously-updated app, remove them completely. 1495 * Otherwise, just revoke their system-level permissions. 1496 */ 1497 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1498 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1499 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1500 1501 String msg; 1502 if (deletedPkg == null) { 1503 msg = "Updated system package " + deletedAppName 1504 + " no longer exists; wiping its data"; 1505 removeDataDirsLI(deletedAppName); 1506 } else { 1507 msg = "Updated system app + " + deletedAppName 1508 + " no longer present; removing system privileges for " 1509 + deletedAppName; 1510 1511 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1512 1513 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1514 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1515 } 1516 reportSettingsProblem(Log.WARN, msg); 1517 } 1518 } else { 1519 mAppInstallObserver = null; 1520 mDrmAppInstallObserver = null; 1521 } 1522 1523 // Now that we know all of the shared libraries, update all clients to have 1524 // the correct library paths. 1525 updateAllSharedLibrariesLPw(); 1526 1527 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1528 SystemClock.uptimeMillis()); 1529 Slog.i(TAG, "Time to scan packages: " 1530 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1531 + " seconds"); 1532 1533 // If the platform SDK has changed since the last time we booted, 1534 // we need to re-grant app permission to catch any new ones that 1535 // appear. This is really a hack, and means that apps can in some 1536 // cases get permissions that the user didn't initially explicitly 1537 // allow... it would be nice to have some better way to handle 1538 // this situation. 1539 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1540 != mSdkVersion; 1541 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1542 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1543 + "; regranting permissions for internal storage"); 1544 mSettings.mInternalSdkPlatform = mSdkVersion; 1545 1546 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1547 | (regrantPermissions 1548 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1549 : 0)); 1550 1551 // If this is the first boot, and it is a normal boot, then 1552 // we need to initialize the default preferred apps. 1553 if (!mRestoredSettings && !onlyCore) { 1554 mSettings.readDefaultPreferredAppsLPw(this, 0); 1555 } 1556 1557 // All the changes are done during package scanning. 1558 mSettings.updateInternalDatabaseVersion(); 1559 1560 // can downgrade to reader 1561 mSettings.writeLPr(); 1562 1563 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1564 SystemClock.uptimeMillis()); 1565 1566 // Now after opening every single application zip, make sure they 1567 // are all flushed. Not really needed, but keeps things nice and 1568 // tidy. 1569 Runtime.getRuntime().gc(); 1570 1571 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1572 } // synchronized (mPackages) 1573 } // synchronized (mInstallLock) 1574 } 1575 1576 public boolean isFirstBoot() { 1577 return !mRestoredSettings; 1578 } 1579 1580 public boolean isOnlyCoreApps() { 1581 return mOnlyCore; 1582 } 1583 1584 private String getRequiredVerifierLPr() { 1585 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1586 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1587 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1588 1589 String requiredVerifier = null; 1590 1591 final int N = receivers.size(); 1592 for (int i = 0; i < N; i++) { 1593 final ResolveInfo info = receivers.get(i); 1594 1595 if (info.activityInfo == null) { 1596 continue; 1597 } 1598 1599 final String packageName = info.activityInfo.packageName; 1600 1601 final PackageSetting ps = mSettings.mPackages.get(packageName); 1602 if (ps == null) { 1603 continue; 1604 } 1605 1606 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1607 if (!gp.grantedPermissions 1608 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1609 continue; 1610 } 1611 1612 if (requiredVerifier != null) { 1613 throw new RuntimeException("There can be only one required verifier"); 1614 } 1615 1616 requiredVerifier = packageName; 1617 } 1618 1619 return requiredVerifier; 1620 } 1621 1622 @Override 1623 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1624 throws RemoteException { 1625 try { 1626 return super.onTransact(code, data, reply, flags); 1627 } catch (RuntimeException e) { 1628 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1629 Slog.wtf(TAG, "Package Manager Crash", e); 1630 } 1631 throw e; 1632 } 1633 } 1634 1635 void cleanupInstallFailedPackage(PackageSetting ps) { 1636 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1637 removeDataDirsLI(ps.name); 1638 if (ps.codePath != null) { 1639 if (!ps.codePath.delete()) { 1640 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1641 } 1642 } 1643 if (ps.resourcePath != null) { 1644 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1645 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1646 } 1647 } 1648 mSettings.removePackageLPw(ps.name); 1649 } 1650 1651 void readPermissions(File libraryDir, boolean onlyFeatures) { 1652 // Read permissions from .../etc/permission directory. 1653 if (!libraryDir.exists() || !libraryDir.isDirectory()) { 1654 Slog.w(TAG, "No directory " + libraryDir + ", skipping"); 1655 return; 1656 } 1657 if (!libraryDir.canRead()) { 1658 Slog.w(TAG, "Directory " + libraryDir + " cannot be read"); 1659 return; 1660 } 1661 1662 // Iterate over the files in the directory and scan .xml files 1663 for (File f : libraryDir.listFiles()) { 1664 // We'll read platform.xml last 1665 if (f.getPath().endsWith("etc/permissions/platform.xml")) { 1666 continue; 1667 } 1668 1669 if (!f.getPath().endsWith(".xml")) { 1670 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring"); 1671 continue; 1672 } 1673 if (!f.canRead()) { 1674 Slog.w(TAG, "Permissions library file " + f + " cannot be read"); 1675 continue; 1676 } 1677 1678 readPermissionsFromXml(f, onlyFeatures); 1679 } 1680 1681 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence 1682 final File permFile = new File(Environment.getRootDirectory(), 1683 "etc/permissions/platform.xml"); 1684 readPermissionsFromXml(permFile, onlyFeatures); 1685 } 1686 1687 private void readPermissionsFromXml(File permFile, boolean onlyFeatures) { 1688 FileReader permReader = null; 1689 try { 1690 permReader = new FileReader(permFile); 1691 } catch (FileNotFoundException e) { 1692 Slog.w(TAG, "Couldn't find or open permissions file " + permFile); 1693 return; 1694 } 1695 1696 try { 1697 XmlPullParser parser = Xml.newPullParser(); 1698 parser.setInput(permReader); 1699 1700 XmlUtils.beginDocument(parser, "permissions"); 1701 1702 while (true) { 1703 XmlUtils.nextElement(parser); 1704 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) { 1705 break; 1706 } 1707 1708 String name = parser.getName(); 1709 if ("group".equals(name) && !onlyFeatures) { 1710 String gidStr = parser.getAttributeValue(null, "gid"); 1711 if (gidStr != null) { 1712 int gid = Process.getGidForName(gidStr); 1713 mGlobalGids = appendInt(mGlobalGids, gid); 1714 } else { 1715 Slog.w(TAG, "<group> without gid at " 1716 + parser.getPositionDescription()); 1717 } 1718 1719 XmlUtils.skipCurrentTag(parser); 1720 continue; 1721 } else if ("permission".equals(name) && !onlyFeatures) { 1722 String perm = parser.getAttributeValue(null, "name"); 1723 if (perm == null) { 1724 Slog.w(TAG, "<permission> without name at " 1725 + parser.getPositionDescription()); 1726 XmlUtils.skipCurrentTag(parser); 1727 continue; 1728 } 1729 perm = perm.intern(); 1730 readPermission(parser, perm); 1731 1732 } else if ("assign-permission".equals(name) && !onlyFeatures) { 1733 String perm = parser.getAttributeValue(null, "name"); 1734 if (perm == null) { 1735 Slog.w(TAG, "<assign-permission> without name at " 1736 + parser.getPositionDescription()); 1737 XmlUtils.skipCurrentTag(parser); 1738 continue; 1739 } 1740 String uidStr = parser.getAttributeValue(null, "uid"); 1741 if (uidStr == null) { 1742 Slog.w(TAG, "<assign-permission> without uid at " 1743 + parser.getPositionDescription()); 1744 XmlUtils.skipCurrentTag(parser); 1745 continue; 1746 } 1747 int uid = Process.getUidForName(uidStr); 1748 if (uid < 0) { 1749 Slog.w(TAG, "<assign-permission> with unknown uid \"" 1750 + uidStr + "\" at " 1751 + parser.getPositionDescription()); 1752 XmlUtils.skipCurrentTag(parser); 1753 continue; 1754 } 1755 perm = perm.intern(); 1756 HashSet<String> perms = mSystemPermissions.get(uid); 1757 if (perms == null) { 1758 perms = new HashSet<String>(); 1759 mSystemPermissions.put(uid, perms); 1760 } 1761 perms.add(perm); 1762 XmlUtils.skipCurrentTag(parser); 1763 1764 } else if ("library".equals(name) && !onlyFeatures) { 1765 String lname = parser.getAttributeValue(null, "name"); 1766 String lfile = parser.getAttributeValue(null, "file"); 1767 if (lname == null) { 1768 Slog.w(TAG, "<library> without name at " 1769 + parser.getPositionDescription()); 1770 } else if (lfile == null) { 1771 Slog.w(TAG, "<library> without file at " 1772 + parser.getPositionDescription()); 1773 } else { 1774 //Log.i(TAG, "Got library " + lname + " in " + lfile); 1775 mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null)); 1776 } 1777 XmlUtils.skipCurrentTag(parser); 1778 continue; 1779 1780 } else if ("feature".equals(name)) { 1781 String fname = parser.getAttributeValue(null, "name"); 1782 if (fname == null) { 1783 Slog.w(TAG, "<feature> without name at " 1784 + parser.getPositionDescription()); 1785 } else { 1786 //Log.i(TAG, "Got feature " + fname); 1787 FeatureInfo fi = new FeatureInfo(); 1788 fi.name = fname; 1789 mAvailableFeatures.put(fname, fi); 1790 } 1791 XmlUtils.skipCurrentTag(parser); 1792 continue; 1793 1794 } else { 1795 XmlUtils.skipCurrentTag(parser); 1796 continue; 1797 } 1798 1799 } 1800 permReader.close(); 1801 } catch (XmlPullParserException e) { 1802 Slog.w(TAG, "Got execption parsing permissions.", e); 1803 } catch (IOException e) { 1804 Slog.w(TAG, "Got execption parsing permissions.", e); 1805 } 1806 } 1807 1808 void readPermission(XmlPullParser parser, String name) 1809 throws IOException, XmlPullParserException { 1810 1811 name = name.intern(); 1812 1813 BasePermission bp = mSettings.mPermissions.get(name); 1814 if (bp == null) { 1815 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN); 1816 mSettings.mPermissions.put(name, bp); 1817 } 1818 int outerDepth = parser.getDepth(); 1819 int type; 1820 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 1821 && (type != XmlPullParser.END_TAG 1822 || parser.getDepth() > outerDepth)) { 1823 if (type == XmlPullParser.END_TAG 1824 || type == XmlPullParser.TEXT) { 1825 continue; 1826 } 1827 1828 String tagName = parser.getName(); 1829 if ("group".equals(tagName)) { 1830 String gidStr = parser.getAttributeValue(null, "gid"); 1831 if (gidStr != null) { 1832 int gid = Process.getGidForName(gidStr); 1833 bp.gids = appendInt(bp.gids, gid); 1834 } else { 1835 Slog.w(TAG, "<group> without gid at " 1836 + parser.getPositionDescription()); 1837 } 1838 } 1839 XmlUtils.skipCurrentTag(parser); 1840 } 1841 } 1842 1843 static int[] appendInts(int[] cur, int[] add) { 1844 if (add == null) return cur; 1845 if (cur == null) return add; 1846 final int N = add.length; 1847 for (int i=0; i<N; i++) { 1848 cur = appendInt(cur, add[i]); 1849 } 1850 return cur; 1851 } 1852 1853 static int[] removeInts(int[] cur, int[] rem) { 1854 if (rem == null) return cur; 1855 if (cur == null) return cur; 1856 final int N = rem.length; 1857 for (int i=0; i<N; i++) { 1858 cur = removeInt(cur, rem[i]); 1859 } 1860 return cur; 1861 } 1862 1863 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1864 if (!sUserManager.exists(userId)) return null; 1865 final PackageSetting ps = (PackageSetting) p.mExtras; 1866 if (ps == null) { 1867 return null; 1868 } 1869 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1870 final PackageUserState state = ps.readUserState(userId); 1871 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1872 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1873 state, userId); 1874 } 1875 1876 public boolean isPackageAvailable(String packageName, int userId) { 1877 if (!sUserManager.exists(userId)) return false; 1878 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1879 synchronized (mPackages) { 1880 PackageParser.Package p = mPackages.get(packageName); 1881 if (p != null) { 1882 final PackageSetting ps = (PackageSetting) p.mExtras; 1883 if (ps != null) { 1884 final PackageUserState state = ps.readUserState(userId); 1885 if (state != null) { 1886 return PackageParser.isAvailable(state); 1887 } 1888 } 1889 } 1890 } 1891 return false; 1892 } 1893 1894 @Override 1895 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1896 if (!sUserManager.exists(userId)) return null; 1897 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1898 // reader 1899 synchronized (mPackages) { 1900 PackageParser.Package p = mPackages.get(packageName); 1901 if (DEBUG_PACKAGE_INFO) 1902 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1903 if (p != null) { 1904 return generatePackageInfo(p, flags, userId); 1905 } 1906 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1907 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1908 } 1909 } 1910 return null; 1911 } 1912 1913 public String[] currentToCanonicalPackageNames(String[] names) { 1914 String[] out = new String[names.length]; 1915 // reader 1916 synchronized (mPackages) { 1917 for (int i=names.length-1; i>=0; i--) { 1918 PackageSetting ps = mSettings.mPackages.get(names[i]); 1919 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1920 } 1921 } 1922 return out; 1923 } 1924 1925 public String[] canonicalToCurrentPackageNames(String[] names) { 1926 String[] out = new String[names.length]; 1927 // reader 1928 synchronized (mPackages) { 1929 for (int i=names.length-1; i>=0; i--) { 1930 String cur = mSettings.mRenamedPackages.get(names[i]); 1931 out[i] = cur != null ? cur : names[i]; 1932 } 1933 } 1934 return out; 1935 } 1936 1937 @Override 1938 public int getPackageUid(String packageName, int userId) { 1939 if (!sUserManager.exists(userId)) return -1; 1940 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1941 // reader 1942 synchronized (mPackages) { 1943 PackageParser.Package p = mPackages.get(packageName); 1944 if(p != null) { 1945 return UserHandle.getUid(userId, p.applicationInfo.uid); 1946 } 1947 PackageSetting ps = mSettings.mPackages.get(packageName); 1948 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1949 return -1; 1950 } 1951 p = ps.pkg; 1952 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1953 } 1954 } 1955 1956 @Override 1957 public int[] getPackageGids(String packageName) { 1958 // reader 1959 synchronized (mPackages) { 1960 PackageParser.Package p = mPackages.get(packageName); 1961 if (DEBUG_PACKAGE_INFO) 1962 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1963 if (p != null) { 1964 final PackageSetting ps = (PackageSetting)p.mExtras; 1965 return ps.getGids(); 1966 } 1967 } 1968 // stupid thing to indicate an error. 1969 return new int[0]; 1970 } 1971 1972 static final PermissionInfo generatePermissionInfo( 1973 BasePermission bp, int flags) { 1974 if (bp.perm != null) { 1975 return PackageParser.generatePermissionInfo(bp.perm, flags); 1976 } 1977 PermissionInfo pi = new PermissionInfo(); 1978 pi.name = bp.name; 1979 pi.packageName = bp.sourcePackage; 1980 pi.nonLocalizedLabel = bp.name; 1981 pi.protectionLevel = bp.protectionLevel; 1982 return pi; 1983 } 1984 1985 public PermissionInfo getPermissionInfo(String name, int flags) { 1986 // reader 1987 synchronized (mPackages) { 1988 final BasePermission p = mSettings.mPermissions.get(name); 1989 if (p != null) { 1990 return generatePermissionInfo(p, flags); 1991 } 1992 return null; 1993 } 1994 } 1995 1996 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1997 // reader 1998 synchronized (mPackages) { 1999 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2000 for (BasePermission p : mSettings.mPermissions.values()) { 2001 if (group == null) { 2002 if (p.perm == null || p.perm.info.group == null) { 2003 out.add(generatePermissionInfo(p, flags)); 2004 } 2005 } else { 2006 if (p.perm != null && group.equals(p.perm.info.group)) { 2007 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2008 } 2009 } 2010 } 2011 2012 if (out.size() > 0) { 2013 return out; 2014 } 2015 return mPermissionGroups.containsKey(group) ? out : null; 2016 } 2017 } 2018 2019 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2020 // reader 2021 synchronized (mPackages) { 2022 return PackageParser.generatePermissionGroupInfo( 2023 mPermissionGroups.get(name), flags); 2024 } 2025 } 2026 2027 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2028 // reader 2029 synchronized (mPackages) { 2030 final int N = mPermissionGroups.size(); 2031 ArrayList<PermissionGroupInfo> out 2032 = new ArrayList<PermissionGroupInfo>(N); 2033 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2034 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2035 } 2036 return out; 2037 } 2038 } 2039 2040 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2041 int userId) { 2042 if (!sUserManager.exists(userId)) return null; 2043 PackageSetting ps = mSettings.mPackages.get(packageName); 2044 if (ps != null) { 2045 if (ps.pkg == null) { 2046 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2047 flags, userId); 2048 if (pInfo != null) { 2049 return pInfo.applicationInfo; 2050 } 2051 return null; 2052 } 2053 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2054 ps.readUserState(userId), userId); 2055 } 2056 return null; 2057 } 2058 2059 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2060 int userId) { 2061 if (!sUserManager.exists(userId)) return null; 2062 PackageSetting ps = mSettings.mPackages.get(packageName); 2063 if (ps != null) { 2064 PackageParser.Package pkg = ps.pkg; 2065 if (pkg == null) { 2066 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2067 return null; 2068 } 2069 pkg = new PackageParser.Package(packageName); 2070 pkg.applicationInfo.packageName = packageName; 2071 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2072 pkg.applicationInfo.publicSourceDir = ps.resourcePathString; 2073 pkg.applicationInfo.sourceDir = ps.codePathString; 2074 pkg.applicationInfo.dataDir = 2075 getDataPathForPackage(packageName, 0).getPath(); 2076 pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString; 2077 pkg.applicationInfo.requiredCpuAbi = ps.requiredCpuAbiString; 2078 } 2079 return generatePackageInfo(pkg, flags, userId); 2080 } 2081 return null; 2082 } 2083 2084 @Override 2085 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2086 if (!sUserManager.exists(userId)) return null; 2087 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2088 // writer 2089 synchronized (mPackages) { 2090 PackageParser.Package p = mPackages.get(packageName); 2091 if (DEBUG_PACKAGE_INFO) Log.v( 2092 TAG, "getApplicationInfo " + packageName 2093 + ": " + p); 2094 if (p != null) { 2095 PackageSetting ps = mSettings.mPackages.get(packageName); 2096 if (ps == null) return null; 2097 // Note: isEnabledLP() does not apply here - always return info 2098 return PackageParser.generateApplicationInfo( 2099 p, flags, ps.readUserState(userId), userId); 2100 } 2101 if ("android".equals(packageName)||"system".equals(packageName)) { 2102 return mAndroidApplication; 2103 } 2104 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2105 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2106 } 2107 } 2108 return null; 2109 } 2110 2111 2112 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2113 mContext.enforceCallingOrSelfPermission( 2114 android.Manifest.permission.CLEAR_APP_CACHE, null); 2115 // Queue up an async operation since clearing cache may take a little while. 2116 mHandler.post(new Runnable() { 2117 public void run() { 2118 mHandler.removeCallbacks(this); 2119 int retCode = -1; 2120 synchronized (mInstallLock) { 2121 retCode = mInstaller.freeCache(freeStorageSize); 2122 if (retCode < 0) { 2123 Slog.w(TAG, "Couldn't clear application caches"); 2124 } 2125 } 2126 if (observer != null) { 2127 try { 2128 observer.onRemoveCompleted(null, (retCode >= 0)); 2129 } catch (RemoteException e) { 2130 Slog.w(TAG, "RemoveException when invoking call back"); 2131 } 2132 } 2133 } 2134 }); 2135 } 2136 2137 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2138 mContext.enforceCallingOrSelfPermission( 2139 android.Manifest.permission.CLEAR_APP_CACHE, null); 2140 // Queue up an async operation since clearing cache may take a little while. 2141 mHandler.post(new Runnable() { 2142 public void run() { 2143 mHandler.removeCallbacks(this); 2144 int retCode = -1; 2145 synchronized (mInstallLock) { 2146 retCode = mInstaller.freeCache(freeStorageSize); 2147 if (retCode < 0) { 2148 Slog.w(TAG, "Couldn't clear application caches"); 2149 } 2150 } 2151 if(pi != null) { 2152 try { 2153 // Callback via pending intent 2154 int code = (retCode >= 0) ? 1 : 0; 2155 pi.sendIntent(null, code, null, 2156 null, null); 2157 } catch (SendIntentException e1) { 2158 Slog.i(TAG, "Failed to send pending intent"); 2159 } 2160 } 2161 } 2162 }); 2163 } 2164 2165 @Override 2166 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2167 if (!sUserManager.exists(userId)) return null; 2168 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2169 synchronized (mPackages) { 2170 PackageParser.Activity a = mActivities.mActivities.get(component); 2171 2172 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2173 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2174 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2175 if (ps == null) return null; 2176 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2177 userId); 2178 } 2179 if (mResolveComponentName.equals(component)) { 2180 return mResolveActivity; 2181 } 2182 } 2183 return null; 2184 } 2185 2186 @Override 2187 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2188 String resolvedType) { 2189 synchronized (mPackages) { 2190 PackageParser.Activity a = mActivities.mActivities.get(component); 2191 if (a == null) { 2192 return false; 2193 } 2194 for (int i=0; i<a.intents.size(); i++) { 2195 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2196 intent.getData(), intent.getCategories(), TAG) >= 0) { 2197 return true; 2198 } 2199 } 2200 return false; 2201 } 2202 } 2203 2204 @Override 2205 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2206 if (!sUserManager.exists(userId)) return null; 2207 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2208 synchronized (mPackages) { 2209 PackageParser.Activity a = mReceivers.mActivities.get(component); 2210 if (DEBUG_PACKAGE_INFO) Log.v( 2211 TAG, "getReceiverInfo " + component + ": " + a); 2212 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2213 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2214 if (ps == null) return null; 2215 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2216 userId); 2217 } 2218 } 2219 return null; 2220 } 2221 2222 @Override 2223 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2224 if (!sUserManager.exists(userId)) return null; 2225 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2226 synchronized (mPackages) { 2227 PackageParser.Service s = mServices.mServices.get(component); 2228 if (DEBUG_PACKAGE_INFO) Log.v( 2229 TAG, "getServiceInfo " + component + ": " + s); 2230 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2231 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2232 if (ps == null) return null; 2233 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2234 userId); 2235 } 2236 } 2237 return null; 2238 } 2239 2240 @Override 2241 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2242 if (!sUserManager.exists(userId)) return null; 2243 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2244 synchronized (mPackages) { 2245 PackageParser.Provider p = mProviders.mProviders.get(component); 2246 if (DEBUG_PACKAGE_INFO) Log.v( 2247 TAG, "getProviderInfo " + component + ": " + p); 2248 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2249 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2250 if (ps == null) return null; 2251 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2252 userId); 2253 } 2254 } 2255 return null; 2256 } 2257 2258 public String[] getSystemSharedLibraryNames() { 2259 Set<String> libSet; 2260 synchronized (mPackages) { 2261 libSet = mSharedLibraries.keySet(); 2262 int size = libSet.size(); 2263 if (size > 0) { 2264 String[] libs = new String[size]; 2265 libSet.toArray(libs); 2266 return libs; 2267 } 2268 } 2269 return null; 2270 } 2271 2272 public FeatureInfo[] getSystemAvailableFeatures() { 2273 Collection<FeatureInfo> featSet; 2274 synchronized (mPackages) { 2275 featSet = mAvailableFeatures.values(); 2276 int size = featSet.size(); 2277 if (size > 0) { 2278 FeatureInfo[] features = new FeatureInfo[size+1]; 2279 featSet.toArray(features); 2280 FeatureInfo fi = new FeatureInfo(); 2281 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2282 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2283 features[size] = fi; 2284 return features; 2285 } 2286 } 2287 return null; 2288 } 2289 2290 public boolean hasSystemFeature(String name) { 2291 synchronized (mPackages) { 2292 return mAvailableFeatures.containsKey(name); 2293 } 2294 } 2295 2296 private void checkValidCaller(int uid, int userId) { 2297 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2298 return; 2299 2300 throw new SecurityException("Caller uid=" + uid 2301 + " is not privileged to communicate with user=" + userId); 2302 } 2303 2304 public int checkPermission(String permName, String pkgName) { 2305 synchronized (mPackages) { 2306 PackageParser.Package p = mPackages.get(pkgName); 2307 if (p != null && p.mExtras != null) { 2308 PackageSetting ps = (PackageSetting)p.mExtras; 2309 if (ps.sharedUser != null) { 2310 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2311 return PackageManager.PERMISSION_GRANTED; 2312 } 2313 } else if (ps.grantedPermissions.contains(permName)) { 2314 return PackageManager.PERMISSION_GRANTED; 2315 } 2316 } 2317 } 2318 return PackageManager.PERMISSION_DENIED; 2319 } 2320 2321 public int checkUidPermission(String permName, int uid) { 2322 synchronized (mPackages) { 2323 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2324 if (obj != null) { 2325 GrantedPermissions gp = (GrantedPermissions)obj; 2326 if (gp.grantedPermissions.contains(permName)) { 2327 return PackageManager.PERMISSION_GRANTED; 2328 } 2329 } else { 2330 HashSet<String> perms = mSystemPermissions.get(uid); 2331 if (perms != null && perms.contains(permName)) { 2332 return PackageManager.PERMISSION_GRANTED; 2333 } 2334 } 2335 } 2336 return PackageManager.PERMISSION_DENIED; 2337 } 2338 2339 /** 2340 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2341 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2342 * @param message the message to log on security exception 2343 * @return 2344 */ 2345 private void enforceCrossUserPermission(int callingUid, int userId, 2346 boolean requireFullPermission, String message) { 2347 if (userId < 0) { 2348 throw new IllegalArgumentException("Invalid userId " + userId); 2349 } 2350 if (userId == UserHandle.getUserId(callingUid)) return; 2351 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2352 if (requireFullPermission) { 2353 mContext.enforceCallingOrSelfPermission( 2354 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2355 } else { 2356 try { 2357 mContext.enforceCallingOrSelfPermission( 2358 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2359 } catch (SecurityException se) { 2360 mContext.enforceCallingOrSelfPermission( 2361 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2362 } 2363 } 2364 } 2365 } 2366 2367 private BasePermission findPermissionTreeLP(String permName) { 2368 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2369 if (permName.startsWith(bp.name) && 2370 permName.length() > bp.name.length() && 2371 permName.charAt(bp.name.length()) == '.') { 2372 return bp; 2373 } 2374 } 2375 return null; 2376 } 2377 2378 private BasePermission checkPermissionTreeLP(String permName) { 2379 if (permName != null) { 2380 BasePermission bp = findPermissionTreeLP(permName); 2381 if (bp != null) { 2382 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2383 return bp; 2384 } 2385 throw new SecurityException("Calling uid " 2386 + Binder.getCallingUid() 2387 + " is not allowed to add to permission tree " 2388 + bp.name + " owned by uid " + bp.uid); 2389 } 2390 } 2391 throw new SecurityException("No permission tree found for " + permName); 2392 } 2393 2394 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2395 if (s1 == null) { 2396 return s2 == null; 2397 } 2398 if (s2 == null) { 2399 return false; 2400 } 2401 if (s1.getClass() != s2.getClass()) { 2402 return false; 2403 } 2404 return s1.equals(s2); 2405 } 2406 2407 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2408 if (pi1.icon != pi2.icon) return false; 2409 if (pi1.logo != pi2.logo) return false; 2410 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2411 if (!compareStrings(pi1.name, pi2.name)) return false; 2412 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2413 // We'll take care of setting this one. 2414 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2415 // These are not currently stored in settings. 2416 //if (!compareStrings(pi1.group, pi2.group)) return false; 2417 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2418 //if (pi1.labelRes != pi2.labelRes) return false; 2419 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2420 return true; 2421 } 2422 2423 int permissionInfoFootprint(PermissionInfo info) { 2424 int size = info.name.length(); 2425 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2426 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2427 return size; 2428 } 2429 2430 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2431 int size = 0; 2432 for (BasePermission perm : mSettings.mPermissions.values()) { 2433 if (perm.uid == tree.uid) { 2434 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2435 } 2436 } 2437 return size; 2438 } 2439 2440 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2441 // We calculate the max size of permissions defined by this uid and throw 2442 // if that plus the size of 'info' would exceed our stated maximum. 2443 if (tree.uid != Process.SYSTEM_UID) { 2444 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2445 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2446 throw new SecurityException("Permission tree size cap exceeded"); 2447 } 2448 } 2449 } 2450 2451 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2452 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2453 throw new SecurityException("Label must be specified in permission"); 2454 } 2455 BasePermission tree = checkPermissionTreeLP(info.name); 2456 BasePermission bp = mSettings.mPermissions.get(info.name); 2457 boolean added = bp == null; 2458 boolean changed = true; 2459 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2460 if (added) { 2461 enforcePermissionCapLocked(info, tree); 2462 bp = new BasePermission(info.name, tree.sourcePackage, 2463 BasePermission.TYPE_DYNAMIC); 2464 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2465 throw new SecurityException( 2466 "Not allowed to modify non-dynamic permission " 2467 + info.name); 2468 } else { 2469 if (bp.protectionLevel == fixedLevel 2470 && bp.perm.owner.equals(tree.perm.owner) 2471 && bp.uid == tree.uid 2472 && comparePermissionInfos(bp.perm.info, info)) { 2473 changed = false; 2474 } 2475 } 2476 bp.protectionLevel = fixedLevel; 2477 info = new PermissionInfo(info); 2478 info.protectionLevel = fixedLevel; 2479 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2480 bp.perm.info.packageName = tree.perm.info.packageName; 2481 bp.uid = tree.uid; 2482 if (added) { 2483 mSettings.mPermissions.put(info.name, bp); 2484 } 2485 if (changed) { 2486 if (!async) { 2487 mSettings.writeLPr(); 2488 } else { 2489 scheduleWriteSettingsLocked(); 2490 } 2491 } 2492 return added; 2493 } 2494 2495 public boolean addPermission(PermissionInfo info) { 2496 synchronized (mPackages) { 2497 return addPermissionLocked(info, false); 2498 } 2499 } 2500 2501 public boolean addPermissionAsync(PermissionInfo info) { 2502 synchronized (mPackages) { 2503 return addPermissionLocked(info, true); 2504 } 2505 } 2506 2507 public void removePermission(String name) { 2508 synchronized (mPackages) { 2509 checkPermissionTreeLP(name); 2510 BasePermission bp = mSettings.mPermissions.get(name); 2511 if (bp != null) { 2512 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2513 throw new SecurityException( 2514 "Not allowed to modify non-dynamic permission " 2515 + name); 2516 } 2517 mSettings.mPermissions.remove(name); 2518 mSettings.writeLPr(); 2519 } 2520 } 2521 } 2522 2523 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2524 int index = pkg.requestedPermissions.indexOf(bp.name); 2525 if (index == -1) { 2526 throw new SecurityException("Package " + pkg.packageName 2527 + " has not requested permission " + bp.name); 2528 } 2529 boolean isNormal = 2530 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2531 == PermissionInfo.PROTECTION_NORMAL); 2532 boolean isDangerous = 2533 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2534 == PermissionInfo.PROTECTION_DANGEROUS); 2535 boolean isDevelopment = 2536 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2537 2538 if (!isNormal && !isDangerous && !isDevelopment) { 2539 throw new SecurityException("Permission " + bp.name 2540 + " is not a changeable permission type"); 2541 } 2542 2543 if (isNormal || isDangerous) { 2544 if (pkg.requestedPermissionsRequired.get(index)) { 2545 throw new SecurityException("Can't change " + bp.name 2546 + ". It is required by the application"); 2547 } 2548 } 2549 } 2550 2551 public void grantPermission(String packageName, String permissionName) { 2552 mContext.enforceCallingOrSelfPermission( 2553 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2554 synchronized (mPackages) { 2555 final PackageParser.Package pkg = mPackages.get(packageName); 2556 if (pkg == null) { 2557 throw new IllegalArgumentException("Unknown package: " + packageName); 2558 } 2559 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2560 if (bp == null) { 2561 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2562 } 2563 2564 checkGrantRevokePermissions(pkg, bp); 2565 2566 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2567 if (ps == null) { 2568 return; 2569 } 2570 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2571 if (gp.grantedPermissions.add(permissionName)) { 2572 if (ps.haveGids) { 2573 gp.gids = appendInts(gp.gids, bp.gids); 2574 } 2575 mSettings.writeLPr(); 2576 } 2577 } 2578 } 2579 2580 public void revokePermission(String packageName, String permissionName) { 2581 int changedAppId = -1; 2582 2583 synchronized (mPackages) { 2584 final PackageParser.Package pkg = mPackages.get(packageName); 2585 if (pkg == null) { 2586 throw new IllegalArgumentException("Unknown package: " + packageName); 2587 } 2588 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2589 mContext.enforceCallingOrSelfPermission( 2590 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2591 } 2592 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2593 if (bp == null) { 2594 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2595 } 2596 2597 checkGrantRevokePermissions(pkg, bp); 2598 2599 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2600 if (ps == null) { 2601 return; 2602 } 2603 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2604 if (gp.grantedPermissions.remove(permissionName)) { 2605 gp.grantedPermissions.remove(permissionName); 2606 if (ps.haveGids) { 2607 gp.gids = removeInts(gp.gids, bp.gids); 2608 } 2609 mSettings.writeLPr(); 2610 changedAppId = ps.appId; 2611 } 2612 } 2613 2614 if (changedAppId >= 0) { 2615 // We changed the perm on someone, kill its processes. 2616 IActivityManager am = ActivityManagerNative.getDefault(); 2617 if (am != null) { 2618 final int callingUserId = UserHandle.getCallingUserId(); 2619 final long ident = Binder.clearCallingIdentity(); 2620 try { 2621 //XXX we should only revoke for the calling user's app permissions, 2622 // but for now we impact all users. 2623 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2624 // "revoke " + permissionName); 2625 int[] users = sUserManager.getUserIds(); 2626 for (int user : users) { 2627 am.killUid(UserHandle.getUid(user, changedAppId), 2628 "revoke " + permissionName); 2629 } 2630 } catch (RemoteException e) { 2631 } finally { 2632 Binder.restoreCallingIdentity(ident); 2633 } 2634 } 2635 } 2636 } 2637 2638 public boolean isProtectedBroadcast(String actionName) { 2639 synchronized (mPackages) { 2640 return mProtectedBroadcasts.contains(actionName); 2641 } 2642 } 2643 2644 public int checkSignatures(String pkg1, String pkg2) { 2645 synchronized (mPackages) { 2646 final PackageParser.Package p1 = mPackages.get(pkg1); 2647 final PackageParser.Package p2 = mPackages.get(pkg2); 2648 if (p1 == null || p1.mExtras == null 2649 || p2 == null || p2.mExtras == null) { 2650 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2651 } 2652 return compareSignatures(p1.mSignatures, p2.mSignatures); 2653 } 2654 } 2655 2656 public int checkUidSignatures(int uid1, int uid2) { 2657 // Map to base uids. 2658 uid1 = UserHandle.getAppId(uid1); 2659 uid2 = UserHandle.getAppId(uid2); 2660 // reader 2661 synchronized (mPackages) { 2662 Signature[] s1; 2663 Signature[] s2; 2664 Object obj = mSettings.getUserIdLPr(uid1); 2665 if (obj != null) { 2666 if (obj instanceof SharedUserSetting) { 2667 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2668 } else if (obj instanceof PackageSetting) { 2669 s1 = ((PackageSetting)obj).signatures.mSignatures; 2670 } else { 2671 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2672 } 2673 } else { 2674 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2675 } 2676 obj = mSettings.getUserIdLPr(uid2); 2677 if (obj != null) { 2678 if (obj instanceof SharedUserSetting) { 2679 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2680 } else if (obj instanceof PackageSetting) { 2681 s2 = ((PackageSetting)obj).signatures.mSignatures; 2682 } else { 2683 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2684 } 2685 } else { 2686 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2687 } 2688 return compareSignatures(s1, s2); 2689 } 2690 } 2691 2692 /** 2693 * Compares two sets of signatures. Returns: 2694 * <br /> 2695 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2696 * <br /> 2697 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2698 * <br /> 2699 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2700 * <br /> 2701 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2702 * <br /> 2703 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2704 */ 2705 static int compareSignatures(Signature[] s1, Signature[] s2) { 2706 if (s1 == null) { 2707 return s2 == null 2708 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2709 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2710 } 2711 2712 if (s2 == null) { 2713 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2714 } 2715 2716 if (s1.length != s2.length) { 2717 return PackageManager.SIGNATURE_NO_MATCH; 2718 } 2719 2720 // Since both signature sets are of size 1, we can compare without HashSets. 2721 if (s1.length == 1) { 2722 return s1[0].equals(s2[0]) ? 2723 PackageManager.SIGNATURE_MATCH : 2724 PackageManager.SIGNATURE_NO_MATCH; 2725 } 2726 2727 HashSet<Signature> set1 = new HashSet<Signature>(); 2728 for (Signature sig : s1) { 2729 set1.add(sig); 2730 } 2731 HashSet<Signature> set2 = new HashSet<Signature>(); 2732 for (Signature sig : s2) { 2733 set2.add(sig); 2734 } 2735 // Make sure s2 contains all signatures in s1. 2736 if (set1.equals(set2)) { 2737 return PackageManager.SIGNATURE_MATCH; 2738 } 2739 return PackageManager.SIGNATURE_NO_MATCH; 2740 } 2741 2742 /** 2743 * If the database version for this type of package (internal storage or 2744 * external storage) is less than the version where package signatures 2745 * were updated, return true. 2746 */ 2747 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2748 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2749 DatabaseVersion.SIGNATURE_END_ENTITY)) 2750 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2751 DatabaseVersion.SIGNATURE_END_ENTITY)); 2752 } 2753 2754 /** 2755 * Used for backward compatibility to make sure any packages with 2756 * certificate chains get upgraded to the new style. {@code existingSigs} 2757 * will be in the old format (since they were stored on disk from before the 2758 * system upgrade) and {@code scannedSigs} will be in the newer format. 2759 */ 2760 private int compareSignaturesCompat(PackageSignatures existingSigs, 2761 PackageParser.Package scannedPkg) { 2762 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2763 return PackageManager.SIGNATURE_NO_MATCH; 2764 } 2765 2766 HashSet<Signature> existingSet = new HashSet<Signature>(); 2767 for (Signature sig : existingSigs.mSignatures) { 2768 existingSet.add(sig); 2769 } 2770 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2771 for (Signature sig : scannedPkg.mSignatures) { 2772 try { 2773 Signature[] chainSignatures = sig.getChainSignatures(); 2774 for (Signature chainSig : chainSignatures) { 2775 scannedCompatSet.add(chainSig); 2776 } 2777 } catch (CertificateEncodingException e) { 2778 scannedCompatSet.add(sig); 2779 } 2780 } 2781 /* 2782 * Make sure the expanded scanned set contains all signatures in the 2783 * existing one. 2784 */ 2785 if (scannedCompatSet.equals(existingSet)) { 2786 // Migrate the old signatures to the new scheme. 2787 existingSigs.assignSignatures(scannedPkg.mSignatures); 2788 // The new KeySets will be re-added later in the scanning process. 2789 mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName); 2790 return PackageManager.SIGNATURE_MATCH; 2791 } 2792 return PackageManager.SIGNATURE_NO_MATCH; 2793 } 2794 2795 public String[] getPackagesForUid(int uid) { 2796 uid = UserHandle.getAppId(uid); 2797 // reader 2798 synchronized (mPackages) { 2799 Object obj = mSettings.getUserIdLPr(uid); 2800 if (obj instanceof SharedUserSetting) { 2801 final SharedUserSetting sus = (SharedUserSetting) obj; 2802 final int N = sus.packages.size(); 2803 final String[] res = new String[N]; 2804 final Iterator<PackageSetting> it = sus.packages.iterator(); 2805 int i = 0; 2806 while (it.hasNext()) { 2807 res[i++] = it.next().name; 2808 } 2809 return res; 2810 } else if (obj instanceof PackageSetting) { 2811 final PackageSetting ps = (PackageSetting) obj; 2812 return new String[] { ps.name }; 2813 } 2814 } 2815 return null; 2816 } 2817 2818 public String getNameForUid(int uid) { 2819 // reader 2820 synchronized (mPackages) { 2821 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2822 if (obj instanceof SharedUserSetting) { 2823 final SharedUserSetting sus = (SharedUserSetting) obj; 2824 return sus.name + ":" + sus.userId; 2825 } else if (obj instanceof PackageSetting) { 2826 final PackageSetting ps = (PackageSetting) obj; 2827 return ps.name; 2828 } 2829 } 2830 return null; 2831 } 2832 2833 public int getUidForSharedUser(String sharedUserName) { 2834 if(sharedUserName == null) { 2835 return -1; 2836 } 2837 // reader 2838 synchronized (mPackages) { 2839 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2840 if (suid == null) { 2841 return -1; 2842 } 2843 return suid.userId; 2844 } 2845 } 2846 2847 public int getFlagsForUid(int uid) { 2848 synchronized (mPackages) { 2849 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2850 if (obj instanceof SharedUserSetting) { 2851 final SharedUserSetting sus = (SharedUserSetting) obj; 2852 return sus.pkgFlags; 2853 } else if (obj instanceof PackageSetting) { 2854 final PackageSetting ps = (PackageSetting) obj; 2855 return ps.pkgFlags; 2856 } 2857 } 2858 return 0; 2859 } 2860 2861 @Override 2862 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2863 int flags, int userId) { 2864 if (!sUserManager.exists(userId)) return null; 2865 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2866 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2867 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2868 } 2869 2870 @Override 2871 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2872 IntentFilter filter, int match, ComponentName activity) { 2873 final int userId = UserHandle.getCallingUserId(); 2874 if (DEBUG_PREFERRED) { 2875 Log.v(TAG, "setLastChosenActivity intent=" + intent 2876 + " resolvedType=" + resolvedType 2877 + " flags=" + flags 2878 + " filter=" + filter 2879 + " match=" + match 2880 + " activity=" + activity); 2881 filter.dump(new PrintStreamPrinter(System.out), " "); 2882 } 2883 intent.setComponent(null); 2884 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2885 // Find any earlier preferred or last chosen entries and nuke them 2886 findPreferredActivity(intent, resolvedType, 2887 flags, query, 0, false, true, false, userId); 2888 // Add the new activity as the last chosen for this filter 2889 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2890 } 2891 2892 @Override 2893 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2894 final int userId = UserHandle.getCallingUserId(); 2895 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2896 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2897 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2898 false, false, false, userId); 2899 } 2900 2901 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2902 int flags, List<ResolveInfo> query, int userId) { 2903 if (query != null) { 2904 final int N = query.size(); 2905 if (N == 1) { 2906 return query.get(0); 2907 } else if (N > 1) { 2908 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2909 // If there is more than one activity with the same priority, 2910 // then let the user decide between them. 2911 ResolveInfo r0 = query.get(0); 2912 ResolveInfo r1 = query.get(1); 2913 if (DEBUG_INTENT_MATCHING || debug) { 2914 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2915 + r1.activityInfo.name + "=" + r1.priority); 2916 } 2917 // If the first activity has a higher priority, or a different 2918 // default, then it is always desireable to pick it. 2919 if (r0.priority != r1.priority 2920 || r0.preferredOrder != r1.preferredOrder 2921 || r0.isDefault != r1.isDefault) { 2922 return query.get(0); 2923 } 2924 // If we have saved a preference for a preferred activity for 2925 // this Intent, use that. 2926 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2927 flags, query, r0.priority, true, false, debug, userId); 2928 if (ri != null) { 2929 return ri; 2930 } 2931 if (userId != 0) { 2932 ri = new ResolveInfo(mResolveInfo); 2933 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2934 ri.activityInfo.applicationInfo = new ApplicationInfo( 2935 ri.activityInfo.applicationInfo); 2936 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2937 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2938 return ri; 2939 } 2940 return mResolveInfo; 2941 } 2942 } 2943 return null; 2944 } 2945 2946 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2947 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2948 final int N = query.size(); 2949 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2950 .get(userId); 2951 // Get the list of persistent preferred activities that handle the intent 2952 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2953 List<PersistentPreferredActivity> pprefs = ppir != null 2954 ? ppir.queryIntent(intent, resolvedType, 2955 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2956 : null; 2957 if (pprefs != null && pprefs.size() > 0) { 2958 final int M = pprefs.size(); 2959 for (int i=0; i<M; i++) { 2960 final PersistentPreferredActivity ppa = pprefs.get(i); 2961 if (DEBUG_PREFERRED || debug) { 2962 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2963 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2964 + "\n component=" + ppa.mComponent); 2965 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2966 } 2967 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2968 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2969 if (DEBUG_PREFERRED || debug) { 2970 Slog.v(TAG, "Found persistent preferred activity:"); 2971 if (ai != null) { 2972 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2973 } else { 2974 Slog.v(TAG, " null"); 2975 } 2976 } 2977 if (ai == null) { 2978 // This previously registered persistent preferred activity 2979 // component is no longer known. Ignore it and do NOT remove it. 2980 continue; 2981 } 2982 for (int j=0; j<N; j++) { 2983 final ResolveInfo ri = query.get(j); 2984 if (!ri.activityInfo.applicationInfo.packageName 2985 .equals(ai.applicationInfo.packageName)) { 2986 continue; 2987 } 2988 if (!ri.activityInfo.name.equals(ai.name)) { 2989 continue; 2990 } 2991 // Found a persistent preference that can handle the intent. 2992 if (DEBUG_PREFERRED || debug) { 2993 Slog.v(TAG, "Returning persistent preferred activity: " + 2994 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 2995 } 2996 return ri; 2997 } 2998 } 2999 } 3000 return null; 3001 } 3002 3003 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3004 List<ResolveInfo> query, int priority, boolean always, 3005 boolean removeMatches, boolean debug, int userId) { 3006 if (!sUserManager.exists(userId)) return null; 3007 // writer 3008 synchronized (mPackages) { 3009 if (intent.getSelector() != null) { 3010 intent = intent.getSelector(); 3011 } 3012 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3013 3014 // Try to find a matching persistent preferred activity. 3015 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3016 debug, userId); 3017 3018 // If a persistent preferred activity matched, use it. 3019 if (pri != null) { 3020 return pri; 3021 } 3022 3023 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3024 // Get the list of preferred activities that handle the intent 3025 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3026 List<PreferredActivity> prefs = pir != null 3027 ? pir.queryIntent(intent, resolvedType, 3028 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3029 : null; 3030 if (prefs != null && prefs.size() > 0) { 3031 // First figure out how good the original match set is. 3032 // We will only allow preferred activities that came 3033 // from the same match quality. 3034 int match = 0; 3035 3036 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3037 3038 final int N = query.size(); 3039 for (int j=0; j<N; j++) { 3040 final ResolveInfo ri = query.get(j); 3041 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3042 + ": 0x" + Integer.toHexString(match)); 3043 if (ri.match > match) { 3044 match = ri.match; 3045 } 3046 } 3047 3048 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3049 + Integer.toHexString(match)); 3050 3051 match &= IntentFilter.MATCH_CATEGORY_MASK; 3052 final int M = prefs.size(); 3053 for (int i=0; i<M; i++) { 3054 final PreferredActivity pa = prefs.get(i); 3055 if (DEBUG_PREFERRED || debug) { 3056 Slog.v(TAG, "Checking PreferredActivity ds=" 3057 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3058 + "\n component=" + pa.mPref.mComponent); 3059 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3060 } 3061 if (pa.mPref.mMatch != match) { 3062 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3063 + Integer.toHexString(pa.mPref.mMatch)); 3064 continue; 3065 } 3066 // If it's not an "always" type preferred activity and that's what we're 3067 // looking for, skip it. 3068 if (always && !pa.mPref.mAlways) { 3069 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3070 continue; 3071 } 3072 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3073 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3074 if (DEBUG_PREFERRED || debug) { 3075 Slog.v(TAG, "Found preferred activity:"); 3076 if (ai != null) { 3077 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3078 } else { 3079 Slog.v(TAG, " null"); 3080 } 3081 } 3082 if (ai == null) { 3083 // This previously registered preferred activity 3084 // component is no longer known. Most likely an update 3085 // to the app was installed and in the new version this 3086 // component no longer exists. Clean it up by removing 3087 // it from the preferred activities list, and skip it. 3088 Slog.w(TAG, "Removing dangling preferred activity: " 3089 + pa.mPref.mComponent); 3090 pir.removeFilter(pa); 3091 continue; 3092 } 3093 for (int j=0; j<N; j++) { 3094 final ResolveInfo ri = query.get(j); 3095 if (!ri.activityInfo.applicationInfo.packageName 3096 .equals(ai.applicationInfo.packageName)) { 3097 continue; 3098 } 3099 if (!ri.activityInfo.name.equals(ai.name)) { 3100 continue; 3101 } 3102 3103 if (removeMatches) { 3104 pir.removeFilter(pa); 3105 if (DEBUG_PREFERRED) { 3106 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3107 } 3108 break; 3109 } 3110 3111 // Okay we found a previously set preferred or last chosen app. 3112 // If the result set is different from when this 3113 // was created, we need to clear it and re-ask the 3114 // user their preference, if we're looking for an "always" type entry. 3115 if (always && !pa.mPref.sameSet(query, priority)) { 3116 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3117 + intent + " type " + resolvedType); 3118 if (DEBUG_PREFERRED) { 3119 Slog.v(TAG, "Removing preferred activity since set changed " 3120 + pa.mPref.mComponent); 3121 } 3122 pir.removeFilter(pa); 3123 // Re-add the filter as a "last chosen" entry (!always) 3124 PreferredActivity lastChosen = new PreferredActivity( 3125 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3126 pir.addFilter(lastChosen); 3127 mSettings.writePackageRestrictionsLPr(userId); 3128 return null; 3129 } 3130 3131 // Yay! Either the set matched or we're looking for the last chosen 3132 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3133 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3134 mSettings.writePackageRestrictionsLPr(userId); 3135 return ri; 3136 } 3137 } 3138 } 3139 mSettings.writePackageRestrictionsLPr(userId); 3140 } 3141 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3142 return null; 3143 } 3144 3145 @Override 3146 public List<ResolveInfo> queryIntentActivities(Intent intent, 3147 String resolvedType, int flags, int userId) { 3148 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3149 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3150 ComponentName comp = intent.getComponent(); 3151 if (comp == null) { 3152 if (intent.getSelector() != null) { 3153 intent = intent.getSelector(); 3154 comp = intent.getComponent(); 3155 } 3156 } 3157 3158 if (comp != null) { 3159 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3160 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3161 if (ai != null) { 3162 final ResolveInfo ri = new ResolveInfo(); 3163 ri.activityInfo = ai; 3164 list.add(ri); 3165 } 3166 return list; 3167 } 3168 3169 // reader 3170 synchronized (mPackages) { 3171 final String pkgName = intent.getPackage(); 3172 if (pkgName == null) { 3173 return mActivities.queryIntent(intent, resolvedType, flags, userId); 3174 } 3175 final PackageParser.Package pkg = mPackages.get(pkgName); 3176 if (pkg != null) { 3177 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3178 pkg.activities, userId); 3179 } 3180 return new ArrayList<ResolveInfo>(); 3181 } 3182 } 3183 3184 @Override 3185 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3186 Intent[] specifics, String[] specificTypes, Intent intent, 3187 String resolvedType, int flags, int userId) { 3188 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3189 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3190 "query intent activity options"); 3191 final String resultsAction = intent.getAction(); 3192 3193 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3194 | PackageManager.GET_RESOLVED_FILTER, userId); 3195 3196 if (DEBUG_INTENT_MATCHING) { 3197 Log.v(TAG, "Query " + intent + ": " + results); 3198 } 3199 3200 int specificsPos = 0; 3201 int N; 3202 3203 // todo: note that the algorithm used here is O(N^2). This 3204 // isn't a problem in our current environment, but if we start running 3205 // into situations where we have more than 5 or 10 matches then this 3206 // should probably be changed to something smarter... 3207 3208 // First we go through and resolve each of the specific items 3209 // that were supplied, taking care of removing any corresponding 3210 // duplicate items in the generic resolve list. 3211 if (specifics != null) { 3212 for (int i=0; i<specifics.length; i++) { 3213 final Intent sintent = specifics[i]; 3214 if (sintent == null) { 3215 continue; 3216 } 3217 3218 if (DEBUG_INTENT_MATCHING) { 3219 Log.v(TAG, "Specific #" + i + ": " + sintent); 3220 } 3221 3222 String action = sintent.getAction(); 3223 if (resultsAction != null && resultsAction.equals(action)) { 3224 // If this action was explicitly requested, then don't 3225 // remove things that have it. 3226 action = null; 3227 } 3228 3229 ResolveInfo ri = null; 3230 ActivityInfo ai = null; 3231 3232 ComponentName comp = sintent.getComponent(); 3233 if (comp == null) { 3234 ri = resolveIntent( 3235 sintent, 3236 specificTypes != null ? specificTypes[i] : null, 3237 flags, userId); 3238 if (ri == null) { 3239 continue; 3240 } 3241 if (ri == mResolveInfo) { 3242 // ACK! Must do something better with this. 3243 } 3244 ai = ri.activityInfo; 3245 comp = new ComponentName(ai.applicationInfo.packageName, 3246 ai.name); 3247 } else { 3248 ai = getActivityInfo(comp, flags, userId); 3249 if (ai == null) { 3250 continue; 3251 } 3252 } 3253 3254 // Look for any generic query activities that are duplicates 3255 // of this specific one, and remove them from the results. 3256 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3257 N = results.size(); 3258 int j; 3259 for (j=specificsPos; j<N; j++) { 3260 ResolveInfo sri = results.get(j); 3261 if ((sri.activityInfo.name.equals(comp.getClassName()) 3262 && sri.activityInfo.applicationInfo.packageName.equals( 3263 comp.getPackageName())) 3264 || (action != null && sri.filter.matchAction(action))) { 3265 results.remove(j); 3266 if (DEBUG_INTENT_MATCHING) Log.v( 3267 TAG, "Removing duplicate item from " + j 3268 + " due to specific " + specificsPos); 3269 if (ri == null) { 3270 ri = sri; 3271 } 3272 j--; 3273 N--; 3274 } 3275 } 3276 3277 // Add this specific item to its proper place. 3278 if (ri == null) { 3279 ri = new ResolveInfo(); 3280 ri.activityInfo = ai; 3281 } 3282 results.add(specificsPos, ri); 3283 ri.specificIndex = i; 3284 specificsPos++; 3285 } 3286 } 3287 3288 // Now we go through the remaining generic results and remove any 3289 // duplicate actions that are found here. 3290 N = results.size(); 3291 for (int i=specificsPos; i<N-1; i++) { 3292 final ResolveInfo rii = results.get(i); 3293 if (rii.filter == null) { 3294 continue; 3295 } 3296 3297 // Iterate over all of the actions of this result's intent 3298 // filter... typically this should be just one. 3299 final Iterator<String> it = rii.filter.actionsIterator(); 3300 if (it == null) { 3301 continue; 3302 } 3303 while (it.hasNext()) { 3304 final String action = it.next(); 3305 if (resultsAction != null && resultsAction.equals(action)) { 3306 // If this action was explicitly requested, then don't 3307 // remove things that have it. 3308 continue; 3309 } 3310 for (int j=i+1; j<N; j++) { 3311 final ResolveInfo rij = results.get(j); 3312 if (rij.filter != null && rij.filter.hasAction(action)) { 3313 results.remove(j); 3314 if (DEBUG_INTENT_MATCHING) Log.v( 3315 TAG, "Removing duplicate item from " + j 3316 + " due to action " + action + " at " + i); 3317 j--; 3318 N--; 3319 } 3320 } 3321 } 3322 3323 // If the caller didn't request filter information, drop it now 3324 // so we don't have to marshall/unmarshall it. 3325 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3326 rii.filter = null; 3327 } 3328 } 3329 3330 // Filter out the caller activity if so requested. 3331 if (caller != null) { 3332 N = results.size(); 3333 for (int i=0; i<N; i++) { 3334 ActivityInfo ainfo = results.get(i).activityInfo; 3335 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3336 && caller.getClassName().equals(ainfo.name)) { 3337 results.remove(i); 3338 break; 3339 } 3340 } 3341 } 3342 3343 // If the caller didn't request filter information, 3344 // drop them now so we don't have to 3345 // marshall/unmarshall it. 3346 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3347 N = results.size(); 3348 for (int i=0; i<N; i++) { 3349 results.get(i).filter = null; 3350 } 3351 } 3352 3353 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3354 return results; 3355 } 3356 3357 @Override 3358 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3359 int userId) { 3360 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3361 ComponentName comp = intent.getComponent(); 3362 if (comp == null) { 3363 if (intent.getSelector() != null) { 3364 intent = intent.getSelector(); 3365 comp = intent.getComponent(); 3366 } 3367 } 3368 if (comp != null) { 3369 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3370 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3371 if (ai != null) { 3372 ResolveInfo ri = new ResolveInfo(); 3373 ri.activityInfo = ai; 3374 list.add(ri); 3375 } 3376 return list; 3377 } 3378 3379 // reader 3380 synchronized (mPackages) { 3381 String pkgName = intent.getPackage(); 3382 if (pkgName == null) { 3383 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3384 } 3385 final PackageParser.Package pkg = mPackages.get(pkgName); 3386 if (pkg != null) { 3387 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3388 userId); 3389 } 3390 return null; 3391 } 3392 } 3393 3394 @Override 3395 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3396 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3397 if (!sUserManager.exists(userId)) return null; 3398 if (query != null) { 3399 if (query.size() >= 1) { 3400 // If there is more than one service with the same priority, 3401 // just arbitrarily pick the first one. 3402 return query.get(0); 3403 } 3404 } 3405 return null; 3406 } 3407 3408 @Override 3409 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3410 int userId) { 3411 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3412 ComponentName comp = intent.getComponent(); 3413 if (comp == null) { 3414 if (intent.getSelector() != null) { 3415 intent = intent.getSelector(); 3416 comp = intent.getComponent(); 3417 } 3418 } 3419 if (comp != null) { 3420 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3421 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3422 if (si != null) { 3423 final ResolveInfo ri = new ResolveInfo(); 3424 ri.serviceInfo = si; 3425 list.add(ri); 3426 } 3427 return list; 3428 } 3429 3430 // reader 3431 synchronized (mPackages) { 3432 String pkgName = intent.getPackage(); 3433 if (pkgName == null) { 3434 return mServices.queryIntent(intent, resolvedType, flags, userId); 3435 } 3436 final PackageParser.Package pkg = mPackages.get(pkgName); 3437 if (pkg != null) { 3438 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3439 userId); 3440 } 3441 return null; 3442 } 3443 } 3444 3445 @Override 3446 public List<ResolveInfo> queryIntentContentProviders( 3447 Intent intent, String resolvedType, int flags, int userId) { 3448 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3449 ComponentName comp = intent.getComponent(); 3450 if (comp == null) { 3451 if (intent.getSelector() != null) { 3452 intent = intent.getSelector(); 3453 comp = intent.getComponent(); 3454 } 3455 } 3456 if (comp != null) { 3457 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3458 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3459 if (pi != null) { 3460 final ResolveInfo ri = new ResolveInfo(); 3461 ri.providerInfo = pi; 3462 list.add(ri); 3463 } 3464 return list; 3465 } 3466 3467 // reader 3468 synchronized (mPackages) { 3469 String pkgName = intent.getPackage(); 3470 if (pkgName == null) { 3471 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3472 } 3473 final PackageParser.Package pkg = mPackages.get(pkgName); 3474 if (pkg != null) { 3475 return mProviders.queryIntentForPackage( 3476 intent, resolvedType, flags, pkg.providers, userId); 3477 } 3478 return null; 3479 } 3480 } 3481 3482 @Override 3483 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3484 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3485 3486 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3487 3488 // writer 3489 synchronized (mPackages) { 3490 ArrayList<PackageInfo> list; 3491 if (listUninstalled) { 3492 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3493 for (PackageSetting ps : mSettings.mPackages.values()) { 3494 PackageInfo pi; 3495 if (ps.pkg != null) { 3496 pi = generatePackageInfo(ps.pkg, flags, userId); 3497 } else { 3498 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3499 } 3500 if (pi != null) { 3501 list.add(pi); 3502 } 3503 } 3504 } else { 3505 list = new ArrayList<PackageInfo>(mPackages.size()); 3506 for (PackageParser.Package p : mPackages.values()) { 3507 PackageInfo pi = generatePackageInfo(p, flags, userId); 3508 if (pi != null) { 3509 list.add(pi); 3510 } 3511 } 3512 } 3513 3514 return new ParceledListSlice<PackageInfo>(list); 3515 } 3516 } 3517 3518 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3519 String[] permissions, boolean[] tmp, int flags, int userId) { 3520 int numMatch = 0; 3521 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3522 for (int i=0; i<permissions.length; i++) { 3523 if (gp.grantedPermissions.contains(permissions[i])) { 3524 tmp[i] = true; 3525 numMatch++; 3526 } else { 3527 tmp[i] = false; 3528 } 3529 } 3530 if (numMatch == 0) { 3531 return; 3532 } 3533 PackageInfo pi; 3534 if (ps.pkg != null) { 3535 pi = generatePackageInfo(ps.pkg, flags, userId); 3536 } else { 3537 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3538 } 3539 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3540 if (numMatch == permissions.length) { 3541 pi.requestedPermissions = permissions; 3542 } else { 3543 pi.requestedPermissions = new String[numMatch]; 3544 numMatch = 0; 3545 for (int i=0; i<permissions.length; i++) { 3546 if (tmp[i]) { 3547 pi.requestedPermissions[numMatch] = permissions[i]; 3548 numMatch++; 3549 } 3550 } 3551 } 3552 } 3553 list.add(pi); 3554 } 3555 3556 @Override 3557 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3558 String[] permissions, int flags, int userId) { 3559 if (!sUserManager.exists(userId)) return null; 3560 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3561 3562 // writer 3563 synchronized (mPackages) { 3564 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3565 boolean[] tmpBools = new boolean[permissions.length]; 3566 if (listUninstalled) { 3567 for (PackageSetting ps : mSettings.mPackages.values()) { 3568 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3569 } 3570 } else { 3571 for (PackageParser.Package pkg : mPackages.values()) { 3572 PackageSetting ps = (PackageSetting)pkg.mExtras; 3573 if (ps != null) { 3574 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3575 userId); 3576 } 3577 } 3578 } 3579 3580 return new ParceledListSlice<PackageInfo>(list); 3581 } 3582 } 3583 3584 @Override 3585 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3586 if (!sUserManager.exists(userId)) return null; 3587 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3588 3589 // writer 3590 synchronized (mPackages) { 3591 ArrayList<ApplicationInfo> list; 3592 if (listUninstalled) { 3593 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3594 for (PackageSetting ps : mSettings.mPackages.values()) { 3595 ApplicationInfo ai; 3596 if (ps.pkg != null) { 3597 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3598 ps.readUserState(userId), userId); 3599 } else { 3600 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3601 } 3602 if (ai != null) { 3603 list.add(ai); 3604 } 3605 } 3606 } else { 3607 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3608 for (PackageParser.Package p : mPackages.values()) { 3609 if (p.mExtras != null) { 3610 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3611 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3612 if (ai != null) { 3613 list.add(ai); 3614 } 3615 } 3616 } 3617 } 3618 3619 return new ParceledListSlice<ApplicationInfo>(list); 3620 } 3621 } 3622 3623 public List<ApplicationInfo> getPersistentApplications(int flags) { 3624 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3625 3626 // reader 3627 synchronized (mPackages) { 3628 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3629 final int userId = UserHandle.getCallingUserId(); 3630 while (i.hasNext()) { 3631 final PackageParser.Package p = i.next(); 3632 if (p.applicationInfo != null 3633 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3634 && (!mSafeMode || isSystemApp(p))) { 3635 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3636 if (ps != null) { 3637 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3638 ps.readUserState(userId), userId); 3639 if (ai != null) { 3640 finalList.add(ai); 3641 } 3642 } 3643 } 3644 } 3645 } 3646 3647 return finalList; 3648 } 3649 3650 @Override 3651 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3652 if (!sUserManager.exists(userId)) return null; 3653 // reader 3654 synchronized (mPackages) { 3655 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3656 PackageSetting ps = provider != null 3657 ? mSettings.mPackages.get(provider.owner.packageName) 3658 : null; 3659 return ps != null 3660 && mSettings.isEnabledLPr(provider.info, flags, userId) 3661 && (!mSafeMode || (provider.info.applicationInfo.flags 3662 &ApplicationInfo.FLAG_SYSTEM) != 0) 3663 ? PackageParser.generateProviderInfo(provider, flags, 3664 ps.readUserState(userId), userId) 3665 : null; 3666 } 3667 } 3668 3669 /** 3670 * @deprecated 3671 */ 3672 @Deprecated 3673 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3674 // reader 3675 synchronized (mPackages) { 3676 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3677 .entrySet().iterator(); 3678 final int userId = UserHandle.getCallingUserId(); 3679 while (i.hasNext()) { 3680 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3681 PackageParser.Provider p = entry.getValue(); 3682 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3683 3684 if (ps != null && p.syncable 3685 && (!mSafeMode || (p.info.applicationInfo.flags 3686 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3687 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3688 ps.readUserState(userId), userId); 3689 if (info != null) { 3690 outNames.add(entry.getKey()); 3691 outInfo.add(info); 3692 } 3693 } 3694 } 3695 } 3696 } 3697 3698 public List<ProviderInfo> queryContentProviders(String processName, 3699 int uid, int flags) { 3700 ArrayList<ProviderInfo> finalList = null; 3701 // reader 3702 synchronized (mPackages) { 3703 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3704 final int userId = processName != null ? 3705 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3706 while (i.hasNext()) { 3707 final PackageParser.Provider p = i.next(); 3708 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3709 if (ps != null && p.info.authority != null 3710 && (processName == null 3711 || (p.info.processName.equals(processName) 3712 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3713 && mSettings.isEnabledLPr(p.info, flags, userId) 3714 && (!mSafeMode 3715 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3716 if (finalList == null) { 3717 finalList = new ArrayList<ProviderInfo>(3); 3718 } 3719 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3720 ps.readUserState(userId), userId); 3721 if (info != null) { 3722 finalList.add(info); 3723 } 3724 } 3725 } 3726 } 3727 3728 if (finalList != null) { 3729 Collections.sort(finalList, mProviderInitOrderSorter); 3730 } 3731 3732 return finalList; 3733 } 3734 3735 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3736 int flags) { 3737 // reader 3738 synchronized (mPackages) { 3739 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3740 return PackageParser.generateInstrumentationInfo(i, flags); 3741 } 3742 } 3743 3744 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3745 int flags) { 3746 ArrayList<InstrumentationInfo> finalList = 3747 new ArrayList<InstrumentationInfo>(); 3748 3749 // reader 3750 synchronized (mPackages) { 3751 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3752 while (i.hasNext()) { 3753 final PackageParser.Instrumentation p = i.next(); 3754 if (targetPackage == null 3755 || targetPackage.equals(p.info.targetPackage)) { 3756 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3757 flags); 3758 if (ii != null) { 3759 finalList.add(ii); 3760 } 3761 } 3762 } 3763 } 3764 3765 return finalList; 3766 } 3767 3768 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 3769 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 3770 if (overlays == null) { 3771 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 3772 return; 3773 } 3774 for (PackageParser.Package opkg : overlays.values()) { 3775 // Not much to do if idmap fails: we already logged the error 3776 // and we certainly don't want to abort installation of pkg simply 3777 // because an overlay didn't fit properly. For these reasons, 3778 // ignore the return value of createIdmapForPackagePairLI. 3779 createIdmapForPackagePairLI(pkg, opkg); 3780 } 3781 } 3782 3783 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 3784 PackageParser.Package opkg) { 3785 if (!opkg.mTrustedOverlay) { 3786 Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " + 3787 opkg.mScanPath + ": overlay not trusted"); 3788 return false; 3789 } 3790 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 3791 if (overlaySet == null) { 3792 Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " + 3793 opkg.mScanPath + " but target package has no known overlays"); 3794 return false; 3795 } 3796 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 3797 if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) { 3798 Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath); 3799 return false; 3800 } 3801 PackageParser.Package[] overlayArray = 3802 overlaySet.values().toArray(new PackageParser.Package[0]); 3803 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 3804 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 3805 return p1.mOverlayPriority - p2.mOverlayPriority; 3806 } 3807 }; 3808 Arrays.sort(overlayArray, cmp); 3809 3810 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 3811 int i = 0; 3812 for (PackageParser.Package p : overlayArray) { 3813 pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir; 3814 } 3815 return true; 3816 } 3817 3818 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 3819 String[] files = dir.list(); 3820 if (files == null) { 3821 Log.d(TAG, "No files in app dir " + dir); 3822 return; 3823 } 3824 3825 if (DEBUG_PACKAGE_SCANNING) { 3826 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 3827 + " flags=0x" + Integer.toHexString(flags)); 3828 } 3829 3830 int i; 3831 for (i=0; i<files.length; i++) { 3832 File file = new File(dir, files[i]); 3833 if (!isPackageFilename(files[i])) { 3834 // Ignore entries which are not apk's 3835 continue; 3836 } 3837 PackageParser.Package pkg = scanPackageLI(file, 3838 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null); 3839 // Don't mess around with apps in system partition. 3840 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 3841 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 3842 // Delete the apk 3843 Slog.w(TAG, "Cleaning up failed install of " + file); 3844 file.delete(); 3845 } 3846 } 3847 } 3848 3849 private static File getSettingsProblemFile() { 3850 File dataDir = Environment.getDataDirectory(); 3851 File systemDir = new File(dataDir, "system"); 3852 File fname = new File(systemDir, "uiderrors.txt"); 3853 return fname; 3854 } 3855 3856 static void reportSettingsProblem(int priority, String msg) { 3857 try { 3858 File fname = getSettingsProblemFile(); 3859 FileOutputStream out = new FileOutputStream(fname, true); 3860 PrintWriter pw = new FastPrintWriter(out); 3861 SimpleDateFormat formatter = new SimpleDateFormat(); 3862 String dateString = formatter.format(new Date(System.currentTimeMillis())); 3863 pw.println(dateString + ": " + msg); 3864 pw.close(); 3865 FileUtils.setPermissions( 3866 fname.toString(), 3867 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 3868 -1, -1); 3869 } catch (java.io.IOException e) { 3870 } 3871 Slog.println(priority, TAG, msg); 3872 } 3873 3874 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 3875 PackageParser.Package pkg, File srcFile, int parseFlags) { 3876 if (ps != null 3877 && ps.codePath.equals(srcFile) 3878 && ps.timeStamp == srcFile.lastModified() 3879 && !isCompatSignatureUpdateNeeded(pkg)) { 3880 if (ps.signatures.mSignatures != null 3881 && ps.signatures.mSignatures.length != 0) { 3882 // Optimization: reuse the existing cached certificates 3883 // if the package appears to be unchanged. 3884 pkg.mSignatures = ps.signatures.mSignatures; 3885 return true; 3886 } 3887 3888 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 3889 } else { 3890 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 3891 } 3892 3893 if (!pp.collectCertificates(pkg, parseFlags)) { 3894 mLastScanError = pp.getParseError(); 3895 return false; 3896 } 3897 return true; 3898 } 3899 3900 /* 3901 * Scan a package and return the newly parsed package. 3902 * Returns null in case of errors and the error code is stored in mLastScanError 3903 */ 3904 private PackageParser.Package scanPackageLI(File scanFile, 3905 int parseFlags, int scanMode, long currentTime, UserHandle user) { 3906 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 3907 String scanPath = scanFile.getPath(); 3908 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath); 3909 parseFlags |= mDefParseFlags; 3910 PackageParser pp = new PackageParser(scanPath); 3911 pp.setSeparateProcesses(mSeparateProcesses); 3912 pp.setOnlyCoreApps(mOnlyCore); 3913 final PackageParser.Package pkg = pp.parsePackage(scanFile, 3914 scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0); 3915 3916 if (pkg == null) { 3917 mLastScanError = pp.getParseError(); 3918 return null; 3919 } 3920 3921 PackageSetting ps = null; 3922 PackageSetting updatedPkg; 3923 // reader 3924 synchronized (mPackages) { 3925 // Look to see if we already know about this package. 3926 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 3927 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 3928 // This package has been renamed to its original name. Let's 3929 // use that. 3930 ps = mSettings.peekPackageLPr(oldName); 3931 } 3932 // If there was no original package, see one for the real package name. 3933 if (ps == null) { 3934 ps = mSettings.peekPackageLPr(pkg.packageName); 3935 } 3936 // Check to see if this package could be hiding/updating a system 3937 // package. Must look for it either under the original or real 3938 // package name depending on our state. 3939 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 3940 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 3941 } 3942 boolean updatedPkgBetter = false; 3943 // First check if this is a system package that may involve an update 3944 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 3945 if (ps != null && !ps.codePath.equals(scanFile)) { 3946 // The path has changed from what was last scanned... check the 3947 // version of the new path against what we have stored to determine 3948 // what to do. 3949 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 3950 if (pkg.mVersionCode < ps.versionCode) { 3951 // The system package has been updated and the code path does not match 3952 // Ignore entry. Skip it. 3953 Log.i(TAG, "Package " + ps.name + " at " + scanFile 3954 + " ignored: updated version " + ps.versionCode 3955 + " better than this " + pkg.mVersionCode); 3956 if (!updatedPkg.codePath.equals(scanFile)) { 3957 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 3958 + ps.name + " changing from " + updatedPkg.codePathString 3959 + " to " + scanFile); 3960 updatedPkg.codePath = scanFile; 3961 updatedPkg.codePathString = scanFile.toString(); 3962 // This is the point at which we know that the system-disk APK 3963 // for this package has moved during a reboot (e.g. due to an OTA), 3964 // so we need to reevaluate it for privilege policy. 3965 if (locationIsPrivileged(scanFile)) { 3966 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 3967 } 3968 } 3969 updatedPkg.pkg = pkg; 3970 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 3971 return null; 3972 } else { 3973 // The current app on the system partion is better than 3974 // what we have updated to on the data partition; switch 3975 // back to the system partition version. 3976 // At this point, its safely assumed that package installation for 3977 // apps in system partition will go through. If not there won't be a working 3978 // version of the app 3979 // writer 3980 synchronized (mPackages) { 3981 // Just remove the loaded entries from package lists. 3982 mPackages.remove(ps.name); 3983 } 3984 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 3985 + "reverting from " + ps.codePathString 3986 + ": new version " + pkg.mVersionCode 3987 + " better than installed " + ps.versionCode); 3988 3989 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 3990 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 3991 getAppInstructionSetFromSettings(ps)); 3992 synchronized (mInstallLock) { 3993 args.cleanUpResourcesLI(); 3994 } 3995 synchronized (mPackages) { 3996 mSettings.enableSystemPackageLPw(ps.name); 3997 } 3998 updatedPkgBetter = true; 3999 } 4000 } 4001 } 4002 4003 if (updatedPkg != null) { 4004 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4005 // initially 4006 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4007 4008 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4009 // flag set initially 4010 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4011 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4012 } 4013 } 4014 // Verify certificates against what was last scanned 4015 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 4016 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 4017 return null; 4018 } 4019 4020 /* 4021 * A new system app appeared, but we already had a non-system one of the 4022 * same name installed earlier. 4023 */ 4024 boolean shouldHideSystemApp = false; 4025 if (updatedPkg == null && ps != null 4026 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4027 /* 4028 * Check to make sure the signatures match first. If they don't, 4029 * wipe the installed application and its data. 4030 */ 4031 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4032 != PackageManager.SIGNATURE_MATCH) { 4033 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4034 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4035 ps = null; 4036 } else { 4037 /* 4038 * If the newly-added system app is an older version than the 4039 * already installed version, hide it. It will be scanned later 4040 * and re-added like an update. 4041 */ 4042 if (pkg.mVersionCode < ps.versionCode) { 4043 shouldHideSystemApp = true; 4044 } else { 4045 /* 4046 * The newly found system app is a newer version that the 4047 * one previously installed. Simply remove the 4048 * already-installed application and replace it with our own 4049 * while keeping the application data. 4050 */ 4051 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4052 + ps.codePathString + ": new version " + pkg.mVersionCode 4053 + " better than installed " + ps.versionCode); 4054 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4055 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4056 getAppInstructionSetFromSettings(ps)); 4057 synchronized (mInstallLock) { 4058 args.cleanUpResourcesLI(); 4059 } 4060 } 4061 } 4062 } 4063 4064 // The apk is forward locked (not public) if its code and resources 4065 // are kept in different files. (except for app in either system or 4066 // vendor path). 4067 // TODO grab this value from PackageSettings 4068 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4069 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4070 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4071 } 4072 } 4073 4074 String codePath = null; 4075 String resPath = null; 4076 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4077 if (ps != null && ps.resourcePathString != null) { 4078 resPath = ps.resourcePathString; 4079 } else { 4080 // Should not happen at all. Just log an error. 4081 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4082 } 4083 } else { 4084 resPath = pkg.mScanPath; 4085 } 4086 4087 codePath = pkg.mScanPath; 4088 // Set application objects path explicitly. 4089 setApplicationInfoPaths(pkg, codePath, resPath); 4090 // Note that we invoke the following method only if we are about to unpack an application 4091 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4092 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4093 4094 /* 4095 * If the system app should be overridden by a previously installed 4096 * data, hide the system app now and let the /data/app scan pick it up 4097 * again. 4098 */ 4099 if (shouldHideSystemApp) { 4100 synchronized (mPackages) { 4101 /* 4102 * We have to grant systems permissions before we hide, because 4103 * grantPermissions will assume the package update is trying to 4104 * expand its permissions. 4105 */ 4106 grantPermissionsLPw(pkg, true); 4107 mSettings.disableSystemPackageLPw(pkg.packageName); 4108 } 4109 } 4110 4111 return scannedPkg; 4112 } 4113 4114 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath, 4115 String destResPath) { 4116 pkg.mPath = pkg.mScanPath = destCodePath; 4117 pkg.applicationInfo.sourceDir = destCodePath; 4118 pkg.applicationInfo.publicSourceDir = destResPath; 4119 } 4120 4121 private static String fixProcessName(String defProcessName, 4122 String processName, int uid) { 4123 if (processName == null) { 4124 return defProcessName; 4125 } 4126 return processName; 4127 } 4128 4129 private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) { 4130 if (pkgSetting.signatures.mSignatures != null) { 4131 // Already existing package. Make sure signatures match 4132 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4133 == PackageManager.SIGNATURE_MATCH; 4134 if (!match) { 4135 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4136 == PackageManager.SIGNATURE_MATCH; 4137 } 4138 if (!match) { 4139 Slog.e(TAG, "Package " + pkg.packageName 4140 + " signatures do not match the previously installed version; ignoring!"); 4141 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4142 return false; 4143 } 4144 } 4145 // Check for shared user signatures 4146 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4147 // Already existing package. Make sure signatures match 4148 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4149 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4150 if (!match) { 4151 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4152 == PackageManager.SIGNATURE_MATCH; 4153 } 4154 if (!match) { 4155 Slog.e(TAG, "Package " + pkg.packageName 4156 + " has no signatures that match those in shared user " 4157 + pkgSetting.sharedUser.name + "; ignoring!"); 4158 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4159 return false; 4160 } 4161 } 4162 return true; 4163 } 4164 4165 /** 4166 * Enforces that only the system UID or root's UID can call a method exposed 4167 * via Binder. 4168 * 4169 * @param message used as message if SecurityException is thrown 4170 * @throws SecurityException if the caller is not system or root 4171 */ 4172 private static final void enforceSystemOrRoot(String message) { 4173 final int uid = Binder.getCallingUid(); 4174 if (uid != Process.SYSTEM_UID && uid != 0) { 4175 throw new SecurityException(message); 4176 } 4177 } 4178 4179 @Override 4180 public void performBootDexOpt() { 4181 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4182 4183 final HashSet<PackageParser.Package> pkgs; 4184 synchronized (mPackages) { 4185 pkgs = mDeferredDexOpt; 4186 mDeferredDexOpt = null; 4187 } 4188 4189 if (pkgs != null) { 4190 int i = 0; 4191 for (PackageParser.Package pkg : pkgs) { 4192 if (!isFirstBoot()) { 4193 i++; 4194 try { 4195 ActivityManagerNative.getDefault().showBootMessage( 4196 mContext.getResources().getString( 4197 com.android.internal.R.string.android_upgrading_apk, 4198 i, pkgs.size()), true); 4199 } catch (RemoteException e) { 4200 } 4201 } 4202 PackageParser.Package p = pkg; 4203 synchronized (mInstallLock) { 4204 if (!p.mDidDexOpt) { 4205 performDexOptLI(p, false /* force dex */, false /* defer */, 4206 true /* include dependencies */); 4207 } 4208 } 4209 } 4210 } 4211 } 4212 4213 @Override 4214 public boolean performDexOpt(String packageName) { 4215 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4216 if (!mNoDexOpt) { 4217 return false; 4218 } 4219 4220 PackageParser.Package p; 4221 synchronized (mPackages) { 4222 p = mPackages.get(packageName); 4223 if (p == null || p.mDidDexOpt) { 4224 return false; 4225 } 4226 } 4227 synchronized (mInstallLock) { 4228 return performDexOptLI(p, false /* force dex */, false /* defer */, 4229 true /* include dependencies */) == DEX_OPT_PERFORMED; 4230 } 4231 } 4232 4233 private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, boolean forceDex, 4234 boolean defer, HashSet<String> done) { 4235 for (int i=0; i<libs.size(); i++) { 4236 PackageParser.Package libPkg; 4237 String libName; 4238 synchronized (mPackages) { 4239 libName = libs.get(i); 4240 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4241 if (lib != null && lib.apk != null) { 4242 libPkg = mPackages.get(lib.apk); 4243 } else { 4244 libPkg = null; 4245 } 4246 } 4247 if (libPkg != null && !done.contains(libName)) { 4248 performDexOptLI(libPkg, instructionSet, forceDex, defer, done); 4249 } 4250 } 4251 } 4252 4253 static final int DEX_OPT_SKIPPED = 0; 4254 static final int DEX_OPT_PERFORMED = 1; 4255 static final int DEX_OPT_DEFERRED = 2; 4256 static final int DEX_OPT_FAILED = -1; 4257 4258 private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride, 4259 boolean forceDex, 4260 boolean defer, HashSet<String> done) { 4261 final String instructionSet = instructionSetOverride != null ? 4262 instructionSetOverride : getAppInstructionSet(pkg.applicationInfo); 4263 4264 if (done != null) { 4265 done.add(pkg.packageName); 4266 if (pkg.usesLibraries != null) { 4267 performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done); 4268 } 4269 if (pkg.usesOptionalLibraries != null) { 4270 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done); 4271 } 4272 } 4273 4274 boolean performed = false; 4275 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 4276 String path = pkg.mScanPath; 4277 int ret = 0; 4278 try { 4279 if (forceDex || dalvik.system.DexFile.isDexOptNeededInternal(path, 4280 pkg.packageName, instructionSet, defer)) { 4281 if (!forceDex && defer) { 4282 if (mDeferredDexOpt == null) { 4283 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4284 } 4285 mDeferredDexOpt.add(pkg); 4286 return DEX_OPT_DEFERRED; 4287 } else { 4288 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName + 4289 " (instructionSet=" + instructionSet + ")"); 4290 4291 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4292 ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4293 pkg.packageName, instructionSet); 4294 pkg.mDidDexOpt = true; 4295 performed = true; 4296 } 4297 } 4298 } catch (FileNotFoundException e) { 4299 Slog.w(TAG, "Apk not found for dexopt: " + path); 4300 ret = -1; 4301 } catch (IOException e) { 4302 Slog.w(TAG, "IOException reading apk: " + path, e); 4303 ret = -1; 4304 } catch (dalvik.system.StaleDexCacheError e) { 4305 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4306 ret = -1; 4307 } catch (Exception e) { 4308 Slog.w(TAG, "Exception when doing dexopt : ", e); 4309 ret = -1; 4310 } 4311 if (ret < 0) { 4312 //error from installer 4313 return DEX_OPT_FAILED; 4314 } 4315 } 4316 4317 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4318 } 4319 4320 private String getAppInstructionSet(ApplicationInfo info) { 4321 String instructionSet = getPreferredInstructionSet(); 4322 4323 if (info.requiredCpuAbi != null) { 4324 instructionSet = VMRuntime.getInstructionSet(info.requiredCpuAbi); 4325 } 4326 4327 return instructionSet; 4328 } 4329 4330 private String getAppInstructionSetFromSettings(PackageSetting ps) { 4331 String instructionSet = getPreferredInstructionSet(); 4332 4333 if (ps.requiredCpuAbiString != null) { 4334 instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString); 4335 } 4336 4337 return instructionSet; 4338 } 4339 4340 private static String getPreferredInstructionSet() { 4341 if (sPreferredInstructionSet == null) { 4342 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4343 } 4344 4345 return sPreferredInstructionSet; 4346 } 4347 4348 private static List<String> getAllInstructionSets() { 4349 final String[] allAbis = Build.SUPPORTED_ABIS; 4350 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4351 4352 for (String abi : allAbis) { 4353 final String instructionSet = VMRuntime.getInstructionSet(abi); 4354 if (!allInstructionSets.contains(instructionSet)) { 4355 allInstructionSets.add(instructionSet); 4356 } 4357 } 4358 4359 return allInstructionSets; 4360 } 4361 4362 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4363 boolean inclDependencies) { 4364 HashSet<String> done; 4365 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4366 done = new HashSet<String>(); 4367 done.add(pkg.packageName); 4368 } else { 4369 done = null; 4370 } 4371 return performDexOptLI(pkg, null /* instruction set override */, forceDex, defer, done); 4372 } 4373 4374 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4375 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4376 Slog.w(TAG, "Unable to update from " + oldPkg.name 4377 + " to " + newPkg.packageName 4378 + ": old package not in system partition"); 4379 return false; 4380 } else if (mPackages.get(oldPkg.name) != null) { 4381 Slog.w(TAG, "Unable to update from " + oldPkg.name 4382 + " to " + newPkg.packageName 4383 + ": old package still exists"); 4384 return false; 4385 } 4386 return true; 4387 } 4388 4389 File getDataPathForUser(int userId) { 4390 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4391 } 4392 4393 private File getDataPathForPackage(String packageName, int userId) { 4394 /* 4395 * Until we fully support multiple users, return the directory we 4396 * previously would have. The PackageManagerTests will need to be 4397 * revised when this is changed back.. 4398 */ 4399 if (userId == 0) { 4400 return new File(mAppDataDir, packageName); 4401 } else { 4402 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4403 + File.separator + packageName); 4404 } 4405 } 4406 4407 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4408 int[] users = sUserManager.getUserIds(); 4409 int res = mInstaller.install(packageName, uid, uid, seinfo); 4410 if (res < 0) { 4411 return res; 4412 } 4413 for (int user : users) { 4414 if (user != 0) { 4415 res = mInstaller.createUserData(packageName, 4416 UserHandle.getUid(user, uid), user, seinfo); 4417 if (res < 0) { 4418 return res; 4419 } 4420 } 4421 } 4422 return res; 4423 } 4424 4425 private int removeDataDirsLI(String packageName) { 4426 int[] users = sUserManager.getUserIds(); 4427 int res = 0; 4428 for (int user : users) { 4429 int resInner = mInstaller.remove(packageName, user); 4430 if (resInner < 0) { 4431 res = resInner; 4432 } 4433 } 4434 4435 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4436 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4437 if (!nativeLibraryFile.delete()) { 4438 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4439 } 4440 4441 return res; 4442 } 4443 4444 private int addSharedLibraryLPw(final SharedLibraryEntry file, int num, 4445 PackageParser.Package changingLib) { 4446 if (file.path != null) { 4447 mTmpSharedLibraries[num] = file.path; 4448 return num+1; 4449 } 4450 PackageParser.Package p = mPackages.get(file.apk); 4451 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4452 // If we are doing this while in the middle of updating a library apk, 4453 // then we need to make sure to use that new apk for determining the 4454 // dependencies here. (We haven't yet finished committing the new apk 4455 // to the package manager state.) 4456 if (p == null || p.packageName.equals(changingLib.packageName)) { 4457 p = changingLib; 4458 } 4459 } 4460 if (p != null) { 4461 String path = p.mPath; 4462 for (int i=0; i<num; i++) { 4463 if (mTmpSharedLibraries[i].equals(path)) { 4464 return num; 4465 } 4466 } 4467 mTmpSharedLibraries[num] = p.mPath; 4468 return num+1; 4469 } 4470 return num; 4471 } 4472 4473 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4474 PackageParser.Package changingLib) { 4475 // We might be upgrading from a version of the platform that did not 4476 // provide per-package native library directories for system apps. 4477 // Fix that up here. 4478 if (isSystemApp(pkg)) { 4479 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4480 setInternalAppNativeLibraryPath(pkg, ps); 4481 } 4482 4483 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4484 if (mTmpSharedLibraries == null || 4485 mTmpSharedLibraries.length < mSharedLibraries.size()) { 4486 mTmpSharedLibraries = new String[mSharedLibraries.size()]; 4487 } 4488 int num = 0; 4489 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4490 for (int i=0; i<N; i++) { 4491 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4492 if (file == null) { 4493 Slog.e(TAG, "Package " + pkg.packageName 4494 + " requires unavailable shared library " 4495 + pkg.usesLibraries.get(i) + "; failing!"); 4496 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4497 return false; 4498 } 4499 num = addSharedLibraryLPw(file, num, changingLib); 4500 } 4501 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4502 for (int i=0; i<N; i++) { 4503 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4504 if (file == null) { 4505 Slog.w(TAG, "Package " + pkg.packageName 4506 + " desires unavailable shared library " 4507 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4508 } else { 4509 num = addSharedLibraryLPw(file, num, changingLib); 4510 } 4511 } 4512 if (num > 0) { 4513 pkg.usesLibraryFiles = new String[num]; 4514 System.arraycopy(mTmpSharedLibraries, 0, 4515 pkg.usesLibraryFiles, 0, num); 4516 } else { 4517 pkg.usesLibraryFiles = null; 4518 } 4519 } 4520 return true; 4521 } 4522 4523 private static boolean hasString(List<String> list, List<String> which) { 4524 if (list == null) { 4525 return false; 4526 } 4527 for (int i=list.size()-1; i>=0; i--) { 4528 for (int j=which.size()-1; j>=0; j--) { 4529 if (which.get(j).equals(list.get(i))) { 4530 return true; 4531 } 4532 } 4533 } 4534 return false; 4535 } 4536 4537 private void updateAllSharedLibrariesLPw() { 4538 for (PackageParser.Package pkg : mPackages.values()) { 4539 updateSharedLibrariesLPw(pkg, null); 4540 } 4541 } 4542 4543 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4544 PackageParser.Package changingPkg) { 4545 ArrayList<PackageParser.Package> res = null; 4546 for (PackageParser.Package pkg : mPackages.values()) { 4547 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4548 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4549 if (res == null) { 4550 res = new ArrayList<PackageParser.Package>(); 4551 } 4552 res.add(pkg); 4553 updateSharedLibrariesLPw(pkg, changingPkg); 4554 } 4555 } 4556 return res; 4557 } 4558 4559 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4560 int parseFlags, int scanMode, long currentTime, UserHandle user) { 4561 File scanFile = new File(pkg.mScanPath); 4562 if (scanFile == null || pkg.applicationInfo.sourceDir == null || 4563 pkg.applicationInfo.publicSourceDir == null) { 4564 // Bail out. The resource and code paths haven't been set. 4565 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4566 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4567 return null; 4568 } 4569 4570 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4571 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4572 } 4573 4574 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4575 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4576 } 4577 4578 if (mCustomResolverComponentName != null && 4579 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4580 setUpCustomResolverActivity(pkg); 4581 } 4582 4583 if (pkg.packageName.equals("android")) { 4584 synchronized (mPackages) { 4585 if (mAndroidApplication != null) { 4586 Slog.w(TAG, "*************************************************"); 4587 Slog.w(TAG, "Core android package being redefined. Skipping."); 4588 Slog.w(TAG, " file=" + scanFile); 4589 Slog.w(TAG, "*************************************************"); 4590 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4591 return null; 4592 } 4593 4594 // Set up information for our fall-back user intent resolution activity. 4595 mPlatformPackage = pkg; 4596 pkg.mVersionCode = mSdkVersion; 4597 mAndroidApplication = pkg.applicationInfo; 4598 4599 if (!mResolverReplaced) { 4600 mResolveActivity.applicationInfo = mAndroidApplication; 4601 mResolveActivity.name = ResolverActivity.class.getName(); 4602 mResolveActivity.packageName = mAndroidApplication.packageName; 4603 mResolveActivity.processName = "system:ui"; 4604 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4605 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4606 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert; 4607 mResolveActivity.exported = true; 4608 mResolveActivity.enabled = true; 4609 mResolveInfo.activityInfo = mResolveActivity; 4610 mResolveInfo.priority = 0; 4611 mResolveInfo.preferredOrder = 0; 4612 mResolveInfo.match = 0; 4613 mResolveComponentName = new ComponentName( 4614 mAndroidApplication.packageName, mResolveActivity.name); 4615 } 4616 } 4617 } 4618 4619 if (DEBUG_PACKAGE_SCANNING) { 4620 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4621 Log.d(TAG, "Scanning package " + pkg.packageName); 4622 } 4623 4624 if (mPackages.containsKey(pkg.packageName) 4625 || mSharedLibraries.containsKey(pkg.packageName)) { 4626 Slog.w(TAG, "Application package " + pkg.packageName 4627 + " already installed. Skipping duplicate."); 4628 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4629 return null; 4630 } 4631 4632 // Initialize package source and resource directories 4633 File destCodeFile = new File(pkg.applicationInfo.sourceDir); 4634 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir); 4635 4636 SharedUserSetting suid = null; 4637 PackageSetting pkgSetting = null; 4638 4639 if (!isSystemApp(pkg)) { 4640 // Only system apps can use these features. 4641 pkg.mOriginalPackages = null; 4642 pkg.mRealPackage = null; 4643 pkg.mAdoptPermissions = null; 4644 } 4645 4646 // writer 4647 synchronized (mPackages) { 4648 if (pkg.mSharedUserId != null) { 4649 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 4650 if (suid == null) { 4651 Slog.w(TAG, "Creating application package " + pkg.packageName 4652 + " for shared user failed"); 4653 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4654 return null; 4655 } 4656 if (DEBUG_PACKAGE_SCANNING) { 4657 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4658 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 4659 + "): packages=" + suid.packages); 4660 } 4661 } 4662 4663 // Check if we are renaming from an original package name. 4664 PackageSetting origPackage = null; 4665 String realName = null; 4666 if (pkg.mOriginalPackages != null) { 4667 // This package may need to be renamed to a previously 4668 // installed name. Let's check on that... 4669 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 4670 if (pkg.mOriginalPackages.contains(renamed)) { 4671 // This package had originally been installed as the 4672 // original name, and we have already taken care of 4673 // transitioning to the new one. Just update the new 4674 // one to continue using the old name. 4675 realName = pkg.mRealPackage; 4676 if (!pkg.packageName.equals(renamed)) { 4677 // Callers into this function may have already taken 4678 // care of renaming the package; only do it here if 4679 // it is not already done. 4680 pkg.setPackageName(renamed); 4681 } 4682 4683 } else { 4684 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 4685 if ((origPackage = mSettings.peekPackageLPr( 4686 pkg.mOriginalPackages.get(i))) != null) { 4687 // We do have the package already installed under its 4688 // original name... should we use it? 4689 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 4690 // New package is not compatible with original. 4691 origPackage = null; 4692 continue; 4693 } else if (origPackage.sharedUser != null) { 4694 // Make sure uid is compatible between packages. 4695 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 4696 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 4697 + " to " + pkg.packageName + ": old uid " 4698 + origPackage.sharedUser.name 4699 + " differs from " + pkg.mSharedUserId); 4700 origPackage = null; 4701 continue; 4702 } 4703 } else { 4704 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 4705 + pkg.packageName + " to old name " + origPackage.name); 4706 } 4707 break; 4708 } 4709 } 4710 } 4711 } 4712 4713 if (mTransferedPackages.contains(pkg.packageName)) { 4714 Slog.w(TAG, "Package " + pkg.packageName 4715 + " was transferred to another, but its .apk remains"); 4716 } 4717 4718 // Just create the setting, don't add it yet. For already existing packages 4719 // the PkgSetting exists already and doesn't have to be created. 4720 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 4721 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 4722 pkg.applicationInfo.requiredCpuAbi, 4723 pkg.applicationInfo.flags, user, false); 4724 if (pkgSetting == null) { 4725 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 4726 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4727 return null; 4728 } 4729 4730 if (pkgSetting.origPackage != null) { 4731 // If we are first transitioning from an original package, 4732 // fix up the new package's name now. We need to do this after 4733 // looking up the package under its new name, so getPackageLP 4734 // can take care of fiddling things correctly. 4735 pkg.setPackageName(origPackage.name); 4736 4737 // File a report about this. 4738 String msg = "New package " + pkgSetting.realName 4739 + " renamed to replace old package " + pkgSetting.name; 4740 reportSettingsProblem(Log.WARN, msg); 4741 4742 // Make a note of it. 4743 mTransferedPackages.add(origPackage.name); 4744 4745 // No longer need to retain this. 4746 pkgSetting.origPackage = null; 4747 } 4748 4749 if (realName != null) { 4750 // Make a note of it. 4751 mTransferedPackages.add(pkg.packageName); 4752 } 4753 4754 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 4755 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 4756 } 4757 4758 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4759 // Check all shared libraries and map to their actual file path. 4760 // We only do this here for apps not on a system dir, because those 4761 // are the only ones that can fail an install due to this. We 4762 // will take care of the system apps by updating all of their 4763 // library paths after the scan is done. 4764 if (!updateSharedLibrariesLPw(pkg, null)) { 4765 return null; 4766 } 4767 } 4768 4769 if (mFoundPolicyFile) { 4770 SELinuxMMAC.assignSeinfoValue(pkg); 4771 } 4772 4773 pkg.applicationInfo.uid = pkgSetting.appId; 4774 pkg.mExtras = pkgSetting; 4775 4776 if (!verifySignaturesLP(pkgSetting, pkg)) { 4777 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4778 return null; 4779 } 4780 // The signature has changed, but this package is in the system 4781 // image... let's recover! 4782 pkgSetting.signatures.mSignatures = pkg.mSignatures; 4783 // However... if this package is part of a shared user, but it 4784 // doesn't match the signature of the shared user, let's fail. 4785 // What this means is that you can't change the signatures 4786 // associated with an overall shared user, which doesn't seem all 4787 // that unreasonable. 4788 if (pkgSetting.sharedUser != null) { 4789 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4790 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 4791 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 4792 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 4793 return null; 4794 } 4795 } 4796 // File a report about this. 4797 String msg = "System package " + pkg.packageName 4798 + " signature changed; retaining data."; 4799 reportSettingsProblem(Log.WARN, msg); 4800 } 4801 4802 // Verify that this new package doesn't have any content providers 4803 // that conflict with existing packages. Only do this if the 4804 // package isn't already installed, since we don't want to break 4805 // things that are installed. 4806 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 4807 final int N = pkg.providers.size(); 4808 int i; 4809 for (i=0; i<N; i++) { 4810 PackageParser.Provider p = pkg.providers.get(i); 4811 if (p.info.authority != null) { 4812 String names[] = p.info.authority.split(";"); 4813 for (int j = 0; j < names.length; j++) { 4814 if (mProvidersByAuthority.containsKey(names[j])) { 4815 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 4816 Slog.w(TAG, "Can't install because provider name " + names[j] + 4817 " (in package " + pkg.applicationInfo.packageName + 4818 ") is already used by " 4819 + ((other != null && other.getComponentName() != null) 4820 ? other.getComponentName().getPackageName() : "?")); 4821 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 4822 return null; 4823 } 4824 } 4825 } 4826 } 4827 } 4828 4829 if (pkg.mAdoptPermissions != null) { 4830 // This package wants to adopt ownership of permissions from 4831 // another package. 4832 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 4833 final String origName = pkg.mAdoptPermissions.get(i); 4834 final PackageSetting orig = mSettings.peekPackageLPr(origName); 4835 if (orig != null) { 4836 if (verifyPackageUpdateLPr(orig, pkg)) { 4837 Slog.i(TAG, "Adopting permissions from " + origName + " to " 4838 + pkg.packageName); 4839 mSettings.transferPermissionsLPw(origName, pkg.packageName); 4840 } 4841 } 4842 } 4843 } 4844 } 4845 4846 final String pkgName = pkg.packageName; 4847 4848 final long scanFileTime = scanFile.lastModified(); 4849 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 4850 pkg.applicationInfo.processName = fixProcessName( 4851 pkg.applicationInfo.packageName, 4852 pkg.applicationInfo.processName, 4853 pkg.applicationInfo.uid); 4854 4855 File dataPath; 4856 if (mPlatformPackage == pkg) { 4857 // The system package is special. 4858 dataPath = new File (Environment.getDataDirectory(), "system"); 4859 pkg.applicationInfo.dataDir = dataPath.getPath(); 4860 } else { 4861 // This is a normal package, need to make its data directory. 4862 dataPath = getDataPathForPackage(pkg.packageName, 0); 4863 4864 boolean uidError = false; 4865 4866 if (dataPath.exists()) { 4867 int currentUid = 0; 4868 try { 4869 StructStat stat = Os.stat(dataPath.getPath()); 4870 currentUid = stat.st_uid; 4871 } catch (ErrnoException e) { 4872 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 4873 } 4874 4875 // If we have mismatched owners for the data path, we have a problem. 4876 if (currentUid != pkg.applicationInfo.uid) { 4877 boolean recovered = false; 4878 if (currentUid == 0) { 4879 // The directory somehow became owned by root. Wow. 4880 // This is probably because the system was stopped while 4881 // installd was in the middle of messing with its libs 4882 // directory. Ask installd to fix that. 4883 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 4884 pkg.applicationInfo.uid); 4885 if (ret >= 0) { 4886 recovered = true; 4887 String msg = "Package " + pkg.packageName 4888 + " unexpectedly changed to uid 0; recovered to " + 4889 + pkg.applicationInfo.uid; 4890 reportSettingsProblem(Log.WARN, msg); 4891 } 4892 } 4893 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 4894 || (scanMode&SCAN_BOOTING) != 0)) { 4895 // If this is a system app, we can at least delete its 4896 // current data so the application will still work. 4897 int ret = removeDataDirsLI(pkgName); 4898 if (ret >= 0) { 4899 // TODO: Kill the processes first 4900 // Old data gone! 4901 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 4902 ? "System package " : "Third party package "; 4903 String msg = prefix + pkg.packageName 4904 + " has changed from uid: " 4905 + currentUid + " to " 4906 + pkg.applicationInfo.uid + "; old data erased"; 4907 reportSettingsProblem(Log.WARN, msg); 4908 recovered = true; 4909 4910 // And now re-install the app. 4911 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 4912 pkg.applicationInfo.seinfo); 4913 if (ret == -1) { 4914 // Ack should not happen! 4915 msg = prefix + pkg.packageName 4916 + " could not have data directory re-created after delete."; 4917 reportSettingsProblem(Log.WARN, msg); 4918 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4919 return null; 4920 } 4921 } 4922 if (!recovered) { 4923 mHasSystemUidErrors = true; 4924 } 4925 } else if (!recovered) { 4926 // If we allow this install to proceed, we will be broken. 4927 // Abort, abort! 4928 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 4929 return null; 4930 } 4931 if (!recovered) { 4932 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 4933 + pkg.applicationInfo.uid + "/fs_" 4934 + currentUid; 4935 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 4936 String msg = "Package " + pkg.packageName 4937 + " has mismatched uid: " 4938 + currentUid + " on disk, " 4939 + pkg.applicationInfo.uid + " in settings"; 4940 // writer 4941 synchronized (mPackages) { 4942 mSettings.mReadMessages.append(msg); 4943 mSettings.mReadMessages.append('\n'); 4944 uidError = true; 4945 if (!pkgSetting.uidError) { 4946 reportSettingsProblem(Log.ERROR, msg); 4947 } 4948 } 4949 } 4950 } 4951 pkg.applicationInfo.dataDir = dataPath.getPath(); 4952 if (mShouldRestoreconData) { 4953 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 4954 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 4955 pkg.applicationInfo.uid); 4956 } 4957 } else { 4958 if (DEBUG_PACKAGE_SCANNING) { 4959 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4960 Log.v(TAG, "Want this data dir: " + dataPath); 4961 } 4962 //invoke installer to do the actual installation 4963 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 4964 pkg.applicationInfo.seinfo); 4965 if (ret < 0) { 4966 // Error from installer 4967 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4968 return null; 4969 } 4970 4971 if (dataPath.exists()) { 4972 pkg.applicationInfo.dataDir = dataPath.getPath(); 4973 } else { 4974 Slog.w(TAG, "Unable to create data directory: " + dataPath); 4975 pkg.applicationInfo.dataDir = null; 4976 } 4977 } 4978 4979 /* 4980 * Set the data dir to the default "/data/data/<package name>/lib" 4981 * if we got here without anyone telling us different (e.g., apps 4982 * stored on SD card have their native libraries stored in the ASEC 4983 * container with the APK). 4984 * 4985 * This happens during an upgrade from a package settings file that 4986 * doesn't have a native library path attribute at all. 4987 */ 4988 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 4989 if (pkgSetting.nativeLibraryPathString == null) { 4990 setInternalAppNativeLibraryPath(pkg, pkgSetting); 4991 } else { 4992 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 4993 } 4994 } 4995 pkgSetting.uidError = uidError; 4996 } 4997 4998 String path = scanFile.getPath(); 4999 /* Note: We don't want to unpack the native binaries for 5000 * system applications, unless they have been updated 5001 * (the binaries are already under /system/lib). 5002 * Also, don't unpack libs for apps on the external card 5003 * since they should have their libraries in the ASEC 5004 * container already. 5005 * 5006 * In other words, we're going to unpack the binaries 5007 * only for non-system apps and system app upgrades. 5008 */ 5009 if (pkg.applicationInfo.nativeLibraryDir != null) { 5010 try { 5011 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5012 final String dataPathString = dataPath.getCanonicalPath(); 5013 5014 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5015 /* 5016 * Upgrading from a previous version of the OS sometimes 5017 * leaves native libraries in the /data/data/<app>/lib 5018 * directory for system apps even when they shouldn't be. 5019 * Recent changes in the JNI library search path 5020 * necessitates we remove those to match previous behavior. 5021 */ 5022 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 5023 Log.i(TAG, "removed obsolete native libraries for system package " 5024 + path); 5025 } 5026 5027 setInternalAppAbi(pkg, pkgSetting); 5028 } else { 5029 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 5030 /* 5031 * Update native library dir if it starts with 5032 * /data/data 5033 */ 5034 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 5035 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5036 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5037 } 5038 5039 try { 5040 int copyRet = copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir); 5041 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5042 Slog.e(TAG, "Unable to copy native libraries"); 5043 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5044 return null; 5045 } 5046 5047 // We've successfully copied native libraries across, so we make a 5048 // note of what ABI we're using 5049 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5050 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[copyRet]; 5051 } else { 5052 pkg.applicationInfo.requiredCpuAbi = null; 5053 } 5054 } catch (IOException e) { 5055 Slog.e(TAG, "Unable to copy native libraries", e); 5056 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5057 return null; 5058 } 5059 } else { 5060 // We don't have to copy the shared libraries if we're in the ASEC container 5061 // but we still need to scan the file to figure out what ABI the app needs. 5062 // 5063 // TODO: This duplicates work done in the default container service. It's possible 5064 // to clean this up but we'll need to change the interface between this service 5065 // and IMediaContainerService (but doing so will spread this logic out, rather 5066 // than centralizing it). 5067 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile); 5068 final int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS); 5069 if (abi >= 0) { 5070 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[abi]; 5071 } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) { 5072 // Note that (non upgraded) system apps will not have any native 5073 // libraries bundled in their APK, but we're guaranteed not to be 5074 // such an app at this point. 5075 pkg.applicationInfo.requiredCpuAbi = null; 5076 } else { 5077 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5078 return null; 5079 } 5080 handle.close(); 5081 } 5082 5083 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5084 final int[] userIds = sUserManager.getUserIds(); 5085 synchronized (mInstallLock) { 5086 for (int userId : userIds) { 5087 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 5088 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 5089 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5090 + ")"); 5091 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5092 return null; 5093 } 5094 } 5095 } 5096 } 5097 } catch (IOException ioe) { 5098 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5099 } 5100 } 5101 pkg.mScanPath = path; 5102 5103 if ((scanMode&SCAN_NO_DEX) == 0) { 5104 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5105 == DEX_OPT_FAILED) { 5106 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5107 removeDataDirsLI(pkg.packageName); 5108 } 5109 5110 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5111 return null; 5112 } 5113 } 5114 5115 if (mFactoryTest && pkg.requestedPermissions.contains( 5116 android.Manifest.permission.FACTORY_TEST)) { 5117 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5118 } 5119 5120 ArrayList<PackageParser.Package> clientLibPkgs = null; 5121 5122 // writer 5123 synchronized (mPackages) { 5124 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5125 // Only system apps can add new shared libraries. 5126 if (pkg.libraryNames != null) { 5127 for (int i=0; i<pkg.libraryNames.size(); i++) { 5128 String name = pkg.libraryNames.get(i); 5129 boolean allowed = false; 5130 if (isUpdatedSystemApp(pkg)) { 5131 // New library entries can only be added through the 5132 // system image. This is important to get rid of a lot 5133 // of nasty edge cases: for example if we allowed a non- 5134 // system update of the app to add a library, then uninstalling 5135 // the update would make the library go away, and assumptions 5136 // we made such as through app install filtering would now 5137 // have allowed apps on the device which aren't compatible 5138 // with it. Better to just have the restriction here, be 5139 // conservative, and create many fewer cases that can negatively 5140 // impact the user experience. 5141 final PackageSetting sysPs = mSettings 5142 .getDisabledSystemPkgLPr(pkg.packageName); 5143 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5144 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5145 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5146 allowed = true; 5147 allowed = true; 5148 break; 5149 } 5150 } 5151 } 5152 } else { 5153 allowed = true; 5154 } 5155 if (allowed) { 5156 if (!mSharedLibraries.containsKey(name)) { 5157 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5158 } else if (!name.equals(pkg.packageName)) { 5159 Slog.w(TAG, "Package " + pkg.packageName + " library " 5160 + name + " already exists; skipping"); 5161 } 5162 } else { 5163 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5164 + name + " that is not declared on system image; skipping"); 5165 } 5166 } 5167 if ((scanMode&SCAN_BOOTING) == 0) { 5168 // If we are not booting, we need to update any applications 5169 // that are clients of our shared library. If we are booting, 5170 // this will all be done once the scan is complete. 5171 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5172 } 5173 } 5174 } 5175 } 5176 5177 // We also need to dexopt any apps that are dependent on this library. Note that 5178 // if these fail, we should abort the install since installing the library will 5179 // result in some apps being broken. 5180 if (clientLibPkgs != null) { 5181 if ((scanMode&SCAN_NO_DEX) == 0) { 5182 for (int i=0; i<clientLibPkgs.size(); i++) { 5183 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5184 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5185 == DEX_OPT_FAILED) { 5186 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5187 removeDataDirsLI(pkg.packageName); 5188 } 5189 5190 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5191 return null; 5192 } 5193 } 5194 } 5195 } 5196 5197 // Request the ActivityManager to kill the process(only for existing packages) 5198 // so that we do not end up in a confused state while the user is still using the older 5199 // version of the application while the new one gets installed. 5200 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5201 // If the package lives in an asec, tell everyone that the container is going 5202 // away so they can clean up any references to its resources (which would prevent 5203 // vold from being able to unmount the asec) 5204 if (isForwardLocked(pkg) || isExternal(pkg)) { 5205 if (DEBUG_INSTALL) { 5206 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5207 } 5208 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5209 final ArrayList<String> pkgList = new ArrayList<String>(1); 5210 pkgList.add(pkg.applicationInfo.packageName); 5211 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5212 } 5213 5214 // Post the request that it be killed now that the going-away broadcast is en route 5215 killApplication(pkg.applicationInfo.packageName, 5216 pkg.applicationInfo.uid, "update pkg"); 5217 } 5218 5219 // Also need to kill any apps that are dependent on the library. 5220 if (clientLibPkgs != null) { 5221 for (int i=0; i<clientLibPkgs.size(); i++) { 5222 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5223 killApplication(clientPkg.applicationInfo.packageName, 5224 clientPkg.applicationInfo.uid, "update lib"); 5225 } 5226 } 5227 5228 // writer 5229 synchronized (mPackages) { 5230 // We don't expect installation to fail beyond this point, 5231 if ((scanMode&SCAN_MONITOR) != 0) { 5232 mAppDirs.put(pkg.mPath, pkg); 5233 } 5234 // Add the new setting to mSettings 5235 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5236 // Add the new setting to mPackages 5237 mPackages.put(pkg.applicationInfo.packageName, pkg); 5238 // Make sure we don't accidentally delete its data. 5239 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5240 while (iter.hasNext()) { 5241 PackageCleanItem item = iter.next(); 5242 if (pkgName.equals(item.packageName)) { 5243 iter.remove(); 5244 } 5245 } 5246 5247 // Take care of first install / last update times. 5248 if (currentTime != 0) { 5249 if (pkgSetting.firstInstallTime == 0) { 5250 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5251 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5252 pkgSetting.lastUpdateTime = currentTime; 5253 } 5254 } else if (pkgSetting.firstInstallTime == 0) { 5255 // We need *something*. Take time time stamp of the file. 5256 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5257 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5258 if (scanFileTime != pkgSetting.timeStamp) { 5259 // A package on the system image has changed; consider this 5260 // to be an update. 5261 pkgSetting.lastUpdateTime = scanFileTime; 5262 } 5263 } 5264 5265 // Add the package's KeySets to the global KeySetManager 5266 KeySetManager ksm = mSettings.mKeySetManager; 5267 try { 5268 ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5269 if (pkg.mKeySetMapping != null) { 5270 for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) { 5271 if (entry.getValue() != null) { 5272 ksm.addDefinedKeySetToPackage(pkg.packageName, 5273 entry.getValue(), entry.getKey()); 5274 } 5275 } 5276 } 5277 } catch (NullPointerException e) { 5278 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5279 } catch (IllegalArgumentException e) { 5280 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5281 } 5282 5283 int N = pkg.providers.size(); 5284 StringBuilder r = null; 5285 int i; 5286 for (i=0; i<N; i++) { 5287 PackageParser.Provider p = pkg.providers.get(i); 5288 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5289 p.info.processName, pkg.applicationInfo.uid); 5290 mProviders.addProvider(p); 5291 p.syncable = p.info.isSyncable; 5292 if (p.info.authority != null) { 5293 String names[] = p.info.authority.split(";"); 5294 p.info.authority = null; 5295 for (int j = 0; j < names.length; j++) { 5296 if (j == 1 && p.syncable) { 5297 // We only want the first authority for a provider to possibly be 5298 // syncable, so if we already added this provider using a different 5299 // authority clear the syncable flag. We copy the provider before 5300 // changing it because the mProviders object contains a reference 5301 // to a provider that we don't want to change. 5302 // Only do this for the second authority since the resulting provider 5303 // object can be the same for all future authorities for this provider. 5304 p = new PackageParser.Provider(p); 5305 p.syncable = false; 5306 } 5307 if (!mProvidersByAuthority.containsKey(names[j])) { 5308 mProvidersByAuthority.put(names[j], p); 5309 if (p.info.authority == null) { 5310 p.info.authority = names[j]; 5311 } else { 5312 p.info.authority = p.info.authority + ";" + names[j]; 5313 } 5314 if (DEBUG_PACKAGE_SCANNING) { 5315 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5316 Log.d(TAG, "Registered content provider: " + names[j] 5317 + ", className = " + p.info.name + ", isSyncable = " 5318 + p.info.isSyncable); 5319 } 5320 } else { 5321 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5322 Slog.w(TAG, "Skipping provider name " + names[j] + 5323 " (in package " + pkg.applicationInfo.packageName + 5324 "): name already used by " 5325 + ((other != null && other.getComponentName() != null) 5326 ? other.getComponentName().getPackageName() : "?")); 5327 } 5328 } 5329 } 5330 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5331 if (r == null) { 5332 r = new StringBuilder(256); 5333 } else { 5334 r.append(' '); 5335 } 5336 r.append(p.info.name); 5337 } 5338 } 5339 if (r != null) { 5340 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5341 } 5342 5343 N = pkg.services.size(); 5344 r = null; 5345 for (i=0; i<N; i++) { 5346 PackageParser.Service s = pkg.services.get(i); 5347 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5348 s.info.processName, pkg.applicationInfo.uid); 5349 mServices.addService(s); 5350 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5351 if (r == null) { 5352 r = new StringBuilder(256); 5353 } else { 5354 r.append(' '); 5355 } 5356 r.append(s.info.name); 5357 } 5358 } 5359 if (r != null) { 5360 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5361 } 5362 5363 N = pkg.receivers.size(); 5364 r = null; 5365 for (i=0; i<N; i++) { 5366 PackageParser.Activity a = pkg.receivers.get(i); 5367 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5368 a.info.processName, pkg.applicationInfo.uid); 5369 mReceivers.addActivity(a, "receiver"); 5370 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5371 if (r == null) { 5372 r = new StringBuilder(256); 5373 } else { 5374 r.append(' '); 5375 } 5376 r.append(a.info.name); 5377 } 5378 } 5379 if (r != null) { 5380 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5381 } 5382 5383 N = pkg.activities.size(); 5384 r = null; 5385 for (i=0; i<N; i++) { 5386 PackageParser.Activity a = pkg.activities.get(i); 5387 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5388 a.info.processName, pkg.applicationInfo.uid); 5389 mActivities.addActivity(a, "activity"); 5390 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5391 if (r == null) { 5392 r = new StringBuilder(256); 5393 } else { 5394 r.append(' '); 5395 } 5396 r.append(a.info.name); 5397 } 5398 } 5399 if (r != null) { 5400 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5401 } 5402 5403 N = pkg.permissionGroups.size(); 5404 r = null; 5405 for (i=0; i<N; i++) { 5406 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5407 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5408 if (cur == null) { 5409 mPermissionGroups.put(pg.info.name, pg); 5410 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5411 if (r == null) { 5412 r = new StringBuilder(256); 5413 } else { 5414 r.append(' '); 5415 } 5416 r.append(pg.info.name); 5417 } 5418 } else { 5419 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5420 + pg.info.packageName + " ignored: original from " 5421 + cur.info.packageName); 5422 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5423 if (r == null) { 5424 r = new StringBuilder(256); 5425 } else { 5426 r.append(' '); 5427 } 5428 r.append("DUP:"); 5429 r.append(pg.info.name); 5430 } 5431 } 5432 } 5433 if (r != null) { 5434 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5435 } 5436 5437 N = pkg.permissions.size(); 5438 r = null; 5439 for (i=0; i<N; i++) { 5440 PackageParser.Permission p = pkg.permissions.get(i); 5441 HashMap<String, BasePermission> permissionMap = 5442 p.tree ? mSettings.mPermissionTrees 5443 : mSettings.mPermissions; 5444 p.group = mPermissionGroups.get(p.info.group); 5445 if (p.info.group == null || p.group != null) { 5446 BasePermission bp = permissionMap.get(p.info.name); 5447 if (bp == null) { 5448 bp = new BasePermission(p.info.name, p.info.packageName, 5449 BasePermission.TYPE_NORMAL); 5450 permissionMap.put(p.info.name, bp); 5451 } 5452 if (bp.perm == null) { 5453 if (bp.sourcePackage != null 5454 && !bp.sourcePackage.equals(p.info.packageName)) { 5455 // If this is a permission that was formerly defined by a non-system 5456 // app, but is now defined by a system app (following an upgrade), 5457 // discard the previous declaration and consider the system's to be 5458 // canonical. 5459 if (isSystemApp(p.owner)) { 5460 String msg = "New decl " + p.owner + " of permission " 5461 + p.info.name + " is system"; 5462 reportSettingsProblem(Log.WARN, msg); 5463 bp.sourcePackage = null; 5464 } 5465 } 5466 if (bp.sourcePackage == null 5467 || bp.sourcePackage.equals(p.info.packageName)) { 5468 BasePermission tree = findPermissionTreeLP(p.info.name); 5469 if (tree == null 5470 || tree.sourcePackage.equals(p.info.packageName)) { 5471 bp.packageSetting = pkgSetting; 5472 bp.perm = p; 5473 bp.uid = pkg.applicationInfo.uid; 5474 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5475 if (r == null) { 5476 r = new StringBuilder(256); 5477 } else { 5478 r.append(' '); 5479 } 5480 r.append(p.info.name); 5481 } 5482 } else { 5483 Slog.w(TAG, "Permission " + p.info.name + " from package " 5484 + p.info.packageName + " ignored: base tree " 5485 + tree.name + " is from package " 5486 + tree.sourcePackage); 5487 } 5488 } else { 5489 Slog.w(TAG, "Permission " + p.info.name + " from package " 5490 + p.info.packageName + " ignored: original from " 5491 + bp.sourcePackage); 5492 } 5493 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5494 if (r == null) { 5495 r = new StringBuilder(256); 5496 } else { 5497 r.append(' '); 5498 } 5499 r.append("DUP:"); 5500 r.append(p.info.name); 5501 } 5502 if (bp.perm == p) { 5503 bp.protectionLevel = p.info.protectionLevel; 5504 } 5505 } else { 5506 Slog.w(TAG, "Permission " + p.info.name + " from package " 5507 + p.info.packageName + " ignored: no group " 5508 + p.group); 5509 } 5510 } 5511 if (r != null) { 5512 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5513 } 5514 5515 N = pkg.instrumentation.size(); 5516 r = null; 5517 for (i=0; i<N; i++) { 5518 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5519 a.info.packageName = pkg.applicationInfo.packageName; 5520 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5521 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5522 a.info.dataDir = pkg.applicationInfo.dataDir; 5523 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5524 mInstrumentation.put(a.getComponentName(), a); 5525 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5526 if (r == null) { 5527 r = new StringBuilder(256); 5528 } else { 5529 r.append(' '); 5530 } 5531 r.append(a.info.name); 5532 } 5533 } 5534 if (r != null) { 5535 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5536 } 5537 5538 if (pkg.protectedBroadcasts != null) { 5539 N = pkg.protectedBroadcasts.size(); 5540 for (i=0; i<N; i++) { 5541 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5542 } 5543 } 5544 5545 pkgSetting.setTimeStamp(scanFileTime); 5546 5547 // Create idmap files for pairs of (packages, overlay packages). 5548 // Note: "android", ie framework-res.apk, is handled by native layers. 5549 if (pkg.mOverlayTarget != null) { 5550 // This is an overlay package. 5551 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 5552 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 5553 mOverlays.put(pkg.mOverlayTarget, 5554 new HashMap<String, PackageParser.Package>()); 5555 } 5556 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 5557 map.put(pkg.packageName, pkg); 5558 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 5559 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 5560 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5561 return null; 5562 } 5563 } 5564 } else if (mOverlays.containsKey(pkg.packageName) && 5565 !pkg.packageName.equals("android")) { 5566 // This is a regular package, with one or more known overlay packages. 5567 createIdmapsForPackageLI(pkg); 5568 } 5569 } 5570 5571 return pkg; 5572 } 5573 5574 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 5575 synchronized (mPackages) { 5576 mResolverReplaced = true; 5577 // Set up information for custom user intent resolution activity. 5578 mResolveActivity.applicationInfo = pkg.applicationInfo; 5579 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 5580 mResolveActivity.packageName = pkg.applicationInfo.packageName; 5581 mResolveActivity.processName = null; 5582 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5583 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 5584 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 5585 mResolveActivity.theme = 0; 5586 mResolveActivity.exported = true; 5587 mResolveActivity.enabled = true; 5588 mResolveInfo.activityInfo = mResolveActivity; 5589 mResolveInfo.priority = 0; 5590 mResolveInfo.preferredOrder = 0; 5591 mResolveInfo.match = 0; 5592 mResolveComponentName = mCustomResolverComponentName; 5593 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 5594 mResolveComponentName); 5595 } 5596 } 5597 5598 private String calculateApkRoot(final String codePathString) { 5599 final File codePath = new File(codePathString); 5600 final File codeRoot; 5601 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 5602 codeRoot = Environment.getRootDirectory(); 5603 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 5604 codeRoot = Environment.getOemDirectory(); 5605 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 5606 codeRoot = Environment.getVendorDirectory(); 5607 } else { 5608 // Unrecognized code path; take its top real segment as the apk root: 5609 // e.g. /something/app/blah.apk => /something 5610 try { 5611 File f = codePath.getCanonicalFile(); 5612 File parent = f.getParentFile(); // non-null because codePath is a file 5613 File tmp; 5614 while ((tmp = parent.getParentFile()) != null) { 5615 f = parent; 5616 parent = tmp; 5617 } 5618 codeRoot = f; 5619 Slog.w(TAG, "Unrecognized code path " 5620 + codePath + " - using " + codeRoot); 5621 } catch (IOException e) { 5622 // Can't canonicalize the lib path -- shenanigans? 5623 Slog.w(TAG, "Can't canonicalize code path " + codePath); 5624 return Environment.getRootDirectory().getPath(); 5625 } 5626 } 5627 return codeRoot.getPath(); 5628 } 5629 5630 // This is the initial scan-time determination of how to handle a given 5631 // package for purposes of native library location. 5632 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 5633 PackageSetting pkgSetting) { 5634 // "bundled" here means system-installed with no overriding update 5635 final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg); 5636 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 5637 final File libDir; 5638 if (bundledApk) { 5639 // If "/system/lib64/apkname" exists, assume that is the per-package 5640 // native library directory to use; otherwise use "/system/lib/apkname". 5641 String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 5642 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 5643 File packLib64 = new File(lib64, apkName); 5644 libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 5645 } else { 5646 libDir = mAppLibInstallDir; 5647 } 5648 final String nativeLibraryPath = (new File(libDir, apkName)).getPath(); 5649 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 5650 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 5651 } 5652 5653 // Deduces the required ABI of an upgraded system app. 5654 private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) { 5655 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 5656 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 5657 5658 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 5659 // or similar. 5660 final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath()); 5661 final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath()); 5662 5663 // Assume that the bundled native libraries always correspond to the 5664 // most preferred 32 or 64 bit ABI. 5665 if (lib64.exists()) { 5666 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 5667 pkgSetting.requiredCpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0]; 5668 } else if (lib.exists()) { 5669 pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5670 pkgSetting.requiredCpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0]; 5671 } else { 5672 // This is the case where the app has no native code. 5673 pkg.applicationInfo.requiredCpuAbi = null; 5674 pkgSetting.requiredCpuAbiString = null; 5675 } 5676 } 5677 5678 private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir) 5679 throws IOException { 5680 if (!nativeLibraryDir.isDirectory()) { 5681 nativeLibraryDir.delete(); 5682 5683 if (!nativeLibraryDir.mkdir()) { 5684 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 5685 } 5686 5687 try { 5688 Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 5689 } catch (ErrnoException e) { 5690 throw new IOException("Cannot chmod native library directory " 5691 + nativeLibraryDir.getPath(), e); 5692 } 5693 } else if (!SELinux.restorecon(nativeLibraryDir)) { 5694 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 5695 } 5696 5697 /* 5698 * If this is an internal application or our nativeLibraryPath points to 5699 * the app-lib directory, unpack the libraries if necessary. 5700 */ 5701 final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile); 5702 try { 5703 int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS); 5704 if (abi >= 0) { 5705 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 5706 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 5707 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 5708 return copyRet; 5709 } 5710 } 5711 5712 return abi; 5713 } finally { 5714 handle.close(); 5715 } 5716 } 5717 5718 private void killApplication(String pkgName, int appId, String reason) { 5719 // Request the ActivityManager to kill the process(only for existing packages) 5720 // so that we do not end up in a confused state while the user is still using the older 5721 // version of the application while the new one gets installed. 5722 IActivityManager am = ActivityManagerNative.getDefault(); 5723 if (am != null) { 5724 try { 5725 am.killApplicationWithAppId(pkgName, appId, reason); 5726 } catch (RemoteException e) { 5727 } 5728 } 5729 } 5730 5731 void removePackageLI(PackageSetting ps, boolean chatty) { 5732 if (DEBUG_INSTALL) { 5733 if (chatty) 5734 Log.d(TAG, "Removing package " + ps.name); 5735 } 5736 5737 // writer 5738 synchronized (mPackages) { 5739 mPackages.remove(ps.name); 5740 if (ps.codePathString != null) { 5741 mAppDirs.remove(ps.codePathString); 5742 } 5743 5744 final PackageParser.Package pkg = ps.pkg; 5745 if (pkg != null) { 5746 cleanPackageDataStructuresLILPw(pkg, chatty); 5747 } 5748 } 5749 } 5750 5751 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 5752 if (DEBUG_INSTALL) { 5753 if (chatty) 5754 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 5755 } 5756 5757 // writer 5758 synchronized (mPackages) { 5759 mPackages.remove(pkg.applicationInfo.packageName); 5760 if (pkg.mPath != null) { 5761 mAppDirs.remove(pkg.mPath); 5762 } 5763 cleanPackageDataStructuresLILPw(pkg, chatty); 5764 } 5765 } 5766 5767 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 5768 int N = pkg.providers.size(); 5769 StringBuilder r = null; 5770 int i; 5771 for (i=0; i<N; i++) { 5772 PackageParser.Provider p = pkg.providers.get(i); 5773 mProviders.removeProvider(p); 5774 if (p.info.authority == null) { 5775 5776 /* There was another ContentProvider with this authority when 5777 * this app was installed so this authority is null, 5778 * Ignore it as we don't have to unregister the provider. 5779 */ 5780 continue; 5781 } 5782 String names[] = p.info.authority.split(";"); 5783 for (int j = 0; j < names.length; j++) { 5784 if (mProvidersByAuthority.get(names[j]) == p) { 5785 mProvidersByAuthority.remove(names[j]); 5786 if (DEBUG_REMOVE) { 5787 if (chatty) 5788 Log.d(TAG, "Unregistered content provider: " + names[j] 5789 + ", className = " + p.info.name + ", isSyncable = " 5790 + p.info.isSyncable); 5791 } 5792 } 5793 } 5794 if (DEBUG_REMOVE && chatty) { 5795 if (r == null) { 5796 r = new StringBuilder(256); 5797 } else { 5798 r.append(' '); 5799 } 5800 r.append(p.info.name); 5801 } 5802 } 5803 if (r != null) { 5804 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 5805 } 5806 5807 N = pkg.services.size(); 5808 r = null; 5809 for (i=0; i<N; i++) { 5810 PackageParser.Service s = pkg.services.get(i); 5811 mServices.removeService(s); 5812 if (chatty) { 5813 if (r == null) { 5814 r = new StringBuilder(256); 5815 } else { 5816 r.append(' '); 5817 } 5818 r.append(s.info.name); 5819 } 5820 } 5821 if (r != null) { 5822 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 5823 } 5824 5825 N = pkg.receivers.size(); 5826 r = null; 5827 for (i=0; i<N; i++) { 5828 PackageParser.Activity a = pkg.receivers.get(i); 5829 mReceivers.removeActivity(a, "receiver"); 5830 if (DEBUG_REMOVE && chatty) { 5831 if (r == null) { 5832 r = new StringBuilder(256); 5833 } else { 5834 r.append(' '); 5835 } 5836 r.append(a.info.name); 5837 } 5838 } 5839 if (r != null) { 5840 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 5841 } 5842 5843 N = pkg.activities.size(); 5844 r = null; 5845 for (i=0; i<N; i++) { 5846 PackageParser.Activity a = pkg.activities.get(i); 5847 mActivities.removeActivity(a, "activity"); 5848 if (DEBUG_REMOVE && chatty) { 5849 if (r == null) { 5850 r = new StringBuilder(256); 5851 } else { 5852 r.append(' '); 5853 } 5854 r.append(a.info.name); 5855 } 5856 } 5857 if (r != null) { 5858 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 5859 } 5860 5861 N = pkg.permissions.size(); 5862 r = null; 5863 for (i=0; i<N; i++) { 5864 PackageParser.Permission p = pkg.permissions.get(i); 5865 BasePermission bp = mSettings.mPermissions.get(p.info.name); 5866 if (bp == null) { 5867 bp = mSettings.mPermissionTrees.get(p.info.name); 5868 } 5869 if (bp != null && bp.perm == p) { 5870 bp.perm = null; 5871 if (DEBUG_REMOVE && chatty) { 5872 if (r == null) { 5873 r = new StringBuilder(256); 5874 } else { 5875 r.append(' '); 5876 } 5877 r.append(p.info.name); 5878 } 5879 } 5880 } 5881 if (r != null) { 5882 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 5883 } 5884 5885 N = pkg.instrumentation.size(); 5886 r = null; 5887 for (i=0; i<N; i++) { 5888 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5889 mInstrumentation.remove(a.getComponentName()); 5890 if (DEBUG_REMOVE && chatty) { 5891 if (r == null) { 5892 r = new StringBuilder(256); 5893 } else { 5894 r.append(' '); 5895 } 5896 r.append(a.info.name); 5897 } 5898 } 5899 if (r != null) { 5900 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 5901 } 5902 5903 r = null; 5904 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5905 // Only system apps can hold shared libraries. 5906 if (pkg.libraryNames != null) { 5907 for (i=0; i<pkg.libraryNames.size(); i++) { 5908 String name = pkg.libraryNames.get(i); 5909 SharedLibraryEntry cur = mSharedLibraries.get(name); 5910 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 5911 mSharedLibraries.remove(name); 5912 if (DEBUG_REMOVE && chatty) { 5913 if (r == null) { 5914 r = new StringBuilder(256); 5915 } else { 5916 r.append(' '); 5917 } 5918 r.append(name); 5919 } 5920 } 5921 } 5922 } 5923 } 5924 if (r != null) { 5925 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 5926 } 5927 } 5928 5929 private static final boolean isPackageFilename(String name) { 5930 return name != null && name.endsWith(".apk"); 5931 } 5932 5933 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 5934 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 5935 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 5936 return true; 5937 } 5938 } 5939 return false; 5940 } 5941 5942 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 5943 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 5944 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 5945 5946 private void updatePermissionsLPw(String changingPkg, 5947 PackageParser.Package pkgInfo, int flags) { 5948 // Make sure there are no dangling permission trees. 5949 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 5950 while (it.hasNext()) { 5951 final BasePermission bp = it.next(); 5952 if (bp.packageSetting == null) { 5953 // We may not yet have parsed the package, so just see if 5954 // we still know about its settings. 5955 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 5956 } 5957 if (bp.packageSetting == null) { 5958 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 5959 + " from package " + bp.sourcePackage); 5960 it.remove(); 5961 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 5962 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 5963 Slog.i(TAG, "Removing old permission tree: " + bp.name 5964 + " from package " + bp.sourcePackage); 5965 flags |= UPDATE_PERMISSIONS_ALL; 5966 it.remove(); 5967 } 5968 } 5969 } 5970 5971 // Make sure all dynamic permissions have been assigned to a package, 5972 // and make sure there are no dangling permissions. 5973 it = mSettings.mPermissions.values().iterator(); 5974 while (it.hasNext()) { 5975 final BasePermission bp = it.next(); 5976 if (bp.type == BasePermission.TYPE_DYNAMIC) { 5977 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 5978 + bp.name + " pkg=" + bp.sourcePackage 5979 + " info=" + bp.pendingInfo); 5980 if (bp.packageSetting == null && bp.pendingInfo != null) { 5981 final BasePermission tree = findPermissionTreeLP(bp.name); 5982 if (tree != null && tree.perm != null) { 5983 bp.packageSetting = tree.packageSetting; 5984 bp.perm = new PackageParser.Permission(tree.perm.owner, 5985 new PermissionInfo(bp.pendingInfo)); 5986 bp.perm.info.packageName = tree.perm.info.packageName; 5987 bp.perm.info.name = bp.name; 5988 bp.uid = tree.uid; 5989 } 5990 } 5991 } 5992 if (bp.packageSetting == null) { 5993 // We may not yet have parsed the package, so just see if 5994 // we still know about its settings. 5995 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 5996 } 5997 if (bp.packageSetting == null) { 5998 Slog.w(TAG, "Removing dangling permission: " + bp.name 5999 + " from package " + bp.sourcePackage); 6000 it.remove(); 6001 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6002 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6003 Slog.i(TAG, "Removing old permission: " + bp.name 6004 + " from package " + bp.sourcePackage); 6005 flags |= UPDATE_PERMISSIONS_ALL; 6006 it.remove(); 6007 } 6008 } 6009 } 6010 6011 // Now update the permissions for all packages, in particular 6012 // replace the granted permissions of the system packages. 6013 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6014 for (PackageParser.Package pkg : mPackages.values()) { 6015 if (pkg != pkgInfo) { 6016 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6017 } 6018 } 6019 } 6020 6021 if (pkgInfo != null) { 6022 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6023 } 6024 } 6025 6026 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6027 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6028 if (ps == null) { 6029 return; 6030 } 6031 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6032 HashSet<String> origPermissions = gp.grantedPermissions; 6033 boolean changedPermission = false; 6034 6035 if (replace) { 6036 ps.permissionsFixed = false; 6037 if (gp == ps) { 6038 origPermissions = new HashSet<String>(gp.grantedPermissions); 6039 gp.grantedPermissions.clear(); 6040 gp.gids = mGlobalGids; 6041 } 6042 } 6043 6044 if (gp.gids == null) { 6045 gp.gids = mGlobalGids; 6046 } 6047 6048 final int N = pkg.requestedPermissions.size(); 6049 for (int i=0; i<N; i++) { 6050 final String name = pkg.requestedPermissions.get(i); 6051 final boolean required = pkg.requestedPermissionsRequired.get(i); 6052 final BasePermission bp = mSettings.mPermissions.get(name); 6053 if (DEBUG_INSTALL) { 6054 if (gp != ps) { 6055 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6056 } 6057 } 6058 6059 if (bp == null || bp.packageSetting == null) { 6060 Slog.w(TAG, "Unknown permission " + name 6061 + " in package " + pkg.packageName); 6062 continue; 6063 } 6064 6065 final String perm = bp.name; 6066 boolean allowed; 6067 boolean allowedSig = false; 6068 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6069 if (level == PermissionInfo.PROTECTION_NORMAL 6070 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6071 // We grant a normal or dangerous permission if any of the following 6072 // are true: 6073 // 1) The permission is required 6074 // 2) The permission is optional, but was granted in the past 6075 // 3) The permission is optional, but was requested by an 6076 // app in /system (not /data) 6077 // 6078 // Otherwise, reject the permission. 6079 allowed = (required || origPermissions.contains(perm) 6080 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6081 } else if (bp.packageSetting == null) { 6082 // This permission is invalid; skip it. 6083 allowed = false; 6084 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6085 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6086 if (allowed) { 6087 allowedSig = true; 6088 } 6089 } else { 6090 allowed = false; 6091 } 6092 if (DEBUG_INSTALL) { 6093 if (gp != ps) { 6094 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6095 } 6096 } 6097 if (allowed) { 6098 if (!isSystemApp(ps) && ps.permissionsFixed) { 6099 // If this is an existing, non-system package, then 6100 // we can't add any new permissions to it. 6101 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6102 // Except... if this is a permission that was added 6103 // to the platform (note: need to only do this when 6104 // updating the platform). 6105 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6106 } 6107 } 6108 if (allowed) { 6109 if (!gp.grantedPermissions.contains(perm)) { 6110 changedPermission = true; 6111 gp.grantedPermissions.add(perm); 6112 gp.gids = appendInts(gp.gids, bp.gids); 6113 } else if (!ps.haveGids) { 6114 gp.gids = appendInts(gp.gids, bp.gids); 6115 } 6116 } else { 6117 Slog.w(TAG, "Not granting permission " + perm 6118 + " to package " + pkg.packageName 6119 + " because it was previously installed without"); 6120 } 6121 } else { 6122 if (gp.grantedPermissions.remove(perm)) { 6123 changedPermission = true; 6124 gp.gids = removeInts(gp.gids, bp.gids); 6125 Slog.i(TAG, "Un-granting permission " + perm 6126 + " from package " + pkg.packageName 6127 + " (protectionLevel=" + bp.protectionLevel 6128 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6129 + ")"); 6130 } else { 6131 Slog.w(TAG, "Not granting permission " + perm 6132 + " to package " + pkg.packageName 6133 + " (protectionLevel=" + bp.protectionLevel 6134 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6135 + ")"); 6136 } 6137 } 6138 } 6139 6140 if ((changedPermission || replace) && !ps.permissionsFixed && 6141 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6142 // This is the first that we have heard about this package, so the 6143 // permissions we have now selected are fixed until explicitly 6144 // changed. 6145 ps.permissionsFixed = true; 6146 } 6147 ps.haveGids = true; 6148 } 6149 6150 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6151 boolean allowed = false; 6152 final int NP = PackageParser.NEW_PERMISSIONS.length; 6153 for (int ip=0; ip<NP; ip++) { 6154 final PackageParser.NewPermissionInfo npi 6155 = PackageParser.NEW_PERMISSIONS[ip]; 6156 if (npi.name.equals(perm) 6157 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6158 allowed = true; 6159 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6160 + pkg.packageName); 6161 break; 6162 } 6163 } 6164 return allowed; 6165 } 6166 6167 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6168 BasePermission bp, HashSet<String> origPermissions) { 6169 boolean allowed; 6170 allowed = (compareSignatures( 6171 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6172 == PackageManager.SIGNATURE_MATCH) 6173 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6174 == PackageManager.SIGNATURE_MATCH); 6175 if (!allowed && (bp.protectionLevel 6176 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6177 if (isSystemApp(pkg)) { 6178 // For updated system applications, a system permission 6179 // is granted only if it had been defined by the original application. 6180 if (isUpdatedSystemApp(pkg)) { 6181 final PackageSetting sysPs = mSettings 6182 .getDisabledSystemPkgLPr(pkg.packageName); 6183 final GrantedPermissions origGp = sysPs.sharedUser != null 6184 ? sysPs.sharedUser : sysPs; 6185 6186 if (origGp.grantedPermissions.contains(perm)) { 6187 // If the original was granted this permission, we take 6188 // that grant decision as read and propagate it to the 6189 // update. 6190 allowed = true; 6191 } else { 6192 // The system apk may have been updated with an older 6193 // version of the one on the data partition, but which 6194 // granted a new system permission that it didn't have 6195 // before. In this case we do want to allow the app to 6196 // now get the new permission if the ancestral apk is 6197 // privileged to get it. 6198 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6199 for (int j=0; 6200 j<sysPs.pkg.requestedPermissions.size(); j++) { 6201 if (perm.equals( 6202 sysPs.pkg.requestedPermissions.get(j))) { 6203 allowed = true; 6204 break; 6205 } 6206 } 6207 } 6208 } 6209 } else { 6210 allowed = isPrivilegedApp(pkg); 6211 } 6212 } 6213 } 6214 if (!allowed && (bp.protectionLevel 6215 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6216 // For development permissions, a development permission 6217 // is granted only if it was already granted. 6218 allowed = origPermissions.contains(perm); 6219 } 6220 return allowed; 6221 } 6222 6223 final class ActivityIntentResolver 6224 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6225 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6226 boolean defaultOnly, int userId) { 6227 if (!sUserManager.exists(userId)) return null; 6228 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6229 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6230 } 6231 6232 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6233 int userId) { 6234 if (!sUserManager.exists(userId)) return null; 6235 mFlags = flags; 6236 return super.queryIntent(intent, resolvedType, 6237 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6238 } 6239 6240 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6241 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6242 if (!sUserManager.exists(userId)) return null; 6243 if (packageActivities == null) { 6244 return null; 6245 } 6246 mFlags = flags; 6247 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6248 final int N = packageActivities.size(); 6249 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6250 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6251 6252 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6253 for (int i = 0; i < N; ++i) { 6254 intentFilters = packageActivities.get(i).intents; 6255 if (intentFilters != null && intentFilters.size() > 0) { 6256 PackageParser.ActivityIntentInfo[] array = 6257 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6258 intentFilters.toArray(array); 6259 listCut.add(array); 6260 } 6261 } 6262 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6263 } 6264 6265 public final void addActivity(PackageParser.Activity a, String type) { 6266 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6267 mActivities.put(a.getComponentName(), a); 6268 if (DEBUG_SHOW_INFO) 6269 Log.v( 6270 TAG, " " + type + " " + 6271 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6272 if (DEBUG_SHOW_INFO) 6273 Log.v(TAG, " Class=" + a.info.name); 6274 final int NI = a.intents.size(); 6275 for (int j=0; j<NI; j++) { 6276 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6277 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6278 intent.setPriority(0); 6279 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6280 + a.className + " with priority > 0, forcing to 0"); 6281 } 6282 if (DEBUG_SHOW_INFO) { 6283 Log.v(TAG, " IntentFilter:"); 6284 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6285 } 6286 if (!intent.debugCheck()) { 6287 Log.w(TAG, "==> For Activity " + a.info.name); 6288 } 6289 addFilter(intent); 6290 } 6291 } 6292 6293 public final void removeActivity(PackageParser.Activity a, String type) { 6294 mActivities.remove(a.getComponentName()); 6295 if (DEBUG_SHOW_INFO) { 6296 Log.v(TAG, " " + type + " " 6297 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6298 : a.info.name) + ":"); 6299 Log.v(TAG, " Class=" + a.info.name); 6300 } 6301 final int NI = a.intents.size(); 6302 for (int j=0; j<NI; j++) { 6303 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6304 if (DEBUG_SHOW_INFO) { 6305 Log.v(TAG, " IntentFilter:"); 6306 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6307 } 6308 removeFilter(intent); 6309 } 6310 } 6311 6312 @Override 6313 protected boolean allowFilterResult( 6314 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6315 ActivityInfo filterAi = filter.activity.info; 6316 for (int i=dest.size()-1; i>=0; i--) { 6317 ActivityInfo destAi = dest.get(i).activityInfo; 6318 if (destAi.name == filterAi.name 6319 && destAi.packageName == filterAi.packageName) { 6320 return false; 6321 } 6322 } 6323 return true; 6324 } 6325 6326 @Override 6327 protected ActivityIntentInfo[] newArray(int size) { 6328 return new ActivityIntentInfo[size]; 6329 } 6330 6331 @Override 6332 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6333 if (!sUserManager.exists(userId)) return true; 6334 PackageParser.Package p = filter.activity.owner; 6335 if (p != null) { 6336 PackageSetting ps = (PackageSetting)p.mExtras; 6337 if (ps != null) { 6338 // System apps are never considered stopped for purposes of 6339 // filtering, because there may be no way for the user to 6340 // actually re-launch them. 6341 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6342 && ps.getStopped(userId); 6343 } 6344 } 6345 return false; 6346 } 6347 6348 @Override 6349 protected boolean isPackageForFilter(String packageName, 6350 PackageParser.ActivityIntentInfo info) { 6351 return packageName.equals(info.activity.owner.packageName); 6352 } 6353 6354 @Override 6355 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6356 int match, int userId) { 6357 if (!sUserManager.exists(userId)) return null; 6358 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6359 return null; 6360 } 6361 final PackageParser.Activity activity = info.activity; 6362 if (mSafeMode && (activity.info.applicationInfo.flags 6363 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6364 return null; 6365 } 6366 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6367 if (ps == null) { 6368 return null; 6369 } 6370 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6371 ps.readUserState(userId), userId); 6372 if (ai == null) { 6373 return null; 6374 } 6375 final ResolveInfo res = new ResolveInfo(); 6376 res.activityInfo = ai; 6377 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6378 res.filter = info; 6379 } 6380 res.priority = info.getPriority(); 6381 res.preferredOrder = activity.owner.mPreferredOrder; 6382 //System.out.println("Result: " + res.activityInfo.className + 6383 // " = " + res.priority); 6384 res.match = match; 6385 res.isDefault = info.hasDefault; 6386 res.labelRes = info.labelRes; 6387 res.nonLocalizedLabel = info.nonLocalizedLabel; 6388 res.icon = info.icon; 6389 res.system = isSystemApp(res.activityInfo.applicationInfo); 6390 return res; 6391 } 6392 6393 @Override 6394 protected void sortResults(List<ResolveInfo> results) { 6395 Collections.sort(results, mResolvePrioritySorter); 6396 } 6397 6398 @Override 6399 protected void dumpFilter(PrintWriter out, String prefix, 6400 PackageParser.ActivityIntentInfo filter) { 6401 out.print(prefix); out.print( 6402 Integer.toHexString(System.identityHashCode(filter.activity))); 6403 out.print(' '); 6404 filter.activity.printComponentShortName(out); 6405 out.print(" filter "); 6406 out.println(Integer.toHexString(System.identityHashCode(filter))); 6407 } 6408 6409// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6410// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6411// final List<ResolveInfo> retList = Lists.newArrayList(); 6412// while (i.hasNext()) { 6413// final ResolveInfo resolveInfo = i.next(); 6414// if (isEnabledLP(resolveInfo.activityInfo)) { 6415// retList.add(resolveInfo); 6416// } 6417// } 6418// return retList; 6419// } 6420 6421 // Keys are String (activity class name), values are Activity. 6422 private final HashMap<ComponentName, PackageParser.Activity> mActivities 6423 = new HashMap<ComponentName, PackageParser.Activity>(); 6424 private int mFlags; 6425 } 6426 6427 private final class ServiceIntentResolver 6428 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 6429 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6430 boolean defaultOnly, int userId) { 6431 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6432 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6433 } 6434 6435 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6436 int userId) { 6437 if (!sUserManager.exists(userId)) return null; 6438 mFlags = flags; 6439 return super.queryIntent(intent, resolvedType, 6440 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6441 } 6442 6443 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6444 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 6445 if (!sUserManager.exists(userId)) return null; 6446 if (packageServices == null) { 6447 return null; 6448 } 6449 mFlags = flags; 6450 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6451 final int N = packageServices.size(); 6452 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 6453 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 6454 6455 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 6456 for (int i = 0; i < N; ++i) { 6457 intentFilters = packageServices.get(i).intents; 6458 if (intentFilters != null && intentFilters.size() > 0) { 6459 PackageParser.ServiceIntentInfo[] array = 6460 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 6461 intentFilters.toArray(array); 6462 listCut.add(array); 6463 } 6464 } 6465 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6466 } 6467 6468 public final void addService(PackageParser.Service s) { 6469 mServices.put(s.getComponentName(), s); 6470 if (DEBUG_SHOW_INFO) { 6471 Log.v(TAG, " " 6472 + (s.info.nonLocalizedLabel != null 6473 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6474 Log.v(TAG, " Class=" + s.info.name); 6475 } 6476 final int NI = s.intents.size(); 6477 int j; 6478 for (j=0; j<NI; j++) { 6479 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6480 if (DEBUG_SHOW_INFO) { 6481 Log.v(TAG, " IntentFilter:"); 6482 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6483 } 6484 if (!intent.debugCheck()) { 6485 Log.w(TAG, "==> For Service " + s.info.name); 6486 } 6487 addFilter(intent); 6488 } 6489 } 6490 6491 public final void removeService(PackageParser.Service s) { 6492 mServices.remove(s.getComponentName()); 6493 if (DEBUG_SHOW_INFO) { 6494 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 6495 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6496 Log.v(TAG, " Class=" + s.info.name); 6497 } 6498 final int NI = s.intents.size(); 6499 int j; 6500 for (j=0; j<NI; j++) { 6501 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6502 if (DEBUG_SHOW_INFO) { 6503 Log.v(TAG, " IntentFilter:"); 6504 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6505 } 6506 removeFilter(intent); 6507 } 6508 } 6509 6510 @Override 6511 protected boolean allowFilterResult( 6512 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 6513 ServiceInfo filterSi = filter.service.info; 6514 for (int i=dest.size()-1; i>=0; i--) { 6515 ServiceInfo destAi = dest.get(i).serviceInfo; 6516 if (destAi.name == filterSi.name 6517 && destAi.packageName == filterSi.packageName) { 6518 return false; 6519 } 6520 } 6521 return true; 6522 } 6523 6524 @Override 6525 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 6526 return new PackageParser.ServiceIntentInfo[size]; 6527 } 6528 6529 @Override 6530 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 6531 if (!sUserManager.exists(userId)) return true; 6532 PackageParser.Package p = filter.service.owner; 6533 if (p != null) { 6534 PackageSetting ps = (PackageSetting)p.mExtras; 6535 if (ps != null) { 6536 // System apps are never considered stopped for purposes of 6537 // filtering, because there may be no way for the user to 6538 // actually re-launch them. 6539 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 6540 && ps.getStopped(userId); 6541 } 6542 } 6543 return false; 6544 } 6545 6546 @Override 6547 protected boolean isPackageForFilter(String packageName, 6548 PackageParser.ServiceIntentInfo info) { 6549 return packageName.equals(info.service.owner.packageName); 6550 } 6551 6552 @Override 6553 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 6554 int match, int userId) { 6555 if (!sUserManager.exists(userId)) return null; 6556 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 6557 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 6558 return null; 6559 } 6560 final PackageParser.Service service = info.service; 6561 if (mSafeMode && (service.info.applicationInfo.flags 6562 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6563 return null; 6564 } 6565 PackageSetting ps = (PackageSetting) service.owner.mExtras; 6566 if (ps == null) { 6567 return null; 6568 } 6569 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 6570 ps.readUserState(userId), userId); 6571 if (si == null) { 6572 return null; 6573 } 6574 final ResolveInfo res = new ResolveInfo(); 6575 res.serviceInfo = si; 6576 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6577 res.filter = filter; 6578 } 6579 res.priority = info.getPriority(); 6580 res.preferredOrder = service.owner.mPreferredOrder; 6581 //System.out.println("Result: " + res.activityInfo.className + 6582 // " = " + res.priority); 6583 res.match = match; 6584 res.isDefault = info.hasDefault; 6585 res.labelRes = info.labelRes; 6586 res.nonLocalizedLabel = info.nonLocalizedLabel; 6587 res.icon = info.icon; 6588 res.system = isSystemApp(res.serviceInfo.applicationInfo); 6589 return res; 6590 } 6591 6592 @Override 6593 protected void sortResults(List<ResolveInfo> results) { 6594 Collections.sort(results, mResolvePrioritySorter); 6595 } 6596 6597 @Override 6598 protected void dumpFilter(PrintWriter out, String prefix, 6599 PackageParser.ServiceIntentInfo filter) { 6600 out.print(prefix); out.print( 6601 Integer.toHexString(System.identityHashCode(filter.service))); 6602 out.print(' '); 6603 filter.service.printComponentShortName(out); 6604 out.print(" filter "); 6605 out.println(Integer.toHexString(System.identityHashCode(filter))); 6606 } 6607 6608// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6609// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6610// final List<ResolveInfo> retList = Lists.newArrayList(); 6611// while (i.hasNext()) { 6612// final ResolveInfo resolveInfo = (ResolveInfo) i; 6613// if (isEnabledLP(resolveInfo.serviceInfo)) { 6614// retList.add(resolveInfo); 6615// } 6616// } 6617// return retList; 6618// } 6619 6620 // Keys are String (activity class name), values are Activity. 6621 private final HashMap<ComponentName, PackageParser.Service> mServices 6622 = new HashMap<ComponentName, PackageParser.Service>(); 6623 private int mFlags; 6624 }; 6625 6626 private final class ProviderIntentResolver 6627 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 6628 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6629 boolean defaultOnly, int userId) { 6630 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6631 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6632 } 6633 6634 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6635 int userId) { 6636 if (!sUserManager.exists(userId)) 6637 return null; 6638 mFlags = flags; 6639 return super.queryIntent(intent, resolvedType, 6640 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6641 } 6642 6643 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6644 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 6645 if (!sUserManager.exists(userId)) 6646 return null; 6647 if (packageProviders == null) { 6648 return null; 6649 } 6650 mFlags = flags; 6651 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 6652 final int N = packageProviders.size(); 6653 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 6654 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 6655 6656 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 6657 for (int i = 0; i < N; ++i) { 6658 intentFilters = packageProviders.get(i).intents; 6659 if (intentFilters != null && intentFilters.size() > 0) { 6660 PackageParser.ProviderIntentInfo[] array = 6661 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 6662 intentFilters.toArray(array); 6663 listCut.add(array); 6664 } 6665 } 6666 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6667 } 6668 6669 public final void addProvider(PackageParser.Provider p) { 6670 if (mProviders.containsKey(p.getComponentName())) { 6671 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 6672 return; 6673 } 6674 6675 mProviders.put(p.getComponentName(), p); 6676 if (DEBUG_SHOW_INFO) { 6677 Log.v(TAG, " " 6678 + (p.info.nonLocalizedLabel != null 6679 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 6680 Log.v(TAG, " Class=" + p.info.name); 6681 } 6682 final int NI = p.intents.size(); 6683 int j; 6684 for (j = 0; j < NI; j++) { 6685 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 6686 if (DEBUG_SHOW_INFO) { 6687 Log.v(TAG, " IntentFilter:"); 6688 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6689 } 6690 if (!intent.debugCheck()) { 6691 Log.w(TAG, "==> For Provider " + p.info.name); 6692 } 6693 addFilter(intent); 6694 } 6695 } 6696 6697 public final void removeProvider(PackageParser.Provider p) { 6698 mProviders.remove(p.getComponentName()); 6699 if (DEBUG_SHOW_INFO) { 6700 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 6701 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 6702 Log.v(TAG, " Class=" + p.info.name); 6703 } 6704 final int NI = p.intents.size(); 6705 int j; 6706 for (j = 0; j < NI; j++) { 6707 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 6708 if (DEBUG_SHOW_INFO) { 6709 Log.v(TAG, " IntentFilter:"); 6710 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6711 } 6712 removeFilter(intent); 6713 } 6714 } 6715 6716 @Override 6717 protected boolean allowFilterResult( 6718 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 6719 ProviderInfo filterPi = filter.provider.info; 6720 for (int i = dest.size() - 1; i >= 0; i--) { 6721 ProviderInfo destPi = dest.get(i).providerInfo; 6722 if (destPi.name == filterPi.name 6723 && destPi.packageName == filterPi.packageName) { 6724 return false; 6725 } 6726 } 6727 return true; 6728 } 6729 6730 @Override 6731 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 6732 return new PackageParser.ProviderIntentInfo[size]; 6733 } 6734 6735 @Override 6736 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 6737 if (!sUserManager.exists(userId)) 6738 return true; 6739 PackageParser.Package p = filter.provider.owner; 6740 if (p != null) { 6741 PackageSetting ps = (PackageSetting) p.mExtras; 6742 if (ps != null) { 6743 // System apps are never considered stopped for purposes of 6744 // filtering, because there may be no way for the user to 6745 // actually re-launch them. 6746 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 6747 && ps.getStopped(userId); 6748 } 6749 } 6750 return false; 6751 } 6752 6753 @Override 6754 protected boolean isPackageForFilter(String packageName, 6755 PackageParser.ProviderIntentInfo info) { 6756 return packageName.equals(info.provider.owner.packageName); 6757 } 6758 6759 @Override 6760 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 6761 int match, int userId) { 6762 if (!sUserManager.exists(userId)) 6763 return null; 6764 final PackageParser.ProviderIntentInfo info = filter; 6765 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 6766 return null; 6767 } 6768 final PackageParser.Provider provider = info.provider; 6769 if (mSafeMode && (provider.info.applicationInfo.flags 6770 & ApplicationInfo.FLAG_SYSTEM) == 0) { 6771 return null; 6772 } 6773 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 6774 if (ps == null) { 6775 return null; 6776 } 6777 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 6778 ps.readUserState(userId), userId); 6779 if (pi == null) { 6780 return null; 6781 } 6782 final ResolveInfo res = new ResolveInfo(); 6783 res.providerInfo = pi; 6784 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 6785 res.filter = filter; 6786 } 6787 res.priority = info.getPriority(); 6788 res.preferredOrder = provider.owner.mPreferredOrder; 6789 res.match = match; 6790 res.isDefault = info.hasDefault; 6791 res.labelRes = info.labelRes; 6792 res.nonLocalizedLabel = info.nonLocalizedLabel; 6793 res.icon = info.icon; 6794 res.system = isSystemApp(res.providerInfo.applicationInfo); 6795 return res; 6796 } 6797 6798 @Override 6799 protected void sortResults(List<ResolveInfo> results) { 6800 Collections.sort(results, mResolvePrioritySorter); 6801 } 6802 6803 @Override 6804 protected void dumpFilter(PrintWriter out, String prefix, 6805 PackageParser.ProviderIntentInfo filter) { 6806 out.print(prefix); 6807 out.print( 6808 Integer.toHexString(System.identityHashCode(filter.provider))); 6809 out.print(' '); 6810 filter.provider.printComponentShortName(out); 6811 out.print(" filter "); 6812 out.println(Integer.toHexString(System.identityHashCode(filter))); 6813 } 6814 6815 private final HashMap<ComponentName, PackageParser.Provider> mProviders 6816 = new HashMap<ComponentName, PackageParser.Provider>(); 6817 private int mFlags; 6818 }; 6819 6820 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 6821 new Comparator<ResolveInfo>() { 6822 public int compare(ResolveInfo r1, ResolveInfo r2) { 6823 int v1 = r1.priority; 6824 int v2 = r2.priority; 6825 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 6826 if (v1 != v2) { 6827 return (v1 > v2) ? -1 : 1; 6828 } 6829 v1 = r1.preferredOrder; 6830 v2 = r2.preferredOrder; 6831 if (v1 != v2) { 6832 return (v1 > v2) ? -1 : 1; 6833 } 6834 if (r1.isDefault != r2.isDefault) { 6835 return r1.isDefault ? -1 : 1; 6836 } 6837 v1 = r1.match; 6838 v2 = r2.match; 6839 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 6840 if (v1 != v2) { 6841 return (v1 > v2) ? -1 : 1; 6842 } 6843 if (r1.system != r2.system) { 6844 return r1.system ? -1 : 1; 6845 } 6846 return 0; 6847 } 6848 }; 6849 6850 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 6851 new Comparator<ProviderInfo>() { 6852 public int compare(ProviderInfo p1, ProviderInfo p2) { 6853 final int v1 = p1.initOrder; 6854 final int v2 = p2.initOrder; 6855 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 6856 } 6857 }; 6858 6859 static final void sendPackageBroadcast(String action, String pkg, 6860 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 6861 int[] userIds) { 6862 IActivityManager am = ActivityManagerNative.getDefault(); 6863 if (am != null) { 6864 try { 6865 if (userIds == null) { 6866 userIds = am.getRunningUserIds(); 6867 } 6868 for (int id : userIds) { 6869 final Intent intent = new Intent(action, 6870 pkg != null ? Uri.fromParts("package", pkg, null) : null); 6871 if (extras != null) { 6872 intent.putExtras(extras); 6873 } 6874 if (targetPkg != null) { 6875 intent.setPackage(targetPkg); 6876 } 6877 // Modify the UID when posting to other users 6878 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 6879 if (uid > 0 && UserHandle.getUserId(uid) != id) { 6880 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 6881 intent.putExtra(Intent.EXTRA_UID, uid); 6882 } 6883 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 6884 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 6885 if (DEBUG_BROADCASTS) { 6886 RuntimeException here = new RuntimeException("here"); 6887 here.fillInStackTrace(); 6888 Slog.d(TAG, "Sending to user " + id + ": " 6889 + intent.toShortString(false, true, false, false) 6890 + " " + intent.getExtras(), here); 6891 } 6892 am.broadcastIntent(null, intent, null, finishedReceiver, 6893 0, null, null, null, android.app.AppOpsManager.OP_NONE, 6894 finishedReceiver != null, false, id); 6895 } 6896 } catch (RemoteException ex) { 6897 } 6898 } 6899 } 6900 6901 /** 6902 * Check if the external storage media is available. This is true if there 6903 * is a mounted external storage medium or if the external storage is 6904 * emulated. 6905 */ 6906 private boolean isExternalMediaAvailable() { 6907 return mMediaMounted || Environment.isExternalStorageEmulated(); 6908 } 6909 6910 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 6911 // writer 6912 synchronized (mPackages) { 6913 if (!isExternalMediaAvailable()) { 6914 // If the external storage is no longer mounted at this point, 6915 // the caller may not have been able to delete all of this 6916 // packages files and can not delete any more. Bail. 6917 return null; 6918 } 6919 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 6920 if (lastPackage != null) { 6921 pkgs.remove(lastPackage); 6922 } 6923 if (pkgs.size() > 0) { 6924 return pkgs.get(0); 6925 } 6926 } 6927 return null; 6928 } 6929 6930 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 6931 if (false) { 6932 RuntimeException here = new RuntimeException("here"); 6933 here.fillInStackTrace(); 6934 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 6935 + " andCode=" + andCode, here); 6936 } 6937 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 6938 userId, andCode ? 1 : 0, packageName)); 6939 } 6940 6941 void startCleaningPackages() { 6942 // reader 6943 synchronized (mPackages) { 6944 if (!isExternalMediaAvailable()) { 6945 return; 6946 } 6947 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 6948 return; 6949 } 6950 } 6951 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 6952 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 6953 IActivityManager am = ActivityManagerNative.getDefault(); 6954 if (am != null) { 6955 try { 6956 am.startService(null, intent, null, UserHandle.USER_OWNER); 6957 } catch (RemoteException e) { 6958 } 6959 } 6960 } 6961 6962 private final class AppDirObserver extends FileObserver { 6963 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 6964 super(path, mask); 6965 mRootDir = path; 6966 mIsRom = isrom; 6967 mIsPrivileged = isPrivileged; 6968 } 6969 6970 public void onEvent(int event, String path) { 6971 String removedPackage = null; 6972 int removedAppId = -1; 6973 int[] removedUsers = null; 6974 String addedPackage = null; 6975 int addedAppId = -1; 6976 int[] addedUsers = null; 6977 6978 // TODO post a message to the handler to obtain serial ordering 6979 synchronized (mInstallLock) { 6980 String fullPathStr = null; 6981 File fullPath = null; 6982 if (path != null) { 6983 fullPath = new File(mRootDir, path); 6984 fullPathStr = fullPath.getPath(); 6985 } 6986 6987 if (DEBUG_APP_DIR_OBSERVER) 6988 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 6989 6990 if (!isPackageFilename(path)) { 6991 if (DEBUG_APP_DIR_OBSERVER) 6992 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 6993 return; 6994 } 6995 6996 // Ignore packages that are being installed or 6997 // have just been installed. 6998 if (ignoreCodePath(fullPathStr)) { 6999 return; 7000 } 7001 PackageParser.Package p = null; 7002 PackageSetting ps = null; 7003 // reader 7004 synchronized (mPackages) { 7005 p = mAppDirs.get(fullPathStr); 7006 if (p != null) { 7007 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7008 if (ps != null) { 7009 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7010 } else { 7011 removedUsers = sUserManager.getUserIds(); 7012 } 7013 } 7014 addedUsers = sUserManager.getUserIds(); 7015 } 7016 if ((event&REMOVE_EVENTS) != 0) { 7017 if (ps != null) { 7018 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7019 removePackageLI(ps, true); 7020 removedPackage = ps.name; 7021 removedAppId = ps.appId; 7022 } 7023 } 7024 7025 if ((event&ADD_EVENTS) != 0) { 7026 if (p == null) { 7027 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7028 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7029 if (mIsRom) { 7030 flags |= PackageParser.PARSE_IS_SYSTEM 7031 | PackageParser.PARSE_IS_SYSTEM_DIR; 7032 if (mIsPrivileged) { 7033 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7034 } 7035 } 7036 p = scanPackageLI(fullPath, flags, 7037 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7038 System.currentTimeMillis(), UserHandle.ALL); 7039 if (p != null) { 7040 /* 7041 * TODO this seems dangerous as the package may have 7042 * changed since we last acquired the mPackages 7043 * lock. 7044 */ 7045 // writer 7046 synchronized (mPackages) { 7047 updatePermissionsLPw(p.packageName, p, 7048 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7049 } 7050 addedPackage = p.applicationInfo.packageName; 7051 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7052 } 7053 } 7054 } 7055 7056 // reader 7057 synchronized (mPackages) { 7058 mSettings.writeLPr(); 7059 } 7060 } 7061 7062 if (removedPackage != null) { 7063 Bundle extras = new Bundle(1); 7064 extras.putInt(Intent.EXTRA_UID, removedAppId); 7065 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7066 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7067 extras, null, null, removedUsers); 7068 } 7069 if (addedPackage != null) { 7070 Bundle extras = new Bundle(1); 7071 extras.putInt(Intent.EXTRA_UID, addedAppId); 7072 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7073 extras, null, null, addedUsers); 7074 } 7075 } 7076 7077 private final String mRootDir; 7078 private final boolean mIsRom; 7079 private final boolean mIsPrivileged; 7080 } 7081 7082 /* 7083 * The old-style observer methods all just trampoline to the newer signature with 7084 * expanded install observer API. The older API continues to work but does not 7085 * supply the additional details of the Observer2 API. 7086 */ 7087 7088 /* Called when a downloaded package installation has been confirmed by the user */ 7089 public void installPackage( 7090 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 7091 installPackageEtc(packageURI, observer, null, flags, null); 7092 } 7093 7094 /* Called when a downloaded package installation has been confirmed by the user */ 7095 public void installPackage( 7096 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 7097 final String installerPackageName) { 7098 installPackageWithVerificationEtc(packageURI, observer, null, flags, 7099 installerPackageName, null, null, null); 7100 } 7101 7102 @Override 7103 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 7104 int flags, String installerPackageName, Uri verificationURI, 7105 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7106 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7107 VerificationParams.NO_UID, manifestDigest); 7108 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7109 installerPackageName, verificationParams, encryptionParams); 7110 } 7111 7112 public void installPackageWithVerificationAndEncryption(Uri packageURI, 7113 IPackageInstallObserver observer, int flags, String installerPackageName, 7114 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7115 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags, 7116 installerPackageName, verificationParams, encryptionParams); 7117 } 7118 7119 /* 7120 * And here are the "live" versions that take both observer arguments 7121 */ 7122 public void installPackageEtc( 7123 final Uri packageURI, final IPackageInstallObserver observer, 7124 IPackageInstallObserver2 observer2, final int flags) { 7125 installPackageEtc(packageURI, observer, observer2, flags, null); 7126 } 7127 7128 public void installPackageEtc( 7129 final Uri packageURI, final IPackageInstallObserver observer, 7130 final IPackageInstallObserver2 observer2, final int flags, 7131 final String installerPackageName) { 7132 installPackageWithVerificationEtc(packageURI, observer, observer2, flags, 7133 installerPackageName, null, null, null); 7134 } 7135 7136 @Override 7137 public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer, 7138 IPackageInstallObserver2 observer2, 7139 int flags, String installerPackageName, Uri verificationURI, 7140 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7141 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7142 VerificationParams.NO_UID, manifestDigest); 7143 installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags, 7144 installerPackageName, verificationParams, encryptionParams); 7145 } 7146 7147 /* 7148 * All of the installPackage...*() methods redirect to this one for the master implementation 7149 */ 7150 public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI, 7151 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7152 int flags, String installerPackageName, 7153 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7154 if (observer == null && observer2 == null) { 7155 throw new IllegalArgumentException("No install observer supplied"); 7156 } 7157 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7158 null); 7159 7160 final int uid = Binder.getCallingUid(); 7161 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7162 try { 7163 if (observer != null) { 7164 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7165 } 7166 if (observer2 != null) { 7167 observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7168 } 7169 } catch (RemoteException re) { 7170 } 7171 return; 7172 } 7173 7174 UserHandle user; 7175 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7176 user = UserHandle.ALL; 7177 } else { 7178 user = new UserHandle(UserHandle.getUserId(uid)); 7179 } 7180 7181 final int filteredFlags; 7182 7183 if (uid == Process.SHELL_UID || uid == 0) { 7184 if (DEBUG_INSTALL) { 7185 Slog.v(TAG, "Install from ADB"); 7186 } 7187 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7188 } else { 7189 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7190 } 7191 7192 verificationParams.setInstallerUid(uid); 7193 7194 final Message msg = mHandler.obtainMessage(INIT_COPY); 7195 msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags, 7196 installerPackageName, verificationParams, encryptionParams, user); 7197 mHandler.sendMessage(msg); 7198 } 7199 7200 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7201 Bundle extras = new Bundle(1); 7202 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7203 7204 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7205 packageName, extras, null, null, new int[] {userId}); 7206 try { 7207 IActivityManager am = ActivityManagerNative.getDefault(); 7208 final boolean isSystem = 7209 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7210 if (isSystem && am.isUserRunning(userId, false)) { 7211 // The just-installed/enabled app is bundled on the system, so presumed 7212 // to be able to run automatically without needing an explicit launch. 7213 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7214 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7215 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7216 .setPackage(packageName); 7217 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7218 android.app.AppOpsManager.OP_NONE, false, false, userId); 7219 } 7220 } catch (RemoteException e) { 7221 // shouldn't happen 7222 Slog.w(TAG, "Unable to bootstrap installed package", e); 7223 } 7224 } 7225 7226 @Override 7227 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7228 int userId) { 7229 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7230 PackageSetting pkgSetting; 7231 final int uid = Binder.getCallingUid(); 7232 if (UserHandle.getUserId(uid) != userId) { 7233 mContext.enforceCallingOrSelfPermission( 7234 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7235 "setApplicationBlockedSetting for user " + userId); 7236 } 7237 7238 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7239 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7240 return false; 7241 } 7242 7243 long callingId = Binder.clearCallingIdentity(); 7244 try { 7245 boolean sendAdded = false; 7246 boolean sendRemoved = false; 7247 // writer 7248 synchronized (mPackages) { 7249 pkgSetting = mSettings.mPackages.get(packageName); 7250 if (pkgSetting == null) { 7251 return false; 7252 } 7253 if (pkgSetting.getBlocked(userId) != blocked) { 7254 pkgSetting.setBlocked(blocked, userId); 7255 mSettings.writePackageRestrictionsLPr(userId); 7256 if (blocked) { 7257 sendRemoved = true; 7258 } else { 7259 sendAdded = true; 7260 } 7261 } 7262 } 7263 if (sendAdded) { 7264 sendPackageAddedForUser(packageName, pkgSetting, userId); 7265 return true; 7266 } 7267 if (sendRemoved) { 7268 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7269 "blocking pkg"); 7270 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7271 } 7272 } finally { 7273 Binder.restoreCallingIdentity(callingId); 7274 } 7275 return false; 7276 } 7277 7278 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7279 int userId) { 7280 final PackageRemovedInfo info = new PackageRemovedInfo(); 7281 info.removedPackage = packageName; 7282 info.removedUsers = new int[] {userId}; 7283 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7284 info.sendBroadcast(false, false, false); 7285 } 7286 7287 /** 7288 * Returns true if application is not found or there was an error. Otherwise it returns 7289 * the blocked state of the package for the given user. 7290 */ 7291 @Override 7292 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7293 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7294 PackageSetting pkgSetting; 7295 final int uid = Binder.getCallingUid(); 7296 if (UserHandle.getUserId(uid) != userId) { 7297 mContext.enforceCallingPermission( 7298 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7299 "getApplicationBlocked for user " + userId); 7300 } 7301 long callingId = Binder.clearCallingIdentity(); 7302 try { 7303 // writer 7304 synchronized (mPackages) { 7305 pkgSetting = mSettings.mPackages.get(packageName); 7306 if (pkgSetting == null) { 7307 return true; 7308 } 7309 return pkgSetting.getBlocked(userId); 7310 } 7311 } finally { 7312 Binder.restoreCallingIdentity(callingId); 7313 } 7314 } 7315 7316 /** 7317 * @hide 7318 */ 7319 @Override 7320 public int installExistingPackageAsUser(String packageName, int userId) { 7321 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7322 null); 7323 PackageSetting pkgSetting; 7324 final int uid = Binder.getCallingUid(); 7325 if (UserHandle.getUserId(uid) != userId) { 7326 mContext.enforceCallingPermission( 7327 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7328 "installExistingPackage for user " + userId); 7329 } 7330 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7331 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7332 } 7333 7334 long callingId = Binder.clearCallingIdentity(); 7335 try { 7336 boolean sendAdded = false; 7337 Bundle extras = new Bundle(1); 7338 7339 // writer 7340 synchronized (mPackages) { 7341 pkgSetting = mSettings.mPackages.get(packageName); 7342 if (pkgSetting == null) { 7343 return PackageManager.INSTALL_FAILED_INVALID_URI; 7344 } 7345 if (!pkgSetting.getInstalled(userId)) { 7346 pkgSetting.setInstalled(true, userId); 7347 pkgSetting.setBlocked(false, userId); 7348 mSettings.writePackageRestrictionsLPr(userId); 7349 sendAdded = true; 7350 } 7351 } 7352 7353 if (sendAdded) { 7354 sendPackageAddedForUser(packageName, pkgSetting, userId); 7355 } 7356 } finally { 7357 Binder.restoreCallingIdentity(callingId); 7358 } 7359 7360 return PackageManager.INSTALL_SUCCEEDED; 7361 } 7362 7363 private boolean isUserRestricted(int userId, String restrictionKey) { 7364 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7365 if (restrictions.getBoolean(restrictionKey, false)) { 7366 Log.w(TAG, "User is restricted: " + restrictionKey); 7367 return true; 7368 } 7369 return false; 7370 } 7371 7372 @Override 7373 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7374 mContext.enforceCallingOrSelfPermission( 7375 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7376 "Only package verification agents can verify applications"); 7377 7378 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7379 final PackageVerificationResponse response = new PackageVerificationResponse( 7380 verificationCode, Binder.getCallingUid()); 7381 msg.arg1 = id; 7382 msg.obj = response; 7383 mHandler.sendMessage(msg); 7384 } 7385 7386 @Override 7387 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7388 long millisecondsToDelay) { 7389 mContext.enforceCallingOrSelfPermission( 7390 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7391 "Only package verification agents can extend verification timeouts"); 7392 7393 final PackageVerificationState state = mPendingVerification.get(id); 7394 final PackageVerificationResponse response = new PackageVerificationResponse( 7395 verificationCodeAtTimeout, Binder.getCallingUid()); 7396 7397 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7398 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7399 } 7400 if (millisecondsToDelay < 0) { 7401 millisecondsToDelay = 0; 7402 } 7403 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7404 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7405 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7406 } 7407 7408 if ((state != null) && !state.timeoutExtended()) { 7409 state.extendTimeout(); 7410 7411 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7412 msg.arg1 = id; 7413 msg.obj = response; 7414 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7415 } 7416 } 7417 7418 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7419 int verificationCode, UserHandle user) { 7420 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7421 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7422 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7423 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7424 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7425 7426 mContext.sendBroadcastAsUser(intent, user, 7427 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7428 } 7429 7430 private ComponentName matchComponentForVerifier(String packageName, 7431 List<ResolveInfo> receivers) { 7432 ActivityInfo targetReceiver = null; 7433 7434 final int NR = receivers.size(); 7435 for (int i = 0; i < NR; i++) { 7436 final ResolveInfo info = receivers.get(i); 7437 if (info.activityInfo == null) { 7438 continue; 7439 } 7440 7441 if (packageName.equals(info.activityInfo.packageName)) { 7442 targetReceiver = info.activityInfo; 7443 break; 7444 } 7445 } 7446 7447 if (targetReceiver == null) { 7448 return null; 7449 } 7450 7451 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 7452 } 7453 7454 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 7455 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 7456 if (pkgInfo.verifiers.length == 0) { 7457 return null; 7458 } 7459 7460 final int N = pkgInfo.verifiers.length; 7461 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 7462 for (int i = 0; i < N; i++) { 7463 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 7464 7465 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 7466 receivers); 7467 if (comp == null) { 7468 continue; 7469 } 7470 7471 final int verifierUid = getUidForVerifier(verifierInfo); 7472 if (verifierUid == -1) { 7473 continue; 7474 } 7475 7476 if (DEBUG_VERIFY) { 7477 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 7478 + " with the correct signature"); 7479 } 7480 sufficientVerifiers.add(comp); 7481 verificationState.addSufficientVerifier(verifierUid); 7482 } 7483 7484 return sufficientVerifiers; 7485 } 7486 7487 private int getUidForVerifier(VerifierInfo verifierInfo) { 7488 synchronized (mPackages) { 7489 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 7490 if (pkg == null) { 7491 return -1; 7492 } else if (pkg.mSignatures.length != 1) { 7493 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7494 + " has more than one signature; ignoring"); 7495 return -1; 7496 } 7497 7498 /* 7499 * If the public key of the package's signature does not match 7500 * our expected public key, then this is a different package and 7501 * we should skip. 7502 */ 7503 7504 final byte[] expectedPublicKey; 7505 try { 7506 final Signature verifierSig = pkg.mSignatures[0]; 7507 final PublicKey publicKey = verifierSig.getPublicKey(); 7508 expectedPublicKey = publicKey.getEncoded(); 7509 } catch (CertificateException e) { 7510 return -1; 7511 } 7512 7513 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 7514 7515 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 7516 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7517 + " does not have the expected public key; ignoring"); 7518 return -1; 7519 } 7520 7521 return pkg.applicationInfo.uid; 7522 } 7523 } 7524 7525 public void finishPackageInstall(int token) { 7526 enforceSystemOrRoot("Only the system is allowed to finish installs"); 7527 7528 if (DEBUG_INSTALL) { 7529 Slog.v(TAG, "BM finishing package install for " + token); 7530 } 7531 7532 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 7533 mHandler.sendMessage(msg); 7534 } 7535 7536 /** 7537 * Get the verification agent timeout. 7538 * 7539 * @return verification timeout in milliseconds 7540 */ 7541 private long getVerificationTimeout() { 7542 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 7543 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 7544 DEFAULT_VERIFICATION_TIMEOUT); 7545 } 7546 7547 /** 7548 * Get the default verification agent response code. 7549 * 7550 * @return default verification response code 7551 */ 7552 private int getDefaultVerificationResponse() { 7553 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7554 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 7555 DEFAULT_VERIFICATION_RESPONSE); 7556 } 7557 7558 /** 7559 * Check whether or not package verification has been enabled. 7560 * 7561 * @return true if verification should be performed 7562 */ 7563 private boolean isVerificationEnabled(int flags) { 7564 if (!DEFAULT_VERIFY_ENABLE) { 7565 return false; 7566 } 7567 7568 // Check if installing from ADB 7569 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 7570 // Do not run verification in a test harness environment 7571 if (ActivityManager.isRunningInTestHarness()) { 7572 return false; 7573 } 7574 // Check if the developer does not want package verification for ADB installs 7575 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7576 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 7577 return false; 7578 } 7579 } 7580 7581 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7582 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 7583 } 7584 7585 /** 7586 * Get the "allow unknown sources" setting. 7587 * 7588 * @return the current "allow unknown sources" setting 7589 */ 7590 private int getUnknownSourcesSettings() { 7591 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7592 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 7593 -1); 7594 } 7595 7596 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 7597 final int uid = Binder.getCallingUid(); 7598 // writer 7599 synchronized (mPackages) { 7600 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 7601 if (targetPackageSetting == null) { 7602 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 7603 } 7604 7605 PackageSetting installerPackageSetting; 7606 if (installerPackageName != null) { 7607 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 7608 if (installerPackageSetting == null) { 7609 throw new IllegalArgumentException("Unknown installer package: " 7610 + installerPackageName); 7611 } 7612 } else { 7613 installerPackageSetting = null; 7614 } 7615 7616 Signature[] callerSignature; 7617 Object obj = mSettings.getUserIdLPr(uid); 7618 if (obj != null) { 7619 if (obj instanceof SharedUserSetting) { 7620 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 7621 } else if (obj instanceof PackageSetting) { 7622 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 7623 } else { 7624 throw new SecurityException("Bad object " + obj + " for uid " + uid); 7625 } 7626 } else { 7627 throw new SecurityException("Unknown calling uid " + uid); 7628 } 7629 7630 // Verify: can't set installerPackageName to a package that is 7631 // not signed with the same cert as the caller. 7632 if (installerPackageSetting != null) { 7633 if (compareSignatures(callerSignature, 7634 installerPackageSetting.signatures.mSignatures) 7635 != PackageManager.SIGNATURE_MATCH) { 7636 throw new SecurityException( 7637 "Caller does not have same cert as new installer package " 7638 + installerPackageName); 7639 } 7640 } 7641 7642 // Verify: if target already has an installer package, it must 7643 // be signed with the same cert as the caller. 7644 if (targetPackageSetting.installerPackageName != null) { 7645 PackageSetting setting = mSettings.mPackages.get( 7646 targetPackageSetting.installerPackageName); 7647 // If the currently set package isn't valid, then it's always 7648 // okay to change it. 7649 if (setting != null) { 7650 if (compareSignatures(callerSignature, 7651 setting.signatures.mSignatures) 7652 != PackageManager.SIGNATURE_MATCH) { 7653 throw new SecurityException( 7654 "Caller does not have same cert as old installer package " 7655 + targetPackageSetting.installerPackageName); 7656 } 7657 } 7658 } 7659 7660 // Okay! 7661 targetPackageSetting.installerPackageName = installerPackageName; 7662 scheduleWriteSettingsLocked(); 7663 } 7664 } 7665 7666 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 7667 // Queue up an async operation since the package installation may take a little while. 7668 mHandler.post(new Runnable() { 7669 public void run() { 7670 mHandler.removeCallbacks(this); 7671 // Result object to be returned 7672 PackageInstalledInfo res = new PackageInstalledInfo(); 7673 res.returnCode = currentStatus; 7674 res.uid = -1; 7675 res.pkg = null; 7676 res.removedInfo = new PackageRemovedInfo(); 7677 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 7678 args.doPreInstall(res.returnCode); 7679 synchronized (mInstallLock) { 7680 installPackageLI(args, true, res); 7681 } 7682 args.doPostInstall(res.returnCode, res.uid); 7683 } 7684 7685 // A restore should be performed at this point if (a) the install 7686 // succeeded, (b) the operation is not an update, and (c) the new 7687 // package has a backupAgent defined. 7688 final boolean update = res.removedInfo.removedPackage != null; 7689 boolean doRestore = (!update 7690 && res.pkg != null 7691 && res.pkg.applicationInfo.backupAgentName != null); 7692 7693 // Set up the post-install work request bookkeeping. This will be used 7694 // and cleaned up by the post-install event handling regardless of whether 7695 // there's a restore pass performed. Token values are >= 1. 7696 int token; 7697 if (mNextInstallToken < 0) mNextInstallToken = 1; 7698 token = mNextInstallToken++; 7699 7700 PostInstallData data = new PostInstallData(args, res); 7701 mRunningInstalls.put(token, data); 7702 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 7703 7704 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 7705 // Pass responsibility to the Backup Manager. It will perform a 7706 // restore if appropriate, then pass responsibility back to the 7707 // Package Manager to run the post-install observer callbacks 7708 // and broadcasts. 7709 IBackupManager bm = IBackupManager.Stub.asInterface( 7710 ServiceManager.getService(Context.BACKUP_SERVICE)); 7711 if (bm != null) { 7712 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 7713 + " to BM for possible restore"); 7714 try { 7715 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 7716 } catch (RemoteException e) { 7717 // can't happen; the backup manager is local 7718 } catch (Exception e) { 7719 Slog.e(TAG, "Exception trying to enqueue restore", e); 7720 doRestore = false; 7721 } 7722 } else { 7723 Slog.e(TAG, "Backup Manager not found!"); 7724 doRestore = false; 7725 } 7726 } 7727 7728 if (!doRestore) { 7729 // No restore possible, or the Backup Manager was mysteriously not 7730 // available -- just fire the post-install work request directly. 7731 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 7732 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 7733 mHandler.sendMessage(msg); 7734 } 7735 } 7736 }); 7737 } 7738 7739 private abstract class HandlerParams { 7740 private static final int MAX_RETRIES = 4; 7741 7742 /** 7743 * Number of times startCopy() has been attempted and had a non-fatal 7744 * error. 7745 */ 7746 private int mRetries = 0; 7747 7748 /** User handle for the user requesting the information or installation. */ 7749 private final UserHandle mUser; 7750 7751 HandlerParams(UserHandle user) { 7752 mUser = user; 7753 } 7754 7755 UserHandle getUser() { 7756 return mUser; 7757 } 7758 7759 final boolean startCopy() { 7760 boolean res; 7761 try { 7762 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 7763 7764 if (++mRetries > MAX_RETRIES) { 7765 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 7766 mHandler.sendEmptyMessage(MCS_GIVE_UP); 7767 handleServiceError(); 7768 return false; 7769 } else { 7770 handleStartCopy(); 7771 res = true; 7772 } 7773 } catch (RemoteException e) { 7774 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 7775 mHandler.sendEmptyMessage(MCS_RECONNECT); 7776 res = false; 7777 } 7778 handleReturnCode(); 7779 return res; 7780 } 7781 7782 final void serviceError() { 7783 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 7784 handleServiceError(); 7785 handleReturnCode(); 7786 } 7787 7788 abstract void handleStartCopy() throws RemoteException; 7789 abstract void handleServiceError(); 7790 abstract void handleReturnCode(); 7791 } 7792 7793 class MeasureParams extends HandlerParams { 7794 private final PackageStats mStats; 7795 private boolean mSuccess; 7796 7797 private final IPackageStatsObserver mObserver; 7798 7799 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 7800 super(new UserHandle(stats.userHandle)); 7801 mObserver = observer; 7802 mStats = stats; 7803 } 7804 7805 @Override 7806 public String toString() { 7807 return "MeasureParams{" 7808 + Integer.toHexString(System.identityHashCode(this)) 7809 + " " + mStats.packageName + "}"; 7810 } 7811 7812 @Override 7813 void handleStartCopy() throws RemoteException { 7814 synchronized (mInstallLock) { 7815 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 7816 } 7817 7818 if (mSuccess) { 7819 final boolean mounted; 7820 if (Environment.isExternalStorageEmulated()) { 7821 mounted = true; 7822 } else { 7823 final String status = Environment.getExternalStorageState(); 7824 mounted = (Environment.MEDIA_MOUNTED.equals(status) 7825 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 7826 } 7827 7828 if (mounted) { 7829 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 7830 7831 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 7832 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 7833 7834 mStats.externalDataSize = calculateDirectorySize(mContainerService, 7835 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 7836 7837 // Always subtract cache size, since it's a subdirectory 7838 mStats.externalDataSize -= mStats.externalCacheSize; 7839 7840 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 7841 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 7842 7843 mStats.externalObbSize = calculateDirectorySize(mContainerService, 7844 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 7845 } 7846 } 7847 } 7848 7849 @Override 7850 void handleReturnCode() { 7851 if (mObserver != null) { 7852 try { 7853 mObserver.onGetStatsCompleted(mStats, mSuccess); 7854 } catch (RemoteException e) { 7855 Slog.i(TAG, "Observer no longer exists."); 7856 } 7857 } 7858 } 7859 7860 @Override 7861 void handleServiceError() { 7862 Slog.e(TAG, "Could not measure application " + mStats.packageName 7863 + " external storage"); 7864 } 7865 } 7866 7867 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 7868 throws RemoteException { 7869 long result = 0; 7870 for (File path : paths) { 7871 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 7872 } 7873 return result; 7874 } 7875 7876 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 7877 for (File path : paths) { 7878 try { 7879 mcs.clearDirectory(path.getAbsolutePath()); 7880 } catch (RemoteException e) { 7881 } 7882 } 7883 } 7884 7885 class InstallParams extends HandlerParams { 7886 final IPackageInstallObserver observer; 7887 final IPackageInstallObserver2 observer2; 7888 int flags; 7889 7890 private final Uri mPackageURI; 7891 final String installerPackageName; 7892 final VerificationParams verificationParams; 7893 private InstallArgs mArgs; 7894 private int mRet; 7895 private File mTempPackage; 7896 final ContainerEncryptionParams encryptionParams; 7897 7898 InstallParams(Uri packageURI, 7899 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 7900 int flags, String installerPackageName, VerificationParams verificationParams, 7901 ContainerEncryptionParams encryptionParams, UserHandle user) { 7902 super(user); 7903 this.mPackageURI = packageURI; 7904 this.flags = flags; 7905 this.observer = observer; 7906 this.observer2 = observer2; 7907 this.installerPackageName = installerPackageName; 7908 this.verificationParams = verificationParams; 7909 this.encryptionParams = encryptionParams; 7910 } 7911 7912 @Override 7913 public String toString() { 7914 return "InstallParams{" 7915 + Integer.toHexString(System.identityHashCode(this)) 7916 + " " + mPackageURI + "}"; 7917 } 7918 7919 public ManifestDigest getManifestDigest() { 7920 if (verificationParams == null) { 7921 return null; 7922 } 7923 return verificationParams.getManifestDigest(); 7924 } 7925 7926 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 7927 String packageName = pkgLite.packageName; 7928 int installLocation = pkgLite.installLocation; 7929 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 7930 // reader 7931 synchronized (mPackages) { 7932 PackageParser.Package pkg = mPackages.get(packageName); 7933 if (pkg != null) { 7934 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 7935 // Check for downgrading. 7936 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 7937 if (pkgLite.versionCode < pkg.mVersionCode) { 7938 Slog.w(TAG, "Can't install update of " + packageName 7939 + " update version " + pkgLite.versionCode 7940 + " is older than installed version " 7941 + pkg.mVersionCode); 7942 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 7943 } 7944 } 7945 // Check for updated system application. 7946 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 7947 if (onSd) { 7948 Slog.w(TAG, "Cannot install update to system app on sdcard"); 7949 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 7950 } 7951 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 7952 } else { 7953 if (onSd) { 7954 // Install flag overrides everything. 7955 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 7956 } 7957 // If current upgrade specifies particular preference 7958 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 7959 // Application explicitly specified internal. 7960 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 7961 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 7962 // App explictly prefers external. Let policy decide 7963 } else { 7964 // Prefer previous location 7965 if (isExternal(pkg)) { 7966 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 7967 } 7968 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 7969 } 7970 } 7971 } else { 7972 // Invalid install. Return error code 7973 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 7974 } 7975 } 7976 } 7977 // All the special cases have been taken care of. 7978 // Return result based on recommended install location. 7979 if (onSd) { 7980 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 7981 } 7982 return pkgLite.recommendedInstallLocation; 7983 } 7984 7985 private long getMemoryLowThreshold() { 7986 final DeviceStorageMonitorInternal 7987 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 7988 if (dsm == null) { 7989 return 0L; 7990 } 7991 return dsm.getMemoryLowThreshold(); 7992 } 7993 7994 /* 7995 * Invoke remote method to get package information and install 7996 * location values. Override install location based on default 7997 * policy if needed and then create install arguments based 7998 * on the install location. 7999 */ 8000 public void handleStartCopy() throws RemoteException { 8001 int ret = PackageManager.INSTALL_SUCCEEDED; 8002 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8003 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8004 PackageInfoLite pkgLite = null; 8005 8006 if (onInt && onSd) { 8007 // Check if both bits are set. 8008 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8009 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8010 } else { 8011 final long lowThreshold = getMemoryLowThreshold(); 8012 if (lowThreshold == 0L) { 8013 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8014 } 8015 8016 try { 8017 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI, 8018 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8019 8020 final File packageFile; 8021 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) { 8022 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir); 8023 if (mTempPackage != null) { 8024 ParcelFileDescriptor out; 8025 try { 8026 out = ParcelFileDescriptor.open(mTempPackage, 8027 ParcelFileDescriptor.MODE_READ_WRITE); 8028 } catch (FileNotFoundException e) { 8029 out = null; 8030 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI); 8031 } 8032 8033 // Make a temporary file for decryption. 8034 ret = mContainerService 8035 .copyResource(mPackageURI, encryptionParams, out); 8036 IoUtils.closeQuietly(out); 8037 8038 packageFile = mTempPackage; 8039 8040 FileUtils.setPermissions(packageFile.getAbsolutePath(), 8041 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP 8042 | FileUtils.S_IROTH, 8043 -1, -1); 8044 } else { 8045 packageFile = null; 8046 } 8047 } else { 8048 packageFile = new File(mPackageURI.getPath()); 8049 } 8050 8051 if (packageFile != null) { 8052 // Remote call to find out default install location 8053 final String packageFilePath = packageFile.getAbsolutePath(); 8054 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags, 8055 lowThreshold); 8056 8057 /* 8058 * If we have too little free space, try to free cache 8059 * before giving up. 8060 */ 8061 if (pkgLite.recommendedInstallLocation 8062 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8063 final long size = mContainerService.calculateInstalledSize( 8064 packageFilePath, isForwardLocked()); 8065 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8066 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, 8067 flags, lowThreshold); 8068 } 8069 /* 8070 * The cache free must have deleted the file we 8071 * downloaded to install. 8072 * 8073 * TODO: fix the "freeCache" call to not delete 8074 * the file we care about. 8075 */ 8076 if (pkgLite.recommendedInstallLocation 8077 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8078 pkgLite.recommendedInstallLocation 8079 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8080 } 8081 } 8082 } 8083 } finally { 8084 mContext.revokeUriPermission(mPackageURI, 8085 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8086 } 8087 } 8088 8089 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8090 int loc = pkgLite.recommendedInstallLocation; 8091 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8092 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8093 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8094 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8095 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8096 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8097 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8098 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8099 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8100 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8101 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8102 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8103 } else { 8104 // Override with defaults if needed. 8105 loc = installLocationPolicy(pkgLite, flags); 8106 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8107 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8108 } else if (!onSd && !onInt) { 8109 // Override install location with flags 8110 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8111 // Set the flag to install on external media. 8112 flags |= PackageManager.INSTALL_EXTERNAL; 8113 flags &= ~PackageManager.INSTALL_INTERNAL; 8114 } else { 8115 // Make sure the flag for installing on external 8116 // media is unset 8117 flags |= PackageManager.INSTALL_INTERNAL; 8118 flags &= ~PackageManager.INSTALL_EXTERNAL; 8119 } 8120 } 8121 } 8122 } 8123 8124 final InstallArgs args = createInstallArgs(this); 8125 mArgs = args; 8126 8127 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8128 /* 8129 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8130 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8131 */ 8132 int userIdentifier = getUser().getIdentifier(); 8133 if (userIdentifier == UserHandle.USER_ALL 8134 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8135 userIdentifier = UserHandle.USER_OWNER; 8136 } 8137 8138 /* 8139 * Determine if we have any installed package verifiers. If we 8140 * do, then we'll defer to them to verify the packages. 8141 */ 8142 final int requiredUid = mRequiredVerifierPackage == null ? -1 8143 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8144 if (requiredUid != -1 && isVerificationEnabled(flags)) { 8145 final Intent verification = new Intent( 8146 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8147 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE); 8148 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8149 8150 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8151 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8152 0 /* TODO: Which userId? */); 8153 8154 if (DEBUG_VERIFY) { 8155 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8156 + verification.toString() + " with " + pkgLite.verifiers.length 8157 + " optional verifiers"); 8158 } 8159 8160 final int verificationId = mPendingVerificationToken++; 8161 8162 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8163 8164 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8165 installerPackageName); 8166 8167 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8168 8169 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8170 pkgLite.packageName); 8171 8172 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8173 pkgLite.versionCode); 8174 8175 if (verificationParams != null) { 8176 if (verificationParams.getVerificationURI() != null) { 8177 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8178 verificationParams.getVerificationURI()); 8179 } 8180 if (verificationParams.getOriginatingURI() != null) { 8181 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8182 verificationParams.getOriginatingURI()); 8183 } 8184 if (verificationParams.getReferrer() != null) { 8185 verification.putExtra(Intent.EXTRA_REFERRER, 8186 verificationParams.getReferrer()); 8187 } 8188 if (verificationParams.getOriginatingUid() >= 0) { 8189 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8190 verificationParams.getOriginatingUid()); 8191 } 8192 if (verificationParams.getInstallerUid() >= 0) { 8193 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8194 verificationParams.getInstallerUid()); 8195 } 8196 } 8197 8198 final PackageVerificationState verificationState = new PackageVerificationState( 8199 requiredUid, args); 8200 8201 mPendingVerification.append(verificationId, verificationState); 8202 8203 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8204 receivers, verificationState); 8205 8206 /* 8207 * If any sufficient verifiers were listed in the package 8208 * manifest, attempt to ask them. 8209 */ 8210 if (sufficientVerifiers != null) { 8211 final int N = sufficientVerifiers.size(); 8212 if (N == 0) { 8213 Slog.i(TAG, "Additional verifiers required, but none installed."); 8214 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8215 } else { 8216 for (int i = 0; i < N; i++) { 8217 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8218 8219 final Intent sufficientIntent = new Intent(verification); 8220 sufficientIntent.setComponent(verifierComponent); 8221 8222 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8223 } 8224 } 8225 } 8226 8227 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8228 mRequiredVerifierPackage, receivers); 8229 if (ret == PackageManager.INSTALL_SUCCEEDED 8230 && mRequiredVerifierPackage != null) { 8231 /* 8232 * Send the intent to the required verification agent, 8233 * but only start the verification timeout after the 8234 * target BroadcastReceivers have run. 8235 */ 8236 verification.setComponent(requiredVerifierComponent); 8237 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8238 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8239 new BroadcastReceiver() { 8240 @Override 8241 public void onReceive(Context context, Intent intent) { 8242 final Message msg = mHandler 8243 .obtainMessage(CHECK_PENDING_VERIFICATION); 8244 msg.arg1 = verificationId; 8245 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8246 } 8247 }, null, 0, null, null); 8248 8249 /* 8250 * We don't want the copy to proceed until verification 8251 * succeeds, so null out this field. 8252 */ 8253 mArgs = null; 8254 } 8255 } else { 8256 /* 8257 * No package verification is enabled, so immediately start 8258 * the remote call to initiate copy using temporary file. 8259 */ 8260 ret = args.copyApk(mContainerService, true); 8261 } 8262 } 8263 8264 mRet = ret; 8265 } 8266 8267 @Override 8268 void handleReturnCode() { 8269 // If mArgs is null, then MCS couldn't be reached. When it 8270 // reconnects, it will try again to install. At that point, this 8271 // will succeed. 8272 if (mArgs != null) { 8273 processPendingInstall(mArgs, mRet); 8274 8275 if (mTempPackage != null) { 8276 if (!mTempPackage.delete()) { 8277 Slog.w(TAG, "Couldn't delete temporary file: " + 8278 mTempPackage.getAbsolutePath()); 8279 } 8280 } 8281 } 8282 } 8283 8284 @Override 8285 void handleServiceError() { 8286 mArgs = createInstallArgs(this); 8287 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8288 } 8289 8290 public boolean isForwardLocked() { 8291 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8292 } 8293 8294 public Uri getPackageUri() { 8295 if (mTempPackage != null) { 8296 return Uri.fromFile(mTempPackage); 8297 } else { 8298 return mPackageURI; 8299 } 8300 } 8301 } 8302 8303 /* 8304 * Utility class used in movePackage api. 8305 * srcArgs and targetArgs are not set for invalid flags and make 8306 * sure to do null checks when invoking methods on them. 8307 * We probably want to return ErrorPrams for both failed installs 8308 * and moves. 8309 */ 8310 class MoveParams extends HandlerParams { 8311 final IPackageMoveObserver observer; 8312 final int flags; 8313 final String packageName; 8314 final InstallArgs srcArgs; 8315 final InstallArgs targetArgs; 8316 int uid; 8317 int mRet; 8318 8319 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8320 String packageName, String dataDir, String instructionSet, 8321 int uid, UserHandle user) { 8322 super(user); 8323 this.srcArgs = srcArgs; 8324 this.observer = observer; 8325 this.flags = flags; 8326 this.packageName = packageName; 8327 this.uid = uid; 8328 if (srcArgs != null) { 8329 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath())); 8330 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet); 8331 } else { 8332 targetArgs = null; 8333 } 8334 } 8335 8336 @Override 8337 public String toString() { 8338 return "MoveParams{" 8339 + Integer.toHexString(System.identityHashCode(this)) 8340 + " " + packageName + "}"; 8341 } 8342 8343 public void handleStartCopy() throws RemoteException { 8344 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8345 // Check for storage space on target medium 8346 if (!targetArgs.checkFreeStorage(mContainerService)) { 8347 Log.w(TAG, "Insufficient storage to install"); 8348 return; 8349 } 8350 8351 mRet = srcArgs.doPreCopy(); 8352 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8353 return; 8354 } 8355 8356 mRet = targetArgs.copyApk(mContainerService, false); 8357 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8358 srcArgs.doPostCopy(uid); 8359 return; 8360 } 8361 8362 mRet = srcArgs.doPostCopy(uid); 8363 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8364 return; 8365 } 8366 8367 mRet = targetArgs.doPreInstall(mRet); 8368 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8369 return; 8370 } 8371 8372 if (DEBUG_SD_INSTALL) { 8373 StringBuilder builder = new StringBuilder(); 8374 if (srcArgs != null) { 8375 builder.append("src: "); 8376 builder.append(srcArgs.getCodePath()); 8377 } 8378 if (targetArgs != null) { 8379 builder.append(" target : "); 8380 builder.append(targetArgs.getCodePath()); 8381 } 8382 Log.i(TAG, builder.toString()); 8383 } 8384 } 8385 8386 @Override 8387 void handleReturnCode() { 8388 targetArgs.doPostInstall(mRet, uid); 8389 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8390 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8391 currentStatus = PackageManager.MOVE_SUCCEEDED; 8392 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8393 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8394 } 8395 processPendingMove(this, currentStatus); 8396 } 8397 8398 @Override 8399 void handleServiceError() { 8400 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8401 } 8402 } 8403 8404 /** 8405 * Used during creation of InstallArgs 8406 * 8407 * @param flags package installation flags 8408 * @return true if should be installed on external storage 8409 */ 8410 private static boolean installOnSd(int flags) { 8411 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8412 return false; 8413 } 8414 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8415 return true; 8416 } 8417 return false; 8418 } 8419 8420 /** 8421 * Used during creation of InstallArgs 8422 * 8423 * @param flags package installation flags 8424 * @return true if should be installed as forward locked 8425 */ 8426 private static boolean installForwardLocked(int flags) { 8427 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8428 } 8429 8430 private InstallArgs createInstallArgs(InstallParams params) { 8431 if (installOnSd(params.flags) || params.isForwardLocked()) { 8432 return new AsecInstallArgs(params); 8433 } else { 8434 return new FileInstallArgs(params); 8435 } 8436 } 8437 8438 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath, 8439 String nativeLibraryPath, String instructionSet) { 8440 final boolean isInAsec; 8441 if (installOnSd(flags)) { 8442 /* Apps on SD card are always in ASEC containers. */ 8443 isInAsec = true; 8444 } else if (installForwardLocked(flags) 8445 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8446 /* 8447 * Forward-locked apps are only in ASEC containers if they're the 8448 * new style 8449 */ 8450 isInAsec = true; 8451 } else { 8452 isInAsec = false; 8453 } 8454 8455 if (isInAsec) { 8456 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8457 instructionSet, installOnSd(flags), installForwardLocked(flags)); 8458 } else { 8459 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8460 instructionSet); 8461 } 8462 } 8463 8464 // Used by package mover 8465 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir, 8466 String instructionSet) { 8467 if (installOnSd(flags) || installForwardLocked(flags)) { 8468 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/" 8469 + AsecInstallArgs.RES_FILE_NAME); 8470 return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags), 8471 installForwardLocked(flags)); 8472 } else { 8473 return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet); 8474 } 8475 } 8476 8477 static abstract class InstallArgs { 8478 final IPackageInstallObserver observer; 8479 final IPackageInstallObserver2 observer2; 8480 // Always refers to PackageManager flags only 8481 final int flags; 8482 final Uri packageURI; 8483 final String installerPackageName; 8484 final ManifestDigest manifestDigest; 8485 final UserHandle user; 8486 final String instructionSet; 8487 8488 InstallArgs(Uri packageURI, 8489 IPackageInstallObserver observer, IPackageInstallObserver2 observer2, 8490 int flags, String installerPackageName, ManifestDigest manifestDigest, 8491 UserHandle user, String instructionSet) { 8492 this.packageURI = packageURI; 8493 this.flags = flags; 8494 this.observer = observer; 8495 this.observer2 = observer2; 8496 this.installerPackageName = installerPackageName; 8497 this.manifestDigest = manifestDigest; 8498 this.user = user; 8499 this.instructionSet = instructionSet; 8500 } 8501 8502 abstract void createCopyFile(); 8503 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 8504 abstract int doPreInstall(int status); 8505 abstract boolean doRename(int status, String pkgName, String oldCodePath); 8506 8507 abstract int doPostInstall(int status, int uid); 8508 abstract String getCodePath(); 8509 abstract String getResourcePath(); 8510 abstract String getNativeLibraryPath(); 8511 // Need installer lock especially for dex file removal. 8512 abstract void cleanUpResourcesLI(); 8513 abstract boolean doPostDeleteLI(boolean delete); 8514 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 8515 8516 /** 8517 * Called before the source arguments are copied. This is used mostly 8518 * for MoveParams when it needs to read the source file to put it in the 8519 * destination. 8520 */ 8521 int doPreCopy() { 8522 return PackageManager.INSTALL_SUCCEEDED; 8523 } 8524 8525 /** 8526 * Called after the source arguments are copied. This is used mostly for 8527 * MoveParams when it needs to read the source file to put it in the 8528 * destination. 8529 * 8530 * @return 8531 */ 8532 int doPostCopy(int uid) { 8533 return PackageManager.INSTALL_SUCCEEDED; 8534 } 8535 8536 protected boolean isFwdLocked() { 8537 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8538 } 8539 8540 UserHandle getUser() { 8541 return user; 8542 } 8543 } 8544 8545 class FileInstallArgs extends InstallArgs { 8546 File installDir; 8547 String codeFileName; 8548 String resourceFileName; 8549 String libraryPath; 8550 boolean created = false; 8551 8552 FileInstallArgs(InstallParams params) { 8553 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 8554 params.installerPackageName, params.getManifestDigest(), 8555 params.getUser(), null /* instruction set */); 8556 } 8557 8558 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 8559 String instructionSet) { 8560 super(null, null, null, 0, null, null, null, instructionSet); 8561 File codeFile = new File(fullCodePath); 8562 installDir = codeFile.getParentFile(); 8563 codeFileName = fullCodePath; 8564 resourceFileName = fullResourcePath; 8565 libraryPath = nativeLibraryPath; 8566 } 8567 8568 FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) { 8569 super(packageURI, null, null, 0, null, null, null, instructionSet); 8570 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 8571 String apkName = getNextCodePath(null, pkgName, ".apk"); 8572 codeFileName = new File(installDir, apkName + ".apk").getPath(); 8573 resourceFileName = getResourcePathFromCodePath(); 8574 libraryPath = new File(mAppLibInstallDir, pkgName).getPath(); 8575 } 8576 8577 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 8578 final long lowThreshold; 8579 8580 final DeviceStorageMonitorInternal 8581 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8582 if (dsm == null) { 8583 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8584 lowThreshold = 0L; 8585 } else { 8586 if (dsm.isMemoryLow()) { 8587 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 8588 return false; 8589 } 8590 8591 lowThreshold = dsm.getMemoryLowThreshold(); 8592 } 8593 8594 try { 8595 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8596 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8597 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold); 8598 } finally { 8599 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8600 } 8601 } 8602 8603 String getCodePath() { 8604 return codeFileName; 8605 } 8606 8607 void createCopyFile() { 8608 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 8609 codeFileName = createTempPackageFile(installDir).getPath(); 8610 resourceFileName = getResourcePathFromCodePath(); 8611 libraryPath = getLibraryPathFromCodePath(); 8612 created = true; 8613 } 8614 8615 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 8616 if (temp) { 8617 // Generate temp file name 8618 createCopyFile(); 8619 } 8620 // Get a ParcelFileDescriptor to write to the output file 8621 File codeFile = new File(codeFileName); 8622 if (!created) { 8623 try { 8624 codeFile.createNewFile(); 8625 // Set permissions 8626 if (!setPermissions()) { 8627 // Failed setting permissions. 8628 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8629 } 8630 } catch (IOException e) { 8631 Slog.w(TAG, "Failed to create file " + codeFile); 8632 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8633 } 8634 } 8635 ParcelFileDescriptor out = null; 8636 try { 8637 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 8638 } catch (FileNotFoundException e) { 8639 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 8640 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8641 } 8642 // Copy the resource now 8643 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8644 try { 8645 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8646 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8647 ret = imcs.copyResource(packageURI, null, out); 8648 } finally { 8649 IoUtils.closeQuietly(out); 8650 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8651 } 8652 8653 if (isFwdLocked()) { 8654 final File destResourceFile = new File(getResourcePath()); 8655 8656 // Copy the public files 8657 try { 8658 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 8659 } catch (IOException e) { 8660 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 8661 + " forward-locked app."); 8662 destResourceFile.delete(); 8663 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8664 } 8665 } 8666 8667 final File nativeLibraryFile = new File(getNativeLibraryPath()); 8668 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath()); 8669 if (nativeLibraryFile.exists()) { 8670 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 8671 nativeLibraryFile.delete(); 8672 } 8673 try { 8674 int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile); 8675 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8676 return copyRet; 8677 } 8678 } catch (IOException e) { 8679 Slog.e(TAG, "Copying native libraries failed", e); 8680 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8681 } 8682 8683 return ret; 8684 } 8685 8686 int doPreInstall(int status) { 8687 if (status != PackageManager.INSTALL_SUCCEEDED) { 8688 cleanUp(); 8689 } 8690 return status; 8691 } 8692 8693 boolean doRename(int status, final String pkgName, String oldCodePath) { 8694 if (status != PackageManager.INSTALL_SUCCEEDED) { 8695 cleanUp(); 8696 return false; 8697 } else { 8698 final File oldCodeFile = new File(getCodePath()); 8699 final File oldResourceFile = new File(getResourcePath()); 8700 final File oldLibraryFile = new File(getNativeLibraryPath()); 8701 8702 // Rename APK file based on packageName 8703 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 8704 final File newCodeFile = new File(installDir, apkName + ".apk"); 8705 if (!oldCodeFile.renameTo(newCodeFile)) { 8706 return false; 8707 } 8708 codeFileName = newCodeFile.getPath(); 8709 8710 // Rename public resource file if it's forward-locked. 8711 final File newResFile = new File(getResourcePathFromCodePath()); 8712 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 8713 return false; 8714 } 8715 resourceFileName = newResFile.getPath(); 8716 8717 // Rename library path 8718 final File newLibraryFile = new File(getLibraryPathFromCodePath()); 8719 if (newLibraryFile.exists()) { 8720 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile); 8721 newLibraryFile.delete(); 8722 } 8723 if (!oldLibraryFile.renameTo(newLibraryFile)) { 8724 Slog.e(TAG, "Cannot rename native library directory " 8725 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath()); 8726 return false; 8727 } 8728 libraryPath = newLibraryFile.getPath(); 8729 8730 // Attempt to set permissions 8731 if (!setPermissions()) { 8732 return false; 8733 } 8734 8735 if (!SELinux.restorecon(newCodeFile)) { 8736 return false; 8737 } 8738 8739 return true; 8740 } 8741 } 8742 8743 int doPostInstall(int status, int uid) { 8744 if (status != PackageManager.INSTALL_SUCCEEDED) { 8745 cleanUp(); 8746 } 8747 return status; 8748 } 8749 8750 String getResourcePath() { 8751 return resourceFileName; 8752 } 8753 8754 private String getResourcePathFromCodePath() { 8755 final String codePath = getCodePath(); 8756 if (isFwdLocked()) { 8757 final StringBuilder sb = new StringBuilder(); 8758 8759 sb.append(mAppInstallDir.getPath()); 8760 sb.append('/'); 8761 sb.append(getApkName(codePath)); 8762 sb.append(".zip"); 8763 8764 /* 8765 * If our APK is a temporary file, mark the resource as a 8766 * temporary file as well so it can be cleaned up after 8767 * catastrophic failure. 8768 */ 8769 if (codePath.endsWith(".tmp")) { 8770 sb.append(".tmp"); 8771 } 8772 8773 return sb.toString(); 8774 } else { 8775 return codePath; 8776 } 8777 } 8778 8779 private String getLibraryPathFromCodePath() { 8780 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath(); 8781 } 8782 8783 @Override 8784 String getNativeLibraryPath() { 8785 if (libraryPath == null) { 8786 libraryPath = getLibraryPathFromCodePath(); 8787 } 8788 return libraryPath; 8789 } 8790 8791 private boolean cleanUp() { 8792 boolean ret = true; 8793 String sourceDir = getCodePath(); 8794 String publicSourceDir = getResourcePath(); 8795 if (sourceDir != null) { 8796 File sourceFile = new File(sourceDir); 8797 if (!sourceFile.exists()) { 8798 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 8799 ret = false; 8800 } 8801 // Delete application's code and resources 8802 sourceFile.delete(); 8803 } 8804 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 8805 final File publicSourceFile = new File(publicSourceDir); 8806 if (!publicSourceFile.exists()) { 8807 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 8808 } 8809 if (publicSourceFile.exists()) { 8810 publicSourceFile.delete(); 8811 } 8812 } 8813 8814 if (libraryPath != null) { 8815 File nativeLibraryFile = new File(libraryPath); 8816 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 8817 if (!nativeLibraryFile.delete()) { 8818 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath); 8819 } 8820 } 8821 8822 return ret; 8823 } 8824 8825 void cleanUpResourcesLI() { 8826 String sourceDir = getCodePath(); 8827 if (cleanUp()) { 8828 if (instructionSet == null) { 8829 throw new IllegalStateException("instructionSet == null"); 8830 } 8831 int retCode = mInstaller.rmdex(sourceDir, instructionSet); 8832 if (retCode < 0) { 8833 Slog.w(TAG, "Couldn't remove dex file for package: " 8834 + " at location " 8835 + sourceDir + ", retcode=" + retCode); 8836 // we don't consider this to be a failure of the core package deletion 8837 } 8838 } 8839 } 8840 8841 private boolean setPermissions() { 8842 // TODO Do this in a more elegant way later on. for now just a hack 8843 if (!isFwdLocked()) { 8844 final int filePermissions = 8845 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 8846 |FileUtils.S_IROTH; 8847 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 8848 if (retCode != 0) { 8849 Slog.e(TAG, "Couldn't set new package file permissions for " + 8850 getCodePath() 8851 + ". The return code was: " + retCode); 8852 // TODO Define new internal error 8853 return false; 8854 } 8855 return true; 8856 } 8857 return true; 8858 } 8859 8860 boolean doPostDeleteLI(boolean delete) { 8861 // XXX err, shouldn't we respect the delete flag? 8862 cleanUpResourcesLI(); 8863 return true; 8864 } 8865 } 8866 8867 private boolean isAsecExternal(String cid) { 8868 final String asecPath = PackageHelper.getSdFilesystem(cid); 8869 return !asecPath.startsWith(mAsecInternalPath); 8870 } 8871 8872 /** 8873 * Extract the MountService "container ID" from the full code path of an 8874 * .apk. 8875 */ 8876 static String cidFromCodePath(String fullCodePath) { 8877 int eidx = fullCodePath.lastIndexOf("/"); 8878 String subStr1 = fullCodePath.substring(0, eidx); 8879 int sidx = subStr1.lastIndexOf("/"); 8880 return subStr1.substring(sidx+1, eidx); 8881 } 8882 8883 class AsecInstallArgs extends InstallArgs { 8884 static final String RES_FILE_NAME = "pkg.apk"; 8885 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 8886 8887 String cid; 8888 String packagePath; 8889 String resourcePath; 8890 String libraryPath; 8891 8892 AsecInstallArgs(InstallParams params) { 8893 super(params.getPackageUri(), params.observer, params.observer2, params.flags, 8894 params.installerPackageName, params.getManifestDigest(), 8895 params.getUser(), null /* instruction set */); 8896 } 8897 8898 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 8899 String instructionSet, boolean isExternal, boolean isForwardLocked) { 8900 super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 8901 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 8902 null, null, null, instructionSet); 8903 // Extract cid from fullCodePath 8904 int eidx = fullCodePath.lastIndexOf("/"); 8905 String subStr1 = fullCodePath.substring(0, eidx); 8906 int sidx = subStr1.lastIndexOf("/"); 8907 cid = subStr1.substring(sidx+1, eidx); 8908 setCachePath(subStr1); 8909 } 8910 8911 AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) { 8912 super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 8913 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 8914 null, null, null, instructionSet); 8915 this.cid = cid; 8916 setCachePath(PackageHelper.getSdDir(cid)); 8917 } 8918 8919 AsecInstallArgs(Uri packageURI, String cid, String instructionSet, 8920 boolean isExternal, boolean isForwardLocked) { 8921 super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 8922 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 8923 null, null, null, instructionSet); 8924 this.cid = cid; 8925 } 8926 8927 void createCopyFile() { 8928 cid = getTempContainerId(); 8929 } 8930 8931 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 8932 try { 8933 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8934 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8935 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked()); 8936 } finally { 8937 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8938 } 8939 } 8940 8941 private final boolean isExternal() { 8942 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8943 } 8944 8945 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 8946 if (temp) { 8947 createCopyFile(); 8948 } else { 8949 /* 8950 * Pre-emptively destroy the container since it's destroyed if 8951 * copying fails due to it existing anyway. 8952 */ 8953 PackageHelper.destroySdDir(cid); 8954 } 8955 8956 final String newCachePath; 8957 try { 8958 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8959 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8960 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(), 8961 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked()); 8962 } finally { 8963 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8964 } 8965 8966 if (newCachePath != null) { 8967 setCachePath(newCachePath); 8968 return PackageManager.INSTALL_SUCCEEDED; 8969 } else { 8970 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 8971 } 8972 } 8973 8974 @Override 8975 String getCodePath() { 8976 return packagePath; 8977 } 8978 8979 @Override 8980 String getResourcePath() { 8981 return resourcePath; 8982 } 8983 8984 @Override 8985 String getNativeLibraryPath() { 8986 return libraryPath; 8987 } 8988 8989 int doPreInstall(int status) { 8990 if (status != PackageManager.INSTALL_SUCCEEDED) { 8991 // Destroy container 8992 PackageHelper.destroySdDir(cid); 8993 } else { 8994 boolean mounted = PackageHelper.isContainerMounted(cid); 8995 if (!mounted) { 8996 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 8997 Process.SYSTEM_UID); 8998 if (newCachePath != null) { 8999 setCachePath(newCachePath); 9000 } else { 9001 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9002 } 9003 } 9004 } 9005 return status; 9006 } 9007 9008 boolean doRename(int status, final String pkgName, 9009 String oldCodePath) { 9010 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 9011 String newCachePath = null; 9012 if (PackageHelper.isContainerMounted(cid)) { 9013 // Unmount the container 9014 if (!PackageHelper.unMountSdDir(cid)) { 9015 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9016 return false; 9017 } 9018 } 9019 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9020 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9021 " which might be stale. Will try to clean up."); 9022 // Clean up the stale container and proceed to recreate. 9023 if (!PackageHelper.destroySdDir(newCacheId)) { 9024 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9025 return false; 9026 } 9027 // Successfully cleaned up stale container. Try to rename again. 9028 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9029 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9030 + " inspite of cleaning it up."); 9031 return false; 9032 } 9033 } 9034 if (!PackageHelper.isContainerMounted(newCacheId)) { 9035 Slog.w(TAG, "Mounting container " + newCacheId); 9036 newCachePath = PackageHelper.mountSdDir(newCacheId, 9037 getEncryptKey(), Process.SYSTEM_UID); 9038 } else { 9039 newCachePath = PackageHelper.getSdDir(newCacheId); 9040 } 9041 if (newCachePath == null) { 9042 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9043 return false; 9044 } 9045 Log.i(TAG, "Succesfully renamed " + cid + 9046 " to " + newCacheId + 9047 " at new path: " + newCachePath); 9048 cid = newCacheId; 9049 setCachePath(newCachePath); 9050 return true; 9051 } 9052 9053 private void setCachePath(String newCachePath) { 9054 File cachePath = new File(newCachePath); 9055 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 9056 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9057 9058 if (isFwdLocked()) { 9059 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9060 } else { 9061 resourcePath = packagePath; 9062 } 9063 } 9064 9065 int doPostInstall(int status, int uid) { 9066 if (status != PackageManager.INSTALL_SUCCEEDED) { 9067 cleanUp(); 9068 } else { 9069 final int groupOwner; 9070 final String protectedFile; 9071 if (isFwdLocked()) { 9072 groupOwner = UserHandle.getSharedAppGid(uid); 9073 protectedFile = RES_FILE_NAME; 9074 } else { 9075 groupOwner = -1; 9076 protectedFile = null; 9077 } 9078 9079 if (uid < Process.FIRST_APPLICATION_UID 9080 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9081 Slog.e(TAG, "Failed to finalize " + cid); 9082 PackageHelper.destroySdDir(cid); 9083 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9084 } 9085 9086 boolean mounted = PackageHelper.isContainerMounted(cid); 9087 if (!mounted) { 9088 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9089 } 9090 } 9091 return status; 9092 } 9093 9094 private void cleanUp() { 9095 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9096 9097 // Destroy secure container 9098 PackageHelper.destroySdDir(cid); 9099 } 9100 9101 void cleanUpResourcesLI() { 9102 String sourceFile = getCodePath(); 9103 // Remove dex file 9104 if (instructionSet == null) { 9105 throw new IllegalStateException("instructionSet == null"); 9106 } 9107 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9108 if (retCode < 0) { 9109 Slog.w(TAG, "Couldn't remove dex file for package: " 9110 + " at location " 9111 + sourceFile.toString() + ", retcode=" + retCode); 9112 // we don't consider this to be a failure of the core package deletion 9113 } 9114 cleanUp(); 9115 } 9116 9117 boolean matchContainer(String app) { 9118 if (cid.startsWith(app)) { 9119 return true; 9120 } 9121 return false; 9122 } 9123 9124 String getPackageName() { 9125 return getAsecPackageName(cid); 9126 } 9127 9128 boolean doPostDeleteLI(boolean delete) { 9129 boolean ret = false; 9130 boolean mounted = PackageHelper.isContainerMounted(cid); 9131 if (mounted) { 9132 // Unmount first 9133 ret = PackageHelper.unMountSdDir(cid); 9134 } 9135 if (ret && delete) { 9136 cleanUpResourcesLI(); 9137 } 9138 return ret; 9139 } 9140 9141 @Override 9142 int doPreCopy() { 9143 if (isFwdLocked()) { 9144 if (!PackageHelper.fixSdPermissions(cid, 9145 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9146 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9147 } 9148 } 9149 9150 return PackageManager.INSTALL_SUCCEEDED; 9151 } 9152 9153 @Override 9154 int doPostCopy(int uid) { 9155 if (isFwdLocked()) { 9156 if (uid < Process.FIRST_APPLICATION_UID 9157 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9158 RES_FILE_NAME)) { 9159 Slog.e(TAG, "Failed to finalize " + cid); 9160 PackageHelper.destroySdDir(cid); 9161 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9162 } 9163 } 9164 9165 return PackageManager.INSTALL_SUCCEEDED; 9166 } 9167 }; 9168 9169 static String getAsecPackageName(String packageCid) { 9170 int idx = packageCid.lastIndexOf("-"); 9171 if (idx == -1) { 9172 return packageCid; 9173 } 9174 return packageCid.substring(0, idx); 9175 } 9176 9177 // Utility method used to create code paths based on package name and available index. 9178 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9179 String idxStr = ""; 9180 int idx = 1; 9181 // Fall back to default value of idx=1 if prefix is not 9182 // part of oldCodePath 9183 if (oldCodePath != null) { 9184 String subStr = oldCodePath; 9185 // Drop the suffix right away 9186 if (subStr.endsWith(suffix)) { 9187 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9188 } 9189 // If oldCodePath already contains prefix find out the 9190 // ending index to either increment or decrement. 9191 int sidx = subStr.lastIndexOf(prefix); 9192 if (sidx != -1) { 9193 subStr = subStr.substring(sidx + prefix.length()); 9194 if (subStr != null) { 9195 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9196 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9197 } 9198 try { 9199 idx = Integer.parseInt(subStr); 9200 if (idx <= 1) { 9201 idx++; 9202 } else { 9203 idx--; 9204 } 9205 } catch(NumberFormatException e) { 9206 } 9207 } 9208 } 9209 } 9210 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9211 return prefix + idxStr; 9212 } 9213 9214 // Utility method used to ignore ADD/REMOVE events 9215 // by directory observer. 9216 private static boolean ignoreCodePath(String fullPathStr) { 9217 String apkName = getApkName(fullPathStr); 9218 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9219 if (idx != -1 && ((idx+1) < apkName.length())) { 9220 // Make sure the package ends with a numeral 9221 String version = apkName.substring(idx+1); 9222 try { 9223 Integer.parseInt(version); 9224 return true; 9225 } catch (NumberFormatException e) {} 9226 } 9227 return false; 9228 } 9229 9230 // Utility method that returns the relative package path with respect 9231 // to the installation directory. Like say for /data/data/com.test-1.apk 9232 // string com.test-1 is returned. 9233 static String getApkName(String codePath) { 9234 if (codePath == null) { 9235 return null; 9236 } 9237 int sidx = codePath.lastIndexOf("/"); 9238 int eidx = codePath.lastIndexOf("."); 9239 if (eidx == -1) { 9240 eidx = codePath.length(); 9241 } else if (eidx == 0) { 9242 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 9243 return null; 9244 } 9245 return codePath.substring(sidx+1, eidx); 9246 } 9247 9248 class PackageInstalledInfo { 9249 String name; 9250 int uid; 9251 // The set of users that originally had this package installed. 9252 int[] origUsers; 9253 // The set of users that now have this package installed. 9254 int[] newUsers; 9255 PackageParser.Package pkg; 9256 int returnCode; 9257 PackageRemovedInfo removedInfo; 9258 9259 // In some error cases we want to convey more info back to the observer 9260 String origPackage; 9261 String origPermission; 9262 } 9263 9264 /* 9265 * Install a non-existing package. 9266 */ 9267 private void installNewPackageLI(PackageParser.Package pkg, 9268 int parseFlags, int scanMode, UserHandle user, 9269 String installerPackageName, PackageInstalledInfo res) { 9270 // Remember this for later, in case we need to rollback this install 9271 String pkgName = pkg.packageName; 9272 9273 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9274 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9275 synchronized(mPackages) { 9276 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9277 // A package with the same name is already installed, though 9278 // it has been renamed to an older name. The package we 9279 // are trying to install should be installed as an update to 9280 // the existing one, but that has not been requested, so bail. 9281 Slog.w(TAG, "Attempt to re-install " + pkgName 9282 + " without first uninstalling package running as " 9283 + mSettings.mRenamedPackages.get(pkgName)); 9284 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9285 return; 9286 } 9287 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) { 9288 // Don't allow installation over an existing package with the same name. 9289 Slog.w(TAG, "Attempt to re-install " + pkgName 9290 + " without first uninstalling."); 9291 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9292 return; 9293 } 9294 } 9295 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9296 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9297 System.currentTimeMillis(), user); 9298 if (newPackage == null) { 9299 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9300 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9301 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9302 } 9303 } else { 9304 updateSettingsLI(newPackage, 9305 installerPackageName, 9306 null, null, 9307 res); 9308 // delete the partially installed application. the data directory will have to be 9309 // restored if it was already existing 9310 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9311 // remove package from internal structures. Note that we want deletePackageX to 9312 // delete the package data and cache directories that it created in 9313 // scanPackageLocked, unless those directories existed before we even tried to 9314 // install. 9315 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9316 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9317 res.removedInfo, true); 9318 } 9319 } 9320 } 9321 9322 private void replacePackageLI(PackageParser.Package pkg, 9323 int parseFlags, int scanMode, UserHandle user, 9324 String installerPackageName, PackageInstalledInfo res) { 9325 9326 PackageParser.Package oldPackage; 9327 String pkgName = pkg.packageName; 9328 int[] allUsers; 9329 boolean[] perUserInstalled; 9330 9331 // First find the old package info and check signatures 9332 synchronized(mPackages) { 9333 oldPackage = mPackages.get(pkgName); 9334 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9335 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9336 != PackageManager.SIGNATURE_MATCH) { 9337 Slog.w(TAG, "New package has a different signature: " + pkgName); 9338 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9339 return; 9340 } 9341 9342 // In case of rollback, remember per-user/profile install state 9343 PackageSetting ps = mSettings.mPackages.get(pkgName); 9344 allUsers = sUserManager.getUserIds(); 9345 perUserInstalled = new boolean[allUsers.length]; 9346 for (int i = 0; i < allUsers.length; i++) { 9347 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9348 } 9349 } 9350 boolean sysPkg = (isSystemApp(oldPackage)); 9351 if (sysPkg) { 9352 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9353 user, allUsers, perUserInstalled, installerPackageName, res); 9354 } else { 9355 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9356 user, allUsers, perUserInstalled, installerPackageName, res); 9357 } 9358 } 9359 9360 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9361 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9362 int[] allUsers, boolean[] perUserInstalled, 9363 String installerPackageName, PackageInstalledInfo res) { 9364 PackageParser.Package newPackage = null; 9365 String pkgName = deletedPackage.packageName; 9366 boolean deletedPkg = true; 9367 boolean updatedSettings = false; 9368 9369 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9370 + deletedPackage); 9371 long origUpdateTime; 9372 if (pkg.mExtras != null) { 9373 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9374 } else { 9375 origUpdateTime = 0; 9376 } 9377 9378 // First delete the existing package while retaining the data directory 9379 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9380 res.removedInfo, true)) { 9381 // If the existing package wasn't successfully deleted 9382 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9383 deletedPkg = false; 9384 } else { 9385 // Successfully deleted the old package. Now proceed with re-installation 9386 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9387 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9388 System.currentTimeMillis(), user); 9389 if (newPackage == null) { 9390 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9391 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9392 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9393 } 9394 } else { 9395 updateSettingsLI(newPackage, 9396 installerPackageName, 9397 allUsers, perUserInstalled, 9398 res); 9399 updatedSettings = true; 9400 } 9401 } 9402 9403 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9404 // remove package from internal structures. Note that we want deletePackageX to 9405 // delete the package data and cache directories that it created in 9406 // scanPackageLocked, unless those directories existed before we even tried to 9407 // install. 9408 if(updatedSettings) { 9409 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9410 deletePackageLI( 9411 pkgName, null, true, allUsers, perUserInstalled, 9412 PackageManager.DELETE_KEEP_DATA, 9413 res.removedInfo, true); 9414 } 9415 // Since we failed to install the new package we need to restore the old 9416 // package that we deleted. 9417 if(deletedPkg) { 9418 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9419 File restoreFile = new File(deletedPackage.mPath); 9420 // Parse old package 9421 boolean oldOnSd = isExternal(deletedPackage); 9422 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9423 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9424 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9425 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 9426 | SCAN_UPDATE_TIME; 9427 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 9428 origUpdateTime, null) == null) { 9429 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 9430 return; 9431 } 9432 // Restore of old package succeeded. Update permissions. 9433 // writer 9434 synchronized (mPackages) { 9435 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9436 UPDATE_PERMISSIONS_ALL); 9437 // can downgrade to reader 9438 mSettings.writeLPr(); 9439 } 9440 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9441 } 9442 } 9443 } 9444 9445 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9446 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9447 int[] allUsers, boolean[] perUserInstalled, 9448 String installerPackageName, PackageInstalledInfo res) { 9449 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9450 + ", old=" + deletedPackage); 9451 PackageParser.Package newPackage = null; 9452 boolean updatedSettings = false; 9453 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 9454 PackageParser.PARSE_IS_SYSTEM; 9455 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9456 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9457 } 9458 String packageName = deletedPackage.packageName; 9459 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9460 if (packageName == null) { 9461 Slog.w(TAG, "Attempt to delete null packageName."); 9462 return; 9463 } 9464 PackageParser.Package oldPkg; 9465 PackageSetting oldPkgSetting; 9466 // reader 9467 synchronized (mPackages) { 9468 oldPkg = mPackages.get(packageName); 9469 oldPkgSetting = mSettings.mPackages.get(packageName); 9470 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 9471 (oldPkgSetting == null)) { 9472 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 9473 return; 9474 } 9475 } 9476 9477 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 9478 9479 res.removedInfo.uid = oldPkg.applicationInfo.uid; 9480 res.removedInfo.removedPackage = packageName; 9481 // Remove existing system package 9482 removePackageLI(oldPkgSetting, true); 9483 // writer 9484 synchronized (mPackages) { 9485 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 9486 // We didn't need to disable the .apk as a current system package, 9487 // which means we are replacing another update that is already 9488 // installed. We need to make sure to delete the older one's .apk. 9489 res.removedInfo.args = createInstallArgs(0, 9490 deletedPackage.applicationInfo.sourceDir, 9491 deletedPackage.applicationInfo.publicSourceDir, 9492 deletedPackage.applicationInfo.nativeLibraryDir, 9493 getAppInstructionSet(deletedPackage.applicationInfo)); 9494 } else { 9495 res.removedInfo.args = null; 9496 } 9497 } 9498 9499 // Successfully disabled the old package. Now proceed with re-installation 9500 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9501 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9502 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user); 9503 if (newPackage == null) { 9504 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9505 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9506 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9507 } 9508 } else { 9509 if (newPackage.mExtras != null) { 9510 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 9511 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 9512 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 9513 9514 // is the update attempting to change shared user? that isn't going to work... 9515 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 9516 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 9517 + " to " + newPkgSetting.sharedUser); 9518 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 9519 updatedSettings = true; 9520 } 9521 } 9522 9523 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9524 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9525 updatedSettings = true; 9526 } 9527 } 9528 9529 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9530 // Re installation failed. Restore old information 9531 // Remove new pkg information 9532 if (newPackage != null) { 9533 removeInstalledPackageLI(newPackage, true); 9534 } 9535 // Add back the old system package 9536 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user); 9537 // Restore the old system information in Settings 9538 synchronized(mPackages) { 9539 if (updatedSettings) { 9540 mSettings.enableSystemPackageLPw(packageName); 9541 mSettings.setInstallerPackageName(packageName, 9542 oldPkgSetting.installerPackageName); 9543 } 9544 mSettings.writeLPr(); 9545 } 9546 } 9547 } 9548 9549 // Utility method used to move dex files during install. 9550 private int moveDexFilesLI(PackageParser.Package newPackage) { 9551 int retCode; 9552 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 9553 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath, 9554 getAppInstructionSet(newPackage.applicationInfo)); 9555 if (retCode != 0) { 9556 if (mNoDexOpt) { 9557 /* 9558 * If we're in an engineering build, programs are lazily run 9559 * through dexopt. If the .dex file doesn't exist yet, it 9560 * will be created when the program is run next. 9561 */ 9562 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath); 9563 } else { 9564 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath); 9565 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9566 } 9567 } 9568 } 9569 return PackageManager.INSTALL_SUCCEEDED; 9570 } 9571 9572 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 9573 int[] allUsers, boolean[] perUserInstalled, 9574 PackageInstalledInfo res) { 9575 String pkgName = newPackage.packageName; 9576 synchronized (mPackages) { 9577 //write settings. the installStatus will be incomplete at this stage. 9578 //note that the new package setting would have already been 9579 //added to mPackages. It hasn't been persisted yet. 9580 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 9581 mSettings.writeLPr(); 9582 } 9583 9584 if ((res.returnCode = moveDexFilesLI(newPackage)) 9585 != PackageManager.INSTALL_SUCCEEDED) { 9586 // Discontinue if moving dex files failed. 9587 return; 9588 } 9589 9590 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath); 9591 9592 synchronized (mPackages) { 9593 updatePermissionsLPw(newPackage.packageName, newPackage, 9594 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 9595 ? UPDATE_PERMISSIONS_ALL : 0)); 9596 // For system-bundled packages, we assume that installing an upgraded version 9597 // of the package implies that the user actually wants to run that new code, 9598 // so we enable the package. 9599 if (isSystemApp(newPackage)) { 9600 // NB: implicit assumption that system package upgrades apply to all users 9601 if (DEBUG_INSTALL) { 9602 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 9603 } 9604 PackageSetting ps = mSettings.mPackages.get(pkgName); 9605 if (ps != null) { 9606 if (res.origUsers != null) { 9607 for (int userHandle : res.origUsers) { 9608 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 9609 userHandle, installerPackageName); 9610 } 9611 } 9612 // Also convey the prior install/uninstall state 9613 if (allUsers != null && perUserInstalled != null) { 9614 for (int i = 0; i < allUsers.length; i++) { 9615 if (DEBUG_INSTALL) { 9616 Slog.d(TAG, " user " + allUsers[i] 9617 + " => " + perUserInstalled[i]); 9618 } 9619 ps.setInstalled(perUserInstalled[i], allUsers[i]); 9620 } 9621 // these install state changes will be persisted in the 9622 // upcoming call to mSettings.writeLPr(). 9623 } 9624 } 9625 } 9626 res.name = pkgName; 9627 res.uid = newPackage.applicationInfo.uid; 9628 res.pkg = newPackage; 9629 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 9630 mSettings.setInstallerPackageName(pkgName, installerPackageName); 9631 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 9632 //to update install status 9633 mSettings.writeLPr(); 9634 } 9635 } 9636 9637 private void installPackageLI(InstallArgs args, 9638 boolean newInstall, PackageInstalledInfo res) { 9639 int pFlags = args.flags; 9640 String installerPackageName = args.installerPackageName; 9641 File tmpPackageFile = new File(args.getCodePath()); 9642 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 9643 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 9644 boolean replace = false; 9645 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 9646 | (newInstall ? SCAN_NEW_INSTALL : 0); 9647 // Result object to be returned 9648 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 9649 9650 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 9651 // Retrieve PackageSettings and parse package 9652 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 9653 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 9654 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 9655 PackageParser pp = new PackageParser(tmpPackageFile.getPath()); 9656 pp.setSeparateProcesses(mSeparateProcesses); 9657 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile, 9658 null, mMetrics, parseFlags); 9659 if (pkg == null) { 9660 res.returnCode = pp.getParseError(); 9661 return; 9662 } 9663 String pkgName = res.name = pkg.packageName; 9664 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 9665 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 9666 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 9667 return; 9668 } 9669 } 9670 if (!pp.collectCertificates(pkg, parseFlags)) { 9671 res.returnCode = pp.getParseError(); 9672 return; 9673 } 9674 9675 /* If the installer passed in a manifest digest, compare it now. */ 9676 if (args.manifestDigest != null) { 9677 if (DEBUG_INSTALL) { 9678 final String parsedManifest = pkg.manifestDigest == null ? "null" 9679 : pkg.manifestDigest.toString(); 9680 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 9681 + parsedManifest); 9682 } 9683 9684 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 9685 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 9686 return; 9687 } 9688 } else if (DEBUG_INSTALL) { 9689 final String parsedManifest = pkg.manifestDigest == null 9690 ? "null" : pkg.manifestDigest.toString(); 9691 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 9692 } 9693 9694 // Get rid of all references to package scan path via parser. 9695 pp = null; 9696 String oldCodePath = null; 9697 boolean systemApp = false; 9698 synchronized (mPackages) { 9699 // Check whether the newly-scanned package wants to define an already-defined perm 9700 int N = pkg.permissions.size(); 9701 for (int i = 0; i < N; i++) { 9702 PackageParser.Permission perm = pkg.permissions.get(i); 9703 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 9704 if (bp != null) { 9705 // If the defining package is signed with our cert, it's okay. This 9706 // also includes the "updating the same package" case, of course. 9707 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 9708 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9709 Slog.w(TAG, "Package " + pkg.packageName 9710 + " attempting to redeclare permission " + perm.info.name 9711 + " already owned by " + bp.sourcePackage); 9712 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 9713 res.origPermission = perm.info.name; 9714 res.origPackage = bp.sourcePackage; 9715 return; 9716 } 9717 } 9718 } 9719 9720 // Check if installing already existing package 9721 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9722 String oldName = mSettings.mRenamedPackages.get(pkgName); 9723 if (pkg.mOriginalPackages != null 9724 && pkg.mOriginalPackages.contains(oldName) 9725 && mPackages.containsKey(oldName)) { 9726 // This package is derived from an original package, 9727 // and this device has been updating from that original 9728 // name. We must continue using the original name, so 9729 // rename the new package here. 9730 pkg.setPackageName(oldName); 9731 pkgName = pkg.packageName; 9732 replace = true; 9733 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 9734 + oldName + " pkgName=" + pkgName); 9735 } else if (mPackages.containsKey(pkgName)) { 9736 // This package, under its official name, already exists 9737 // on the device; we should replace it. 9738 replace = true; 9739 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 9740 } 9741 } 9742 PackageSetting ps = mSettings.mPackages.get(pkgName); 9743 if (ps != null) { 9744 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 9745 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 9746 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 9747 systemApp = (ps.pkg.applicationInfo.flags & 9748 ApplicationInfo.FLAG_SYSTEM) != 0; 9749 } 9750 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 9751 } 9752 } 9753 9754 if (systemApp && onSd) { 9755 // Disable updates to system apps on sdcard 9756 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 9757 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9758 return; 9759 } 9760 9761 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 9762 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9763 return; 9764 } 9765 // Set application objects path explicitly after the rename 9766 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath()); 9767 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 9768 if (replace) { 9769 replacePackageLI(pkg, parseFlags, scanMode, args.user, 9770 installerPackageName, res); 9771 } else { 9772 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 9773 installerPackageName, res); 9774 } 9775 synchronized (mPackages) { 9776 final PackageSetting ps = mSettings.mPackages.get(pkgName); 9777 if (ps != null) { 9778 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 9779 } 9780 } 9781 } 9782 9783 private static boolean isForwardLocked(PackageParser.Package pkg) { 9784 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 9785 } 9786 9787 9788 private boolean isForwardLocked(PackageSetting ps) { 9789 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 9790 } 9791 9792 private static boolean isExternal(PackageParser.Package pkg) { 9793 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 9794 } 9795 9796 private static boolean isExternal(PackageSetting ps) { 9797 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 9798 } 9799 9800 private static boolean isSystemApp(PackageParser.Package pkg) { 9801 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9802 } 9803 9804 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 9805 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 9806 } 9807 9808 private static boolean isSystemApp(ApplicationInfo info) { 9809 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9810 } 9811 9812 private static boolean isSystemApp(PackageSetting ps) { 9813 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 9814 } 9815 9816 private static boolean isUpdatedSystemApp(PackageSetting ps) { 9817 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 9818 } 9819 9820 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 9821 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 9822 } 9823 9824 private int packageFlagsToInstallFlags(PackageSetting ps) { 9825 int installFlags = 0; 9826 if (isExternal(ps)) { 9827 installFlags |= PackageManager.INSTALL_EXTERNAL; 9828 } 9829 if (isForwardLocked(ps)) { 9830 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 9831 } 9832 return installFlags; 9833 } 9834 9835 private void deleteTempPackageFiles() { 9836 final FilenameFilter filter = new FilenameFilter() { 9837 public boolean accept(File dir, String name) { 9838 return name.startsWith("vmdl") && name.endsWith(".tmp"); 9839 } 9840 }; 9841 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 9842 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 9843 } 9844 9845 private static final void deleteTempPackageFilesInDirectory(File directory, 9846 FilenameFilter filter) { 9847 final String[] tmpFilesList = directory.list(filter); 9848 if (tmpFilesList == null) { 9849 return; 9850 } 9851 for (int i = 0; i < tmpFilesList.length; i++) { 9852 final File tmpFile = new File(directory, tmpFilesList[i]); 9853 tmpFile.delete(); 9854 } 9855 } 9856 9857 private File createTempPackageFile(File installDir) { 9858 File tmpPackageFile; 9859 try { 9860 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 9861 } catch (IOException e) { 9862 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 9863 return null; 9864 } 9865 try { 9866 FileUtils.setPermissions( 9867 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 9868 -1, -1); 9869 if (!SELinux.restorecon(tmpPackageFile)) { 9870 return null; 9871 } 9872 } catch (IOException e) { 9873 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 9874 return null; 9875 } 9876 return tmpPackageFile; 9877 } 9878 9879 @Override 9880 public void deletePackageAsUser(final String packageName, 9881 final IPackageDeleteObserver observer, 9882 final int userId, final int flags) { 9883 mContext.enforceCallingOrSelfPermission( 9884 android.Manifest.permission.DELETE_PACKAGES, null); 9885 final int uid = Binder.getCallingUid(); 9886 if (UserHandle.getUserId(uid) != userId) { 9887 mContext.enforceCallingPermission( 9888 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 9889 "deletePackage for user " + userId); 9890 } 9891 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 9892 try { 9893 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 9894 } catch (RemoteException re) { 9895 } 9896 return; 9897 } 9898 9899 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 9900 // Queue up an async operation since the package deletion may take a little while. 9901 mHandler.post(new Runnable() { 9902 public void run() { 9903 mHandler.removeCallbacks(this); 9904 final int returnCode = deletePackageX(packageName, userId, flags); 9905 if (observer != null) { 9906 try { 9907 observer.packageDeleted(packageName, returnCode); 9908 } catch (RemoteException e) { 9909 Log.i(TAG, "Observer no longer exists."); 9910 } //end catch 9911 } //end if 9912 } //end run 9913 }); 9914 } 9915 9916 private boolean isPackageDeviceAdmin(String packageName, int userId) { 9917 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 9918 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 9919 try { 9920 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 9921 || dpm.isDeviceOwner(packageName))) { 9922 return true; 9923 } 9924 } catch (RemoteException e) { 9925 } 9926 return false; 9927 } 9928 9929 /** 9930 * This method is an internal method that could be get invoked either 9931 * to delete an installed package or to clean up a failed installation. 9932 * After deleting an installed package, a broadcast is sent to notify any 9933 * listeners that the package has been installed. For cleaning up a failed 9934 * installation, the broadcast is not necessary since the package's 9935 * installation wouldn't have sent the initial broadcast either 9936 * The key steps in deleting a package are 9937 * deleting the package information in internal structures like mPackages, 9938 * deleting the packages base directories through installd 9939 * updating mSettings to reflect current status 9940 * persisting settings for later use 9941 * sending a broadcast if necessary 9942 */ 9943 private int deletePackageX(String packageName, int userId, int flags) { 9944 final PackageRemovedInfo info = new PackageRemovedInfo(); 9945 final boolean res; 9946 9947 if (isPackageDeviceAdmin(packageName, userId)) { 9948 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 9949 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 9950 } 9951 9952 boolean removedForAllUsers = false; 9953 boolean systemUpdate = false; 9954 9955 // for the uninstall-updates case and restricted profiles, remember the per- 9956 // userhandle installed state 9957 int[] allUsers; 9958 boolean[] perUserInstalled; 9959 synchronized (mPackages) { 9960 PackageSetting ps = mSettings.mPackages.get(packageName); 9961 allUsers = sUserManager.getUserIds(); 9962 perUserInstalled = new boolean[allUsers.length]; 9963 for (int i = 0; i < allUsers.length; i++) { 9964 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9965 } 9966 } 9967 9968 synchronized (mInstallLock) { 9969 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 9970 res = deletePackageLI(packageName, 9971 (flags & PackageManager.DELETE_ALL_USERS) != 0 9972 ? UserHandle.ALL : new UserHandle(userId), 9973 true, allUsers, perUserInstalled, 9974 flags | REMOVE_CHATTY, info, true); 9975 systemUpdate = info.isRemovedPackageSystemUpdate; 9976 if (res && !systemUpdate && mPackages.get(packageName) == null) { 9977 removedForAllUsers = true; 9978 } 9979 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 9980 + " removedForAllUsers=" + removedForAllUsers); 9981 } 9982 9983 if (res) { 9984 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 9985 9986 // If the removed package was a system update, the old system package 9987 // was re-enabled; we need to broadcast this information 9988 if (systemUpdate) { 9989 Bundle extras = new Bundle(1); 9990 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 9991 ? info.removedAppId : info.uid); 9992 extras.putBoolean(Intent.EXTRA_REPLACING, true); 9993 9994 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 9995 extras, null, null, null); 9996 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 9997 extras, null, null, null); 9998 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 9999 null, packageName, null, null); 10000 } 10001 } 10002 // Force a gc here. 10003 Runtime.getRuntime().gc(); 10004 // Delete the resources here after sending the broadcast to let 10005 // other processes clean up before deleting resources. 10006 if (info.args != null) { 10007 synchronized (mInstallLock) { 10008 info.args.doPostDeleteLI(true); 10009 } 10010 } 10011 10012 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10013 } 10014 10015 static class PackageRemovedInfo { 10016 String removedPackage; 10017 int uid = -1; 10018 int removedAppId = -1; 10019 int[] removedUsers = null; 10020 boolean isRemovedPackageSystemUpdate = false; 10021 // Clean up resources deleted packages. 10022 InstallArgs args = null; 10023 10024 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10025 Bundle extras = new Bundle(1); 10026 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10027 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10028 if (replacing) { 10029 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10030 } 10031 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10032 if (removedPackage != null) { 10033 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10034 extras, null, null, removedUsers); 10035 if (fullRemove && !replacing) { 10036 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10037 extras, null, null, removedUsers); 10038 } 10039 } 10040 if (removedAppId >= 0) { 10041 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10042 removedUsers); 10043 } 10044 } 10045 } 10046 10047 /* 10048 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10049 * flag is not set, the data directory is removed as well. 10050 * make sure this flag is set for partially installed apps. If not its meaningless to 10051 * delete a partially installed application. 10052 */ 10053 private void removePackageDataLI(PackageSetting ps, 10054 int[] allUserHandles, boolean[] perUserInstalled, 10055 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10056 String packageName = ps.name; 10057 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10058 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10059 // Retrieve object to delete permissions for shared user later on 10060 final PackageSetting deletedPs; 10061 // reader 10062 synchronized (mPackages) { 10063 deletedPs = mSettings.mPackages.get(packageName); 10064 if (outInfo != null) { 10065 outInfo.removedPackage = packageName; 10066 outInfo.removedUsers = deletedPs != null 10067 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10068 : null; 10069 } 10070 } 10071 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10072 removeDataDirsLI(packageName); 10073 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10074 } 10075 // writer 10076 synchronized (mPackages) { 10077 if (deletedPs != null) { 10078 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10079 if (outInfo != null) { 10080 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10081 } 10082 if (deletedPs != null) { 10083 updatePermissionsLPw(deletedPs.name, null, 0); 10084 if (deletedPs.sharedUser != null) { 10085 // remove permissions associated with package 10086 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10087 } 10088 } 10089 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10090 } 10091 // make sure to preserve per-user disabled state if this removal was just 10092 // a downgrade of a system app to the factory package 10093 if (allUserHandles != null && perUserInstalled != null) { 10094 if (DEBUG_REMOVE) { 10095 Slog.d(TAG, "Propagating install state across downgrade"); 10096 } 10097 for (int i = 0; i < allUserHandles.length; i++) { 10098 if (DEBUG_REMOVE) { 10099 Slog.d(TAG, " user " + allUserHandles[i] 10100 + " => " + perUserInstalled[i]); 10101 } 10102 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10103 } 10104 } 10105 } 10106 // can downgrade to reader 10107 if (writeSettings) { 10108 // Save settings now 10109 mSettings.writeLPr(); 10110 } 10111 } 10112 if (outInfo != null) { 10113 // A user ID was deleted here. Go through all users and remove it 10114 // from KeyStore. 10115 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10116 } 10117 } 10118 10119 static boolean locationIsPrivileged(File path) { 10120 try { 10121 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10122 .getCanonicalPath(); 10123 return path.getCanonicalPath().startsWith(privilegedAppDir); 10124 } catch (IOException e) { 10125 Slog.e(TAG, "Unable to access code path " + path); 10126 } 10127 return false; 10128 } 10129 10130 /* 10131 * Tries to delete system package. 10132 */ 10133 private boolean deleteSystemPackageLI(PackageSetting newPs, 10134 int[] allUserHandles, boolean[] perUserInstalled, 10135 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10136 final boolean applyUserRestrictions 10137 = (allUserHandles != null) && (perUserInstalled != null); 10138 PackageSetting disabledPs = null; 10139 // Confirm if the system package has been updated 10140 // An updated system app can be deleted. This will also have to restore 10141 // the system pkg from system partition 10142 // reader 10143 synchronized (mPackages) { 10144 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10145 } 10146 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10147 + " disabledPs=" + disabledPs); 10148 if (disabledPs == null) { 10149 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10150 return false; 10151 } else if (DEBUG_REMOVE) { 10152 Slog.d(TAG, "Deleting system pkg from data partition"); 10153 } 10154 if (DEBUG_REMOVE) { 10155 if (applyUserRestrictions) { 10156 Slog.d(TAG, "Remembering install states:"); 10157 for (int i = 0; i < allUserHandles.length; i++) { 10158 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10159 } 10160 } 10161 } 10162 // Delete the updated package 10163 outInfo.isRemovedPackageSystemUpdate = true; 10164 if (disabledPs.versionCode < newPs.versionCode) { 10165 // Delete data for downgrades 10166 flags &= ~PackageManager.DELETE_KEEP_DATA; 10167 } else { 10168 // Preserve data by setting flag 10169 flags |= PackageManager.DELETE_KEEP_DATA; 10170 } 10171 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10172 allUserHandles, perUserInstalled, outInfo, writeSettings); 10173 if (!ret) { 10174 return false; 10175 } 10176 // writer 10177 synchronized (mPackages) { 10178 // Reinstate the old system package 10179 mSettings.enableSystemPackageLPw(newPs.name); 10180 // Remove any native libraries from the upgraded package. 10181 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 10182 } 10183 // Install the system package 10184 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10185 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10186 if (locationIsPrivileged(disabledPs.codePath)) { 10187 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10188 } 10189 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10190 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null); 10191 10192 if (newPkg == null) { 10193 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10194 + " with error:" + mLastScanError); 10195 return false; 10196 } 10197 // writer 10198 synchronized (mPackages) { 10199 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10200 setInternalAppNativeLibraryPath(newPkg, ps); 10201 updatePermissionsLPw(newPkg.packageName, newPkg, 10202 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10203 if (applyUserRestrictions) { 10204 if (DEBUG_REMOVE) { 10205 Slog.d(TAG, "Propagating install state across reinstall"); 10206 } 10207 for (int i = 0; i < allUserHandles.length; i++) { 10208 if (DEBUG_REMOVE) { 10209 Slog.d(TAG, " user " + allUserHandles[i] 10210 + " => " + perUserInstalled[i]); 10211 } 10212 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10213 } 10214 // Regardless of writeSettings we need to ensure that this restriction 10215 // state propagation is persisted 10216 mSettings.writeAllUsersPackageRestrictionsLPr(); 10217 } 10218 // can downgrade to reader here 10219 if (writeSettings) { 10220 mSettings.writeLPr(); 10221 } 10222 } 10223 return true; 10224 } 10225 10226 private boolean deleteInstalledPackageLI(PackageSetting ps, 10227 boolean deleteCodeAndResources, int flags, 10228 int[] allUserHandles, boolean[] perUserInstalled, 10229 PackageRemovedInfo outInfo, boolean writeSettings) { 10230 if (outInfo != null) { 10231 outInfo.uid = ps.appId; 10232 } 10233 10234 // Delete package data from internal structures and also remove data if flag is set 10235 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10236 10237 // Delete application code and resources 10238 if (deleteCodeAndResources && (outInfo != null)) { 10239 outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString, 10240 ps.resourcePathString, ps.nativeLibraryPathString, 10241 getAppInstructionSetFromSettings(ps)); 10242 } 10243 return true; 10244 } 10245 10246 /* 10247 * This method handles package deletion in general 10248 */ 10249 private boolean deletePackageLI(String packageName, UserHandle user, 10250 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10251 int flags, PackageRemovedInfo outInfo, 10252 boolean writeSettings) { 10253 if (packageName == null) { 10254 Slog.w(TAG, "Attempt to delete null packageName."); 10255 return false; 10256 } 10257 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10258 PackageSetting ps; 10259 boolean dataOnly = false; 10260 int removeUser = -1; 10261 int appId = -1; 10262 synchronized (mPackages) { 10263 ps = mSettings.mPackages.get(packageName); 10264 if (ps == null) { 10265 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10266 return false; 10267 } 10268 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10269 && user.getIdentifier() != UserHandle.USER_ALL) { 10270 // The caller is asking that the package only be deleted for a single 10271 // user. To do this, we just mark its uninstalled state and delete 10272 // its data. If this is a system app, we only allow this to happen if 10273 // they have set the special DELETE_SYSTEM_APP which requests different 10274 // semantics than normal for uninstalling system apps. 10275 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10276 ps.setUserState(user.getIdentifier(), 10277 COMPONENT_ENABLED_STATE_DEFAULT, 10278 false, //installed 10279 true, //stopped 10280 true, //notLaunched 10281 false, //blocked 10282 null, null, null); 10283 if (!isSystemApp(ps)) { 10284 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10285 // Other user still have this package installed, so all 10286 // we need to do is clear this user's data and save that 10287 // it is uninstalled. 10288 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10289 removeUser = user.getIdentifier(); 10290 appId = ps.appId; 10291 mSettings.writePackageRestrictionsLPr(removeUser); 10292 } else { 10293 // We need to set it back to 'installed' so the uninstall 10294 // broadcasts will be sent correctly. 10295 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10296 ps.setInstalled(true, user.getIdentifier()); 10297 } 10298 } else { 10299 // This is a system app, so we assume that the 10300 // other users still have this package installed, so all 10301 // we need to do is clear this user's data and save that 10302 // it is uninstalled. 10303 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10304 removeUser = user.getIdentifier(); 10305 appId = ps.appId; 10306 mSettings.writePackageRestrictionsLPr(removeUser); 10307 } 10308 } 10309 } 10310 10311 if (removeUser >= 0) { 10312 // From above, we determined that we are deleting this only 10313 // for a single user. Continue the work here. 10314 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10315 if (outInfo != null) { 10316 outInfo.removedPackage = packageName; 10317 outInfo.removedAppId = appId; 10318 outInfo.removedUsers = new int[] {removeUser}; 10319 } 10320 mInstaller.clearUserData(packageName, removeUser); 10321 removeKeystoreDataIfNeeded(removeUser, appId); 10322 schedulePackageCleaning(packageName, removeUser, false); 10323 return true; 10324 } 10325 10326 if (dataOnly) { 10327 // Delete application data first 10328 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10329 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10330 return true; 10331 } 10332 10333 boolean ret = false; 10334 mSettings.mKeySetManager.removeAppKeySetData(packageName); 10335 if (isSystemApp(ps)) { 10336 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10337 // When an updated system application is deleted we delete the existing resources as well and 10338 // fall back to existing code in system partition 10339 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10340 flags, outInfo, writeSettings); 10341 } else { 10342 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10343 // Kill application pre-emptively especially for apps on sd. 10344 killApplication(packageName, ps.appId, "uninstall pkg"); 10345 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10346 allUserHandles, perUserInstalled, 10347 outInfo, writeSettings); 10348 } 10349 10350 return ret; 10351 } 10352 10353 private final class ClearStorageConnection implements ServiceConnection { 10354 IMediaContainerService mContainerService; 10355 10356 @Override 10357 public void onServiceConnected(ComponentName name, IBinder service) { 10358 synchronized (this) { 10359 mContainerService = IMediaContainerService.Stub.asInterface(service); 10360 notifyAll(); 10361 } 10362 } 10363 10364 @Override 10365 public void onServiceDisconnected(ComponentName name) { 10366 } 10367 } 10368 10369 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10370 final boolean mounted; 10371 if (Environment.isExternalStorageEmulated()) { 10372 mounted = true; 10373 } else { 10374 final String status = Environment.getExternalStorageState(); 10375 10376 mounted = status.equals(Environment.MEDIA_MOUNTED) 10377 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10378 } 10379 10380 if (!mounted) { 10381 return; 10382 } 10383 10384 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10385 int[] users; 10386 if (userId == UserHandle.USER_ALL) { 10387 users = sUserManager.getUserIds(); 10388 } else { 10389 users = new int[] { userId }; 10390 } 10391 final ClearStorageConnection conn = new ClearStorageConnection(); 10392 if (mContext.bindServiceAsUser( 10393 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10394 try { 10395 for (int curUser : users) { 10396 long timeout = SystemClock.uptimeMillis() + 5000; 10397 synchronized (conn) { 10398 long now = SystemClock.uptimeMillis(); 10399 while (conn.mContainerService == null && now < timeout) { 10400 try { 10401 conn.wait(timeout - now); 10402 } catch (InterruptedException e) { 10403 } 10404 } 10405 } 10406 if (conn.mContainerService == null) { 10407 return; 10408 } 10409 10410 final UserEnvironment userEnv = new UserEnvironment(curUser); 10411 clearDirectory(conn.mContainerService, 10412 userEnv.buildExternalStorageAppCacheDirs(packageName)); 10413 if (allData) { 10414 clearDirectory(conn.mContainerService, 10415 userEnv.buildExternalStorageAppDataDirs(packageName)); 10416 clearDirectory(conn.mContainerService, 10417 userEnv.buildExternalStorageAppMediaDirs(packageName)); 10418 } 10419 } 10420 } finally { 10421 mContext.unbindService(conn); 10422 } 10423 } 10424 } 10425 10426 @Override 10427 public void clearApplicationUserData(final String packageName, 10428 final IPackageDataObserver observer, final int userId) { 10429 mContext.enforceCallingOrSelfPermission( 10430 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 10431 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 10432 // Queue up an async operation since the package deletion may take a little while. 10433 mHandler.post(new Runnable() { 10434 public void run() { 10435 mHandler.removeCallbacks(this); 10436 final boolean succeeded; 10437 synchronized (mInstallLock) { 10438 succeeded = clearApplicationUserDataLI(packageName, userId); 10439 } 10440 clearExternalStorageDataSync(packageName, userId, true); 10441 if (succeeded) { 10442 // invoke DeviceStorageMonitor's update method to clear any notifications 10443 DeviceStorageMonitorInternal 10444 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 10445 if (dsm != null) { 10446 dsm.checkMemory(); 10447 } 10448 } 10449 if(observer != null) { 10450 try { 10451 observer.onRemoveCompleted(packageName, succeeded); 10452 } catch (RemoteException e) { 10453 Log.i(TAG, "Observer no longer exists."); 10454 } 10455 } //end if observer 10456 } //end run 10457 }); 10458 } 10459 10460 private boolean clearApplicationUserDataLI(String packageName, int userId) { 10461 if (packageName == null) { 10462 Slog.w(TAG, "Attempt to delete null packageName."); 10463 return false; 10464 } 10465 PackageParser.Package p; 10466 boolean dataOnly = false; 10467 final int appId; 10468 synchronized (mPackages) { 10469 p = mPackages.get(packageName); 10470 if (p == null) { 10471 dataOnly = true; 10472 PackageSetting ps = mSettings.mPackages.get(packageName); 10473 if ((ps == null) || (ps.pkg == null)) { 10474 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10475 return false; 10476 } 10477 p = ps.pkg; 10478 } 10479 if (!dataOnly) { 10480 // need to check this only for fully installed applications 10481 if (p == null) { 10482 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10483 return false; 10484 } 10485 final ApplicationInfo applicationInfo = p.applicationInfo; 10486 if (applicationInfo == null) { 10487 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10488 return false; 10489 } 10490 } 10491 if (p != null && p.applicationInfo != null) { 10492 appId = p.applicationInfo.uid; 10493 } else { 10494 appId = -1; 10495 } 10496 } 10497 int retCode = mInstaller.clearUserData(packageName, userId); 10498 if (retCode < 0) { 10499 Slog.w(TAG, "Couldn't remove cache files for package: " 10500 + packageName); 10501 return false; 10502 } 10503 removeKeystoreDataIfNeeded(userId, appId); 10504 return true; 10505 } 10506 10507 /** 10508 * Remove entries from the keystore daemon. Will only remove it if the 10509 * {@code appId} is valid. 10510 */ 10511 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 10512 if (appId < 0) { 10513 return; 10514 } 10515 10516 final KeyStore keyStore = KeyStore.getInstance(); 10517 if (keyStore != null) { 10518 if (userId == UserHandle.USER_ALL) { 10519 for (final int individual : sUserManager.getUserIds()) { 10520 keyStore.clearUid(UserHandle.getUid(individual, appId)); 10521 } 10522 } else { 10523 keyStore.clearUid(UserHandle.getUid(userId, appId)); 10524 } 10525 } else { 10526 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 10527 } 10528 } 10529 10530 public void deleteApplicationCacheFiles(final String packageName, 10531 final IPackageDataObserver observer) { 10532 mContext.enforceCallingOrSelfPermission( 10533 android.Manifest.permission.DELETE_CACHE_FILES, null); 10534 // Queue up an async operation since the package deletion may take a little while. 10535 final int userId = UserHandle.getCallingUserId(); 10536 mHandler.post(new Runnable() { 10537 public void run() { 10538 mHandler.removeCallbacks(this); 10539 final boolean succeded; 10540 synchronized (mInstallLock) { 10541 succeded = deleteApplicationCacheFilesLI(packageName, userId); 10542 } 10543 clearExternalStorageDataSync(packageName, userId, false); 10544 if(observer != null) { 10545 try { 10546 observer.onRemoveCompleted(packageName, succeded); 10547 } catch (RemoteException e) { 10548 Log.i(TAG, "Observer no longer exists."); 10549 } 10550 } //end if observer 10551 } //end run 10552 }); 10553 } 10554 10555 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 10556 if (packageName == null) { 10557 Slog.w(TAG, "Attempt to delete null packageName."); 10558 return false; 10559 } 10560 PackageParser.Package p; 10561 synchronized (mPackages) { 10562 p = mPackages.get(packageName); 10563 } 10564 if (p == null) { 10565 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 10566 return false; 10567 } 10568 final ApplicationInfo applicationInfo = p.applicationInfo; 10569 if (applicationInfo == null) { 10570 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10571 return false; 10572 } 10573 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 10574 if (retCode < 0) { 10575 Slog.w(TAG, "Couldn't remove cache files for package: " 10576 + packageName + " u" + userId); 10577 return false; 10578 } 10579 return true; 10580 } 10581 10582 public void getPackageSizeInfo(final String packageName, int userHandle, 10583 final IPackageStatsObserver observer) { 10584 mContext.enforceCallingOrSelfPermission( 10585 android.Manifest.permission.GET_PACKAGE_SIZE, null); 10586 if (packageName == null) { 10587 throw new IllegalArgumentException("Attempt to get size of null packageName"); 10588 } 10589 10590 PackageStats stats = new PackageStats(packageName, userHandle); 10591 10592 /* 10593 * Queue up an async operation since the package measurement may take a 10594 * little while. 10595 */ 10596 Message msg = mHandler.obtainMessage(INIT_COPY); 10597 msg.obj = new MeasureParams(stats, observer); 10598 mHandler.sendMessage(msg); 10599 } 10600 10601 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 10602 PackageStats pStats) { 10603 if (packageName == null) { 10604 Slog.w(TAG, "Attempt to get size of null packageName."); 10605 return false; 10606 } 10607 PackageParser.Package p; 10608 boolean dataOnly = false; 10609 String libDirPath = null; 10610 String asecPath = null; 10611 PackageSetting ps = null; 10612 synchronized (mPackages) { 10613 p = mPackages.get(packageName); 10614 ps = mSettings.mPackages.get(packageName); 10615 if(p == null) { 10616 dataOnly = true; 10617 if((ps == null) || (ps.pkg == null)) { 10618 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 10619 return false; 10620 } 10621 p = ps.pkg; 10622 } 10623 if (ps != null) { 10624 libDirPath = ps.nativeLibraryPathString; 10625 } 10626 if (p != null && (isExternal(p) || isForwardLocked(p))) { 10627 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 10628 if (secureContainerId != null) { 10629 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 10630 } 10631 } 10632 } 10633 String publicSrcDir = null; 10634 if(!dataOnly) { 10635 final ApplicationInfo applicationInfo = p.applicationInfo; 10636 if (applicationInfo == null) { 10637 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10638 return false; 10639 } 10640 if (isForwardLocked(p)) { 10641 publicSrcDir = applicationInfo.publicSourceDir; 10642 } 10643 } 10644 int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath, 10645 publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps), 10646 pStats); 10647 if (res < 0) { 10648 return false; 10649 } 10650 10651 // Fix-up for forward-locked applications in ASEC containers. 10652 if (!isExternal(p)) { 10653 pStats.codeSize += pStats.externalCodeSize; 10654 pStats.externalCodeSize = 0L; 10655 } 10656 10657 return true; 10658 } 10659 10660 10661 public void addPackageToPreferred(String packageName) { 10662 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 10663 } 10664 10665 public void removePackageFromPreferred(String packageName) { 10666 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 10667 } 10668 10669 public List<PackageInfo> getPreferredPackages(int flags) { 10670 return new ArrayList<PackageInfo>(); 10671 } 10672 10673 private int getUidTargetSdkVersionLockedLPr(int uid) { 10674 Object obj = mSettings.getUserIdLPr(uid); 10675 if (obj instanceof SharedUserSetting) { 10676 final SharedUserSetting sus = (SharedUserSetting) obj; 10677 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 10678 final Iterator<PackageSetting> it = sus.packages.iterator(); 10679 while (it.hasNext()) { 10680 final PackageSetting ps = it.next(); 10681 if (ps.pkg != null) { 10682 int v = ps.pkg.applicationInfo.targetSdkVersion; 10683 if (v < vers) vers = v; 10684 } 10685 } 10686 return vers; 10687 } else if (obj instanceof PackageSetting) { 10688 final PackageSetting ps = (PackageSetting) obj; 10689 if (ps.pkg != null) { 10690 return ps.pkg.applicationInfo.targetSdkVersion; 10691 } 10692 } 10693 return Build.VERSION_CODES.CUR_DEVELOPMENT; 10694 } 10695 10696 public void addPreferredActivity(IntentFilter filter, int match, 10697 ComponentName[] set, ComponentName activity, int userId) { 10698 addPreferredActivityInternal(filter, match, set, activity, true, userId); 10699 } 10700 10701 private void addPreferredActivityInternal(IntentFilter filter, int match, 10702 ComponentName[] set, ComponentName activity, boolean always, int userId) { 10703 // writer 10704 int callingUid = Binder.getCallingUid(); 10705 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 10706 if (filter.countActions() == 0) { 10707 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 10708 return; 10709 } 10710 synchronized (mPackages) { 10711 if (mContext.checkCallingOrSelfPermission( 10712 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10713 != PackageManager.PERMISSION_GRANTED) { 10714 if (getUidTargetSdkVersionLockedLPr(callingUid) 10715 < Build.VERSION_CODES.FROYO) { 10716 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 10717 + callingUid); 10718 return; 10719 } 10720 mContext.enforceCallingOrSelfPermission( 10721 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10722 } 10723 10724 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 10725 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10726 mSettings.editPreferredActivitiesLPw(userId).addFilter( 10727 new PreferredActivity(filter, match, set, activity, always)); 10728 mSettings.writePackageRestrictionsLPr(userId); 10729 } 10730 } 10731 10732 public void replacePreferredActivity(IntentFilter filter, int match, 10733 ComponentName[] set, ComponentName activity) { 10734 if (filter.countActions() != 1) { 10735 throw new IllegalArgumentException( 10736 "replacePreferredActivity expects filter to have only 1 action."); 10737 } 10738 if (filter.countDataAuthorities() != 0 10739 || filter.countDataPaths() != 0 10740 || filter.countDataSchemes() > 1 10741 || filter.countDataTypes() != 0) { 10742 throw new IllegalArgumentException( 10743 "replacePreferredActivity expects filter to have no data authorities, " + 10744 "paths, or types; and at most one scheme."); 10745 } 10746 synchronized (mPackages) { 10747 if (mContext.checkCallingOrSelfPermission( 10748 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10749 != PackageManager.PERMISSION_GRANTED) { 10750 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 10751 < Build.VERSION_CODES.FROYO) { 10752 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 10753 + Binder.getCallingUid()); 10754 return; 10755 } 10756 mContext.enforceCallingOrSelfPermission( 10757 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10758 } 10759 10760 final int callingUserId = UserHandle.getCallingUserId(); 10761 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 10762 if (pir != null) { 10763 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 10764 if (filter.countDataSchemes() == 1) { 10765 Uri.Builder builder = new Uri.Builder(); 10766 builder.scheme(filter.getDataScheme(0)); 10767 intent.setData(builder.build()); 10768 } 10769 List<PreferredActivity> matches = pir.queryIntent( 10770 intent, null, true, callingUserId); 10771 if (DEBUG_PREFERRED) { 10772 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 10773 } 10774 for (int i = 0; i < matches.size(); i++) { 10775 PreferredActivity pa = matches.get(i); 10776 if (DEBUG_PREFERRED) { 10777 Slog.i(TAG, "Removing preferred activity " 10778 + pa.mPref.mComponent + ":"); 10779 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10780 } 10781 pir.removeFilter(pa); 10782 } 10783 } 10784 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 10785 } 10786 } 10787 10788 public void clearPackagePreferredActivities(String packageName) { 10789 final int uid = Binder.getCallingUid(); 10790 // writer 10791 synchronized (mPackages) { 10792 PackageParser.Package pkg = mPackages.get(packageName); 10793 if (pkg == null || pkg.applicationInfo.uid != uid) { 10794 if (mContext.checkCallingOrSelfPermission( 10795 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10796 != PackageManager.PERMISSION_GRANTED) { 10797 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 10798 < Build.VERSION_CODES.FROYO) { 10799 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 10800 + Binder.getCallingUid()); 10801 return; 10802 } 10803 mContext.enforceCallingOrSelfPermission( 10804 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10805 } 10806 } 10807 10808 int user = UserHandle.getCallingUserId(); 10809 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 10810 mSettings.writePackageRestrictionsLPr(user); 10811 scheduleWriteSettingsLocked(); 10812 } 10813 } 10814 } 10815 10816 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 10817 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 10818 ArrayList<PreferredActivity> removed = null; 10819 boolean changed = false; 10820 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 10821 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 10822 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 10823 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 10824 continue; 10825 } 10826 Iterator<PreferredActivity> it = pir.filterIterator(); 10827 while (it.hasNext()) { 10828 PreferredActivity pa = it.next(); 10829 // Mark entry for removal only if it matches the package name 10830 // and the entry is of type "always". 10831 if (packageName == null || 10832 (pa.mPref.mComponent.getPackageName().equals(packageName) 10833 && pa.mPref.mAlways)) { 10834 if (removed == null) { 10835 removed = new ArrayList<PreferredActivity>(); 10836 } 10837 removed.add(pa); 10838 } 10839 } 10840 if (removed != null) { 10841 for (int j=0; j<removed.size(); j++) { 10842 PreferredActivity pa = removed.get(j); 10843 pir.removeFilter(pa); 10844 } 10845 changed = true; 10846 } 10847 } 10848 return changed; 10849 } 10850 10851 public void resetPreferredActivities(int userId) { 10852 mContext.enforceCallingOrSelfPermission( 10853 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10854 // writer 10855 synchronized (mPackages) { 10856 int user = UserHandle.getCallingUserId(); 10857 clearPackagePreferredActivitiesLPw(null, user); 10858 mSettings.readDefaultPreferredAppsLPw(this, user); 10859 mSettings.writePackageRestrictionsLPr(user); 10860 scheduleWriteSettingsLocked(); 10861 } 10862 } 10863 10864 public int getPreferredActivities(List<IntentFilter> outFilters, 10865 List<ComponentName> outActivities, String packageName) { 10866 10867 int num = 0; 10868 final int userId = UserHandle.getCallingUserId(); 10869 // reader 10870 synchronized (mPackages) { 10871 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 10872 if (pir != null) { 10873 final Iterator<PreferredActivity> it = pir.filterIterator(); 10874 while (it.hasNext()) { 10875 final PreferredActivity pa = it.next(); 10876 if (packageName == null 10877 || (pa.mPref.mComponent.getPackageName().equals(packageName) 10878 && pa.mPref.mAlways)) { 10879 if (outFilters != null) { 10880 outFilters.add(new IntentFilter(pa)); 10881 } 10882 if (outActivities != null) { 10883 outActivities.add(pa.mPref.mComponent); 10884 } 10885 } 10886 } 10887 } 10888 } 10889 10890 return num; 10891 } 10892 10893 @Override 10894 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 10895 int userId) { 10896 int callingUid = Binder.getCallingUid(); 10897 if (callingUid != Process.SYSTEM_UID) { 10898 throw new SecurityException( 10899 "addPersistentPreferredActivity can only be run by the system"); 10900 } 10901 if (filter.countActions() == 0) { 10902 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 10903 return; 10904 } 10905 synchronized (mPackages) { 10906 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 10907 " :"); 10908 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10909 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 10910 new PersistentPreferredActivity(filter, activity)); 10911 mSettings.writePackageRestrictionsLPr(userId); 10912 } 10913 } 10914 10915 @Override 10916 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 10917 int callingUid = Binder.getCallingUid(); 10918 if (callingUid != Process.SYSTEM_UID) { 10919 throw new SecurityException( 10920 "clearPackagePersistentPreferredActivities can only be run by the system"); 10921 } 10922 ArrayList<PersistentPreferredActivity> removed = null; 10923 boolean changed = false; 10924 synchronized (mPackages) { 10925 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 10926 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 10927 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 10928 .valueAt(i); 10929 if (userId != thisUserId) { 10930 continue; 10931 } 10932 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 10933 while (it.hasNext()) { 10934 PersistentPreferredActivity ppa = it.next(); 10935 // Mark entry for removal only if it matches the package name. 10936 if (ppa.mComponent.getPackageName().equals(packageName)) { 10937 if (removed == null) { 10938 removed = new ArrayList<PersistentPreferredActivity>(); 10939 } 10940 removed.add(ppa); 10941 } 10942 } 10943 if (removed != null) { 10944 for (int j=0; j<removed.size(); j++) { 10945 PersistentPreferredActivity ppa = removed.get(j); 10946 ppir.removeFilter(ppa); 10947 } 10948 changed = true; 10949 } 10950 } 10951 10952 if (changed) { 10953 mSettings.writePackageRestrictionsLPr(userId); 10954 } 10955 } 10956 } 10957 10958 @Override 10959 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 10960 Intent intent = new Intent(Intent.ACTION_MAIN); 10961 intent.addCategory(Intent.CATEGORY_HOME); 10962 10963 final int callingUserId = UserHandle.getCallingUserId(); 10964 List<ResolveInfo> list = queryIntentActivities(intent, null, 10965 PackageManager.GET_META_DATA, callingUserId); 10966 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 10967 true, false, false, callingUserId); 10968 10969 allHomeCandidates.clear(); 10970 if (list != null) { 10971 for (ResolveInfo ri : list) { 10972 allHomeCandidates.add(ri); 10973 } 10974 } 10975 return (preferred == null || preferred.activityInfo == null) 10976 ? null 10977 : new ComponentName(preferred.activityInfo.packageName, 10978 preferred.activityInfo.name); 10979 } 10980 10981 @Override 10982 public void setApplicationEnabledSetting(String appPackageName, 10983 int newState, int flags, int userId, String callingPackage) { 10984 if (!sUserManager.exists(userId)) return; 10985 if (callingPackage == null) { 10986 callingPackage = Integer.toString(Binder.getCallingUid()); 10987 } 10988 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 10989 } 10990 10991 @Override 10992 public void setComponentEnabledSetting(ComponentName componentName, 10993 int newState, int flags, int userId) { 10994 if (!sUserManager.exists(userId)) return; 10995 setEnabledSetting(componentName.getPackageName(), 10996 componentName.getClassName(), newState, flags, userId, null); 10997 } 10998 10999 private void setEnabledSetting(final String packageName, String className, int newState, 11000 final int flags, int userId, String callingPackage) { 11001 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11002 || newState == COMPONENT_ENABLED_STATE_ENABLED 11003 || newState == COMPONENT_ENABLED_STATE_DISABLED 11004 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11005 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11006 throw new IllegalArgumentException("Invalid new component state: " 11007 + newState); 11008 } 11009 PackageSetting pkgSetting; 11010 final int uid = Binder.getCallingUid(); 11011 final int permission = mContext.checkCallingOrSelfPermission( 11012 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11013 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11014 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11015 boolean sendNow = false; 11016 boolean isApp = (className == null); 11017 String componentName = isApp ? packageName : className; 11018 int packageUid = -1; 11019 ArrayList<String> components; 11020 11021 // writer 11022 synchronized (mPackages) { 11023 pkgSetting = mSettings.mPackages.get(packageName); 11024 if (pkgSetting == null) { 11025 if (className == null) { 11026 throw new IllegalArgumentException( 11027 "Unknown package: " + packageName); 11028 } 11029 throw new IllegalArgumentException( 11030 "Unknown component: " + packageName 11031 + "/" + className); 11032 } 11033 // Allow root and verify that userId is not being specified by a different user 11034 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11035 throw new SecurityException( 11036 "Permission Denial: attempt to change component state from pid=" 11037 + Binder.getCallingPid() 11038 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11039 } 11040 if (className == null) { 11041 // We're dealing with an application/package level state change 11042 if (pkgSetting.getEnabled(userId) == newState) { 11043 // Nothing to do 11044 return; 11045 } 11046 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11047 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11048 // Don't care about who enables an app. 11049 callingPackage = null; 11050 } 11051 pkgSetting.setEnabled(newState, userId, callingPackage); 11052 // pkgSetting.pkg.mSetEnabled = newState; 11053 } else { 11054 // We're dealing with a component level state change 11055 // First, verify that this is a valid class name. 11056 PackageParser.Package pkg = pkgSetting.pkg; 11057 if (pkg == null || !pkg.hasComponentClassName(className)) { 11058 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11059 throw new IllegalArgumentException("Component class " + className 11060 + " does not exist in " + packageName); 11061 } else { 11062 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11063 + className + " does not exist in " + packageName); 11064 } 11065 } 11066 switch (newState) { 11067 case COMPONENT_ENABLED_STATE_ENABLED: 11068 if (!pkgSetting.enableComponentLPw(className, userId)) { 11069 return; 11070 } 11071 break; 11072 case COMPONENT_ENABLED_STATE_DISABLED: 11073 if (!pkgSetting.disableComponentLPw(className, userId)) { 11074 return; 11075 } 11076 break; 11077 case COMPONENT_ENABLED_STATE_DEFAULT: 11078 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11079 return; 11080 } 11081 break; 11082 default: 11083 Slog.e(TAG, "Invalid new component state: " + newState); 11084 return; 11085 } 11086 } 11087 mSettings.writePackageRestrictionsLPr(userId); 11088 components = mPendingBroadcasts.get(userId, packageName); 11089 final boolean newPackage = components == null; 11090 if (newPackage) { 11091 components = new ArrayList<String>(); 11092 } 11093 if (!components.contains(componentName)) { 11094 components.add(componentName); 11095 } 11096 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11097 sendNow = true; 11098 // Purge entry from pending broadcast list if another one exists already 11099 // since we are sending one right away. 11100 mPendingBroadcasts.remove(userId, packageName); 11101 } else { 11102 if (newPackage) { 11103 mPendingBroadcasts.put(userId, packageName, components); 11104 } 11105 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11106 // Schedule a message 11107 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11108 } 11109 } 11110 } 11111 11112 long callingId = Binder.clearCallingIdentity(); 11113 try { 11114 if (sendNow) { 11115 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11116 sendPackageChangedBroadcast(packageName, 11117 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11118 } 11119 } finally { 11120 Binder.restoreCallingIdentity(callingId); 11121 } 11122 } 11123 11124 private void sendPackageChangedBroadcast(String packageName, 11125 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11126 if (DEBUG_INSTALL) 11127 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11128 + componentNames); 11129 Bundle extras = new Bundle(4); 11130 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11131 String nameList[] = new String[componentNames.size()]; 11132 componentNames.toArray(nameList); 11133 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11134 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11135 extras.putInt(Intent.EXTRA_UID, packageUid); 11136 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11137 new int[] {UserHandle.getUserId(packageUid)}); 11138 } 11139 11140 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11141 if (!sUserManager.exists(userId)) return; 11142 final int uid = Binder.getCallingUid(); 11143 final int permission = mContext.checkCallingOrSelfPermission( 11144 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11145 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11146 enforceCrossUserPermission(uid, userId, true, "stop package"); 11147 // writer 11148 synchronized (mPackages) { 11149 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11150 uid, userId)) { 11151 scheduleWritePackageRestrictionsLocked(userId); 11152 } 11153 } 11154 } 11155 11156 public String getInstallerPackageName(String packageName) { 11157 // reader 11158 synchronized (mPackages) { 11159 return mSettings.getInstallerPackageNameLPr(packageName); 11160 } 11161 } 11162 11163 @Override 11164 public int getApplicationEnabledSetting(String packageName, int userId) { 11165 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11166 int uid = Binder.getCallingUid(); 11167 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11168 // reader 11169 synchronized (mPackages) { 11170 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11171 } 11172 } 11173 11174 @Override 11175 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11176 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11177 int uid = Binder.getCallingUid(); 11178 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11179 // reader 11180 synchronized (mPackages) { 11181 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11182 } 11183 } 11184 11185 public void enterSafeMode() { 11186 enforceSystemOrRoot("Only the system can request entering safe mode"); 11187 11188 if (!mSystemReady) { 11189 mSafeMode = true; 11190 } 11191 } 11192 11193 public void systemReady() { 11194 mSystemReady = true; 11195 11196 // Read the compatibilty setting when the system is ready. 11197 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11198 mContext.getContentResolver(), 11199 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11200 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11201 if (DEBUG_SETTINGS) { 11202 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11203 } 11204 11205 synchronized (mPackages) { 11206 // Verify that all of the preferred activity components actually 11207 // exist. It is possible for applications to be updated and at 11208 // that point remove a previously declared activity component that 11209 // had been set as a preferred activity. We try to clean this up 11210 // the next time we encounter that preferred activity, but it is 11211 // possible for the user flow to never be able to return to that 11212 // situation so here we do a sanity check to make sure we haven't 11213 // left any junk around. 11214 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11215 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11216 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11217 removed.clear(); 11218 for (PreferredActivity pa : pir.filterSet()) { 11219 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11220 removed.add(pa); 11221 } 11222 } 11223 if (removed.size() > 0) { 11224 for (int j=0; j<removed.size(); j++) { 11225 PreferredActivity pa = removed.get(i); 11226 Slog.w(TAG, "Removing dangling preferred activity: " 11227 + pa.mPref.mComponent); 11228 pir.removeFilter(pa); 11229 } 11230 mSettings.writePackageRestrictionsLPr( 11231 mSettings.mPreferredActivities.keyAt(i)); 11232 } 11233 } 11234 } 11235 sUserManager.systemReady(); 11236 } 11237 11238 public boolean isSafeMode() { 11239 return mSafeMode; 11240 } 11241 11242 public boolean hasSystemUidErrors() { 11243 return mHasSystemUidErrors; 11244 } 11245 11246 static String arrayToString(int[] array) { 11247 StringBuffer buf = new StringBuffer(128); 11248 buf.append('['); 11249 if (array != null) { 11250 for (int i=0; i<array.length; i++) { 11251 if (i > 0) buf.append(", "); 11252 buf.append(array[i]); 11253 } 11254 } 11255 buf.append(']'); 11256 return buf.toString(); 11257 } 11258 11259 static class DumpState { 11260 public static final int DUMP_LIBS = 1 << 0; 11261 11262 public static final int DUMP_FEATURES = 1 << 1; 11263 11264 public static final int DUMP_RESOLVERS = 1 << 2; 11265 11266 public static final int DUMP_PERMISSIONS = 1 << 3; 11267 11268 public static final int DUMP_PACKAGES = 1 << 4; 11269 11270 public static final int DUMP_SHARED_USERS = 1 << 5; 11271 11272 public static final int DUMP_MESSAGES = 1 << 6; 11273 11274 public static final int DUMP_PROVIDERS = 1 << 7; 11275 11276 public static final int DUMP_VERIFIERS = 1 << 8; 11277 11278 public static final int DUMP_PREFERRED = 1 << 9; 11279 11280 public static final int DUMP_PREFERRED_XML = 1 << 10; 11281 11282 public static final int DUMP_KEYSETS = 1 << 11; 11283 11284 public static final int DUMP_VERSION = 1 << 12; 11285 11286 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11287 11288 private int mTypes; 11289 11290 private int mOptions; 11291 11292 private boolean mTitlePrinted; 11293 11294 private SharedUserSetting mSharedUser; 11295 11296 public boolean isDumping(int type) { 11297 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11298 return true; 11299 } 11300 11301 return (mTypes & type) != 0; 11302 } 11303 11304 public void setDump(int type) { 11305 mTypes |= type; 11306 } 11307 11308 public boolean isOptionEnabled(int option) { 11309 return (mOptions & option) != 0; 11310 } 11311 11312 public void setOptionEnabled(int option) { 11313 mOptions |= option; 11314 } 11315 11316 public boolean onTitlePrinted() { 11317 final boolean printed = mTitlePrinted; 11318 mTitlePrinted = true; 11319 return printed; 11320 } 11321 11322 public boolean getTitlePrinted() { 11323 return mTitlePrinted; 11324 } 11325 11326 public void setTitlePrinted(boolean enabled) { 11327 mTitlePrinted = enabled; 11328 } 11329 11330 public SharedUserSetting getSharedUser() { 11331 return mSharedUser; 11332 } 11333 11334 public void setSharedUser(SharedUserSetting user) { 11335 mSharedUser = user; 11336 } 11337 } 11338 11339 @Override 11340 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 11341 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 11342 != PackageManager.PERMISSION_GRANTED) { 11343 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 11344 + Binder.getCallingPid() 11345 + ", uid=" + Binder.getCallingUid() 11346 + " without permission " 11347 + android.Manifest.permission.DUMP); 11348 return; 11349 } 11350 11351 DumpState dumpState = new DumpState(); 11352 boolean fullPreferred = false; 11353 boolean checkin = false; 11354 11355 String packageName = null; 11356 11357 int opti = 0; 11358 while (opti < args.length) { 11359 String opt = args[opti]; 11360 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 11361 break; 11362 } 11363 opti++; 11364 if ("-a".equals(opt)) { 11365 // Right now we only know how to print all. 11366 } else if ("-h".equals(opt)) { 11367 pw.println("Package manager dump options:"); 11368 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 11369 pw.println(" --checkin: dump for a checkin"); 11370 pw.println(" -f: print details of intent filters"); 11371 pw.println(" -h: print this help"); 11372 pw.println(" cmd may be one of:"); 11373 pw.println(" l[ibraries]: list known shared libraries"); 11374 pw.println(" f[ibraries]: list device features"); 11375 pw.println(" r[esolvers]: dump intent resolvers"); 11376 pw.println(" perm[issions]: dump permissions"); 11377 pw.println(" pref[erred]: print preferred package settings"); 11378 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 11379 pw.println(" prov[iders]: dump content providers"); 11380 pw.println(" p[ackages]: dump installed packages"); 11381 pw.println(" s[hared-users]: dump shared user IDs"); 11382 pw.println(" m[essages]: print collected runtime messages"); 11383 pw.println(" v[erifiers]: print package verifier info"); 11384 pw.println(" version: print database version info"); 11385 pw.println(" <package.name>: info about given package"); 11386 pw.println(" k[eysets]: print known keysets"); 11387 return; 11388 } else if ("--checkin".equals(opt)) { 11389 checkin = true; 11390 } else if ("-f".equals(opt)) { 11391 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11392 } else { 11393 pw.println("Unknown argument: " + opt + "; use -h for help"); 11394 } 11395 } 11396 11397 // Is the caller requesting to dump a particular piece of data? 11398 if (opti < args.length) { 11399 String cmd = args[opti]; 11400 opti++; 11401 // Is this a package name? 11402 if ("android".equals(cmd) || cmd.contains(".")) { 11403 packageName = cmd; 11404 // When dumping a single package, we always dump all of its 11405 // filter information since the amount of data will be reasonable. 11406 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11407 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 11408 dumpState.setDump(DumpState.DUMP_LIBS); 11409 } else if ("f".equals(cmd) || "features".equals(cmd)) { 11410 dumpState.setDump(DumpState.DUMP_FEATURES); 11411 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 11412 dumpState.setDump(DumpState.DUMP_RESOLVERS); 11413 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 11414 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 11415 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 11416 dumpState.setDump(DumpState.DUMP_PREFERRED); 11417 } else if ("preferred-xml".equals(cmd)) { 11418 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 11419 if (opti < args.length && "--full".equals(args[opti])) { 11420 fullPreferred = true; 11421 opti++; 11422 } 11423 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 11424 dumpState.setDump(DumpState.DUMP_PACKAGES); 11425 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 11426 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 11427 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 11428 dumpState.setDump(DumpState.DUMP_PROVIDERS); 11429 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 11430 dumpState.setDump(DumpState.DUMP_MESSAGES); 11431 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 11432 dumpState.setDump(DumpState.DUMP_VERIFIERS); 11433 } else if ("version".equals(cmd)) { 11434 dumpState.setDump(DumpState.DUMP_VERSION); 11435 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 11436 dumpState.setDump(DumpState.DUMP_KEYSETS); 11437 } 11438 } 11439 11440 if (checkin) { 11441 pw.println("vers,1"); 11442 } 11443 11444 // reader 11445 synchronized (mPackages) { 11446 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 11447 if (!checkin) { 11448 if (dumpState.onTitlePrinted()) 11449 pw.println(); 11450 pw.println("Database versions:"); 11451 pw.print(" SDK Version:"); 11452 pw.print(" internal="); 11453 pw.print(mSettings.mInternalSdkPlatform); 11454 pw.print(" external="); 11455 pw.println(mSettings.mExternalSdkPlatform); 11456 pw.print(" DB Version:"); 11457 pw.print(" internal="); 11458 pw.print(mSettings.mInternalDatabaseVersion); 11459 pw.print(" external="); 11460 pw.println(mSettings.mExternalDatabaseVersion); 11461 } 11462 } 11463 11464 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 11465 if (!checkin) { 11466 if (dumpState.onTitlePrinted()) 11467 pw.println(); 11468 pw.println("Verifiers:"); 11469 pw.print(" Required: "); 11470 pw.print(mRequiredVerifierPackage); 11471 pw.print(" (uid="); 11472 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 11473 pw.println(")"); 11474 } else if (mRequiredVerifierPackage != null) { 11475 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 11476 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 11477 } 11478 } 11479 11480 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 11481 boolean printedHeader = false; 11482 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 11483 while (it.hasNext()) { 11484 String name = it.next(); 11485 SharedLibraryEntry ent = mSharedLibraries.get(name); 11486 if (!checkin) { 11487 if (!printedHeader) { 11488 if (dumpState.onTitlePrinted()) 11489 pw.println(); 11490 pw.println("Libraries:"); 11491 printedHeader = true; 11492 } 11493 pw.print(" "); 11494 } else { 11495 pw.print("lib,"); 11496 } 11497 pw.print(name); 11498 if (!checkin) { 11499 pw.print(" -> "); 11500 } 11501 if (ent.path != null) { 11502 if (!checkin) { 11503 pw.print("(jar) "); 11504 pw.print(ent.path); 11505 } else { 11506 pw.print(",jar,"); 11507 pw.print(ent.path); 11508 } 11509 } else { 11510 if (!checkin) { 11511 pw.print("(apk) "); 11512 pw.print(ent.apk); 11513 } else { 11514 pw.print(",apk,"); 11515 pw.print(ent.apk); 11516 } 11517 } 11518 pw.println(); 11519 } 11520 } 11521 11522 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 11523 if (dumpState.onTitlePrinted()) 11524 pw.println(); 11525 if (!checkin) { 11526 pw.println("Features:"); 11527 } 11528 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 11529 while (it.hasNext()) { 11530 String name = it.next(); 11531 if (!checkin) { 11532 pw.print(" "); 11533 } else { 11534 pw.print("feat,"); 11535 } 11536 pw.println(name); 11537 } 11538 } 11539 11540 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 11541 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 11542 : "Activity Resolver Table:", " ", packageName, 11543 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11544 dumpState.setTitlePrinted(true); 11545 } 11546 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 11547 : "Receiver Resolver Table:", " ", packageName, 11548 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11549 dumpState.setTitlePrinted(true); 11550 } 11551 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 11552 : "Service Resolver Table:", " ", packageName, 11553 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11554 dumpState.setTitlePrinted(true); 11555 } 11556 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 11557 : "Provider Resolver Table:", " ", packageName, 11558 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11559 dumpState.setTitlePrinted(true); 11560 } 11561 } 11562 11563 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 11564 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11565 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11566 int user = mSettings.mPreferredActivities.keyAt(i); 11567 if (pir.dump(pw, 11568 dumpState.getTitlePrinted() 11569 ? "\nPreferred Activities User " + user + ":" 11570 : "Preferred Activities User " + user + ":", " ", 11571 packageName, true)) { 11572 dumpState.setTitlePrinted(true); 11573 } 11574 } 11575 } 11576 11577 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 11578 pw.flush(); 11579 FileOutputStream fout = new FileOutputStream(fd); 11580 BufferedOutputStream str = new BufferedOutputStream(fout); 11581 XmlSerializer serializer = new FastXmlSerializer(); 11582 try { 11583 serializer.setOutput(str, "utf-8"); 11584 serializer.startDocument(null, true); 11585 serializer.setFeature( 11586 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 11587 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 11588 serializer.endDocument(); 11589 serializer.flush(); 11590 } catch (IllegalArgumentException e) { 11591 pw.println("Failed writing: " + e); 11592 } catch (IllegalStateException e) { 11593 pw.println("Failed writing: " + e); 11594 } catch (IOException e) { 11595 pw.println("Failed writing: " + e); 11596 } 11597 } 11598 11599 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 11600 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 11601 } 11602 11603 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 11604 boolean printedSomething = false; 11605 for (PackageParser.Provider p : mProviders.mProviders.values()) { 11606 if (packageName != null && !packageName.equals(p.info.packageName)) { 11607 continue; 11608 } 11609 if (!printedSomething) { 11610 if (dumpState.onTitlePrinted()) 11611 pw.println(); 11612 pw.println("Registered ContentProviders:"); 11613 printedSomething = true; 11614 } 11615 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 11616 pw.print(" "); pw.println(p.toString()); 11617 } 11618 printedSomething = false; 11619 for (Map.Entry<String, PackageParser.Provider> entry : 11620 mProvidersByAuthority.entrySet()) { 11621 PackageParser.Provider p = entry.getValue(); 11622 if (packageName != null && !packageName.equals(p.info.packageName)) { 11623 continue; 11624 } 11625 if (!printedSomething) { 11626 if (dumpState.onTitlePrinted()) 11627 pw.println(); 11628 pw.println("ContentProvider Authorities:"); 11629 printedSomething = true; 11630 } 11631 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 11632 pw.print(" "); pw.println(p.toString()); 11633 if (p.info != null && p.info.applicationInfo != null) { 11634 final String appInfo = p.info.applicationInfo.toString(); 11635 pw.print(" applicationInfo="); pw.println(appInfo); 11636 } 11637 } 11638 } 11639 11640 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 11641 mSettings.mKeySetManager.dump(pw, packageName, dumpState); 11642 } 11643 11644 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 11645 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 11646 } 11647 11648 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 11649 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 11650 } 11651 11652 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 11653 if (dumpState.onTitlePrinted()) 11654 pw.println(); 11655 mSettings.dumpReadMessagesLPr(pw, dumpState); 11656 11657 pw.println(); 11658 pw.println("Package warning messages:"); 11659 final File fname = getSettingsProblemFile(); 11660 FileInputStream in = null; 11661 try { 11662 in = new FileInputStream(fname); 11663 final int avail = in.available(); 11664 final byte[] data = new byte[avail]; 11665 in.read(data); 11666 pw.print(new String(data)); 11667 } catch (FileNotFoundException e) { 11668 } catch (IOException e) { 11669 } finally { 11670 if (in != null) { 11671 try { 11672 in.close(); 11673 } catch (IOException e) { 11674 } 11675 } 11676 } 11677 } 11678 } 11679 } 11680 11681 // ------- apps on sdcard specific code ------- 11682 static final boolean DEBUG_SD_INSTALL = false; 11683 11684 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 11685 11686 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 11687 11688 private boolean mMediaMounted = false; 11689 11690 private String getEncryptKey() { 11691 try { 11692 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 11693 SD_ENCRYPTION_KEYSTORE_NAME); 11694 if (sdEncKey == null) { 11695 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 11696 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 11697 if (sdEncKey == null) { 11698 Slog.e(TAG, "Failed to create encryption keys"); 11699 return null; 11700 } 11701 } 11702 return sdEncKey; 11703 } catch (NoSuchAlgorithmException nsae) { 11704 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 11705 return null; 11706 } catch (IOException ioe) { 11707 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 11708 return null; 11709 } 11710 11711 } 11712 11713 /* package */static String getTempContainerId() { 11714 int tmpIdx = 1; 11715 String list[] = PackageHelper.getSecureContainerList(); 11716 if (list != null) { 11717 for (final String name : list) { 11718 // Ignore null and non-temporary container entries 11719 if (name == null || !name.startsWith(mTempContainerPrefix)) { 11720 continue; 11721 } 11722 11723 String subStr = name.substring(mTempContainerPrefix.length()); 11724 try { 11725 int cid = Integer.parseInt(subStr); 11726 if (cid >= tmpIdx) { 11727 tmpIdx = cid + 1; 11728 } 11729 } catch (NumberFormatException e) { 11730 } 11731 } 11732 } 11733 return mTempContainerPrefix + tmpIdx; 11734 } 11735 11736 /* 11737 * Update media status on PackageManager. 11738 */ 11739 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 11740 int callingUid = Binder.getCallingUid(); 11741 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 11742 throw new SecurityException("Media status can only be updated by the system"); 11743 } 11744 // reader; this apparently protects mMediaMounted, but should probably 11745 // be a different lock in that case. 11746 synchronized (mPackages) { 11747 Log.i(TAG, "Updating external media status from " 11748 + (mMediaMounted ? "mounted" : "unmounted") + " to " 11749 + (mediaStatus ? "mounted" : "unmounted")); 11750 if (DEBUG_SD_INSTALL) 11751 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 11752 + ", mMediaMounted=" + mMediaMounted); 11753 if (mediaStatus == mMediaMounted) { 11754 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 11755 : 0, -1); 11756 mHandler.sendMessage(msg); 11757 return; 11758 } 11759 mMediaMounted = mediaStatus; 11760 } 11761 // Queue up an async operation since the package installation may take a 11762 // little while. 11763 mHandler.post(new Runnable() { 11764 public void run() { 11765 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 11766 } 11767 }); 11768 } 11769 11770 /** 11771 * Called by MountService when the initial ASECs to scan are available. 11772 * Should block until all the ASEC containers are finished being scanned. 11773 */ 11774 public void scanAvailableAsecs() { 11775 updateExternalMediaStatusInner(true, false, false); 11776 if (mShouldRestoreconData) { 11777 SELinuxMMAC.setRestoreconDone(); 11778 mShouldRestoreconData = false; 11779 } 11780 } 11781 11782 /* 11783 * Collect information of applications on external media, map them against 11784 * existing containers and update information based on current mount status. 11785 * Please note that we always have to report status if reportStatus has been 11786 * set to true especially when unloading packages. 11787 */ 11788 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 11789 boolean externalStorage) { 11790 // Collection of uids 11791 int uidArr[] = null; 11792 // Collection of stale containers 11793 HashSet<String> removeCids = new HashSet<String>(); 11794 // Collection of packages on external media with valid containers. 11795 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 11796 // Get list of secure containers. 11797 final String list[] = PackageHelper.getSecureContainerList(); 11798 if (list == null || list.length == 0) { 11799 Log.i(TAG, "No secure containers on sdcard"); 11800 } else { 11801 // Process list of secure containers and categorize them 11802 // as active or stale based on their package internal state. 11803 int uidList[] = new int[list.length]; 11804 int num = 0; 11805 // reader 11806 synchronized (mPackages) { 11807 for (String cid : list) { 11808 if (DEBUG_SD_INSTALL) 11809 Log.i(TAG, "Processing container " + cid); 11810 String pkgName = getAsecPackageName(cid); 11811 if (pkgName == null) { 11812 if (DEBUG_SD_INSTALL) 11813 Log.i(TAG, "Container : " + cid + " stale"); 11814 removeCids.add(cid); 11815 continue; 11816 } 11817 if (DEBUG_SD_INSTALL) 11818 Log.i(TAG, "Looking for pkg : " + pkgName); 11819 11820 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11821 if (ps == null) { 11822 Log.i(TAG, "Deleting container with no matching settings " + cid); 11823 removeCids.add(cid); 11824 continue; 11825 } 11826 11827 /* 11828 * Skip packages that are not external if we're unmounting 11829 * external storage. 11830 */ 11831 if (externalStorage && !isMounted && !isExternal(ps)) { 11832 continue; 11833 } 11834 11835 final AsecInstallArgs args = new AsecInstallArgs(cid, 11836 getAppInstructionSetFromSettings(ps), 11837 isForwardLocked(ps)); 11838 // The package status is changed only if the code path 11839 // matches between settings and the container id. 11840 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 11841 if (DEBUG_SD_INSTALL) { 11842 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 11843 + " at code path: " + ps.codePathString); 11844 } 11845 11846 // We do have a valid package installed on sdcard 11847 processCids.put(args, ps.codePathString); 11848 final int uid = ps.appId; 11849 if (uid != -1) { 11850 uidList[num++] = uid; 11851 } 11852 } else { 11853 Log.i(TAG, "Deleting stale container for " + cid); 11854 removeCids.add(cid); 11855 } 11856 } 11857 } 11858 11859 if (num > 0) { 11860 // Sort uid list 11861 Arrays.sort(uidList, 0, num); 11862 // Throw away duplicates 11863 uidArr = new int[num]; 11864 uidArr[0] = uidList[0]; 11865 int di = 0; 11866 for (int i = 1; i < num; i++) { 11867 if (uidList[i - 1] != uidList[i]) { 11868 uidArr[di++] = uidList[i]; 11869 } 11870 } 11871 } 11872 } 11873 // Process packages with valid entries. 11874 if (isMounted) { 11875 if (DEBUG_SD_INSTALL) 11876 Log.i(TAG, "Loading packages"); 11877 loadMediaPackages(processCids, uidArr, removeCids); 11878 startCleaningPackages(); 11879 } else { 11880 if (DEBUG_SD_INSTALL) 11881 Log.i(TAG, "Unloading packages"); 11882 unloadMediaPackages(processCids, uidArr, reportStatus); 11883 } 11884 } 11885 11886 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 11887 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 11888 int size = pkgList.size(); 11889 if (size > 0) { 11890 // Send broadcasts here 11891 Bundle extras = new Bundle(); 11892 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 11893 .toArray(new String[size])); 11894 if (uidArr != null) { 11895 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 11896 } 11897 if (replacing) { 11898 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 11899 } 11900 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 11901 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 11902 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 11903 } 11904 } 11905 11906 /* 11907 * Look at potentially valid container ids from processCids If package 11908 * information doesn't match the one on record or package scanning fails, 11909 * the cid is added to list of removeCids. We currently don't delete stale 11910 * containers. 11911 */ 11912 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 11913 HashSet<String> removeCids) { 11914 ArrayList<String> pkgList = new ArrayList<String>(); 11915 Set<AsecInstallArgs> keys = processCids.keySet(); 11916 boolean doGc = false; 11917 for (AsecInstallArgs args : keys) { 11918 String codePath = processCids.get(args); 11919 if (DEBUG_SD_INSTALL) 11920 Log.i(TAG, "Loading container : " + args.cid); 11921 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11922 try { 11923 // Make sure there are no container errors first. 11924 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 11925 Slog.e(TAG, "Failed to mount cid : " + args.cid 11926 + " when installing from sdcard"); 11927 continue; 11928 } 11929 // Check code path here. 11930 if (codePath == null || !codePath.equals(args.getCodePath())) { 11931 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 11932 + " does not match one in settings " + codePath); 11933 continue; 11934 } 11935 // Parse package 11936 int parseFlags = mDefParseFlags; 11937 if (args.isExternal()) { 11938 parseFlags |= PackageParser.PARSE_ON_SDCARD; 11939 } 11940 if (args.isFwdLocked()) { 11941 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 11942 } 11943 11944 doGc = true; 11945 synchronized (mInstallLock) { 11946 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 11947 0, 0, null); 11948 // Scan the package 11949 if (pkg != null) { 11950 /* 11951 * TODO why is the lock being held? doPostInstall is 11952 * called in other places without the lock. This needs 11953 * to be straightened out. 11954 */ 11955 // writer 11956 synchronized (mPackages) { 11957 retCode = PackageManager.INSTALL_SUCCEEDED; 11958 pkgList.add(pkg.packageName); 11959 // Post process args 11960 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 11961 pkg.applicationInfo.uid); 11962 } 11963 } else { 11964 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 11965 } 11966 } 11967 11968 } finally { 11969 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 11970 // Don't destroy container here. Wait till gc clears things 11971 // up. 11972 removeCids.add(args.cid); 11973 } 11974 } 11975 } 11976 // writer 11977 synchronized (mPackages) { 11978 // If the platform SDK has changed since the last time we booted, 11979 // we need to re-grant app permission to catch any new ones that 11980 // appear. This is really a hack, and means that apps can in some 11981 // cases get permissions that the user didn't initially explicitly 11982 // allow... it would be nice to have some better way to handle 11983 // this situation. 11984 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 11985 if (regrantPermissions) 11986 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 11987 + mSdkVersion + "; regranting permissions for external storage"); 11988 mSettings.mExternalSdkPlatform = mSdkVersion; 11989 11990 // Make sure group IDs have been assigned, and any permission 11991 // changes in other apps are accounted for 11992 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 11993 | (regrantPermissions 11994 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 11995 : 0)); 11996 11997 mSettings.updateExternalDatabaseVersion(); 11998 11999 // can downgrade to reader 12000 // Persist settings 12001 mSettings.writeLPr(); 12002 } 12003 // Send a broadcast to let everyone know we are done processing 12004 if (pkgList.size() > 0) { 12005 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12006 } 12007 // Force gc to avoid any stale parser references that we might have. 12008 if (doGc) { 12009 Runtime.getRuntime().gc(); 12010 } 12011 // List stale containers and destroy stale temporary containers. 12012 if (removeCids != null) { 12013 for (String cid : removeCids) { 12014 if (cid.startsWith(mTempContainerPrefix)) { 12015 Log.i(TAG, "Destroying stale temporary container " + cid); 12016 PackageHelper.destroySdDir(cid); 12017 } else { 12018 Log.w(TAG, "Container " + cid + " is stale"); 12019 } 12020 } 12021 } 12022 } 12023 12024 /* 12025 * Utility method to unload a list of specified containers 12026 */ 12027 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12028 // Just unmount all valid containers. 12029 for (AsecInstallArgs arg : cidArgs) { 12030 synchronized (mInstallLock) { 12031 arg.doPostDeleteLI(false); 12032 } 12033 } 12034 } 12035 12036 /* 12037 * Unload packages mounted on external media. This involves deleting package 12038 * data from internal structures, sending broadcasts about diabled packages, 12039 * gc'ing to free up references, unmounting all secure containers 12040 * corresponding to packages on external media, and posting a 12041 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12042 * that we always have to post this message if status has been requested no 12043 * matter what. 12044 */ 12045 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12046 final boolean reportStatus) { 12047 if (DEBUG_SD_INSTALL) 12048 Log.i(TAG, "unloading media packages"); 12049 ArrayList<String> pkgList = new ArrayList<String>(); 12050 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12051 final Set<AsecInstallArgs> keys = processCids.keySet(); 12052 for (AsecInstallArgs args : keys) { 12053 String pkgName = args.getPackageName(); 12054 if (DEBUG_SD_INSTALL) 12055 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12056 // Delete package internally 12057 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12058 synchronized (mInstallLock) { 12059 boolean res = deletePackageLI(pkgName, null, false, null, null, 12060 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12061 if (res) { 12062 pkgList.add(pkgName); 12063 } else { 12064 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12065 failedList.add(args); 12066 } 12067 } 12068 } 12069 12070 // reader 12071 synchronized (mPackages) { 12072 // We didn't update the settings after removing each package; 12073 // write them now for all packages. 12074 mSettings.writeLPr(); 12075 } 12076 12077 // We have to absolutely send UPDATED_MEDIA_STATUS only 12078 // after confirming that all the receivers processed the ordered 12079 // broadcast when packages get disabled, force a gc to clean things up. 12080 // and unload all the containers. 12081 if (pkgList.size() > 0) { 12082 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12083 new IIntentReceiver.Stub() { 12084 public void performReceive(Intent intent, int resultCode, String data, 12085 Bundle extras, boolean ordered, boolean sticky, 12086 int sendingUser) throws RemoteException { 12087 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12088 reportStatus ? 1 : 0, 1, keys); 12089 mHandler.sendMessage(msg); 12090 } 12091 }); 12092 } else { 12093 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12094 keys); 12095 mHandler.sendMessage(msg); 12096 } 12097 } 12098 12099 /** Binder call */ 12100 @Override 12101 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12102 final int flags) { 12103 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12104 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12105 int returnCode = PackageManager.MOVE_SUCCEEDED; 12106 int currFlags = 0; 12107 int newFlags = 0; 12108 // reader 12109 synchronized (mPackages) { 12110 PackageParser.Package pkg = mPackages.get(packageName); 12111 if (pkg == null) { 12112 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12113 } else { 12114 // Disable moving fwd locked apps and system packages 12115 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12116 Slog.w(TAG, "Cannot move system application"); 12117 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12118 } else if (pkg.mOperationPending) { 12119 Slog.w(TAG, "Attempt to move package which has pending operations"); 12120 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12121 } else { 12122 // Find install location first 12123 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12124 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12125 Slog.w(TAG, "Ambigous flags specified for move location."); 12126 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12127 } else { 12128 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12129 : PackageManager.INSTALL_INTERNAL; 12130 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12131 : PackageManager.INSTALL_INTERNAL; 12132 12133 if (newFlags == currFlags) { 12134 Slog.w(TAG, "No move required. Trying to move to same location"); 12135 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12136 } else { 12137 if (isForwardLocked(pkg)) { 12138 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12139 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12140 } 12141 } 12142 } 12143 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12144 pkg.mOperationPending = true; 12145 } 12146 } 12147 } 12148 12149 /* 12150 * TODO this next block probably shouldn't be inside the lock. We 12151 * can't guarantee these won't change after this is fired off 12152 * anyway. 12153 */ 12154 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12155 processPendingMove(new MoveParams(null, observer, 0, packageName, null, 12156 null, -1, user), 12157 returnCode); 12158 } else { 12159 Message msg = mHandler.obtainMessage(INIT_COPY); 12160 final String instructionSet = getAppInstructionSet(pkg.applicationInfo); 12161 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir, 12162 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir, 12163 instructionSet); 12164 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12165 pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user); 12166 msg.obj = mp; 12167 mHandler.sendMessage(msg); 12168 } 12169 } 12170 } 12171 12172 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12173 // Queue up an async operation since the package deletion may take a 12174 // little while. 12175 mHandler.post(new Runnable() { 12176 public void run() { 12177 // TODO fix this; this does nothing. 12178 mHandler.removeCallbacks(this); 12179 int returnCode = currentStatus; 12180 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12181 int uidArr[] = null; 12182 ArrayList<String> pkgList = null; 12183 synchronized (mPackages) { 12184 PackageParser.Package pkg = mPackages.get(mp.packageName); 12185 if (pkg == null) { 12186 Slog.w(TAG, " Package " + mp.packageName 12187 + " doesn't exist. Aborting move"); 12188 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12189 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 12190 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12191 + mp.srcArgs.getCodePath() + " to " 12192 + pkg.applicationInfo.sourceDir 12193 + " Aborting move and returning error"); 12194 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12195 } else { 12196 uidArr = new int[] { 12197 pkg.applicationInfo.uid 12198 }; 12199 pkgList = new ArrayList<String>(); 12200 pkgList.add(mp.packageName); 12201 } 12202 } 12203 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12204 // Send resources unavailable broadcast 12205 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12206 // Update package code and resource paths 12207 synchronized (mInstallLock) { 12208 synchronized (mPackages) { 12209 PackageParser.Package pkg = mPackages.get(mp.packageName); 12210 // Recheck for package again. 12211 if (pkg == null) { 12212 Slog.w(TAG, " Package " + mp.packageName 12213 + " doesn't exist. Aborting move"); 12214 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12215 } else if (!mp.srcArgs.getCodePath().equals( 12216 pkg.applicationInfo.sourceDir)) { 12217 Slog.w(TAG, "Package " + mp.packageName 12218 + " code path changed from " + mp.srcArgs.getCodePath() 12219 + " to " + pkg.applicationInfo.sourceDir 12220 + " Aborting move and returning error"); 12221 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12222 } else { 12223 final String oldCodePath = pkg.mPath; 12224 final String newCodePath = mp.targetArgs.getCodePath(); 12225 final String newResPath = mp.targetArgs.getResourcePath(); 12226 final String newNativePath = mp.targetArgs 12227 .getNativeLibraryPath(); 12228 12229 final File newNativeDir = new File(newNativePath); 12230 12231 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12232 // NOTE: We do not report any errors from the APK scan and library 12233 // copy at this point. 12234 NativeLibraryHelper.ApkHandle handle = 12235 new NativeLibraryHelper.ApkHandle(newCodePath); 12236 final int abi = NativeLibraryHelper.findSupportedAbi( 12237 handle, Build.SUPPORTED_ABIS); 12238 if (abi >= 0) { 12239 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12240 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12241 } 12242 handle.close(); 12243 } 12244 final int[] users = sUserManager.getUserIds(); 12245 for (int user : users) { 12246 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 12247 newNativePath, user) < 0) { 12248 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12249 } 12250 } 12251 12252 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12253 pkg.mPath = newCodePath; 12254 // Move dex files around 12255 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) { 12256 // Moving of dex files failed. Set 12257 // error code and abort move. 12258 pkg.mPath = pkg.mScanPath; 12259 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12260 } 12261 } 12262 12263 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12264 pkg.mScanPath = newCodePath; 12265 pkg.applicationInfo.sourceDir = newCodePath; 12266 pkg.applicationInfo.publicSourceDir = newResPath; 12267 pkg.applicationInfo.nativeLibraryDir = newNativePath; 12268 PackageSetting ps = (PackageSetting) pkg.mExtras; 12269 ps.codePath = new File(pkg.applicationInfo.sourceDir); 12270 ps.codePathString = ps.codePath.getPath(); 12271 ps.resourcePath = new File( 12272 pkg.applicationInfo.publicSourceDir); 12273 ps.resourcePathString = ps.resourcePath.getPath(); 12274 ps.nativeLibraryPathString = newNativePath; 12275 // Set the application info flag 12276 // correctly. 12277 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 12278 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12279 } else { 12280 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12281 } 12282 ps.setFlags(pkg.applicationInfo.flags); 12283 mAppDirs.remove(oldCodePath); 12284 mAppDirs.put(newCodePath, pkg); 12285 // Persist settings 12286 mSettings.writeLPr(); 12287 } 12288 } 12289 } 12290 } 12291 // Send resources available broadcast 12292 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12293 } 12294 } 12295 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12296 // Clean up failed installation 12297 if (mp.targetArgs != null) { 12298 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 12299 -1); 12300 } 12301 } else { 12302 // Force a gc to clear things up. 12303 Runtime.getRuntime().gc(); 12304 // Delete older code 12305 synchronized (mInstallLock) { 12306 mp.srcArgs.doPostDeleteLI(true); 12307 } 12308 } 12309 12310 // Allow more operations on this file if we didn't fail because 12311 // an operation was already pending for this package. 12312 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 12313 synchronized (mPackages) { 12314 PackageParser.Package pkg = mPackages.get(mp.packageName); 12315 if (pkg != null) { 12316 pkg.mOperationPending = false; 12317 } 12318 } 12319 } 12320 12321 IPackageMoveObserver observer = mp.observer; 12322 if (observer != null) { 12323 try { 12324 observer.packageMoved(mp.packageName, returnCode); 12325 } catch (RemoteException e) { 12326 Log.i(TAG, "Observer no longer exists."); 12327 } 12328 } 12329 } 12330 }); 12331 } 12332 12333 public boolean setInstallLocation(int loc) { 12334 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12335 null); 12336 if (getInstallLocation() == loc) { 12337 return true; 12338 } 12339 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12340 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12341 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12342 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12343 return true; 12344 } 12345 return false; 12346 } 12347 12348 public int getInstallLocation() { 12349 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12350 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12351 PackageHelper.APP_INSTALL_AUTO); 12352 } 12353 12354 /** Called by UserManagerService */ 12355 void cleanUpUserLILPw(int userHandle) { 12356 mDirtyUsers.remove(userHandle); 12357 mSettings.removeUserLPr(userHandle); 12358 mPendingBroadcasts.remove(userHandle); 12359 if (mInstaller != null) { 12360 // Technically, we shouldn't be doing this with the package lock 12361 // held. However, this is very rare, and there is already so much 12362 // other disk I/O going on, that we'll let it slide for now. 12363 mInstaller.removeUserDataDirs(userHandle); 12364 } 12365 } 12366 12367 /** Called by UserManagerService */ 12368 void createNewUserLILPw(int userHandle, File path) { 12369 if (mInstaller != null) { 12370 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 12371 } 12372 } 12373 12374 @Override 12375 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 12376 mContext.enforceCallingOrSelfPermission( 12377 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12378 "Only package verification agents can read the verifier device identity"); 12379 12380 synchronized (mPackages) { 12381 return mSettings.getVerifierDeviceIdentityLPw(); 12382 } 12383 } 12384 12385 @Override 12386 public void setPermissionEnforced(String permission, boolean enforced) { 12387 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 12388 if (READ_EXTERNAL_STORAGE.equals(permission)) { 12389 synchronized (mPackages) { 12390 if (mSettings.mReadExternalStorageEnforced == null 12391 || mSettings.mReadExternalStorageEnforced != enforced) { 12392 mSettings.mReadExternalStorageEnforced = enforced; 12393 mSettings.writeLPr(); 12394 } 12395 } 12396 // kill any non-foreground processes so we restart them and 12397 // grant/revoke the GID. 12398 final IActivityManager am = ActivityManagerNative.getDefault(); 12399 if (am != null) { 12400 final long token = Binder.clearCallingIdentity(); 12401 try { 12402 am.killProcessesBelowForeground("setPermissionEnforcement"); 12403 } catch (RemoteException e) { 12404 } finally { 12405 Binder.restoreCallingIdentity(token); 12406 } 12407 } 12408 } else { 12409 throw new IllegalArgumentException("No selective enforcement for " + permission); 12410 } 12411 } 12412 12413 @Override 12414 @Deprecated 12415 public boolean isPermissionEnforced(String permission) { 12416 return true; 12417 } 12418 12419 @Override 12420 public boolean isStorageLow() { 12421 final long token = Binder.clearCallingIdentity(); 12422 try { 12423 final DeviceStorageMonitorInternal 12424 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12425 if (dsm != null) { 12426 return dsm.isMemoryLow(); 12427 } else { 12428 return false; 12429 } 12430 } finally { 12431 Binder.restoreCallingIdentity(token); 12432 } 12433 } 12434} 12435